From b2ed5ec906f3e4c1808833980a75c6494a16e8aa Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:03:48 -0700 Subject: [PATCH 1/9] Stop showing tracked files with empty diffs as new --- diffui/git_utils.py | 8 ++++++-- tests/test_server.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/diffui/git_utils.py b/diffui/git_utils.py index 33568ce..4bfd8fb 100644 --- a/diffui/git_utils.py +++ b/diffui/git_utils.py @@ -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) @@ -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(): diff --git a/tests/test_server.py b/tests/test_server.py index 69e736d..8d33811 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -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 From 2699eb21d84b8aacf603adf660b0de819745ea2a Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:04:11 -0700 Subject: [PATCH 2/9] Close the parent pty fd when the agent fails to spawn --- diffui/server/routes_agent_terminal.py | 3 +++ tests/test_agent_terminal.py | 37 ++++++++++++++++++-------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/diffui/server/routes_agent_terminal.py b/diffui/server/routes_agent_terminal.py index 3f57ba4..6d55388 100644 --- a/diffui/server/routes_agent_terminal.py +++ b/diffui/server/routes_agent_terminal.py @@ -83,6 +83,9 @@ def _child_setup(): close_fds=True, preexec_fn=_child_setup, ) + except BaseException: + os.close(pty_fd) + raise finally: os.close(child_fd) diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index ec74f42..9f34779 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import pty import signal import subprocess import sys @@ -153,19 +154,33 @@ 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): + def test_failed_spawn_closes_both_pty_fds(self): 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.object(rat.subprocess, "Popen", side_effect=OSError("no exec")), + 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: From bfc3f440aee91ec789a1e3529a5d26ac94f56b37 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:04:16 -0700 Subject: [PATCH 3/9] Test the no-pending-start guard through the agent websocket --- tests/test_agent_terminal.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index 9f34779..ea35020 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -193,6 +193,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 From 17d00c8eb432c534079497bb19e45fb91b227378 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:04:32 -0700 Subject: [PATCH 4/9] Keep word highlights on removed lines that start with -- --- diffui/diff.py | 12 +++++++++--- tests/test_diff.py | 9 +++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/diffui/diff.py b/diffui/diff.py index 26d4ca9..984782f 100644 --- a/diffui/diff.py +++ b/diffui/diff.py @@ -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): diff --git a/tests/test_diff.py b/tests/test_diff.py index 8d41557..a268e2e 100644 --- a/tests/test_diff.py +++ b/tests/test_diff.py @@ -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): From a772c194e4a980b73c42d4ec2e5f71c0d0b30d8c Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:06:07 -0700 Subject: [PATCH 5/9] Guard the keyboard handler against non-element event targets --- diffui/static/lib/useKeyboard.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diffui/static/lib/useKeyboard.js b/diffui/static/lib/useKeyboard.js index d67624a..7448ea9 100644 --- a/diffui/static/lib/useKeyboard.js +++ b/diffui/static/lib/useKeyboard.js @@ -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(); From 75467f78bb98c0eb67ac009d98c5a57eed0b3504 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:06:07 -0700 Subject: [PATCH 6/9] Render diagram fences in comments as code blocks --- AGENTS.md | 2 +- diffui/static/components/PreviewViewer.js | 2 +- diffui/static/lib/markdown.js | 13 ++++++++----- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6885ae9..7f9a34d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. diff --git a/diffui/static/components/PreviewViewer.js b/diffui/static/components/PreviewViewer.js index 9b4fded..81ece97 100644 --- a/diffui/static/components/PreviewViewer.js +++ b/diffui/static/components/PreviewViewer.js @@ -52,7 +52,7 @@ export function PreviewViewer({ filePath, containerRef }) { } ` : MD_EXTS.has(ext) && preview?.content ? html` -
+
` : html`
No preview available
`} diff --git a/diffui/static/lib/markdown.js b/diffui/static/lib/markdown.js index 7c93201..dd5fe64 100644 --- a/diffui/static/lib/markdown.js +++ b/diffui/static/lib/markdown.js @@ -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', @@ -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', @@ -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() { From 337c1db6b120744ae4bc783138b236b5ac7f56fa Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:06:37 -0700 Subject: [PATCH 7/9] Clear the blame cache on file and git changes --- AGENTS.md | 2 +- diffui/static/app.js | 3 +++ diffui/static/components/DiffViewer.js | 7 +++---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7f9a34d..6c12c3a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. diff --git a/diffui/static/app.js b/diffui/static/app.js index fd983fd..2d71fca 100644 --- a/diffui/static/app.js +++ b/diffui/static/app.js @@ -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); @@ -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(); @@ -566,6 +568,7 @@ function App() { onOpenInEditor=${handleOpenInEditor} onLineHover=${(num) => { hoveredLineRef.current = num; }} showBlame=${showBlame} + blameCache=${blameCache} collapseAll=${collapseAll} />` : html`<${DiffSkeleton} />` diff --git a/diffui/static/components/DiffViewer.js b/diffui/static/components/DiffViewer.js index bada312..eafcf88 100644 --- a/diffui/static/components/DiffViewer.js +++ b/diffui/static/components/DiffViewer.js @@ -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); @@ -186,7 +185,7 @@ 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) { @@ -194,7 +193,7 @@ export function DiffViewer({ data, comments, searchTerm, actions, onOpenInEditor } else { setBlameData(null); } - }, [showBlame, data?.file_path, fetchBlame]); + }, [showBlame, data, fetchBlame]); const handleRightClick = (line) => { setPendingSelection(null); From 66112042b971a7256534bd0033d37ca460649c77 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:06:46 -0700 Subject: [PATCH 8/9] Bump version to 0.11.2 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fcca2ea..99cf8a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ From 16d293e90e6e29fef92176950c424cb511c486ba Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 12:11:10 -0700 Subject: [PATCH 9/9] Close the pty fds when pty setup fails, clear the blame cache on a repo switch --- diffui/server/routes_agent_terminal.py | 7 +++---- diffui/static/app.js | 1 + tests/test_agent_terminal.py | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/diffui/server/routes_agent_terminal.py b/diffui/server/routes_agent_terminal.py index 6d55388..952f707 100644 --- a/diffui/server/routes_agent_terminal.py +++ b/diffui/server/routes_agent_terminal.py @@ -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(): @@ -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"], diff --git a/diffui/static/app.js b/diffui/static/app.js index 2d71fca..89a59f7 100644 --- a/diffui/static/app.js +++ b/diffui/static/app.js @@ -240,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); diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index ea35020..3e587c3 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -154,7 +154,8 @@ 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_failed_spawn_closes_both_pty_fds(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"]} opened = [] real_openpty = pty.openpty @@ -166,7 +167,7 @@ def record_openpty(): try: with ( patch.object(rat.pty, "openpty", side_effect=record_openpty), - patch.object(rat.subprocess, "Popen", side_effect=OSError("no exec")), + patch(f"diffui.server.routes_agent_terminal.{failing}", side_effect=OSError("spawn failed")), pytest.raises(OSError), ): rat._spawn_agent(24, 80)