Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): review a pane's agent work whether it is committed or not
rubenluetke10-beeped070a9389cd
diff --git a/jarvis/agentic_ide/change_authors.py b/jarvis/agentic_ide/change_authors.pyindex eb947cb964..ce16b74927 100644--- a/jarvis/agentic_ide/change_authors.py+++ b/jarvis/agentic_ide/change_authors.py@@ -104,6 +104,15 @@ def _patch_paths(value: Any) -> list[str]:def written_paths(events: Iterable[dict[str, Any]]) -> dict[str, int]:"""``{path as written in the call: last write ms}`` for successful writing calls."""+ return {path: last for path, (_first, last) in write_spans(events).items()}+++def write_spans(events: Iterable[dict[str, Any]]) -> dict[str, tuple[int, int]]:+ """``{path as written in the call: (first, last) write ms}`` for successful writes.++ The first write is what a review compares against: the code as it stood+ before this agent touched the file. 0 means the record carried no time.+ """calls: dict[str, tuple[list[str], int]] = {}failed: set[str] = set()for event in events:@@ -128,12 +137,13 @@ def written_paths(events: Iterable[dict[str, Any]]) -> dict[str, int]:paths.extend(_patch_paths(args))if paths:calls[str(payload.get("call_id"))] = (paths, int(event.get("ts_ms") or 0))- out: dict[str, int] = {}+ out: dict[str, tuple[int, int]] = {}for call_id, (paths, ts) in calls.items():if call_id in failed:continuefor path in paths:- out[path] = max(out.get(path, 0), ts)+ first, last = out.get(path, (ts, ts))+ out[path] = (min(first, ts) if first and ts else first or ts, max(last, ts))return out@@ -158,10 +168,14 @@ def _read_events(record: PaneRecord) -> list[dict[str, Any]] | None:return agent_transcript.read_events(record.agent, record.session_id, home=record.home)-_cache: dict[tuple[str, str], tuple[float, dict[str, int]]] = {}+_cache: dict[tuple[str, str], tuple[float, dict[str, tuple[int, int]]]] = {}def _pane_writes(record: PaneRecord, reader: Reader, now: float) -> dict[str, int]:+ return {path: last for path, (_first, last) in _pane_spans(record, reader, now).items()}+++def _pane_spans(record: PaneRecord, reader: Reader, now: float) -> dict[str, tuple[int, int]]:key = (record.history_id, record.session_id)cached = _cache.get(key)if cached is not None and now - cached[0] < CACHE_TTL_S:@@ -171,9 +185,9 @@ def _pane_writes(record: PaneRecord, reader: Reader, now: float) -> dict[str, inexcept Exception as exc: # a record the CLI rewrote mid-read: no names this roundlogger.info("Change authors: pane {} record unreadable: {}", record.pane, exc)events = []- writes = written_paths(events)- _cache[key] = (now, writes)- return writes+ spans = write_spans(events)+ _cache[key] = (now, spans)+ return spansdef change_authors(@@ -212,6 +226,25 @@ def change_authors(return by_path+def first_write_ms(+ workspace_folder: str | Path,+ record: PaneRecord,+ *,+ reader: Reader = _read_events,+ now: float | None = None,+) -> int:+ """When ``record``'s agent first wrote a file inside the workspace; 0 if never or unknown."""+ root = Path(workspace_folder).expanduser().resolve(strict=False)+ base = Path(record.folder or root).expanduser()+ moment = time.monotonic() if now is None else now+ firsts = [+ first+ for raw, (first, _last) in _pane_spans(record, reader, moment).items()+ if first and _relative(raw, base, root) is not None+ ]+ return min(firsts, default=0)++def authors_for(path: str, is_directory: bool, by_path: dict[str, list[ChangeAuthor]]) -> list[ChangeAuthor]:diff --git a/jarvis/agentic_ide/pane_changes.py b/jarvis/agentic_ide/pane_changes.pynew file mode 100644index 0000000000..2a8d95077c--- /dev/null+++ b/jarvis/agentic_ide/pane_changes.py@@ -0,0 +1,172 @@+"""Everything one pane's agent changed, committed or not.++A coding agent commits as it goes, so "what is uncommitted" is usually empty+by the time someone looks — the pane's review must show the agent's work, not+the working tree's leftovers. So the review compares each file the agent's+record says it wrote against the code as it stood BEFORE the agent's first+write: the last commit on the checkout's first-parent line made before that+moment (:func:`session_base`), diffed against the file on disk now. That+covers work the agent committed, work still uncommitted, and new files.++Another agent's commits to the same files after that moment show up in the+diff too — git cannot split one file's history by author once it is merged+into one line. The file list itself stays this agent's own.++Paths are workspace-relative POSIX paths, the shape :mod:`.git_changes` uses;+git runs with ``--relative`` from the workspace folder, so a workspace below+the repository root works the same.+"""++from __future__ import annotations++import re+from pathlib import Path++from .git_changes import (+ MAX_CHANGED_FILES,+ ChangedFile,+ FileDiff,+ _count_lines,+ _git,+ _has_head,+ _parse_unified,+ _repo_prefix,+ file_diff,+ normalize_workspace_path,+ workspace_changes,+)++#: Paths handed to one git call; keeps the command line far below Windows' limit.+_PATHS_PER_CALL = 100++#: A commit or tree id as the client may send it back.+BASE_PATTERN = re.compile(r"^[0-9a-f]{7,64}$")+++#: The empty tree's id per object format, for "before the first commit".+_EMPTY_TREES = {+ "sha1": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",+ "sha256": "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321",+}+++def _empty_tree(root: Path) -> str | None:+ """The id of an empty tree in this repository's hash."""+ result = _git(["rev-parse", "--show-object-format"], root)+ fmt = result.stdout.strip() if result is not None and result.returncode == 0 else "sha1"+ return _EMPTY_TREES.get(fmt or "sha1")+++def session_base(folder: str | Path, since_ms: int) -> str | None:+ """The commit the checkout stood on just before ``since_ms``; HEAD when the time is unknown.++ The empty tree when every commit is newer (the agent started the repo).+ None when git cannot answer.+ """+ root = Path(folder).expanduser()+ if not _has_head(root):+ return _empty_tree(root)+ if since_ms <= 0:+ head = _git(["rev-parse", "HEAD"], root)+ return head.stdout.strip() if head and head.returncode == 0 else None+ found = _git(+ ["rev-list", "-1", "--first-parent", f"--before=@{since_ms // 1000}", "HEAD"], root+ )+ if found is None or found.returncode != 0:+ return None+ return found.stdout.strip() or _empty_tree(root)+++def _chunks(paths: list[str]) -> list[list[str]]:+ return [paths[i : i + _PATHS_PER_CALL] for i in range(0, len(paths), _PATHS_PER_CALL)]+++def _status_from_letter(letter: str) -> str:+ return {"A": "added", "D": "deleted"}.get(letter[:1], "modified")+++def pane_changes(+ folder: str | Path, paths: set[str], base: str+) -> tuple[list[ChangedFile], set[str], bool]:+ """``(files that differ from base, the ones still uncommitted, truncated)`` among ``paths``."""+ root = Path(folder).expanduser()+ wanted = sorted(paths)+ status: dict[str, str] = {}+ counts: dict[str, tuple[int | None, int | None]] = {}+ untracked: set[str] = set()+ for chunk in _chunks(wanted):+ named = _git(+ ["diff", "--name-status", "-z", "--no-renames", "--relative", base, "--", *chunk], root+ )+ if named is not None and named.returncode == 0:+ parts = named.stdout.split("\0")+ for letter, path in zip(parts[0::2], parts[1::2], strict=False):+ if path:+ status[path] = _status_from_letter(letter)+ numstat = _git(+ ["diff", "--numstat", "-z", "--no-renames", "--relative", base, "--", *chunk], root+ )+ if numstat is not None and numstat.returncode == 0:+ for record in numstat.stdout.split("\0"):+ bits = record.split("\t")+ if len(bits) == 3:+ counts[bits[2]] = (+ int(bits[0]) if bits[0].isdigit() else None,+ int(bits[1]) if bits[1].isdigit() else None,+ )+ others = _git(["ls-files", "--others", "--exclude-standard", "-z", "--", *chunk], root)+ if others is not None and others.returncode == 0:+ untracked.update(path for path in others.stdout.split("\0") if path)++ files: list[ChangedFile] = []+ truncated = False+ for path in wanted:+ if path in untracked:+ word, added, removed = "untracked", _count_lines(root / path), 0+ elif path in status:+ word = status[path]+ added, removed = counts.get(path, (None, None))+ else:+ continue # the agent's edits to it are gone again, or it never left the base+ if len(files) >= MAX_CHANGED_FILES:+ truncated = True+ break+ files.append(ChangedFile(path=path, status=word, added=added, removed=removed))+ pending = {item.path for item in workspace_changes(root, only=set(wanted)).files}+ return files, pending, truncated+++def pane_file_diff(folder: str | Path, path: str, base: str) -> FileDiff:+ """How one file differs from ``base`` now; an untracked file is all new."""+ rel = normalize_workspace_path(folder, path)+ root = Path(folder).expanduser()+ if not BASE_PATTERN.match(base):+ raise ValueError("That is not a commit id.")+ is_repo, _prefix, _reason = _repo_prefix(root)+ if not is_repo:+ return FileDiff(path=rel, status="unchanged")+ others = _git(["ls-files", "--others", "--exclude-standard", "-z", "--", rel], root)+ if others is not None and others.returncode == 0 and others.stdout.strip("\0"):+ return file_diff(root, rel)+ diff = _git(+ ["diff", "--no-color", "--no-ext-diff", "--no-renames", "--relative", "-U3"]+ + [base, "--", rel],+ root,+ )+ if diff is None or diff.returncode != 0:+ return FileDiff(path=rel, status="unchanged")+ named = _git(["diff", "--name-status", "--no-renames", "--relative", base, "--", rel], root)+ letter = named.stdout.strip()[:1] if named is not None and named.returncode == 0 else ""+ hunks, added, removed, binary, truncated = _parse_unified(diff.stdout)+ return FileDiff(+ path=rel,+ status=_status_from_letter(letter) if letter else "unchanged",+ binary=binary,+ hunks=hunks,+ added=added,+ removed=removed,+ truncated=truncated,+ )+++__all__ = ["BASE_PATTERN", "pane_changes", "pane_file_diff", "session_base"]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex ac44d0dead..5afbd676fd 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -91,6 +91,7 @@ from jarvis.agentic_ide import (layout_tree,native_picker,notifications,+ pane_changes,prompt_attachments,prompt_history,recap_engine,@@ -920,6 +921,27 @@ class WorkspaceChangesResponse(BaseModel):reason: str = ""+class PaneChangedFileItem(ChangedFileItem):+ """One file a pane's agent changed, compared with the code before its first write."""++ committed: bool = Field(+ default=False, description="True when nothing of it is left uncommitted."+ )+++class PaneChangesResponse(BaseModel):+ """What one pane's agent changed, committed or not."""++ workspace_id: str+ available: bool = Field(description="False when git or the repository is not usable.")+ branch: str = ""+ files: list[PaneChangedFileItem] = Field(default_factory=list)+ truncated: bool = False+ reason: str = ""+ base: str = Field(default="", description="The commit the files are compared with.")+ since_ms: int = Field(default=0, description="The agent's first write; 0 when unknown.")++class DiffLineItem(BaseModel):kind: str = Field(description="'add', 'del' or 'ctx'.")text: str@@ -1748,60 +1770,101 @@ async def get_workspace_changes(workspace_id: str) -> WorkspaceChangesResponse:)- "/workspaces/{workspace_id}/terminals/{name}/changes",- response_model=WorkspaceChangesResponse,- summary="Uncommitted files one pane's agent wrote in its workspace",-)-async def get_pane_changes(workspace_id: str, name: str) -> WorkspaceChangesResponse:- """The pane's "Review changes" list: the files its agent's own record- names as written, as git sees them now.+def _pane_record(session: Any, term: Any) -> change_authors.PaneRecord | None:+ """What reading this pane's agent record needs; None when there is no readable record."""+ if term.resume is None or not agent_transcript.can_read(term.agent):+ return None+ return change_authors.PaneRecord(+ pane=term.name,+ history_id=term.history_id,+ agent=term.agent,+ display_name=term.display_name,+ session_id=term.resume.id,+ home=account_home(term.agent, term.account),+ folder=term.folder or session.folder,+ )- Reads only this pane's record, not every pane's, and filters git's answer- to those files before any cap, so a folder full of other changes cannot- hide them. A pane whose record cannot be read answers an empty list.- """++def _pane_of(workspace_id: str, name: str) -> tuple[Any, Any]:session = get_registry().get(workspace_id)if session is None:raise HTTPException(status_code=404, detail="Workspace not found.")term = next((t for t in session.terminals if t.name == name), None)if term is None:raise HTTPException(status_code=404, detail="Terminal not found.")- records = (- [- change_authors.PaneRecord(- pane=term.name,- history_id=term.history_id,- agent=term.agent,- display_name=term.display_name,- session_id=term.resume.id,- home=account_home(term.agent, term.account),- folder=term.folder or session.folder,- )- ]- if term.resume is not None and agent_transcript.can_read(term.agent)- else []- )- authors = await asyncio.to_thread(change_authors.change_authors, session.folder, records)- changes = await asyncio.to_thread(- git_changes.workspace_changes, session.folder, set(authors)+ return session, term+++def _read_pane_changes(+ folder: str, record: change_authors.PaneRecord | None+) -> tuple[dict[str, list[change_authors.ChangeAuthor]], int, str | None, Any]:+ authors = change_authors.change_authors(folder, [record] if record else [])+ since = change_authors.first_write_ms(folder, record) if record else 0+ base = pane_changes.session_base(folder, since) if authors else None+ listed = pane_changes.pane_changes(folder, set(authors), base) if base else ([], set(), False)+ return authors, since, base, listed+++ "/workspaces/{workspace_id}/terminals/{name}/changes",+ response_model=PaneChangesResponse,+ summary="Every file one pane's agent changed, committed or not",+)+async def get_pane_changes(workspace_id: str, name: str) -> PaneChangesResponse:+ """The pane's "Review changes" list.++ The files are the ones its agent's own record names as written; each is+ compared with the code before the agent's first write (``base``), so work+ it already committed shows as well as work still pending. A pane on its+ own worktree is read in that worktree. A pane whose record cannot be read+ answers an empty list.+ """+ session, term = _pane_of(workspace_id, name)+ folder = term.folder or session.folder+ changes = await asyncio.to_thread(git_changes.workspace_changes, folder, set())+ if not changes.available:+ return PaneChangesResponse(+ workspace_id=workspace_id, available=False, reason=changes.reason+ )+ authors, since, base, (files, pending, truncated) = await asyncio.to_thread(+ _read_pane_changes, folder, _pane_record(session, term))- return WorkspaceChangesResponse(+ return PaneChangesResponse(workspace_id=workspace_id,- available=changes.available,+ available=True,branch=changes.branch,files=[- ChangedFileItem(+ PaneChangedFileItem(**asdict(item),authors=[ChangeAuthorItem(**asdict(a)) for a in authors.get(item.path, [])],+ committed=item.path not in pending,)- for item in changes.files+ for item in files],- truncated=changes.truncated,- reason=changes.reason,+ truncated=truncated,+ base=base or "",+ since_ms=since,)+ "/workspaces/{workspace_id}/terminals/{name}/diff",+ response_model=WorkspaceFileDiffResponse,+ summary="How one file a pane's agent changed differs from the code before it",+)+async def get_pane_file_diff(+ workspace_id: str, name: str, path: str, base: str+) -> WorkspaceFileDiffResponse:+ """One file of the pane's review, against the ``base`` its list answered."""+ session, term = _pane_of(workspace_id, name)+ folder = term.folder or session.folder+ try:+ diff = await asyncio.to_thread(pane_changes.pane_file_diff, folder, path, base)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None+ return WorkspaceFileDiffResponse(workspace_id=workspace_id, **asdict(diff))++@router.get("/workspaces/{workspace_id}/diff",response_model=WorkspaceFileDiffResponse,diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsxindex c5e5c98171..c9c3022910 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx@@ -59,7 +59,15 @@ beforeEach(() => {const body = url.includes("/diff")? diffFor(path): pane- ? { ...CHANGES, files: CHANGES.files.filter((file) => file.authors.some((a) => a.pane === pane)) }+ ? {+ ...CHANGES,+ base: "abc1234",+ since_ms: 1_700_000_000_000,+ // The pane route answers committed work too, and marks it.+ files: CHANGES.files+ .filter((file) => file.authors.some((a) => a.pane === pane))+ .map((file) => ({ ...file, committed: true })),+ }: url.includes("/changes") ? CHANGES : {};return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });}));@@ -92,7 +100,7 @@ describe("PaneChangesDialog", () => {expect(paths()).toEqual(["src/app.ts"]);expect(await screen.findByText("new src/app.ts")).toBeTruthy();expect(screen.getByTestId("pane-changes-summary").textContent).toContain("1 file");- expect(urls.some((url) => url.includes("/workspaces/w1/diff") && url.includes("src%2Fapp.ts"))).toBe(true);+ expect(urls.some((url) => url.includes("/terminals/T1/diff") && url.includes("src%2Fapp.ts"))).toBe(true);expect(urls.some((url) => url.includes("other.ts"))).toBe(false);});@@ -123,12 +131,30 @@ describe("PaneChangesDialog", () => {expect(await screen.findByTestId("pane-changes-empty")).toBeTruthy();});- it("reads a worktree pane's own checkout through the folder routes", async () => {+ it("shows committed work and diffs it against the base the list answered", async () => {+ render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" />);+ const [card] = await screen.findAllByTestId("pane-changes-file");+ expect(within(card).getByTestId("pane-changes-commit-state").textContent).toBe("Committed");+ await screen.findByText("new src/app.ts");+ expect(urls.some((url) => url.includes("/terminals/T1/diff?path=src%2Fapp.ts&base=abc1234"))).toBe(true);+ expect(screen.getByText(/compared with the code before its first edit/)).toBeTruthy();+ });++ it("asks the pane route for a worktree pane too", async () => {+ render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" folder="/code/app-wt" branch="feat/x" />);+ await screen.findAllByTestId("pane-changes-file");+ expect(urls[0]).toContain("/workspaces/w1/terminals/T1/changes");+ expect(screen.getByText("feat/x")).toBeTruthy();+ expect(screen.queryByTestId("pane-changes-scope-folder")).toBeNull();+ });++ it("reads a worktree pane's own checkout through the folder routes on an older backend", async () => {+ paneRoute = false;render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T3" folder="/code/app-wt" branch="feat/x" />);await screen.findAllByTestId("pane-changes-file");// Every change in its own checkout is its own, record or not.expect(paths()).toEqual(["src/app.ts", "src/other.ts", "notes.md"]);- expect(urls[0]).toContain("/api/agentic-ide/git/changes?folder=%2Fcode%2Fapp-wt");+ expect(urls[1]).toContain("/api/agentic-ide/git/changes?folder=%2Fcode%2Fapp-wt");await waitFor(() => expect(urls.filter((url) => url.includes("/api/agentic-ide/git/diff?folder=")).length).toBe(3));expect(screen.queryByTestId("pane-changes-scope-folder")).toBeNull();expect(screen.queryByLabelText("Open in the editor")).toBeNull();diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsxindex c6424ce3b0..a323273867 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx@@ -26,10 +26,11 @@ import {type ChangeScope,type PaneChanges,type PaneChangesTarget,+ type ReviewFile,} from "./paneChangesApi";import { DiffView } from "./sidePanel/explorer/DiffView";import { FileTypeIcon } from "./sidePanel/explorer/FileTypeIcon";-import type { ChangeStatus, ChangedFile, FileDiff as FileDiffBody } from "./sidePanel/explorer/explorerApi";+import type { ChangeStatus, FileDiff as FileDiffBody } from "./sidePanel/explorer/explorerApi";/** How many diffs are read at once — enough to fill the screen fast, few enough to leave git alone. */const DIFF_CONCURRENCY = 4;@@ -125,7 +126,7 @@ export function PaneChangesDialog({for (let path = queue.shift(); path !== undefined && !cancelled; path = queue.shift()) {let next: DiffState;try {- next = { kind: "ready", diff: await fetchPaneFileDiff(target, path) };+ next = { kind: "ready", diff: await fetchPaneFileDiff(target, path, changes.base) };} catch (error) {next = { kind: "error", message: error instanceof Error ? error.message : String(error) };}@@ -199,14 +200,21 @@ export function PaneChangesDialog({</Dialog.Title></div><Dialog.Description className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs leading-relaxed text-muted-foreground">- {folder ? (- <span className="inline-flex min-w-0 items-center gap-1">+ {folder && (+ <span className="inline-flex min-w-0 items-center gap-1 font-mono"><GitBranch className="h-3 w-3 shrink-0" aria-hidden="true" />- {fill(t("pane_review.description_worktree"), { branch: branch || changes?.branch || "" })}+ {branch || changes?.branch}</span>- ) : (- <span>{t(scope === "pane" ? "pane_review.description_pane" : "pane_review.description_folder")}</span>)}+ <span>+ {scope === "folder" && !folder+ ? t("pane_review.description_folder")+ : changes?.base+ ? changes.sinceMs > 0+ ? fill(t("pane_review.description_since"), { time: new Date(changes.sinceMs).toLocaleString() })+ : t("pane_review.description_pane")+ : t("pane_review.description_uncommitted")}+ </span>{changes && files.length > 0 && (<span data-testid="pane-changes-summary" className="inline-flex items-center gap-2 text-foreground-secondary"><span aria-hidden="true">·</span>@@ -282,7 +290,7 @@ export function PaneChangesDialog({{t(scope === "pane" || folder ? "pane_review.empty_pane" : "pane_review.empty_folder")}</p><p className="max-w-md text-xs text-muted-foreground">- {t(scope === "pane" && !folder ? "pane_review.empty_pane_hint" : "pane_review.empty_hint")}+ {t(scope === "pane" || folder ? "pane_review.empty_pane_hint" : "pane_review.empty_hint")}</p></div>) : (@@ -361,7 +369,7 @@ function FileCard({onOpen,cardRef,}: {- file: ChangedFile;+ file: ReviewFile;diff: DiffState | undefined;collapsed: boolean;onToggle: () => void;@@ -401,6 +409,17 @@ function FileCard({<span className={cn("shrink-0 text-[11px] font-medium", STATUS_TONE[file.status])}>{t(`pane_review.status.${file.status}`)}</span>+ {file.committed !== undefined && (+ <span+ data-testid="pane-changes-commit-state"+ className={cn(+ "shrink-0 rounded px-1.5 py-px text-[10.5px]",+ file.committed ? "bg-muted text-muted-foreground" : "bg-warning/15 text-warning",+ )}+ >+ {t(file.committed ? "pane_review.committed" : "pane_review.pending")}+ </span>+ )}<Counts added={ready ? ready.added : file.added} removed={ready ? ready.removed : file.removed} />{onOpen && (<buttondiff --git a/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts b/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.tsindex c6051f45d4..1945f1bcf2 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts@@ -1,20 +1,20 @@/*** What one pane's coding agent changed, for the pane's "Review changes" dialog.*- * Two places a pane's work can live, and each has its own honest reading:+ * "This agent" is everything the agent changed, committed or not. Agents+ * commit as they go, so the working tree's leftovers are usually empty by the+ * time someone looks. The pane route takes the files the agent's own record+ * names as written and compares each with the code before the agent's first+ * write (`base`), so committed work, pending work and new files all show.+ * A pane on its own worktree is read in that worktree.*- * - A pane on its own git worktree (a worktree fork) owns that checkout, so- * every uncommitted change in it is this agent's. Read through the folder- * routes (`/api/agentic-ide/git/changes` and `/diff`).- * - A pane in the workspace's shared folder shares it with its neighbours.- * Its own files are the ones its agent's record names as written; the pane- * route reads only that record and filters git's answer to those files- * before any cap, so a folder full of build output cannot hide them. The- * whole folder stays one toggle away for a file a shell command wrote,- * which no agent record names.+ * "Whole folder" is everything uncommitted in the shared folder, whoever+ * wrote it — the way to see a file a shell command changed, which no agent+ * record names.*- * Only uncommitted work shows: once the agent commits, the change belongs to- * a commit and the Git tab is where it is read.+ * A backend older than the pane route (a running app updates its bundle+ * before its next restart loads new routes) gets the older reading: the+ * uncommitted files, filtered here.*/import {fetchFileDiff,@@ -26,18 +26,28 @@ import {/** Which files the dialog lists: this pane's own, or everything uncommitted in its folder. */export type ChangeScope = "pane" | "folder";+/** A listed file; `committed` is set by the pane route only. */+export interface ReviewFile extends ChangedFile {+ /** True when nothing of the change is left uncommitted. */+ committed?: boolean;+}+export interface PaneChanges {available: boolean;/** Why `available` is false, in one plain sentence from the backend. */reason: string;branch: string;/** The files in the requested scope. */- files: ChangedFile[];+ files: ReviewFile[];/** How many uncommitted files the folder has in all, when that was read. */folderTotal: number | null;/** True when the pane has a checkout of its own: every change there is its own. */ownCheckout: boolean;truncated: boolean;+ /** The commit the pane's files are compared with; empty for an uncommitted-only reading. */+ base: string;+ /** When the agent first wrote a file (epoch ms); 0 when unknown. */+ sinceMs: number;}/** Where a pane's work lives: its own worktree folder, else the workspace's shared one. */@@ -72,12 +82,14 @@ async function read<T>(url: string): Promise<T> {return (await res.json()) as T;}-interface FolderChangesBody {+interface ChangesBody {available: boolean;branch: string;- files: ChangedFile[];+ files: ReviewFile[];truncated: boolean;reason: string;+ base?: string;+ since_ms?: number;}/** The files whose agent records name `pane` as a writer. Directories are kept only when named too. */@@ -96,65 +108,46 @@ export function changeTotals(files: readonly ChangedFile[]): { added: number; rereturn { added, removed };}-export async function fetchPaneChanges(target: PaneChangesTarget, scope: ChangeScope): Promise<PaneChanges> {- if (target.folder) {- const body = await read<FolderChangesBody>(- `/api/agentic-ide/git/changes?${new URLSearchParams({ folder: target.folder }).toString()}`,- );- return {- available: body.available,- reason: body.reason,- branch: body.branch,- files: body.files,- folderTotal: body.files.length,- ownCheckout: true,- truncated: body.truncated,- };- }- if (scope === "pane") {- const own = await fetchOwnChanges(target);- if (own) return own;- }- const body = await fetchWorkspaceChanges(target.workspaceId);+const paneUrl = (target: PaneChangesTarget, tail: string) =>+ `/api/agentic-ide/workspaces/${encodeURIComponent(target.workspaceId)}/terminals/${encodeURIComponent(target.pane)}/${tail}`;++function reading(body: ChangesBody, extra: Pick<PaneChanges, "folderTotal" | "ownCheckout">, files = body.files): PaneChanges {return {available: body.available,reason: body.reason,branch: body.branch,- files: scope === "pane" ? filesWrittenBy(body.files, target.pane) : body.files,- folderTotal: body.files.length,- ownCheckout: false,+ files,truncated: body.truncated,+ base: body.base ?? "",+ sinceMs: body.since_ms ?? 0,+ ...extra,};}-/**- * The pane route's answer, or null from a backend that predates it (a running- * app updates its bundle before its next restart loads the route), which then- * reads the whole workspace and filters here instead.- */-async function fetchOwnChanges(target: PaneChangesTarget): Promise<PaneChanges | null> {- let body: FolderChangesBody;- try {- body = await read<FolderChangesBody>(- `/api/agentic-ide/workspaces/${encodeURIComponent(target.workspaceId)}/terminals/${encodeURIComponent(target.pane)}/changes`,+export async function fetchPaneChanges(target: PaneChangesTarget, scope: ChangeScope): Promise<PaneChanges> {+ const ownCheckout = Boolean(target.folder);+ if (scope === "pane" || ownCheckout) {+ try {+ return reading(await read<ChangesBody>(paneUrl(target, "changes")), { folderTotal: null, ownCheckout });+ } catch (error) {+ // FastAPI's own "Not Found" means no such route; the route's 404s say what is missing.+ if (!(error instanceof HttpError && error.status === 404 && error.message === "Not Found")) throw error;+ }+ }+ if (target.folder) {+ const body = await read<ChangesBody>(+ `/api/agentic-ide/git/changes?${new URLSearchParams({ folder: target.folder }).toString()}`,);- } catch (error) {- // FastAPI's own "Not Found" means no such route; the route's 404s say what is missing.- if (error instanceof HttpError && error.status === 404 && error.message === "Not Found") return null;- throw error;+ return reading(body, { folderTotal: body.files.length, ownCheckout });}- return {- available: body.available,- reason: body.reason,- branch: body.branch,- files: body.files,- folderTotal: null,- ownCheckout: false,- truncated: body.truncated,- };+ const body = await fetchWorkspaceChanges(target.workspaceId);+ const files = scope === "pane" ? filesWrittenBy(body.files, target.pane) : body.files;+ return reading(body, { folderTotal: body.files.length, ownCheckout }, files);}-export function fetchPaneFileDiff(target: PaneChangesTarget, path: string): Promise<FileDiff> {+/** One file's diff: against `base` when the pane route gave one, else against the last commit. */+export function fetchPaneFileDiff(target: PaneChangesTarget, path: string, base = ""): Promise<FileDiff> {+ if (base) return read<FileDiff>(`${paneUrl(target, "diff")}?${new URLSearchParams({ path, base }).toString()}`);if (target.folder) {return read<FileDiff>(`/api/agentic-ide/git/diff?${new URLSearchParams({ folder: target.folder, path }).toString()}`,diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.jsonindex 209a903d44..8bc72f2640 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json@@ -1,9 +1,10 @@{"pane_review": {"title": "Änderungen prüfen: {name}",- "description_pane": "Jede Datei, die dieser Agent geändert und noch nicht committet hat, mit ihrem Unterschied zum letzten Commit.",+ "description_pane": "Jede Datei, die dieser Agent geändert hat, committet oder nicht, verglichen mit dem Code vor seiner ersten Änderung.",+ "description_since": "Jede Datei, die dieser Agent geändert hat, committet oder nicht, verglichen mit dem Code vor seiner ersten Änderung ({time}).",+ "description_uncommitted": "Jede Datei, die dieser Agent geändert und noch nicht committet hat.","description_folder": "Jede noch nicht committete Datei in diesem Ordner, egal wer sie geändert hat.",- "description_worktree": "Alles, was auf {branch} noch nicht committet ist, der eigenen Arbeitskopie dieses Agenten.","files_one": "1 Datei","files_other": "{count} Dateien","scope_label": "Welche Änderungen angezeigt werden",@@ -17,8 +18,8 @@"load_failed": "Die Änderungen konnten nicht gelesen werden: {error}","diff_failed": "Dieser Unterschied konnte nicht gelesen werden: {error}","unavailable": "Änderungen können hier nicht angezeigt werden: {reason}",- "empty_pane": "Dieser Agent hat keine offenen Änderungen.",- "empty_pane_hint": "Was er schon committet hat, steht im Git-Tab. Eine Datei, die ein Shell-Befehl geändert hat, steht unter „Ganzer Ordner“.",+ "empty_pane": "Dieser Agent hat noch keine Dateien geändert.",+ "empty_pane_hint": "Es zählen nur Dateien, die er selbst bearbeitet hat. Eine Datei, die ein Shell-Befehl geändert hat, steht unter „Ganzer Ordner“, solange sie nicht committet ist.","empty_folder": "In diesem Ordner ist nichts unkommittet.","empty_hint": "Was schon committet ist, steht im Git-Tab.","file_list": "Geänderte Dateien",@@ -36,6 +37,8 @@"untracked": "Neu","deleted": "Gelöscht","conflicted": "Konflikt"- }+ },+ "committed": "Committet",+ "pending": "Nicht committet"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.jsonindex 79dd360655..b00ccb15c3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json@@ -1,9 +1,10 @@{"pane_review": {"title": "Review changes: {name}",- "description_pane": "Every file this agent changed that is not committed yet, with its diff against the last commit.",+ "description_pane": "Every file this agent changed, committed or not, compared with the code before its first edit.",+ "description_since": "Every file this agent changed, committed or not, compared with the code before its first edit ({time}).",+ "description_uncommitted": "Every file this agent changed that is not committed yet.","description_folder": "Every uncommitted file in this folder, whoever changed it.",- "description_worktree": "Everything not committed yet on {branch}, this agent's own checkout.","files_one": "1 file","files_other": "{count} files","scope_label": "Which changes to show",@@ -17,8 +18,8 @@"load_failed": "The changes could not be read: {error}","diff_failed": "This diff could not be read: {error}","unavailable": "Changes cannot be shown here: {reason}",- "empty_pane": "This agent has no uncommitted changes.",- "empty_pane_hint": "Work it already committed is in the Git tab. A file changed by a shell command shows under Whole folder.",+ "empty_pane": "This agent has not changed any files yet.",+ "empty_pane_hint": "Only files it edited itself count. A file changed by a shell command shows under Whole folder while it is uncommitted.","empty_folder": "Nothing in this folder is uncommitted.","empty_hint": "Work that was already committed is in the Git tab.","file_list": "Changed files",@@ -36,6 +37,8 @@"untracked": "New","deleted": "Deleted","conflicted": "Conflict"- }+ },+ "committed": "Committed",+ "pending": "Not committed"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.jsonindex d8002b6913..830268ea7e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json@@ -1,9 +1,10 @@{"pane_review": {"title": "Revisar cambios: {name}",- "description_pane": "Cada archivo que este agente cambió y que aún no tiene commit, con su diferencia respecto al último commit.",+ "description_pane": "Cada archivo que este agente cambió, con commit o sin él, comparado con el código antes de su primer cambio.",+ "description_since": "Cada archivo que este agente cambió, con commit o sin él, comparado con el código antes de su primer cambio ({time}).",+ "description_uncommitted": "Cada archivo que este agente cambió y que aún no tiene commit.","description_folder": "Cada archivo sin commit de esta carpeta, sin importar quién lo cambió.",- "description_worktree": "Todo lo que aún no tiene commit en {branch}, la copia de trabajo propia de este agente.","files_one": "1 archivo","files_other": "{count} archivos","scope_label": "Qué cambios mostrar",@@ -17,8 +18,8 @@"load_failed": "No se pudieron leer los cambios: {error}","diff_failed": "No se pudo leer esta diferencia: {error}","unavailable": "Los cambios no se pueden mostrar aquí: {reason}",- "empty_pane": "Este agente no tiene cambios sin commit.",- "empty_pane_hint": "Lo que ya tiene commit está en la pestaña Git. Un archivo cambiado por un comando de shell aparece en «Carpeta entera».",+ "empty_pane": "Este agente aún no ha cambiado ningún archivo.",+ "empty_pane_hint": "Solo cuentan los archivos que editó él mismo. Un archivo cambiado por un comando de shell aparece en «Carpeta entera» mientras no tenga commit.","empty_folder": "No hay nada sin commit en esta carpeta.","empty_hint": "Lo que ya tiene commit está en la pestaña Git.","file_list": "Archivos cambiados",@@ -36,6 +37,8 @@"untracked": "Nuevo","deleted": "Eliminado","conflicted": "Conflicto"- }+ },+ "committed": "Con commit",+ "pending": "Sin commit"}}diff --git a/tests/unit/web/test_agentic_ide_pane_changes_route.py b/tests/unit/web/test_agentic_ide_pane_changes_route.pyindex a2fc438596..22ae5e04ab 100644--- a/tests/unit/web/test_agentic_ide_pane_changes_route.py+++ b/tests/unit/web/test_agentic_ide_pane_changes_route.py@@ -1,28 +1,37 @@-"""The endpoint behind a pane's "Review changes" dialog.+"""The endpoints behind a pane's "Review changes" dialog.-It must list the files the pane's OWN agent wrote, and find them even when-the folder holds more uncommitted files than one answer carries — a shared-working tree with thousands of untracked build chunks once filled the whole-list and left the dialog saying the agent had changed nothing.+They must list everything the pane's OWN agent changed — work it already+committed as well as work still pending, because coding agents commit as they+go — and compare it with the code as it stood before the agent's first write.+A folder full of other uncommitted files must not hide them."""from __future__ import annotations+import osimport shutilimport subprocess+import timefrom pathlib import Pathfrom types import SimpleNamespaceimport pytestfrom fastapi import HTTPException-from jarvis.agentic_ide import agent_transcript, change_authors, git_changes+from jarvis.agentic_ide import agent_transcript, change_authorsfrom jarvis.ui.web import agentic_ide_routes as routespytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")+NOW = int(time.time())+#: The agent's first write, between the starting commit and its own commit.+FIRST_WRITE_MS = (NOW - 50) * 1000-def _git(cwd: Path, *args: str) -> None:- subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)++def _git(cwd: Path, *args: str, at: int | None = None) -> None:+ env = dict(os.environ)+ if at is not None:+ env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = f"@{at} +0000"+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, env=env)@pytest.fixture@@ -34,7 +43,7 @@ def repo(tmp_path: Path) -> Path:(tmp_path / "mine.py").write_text("one\n", encoding="utf-8")(tmp_path / "theirs.py").write_text("one\n", encoding="utf-8")_git(tmp_path, "add", "-A")- _git(tmp_path, "commit", "-q", "-m", "init")+ _git(tmp_path, "commit", "-q", "-m", "init", at=NOW - 100)return tmp_path@@ -54,7 +63,7 @@ def _write(path: str, call_id: str) -> list[dict]:return [{"kind": "tool_call",- "ts_ms": 5,+ "ts_ms": FIRST_WRITE_MS,"payload": {"call_id": call_id, "name": "Edit", "input": {"file_path": path}},},{"kind": "tool_result", "payload": {"call_id": call_id, "is_error": False}},@@ -73,22 +82,40 @@ def workspace(repo: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:return session-async def test_lists_only_the_panes_own_files_past_a_full_folder(- repo: Path, workspace: SimpleNamespace, monkeypatch: pytest.MonkeyPatch+async def test_work_the_agent_already_committed_is_listed(+ repo: Path, workspace: SimpleNamespace) -> None:- monkeypatch.setattr(git_changes, "MAX_CHANGED_FILES", 2)- for index in range(5):- (repo / f"aaa_chunk{index}.js").write_text("x\n", encoding="utf-8")(repo / "mine.py").write_text("two\n", encoding="utf-8")(repo / "theirs.py").write_text("two\n", encoding="utf-8")+ _git(repo, "commit", "-q", "-am", "agent work", at=NOW - 10)++ answer = await routes.get_pane_changes("w1", "T1")++ assert [(f.path, f.status, f.added, f.removed, f.committed) for f in answer.files] == [+ ("mine.py", "modified", 1, 1, True)+ ]+ assert answer.since_ms == FIRST_WRITE_MS+ diff = await routes.get_pane_file_diff("w1", "T1", "mine.py", answer.base)+ assert [(line.kind, line.text) for hunk in diff.hunks for line in hunk.lines] == [+ ("del", "one"),+ ("add", "two"),+ ]+++async def test_pending_work_is_marked_not_committed_and_noise_does_not_hide_it(+ repo: Path, workspace: SimpleNamespace+) -> None:+ for index in range(600):+ (repo / f"aaa_chunk{index}.js").write_text("x\n", encoding="utf-8")+ (repo / "mine.py").write_text("two\n", encoding="utf-8")answer = await routes.get_pane_changes("w1", "T1")- assert [(f.path, [a.pane for a in f.authors]) for f in answer.files] == [("mine.py", ["T1"])]- assert not answer.truncated+ assert [(f.path, f.committed) for f in answer.files] == [("mine.py", False)]+ assert [a.pane for a in answer.files[0].authors] == ["T1"]-async def test_a_pane_that_wrote_nothing_gets_an_empty_list(+async def test_a_file_back_to_its_old_text_is_not_listed(repo: Path, workspace: SimpleNamespace) -> None:(repo / "theirs.py").write_text("two\n", encoding="utf-8")@@ -99,6 +126,12 @@ async def test_a_pane_that_wrote_nothing_gets_an_empty_list(assert answer.files == []+async def test_a_diff_refuses_a_base_that_is_not_a_commit_id(workspace: SimpleNamespace) -> None:+ with pytest.raises(HTTPException) as refused:+ await routes.get_pane_file_diff("w1", "T1", "mine.py", "HEAD; rm -rf")+ assert refused.value.status_code == 400++async def test_unknown_workspace_or_pane_is_a_404(workspace: SimpleNamespace) -> None:with pytest.raises(HTTPException) as missing_pane:await routes.get_pane_changes("w1", "T9")