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(agent-chat): a code change reads as a diff, and a finished run of steps puts itself away
rubenluetke10-beep730ecd6d505b
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsxindex 2c5f5fc39a..3f3d39b209 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx@@ -224,3 +224,161 @@ describe("the scratchpad", () => {expect(screen.getAllByTestId("agent-turn-live")).toHaveLength(1);});});++/*+ * The change a coding call made, and the wall of steps around it.+ *+ * Two complaints from 2026-08-27, judged against Claude Code and Codex: an+ * edit arrived as its raw arguments, so the one thing worth reading — what+ * actually changed — was the one thing you could not read; and a finished+ * turn left its whole run of calls lying in the transcript, which the+ * maintainer called "far too much stuff".+ */+describe("a coding call shows its diff", () => {+ const EDIT = {+ turn_id: "d1",+ call_id: "e1",+ name: "Edit",+ input: {+ file_path: "src/app.ts",+ old_string: "const port = 47821;",+ new_string: "const port = 47921;",+ },+ };++ function drawEdit(output = "The file src/app.ts has been updated successfully.") {+ draw([+ ev("user_message", { text: "change the port" }),+ ev("turn_started", { turn_id: "d1", ...TURN }),+ ev("tool_call", EDIT),+ ev("tool_result", { turn_id: "d1", call_id: "e1", output, is_error: false }),+ ev("turn_finished", { turn_id: "d1", status: "done", duration_ms: 900, usage: {} }),+ ]);+ }++ it("wears the size of the change on the row, before anything is opened", () => {+ drawEdit();+ const stat = screen.getByTestId("agent-diff-stat");+ expect(stat.dataset.added).toBe("1");+ expect(stat.dataset.removed).toBe("1");+ });++ it("paints the removed line and the added one when the row is opened", () => {+ drawEdit();+ fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);+ const diff = screen.getByTestId("agent-tool-diff");+ const removed = diff.querySelector("[data-diff='del']");+ const added = diff.querySelector("[data-diff='add']");+ expect(removed?.textContent).toContain("47821");+ expect(added?.textContent).toContain("47921");+ // The colours live on a class each, so both themes get their own pair.+ expect(removed?.className).toContain("diff-line-del");+ expect(added?.className).toContain("diff-line-add");+ });++ it("does not repeat the edit's receipt under the diff it already showed", () => {+ drawEdit();+ fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);+ expect(screen.getByTestId("agent-tool-diff")).toBeTruthy();+ expect(screen.queryByText(/has been updated successfully/)).toBeNull();+ });++ it("still shows the output when the edit FAILED — that is the whole point", () => {+ draw([+ ev("turn_started", { turn_id: "d1", ...TURN }),+ ev("tool_call", EDIT),+ ev("tool_result", {+ turn_id: "d1",+ call_id: "e1",+ output: "String to replace not found in file.",+ is_error: true,+ }),+ ev("turn_finished", { turn_id: "d1", status: "done", duration_ms: 900, usage: {} }),+ ]);+ fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);+ expect(screen.getByText(/String to replace not found/)).toBeTruthy();+ });++ it("leaves a call that edits nothing exactly as it was", () => {+ draw([+ ev("turn_started", { turn_id: "d2", ...TURN }),+ ev("tool_call", { turn_id: "d2", call_id: "b1", name: "Bash", input: { command: "ls" } }),+ ev("tool_result", { turn_id: "d2", call_id: "b1", output: "a.ts", is_error: false }),+ ev("turn_finished", { turn_id: "d2", status: "done", duration_ms: 200, usage: {} }),+ ]);+ expect(screen.queryByTestId("agent-diff-stat")).toBeNull();+ fireEvent.click(screen.getByTestId("agent-tool").querySelector("button")!);+ expect(screen.queryByTestId("agent-tool-diff")).toBeNull();+ expect(screen.getByText("a.ts")).toBeTruthy();+ });+});++describe("a run of steps puts itself away", () => {+ /** `count` calls in a row, optionally one of them failing. */+ function run(count: number, opts: { live?: boolean; failAt?: number } = {}) {+ const events = [+ ev("user_message", { text: "look into it" }),+ ev("turn_started", { turn_id: "g1", ...TURN }),+ ];+ for (let i = 0; i < count; i++) {+ events.push(+ ev("tool_call", {+ turn_id: "g1",+ call_id: `c${i}`,+ name: "Grep",+ input: { pattern: `p${i}` },+ }),+ );+ events.push(+ ev("tool_result", {+ turn_id: "g1",+ call_id: `c${i}`,+ output: "hit",+ is_error: opts.failAt === i,+ }),+ );+ }+ if (!opts.live) {+ events.push(+ ev("turn_finished", { turn_id: "g1", status: "done", duration_ms: 5000, usage: {} }),+ );+ }+ draw(events);+ }++ it("folds a finished run to one line, and opens it again on a click", () => {+ run(6);+ const group = screen.getByTestId("agent-tool-group");+ expect(group.dataset.state).toBe("folded");+ expect(screen.queryAllByTestId("agent-tool")).toHaveLength(0);++ fireEvent.click(screen.getByTestId("agent-tool-group-toggle"));+ expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("open");+ expect(screen.queryAllByTestId("agent-tool")).toHaveLength(6);+ });++ it("leaves a short run alone: three rows are not a wall", () => {+ run(3);+ expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("plain");+ expect(screen.queryByTestId("agent-tool-group-toggle")).toBeNull();+ expect(screen.queryAllByTestId("agent-tool")).toHaveLength(3);+ });++ it("shows every step while the turn is still working", () => {+ run(6, { live: true });+ expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("plain");+ expect(screen.queryAllByTestId("agent-tool")).toHaveLength(6);+ });++ it("folds AROUND a step that failed, keeping the failure itself in view", () => {+ // The first pass held the whole run open on any failure, which left a+ // group of thirty-five calls lying open because one of them missed (live+ // check, 2026-08-27). The failure is the thing worth seeing — not the+ // thirty-four calls that went fine around it.+ run(6, { failAt: 2 });+ expect(screen.getByTestId("agent-tool-group").dataset.state).toBe("folded");+ const rows = screen.queryAllByTestId("agent-tool");+ expect(rows).toHaveLength(1);+ expect(rows[0].dataset.state).toBe("error");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsxindex c4529f4e15..17e4b38134 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx@@ -25,6 +25,7 @@ import { LiveCore } from "@/components/LiveCore";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { formatThoughtDuration } from "@/components/home/TurnSteps";import { agentToolView, formatTokens, outputTokens } from "@/components/agentchat/toolView";+import { diffStat, toolDiff, type DiffFile, type DiffLine } from "@/components/agentchat/toolDiff";import type {ReasoningBlock,TextBlock,@@ -185,6 +186,7 @@ const Turn = memo(function Turn({const live = turn.status === "running";const elapsed = useElapsedMs(live ? turn.startedMs : null);const blocks = useMemo(() => arrangeThinking(turn.blocks), [turn.blocks]);+ const groups = useMemo(() => groupSteps(blocks), [blocks]);// A scratchpad still receiving words carries the turn's live line in its// own header; the line below would only say "thinking" a second time.const thinkingAloud = blocks.some((b) => b.kind === "reasoning" && b.live);@@ -215,14 +217,26 @@ const Turn = memo(function Turn({{/* No rail, no frame: the byline above and the spacing are what groupthe turn, and the closing line below says how it ended. */}<div className="flex flex-col gap-1.5 px-1">- {blocks.map((block) => {- if (block.kind === "text") return <Prose key={block.id} block={block} />;- if (block.kind === "reasoning") {+ {groups.map((group) => {+ if (group.kind === "tools") {return (- <Thought key={block.id} block={block} turnLive={live} usage={turn.liveUsage} />+ <ToolGroup+ key={group.id}+ blocks={group.blocks}+ turnLive={live}+ onDecide={onDecide}+ />);}- return <ToolRow key={block.callId} block={block} onDecide={onDecide} />;+ if (group.block.kind === "text") return <Prose key={group.id} block={group.block} />;+ return (+ <Thought+ key={group.id}+ block={group.block}+ turnLive={live}+ usage={turn.liveUsage}+ />+ );})}{live && !thinkingAloud && <LiveStatus elapsed={elapsed} usage={turn.liveUsage} />}@@ -707,6 +721,242 @@ function errorGist(text: string): string {return trimmed.length > 160 ? `${trimmed.slice(0, 159)}…` : trimmed;}+/**+ * The change a coding call made, painted the way every code host paints one.+ *+ * A row saying `Edit src/app.ts` names a file and says nothing about what+ * happened in it, and the arguments underneath were worse: two JSON string+ * literals, escapes and all, so the one thing worth reading was the one thing+ * that could not be (maintainer, 2026-08-27, against Claude Code and Codex).+ *+ * No frame — the fold's own indent already holds it (rule 1). What carries+ * the meaning is the ink: removed lines in the destructive red the whole app+ * uses for loss, added lines in the one green the palette now has, and every+ * line that did NOT move in plain grey, which is what makes a change legible+ * rather than a wall of colour.+ */+function DiffView({ files }: { files: DiffFile[] }) {+ const t = useT();+ return (+ <div className="flex flex-col gap-2" data-testid="agent-tool-diff">+ {files.map((file, i) => (+ <div key={`${file.path}:${i}`} className="flex min-w-0 flex-col gap-1">+ {/* The path only when the row above cannot already be carrying it:+ one file is named on the row, several need naming here. */}+ {files.length > 1 && file.path && (+ <span className="truncate font-mono text-[10px] text-muted-foreground/60">+ {file.path}+ </span>+ )}+ <div className="scrollbar-jarvis max-h-80 overflow-auto">+ {file.lines.map((line, n) => (+ <DiffRow key={n} line={line} />+ ))}+ </div>+ {file.truncated > 0 && (+ <span className="font-mono text-[10px] text-muted-foreground/50">+ {fill(t("agent_chat.diff_truncated"), { count: String(file.truncated) })}+ </span>+ )}+ </div>+ ))}+ </div>+ );+}++/**+ * One line of a diff.+ *+ * The +/- mark is unselectable, so copying a diff out of the chat yields the+ * CODE rather than a column of marks to strip afterwards.+ */+function DiffRow({ line }: { line: DiffLine }) {+ const t = useT();+ if (line.kind === "gap") {+ return (+ <div+ data-diff="gap"+ className="select-none px-2 py-0.5 font-mono text-[10px] text-muted-foreground/40"+ >+ {line.text ? fill(t("agent_chat.diff_skipped"), { count: line.text }) : "⋯"}+ </div>+ );+ }+ return (+ <div+ data-diff={line.kind}+ className={cn(+ "flex whitespace-pre-wrap break-words px-2 font-mono text-[11.5px] leading-relaxed",+ line.kind === "add" && "diff-line-add",+ line.kind === "del" && "diff-line-del",+ line.kind === "ctx" && "text-muted-foreground/70",+ )}+ >+ <span aria-hidden className="mr-2 w-2 shrink-0 select-none opacity-70">+ {line.kind === "add" ? "+" : line.kind === "del" ? "-" : " "}+ </span>+ <span className="min-w-0">{line.text || "\u00A0"}</span>+ </div>+ );+}++/** `+12 -3` — how big the change is, in the shape every code host uses. */+function DiffStat({ added, removed }: { added: number; removed: number }) {+ if (added === 0 && removed === 0) return null;+ return (+ <span+ className="shrink-0 font-mono text-[10px] tabular-nums"+ data-testid="agent-diff-stat"+ data-added={added}+ data-removed={removed}+ >+ {added > 0 && <span className="diff-ink-add">+{added}</span>}+ {added > 0 && removed > 0 && <span className="text-muted-foreground/40"> </span>}+ {removed > 0 && <span className="diff-ink-del">-{removed}</span>}+ </span>+ );+}++/**+ * A turn's blocks, with consecutive tool calls collected into one group.+ *+ * Thinking and prose stay exactly where they happened — that is rule 2 and it+ * is not up for negotiation. What CAN be put away is a run of tool calls with+ * nothing between them: twenty greps and reads in a row is the "far too much+ * stuff" the maintainer objected to (2026-08-27), and it is also the part of+ * a finished turn nobody re-reads.+ */+export type TurnGroup =+ | { kind: "tools"; id: string; blocks: ToolBlock[] }+ | { kind: "block"; id: string; block: TextBlock | ReasoningBlock };++export function groupSteps(blocks: TurnBlock[]): TurnGroup[] {+ const out: TurnGroup[] = [];+ for (const block of blocks) {+ if (block.kind === "tool") {+ const last = out[out.length - 1];+ if (last && last.kind === "tools") {+ last.blocks.push(block);+ continue;+ }+ out.push({ kind: "tools", id: `g-${block.callId}`, blocks: [block] });+ continue;+ }+ out.push({ kind: "block", id: block.id, block });+ }+ return out;+}++/** From this many calls in a row, a finished run puts itself away. */+export const FOLD_STEPS_FROM = 4;++/**+ * A run of tool calls — open while it matters, one line once it does not.+ *+ * WHILE THE TURN WORKS every step shows: watching the work is the whole point+ * of a running turn, and a spinner behind a fold proves nothing. The moment+ * the turn is done a long run collapses to "14 steps · +42 -7 · 1m 12s",+ * which is what a finished conversation should read as — the answer, with the+ * work one click away.+ *+ * Two runs never fold, however long: one holding a step that FAILED, and one+ * holding a step still waiting for a decision. Both are the reason the person+ * is looking at the turn at all.+ */+function ToolGroup({+ blocks,+ turnLive,+ onDecide,+}: {+ blocks: ToolBlock[];+ turnLive: boolean;+ onDecide: (approvalId: string, decision: ApprovalDecision) => void;+}) {+ const [manual, setManual] = useState<boolean | null>(null);+ // A call still waiting for a decision is a question to the person: it holds+ // the whole run open, because an approval behind a fold is an approval+ // nobody gives. A call that FAILED does not — it stays in view on its own+ // while the rest of the run folds away around it.+ const asking = blocks.some((b) => b.approval !== null && b.approval.decision === null);+ const foldable = !turnLive && !asking && blocks.length >= FOLD_STEPS_FROM;+ const open = !foldable || (manual ?? false);+ const shown = open ? blocks : blocks.filter((b) => b.isError);+ const duration = blocks.reduce((sum, b) => sum + (b.durationMs ?? 0), 0);+ const stat = useMemo(() => {+ const files = blocks.flatMap((b) => toolDiff(b.name, b.input) ?? []);+ return files.length ? diffStat(files) : null;+ }, [blocks]);++ return (+ <div+ className="flex min-w-0 flex-col gap-1.5"+ data-testid="agent-tool-group"+ data-state={!foldable ? "plain" : open ? "open" : "folded"}+ data-steps={blocks.length}+ >+ {foldable && (+ <GroupToggle+ open={open}+ count={blocks.length}+ duration={duration}+ stat={stat}+ onClick={() => setManual(!open)}+ />+ )}+ {shown.map((b) => (+ <ToolRow key={b.callId} block={b} onDecide={onDecide} />+ ))}+ </div>+ );+}++/** The one line a folded run wears, and the way back out of an open one. */+function GroupToggle({+ open,+ count,+ duration,+ stat,+ onClick,+}: {+ open: boolean;+ count: number;+ duration: number;+ stat: { added: number; removed: number } | null;+ onClick: () => void;+}) {+ const t = useT();+ return (+ <button+ type="button"+ onClick={onClick}+ aria-expanded={open}+ data-testid="agent-tool-group-toggle"+ className={cn(+ "-ml-1 flex w-full min-w-0 items-center gap-2 rounded-md px-1 py-1",+ "text-left text-xs transition-colors hover:bg-secondary/50",+ )}+ >+ <ChevronRight+ className={cn(+ "h-3.5 w-3.5 shrink-0 text-muted-foreground/50 transition-transform",+ open && "rotate-90",+ )}+ aria-hidden+ />+ <span className="shrink-0 font-medium text-muted-foreground">+ {fill(t("agent_chat.steps_count"), { count: String(count) })}+ </span>+ {stat && <DiffStat added={stat.added} removed={stat.removed} />}+ <span className="flex-1" />+ {duration > 0 && (+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60">+ {formatStepDuration(duration)}+ </span>+ )}+ </button>+ );+}+/*** One tool call — a ROW, not a card.*@@ -741,6 +991,10 @@ function ToolRow({const showLogo = Boolean(view.logoUrl) && !logoFailed;const gist = block.isError && block.output ? errorGist(block.output) : "";const showInput = !inputAddsNothing(block.input, summary);+ // A coding call carries its change in its arguments. Read it once here: the+ // row wears the size of it, the fold paints the whole thing.+ const diff = useMemo(() => toolDiff(block.name, block.input), [block.name, block.input]);+ const stat = diff ? diffStat(diff) : null;return (<div@@ -810,6 +1064,7 @@ function ToolRow({) : (<span className="flex-1" />)}+ {stat && !running && <DiffStat added={stat.added} removed={stat.removed} />}{running ? (<span className="inline-flex shrink-0 items-center gap-1.5 text-[10px] text-primary/90"><Spinner />@@ -877,17 +1132,27 @@ function ToolRow({{open && (<Trace tone={block.isError ? "error" : "plain"}>- {showInput && <Detail label={t("agent_chat.tool_input")} text={pretty(block.input)} />}- {denied && <div className="text-muted-foreground">{t("agent_chat.approval_denied")}</div>}- {block.output !== null ? (- <Detail- label={block.isError ? t("agent_chat.tool_error") : t("agent_chat.tool_output")}- text={block.output}- error={block.isError}- />+ {diff ? (+ <DiffView files={diff} />) : (- running && <div className="text-muted-foreground">{t("agent_chat.tool_running")}</div>+ showInput && <Detail label={t("agent_chat.tool_input")} text={pretty(block.input)} />)}+ {denied && <div className="text-muted-foreground">{t("agent_chat.approval_denied")}</div>}+ {block.output !== null+ ? // An edit's receipt — "The file … has been updated successfully" —+ // says nothing the diff above did not already show, so a call that+ // painted its change keeps its output for the case that matters:+ // when it failed.+ (!diff || block.isError) && (+ <Detail+ label={block.isError ? t("agent_chat.tool_error") : t("agent_chat.tool_output")}+ text={block.output}+ error={block.isError}+ />+ )+ : running && (+ <div className="text-muted-foreground">{t("agent_chat.tool_running")}</div>+ )}</Trace>)}</div>diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.tsnew file mode 100644index 0000000000..3141838b90--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.ts@@ -0,0 +1,153 @@+/*+ * What a coding tool call turns into on screen.+ *+ * The claim under test is not "a diff was produced" but "the lines that did+ * not move stayed grey": a change is readable exactly to the degree that the+ * unchanged code around it is visibly unchanged. Every CLI spells its+ * arguments differently, so each vocabulary gets its own case.+ */+import { describe, expect, it } from "vitest";++import { diffStat, isDiffTool, parsePatchText, toolDiff } from "./toolDiff";++/** The diff as one string, the way a reader sees it: "-old", "+new", " ctx". */+function render(lines: Array<{ kind: string; text: string }>): string {+ return lines+ .map((l) =>+ l.kind === "add" ? `+${l.text}` : l.kind === "del" ? `-${l.text}` : l.kind === "gap" ? "…" : ` ${l.text}`,+ )+ .join("\n");+}++describe("which calls carry a diff", () => {+ it("knows the editing tools of every CLI, and leaves the rest alone", () => {+ for (const name of ["Edit", "MultiEdit", "Write", "apply_patch", "str_replace_based_edit_tool", "NotebookEdit"]) {+ expect(isDiffTool(name)).toBe(true);+ }+ for (const name of ["Bash", "Read", "Grep", "WebFetch", "Task"]) {+ expect(isDiffTool(name)).toBe(false);+ }+ });++ it("answers null for a call that edits nothing, rather than an empty diff", () => {+ expect(toolDiff("Bash", { command: "ls" })).toBeNull();+ // An edit whose arguments did not survive the transport: the row falls+ // back to its plain summary, which is honest. An empty diff would not be.+ expect(toolDiff("Edit", { file_path: "a.ts" })).toBeNull();+ });+});++describe("Claude Code's edits", () => {+ it("colours only the line that moved, keeping its neighbours grey", () => {+ const files = toolDiff("Edit", {+ file_path: "src/app.ts",+ old_string: "const a = 1;\nconst b = 2;\nconst c = 3;",+ new_string: "const a = 1;\nconst b = 22;\nconst c = 3;",+ });+ expect(files).not.toBeNull();+ expect(files![0].path).toBe("src/app.ts");+ expect(render(files![0].lines)).toBe(+ [" const a = 1;", "-const b = 2;", "+const b = 22;", " const c = 3;"].join("\n"),+ );+ expect(diffStat(files!)).toEqual({ added: 1, removed: 1 });+ });++ it("reads a MultiEdit as one file changed in several places, in order", () => {+ const files = toolDiff("MultiEdit", {+ file_path: "src/app.ts",+ edits: [+ { old_string: "one", new_string: "ONE" },+ { old_string: "two", new_string: "TWO" },+ ],+ });+ expect(files).toHaveLength(2);+ expect(files!.every((f) => f.path === "src/app.ts")).toBe(true);+ expect(diffStat(files!)).toEqual({ added: 2, removed: 2 });+ });++ it("treats a Write as a file being started: every line is an addition", () => {+ const files = toolDiff("Write", { file_path: "new.ts", content: "a\nb\n" });+ expect(files![0].created).toBe(true);+ expect(render(files![0].lines)).toBe("+a\n+b");+ expect(diffStat(files!)).toEqual({ added: 2, removed: 0 });+ });++ it("reads the text editor's own field names too", () => {+ const files = toolDiff("str_replace_based_edit_tool", {+ command: "str_replace",+ path: "x.py",+ old_str: "print(1)",+ new_str: "print(2)",+ });+ expect(files![0].path).toBe("x.py");+ expect(diffStat(files!)).toEqual({ added: 1, removed: 1 });+ });+});++describe("Codex's apply_patch", () => {+ const PATCH = [+ "*** Begin Patch",+ "*** Update File: src/main.py",+ "@@",+ " def main():",+ "- print('old')",+ "+ print('new')",+ " ",+ "*** End Patch",+ ].join("\n");++ it("takes the file name out of the patch envelope", () => {+ const files = toolDiff("apply_patch", { input: PATCH });+ expect(files).toHaveLength(1);+ expect(files![0].path).toBe("src/main.py");+ expect(diffStat(files!)).toEqual({ added: 1, removed: 1 });+ });++ it("reads a plain unified header as well, and splits it per file", () => {+ const files = parsePatchText(+ [+ "--- a/one.ts",+ "+++ b/one.ts",+ "@@ -1,2 +1,2 @@",+ "-a",+ "+A",+ "--- a/two.ts",+ "+++ b/two.ts",+ "@@ -1,1 +1,1 @@",+ "-b",+ "+B",+ ].join("\n"),+ );+ expect(files.map((f) => f.path)).toEqual(["one.ts", "two.ts"]);+ });++ it("accepts the patch as a bare string argument", () => {+ expect(toolDiff("apply_patch", PATCH)![0].path).toBe("src/main.py");+ });+});++describe("long changes stay readable", () => {+ it("replaces untouched stretches with one gap rather than printing them", () => {+ const before = Array.from({ length: 40 }, (_, i) => `line ${i}`).join("\n");+ const after = before.replace("line 20", "line twenty");+ const files = toolDiff("Edit", { file_path: "big.txt", old_string: before, new_string: after });+ const shown = files![0].lines;+ // Three lines of context each side, the change itself, and a gap standing+ // in for everything else — not forty lines to find one.+ expect(shown.filter((l) => l.kind === "gap")).toHaveLength(2);+ expect(shown.length).toBeLessThan(12);+ expect(render(shown)).toContain("-line 20");+ expect(render(shown)).toContain("+line twenty");+ });++ it("does not try to match line-by-line past the size where it would stall", () => {+ const before = Array.from({ length: 1400 }, (_, i) => `a${i}`).join("\n");+ const after = Array.from({ length: 1400 }, (_, i) => `b${i}`).join("\n");+ const files = toolDiff("Edit", { file_path: "huge.txt", old_string: before, new_string: after });+ expect(files![0].added).toBe(1400);+ expect(files![0].removed).toBe(1400);+ // Painted up to the cap, and honest about the rest.+ expect(files![0].lines.length).toBeLessThanOrEqual(400);+ expect(files![0].truncated).toBeGreaterThan(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.tsnew file mode 100644index 0000000000..f8ee34d724--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.ts@@ -0,0 +1,316 @@+/**+ * A code-editing tool call → the diff it describes, ready to paint.+ *+ * A row that says `Edit src/app.ts` tells you a file changed and nothing+ * about WHAT changed, and the raw arguments underneath are worse: an `Edit`+ * carries its before and after as two JSON string literals, escapes and all,+ * so the one thing worth reading is the one thing you cannot (maintainer,+ * 2026-08-27, against Claude Code and Codex, which both paint the change).+ *+ * So this module turns whatever the agent's own tool vocabulary called it+ * into the same small shape: a list of files, each a list of lines marked+ * added / removed / context. Every coding CLI is covered because they+ * disagree about the field names and agree about nothing else:+ *+ * - Claude Code `Edit` — `old_string` / `new_string`+ * - Claude Code `MultiEdit` — `edits: [{old_string, new_string}]`+ * - Claude Code `Write` — `content`, whole file, all additions+ * - Anthropic text editor — `command: str_replace|create`, `old_str`+ * - Codex / OpenAI `apply_patch` — a unified-ish patch as ONE string+ * - Notebook edits — `new_source` against `old_source`+ *+ * Pure — no React — so the mapping is unit-testable and identical wherever a+ * diff is drawn.+ */++/** One printed line of a diff. `gap` stands for context that was skipped. */+export interface DiffLine {+ kind: "add" | "del" | "ctx" | "gap";+ text: string;+}++export interface DiffFile {+ /** The path the tool named, or "" when it named none. */+ path: string;+ lines: DiffLine[];+ added: number;+ removed: number;+ /** A file being written whole: there is no "before" to show. */+ created: boolean;+ /** Lines dropped from the end because the change is enormous. */+ truncated: number;+}++/**+ * How much unchanged code stays around a change.+ *+ * Three lines is the unified-diff convention and it is the right amount for+ * reading: enough to recognise where in the file you are, not so much that a+ * one-line fix arrives inside a screenful of things that did not move.+ */+const CONTEXT_LINES = 3;++/** Past this, painting every line costs more than it tells. */+const MAX_LINES = 400;++/**+ * Above this many lines on either side, the line-by-line match is dropped.+ *+ * The matcher is quadratic. That is free for the hunk-sized before/after an+ * `Edit` carries and ruinous for a 5000-line file pasted in whole, so past+ * the cap the change is shown honestly as "all of that, then all of this"+ * rather than freezing the column to compute a prettier answer.+ */+const MATCH_CAP = 1200;++export function isDiffTool(name: string): boolean {+ return /^(edit|multi_?edit|write|create_?file|write_?file|apply_?patch|str_replace(_based_edit_tool)?|notebook_?edit|update_?file|patch_?file)$/i.test(+ (name ?? "").trim(),+ );+}++/** Split keeping no trailing empty line, so a file ending in \n has no ghost row. */+function lines(text: string): string[] {+ const out = text.replace(/\r\n/g, "\n").split("\n");+ if (out.length > 1 && out[out.length - 1] === "") out.pop();+ return out;+}++function str(obj: Record<string, unknown>, ...keys: string[]): string | null {+ for (const key of keys) {+ const v = obj[key];+ if (typeof v === "string") return v;+ }+ return null;+}++/**+ * Longest-common-subsequence line match, then rendered as a unified diff.+ *+ * The match is what separates this from "print the old, print the new": the+ * lines both sides share stay grey and only what actually moved is coloured,+ * which is the difference between reading a change and re-reading a file.+ */+function diffLines(before: string, after: string): DiffLine[] {+ const a = lines(before);+ const b = lines(after);++ if (a.length > MATCH_CAP || b.length > MATCH_CAP) {+ return [+ ...a.map((text): DiffLine => ({ kind: "del", text })),+ ...b.map((text): DiffLine => ({ kind: "add", text })),+ ];+ }++ // table[i][j] = length of the LCS of a[i:] and b[j:]+ const table: number[][] = Array.from({ length: a.length + 1 }, () =>+ new Array<number>(b.length + 1).fill(0),+ );+ for (let i = a.length - 1; i >= 0; i--) {+ for (let j = b.length - 1; j >= 0; j--) {+ table[i][j] =+ a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);+ }+ }++ const out: DiffLine[] = [];+ let i = 0;+ let j = 0;+ while (i < a.length && j < b.length) {+ if (a[i] === b[j]) {+ out.push({ kind: "ctx", text: a[i] });+ i++;+ j++;+ } else if (table[i + 1][j] >= table[i][j + 1]) {+ out.push({ kind: "del", text: a[i] });+ i++;+ } else {+ out.push({ kind: "add", text: b[j] });+ j++;+ }+ }+ while (i < a.length) out.push({ kind: "del", text: a[i++] });+ while (j < b.length) out.push({ kind: "add", text: b[j++] });+ return out;+}++/**+ * Keep the changes and `CONTEXT_LINES` around each, replacing the rest with+ * one `gap` row. A diff of a long file is mostly lines that did not change.+ */+export function trimContext(all: DiffLine[]): DiffLine[] {+ const keep = new Array<boolean>(all.length).fill(false);+ let anyChange = false;+ for (let i = 0; i < all.length; i++) {+ if (all[i].kind === "ctx") continue;+ anyChange = true;+ for (let k = Math.max(0, i - CONTEXT_LINES); k <= Math.min(all.length - 1, i + CONTEXT_LINES); k++) {+ keep[k] = true;+ }+ }+ // Nothing moved (an Edit whose strings are equal): say so with the text+ // itself rather than with an empty frame.+ if (!anyChange) return all.slice(0, CONTEXT_LINES * 2);++ const out: DiffLine[] = [];+ let skipped = 0;+ for (let i = 0; i < all.length; i++) {+ if (keep[i]) {+ if (skipped > 0) {+ out.push({ kind: "gap", text: String(skipped) });+ skipped = 0;+ }+ out.push(all[i]);+ } else {+ skipped++;+ }+ }+ // A trailing gap too, unlike a unified diff: on screen the last printed+ // line otherwise reads as the end of the file rather than as the end of+ // the part worth showing.+ if (skipped > 0) out.push({ kind: "gap", text: String(skipped) });+ return out;+}++function build(path: string, before: string, after: string, created = false): DiffFile {+ const all = created+ ? lines(after).map((text): DiffLine => ({ kind: "add", text }))+ : diffLines(before, after);+ const trimmed = trimContext(all);+ const shown = trimmed.slice(0, MAX_LINES);+ return {+ path,+ lines: shown,+ added: all.filter((l) => l.kind === "add").length,+ removed: all.filter((l) => l.kind === "del").length,+ created,+ truncated: Math.max(0, trimmed.length - shown.length),+ };+}++/**+ * Parse a Codex-style `apply_patch` payload.+ *+ * The patch arrives as ONE string carrying its own file headers, so the file+ * names come out of the text rather than out of a field. Both the+ * `*** Update File: x` envelope and a plain `--- a/x` / `+++ b/x` unified+ * header are read, because the two live side by side in the wild.+ */+export function parsePatchText(patch: string): DiffFile[] {+ const files: DiffFile[] = [];+ let path = "";+ let created = false;+ let acc: DiffLine[] = [];++ const flush = () => {+ if (!acc.length && !path) return;+ const trimmed = trimContext(acc);+ const shown = trimmed.slice(0, MAX_LINES);+ files.push({+ path,+ lines: shown,+ added: acc.filter((l) => l.kind === "add").length,+ removed: acc.filter((l) => l.kind === "del").length,+ created,+ truncated: Math.max(0, trimmed.length - shown.length),+ });+ acc = [];+ };++ for (const raw of patch.replace(/\r\n/g, "\n").split("\n")) {+ const envelope = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(raw);+ if (envelope) {+ flush();+ path = envelope[2].trim();+ created = envelope[1] === "Add";+ continue;+ }+ if (/^\*\*\* (Begin|End) Patch\s*$/.test(raw)) continue;+ const unified = /^\+\+\+ (?:b\/)?(.+)$/.exec(raw);+ if (unified) {+ // The "---" line came first and told us nothing new; the "+++" one+ // names the file as it will be, which is the name worth showing.+ if (acc.length) flush();+ path = unified[1].trim();+ continue;+ }+ if (/^--- /.test(raw) || /^(diff |index |new file|deleted file|similarity |rename )/.test(raw)) {+ continue;+ }+ if (/^@@/.test(raw)) {+ if (acc.length) acc.push({ kind: "gap", text: "" });+ continue;+ }+ if (raw.startsWith("+")) acc.push({ kind: "add", text: raw.slice(1) });+ else if (raw.startsWith("-")) acc.push({ kind: "del", text: raw.slice(1) });+ else if (raw.startsWith(" ")) acc.push({ kind: "ctx", text: raw.slice(1) });+ else if (raw.trim()) acc.push({ kind: "ctx", text: raw });+ }+ flush();+ return files.filter((f) => f.lines.length > 0);+}++/**+ * The diff a tool call describes, or `null` when it describes none.+ *+ * `null` is the honest answer for a call that edits nothing, and also for an+ * edit whose arguments did not survive the transport — a row falling back to+ * its plain summary is right, inventing an empty diff is not.+ */+export function toolDiff(name: string, input: unknown): DiffFile[] | null {+ const raw = (name ?? "").trim();+ if (!isDiffTool(raw)) return null;+ if (typeof input === "string") {+ const files = parsePatchText(input);+ return files.length ? files : null;+ }+ if (!input || typeof input !== "object" || Array.isArray(input)) return null;+ const obj = input as Record<string, unknown>;++ // Codex hands the whole patch as one string under one of several names.+ const patch = str(obj, "patch", "input", "diff", "content_patch");+ if (patch && /^\s*(\*\*\* |--- |diff --git|@@)/m.test(patch)) {+ const files = parsePatchText(patch);+ if (files.length) return files;+ }++ const path = str(obj, "file_path", "path", "notebook_path", "filename", "file") ?? "";++ // MultiEdit: several before/after pairs against one file, read in order.+ const edits = obj.edits;+ if (Array.isArray(edits) && edits.length) {+ const out: DiffFile[] = [];+ for (const entry of edits) {+ if (!entry || typeof entry !== "object") continue;+ const e = entry as Record<string, unknown>;+ const before = str(e, "old_string", "old_str", "old", "old_source");+ const after = str(e, "new_string", "new_str", "new", "new_source");+ if (before === null && after === null) continue;+ out.push(build(path, before ?? "", after ?? ""));+ }+ if (out.length) return out;+ }++ const before = str(obj, "old_string", "old_str", "old_source", "old_text");+ const after = str(obj, "new_string", "new_str", "new_source", "new_text");+ if (before !== null || after !== null) {+ // An Edit with an empty "before" is a file being started, not a change+ // with nothing on its left.+ const created = !before?.trim();+ return [build(path, before ?? "", after ?? "", created)];+ }++ // Write / create: the whole file arrives, and all of it is new.+ const content = str(obj, "content", "file_text", "text", "source");+ if (content !== null) return [build(path, "", content, true)];++ return null;+}++/** `+12 −3` for the row, or "" when the call added and removed nothing. */+export function diffStat(files: DiffFile[]): { added: number; removed: number } {+ return files.reduce(+ (acc, f) => ({ added: acc.added + f.added, removed: acc.removed + f.removed }),+ { added: 0, removed: 0 },+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.tsindex 25e5313f47..a0aa7f7c23 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts@@ -5,6 +5,7 @@ import {formatTokens,inputSummary,outputTokens,+ shortenPath,} from "@/components/agentchat/toolView";describe("agentToolView", () => {@@ -79,3 +80,34 @@ describe("token formatting", () => {expect(outputTokens({})).toBeNull();});});++/*+ * A path on a row.+ *+ * Every file in one workspace shares its first six or seven segments, so a+ * row printing the whole of an absolute path spends its width saying where+ * the project lives and runs out before saying which file (live check,+ * 2026-08-27).+ */+describe("shortenPath", () => {+ it("keeps the three segments that tell a row apart from its neighbours", () => {+ expect(+ shortenPath("C:\\Users\\Someone\\Desktop\\Project\\src\\brain\\healthcheck.py"),+ ).toBe("…/src/brain/healthcheck.py");+ expect(shortenPath("/home/someone/work/repo/src/app.ts")).toBe("…/repo/src/app.ts");+ });++ it("leaves a path that is already short exactly as it is", () => {+ expect(shortenPath("/etc/hosts")).toBe("/etc/hosts");+ expect(shortenPath("src/app.ts")).toBe("src/app.ts");+ });++ it("does not touch things that merely contain a slash", () => {+ expect(shortenPath("a/b or c/d — either way")).toBe("a/b or c/d — either way");+ expect(shortenPath("rg -n 'foo/bar' src")).toBe("rg -n 'foo/bar' src");+ });++ it("reaches the row through the summary, whichever way the agent spells it", () => {+ expect(inputSummary({ file_path: "C:\\a\\b\\c\\d\\e.ts" }, "edit")).toBe("…/c/d/e.ts");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.tsindex 5b7c6d97c0..87521a834e 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts@@ -117,12 +117,33 @@ export function inputSummary(input: unknown, family?: string): string {const keys = [...(family ? (SUMMARY_KEYS[family] ?? []) : []), ...GENERIC_SUMMARY_KEYS];for (const key of keys) {const v = obj[key];- if (typeof v === "string" && v.trim()) return firstLine(v);+ if (typeof v === "string" && v.trim()) return shortenPath(firstLine(v));}const first = Object.values(obj).find((v) => typeof v === "string" && v.trim());return typeof first === "string" ? firstLine(first) : "";}+/**+ * An absolute path, shortened to the part that differs between rows.+ *+ * Every file in a workspace shares its first six or seven segments, so a row+ * showing the whole of it spends its width saying where the project is and+ * runs out before saying which file (live check, 2026-08-27). The last three+ * segments are what a person reads anyway, and the leading ellipsis says+ * plainly that something was cut.+ *+ * Windows separators become forward slashes on the way: one shape for a path+ * beats two, and every agent in the column writes both.+ */+export function shortenPath(value: string): string {+ const flat = value.replace(/\\/g, "/");+ // Not a path: a sentence with a slash in it, a URL, a bare name.+ if (!/^([A-Za-z]:\/|\/|\.{1,2}\/)/.test(flat) || /\s{2,}/.test(flat)) return value;+ const parts = flat.split("/").filter(Boolean);+ if (parts.length <= 3) return flat;+ return `…/${parts.slice(-3).join("/")}`;+}+function firstLine(text: string): string {const line = text.trim().split(/\r?\n/, 1)[0] ?? "";return line.length > 200 ? `${line.slice(0, 199)}…` : line;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 81e3411595..8bc5c0a7c4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -650,6 +650,9 @@"tool_input": "Eingabe","tool_output": "Ausgabe","tool_error": "Fehler",+ "steps_count": "{count} Schritte",+ "diff_skipped": "{count} unveränderte Zeilen",+ "diff_truncated": "{count} weitere Zeilen nicht gezeigt","thinking_for": "Denkt seit {duration}","tokens": "Tokens","tokens_out": "Ausgabe-Tokens",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 2cf2affc92..5a8b4282c0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -650,6 +650,9 @@"tool_input": "Input","tool_output": "Output","tool_error": "Error",+ "steps_count": "{count} steps",+ "diff_skipped": "{count} unchanged lines",+ "diff_truncated": "{count} more lines not shown","thinking_for": "Thinking for {duration}","tokens": "tokens","tokens_out": "Output tokens",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 49fa7648c5..df88e6e674 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -650,6 +650,9 @@"tool_input": "Entrada","tool_output": "Salida","tool_error": "Error",+ "steps_count": "{count} pasos",+ "diff_skipped": "{count} líneas sin cambios",+ "diff_truncated": "{count} líneas más no mostradas","thinking_for": "Pensando desde hace {duration}","tokens": "tokens","tokens_out": "Tokens de salida",diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 4b0b2a5310..1ffae26d8a 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -476,6 +476,12 @@ label,--accent-foreground: 0 0% 100%;--destructive: 6 63% 46%; /* #C0392B — the light terminal's red */--destructive-foreground: 0 0% 100%;+ /* Added / removed code in a chat diff. The red is the destructive one, so+ a deleted line and a failed step speak with the same voice. */+ --diff-add: 145 55% 24%;+ --diff-add-bg: 145 50% 95%;+ --diff-del: 6 60% 40%;+ --diff-del-bg: 6 60% 96%;--border: 50 21% 89%; /* #E8E6DC */--input: 52 29% 95%;--ring: 38 100% 33%;@@ -573,6 +579,10 @@ label,--accent-foreground: 0 0% 4%;--destructive: 0 84% 60%;--destructive-foreground: 48 23% 95%;+ --diff-add: 145 55% 65%;+ --diff-add-bg: 145 40% 11%;+ --diff-del: 0 70% 72%;+ --diff-del-bg: 0 45% 12%;--border: 40 3% 23%; /* #3B3A38 */--input: 60 2% 21%;--ring: 50 100% 52%;@@ -3168,3 +3178,32 @@ label,background: hsl(var(--background));}}++/*+ * One line of a diff in the chat column.+ *+ * Classes rather than utilities because the PAIR of tokens is the thing being+ * applied: ink and ground belong together, and both are redefined per mode.+ * The ground is faint on purpose — the mark and the ink carry the meaning, and+ * a solid band per line turns a twenty-line change into a flag.+ */+@layer components {+ .diff-line-add {+ background-color: hsl(var(--diff-add-bg));+ color: hsl(var(--diff-add));+ }++ .diff-line-del {+ background-color: hsl(var(--diff-del-bg));+ color: hsl(var(--diff-del));+ }++ /* The same two inks with no ground, for the "+12 -3" on a row. */+ .diff-ink-add {+ color: hsl(var(--diff-add));+ }++ .diff-ink-del {+ color: hsl(var(--diff-del));+ }+}