Skip to content
Merged
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ diffui/
- Events: `events.py` serves a WebSocket (`/api/ws`) and an SSE stream (`/api/events`). The web client uses the WebSocket and falls back to SSE when it closes. Both carry `connected`, `files_changed`, `git_changed` and `comments_changed`. `watchfiles` watches the repo, the git dir and the comments file with a 400ms debounce. `_bg_tasks` keeps background tasks from being garbage collected. `start_poller` runs from the lifespan handler, so it and `_do_restart` can call `asyncio.get_running_loop()`.
- Git dir boundary: `_classify_changes` compares against the git dir plus a separator. A bare `startswith` also matches `.gitignore` and `.github/`, which turns a workflow edit into a full `reload_repo_state()`.
- The watcher follows the branch: `_watch_loop` snapshots the comments path when it starts, so a branch switch (`git_changed`) restarts it. `reload_repo_state()` also re-reads comments, so `_apply_state_updates` adds `comments_changed` to the broadcast when they differ. Without it, clients keep a stale thread.
- Diff caching: server-side `_diff_cache` is keyed by `(repo, merge_base, path, view:context:whitespace, mtime)` and holds one entry per path and view key. The web client keeps a `diffCache` Map and clears it on `files_changed` and `git_changed`. `AppState.numstat` refreshes on `reload_repo_state` and on `files_changed`.
- Diff caching: server-side `_diff_cache` is keyed by `(repo, merge_base, path, view:context:whitespace, mtime)` and holds one entry per path and view key. The web client keeps a `diffCache` Map and a `blameCache` Map and clears both on `files_changed` and `git_changed`. `AppState.numstat` refreshes on `reload_repo_state` and on `files_changed`.
- Auto-unreview: `_invalidate_stale_reviews()` in `events.py` unreviews files whose mtime no longer matches the stored one, on both `files_changed` and `git_changed`.
- Risk scoring: `_score_risk()` in `routes_diff.py` turns path patterns, config extensions, deletions, churn and test removal into a `risk_level`. `/api/files?order=risk` sorts by its score.
- Review counts: `AppState.review_files`, `reviewed_count` and `open_comments()` feed the progress bar, the summary, the agent prompt and the sidebar status, so they all count the same files. `diffui --json` builds the same file set without `AppState`.
Expand All @@ -78,7 +78,7 @@ diffui/
- Last turn: `view=last-turn` diffs the tree saved when an agent's latest turn started against the worktree as it is now. `turns.py` polls `repo_agent_statuses` and counts the agents whose `foreground_cwd` (else `cwd`) is inside the repo, in any workspace. `TurnTracker` fires on the sample where the repo goes from resting (`idle`, `done`, or no agent) to `working`. A `blocked` or unknown agent is mid-turn, so working after it starts nothing, and the first sample after startup never fires. `AppState.last_turn` holds the base tree, a fresh tree of the worktree (`snapshot_worktree`) and `git diff --numstat` between them. `reload_last_turn` only marks it stale. The next read of `last_turn` snapshots, so file events while an agent writes cost nothing until a client asks for the view. Each file list and diff comes from one pair of trees, untracked files included. `GET /api/last-turn` returns the reason an empty view is empty.
- Search: `GET /api/search?q=&view=&scope=` returns `files`, `hits` (`path`, `line`, `text`, read from the working tree, at most `MAX_HITS`) and `truncated`. Files and hits both carry `changed`, whether `view` lists the file. `scope=changed`, the default, covers the files `view_files(view)` lists, minus `.diffuiignore` matches. It adds fff's fuzzy matches to the name matches, reads the first 1 MB of each file and skips binary ones. `scope=all` searches the whole repo through fff, which skips `.gitignore`d and binary files and does not apply `.diffuiignore`. fff's fuzzy name matches are capped at `FILE_CAP` = 30.
- fff index: `fff_index.finder()` hands out one `FileFinder` for the active repo under a lock, since sync routes run in a threadpool. The first search that needs it builds it, never startup, with `watch=False`, because `events.py` already watches the tree. `_apply_state_updates` calls `mark_stale()` on `files_changed` and `git_changed`, and the next `finder()` rescans before it hands the index out. The index is dropped when the repo changes (`switch_repo`, or a different `get_repo_root()`) and closed in the lifespan shutdown. A search that arrives inside the 400ms debounce misses the write, and the next keystroke finds it. `/api/search` lowercases the query because fff matches a lowercase query case-insensitively. `multi_grep` takes it as plain text where `grep` would read a `*.py` word as a path filter. fff's fuzzy name match returns something for almost any query, so `_fuzzy_names` keeps only scores within 75% of the best and above 8 per character of the longest word.
- Markdown is sanitized: `renderMd` in `lib/markdown.js` runs marked's output through an allowlist of tags, attributes and URL schemes before it reaches `dangerouslySetInnerHTML`. marked emits raw HTML, and comment bodies, agent replies and previewed `.md` files all come from outside. Without the allowlist, a branch under review can run script in the diffui origin. Diagram blocks go to kroki.io, the one call that leaves the machine.
- Markdown is sanitized: `renderMd` in `lib/markdown.js` runs marked's output through an allowlist of tags, attributes and URL schemes before it reaches `dangerouslySetInnerHTML`. marked emits raw HTML, and comment bodies, agent replies and previewed `.md` files all come from outside. Without the allowlist, a branch under review can run script in the diffui origin. Diagram blocks go to kroki.io, the one call that leaves the machine, and only in previews (`renderMd(text, { diagrams: true })`). Comment bodies keep a diagram fence as a code block.
- Explain: `/api/explain` spawns the configured agent CLI to write an HTML walkthrough to the temp dir. `/api/explain/status` polls it. `/api/explain/view` serves the result and refuses a path outside the temp dir.
- `_LocalOriginOnly` in `app.py` returns 403 (1008 on a WebSocket) unless Host is `localhost` or `127.0.0.1` and any Origin matches Host. Tests build clients with `base_url="http://localhost"` and connect WebSockets to `ws://localhost`.

