diff --git a/AGENTS.md b/AGENTS.md index 6885ae9..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`. @@ -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/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/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/diffui/server/routes_agent_terminal.py b/diffui/server/routes_agent_terminal.py index 3f57ba4..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"], @@ -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) diff --git a/diffui/static/app.js b/diffui/static/app.js index fd983fd..89a59f7 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(); @@ -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); @@ -566,6 +569,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); 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`