Skip to content

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.

perf(agentic-ide): open the pane review already painted

rubenluetke10-beep6e80d7a4d6e5
diff --git a/jarvis/agentic_ide/git_changes.py b/jarvis/agentic_ide/git_changes.py
index 2efc9687bf..16e1e6032a 100644
--- a/jarvis/agentic_ide/git_changes.py
+++ b/jarvis/agentic_ide/git_changes.py
@@ -345,6 +345,30 @@ def head_text(folder: str | Path, path: str, ref: str = "") -> str | None:
return result.stdout.removeprefix("")
+def untracked_diff(root: Path, rel: str) -> FileDiff:
+ """A file git does not track yet, as an all-new diff read from disk."""
+ target = root / rel
+ count = _count_lines(target)
+ if count is None:
+ return FileDiff(path=rel, status="untracked", binary=target.is_file())
+ text = target.read_text(encoding="utf-8", errors="replace")
+ lines = text.splitlines()
+ shown = lines[:MAX_DIFF_LINES]
+ hunk = DiffHunk(
+ header=f"@@ -0,0 +1,{len(lines)} @@",
+ lines=[
+ DiffLine(kind="add", text=line, new_no=index + 1) for index, line in enumerate(shown)
+ ],
+ )
+ return FileDiff(
+ path=rel,
+ status="untracked",
+ hunks=[hunk],
+ added=len(lines),
+ truncated=len(lines) > len(shown),
+ )
+
+
def file_diff(folder: str | Path, path: str) -> FileDiff:
"""How one file differs from the last commit; an untracked file is all new."""
rel = normalize_workspace_path(folder, path)
@@ -362,27 +386,7 @@ def file_diff(folder: str | Path, path: str) -> FileDiff:
word = _status_word(record[:2]) if record else "unchanged"
if word == "untracked":
- target = root / rel
- count = _count_lines(target)
- if count is None:
- return FileDiff(path=rel, status=word, binary=target.is_file())
- text = target.read_text(encoding="utf-8", errors="replace")
- lines = text.splitlines()
- shown = lines[:MAX_DIFF_LINES]
- hunk = DiffHunk(
- header=f"@@ -0,0 +1,{len(lines)} @@",
- lines=[
- DiffLine(kind="add", text=line, new_no=index + 1)
- for index, line in enumerate(shown)
- ],
- )
- return FileDiff(
- path=rel,
- status=word,
- hunks=[hunk],
- added=len(lines),
- truncated=len(lines) > len(shown),
- )
+ return untracked_diff(root, rel)
args = ["diff", "--no-color", "--no-ext-diff", "--no-renames", "-U3"]
if _has_head(root):
@@ -412,5 +416,6 @@ __all__ = [
"WorkspaceChanges",
"file_diff",
"normalize_workspace_path",
+ "untracked_diff",
"workspace_changes",
]
diff --git a/jarvis/agentic_ide/pane_changes.py b/jarvis/agentic_ide/pane_changes.py
index 0595c480c4..187656b50c 100644
--- a/jarvis/agentic_ide/pane_changes.py
+++ b/jarvis/agentic_ide/pane_changes.py
@@ -29,6 +29,7 @@ from __future__ import annotations
import json
import re
from collections.abc import Iterable
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -45,6 +46,7 @@ from .git_changes import (
_repo_prefix,
file_diff,
normalize_workspace_path,
+ untracked_diff,
)
#: Paths handed to one git call; keeps the command line far below Windows' limit.
@@ -96,41 +98,122 @@ 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``."""
+#: Most diff lines one listing carries inline; files past it are read one by one on demand.
+MAX_INLINE_DIFF_LINES = 20_000
+
+
+@dataclass(slots=True)
+class PaneListing:
+ """The agent's files as git sees them against ``base``."""
+
+ files: list[ChangedFile] = field(default_factory=list)
+ #: The listed files git still reports as changed or untracked in the working tree.
+ pending: set[str] = field(default_factory=set)
+ truncated: bool = False
+ #: Each listed file's diff, up to :data:`MAX_INLINE_DIFF_LINES` in all.
+ diffs: dict[str, FileDiff] = field(default_factory=dict)
+
+
+def _worktree_state(root: Path, prefix: str, chunk: list[str]) -> tuple[set[str], set[str]]:
+ """(changed or untracked in the working tree, untracked) among ``chunk``."""
+ result = _git(
+ ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all", "--", *chunk],
+ root,
+ )
+ pending: set[str] = set()
+ untracked: set[str] = set()
+ for record in (result.stdout.split("\0") if result and result.returncode == 0 else []):
+ if len(record) < 4 or not record[3:].startswith(prefix):
+ continue
+ path = record[3 + len(prefix) :]
+ pending.add(path)
+ if record[:2] == "??":
+ untracked.add(path)
+ return pending, untracked
+
+
+def _raw_counts(
+ root: Path, base: str, chunk: list[str]
+) -> tuple[dict[str, str], dict[str, tuple[int | None, int | None]]]:
+ """Status word and line counts of each file in ``chunk`` that differs from ``base``."""
+ result = _git(
+ ["diff", "--raw", "--numstat", "-z", "--no-renames", "--relative", base, "--", *chunk],
+ root,
+ )
+ status: dict[str, str] = {}
+ counts: dict[str, tuple[int | None, int | None]] = {}
+ tokens = result.stdout.split("\0") if result and result.returncode == 0 else []
+ index = 0
+ while index < len(tokens):
+ token = tokens[index]
+ if token.startswith(":") and index + 1 < len(tokens):
+ status[tokens[index + 1]] = _status_from_letter(token.split()[-1])
+ index += 2
+ continue
+ bits = token.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,
+ )
+ index += 1
+ return status, counts
+
+
+def _patches(root: Path, base: str, chunk: list[str]) -> dict[str, str]:
+ """``{path: its unified diff against base}`` for the files in ``chunk``, from one git call."""
+ result = _git(
+ ["diff", "--no-color", "--no-ext-diff", "--no-renames", "--relative", "-U3", base]
+ + ["--", *chunk],
+ root,
+ )
+ if result is None or result.returncode != 0:
+ return {}
+ headers = {f"diff --git a/{path} b/{path}": path for path in chunk}
+ patches: dict[str, str] = {}
+ for block in result.stdout.split("\ndiff --git "):
+ text = block if block.startswith("diff --git ") else "diff --git " + block
+ path = headers.get(text.split("\n", 1)[0])
+ if path is not None:
+ patches[path] = text
+ return patches
+
+
+def pane_changes(folder: str | Path, paths: set[str], base: str) -> PaneListing:
+ """The files among ``paths`` that differ from ``base``, with their diffs.
+
+ Three git calls per chunk of paths — working-tree state, status and line
+ counts, and the patch text — run side by side, so a listing costs about
+ one git round trip however many files the agent touched.
+ """
root = Path(folder).expanduser()
wanted = sorted(paths)
+ _is_repo, prefix, _reason = _repo_prefix(root)
+ pending: set[str] = set()
+ untracked: set[str] = set()
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
+ patches: dict[str, str] = {}
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ jobs = [
+ (
+ pool.submit(_worktree_state, root, prefix, chunk),
+ pool.submit(_raw_counts, root, base, chunk),
+ pool.submit(_patches, root, base, chunk),
+ )
+ for chunk in _chunks(wanted)
+ ]
+ for state, raw, patch in jobs:
+ chunk_pending, chunk_untracked = state.result()
+ pending |= chunk_pending
+ untracked |= chunk_untracked
+ chunk_status, chunk_counts = raw.result()
+ status.update(chunk_status)
+ counts.update(chunk_counts)
+ patches.update(patch.result())
+
+ listing = PaneListing(pending=set())
+ budget = MAX_INLINE_DIFF_LINES
for path in wanted:
if path in untracked:
word, added, removed = "untracked", _count_lines(root / path), 0
@@ -139,29 +222,30 @@ def pane_changes(
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
+ if len(listing.files) >= MAX_CHANGED_FILES:
+ listing.truncated = True
break
- files.append(ChangedFile(path=path, status=word, added=added, removed=removed))
- return files, _pending(root, [item.path for item in files]), truncated
-
-
-def _pending(root: Path, paths: list[str]) -> set[str]:
- """Which of ``paths`` git still reports as changed or untracked in the working tree."""
- pending: set[str] = set()
- _is_repo, prefix, _reason = _repo_prefix(root)
- for chunk in _chunks(paths):
- status = _git(
- ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"]
- + ["--", *chunk],
- root,
- )
- if status is None or status.returncode != 0:
+ listing.files.append(ChangedFile(path=path, status=word, added=added, removed=removed))
+ if path in pending:
+ listing.pending.add(path)
+ if budget <= 0:
continue
- for record in status.stdout.split("\0"):
- if len(record) >= 4 and record[3:].startswith(prefix):
- pending.add(record[3 + len(prefix) :])
- return pending
+ if word == "untracked":
+ diff = untracked_diff(root, path)
+ else:
+ hunks, d_added, d_removed, binary, cut = _parse_unified(patches.get(path, ""))
+ diff = FileDiff(
+ path=path,
+ status=word,
+ binary=binary,
+ hunks=hunks,
+ added=d_added,
+ removed=d_removed,
+ truncated=cut,
+ )
+ budget -= sum(len(hunk.lines) for hunk in diff.hunks)
+ listing.diffs[path] = diff
+ return listing
def pane_file_diff(folder: str | Path, path: str, base: str) -> FileDiff:
@@ -391,6 +475,7 @@ def pane_work(
__all__ = [
"BASE_PATTERN",
"CommitRefs",
+ "PaneListing",
"PaneWork",
"agent_commit_refs",
"commit_files",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index dafbd8ddcf..f90be418f9 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -61,6 +61,7 @@ import mimetypes
import os
import re
import time
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
from typing import Annotated, Any, Literal, get_args
@@ -921,30 +922,6 @@ 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 change; 0 when unknown.")
- generated: int = Field(
- default=0, description="Generated files (build output) the agent changed, not listed."
- )
-
-
class DiffLineItem(BaseModel):
kind: str = Field(description="'add', 'del' or 'ctx'.")
text: str
@@ -970,6 +947,44 @@ class WorkspaceFileDiffResponse(BaseModel):
truncated: bool = False
+class PaneFileDiffItem(BaseModel):
+ """One file's diff inside a pane's review listing."""
+
+ status: str
+ binary: bool = False
+ added: int = 0
+ removed: int = 0
+ hunks: list[DiffHunkItem] = Field(default_factory=list)
+ truncated: bool = False
+
+
+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."
+ )
+ diff: PaneFileDiffItem | None = Field(
+ default=None, description="Its diff against the base; null when it is read on demand."
+ )
+
+
+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 change; 0 when unknown.")
+ generated: int = Field(
+ default=0, description="Generated files (build output) the agent changed, not listed."
+ )
+
+
class WorkspaceFilePreviewResponse(BaseModel):
"""A bounded in-app preview without exposing an absolute host path."""
@@ -1800,7 +1815,7 @@ def _pane_of(workspace_id: str, name: str) -> tuple[Any, Any]:
def _read_pane_changes(
folder: str, record: change_authors.PaneRecord | None
-) -> tuple[pane_changes.PaneWork, str | None, int, Any]:
+) -> tuple[pane_changes.PaneWork, str | None, int, pane_changes.PaneListing]:
"""(the agent's work, the base it is compared with, generated files left out, listing)."""
events: list[dict[str, Any]] = []
if record is not None:
@@ -1812,11 +1827,22 @@ def _read_pane_changes(
except Exception as exc: # a record the CLI rewrote mid-read: an empty review this time
log.info("Pane changes: %s record unreadable: %s", record.pane, exc)
work = pane_changes.pane_work(folder, events, record.folder if record else None)
- generated = pane_changes.generated_paths(folder, set(work.files))
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ generated_job = pool.submit(pane_changes.generated_paths, folder, set(work.files))
+ base_job = pool.submit(pane_changes.session_base, folder, work.since_ms)
+ generated, base = generated_job.result(), base_job.result()
wanted = set(work.files) - generated
- base = pane_changes.session_base(folder, work.since_ms) if wanted else None
- listed = pane_changes.pane_changes(folder, wanted, base) if base else ([], set(), False)
- return work, base, len(generated), listed
+ if not wanted or not base:
+ return work, base if wanted else None, len(generated), pane_changes.PaneListing()
+ return work, base, len(generated), pane_changes.pane_changes(folder, wanted, base)
+
+
+def _diff_item(diff: git_changes.FileDiff | None) -> PaneFileDiffItem | None:
+ if diff is None:
+ return None
+ data = asdict(diff)
+ data.pop("path", None)
+ return PaneFileDiffItem(**data)
@router.get(
@@ -1835,15 +1861,15 @@ async def get_pane_changes(workspace_id: str, name: str) -> PaneChangesResponse:
"""
session, term = _pane_of(workspace_id, name)
folder = term.folder or session.folder
- changes = await asyncio.to_thread(git_changes.workspace_changes, folder, set())
+ # The repository check and the record's reading run side by side.
+ changes, (work, base, generated, listing) = await asyncio.gather(
+ asyncio.to_thread(git_changes.workspace_changes, folder, set()),
+ asyncio.to_thread(_read_pane_changes, folder, _pane_record(session, term)),
+ )
if not changes.available:
return PaneChangesResponse(
workspace_id=workspace_id, available=False, reason=changes.reason
)
- record = _pane_record(session, term)
- work, base, generated, (files, pending, truncated) = await asyncio.to_thread(
- _read_pane_changes, folder, record
- )
return PaneChangesResponse(
workspace_id=workspace_id,
available=True,
@@ -1860,11 +1886,12 @@ async def get_pane_changes(workspace_id: str, name: str) -> PaneChangesResponse:
last_edit_ms=work.files.get(item.path, 0),
)
],
- committed=item.path not in pending,
+ committed=item.path not in listing.pending,
+ diff=_diff_item(listing.diffs.get(item.path)),
)
- for item in files
+ for item in listing.files
],
- truncated=truncated,
+ truncated=listing.truncated,
base=base or "",
since_ms=work.since_ms,
generated=generated,
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index c3e07943b4..10a14fe5e3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -159,10 +159,11 @@ import { PromptReceipt } from "./PromptReceipt";
import { PromptHistoryButton } from "./PromptHistoryButton";
import { PaneConversationDialog } from "./PaneConversationDialog";
import { PaneChangesDialog } from "./PaneChangesDialog";
+import { prefetchPaneChanges } from "./paneChangesApi";
import { WorkspaceTerminalHeader } from "./WorkspaceTerminalHeader";
import { usePaneContextMenu } from "./usePaneContextMenu";
import { SessionGitHubBadge } from "./SessionGitHubBadge";
-import { useT } from "@/i18n";
+import { loadLocaleChunk, useT } from "@/i18n";
/**
* How old a delivery may be and still raise its receipt on a fresh connection.
@@ -2810,6 +2811,12 @@ export function AgenticTerminal({
// A pane whose agent runs on another computer changes files THERE, which
// this machine's git cannot read — so only a local pane offers the review.
const reviewChanges = workspaceId && !computerName ? () => setChangesOpen(true) : undefined;
+ const prefetchReview = workspaceId && !computerName
+ ? () => {
+ void loadLocaleChunk("pane_review");
+ prefetchPaneChanges({ workspaceId, pane: name, folder });
+ }
+ : undefined;
const headerProps = {
githubStatusEnabled: active,
contextMenuRequest: paneMenu.request,
@@ -2836,6 +2843,7 @@ export function AgenticTerminal({
onOpenConversation: () => setHistoryOpen(true),
onOpenChat,
onReviewChanges: reviewChanges,
+ onReviewChangesPrefetch: prefetchReview,
onRestart,
onFork,
branch,
@@ -2952,6 +2960,7 @@ export function AgenticTerminal({
onOpenConversation={() => setHistoryOpen(true)}
onOpenChat={onOpenChat}
onReviewChanges={reviewChanges}
+ onReviewChangesPrefetch={prefetchReview}
/>}
{/*
What went wrong, kept on screen for as long as it is true — and the one
@@ -3146,6 +3155,7 @@ function PaneHeader({
onOpenConversation,
onOpenChat,
onReviewChanges,
+ onReviewChangesPrefetch,
}: {
workspaceId?: string;
githubStatusEnabled: boolean;
@@ -3181,6 +3191,8 @@ function PaneHeader({
onOpenChat?: () => void;
/** Opens the review of every uncommitted change this pane's agent made. */
onReviewChanges?: () => void;
+ /** Starts reading the review the moment the pointer reaches its button. */
+ onReviewChangesPrefetch?: () => void;
}) {
const t = useT();
const light = appearance === "light";
@@ -3709,6 +3721,7 @@ function PaneHeader({
label={`Review changes by ${name}`}
testId={`pane-review-changes-${name}`}
onClick={onReviewChanges}
+ onHover={onReviewChangesPrefetch}
>
<FileDiff className="h-3.5 w-3.5" aria-hidden="true" />
</PaneAction>
@@ -3881,6 +3894,7 @@ function PaneAction({
disabled = false,
expanded,
onClick,
+ onHover,
children,
}: {
label: string;
@@ -3890,11 +3904,14 @@ function PaneAction({
/** Set when this button opens a menu — announces its state to a screen reader. */
expanded?: boolean;
onClick?: () => void;
+ /** The pointer reached the button: a chance to start work its click will need. */
+ onHover?: () => void;
children: React.ReactNode;
}) {
return (
<button
type="button"
+ onPointerEnter={onHover}
aria-label={label}
title={label}
data-testid={testId}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
index 2ebb84f33e..c31c5c5094 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
@@ -1,7 +1,7 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PaneChangesDialog } from "./PaneChangesDialog";
-import { changeTotals, filesWrittenBy } from "./paneChangesApi";
+import { changeTotals, clearPaneChangesCache, filesWrittenBy, prefetchPaneChanges } from "./paneChangesApi";
import { useCodeEditorStore } from "@/store/codeEditor";
import en from "@/i18n/locales/pane_review/en.json";
import de from "@/i18n/locales/pane_review/de.json";
@@ -45,9 +45,14 @@ const urls: string[] = [];
/** False plays a backend from before the pane route: FastAPI answers 404 "Not Found". */
let paneRoute = true;
+/** True: the pane route sends every diff inline, as the current backend does. */
+let inlineDiffs = false;
+
beforeEach(() => {
urls.length = 0;
paneRoute = true;
+ inlineDiffs = false;
+ clearPaneChangesCache();
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
urls.push(url);
@@ -67,7 +72,7 @@ beforeEach(() => {
// 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 })),
+ .map((file) => ({ ...file, committed: true, diff: inlineDiffs ? diffFor(file.path) : null })),
}
: url.includes("/changes") ? CHANGES : {};
return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
@@ -120,6 +125,25 @@ describe("PaneChangesDialog", () => {
expect(urls.some((url) => url.endsWith("/workspaces/w1/changes"))).toBe(true);
});
+ it("paints the diffs the list carried without asking for them one by one", async () => {
+ inlineDiffs = true;
+ render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" />);
+ expect(await screen.findByText("new src/app.ts")).toBeTruthy();
+ expect(urls.filter((url) => url.includes("/diff"))).toEqual([]);
+ });
+
+ it("opens already painted after a hover read the changes ahead", async () => {
+ inlineDiffs = true;
+ prefetchPaneChanges({ workspaceId: "w1", pane: "T1" });
+ await waitFor(() => expect(urls.length).toBe(1));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" />);
+ expect(await screen.findByText("new src/app.ts")).toBeTruthy();
+ // The fresh reading is reused, not read a second time.
+ expect(urls.filter((url) => url.includes("/terminals/T1/changes")).length).toBe(1);
+ expect(screen.queryByText("Reading the changes…")).toBeNull();
+ });
+
it("widens to the whole folder on request", async () => {
render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" />);
await screen.findAllByTestId("pane-changes-file");
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
index 04e595463e..6b80bcd7f2 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
@@ -21,7 +21,8 @@ import { useCodeEditorStore } from "@/store/codeEditor";
import { usePaneTitle } from "@/store/paneRecaps";
import {
changeTotals,
- fetchPaneChanges,
+ cachedPaneChanges,
+ loadPaneChanges,
fetchPaneFileDiff,
type ChangeScope,
type PaneChanges,
@@ -102,26 +103,37 @@ export function PaneChangesDialog({
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const cards = useRef(new Map<string, HTMLElement>());
- // Read the list, then every file's diff a few at a time. A newer read (a
- // scope switch, Refresh, closing the dialog) cancels the older one.
+ // Paint the newest reading at once (a hover may have fetched it already),
+ // read again behind it, then fetch only the diffs the list did not carry.
+ // A newer read (a scope switch, Refresh, closing the dialog) cancels the older one.
useEffect(() => {
if (!open) return;
const target: PaneChangesTarget = { workspaceId, pane, folder };
let cancelled = false;
- setList({ kind: "loading" });
- setDiffs({});
+ const show = (changes: PaneChanges) => {
+ setList({ kind: "ready", changes });
+ setDiffs(Object.fromEntries(changes.files.filter((file) => !file.is_directory).map((file) => [
+ file.path,
+ file.diff ? ({ kind: "ready", diff: { workspace_id: workspaceId, path: file.path, ...file.diff } } as DiffState) : ({ kind: "loading" } as DiffState),
+ ])));
+ };
+ const cached = revision === 0 ? cachedPaneChanges(target, scope) : null;
+ if (cached) show(cached);
+ else {
+ setList({ kind: "loading" });
+ setDiffs({});
+ }
void (async () => {
let changes: PaneChanges;
try {
- changes = await fetchPaneChanges(target, scope);
+ changes = await loadPaneChanges(target, scope, revision > 0);
} catch (error) {
- if (!cancelled) setList({ kind: "error", message: error instanceof Error ? error.message : String(error) });
+ if (!cancelled && !cached) setList({ kind: "error", message: error instanceof Error ? error.message : String(error) });
return;
}
if (cancelled) return;
- setList({ kind: "ready", changes });
- const queue = changes.files.filter((file) => !file.is_directory).map((file) => file.path);
- setDiffs(Object.fromEntries(queue.map((path) => [path, { kind: "loading" } as DiffState])));
+ if (changes !== cached) show(changes);
+ const queue = changes.files.filter((file) => !file.is_directory && !file.diff).map((file) => file.path);
const worker = async () => {
for (let path = queue.shift(); path !== undefined && !cancelled; path = queue.shift()) {
let next: DiffState;
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx
index 22174c9167..030b88a966 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx
@@ -34,6 +34,26 @@ describe("compact workspace terminal header", () => {
expect(screen.queryByRole("button", { name: "Review changes by Dana" })).toBeNull();
});
+ it("reads the review ahead when the pointer reaches its button, and after a dwell on the bar", () => {
+ vi.useFakeTimers();
+ try {
+ const prefetch = vi.fn();
+ render(<WorkspaceTerminalHeader {...BASE} onReviewChanges={() => {}} onReviewChangesPrefetch={prefetch} />);
+ const header = screen.getByTestId("workspace-terminal-header-Dana");
+ fireEvent.pointerEnter(header);
+ fireEvent.pointerLeave(header);
+ act(() => { vi.advanceTimersByTime(1000); });
+ expect(prefetch).not.toHaveBeenCalled();
+ fireEvent.pointerEnter(header);
+ act(() => { vi.advanceTimersByTime(300); });
+ expect(prefetch).toHaveBeenCalledTimes(1);
+ fireEvent.pointerEnter(screen.getByRole("button", { name: "Review changes by Dana" }));
+ expect(prefetch).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("uses the name and accurate status without a verbose toolbar", () => {
render(<WorkspaceTerminalHeader {...BASE} onOpenConversation={() => {}} />);
const header = screen.getByTestId("workspace-terminal-header-Dana");
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx
index af89a7715d..8df4681baa 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx
@@ -40,6 +40,8 @@ interface Props {
onOpenChat?: () => void;
/** Opens the review of every uncommitted change this pane's agent made. */
onReviewChanges?: () => void;
+ /** Starts reading the review ahead of a click: on the button at once, on the title bar after a short dwell. */
+ onReviewChangesPrefetch?: () => void;
onRestart?: () => void;
/** Opens the fork dialog: a new agent continuing a copy of this pane's chat. */
onFork?: () => void;
@@ -78,7 +80,7 @@ export function WorkspaceTerminalHeader({
contextMenuRequest, onSwapWithFocused, sendRightClicks = false, onToggleSendRightClicks,
name, workspaceId, promptCount = 0, agent, agentLogoUrl, displayName, status, appearance, arranging = false,
maximized = false, addDisabled = false, onArrangeStart, onActivate, onToggleMaximize,
- onAdd, onClose, onRename, onOpenConversation, onOpenChat, onReviewChanges, onRestart, onFork, branch,
+ onAdd, onClose, onRename, onOpenConversation, onOpenChat, onReviewChanges, onReviewChangesPrefetch, onRestart, onFork, branch,
computerName, placementItems, workspaceItems, variant = "bar", focused = false, githubStatusEnabled = true,
}: Props) {
const brand = PANE_BRAND[appearance];
@@ -97,6 +99,19 @@ export function WorkspaceTerminalHeader({
const [renameError, setRenameError] = useState("");
const stopped = status === "exited" || status === "error";
const menuOpen = menuPosition !== null;
+ // A pointer resting on the title bar is a pointer about to use it: the
+ // review is read ahead so it opens already painted. A pass across the bar
+ // on the way somewhere else is too short to start a read.
+ const prefetchTimer = useRef<number | null>(null);
+ const cancelPrefetch = () => {
+ if (prefetchTimer.current !== null) window.clearTimeout(prefetchTimer.current);
+ prefetchTimer.current = null;
+ };
+ useEffect(() => cancelPrefetch, []);
+ const prefetchReview = () => {
+ void loadLocaleChunk("pane_review");
+ onReviewChangesPrefetch?.();
+ };
useEffect(() => {
if (contextMenuRequest) setMenuPosition(contextMenuRequest);
}, [contextMenuRequest]);
@@ -245,6 +260,11 @@ export function WorkspaceTerminalHeader({
: "relative flex h-9 min-h-9 shrink-0 select-none items-center gap-1 border-b pl-2.5 pr-1"}
style={{ ...variables, borderColor: chrome.border, background: chrome.shell, touchAction: onArrangeStart ? "none" : undefined }}
onContextMenu={openMenuAt}
+ onPointerEnter={onReviewChanges ? () => {
+ cancelPrefetch();
+ prefetchTimer.current = window.setTimeout(prefetchReview, 300);
+ } : undefined}
+ onPointerLeave={cancelPrefetch}
onPointerDown={(event) => {
if (event.button !== 0 || (event.target as HTMLElement).closest("[data-header-control]")) return;
setMenuPosition(null);
@@ -279,7 +299,7 @@ export function WorkspaceTerminalHeader({
<SessionGitHubBadge workspaceId={githubStatusEnabled ? workspaceId : undefined} name={name} appearance={appearance} />
<div data-header-control="true" className="flex shrink-0 items-center gap-0.5">
{onReviewChanges && <button type="button" data-testid={`pane-review-changes-${name}`} aria-label={`Review changes by ${name}`}
- title="Review changes" onClick={onReviewChanges} onPointerEnter={() => void loadLocaleChunk("pane_review")} className={action}><FileDiff className="h-[15px] w-[15px]" /></button>}
+ title="Review changes" onClick={onReviewChanges} onPointerEnter={() => { cancelPrefetch(); prefetchReview(); }} className={action}><FileDiff className="h-[15px] w-[15px]" /></button>}
{moreButton}
{maximizeButton}
{onFork && <button type="button" data-testid={`pane-fork-${name}`} aria-label={`Fork ${name}`} title={`Fork ${name}`}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts b/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts
index 7fa30aa240..4fb20ac297 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneChangesApi.ts
@@ -26,10 +26,15 @@ 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. */
+/** A file's diff as the pane route carries it inline. */
+export type InlineDiff = Omit<FileDiff, "workspace_id" | "path">;
+
+/** A listed file; `committed` and `diff` are set by the pane route only. */
export interface ReviewFile extends ChangedFile {
/** True when nothing of the change is left uncommitted. */
committed?: boolean;
+ /** Its diff, sent with the list so the review paints at once; absent = read on demand. */
+ diff?: InlineDiff | null;
}
export interface PaneChanges {
@@ -149,6 +154,68 @@ export async function fetchPaneChanges(target: PaneChangesTarget, scope: ChangeS
return reading(body, { folderTotal: body.files.length, ownCheckout }, files);
}
+/**
+ * The last reading per pane and scope, so the review opens already painted.
+ *
+ * Hovering the pane's title bar or its review button starts a reading
+ * (`prefetchPaneChanges`); opening the review shows the newest reading at
+ * once and reads again behind it, so what is on screen is never older than
+ * the moment it was opened plus one round trip.
+ */
+interface CacheEntry {
+ at: number;
+ value?: PaneChanges;
+ pending?: Promise<PaneChanges>;
+}
+
+/** A reading this young is reused as is instead of being read again. */
+export const PANE_CHANGES_FRESH_MS = 5_000;
+
+const readings = new Map<string, CacheEntry>();
+
+const cacheKey = (target: PaneChangesTarget, scope: ChangeScope) =>
+ `${target.workspaceId}|${target.pane}|${target.folder ?? ""}|${scope}`;
+
+/** The newest finished reading, however old; null before the first one. */
+export function cachedPaneChanges(target: PaneChangesTarget, scope: ChangeScope): PaneChanges | null {
+ return readings.get(cacheKey(target, scope))?.value ?? null;
+}
+
+/**
+ * Read the pane's changes, sharing a reading already under way and reusing
+ * one younger than `PANE_CHANGES_FRESH_MS`; `force` (Refresh) always reads anew.
+ */
+export function loadPaneChanges(target: PaneChangesTarget, scope: ChangeScope, force = false): Promise<PaneChanges> {
+ const key = cacheKey(target, scope);
+ const entry = readings.get(key);
+ if (entry?.pending && !force) return entry.pending;
+ if (!force && entry?.value && Date.now() - entry.at < PANE_CHANGES_FRESH_MS) return Promise.resolve(entry.value);
+ const pending = fetchPaneChanges(target, scope).then(
+ (value) => {
+ readings.set(key, { at: Date.now(), value });
+ return value;
+ },
+ (error: unknown) => {
+ readings.set(key, { at: entry?.at ?? 0, value: entry?.value });
+ throw error;
+ },
+ );
+ readings.set(key, { at: entry?.at ?? 0, value: entry?.value, pending });
+ return pending;
+}
+
+/** Start reading a pane's own changes ahead of a click; failures stay silent until the review opens. */
+export function prefetchPaneChanges(target: PaneChangesTarget): void {
+ loadPaneChanges(target, "pane").catch(() => {
+ /* the review reads again when it opens and shows the error there */
+ });
+}
+
+/** Forget every reading — for tests. */
+export function clearPaneChangesCache(): void {
+ readings.clear();
+}
+
/** 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()}`);
diff --git a/tests/unit/web/test_agentic_ide_pane_changes_route.py b/tests/unit/web/test_agentic_ide_pane_changes_route.py
index 791e1b10b1..fb919e4fdd 100644
--- a/tests/unit/web/test_agentic_ide_pane_changes_route.py
+++ b/tests/unit/web/test_agentic_ide_pane_changes_route.py
@@ -114,6 +114,13 @@ async def test_work_the_agent_already_committed_is_listed(
("mine.py", "modified", 1, 1, True)
]
assert answer.since_ms == FIRST_WRITE_MS
+ # The diff travels with the list, so the review paints without another round trip.
+ inline = answer.files[0].diff
+ assert inline is not None
+ assert [(line.kind, line.text) for hunk in inline.hunks for line in hunk.lines] == [
+ ("del", "one"),
+ ("add", "two"),
+ ]
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"),