Expand Down
12 changes: 9 additions & 3 deletions diffui/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,22 @@ def word_diff_ranges(old_line: str, new_line: str) -> tuple[list[tuple[int, int]


def pair_diff_lines(lines: list[str]) -> dict[int, list[tuple[int, int]]]:
def is_remove(line: str) -> bool:
return line.startswith("-") and not is_meta_line(line)

def is_add(line: str) -> bool:
return line.startswith("+") and not is_meta_line(line)

paired: dict[int, list[tuple[int, int]]] = {}
i = 0
while i < len(lines):
if lines[i].startswith("-") and not lines[i].startswith("---"):
if is_remove(lines[i]):
removes = []
while i < len(lines) and lines[i].startswith("-") and not lines[i].startswith("---"):
while i < len(lines) and is_remove(lines[i]):
removes.append(i)
i += 1
adds = []
while i < len(lines) and lines[i].startswith("+") and not lines[i].startswith("+++"):
while i < len(lines) and is_add(lines[i]):
adds.append(i)
i += 1
for r_idx, a_idx in zip(removes, adds, strict=False):
Expand Down
8 changes: 6 additions & 2 deletions diffui/git_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def get_full_diff(merge_base: str, path: str, context: int = 3, *, ignore_whites
args.append("-w")
args.extend([merge_base, "--", path])
result = _git(*args).stdout
if result.strip():
if result.strip() or _is_tracked(path):
return result
return _diff_untracked(path)

Expand All @@ -201,11 +201,15 @@ def get_working_diff(path: str, context: int = 3, *, ignore_whitespace: bool = F
parts.append(staged)
if unstaged.strip():
parts.append(unstaged)
if parts:
if parts or _is_tracked(path):
return "".join(parts)
return _diff_untracked(path)


def _is_tracked(path: str) -> bool:
return bool(_git("ls-files", "--", path).stdout.strip())


def _diff_untracked(path: str) -> str:
full_path = repo_path(path)
if not full_path.exists():
Expand Down
10 changes: 6 additions & 4 deletions diffui/server/routes_agent_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,6 @@ def _spawn_agent(rows: int, cols: int) -> dict:
return {"ok": False, "error": "No pending agent start"}

pty_fd, child_fd = pty.openpty()
child_tty = os.ttyname(child_fd)
tty.setraw(child_fd)
_resize_pty(pty_fd, rows, cols)

env = {**os.environ, "TERM": "xterm-256color", "COLUMNS": str(cols), "LINES": str(rows)}

def _child_setup():
Expand All @@ -73,6 +69,9 @@ def _child_setup():
os.close(ctty)

try:
child_tty = os.ttyname(child_fd)
tty.setraw(child_fd)
_resize_pty(pty_fd, rows, cols)
proc = subprocess.Popen(
[*pending["cmd"], pending["prompt"]],
cwd=pending["repo_root"],
Expand All @@ -83,6 +82,9 @@ def _child_setup():
close_fds=True,
preexec_fn=_child_setup,
)
except BaseException:
os.close(pty_fd)
raise
finally:
os.close(child_fd)

Expand Down
4 changes: 4 additions & 0 deletions diffui/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function App() {
const [commentsPulse, setCommentsPulse] = useState(false);
const diffRef = useRef(null);
const diffCache = useRef(new Map());
const blameCache = useRef(new Map());
const scrollPositions = useRef(new Map());
const hoveredLineRef = useRef(null);
const scrollToLineRef = useRef(null);
Expand Down Expand Up @@ -199,6 +200,7 @@ function App() {
const handleLiveEvents = useCallback((events) => {
if (events.includes('git_changed') || events.includes('files_changed')) {
diffCache.current.clear();
blameCache.current.clear();
saveScrollPosition();
fetchFiles();
fetchCommits();
Expand Down Expand Up @@ -238,6 +240,7 @@ function App() {
setDiffData(null);
setView('all');
diffCache.current.clear();
blameCache.current.clear();
scrollPositions.current.clear();
await Promise.all([fetchRepos(), fetchBranch(), fetchCommits(), fetchFiles('all'), fetchComments()]);
setLoading(false);
Expand Down Expand Up @@ -566,6 +569,7 @@ function App() {
onOpenInEditor=${handleOpenInEditor}
onLineHover=${(num) => { hoveredLineRef.current = num; }}
showBlame=${showBlame}
blameCache=${blameCache}
collapseAll=${collapseAll}
/>`
: html`<${DiffSkeleton} />`
Expand Down
7 changes: 3 additions & 4 deletions diffui/static/components/DiffViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,9 @@ function Hunk({ hunk, byLine, searchTerm, onRightClick, onCtrlClick, onLineHover
`;
}

export function DiffViewer({ data, comments, searchTerm, actions, onOpenInEditor, onLineHover, showBlame, containerRef, collapseAll }) {
export function DiffViewer({ data, comments, searchTerm, actions, onOpenInEditor, onLineHover, showBlame, blameCache, containerRef, collapseAll }) {
const [commentingLine, setCommentingLine] = useState(null);
const [blameData, setBlameData] = useState(null);
const blameCache = useRef(new Map());
const hoveredLineRef = useRef(null);
const localContainerRef = useRef(null);
const { selMenu, pendingSelection: commentingSelection, setPendingSelection, commentFromSelection } = useRangeSelection('.diff-code', localContainerRef);
Expand All @@ -186,15 +185,15 @@ export function DiffViewer({ data, comments, searchTerm, actions, onOpenInEditor
const result = await res.json();
blameCache.current.set(filePath, result);
setBlameData(result);
}, []);
}, [blameCache]);

useEffect(() => {
if (showBlame && data?.file_path) {
fetchBlame(data.file_path);
} else {
setBlameData(null);
}
}, [showBlame, data?.file_path, fetchBlame]);
}, [showBlame, data, fetchBlame]);

const handleRightClick = (line) => {
setPendingSelection(null);
Expand Down
2 changes: 1 addition & 1 deletion diffui/static/components/PreviewViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function PreviewViewer({ filePath, containerRef }) {
}
</div>
` : MD_EXTS.has(ext) && preview?.content ? html`
<div class="preview-markdown comment-md" dangerouslySetInnerHTML=${renderMd(preview.content)}></div>
<div class="preview-markdown comment-md" dangerouslySetInnerHTML=${renderMd(preview.content, { diagrams: true })}></div>
` : html`
<div class="empty-state">No preview available</div>
`}
Expand Down
13 changes: 8 additions & 5 deletions diffui/static/lib/markdown.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { marked } from 'marked';
import { Marked } from 'marked';

marked.setOptions({ breaks: true, gfm: true });
const MD_OPTIONS = { breaks: true, gfm: true };

const KROKI_BASE = [
'mermaid', 'plantuml', 'graphviz', 'dot', 'd2', 'excalidraw',
Expand All @@ -25,7 +25,10 @@ const renderer = {
}
};

marked.use({ renderer });
// Only previews render diagrams. Comment bodies use plain marked, so a diagram fence stays a code block
// and its source never goes to kroki.io.
const diagramMarked = new Marked(MD_OPTIONS, { renderer });
const plainMarked = new Marked(MD_OPTIONS);

const ALLOWED_TAGS = new Set([
'p', 'br', 'hr', 'em', 'strong', 'del', 's', 'code', 'pre', 'blockquote',
Expand Down Expand Up @@ -77,8 +80,8 @@ function sanitize(html) {
return doc.body.innerHTML;
}

export function renderMd(text) {
return { __html: sanitize(marked.parse(text || '')) };
export function renderMd(text, { diagrams = false } = {}) {
return { __html: sanitize((diagrams ? diagramMarked : plainMarked).parse(text || '')) };
}

export function renderDiagrams() {
Expand Down
2 changes: 1 addition & 1 deletion diffui/static/lib/useKeyboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function useKeyboard({
const handler = (e) => {
if (showCompletionRef.current) { setShowCompletion(false); return; }
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
if (e.target.closest('.agent-terminal-panel')) return;
if (e.target instanceof Element && e.target.closest('.agent-terminal-panel')) return;

if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "diffui"
version = "0.11.1"
version = "0.11.2"
description = "UI for reviewing AI agent diffs"
requires-python = ">=3.10"
dependencies = [
Expand Down
47 changes: 36 additions & 11 deletions tests/test_agent_terminal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import os
import pty
import signal
import subprocess
import sys
Expand Down Expand Up @@ -153,19 +154,34 @@ def test_spawned_agent_runs_in_its_own_session_on_a_sized_terminal(self, temp_re
assert result["ok"] is True
assert output.decode().split() == ["True", "100", "30", "100", "30", "the-prompt"]

def test_spawn_closes_child_fd_on_popen_failure(self):
@pytest.mark.parametrize("failing", ["subprocess.Popen", "tty.setraw"])
def test_failed_spawn_closes_both_pty_fds(self, failing):
rat._pending_start = {"prompt": "test", "repo_root": "/repo", "agent": "claude", "cmd": ["claude"]}
with (
patch.object(rat.pty, "openpty", return_value=(10, 11)),
patch.object(rat.os, "ttyname", return_value="/dev/pts/99"),
patch.object(rat.tty, "setraw"),
patch.object(rat.subprocess, "Popen", side_effect=OSError("no exec")),
patch.object(rat.os, "close") as mock_close,
pytest.raises(OSError),
):
rat._spawn_agent(24, 80)
opened = []
real_openpty = pty.openpty

def record_openpty():
opened.extend(real_openpty())
return tuple(opened)

mock_close.assert_called_once_with(11)
try:
with (
patch.object(rat.pty, "openpty", side_effect=record_openpty),
patch(f"diffui.server.routes_agent_terminal.{failing}", side_effect=OSError("spawn failed")),
pytest.raises(OSError),
):
rat._spawn_agent(24, 80)

assert len(opened) == 2
for fd in opened:
with pytest.raises(OSError):
os.fstat(fd)
finally:
for fd in opened:
try:
os.close(fd)
except OSError:
pass


class TestAgentWebSocket:
Expand All @@ -178,6 +194,15 @@ def test_no_process_sends_error(self, _server_app):
msg = ws.receive_json()
assert msg == {"type": "error", "message": "No agent running"}

def test_start_consumed_between_check_and_spawn_sends_error(self, _server_app):
with (
patch.object(rat, "_pending_is_stale", return_value=False),
_server_app.websocket_connect("ws://localhost/api/agent/ws") as ws,
):
ws.send_json({"type": "init", "rows": 24, "cols": 80})
msg = ws.receive_json()
assert msg == {"type": "error", "message": "No pending agent start"}

def test_replays_buffer_and_started_then_exit(self, _server_app):
proc = MagicMock()
proc.pid = 555
Expand Down
9 changes: 9 additions & 0 deletions tests/test_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,15 @@ def test_word_diff_ranges(old, new, ranges):
pytest.param(
["-removed1", "-removed2", "+added1"], {0: [(0, 8)], 2: [(0, 6)]}, id="surplus-removal-stays-plain"
),
pytest.param(
["@@ -1 +1 @@", "--- old comment", "+-- new comment"], {1: [(3, 6)], 2: [(3, 6)]}, id="removed-dash-comment"
),
pytest.param(["@@ -1 +1 @@", "-i", "+++i"], {1: [(0, 1)], 2: [(0, 3)]}, id="added-line-starting-with-plusses"),
pytest.param(
["--- a/f.lua", "+++ b/f.lua", "@@ -1 +1 @@", "-old", "+new"],
{3: [(0, 3)], 4: [(0, 3)]},
id="file-headers-stay-plain",
),
],
)
def test_pair_diff_lines(lines, paired):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,19 @@ def stats(**params):
finally:
app_py.write_text(original)

@pytest.mark.parametrize("view", ["all", "working"])
@pytest.mark.parametrize("edit", [False, True], ids=["unchanged", "whitespace-only"])
def test_diff_ignore_whitespace_never_shows_a_tracked_file_as_new(self, _server_app, temp_repo, view, edit):
readme = temp_repo / "README.md"
original = readme.read_text()
if edit:
readme.write_text(original.replace("# fixture", "# fixture"))
try:
data = _server_app.get("/api/diff/README.md", params={"view": view, "ignore_whitespace": "true"}).json()
assert data["hunks"] == []
finally:
readme.write_text(original)

def test_repo_switch_invalid_index(self, _server_app):
r = _server_app.post("/api/repo/switch", json={"index": 999})
assert r.status_code == 400
Expand Down
Loading