Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5494: feat(transcript): render tool events as diffs, content and terminal output (#6134)

Larry Laida7451843be3
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index 17020185c0..d2924486fb 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
+import { readFileSync } from "node:fs";
import { cleanup, fireEvent, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ButtonHTMLAttributes, ReactNode } from "react";
@@ -439,4 +440,150 @@ describe("AgentTranscriptDialog", () => {
["[Agent] Missing timestamp", "[Error] Invalid timestamp"].join("\n\n"),
);
});
+ it("renders a file edit as a diff instead of escaped JSON strings", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const { container } = renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Edit",
+ input: {
+ file_path: "/repo/src/counter.rs",
+ old_string: "pub count: u32,",
+ new_string: "pub count: u32,\npub total: u64,",
+ },
+ },
+ ]);
+
+ // Changed lines read as diff rows. Text is asserted on the row, not on a
+ // leaf node: syntax highlighting splits a line across `hljs-*` spans.
+ const rowText = (selector: string) =>
+ Array.from(container.querySelectorAll(selector)).map((el) => el.textContent?.trim());
+ // The first line is unchanged, so it is context; only the second is added.
+ expect(rowText(".bg-success\\/10")).toEqual(["+ pub total: u64,"]);
+ expect(rowText(".bg-destructive\\/10")).toEqual([]);
+ expect(container.querySelector("pre")?.textContent).toContain("pub count: u32,");
+ // ...and the raw JSON keys are gone from the surface.
+ expect(screen.queryByText(/"new_string"/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/\\n/)).not.toBeInTheDocument();
+ });
+
+ it("highlights diff rows using the grammar for the file extension", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const { container } = renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Edit",
+ input: {
+ file_path: "/repo/src/lib.rs",
+ old_string: "let a = 1;",
+ new_string: "let b = 2;",
+ },
+ },
+ ]);
+
+ // `let` is a Rust keyword, so the highlighter must have marked it up.
+ expect(container.querySelector(".hljs-keyword")?.textContent).toBe("let");
+ });
+
+ it("carries the scope class the hljs palette is defined under", () => {
+ // The palette lives in editor/styles/code.css, scoped to the editor surface
+ // and this class. Without it the spans render but stay uncoloured.
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const { container } = renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Edit",
+ input: { file_path: "/repo/src/lib.rs", old_string: "let a = 1;", new_string: "let b = 2;" },
+ },
+ ]);
+
+ expect(container.querySelector("pre")?.className).toContain("transcript-code");
+ const css = readFileSync("editor/styles/code.css", "utf8");
+ expect(css).toContain(".transcript-code");
+ });
+
+ it("leaves an unknown extension unhighlighted rather than guessing", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const { container } = renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Edit",
+ input: { file_path: "/repo/NOTES", old_string: "let a = 1;", new_string: "let b = 2;" },
+ },
+ ]);
+
+ expect(container.querySelector(".hljs-keyword")).toBeNull();
+ expect(container.textContent).toContain("let b = 2;");
+ });
+
+ it("unwraps a JSON-encoded tool result so it reads as terminal output", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ renderDialog([
+ {
+ seq: 1,
+ type: "tool_result",
+ tool: "Bash",
+ output: '"total 0\\ndrwxr-xr-x 2 user staff"',
+ },
+ ]);
+
+ expect(
+ screen.getByText("total 0\ndrwxr-xr-x 2 user staff", {
+ selector: "pre",
+ // Keep the newline and column spacing the unwrap is meant to restore.
+ normalizer: (text) => text,
+ }),
+ ).toBeInTheDocument();
+ });
+ it("shows a whole-file write as plain content with a line count", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const { container } = renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Write",
+ input: { file_path: "/f.rs", content: "alpha\nbeta" },
+ },
+ ]);
+
+ expect(screen.getByText("+2")).toBeInTheDocument();
+ // Plain content: no per-line + gutter and no diff tinting.
+ const pre = container.querySelector("pre");
+ expect(pre?.textContent).toBe("alpha\nbeta");
+ expect(container.querySelector(".bg-success\\/10")).toBeNull();
+ });
+
+ it("clamps a long body behind the show-all affordance", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ const content = Array.from({ length: 40 }, (_, i) => `line ${i}`).join("\n");
+ const { container } = renderDialog([
+ { seq: 1, type: "tool_use", tool: "Write", input: { file_path: "/f.rs", content } },
+ ]);
+
+ const pre = container.querySelector("pre");
+ expect(pre?.className).toContain("max-h-52");
+ expect(pre?.className).toContain("overflow-hidden");
+ expect(screen.getByRole("button", { name: "Show all" })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+ expect(container.querySelector("pre")?.className).not.toContain("max-h-52");
+ });
+
+ it("does not clamp a short diff", () => {
+ useTranscriptViewStore.setState({ density: "expanded" });
+ renderDialog([
+ {
+ seq: 1,
+ type: "tool_use",
+ tool: "Edit",
+ input: { file_path: "/f.rs", old_string: "a", new_string: "b" },
+ },
+ ]);
+
+ expect(screen.queryByRole("button", { name: "Show all" })).not.toBeInTheDocument();
+ });
});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 6346340370..147f697c34 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -58,13 +58,17 @@ import type { TimelineItem } from "./build-timeline";
import {
traceEventCopyText,
traceEventDefaultExpanded,
+ traceEventDetail,
traceEventHasDetail,
traceEventKind,
traceEventLabel,
traceEventSummary,
traceEventSummaryIsMono,
} from "./trace-event-presenter";
+import type { TraceDiffLine } from "./trace-event-presenter";
+import { highlightBlock, highlightToLines, languageForPath } from "./diff-highlight";
import { useT } from "../../i18n";
+import "../../editor/styles/code.css";
import "./task-transcript.css";
interface AgentTranscriptDialogProps {
@@ -1105,6 +1109,7 @@ const TranscriptEventRow = ({
);
const hasDetail = traceEventHasDetail(item);
+ const detail = useMemo(() => traceEventDetail(item), [item]);
// Prose kinds swap the one-line summary for the full body in place when
// expanded (no box). Tool kinds keep the summary line and reveal the
// params/output surface below it.
@@ -1214,17 +1219,19 @@ const TranscriptEventRow = ({
<CollapsibleContent>
<div className="px-4 pb-3">
<div className="ml-[72px] rounded-md bg-muted/40">
- <ToolDetailSurface
- text={
- kind === "tool_use"
- ? redactSecrets(JSON.stringify(item.input ?? {}, null, 2))
- : item.output
- ? item.output.length > 4000
- ? redactSecrets(item.output.slice(0, 4000)) + "\n... (truncated)"
- : redactSecrets(item.output)
- : ""
- }
- />
+ {detail.kind === "diff" ? (
+ <DiffDetailSurface lines={detail.lines} path={detail.path} />
+ ) : detail.kind === "file" ? (
+ <FileWriteSurface text={detail.text} lineCount={detail.lineCount} path={detail.path} />
+ ) : (
+ <ToolDetailSurface
+ text={
+ detail.text.length > 4000
+ ? redactSecrets(detail.text.slice(0, 4000)) + "\n... (truncated)"
+ : redactSecrets(detail.text)
+ }
+ />
+ )}
</div>
</div>
</CollapsibleContent>
@@ -1240,27 +1247,182 @@ const TranscriptEventRow = ({
* Long content fades out behind a "show all" affordance instead of trapping a
* nested scrollbar inside the virtualized list.
*/
-function ToolDetailSurface({ text }: { text: string }) {
+type HighlightedSides = Record<"add" | "remove" | "context", string[] | null> | null;
+
+/**
+ * Diff rows. Highlighting is looked up per side, since each side was
+ * highlighted as its own block; a side that failed to highlight falls back to
+ * plain text for that side only.
+ */
+function renderDiffRows(lines: TraceDiffLine[], highlighted: HighlightedSides) {
+ const cursor: Record<"add" | "remove" | "context", number> = { add: 0, remove: 0, context: 0 };
+
+ return lines.map((line, index) => {
+ if (line.kind === "gap") {
+ return (
+ // Transcript events are immutable once persisted, so index is stable.
+ <div key={index} className="select-none text-muted-foreground/40" aria-hidden>
+ {" ⋯"}
+ </div>
+ );
+ }
+
+ const kind = line.kind;
+ const html = highlighted?.[kind]?.[cursor[kind]];
+ cursor[kind] += 1;
+
+ return (
+ <div
+ key={index}
+ className={cn(
+ "-mx-1 px-1",
+ kind === "add" && "bg-success/10",
+ kind === "remove" && "bg-destructive/10",
+ // Only tint the gutter for changed rows; the code itself keeps its
+ // syntax colours so a diff reads like the file it came from.
+ !html && kind === "add" && "text-success",
+ !html && kind === "remove" && "text-destructive",
+ !html && kind === "context" && "text-muted-foreground",
+ )}
+ >
+ <span
+ aria-hidden
+ className={cn(
+ "select-none opacity-60",
+ kind === "add" && "text-success",
+ kind === "remove" && "text-destructive",
+ )}
+ >
+ {kind === "add" ? "+" : kind === "remove" ? "-" : " "}
+ </span>{" "}
+ {html === undefined ? (
+ redactSecrets(line.text)
+ ) : (
+ // lowlight output only: text is escaped by the hast serializer and
+ // the sole elements are its own `hljs-*` spans.
+ <span className="hljs" dangerouslySetInnerHTML={{ __html: html }} />
+ )}
+ </div>
+ );
+ });
+}
+
+/**
+ * A whole-file write has no before side, so it reads as plain content with a
+ * line count rather than as an all-additions diff — the `+` gutter would carry
+ * no information here.
+ */
+function FileWriteSurface({
+ text,
+ lineCount,
+ path,
+}: {
+ text: string;
+ lineCount: number;
+ path: string;
+}) {
+ return (
+ <div>
+ <div className="px-3 pt-2 font-mono text-[10px] text-success">+{lineCount}</div>
+ <ToolDetailSurface text={redactSecrets(text)} language={languageForPath(path)} />
+ </div>
+ );
+}
+
+/**
+ * A file change reads as a diff rather than two escaped string literals. Same
+ * fade/"show all" shell as the text surface so both bodies behave alike inside
+ * the virtualized list.
+ */
+function DiffDetailSurface({ lines, path }: { lines: TraceDiffLine[]; path: string }) {
+ const { t } = useT("agents");
+ const [showAll, setShowAll] = useState(false);
+ const isLong = lines.length > 14;
+ const added = lines.filter((l) => l.kind === "add").length;
+ const removed = lines.filter((l) => l.kind === "remove").length;
+
+ // Each side is highlighted as one block so multi-line strings and comments
+ // keep their grammar, then split back per line to sit in the diff gutter.
+ // Runs only when the row is expanded, which is where this component mounts.
+ const highlighted = useMemo(() => {
+ const language = languageForPath(path);
+ if (!language) return null;
+ const sides: Record<"add" | "remove" | "context", string[] | null> = {
+ add: null,
+ remove: null,
+ context: null,
+ };
+ for (const kind of ["add", "remove", "context"] as const) {
+ const side = lines.filter((l) => l.kind === kind);
+ if (side.length > 0) {
+ sides[kind] = highlightToLines(side.map((l) => l.text).join("\n"), language);
+ }
+ }
+ return sides;
+ }, [lines, path]);
+
+ return (
+ <div className="relative">
+ <div className="flex items-center gap-2 px-3 pt-2 font-mono text-[10px] text-muted-foreground/70">
+ {added > 0 && <span className="text-success">+{added}</span>}
+ {removed > 0 && <span className="text-destructive">-{removed}</span>}
+ </div>
+ <pre
+ className={cn(
+ "transcript-code px-3 pb-3 pt-1 font-mono text-[11px] whitespace-pre-wrap break-all",
+ isLong && !showAll && "max-h-52 overflow-hidden",
+ )}
+ >
+ {renderDiffRows(lines, highlighted)}
+ </pre>
+ {isLong && !showAll && (
+ <div className="absolute inset-x-0 bottom-0 flex h-12 items-end justify-center rounded-b-md bg-gradient-to-b from-transparent to-background">
+ <button
+ type="button"
+ onClick={() => setShowAll(true)}
+ // Opaque: the gradient alone does not clear the clipped line, so a
+ // transparent label lands on top of it and both become unreadable.
+ className="mb-1.5 rounded border bg-background px-2 py-0.5 text-[11px] text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
+ >
+ {t(($) => $.transcript.show_all)}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ToolDetailSurface({ text, language }: { text: string; language?: string }) {
const { t } = useT("agents");
const [showAll, setShowAll] = useState(false);
const isLong = text.length > 1600 || text.split("\n").length > 14;
+ // Only file bodies carry a language; command output and JSON stay plain.
+ const html = useMemo(() => (language ? highlightBlock(text, language) : null), [text, language]);
return (
<div className="relative">
<pre
className={cn(
- "p-3 font-mono text-[11px] text-muted-foreground whitespace-pre-wrap break-all",
+ "transcript-code p-3 font-mono text-[11px] text-muted-foreground whitespace-pre-wrap break-all",
isLong && !showAll && "max-h-52 overflow-hidden",
)}
>
- {text}
+ {html === null ? (
+ text
+ ) : (
+ // lowlight output only: the hast serializer escapes text and the sole
+ // elements are its own `hljs-*` spans.
+ <code className="hljs" dangerouslySetInnerHTML={{ __html: html }} />
+ )}
</pre>
{isLong && !showAll && (
<div className="absolute inset-x-0 bottom-0 flex h-12 items-end justify-center rounded-b-md bg-gradient-to-b from-transparent to-background">
<button
type="button"
onClick={() => setShowAll(true)}
- className="mb-1.5 rounded px-2 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ // Opaque: the gradient alone does not clear the clipped line, so a
+ // transparent label lands on top of it and both become unreadable.
+ className="mb-1.5 rounded border bg-background px-2 py-0.5 text-[11px] text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
>
{t(($) => $.transcript.show_all)}
</button>
diff --git a/packages/views/common/task-transcript/diff-highlight.ts b/packages/views/common/task-transcript/diff-highlight.ts
new file mode 100644
index 0000000000..deb8721a1f
--- /dev/null
+++ b/packages/views/common/task-transcript/diff-highlight.ts
@@ -0,0 +1,134 @@
+// Syntax highlighting for transcript diffs. Highlighting runs over a whole
+// side at once — never line by line — so a multi-line string, comment or
+// template literal is coloured as the one token it is. The highlighted tree is
+// then split at newlines, re-opening the enclosing spans on each line, which is
+// what lets a per-line diff gutter coexist with block-accurate grammar.
+//
+// Same engine (`lowlight`) and same `.hljs-*` class contract as the rich
+// content code block, so a Rust file looks the same in a transcript as it does
+// in a comment.
+
+import { toHtml } from "hast-util-to-html";
+import type { Element, ElementContent, Properties, Root, RootContent } from "hast";
+import { highlightCode } from "../../editor/syntax-highlight";
+
+/**
+ * File extension to a lowlight grammar name. Unlisted extensions resolve to
+ * plaintext inside `highlightCode`, so this map only needs the languages worth
+ * naming — a miss degrades to unhighlighted text, never to an error.
+ */
+const LANGUAGE_BY_EXTENSION: Record<string, string> = {
+ bash: "bash",
+ c: "c",
+ cc: "cpp",
+ cjs: "javascript",
+ cpp: "cpp",
+ cs: "csharp",
+ css: "css",
+ go: "go",
+ h: "c",
+ hpp: "cpp",
+ htm: "xml",
+ html: "xml",
+ java: "java",
+ js: "javascript",
+ json: "json",
+ jsx: "javascript",
+ kt: "kotlin",
+ lua: "lua",
+ md: "markdown",
+ mjs: "javascript",
+ php: "php",
+ pl: "perl",
+ py: "python",
+ r: "r",
+ rb: "ruby",
+ rs: "rust",
+ scala: "scala",
+ scss: "scss",
+ sh: "bash",
+ sql: "sql",
+ swift: "swift",
+ toml: "ini",
+ ts: "typescript",
+ tsx: "typescript",
+ xml: "xml",
+ yaml: "yaml",
+ yml: "yaml",
+ zsh: "bash",
+};
+
+/** Grammar for a path, by extension. Undefined means "highlight as plaintext". */
+export function languageForPath(path: string): string | undefined {
+ const base = path.split("/").pop() ?? path;
+ const dot = base.lastIndexOf(".");
+ if (dot <= 0) return undefined;
+ return LANGUAGE_BY_EXTENSION[base.slice(dot + 1).toLowerCase()];
+}
+
+/** The open-element chain a piece of text sits inside, innermost last. */
+type Ancestors = ReadonlyArray<Pick<Element, "tagName" | "properties">>;
+
+function wrap(text: string, ancestors: Ancestors): ElementContent {
+ let node: ElementContent = { type: "text", value: text };
+ for (let i = ancestors.length - 1; i >= 0; i--) {
+ const ancestor = ancestors[i];
+ if (!ancestor) continue;
+ node = {
+ type: "element",
+ tagName: ancestor.tagName,
+ properties: (ancestor.properties ?? {}) as Properties,
+ children: [node],
+ };
+ }
+ return node;
+}
+
+function collect(
+ nodes: ReadonlyArray<RootContent>,
+ ancestors: Ancestors,
+ lines: ElementContent[][],
+): void {
+ for (const node of nodes) {
+ if (node.type === "text") {
+ const parts = node.value.split("\n");
+ for (let i = 0; i < parts.length; i++) {
+ if (i > 0) lines.push([]);
+ const part = parts[i];
+ if (part === undefined || part.length === 0) continue;
+ lines[lines.length - 1]?.push(wrap(part, ancestors));
+ }
+ continue;
+ }
+ if (node.type === "element") {
+ collect(node.children, [...ancestors, { tagName: node.tagName, properties: node.properties }], lines);
+ }
+ // Comments/doctypes cannot appear in a lowlight result; ignoring them keeps
+ // the walker total without inventing output for impossible input.
+ }
+}
+
+/**
+ * Highlight `text` as one block and return one HTML string per line. Falls back
+ * to `null` so callers can render the original text unhighlighted rather than
+ * showing nothing when a grammar throws.
+ */
+/** Highlight `text` as one block. `null` when the grammar throws. */
+export function highlightBlock(text: string, language: string | undefined): string | null {
+ try {
+ return toHtml(highlightCode(text, language) as Root);
+ } catch {
+ return null;
+ }
+}
+
+export function highlightToLines(text: string, language: string | undefined): string[] | null {
+ try {
+ const tree = highlightCode(text, language) as Root;
+ const lines: ElementContent[][] = [[]];
+ collect(tree.children, [], lines);
+ return lines.map((children) => toHtml({ type: "root", children }));
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/views/common/task-transcript/trace-event-presenter.test.ts b/packages/views/common/task-transcript/trace-event-presenter.test.ts
index 027fa4e265..c491e3efa8 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.test.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.test.ts
@@ -1,13 +1,16 @@
import { describe, expect, it } from "vitest";
import {
+ collapseDiffContext,
stripShellWrapper,
traceEventCopyText,
traceEventDefaultExpanded,
+ traceEventDetail,
traceEventHasDetail,
traceEventKind,
traceEventLabel,
traceEventSummary,
traceToolArgSummary,
+ unwrapToolOutput,
} from "./trace-event-presenter";
describe("traceEventKind / traceEventLabel", () => {
@@ -69,6 +72,16 @@ describe("traceEventSummary", () => {
);
});
+ it("unwraps a JSON-encoded result so the collapsed row shows no transport escaping", () => {
+ expect(
+ traceEventSummary({
+ type: "tool_result",
+ tool: "Bash",
+ output: '"target/release/deps/acceptance\\n 0 page faults\\n 0 swaps"',
+ }),
+ ).toBe("target/release/deps/acceptance 0 page faults 0 swaps");
+ });
+
it("retains unknown events instead of dropping them", () => {
expect(traceEventSummary({ type: "custom", content: "payload" })).toBe("payload");
});
@@ -88,6 +101,12 @@ describe("traceEventCopyText", () => {
);
});
+ it("copies a result as the terminal output it was, not its transport encoding", () => {
+ expect(
+ traceEventCopyText({ type: "tool_result", tool: "Bash", output: '"line 1\\nline 2"' }),
+ ).toBe("[Bash] line 1\nline 2");
+ });
+
it("emits a bare label when the event has no body", () => {
expect(traceEventCopyText({ type: "tool_use", tool: "Bash" })).toBe("[Bash]");
});
@@ -116,3 +135,156 @@ describe("traceEventDefaultExpanded", () => {
expect(traceEventHasDetail({ type: "tool_use", input: {} })).toBe(false);
});
});
+
+describe("unwrapToolOutput", () => {
+ it("decodes the one JSON string layer a result arrives wrapped in", () => {
+ expect(unwrapToolOutput('"line one\\nline two"')).toBe("line one\nline two");
+ expect(unwrapToolOutput('"{\\n \\"id\\": 1\\n}"')).toBe('{\n "id": 1\n}');
+ });
+
+ it("leaves anything that is not a wrapped string untouched", () => {
+ expect(unwrapToolOutput("plain text")).toBe("plain text");
+ expect(unwrapToolOutput('{"id": 1}')).toBe('{"id": 1}');
+ // A quoted-looking body that is not valid JSON must survive verbatim.
+ expect(unwrapToolOutput('"unterminated')).toBe('"unterminated');
+ expect(unwrapToolOutput("")).toBe("");
+ });
+
+ it("decodes only one layer, so a JSON document stays a document", () => {
+ expect(unwrapToolOutput('"[1, 2]"')).toBe("[1, 2]");
+ });
+});
+
+describe("traceEventDetail", () => {
+ it("renders a replacement edit as a diff, keyed off input shape not tool name", () => {
+ // Provider-native names differ (Edit, patch_apply, str_replace...), so the
+ // shape of the input is what identifies an edit.
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: {
+ file_path: "/repo/src/counter.rs",
+ old_string: "let a = 1;\nlet b = 2;",
+ new_string: "let a = 1;\nlet b = 3;\nlet c = 4;",
+ },
+ });
+ expect(detail.kind).toBe("diff");
+ if (detail.kind !== "diff") return;
+ expect(detail.path).toBe("/repo/src/counter.rs");
+ expect(detail.lines).toEqual([
+ { kind: "context", text: "let a = 1;" },
+ { kind: "remove", text: "let b = 2;" },
+ { kind: "add", text: "let b = 3;" },
+ { kind: "add", text: "let c = 4;" },
+ ]);
+ });
+
+ it("renders a whole-file write as plain content, not an all-additions diff", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "Write",
+ input: { file_path: "/repo/new.txt", content: "alpha\nbeta" },
+ });
+ expect(detail).toEqual({
+ kind: "file",
+ path: "/repo/new.txt",
+ text: "alpha\nbeta",
+ lineCount: 2,
+ });
+ });
+
+ it("still diffs an insertion whose old side is empty", () => {
+ // `content` marks a whole-file write; an empty old_string is an insertion
+ // into a file that already exists, so the diff gutter still carries meaning.
+ const detail = traceEventDetail({
+ type: "tool_use",
+ input: { file_path: "/f", old_string: "", new_string: "added" },
+ });
+ expect(detail.kind).toBe("diff");
+ if (detail.kind !== "diff") return;
+ expect(detail.lines).toEqual([{ kind: "add", text: "added" }]);
+ });
+
+ it("keeps a deletion visible when new_string is empty", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ input: { file_path: "/f", old_string: "gone", new_string: "" },
+ });
+ expect(detail.kind).toBe("diff");
+ if (detail.kind !== "diff") return;
+ expect(detail.lines).toEqual([{ kind: "remove", text: "gone" }]);
+ });
+
+ it("falls back to pretty JSON for a tool call that is not an edit", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "Bash",
+ input: { command: "ls -la" },
+ });
+ expect(detail.kind).toBe("text");
+ if (detail.kind !== "text") return;
+ expect(detail.text).toBe('{\n "command": "ls -la"\n}');
+ });
+
+ it("unwraps a tool result so it reads as the terminal output it was", () => {
+ const detail = traceEventDetail({
+ type: "tool_result",
+ tool: "Bash",
+ output: '"total 0\\ndrwxr-xr-x 2 user staff"',
+ });
+ expect(detail).toEqual({ kind: "text", text: "total 0\ndrwxr-xr-x 2 user staff" });
+ });
+
+ it("uses content for prose events and never throws on an empty event", () => {
+ expect(traceEventDetail({ type: "text", content: "hello" })).toEqual({
+ kind: "text",
+ text: "hello",
+ });
+ expect(traceEventDetail({ type: "tool_use" })).toEqual({ kind: "text", text: "" });
+ });
+});
+
+describe("collapseDiffContext", () => {
+ const ctx = (n: number) => Array.from({ length: n }, (_, i) => ctxLine(`c${i}`));
+ function ctxLine(text: string) {
+ return { kind: "context" as const, text };
+ }
+
+ it("collapses a long unchanged stretch between two changes", () => {
+ const lines = [
+ { kind: "remove" as const, text: "old" },
+ ...ctx(10),
+ { kind: "add" as const, text: "new" },
+ ];
+ const out = collapseDiffContext(lines, 2);
+ expect(out.map((l) => l.kind)).toEqual([
+ "remove",
+ "context",
+ "context",
+ "gap",
+ "context",
+ "context",
+ "add",
+ ]);
+ expect(out[3]).toEqual({ kind: "gap", text: "", hidden: 6 });
+ });
+
+ it("drops leading and trailing context entirely — nothing faces a change there", () => {
+ const out = collapseDiffContext([...ctx(8), { kind: "add", text: "x" }, ...ctx(8)], 2);
+ expect(out.map((l) => l.kind)).toEqual(["gap", "context", "context", "add", "context", "context", "gap"]);
+ expect(out[0]?.hidden).toBe(6);
+ });
+
+ it("leaves a run alone when collapsing would not save a line", () => {
+ const lines = [{ kind: "remove" as const, text: "a" }, ...ctx(4), { kind: "add" as const, text: "b" }];
+ expect(collapseDiffContext(lines, 2)).toEqual(lines);
+ });
+
+ it("is a no-op for a diff with no context at all", () => {
+ const lines = [
+ { kind: "remove" as const, text: "a" },
+ { kind: "add" as const, text: "b" },
+ ];
+ expect(collapseDiffContext(lines)).toEqual(lines);
+ });
+});
diff --git a/packages/views/common/task-transcript/trace-event-presenter.ts b/packages/views/common/task-transcript/trace-event-presenter.ts
index 6ccddda69d..42da3be608 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.ts
@@ -138,7 +138,9 @@ export function traceEventSummary(event: TraceEvent): string {
case "tool_use":
return traceToolArgSummary(event.input);
case "tool_result":
- return clip(collapseWhitespace(event.output), 200);
+ // Unwrap first: the collapsed row is the one people read without
+ // clicking, so it must not show transport escaping.
+ return clip(collapseWhitespace(unwrapToolOutput(event.output ?? "")), 200);
default:
return firstLine(event.content ?? event.output);
}
@@ -158,7 +160,9 @@ export function traceEventCopyText(event: TraceEvent): string {
body = event.input ? JSON.stringify(event.input, null, 2) : "";
break;
case "tool_result":
- body = event.output ?? "";
+ // Match what the row displays, so copied evidence reads like the
+ // terminal output rather than its transport encoding.
+ body = unwrapToolOutput(event.output ?? "");
break;
default:
body = event.content ?? "";
@@ -168,6 +172,204 @@ export function traceEventCopyText(event: TraceEvent): string {
return body ? `${timestamp}[${label}] ${body}` : `${timestamp}[${label}]`;
}
+/**
+ * Tool output is persisted JSON-encoded, so a result arrives as a quoted string
+ * whose newlines are escaped. Decode exactly one layer so it reads as the
+ * terminal output it was. Anything that is not a wrapped string — a bare JSON
+ * document, plain prose, a truncated body — is returned untouched.
+ */
+export function unwrapToolOutput(raw: string): string {
+ const trimmed = raw.trim();
+ if (trimmed.length < 2 || !trimmed.startsWith('"') || !trimmed.endsWith('"')) return raw;
+ try {
+ const decoded: unknown = JSON.parse(trimmed);
+ return typeof decoded === "string" ? decoded : raw;
+ } catch {
+ return raw;
+ }
+}
+
+export type TraceDiffLineKind = "add" | "remove" | "context" | "gap";
+
+export interface TraceDiffLine {
+ kind: TraceDiffLineKind;
+ text: string;
+ /** Number of context lines a `gap` stands in for. Absent on other kinds. */
+ hidden?: number;
+}
+
+/**
+ * Expanded-row body. A replacement reads as a diff; a whole-file write reads as
+ * plain content, because nothing was compared — marking all of it `+` adds
+ * noise, not information. Everything else is text.
+ */
+export type TraceEventDetail =
+ | { kind: "diff"; path: string; lines: TraceDiffLine[] }
+ | { kind: "file"; path: string; text: string; lineCount: number }
+ | { kind: "text"; text: string };
+
+/** An empty body is zero lines, not one blank line — a pure deletion has no `+`. */
+function toLines(value: string): string[] {
+ return value.length === 0 ? [] : value.split("\n");
+}
+
+// Above this product the LCS table costs more than the readability is worth, so
+// the change degrades to a plain replacement block instead of a minimal diff.
+const MAX_DIFF_CELLS = 250_000;
+
+/** Minimal line diff. Removals precede additions inside a change block. */
+export function diffTraceLines(before: string[], after: string[]): TraceDiffLine[] {
+ const n = before.length;
+ const m = after.length;
+ const out: TraceDiffLine[] = [];
+
+ if (n * m > MAX_DIFF_CELLS) {
+ for (const text of before) out.push({ kind: "remove", text });
+ for (const text of after) out.push({ kind: "add", text });
+ return out;
+ }
+
+ // Flat (n+1) x (m+1) table: lcs[i][j] is the longest common subsequence of
+ // before[i:] and after[j:]. Typed-array cells stay `number` under
+ // noUncheckedIndexedAccess, and one allocation beats n+1 of them.
+ const width = m + 1;
+ const lcs = new Int32Array((n + 1) * width);
+ const at = (i: number, j: number): number => lcs[i * width + j] ?? 0;
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ lcs[i * width + j] =
+ before[i] === after[j] ? at(i + 1, j + 1) + 1 : Math.max(at(i + 1, j), at(i, j + 1));
+ }
+ }
+
+ let i = 0;
+ let j = 0;
+ while (i < n && j < m) {
+ const beforeLine = before[i] ?? "";
+ const afterLine = after[j] ?? "";
+ if (beforeLine === afterLine) {
+ out.push({ kind: "context", text: beforeLine });
+ i++;
+ j++;
+ } else if (at(i + 1, j) >= at(i, j + 1)) {
+ out.push({ kind: "remove", text: beforeLine });
+ i++;
+ } else {
+ out.push({ kind: "add", text: afterLine });
+ j++;
+ }
+ }
+ while (i < n) out.push({ kind: "remove", text: before[i++] ?? "" });
+ while (j < m) out.push({ kind: "add", text: after[j++] ?? "" });
+ return out;
+}
+
+/** Context lines kept either side of a change before a run is collapsed. */
+const DIFF_CONTEXT_LINES = 3;
+
+/**
+ * Collapse long unchanged stretches into a single `gap` row. A replacement can
+ * carry a large `old_string` for a one-line change; without this the change is
+ * buried in context that never moved. Runs short enough that collapsing would
+ * not save a line are left alone.
+ */
+export function collapseDiffContext(
+ lines: readonly TraceDiffLine[],
+ contextLines: number = DIFF_CONTEXT_LINES,
+): TraceDiffLine[] {
+ const out: TraceDiffLine[] = [];
+ let index = 0;
+ while (index < lines.length) {
+ const line = lines[index];
+ if (line === undefined) break;
+ if (line.kind !== "context") {
+ out.push(line);
+ index++;
+ continue;
+ }
+
+ let end = index;
+ while (end < lines.length && lines[end]?.kind === "context") end++;
+ const run = lines.slice(index, end);
+ // A leading/trailing run only needs context on the side facing a change.
+ const head = index === 0 ? 0 : contextLines;
+ const tail = end === lines.length ? 0 : contextLines;
+
+ if (run.length <= head + tail + 1) {
+ out.push(...run);
+ } else {
+ out.push(...run.slice(0, head));
+ out.push({ kind: "gap", text: "", hidden: run.length - head - tail });
+ out.push(...run.slice(run.length - tail));
+ }
+ index = end;
+ }
+ return out;
+}
+
+/**
+ * A file mutation is identified by the *shape* of its input, never by tool name:
+ * providers call this Edit, patch_apply, str_replace, write_file… and the
+ * presenter's contract is to keep provider-native names verbatim.
+ */
+type FileMutation =
+ | { mode: "replace"; path: string; before: string[]; after: string[] }
+ | { mode: "write"; path: string; content: string };
+
+function readFileMutation(input: Record<string, unknown>): FileMutation | null {
+ const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
+ const path = str(input.file_path) ?? str(input.path);
+ if (path === null) return null;
+
+ const oldString = str(input.old_string);
+ const newString = str(input.new_string);
+ if (oldString !== null && newString !== null) {
+ return { mode: "replace", path, before: toLines(oldString), after: toLines(newString) };
+ }
+
+ // Keyed on `content`, not on "the before side is empty": an edit whose
+ // old_string is empty is an insertion into an existing file, which still
+ // reads best as a diff.
+ const content = str(input.content);
+ if (content !== null) return { mode: "write", path, content };
+
+ return null;
+}
+
+/**
+ * Structured body for the expanded row. Edits become a diff so a reviewer sees
+ * what changed rather than two escaped string literals; results are unwrapped;
+ * every other tool call falls back to pretty JSON.
+ */
+export function traceEventDetail(event: TraceEvent): TraceEventDetail {
+ switch (traceEventKind(event)) {
+ case "tool_use": {
+ if (!event.input) return { kind: "text", text: "" };
+ const mutation = readFileMutation(event.input);
+ if (mutation?.mode === "replace") {
+ return {
+ kind: "diff",
+ path: mutation.path,
+ lines: collapseDiffContext(diffTraceLines(mutation.before, mutation.after)),
+ };
+ }
+ if (mutation?.mode === "write") {
+ return {
+ kind: "file",
+ path: mutation.path,
+ text: mutation.content,
+ lineCount: toLines(mutation.content).length,
+ };
+ }
+ return { kind: "text", text: JSON.stringify(event.input, null, 2) };
+ }
+ case "tool_result":
+ return { kind: "text", text: unwrapToolOutput(event.output ?? "") };
+ default:
+ return { kind: "text", text: event.content ?? "" };
+ }
+}
+
export function traceEventHasDetail(event: TraceEvent): boolean {
switch (traceEventKind(event)) {
case "tool_use":
diff --git a/packages/views/editor/styles/code.css b/packages/views/editor/styles/code.css
index 57b936d14a..41ef4af66c 100644
--- a/packages/views/editor/styles/code.css
+++ b/packages/views/editor/styles/code.css
@@ -52,67 +52,69 @@ pre.rich-text-editor code {
line-height: 1.6;
}
-/* Syntax highlighting — lowlight (hljs) */
-.rich-text-editor .hljs-keyword,
-.rich-text-editor .hljs-selector-tag,
-.rich-text-editor .hljs-built_in { color: oklch(0.55 0.16 255); }
+/* Syntax highlighting — lowlight (hljs). Scoped to the editor surface and to
+ the task transcript, which highlights file bodies with the same engine so a
+ file reads identically in a comment and in an execution trace. */
+:is(.rich-text-editor, .transcript-code) .hljs-keyword,
+:is(.rich-text-editor, .transcript-code) .hljs-selector-tag,
+:is(.rich-text-editor, .transcript-code) .hljs-built_in { color: oklch(0.55 0.16 255); }
-.rich-text-editor .hljs-string,
-.rich-text-editor .hljs-addition { color: oklch(0.55 0.14 155); }
+:is(.rich-text-editor, .transcript-code) .hljs-string,
+:is(.rich-text-editor, .transcript-code) .hljs-addition { color: oklch(0.55 0.14 155); }
-.rich-text-editor .hljs-comment,
-.rich-text-editor .hljs-quote { color: var(--muted-foreground); font-style: italic; }
+:is(.rich-text-editor, .transcript-code) .hljs-comment,
+:is(.rich-text-editor, .transcript-code) .hljs-quote { color: var(--muted-foreground); font-style: italic; }
-.rich-text-editor .hljs-number,
-.rich-text-editor .hljs-literal { color: oklch(0.58 0.16 30); }
+:is(.rich-text-editor, .transcript-code) .hljs-number,
+:is(.rich-text-editor, .transcript-code) .hljs-literal { color: oklch(0.58 0.16 30); }
-.rich-text-editor .hljs-title,
-.rich-text-editor .hljs-section,
-.rich-text-editor .hljs-title\.function_ { color: oklch(0.55 0.14 280); }
+:is(.rich-text-editor, .transcript-code) .hljs-title,
+:is(.rich-text-editor, .transcript-code) .hljs-section,
+:is(.rich-text-editor, .transcript-code) .hljs-title\.function_ { color: oklch(0.55 0.14 280); }
-.rich-text-editor .hljs-attr,
-.rich-text-editor .hljs-attribute { color: oklch(0.58 0.12 60); }
+:is(.rich-text-editor, .transcript-code) .hljs-attr,
+:is(.rich-text-editor, .transcript-code) .hljs-attribute { color: oklch(0.58 0.12 60); }
-.rich-text-editor .hljs-variable,
-.rich-text-editor .hljs-template-variable { color: oklch(0.58 0.14 20); }
+:is(.rich-text-editor, .transcript-code) .hljs-variable,
+:is(.rich-text-editor, .transcript-code) .hljs-template-variable { color: oklch(0.58 0.14 20); }
-.rich-text-editor .hljs-type,
-.rich-text-editor .hljs-title\.class_ { color: oklch(0.55 0.14 200); }
+:is(.rich-text-editor, .transcript-code) .hljs-type,
+:is(.rich-text-editor, .transcript-code) .hljs-title\.class_ { color: oklch(0.55 0.14 200); }
-.rich-text-editor .hljs-deletion { color: oklch(0.55 0.2 25); }
+:is(.rich-text-editor, .transcript-code) .hljs-deletion { color: oklch(0.55 0.2 25); }
-.rich-text-editor .hljs-meta { color: var(--muted-foreground); }
+:is(.rich-text-editor, .transcript-code) .hljs-meta { color: var(--muted-foreground); }
/* XML / HTML — lowlight emits .hljs-tag for `<` `>` brackets and .hljs-name
for the element name. Without these rules, HTML source renders mostly in
the default text color and looks unhighlighted. */
-.rich-text-editor .hljs-tag { color: var(--muted-foreground); }
-.rich-text-editor .hljs-name { color: oklch(0.55 0.16 255); }
+:is(.rich-text-editor, .transcript-code) .hljs-tag { color: var(--muted-foreground); }
+:is(.rich-text-editor, .transcript-code) .hljs-name { color: oklch(0.55 0.16 255); }
/* Dark mode overrides */
-.dark .rich-text-editor .hljs-keyword,
-.dark .rich-text-editor .hljs-selector-tag,
-.dark .rich-text-editor .hljs-built_in { color: oklch(0.7 0.14 255); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-keyword,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-selector-tag,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-built_in { color: oklch(0.7 0.14 255); }
-.dark .rich-text-editor .hljs-string,
-.dark .rich-text-editor .hljs-addition { color: oklch(0.7 0.14 155); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-string,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-addition { color: oklch(0.7 0.14 155); }
-.dark .rich-text-editor .hljs-number,
-.dark .rich-text-editor .hljs-literal { color: oklch(0.72 0.14 30); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-number,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-literal { color: oklch(0.72 0.14 30); }
-.dark .rich-text-editor .hljs-title,
-.dark .rich-text-editor .hljs-section,
-.dark .rich-text-editor .hljs-title\.function_ { color: oklch(0.72 0.12 280); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-title,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-section,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-title\.function_ { color: oklch(0.72 0.12 280); }
-.dark .rich-text-editor .hljs-attr,
-.dark .rich-text-editor .hljs-attribute { color: oklch(0.72 0.1 60); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-attr,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-attribute { color: oklch(0.72 0.1 60); }
-.dark .rich-text-editor .hljs-variable,
-.dark .rich-text-editor .hljs-template-variable { color: oklch(0.72 0.12 20); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-variable,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-template-variable { color: oklch(0.72 0.12 20); }
-.dark .rich-text-editor .hljs-type,
-.dark .rich-text-editor .hljs-title\.class_ { color: oklch(0.72 0.12 200); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-type,
+.dark :is(.rich-text-editor, .transcript-code) .hljs-title\.class_ { color: oklch(0.72 0.12 200); }
-.dark .rich-text-editor .hljs-deletion { color: oklch(0.7 0.18 25); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-deletion { color: oklch(0.7 0.18 25); }
-.dark .rich-text-editor .hljs-name { color: oklch(0.72 0.14 255); }
+.dark :is(.rich-text-editor, .transcript-code) .hljs-name { color: oklch(0.72 0.14 255); }