Skip to content

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

Go

feat(views): rebuild the run trace around steps, lanes, and outcome (#7011)

Jiayuan Zhang42dbf60dc8ad
diff --git a/packages/core/agents/stores/index.ts b/packages/core/agents/stores/index.ts
index f1d401560b..4d3eeb9d8e 100644
--- a/packages/core/agents/stores/index.ts
+++ b/packages/core/agents/stores/index.ts
@@ -13,7 +13,6 @@ export {
} from "./view-store";
export {
useTranscriptViewStore,
- type TranscriptDetailDensity,
type TranscriptFilterKey,
type TranscriptSortDirection,
} from "./transcript-view-store";
diff --git a/packages/core/agents/stores/transcript-view-store.test.ts b/packages/core/agents/stores/transcript-view-store.test.ts
index 1a0c3f725e..c1ea081d74 100644
--- a/packages/core/agents/stores/transcript-view-store.test.ts
+++ b/packages/core/agents/stores/transcript-view-store.test.ts
@@ -5,15 +5,13 @@ beforeEach(() => {
useTranscriptViewStore.setState({
sortDirection: "chronological",
selectedFilterKeys: [],
- density: "smart",
});
});
describe("useTranscriptViewStore", () => {
- it("defaults to chronological, unfiltered, and smart density", () => {
+ it("defaults to chronological and unfiltered", () => {
expect(useTranscriptViewStore.getState().sortDirection).toBe("chronological");
expect(useTranscriptViewStore.getState().selectedFilterKeys).toEqual([]);
- expect(useTranscriptViewStore.getState().density).toBe("smart");
});
it("setSortDirection switches between the two known directions", () => {
@@ -49,24 +47,16 @@ describe("useTranscriptViewStore", () => {
expect(useTranscriptViewStore.getState().selectedFilterKeys).toEqual([]);
});
- it("stores the density preference", () => {
- const { setDensity } = useTranscriptViewStore.getState();
-
- setDensity("expanded");
- expect(useTranscriptViewStore.getState().density).toBe("expanded");
-
- setDensity("collapsed");
- expect(useTranscriptViewStore.getState().density).toBe("collapsed");
- });
-
- it("migrates the legacy defaultExpanded boolean and rejects unknown density values", () => {
+ it("drops a persisted density from before the reading hierarchy replaced it", () => {
const merge = useTranscriptViewStore.persist.getOptions().merge!;
const current = useTranscriptViewStore.getState();
- expect(merge({ defaultExpanded: true }, current)).toMatchObject({ density: "expanded" });
- expect(merge({ defaultExpanded: false }, current)).toMatchObject({ density: "smart" });
- expect(merge({ density: "collapsed" }, current)).toMatchObject({ density: "collapsed" });
- expect(merge({ density: "bogus" }, current)).toMatchObject({ density: "smart" });
- expect(merge(undefined, current)).toMatchObject({ density: "smart" });
+ // Expand mode is no longer a setting: agent prose reads open and tool
+ // calls fold, so a stale persisted value must not resurface as state.
+ expect(merge({ density: "collapsed", sortDirection: "newest_first" }, current)).toMatchObject({
+ sortDirection: "newest_first",
+ });
+ expect(merge({ density: "collapsed" }, current)).not.toHaveProperty("density");
+ expect(merge(undefined, current)).toMatchObject({ sortDirection: "chronological" });
});
});
diff --git a/packages/core/agents/stores/transcript-view-store.ts b/packages/core/agents/stores/transcript-view-store.ts
index 9aad9cd321..a83c1b9c6a 100644
--- a/packages/core/agents/stores/transcript-view-store.ts
+++ b/packages/core/agents/stores/transcript-view-store.ts
@@ -7,31 +7,18 @@ import { defaultStorage } from "../../platform/storage";
export type TranscriptSortDirection = "chronological" | "newest_first";
export type TranscriptFilterKey = string;
-/**
- * Persisted expand-mode preference for the transcript. `smart` applies the
- * per-kind reading hierarchy (agent text and errors open, process noise
- * folded); `expanded`/`collapsed` are wholesale overrides. Row-level manual
- * toggles live in the dialog, sit above all three, and reset on mode switch.
- */
-export type TranscriptDetailDensity = "smart" | "expanded" | "collapsed";
-
-const DENSITIES: readonly TranscriptDetailDensity[] = ["smart", "expanded", "collapsed"];
-
interface TranscriptViewState {
sortDirection: TranscriptSortDirection;
selectedFilterKeys: TranscriptFilterKey[];
- density: TranscriptDetailDensity;
setSortDirection: (dir: TranscriptSortDirection) => void;
setSelectedFilterKeys: (keys: TranscriptFilterKey[]) => void;
toggleFilterKey: (key: TranscriptFilterKey) => void;
clearFilterKeys: () => void;
- setDensity: (density: TranscriptDetailDensity) => void;
}
const DEFAULTS = {
sortDirection: "chronological" as TranscriptSortDirection,
selectedFilterKeys: [] as TranscriptFilterKey[],
- density: "smart" as TranscriptDetailDensity,
};
function uniqueFilterKeys(keys: TranscriptFilterKey[]): TranscriptFilterKey[] {
@@ -52,7 +39,6 @@ export const useTranscriptViewStore = create<TranscriptViewState>()(
: [...state.selectedFilterKeys, key],
})),
clearFilterKeys: () => set({ selectedFilterKeys: [] }),
- setDensity: (density) => set({ density }),
}),
{
name: "multica_transcript_view",
@@ -60,24 +46,14 @@ export const useTranscriptViewStore = create<TranscriptViewState>()(
partialize: (state) => ({
sortDirection: state.sortDirection,
selectedFilterKeys: state.selectedFilterKeys,
- density: state.density,
}),
merge: (persisted, current) => {
if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<TranscriptViewState> & {
- /** Pre-density persisted shape: a boolean expand-everything flag. */
- defaultExpanded?: boolean;
- };
- const density = DENSITIES.includes(p.density as TranscriptDetailDensity)
- ? (p.density as TranscriptDetailDensity)
- : p.defaultExpanded === true
- ? "expanded"
- : DEFAULTS.density;
+ const p = persisted as Partial<TranscriptViewState>;
return {
...current,
sortDirection: p.sortDirection ?? DEFAULTS.sortDirection,
selectedFilterKeys: uniqueFilterKeys(p.selectedFilterKeys ?? []),
- density,
};
},
},
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 0e28709c2e..efacf5d4b4 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { readFileSync } from "node:fs";
-import { cleanup, fireEvent, screen } from "@testing-library/react";
+import { cleanup, fireEvent, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ButtonHTMLAttributes, ReactNode } from "react";
@@ -147,53 +147,6 @@ vi.mock("../../rich-content", () => ({
),
}));
-vi.mock("@multica/ui/components/ui/collapsible", async () => {
- const React = await import("react");
- const Context = React.createContext<{
- open: boolean;
- onOpenChange?: (open: boolean) => void;
- }>({ open: false });
-
- return {
- Collapsible: ({
- open,
- onOpenChange,
- children,
- }: {
- open: boolean;
- onOpenChange?: (open: boolean) => void;
- children: ReactNode;
- }) => (
- <Context.Provider value={{ open, onOpenChange }}>{children}</Context.Provider>
- ),
- CollapsibleTrigger: ({
- disabled,
- children,
- className: _className,
- ...props
- }: ButtonHTMLAttributes<HTMLButtonElement>) => {
- const ctx = React.useContext(Context);
- return (
- <button
- type="button"
- disabled={disabled}
- aria-expanded={ctx.open}
- onClick={() => {
- if (!disabled) ctx.onOpenChange?.(!ctx.open);
- }}
- {...props}
- >
- {children}
- </button>
- );
- },
- CollapsibleContent: ({ children }: { children: ReactNode }) => {
- const ctx = React.useContext(Context);
- return ctx.open ? <div>{children}</div> : null;
- },
- };
-});
-
const baseTask: AgentTask = {
id: "task-1",
agent_id: "",
@@ -278,9 +231,6 @@ beforeEach(() => {
useTranscriptViewStore.setState({
sortDirection: "chronological",
selectedFilterKeys: [],
- // Legacy row assertions below expect one-line summaries; smart density is
- // exercised by its own tests.
- density: "collapsed",
});
});
@@ -318,14 +268,14 @@ describe("AgentTranscriptDialog", () => {
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Thinking" }));
- expect(screen.queryByText("Agent summary")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("rich-content")).not.toBeInTheDocument();
expect(screen.getByText(/Thinking summary/)).toBeInTheDocument();
expect(useTranscriptViewStore.getState().selectedFilterKeys).toEqual(["thinking"]);
first.unmount();
renderDialog();
- expect(screen.queryByText("Agent summary")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("rich-content")).not.toBeInTheDocument();
expect(screen.getByText(/Thinking summary/)).toBeInTheDocument();
});
@@ -342,54 +292,113 @@ describe("AgentTranscriptDialog", () => {
},
]);
- expect(screen.getByText("Only agent summary")).toBeInTheDocument();
+ expect(screen.getByTestId("rich-content")).toHaveTextContent("Only agent summary");
expect(screen.queryByText("No execution data recorded.")).not.toBeInTheDocument();
});
- it("switches wholesale between expand-all and collapse-all via the density menu", () => {
+ it("reads agent prose in place and keeps tool detail one click away", () => {
renderDialog();
- expect(screen.queryByText(/Agent hidden detail/)).not.toBeInTheDocument();
+ // The report is the narrative and renders whole; a tool call is a line
+ // whose body waits in the inspector. This inversion is the redesign.
+ expect(screen.getByTestId("rich-content")).toHaveTextContent("Agent hidden detail");
expect(screen.queryByText(/"command": "pnpm test"/)).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole("menuitemradio", { name: /Expand all/ }));
+ fireEvent.click(screen.getByRole("button", { name: /pnpm test/ }));
- expect(screen.getByText(/Agent hidden detail/)).toBeInTheDocument();
- expect(screen.getByText(/Thinking hidden detail/)).toBeInTheDocument();
expect(screen.getByText(/"command": "pnpm test"/)).toBeInTheDocument();
+ });
+
+ it("folds a call and its result into one step instead of two rows", () => {
+ renderDialog([
+ { seq: 1, type: "tool_use", tool: "Bash", input: { command: "ls" } },
+ { seq: 2, type: "tool_result", tool: "Bash", output: "total 0" },
+ ]);
- fireEvent.click(screen.getByRole("menuitemradio", { name: /Collapse all/ }));
+ // One row for the call, and the result body is not in the list at all.
+ expect(screen.getAllByRole("button", { name: /^Bash/ })).toHaveLength(1);
+ expect(screen.queryByText("total 0")).not.toBeInTheDocument();
- expect(screen.queryByText(/Agent hidden detail/)).not.toBeInTheDocument();
- expect(screen.queryByText(/"command": "pnpm test"/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /^Bash/ }));
+ expect(screen.getByText("total 0")).toBeInTheDocument();
});
- it("smart density opens agent text in place and keeps process noise folded", () => {
- useTranscriptViewStore.setState({ density: "smart" });
+ it("keeps a screenshot out of the list and renders it as an image", () => {
+ const output = JSON.stringify([
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgo=" } },
+ ]);
+ renderDialog([
+ { seq: 1, type: "tool_use", tool: "Bash", input: { command: "screenshot" } },
+ { seq: 2, type: "tool_result", tool: "Bash", output },
+ ]);
+
+ // The old surface printed the whole base64 payload into the row.
+ expect(screen.queryByText(/iVBORw0KGgo/)).not.toBeInTheDocument();
- renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: /screenshot/ }));
- // Agent body reads without a click (through RichContent), tools stay folded.
- expect(screen.getByTestId("rich-content")).toHaveTextContent("Agent hidden detail");
- expect(screen.queryByText(/Thinking hidden detail/)).not.toBeInTheDocument();
- expect(screen.queryByText(/"command": "pnpm test"/)).not.toBeInTheDocument();
+ expect(screen.getByRole("img", { name: "Image" })).toHaveAttribute(
+ "src",
+ "data:image/png;base64,iVBORw0KGgo=",
+ );
});
- it("row-level toggles override the density default until the mode changes", () => {
- useTranscriptViewStore.setState({ density: "smart" });
+ it("folds consecutive same-tool calls into one group that expands", () => {
+ renderDialog([
+ { seq: 1, type: "tool_use", tool: "Read", input: { file_path: "/a.ts" } },
+ { seq: 2, type: "tool_result", tool: "Read", output: "a" },
+ { seq: 3, type: "tool_use", tool: "Read", input: { file_path: "/b.ts" } },
+ { seq: 4, type: "tool_result", tool: "Read", output: "b" },
+ { seq: 5, type: "tool_use", tool: "Read", input: { file_path: "/c.ts" } },
+ { seq: 6, type: "tool_result", tool: "Read", output: "c" },
+ ]);
+
+ // The folded row still names what it touched first — "Read · 3 calls"
+ // alone would hide the only detail that makes a group scannable.
+ const group = screen.getByRole("button", { name: /\/a\.ts.*3 calls/ });
+ expect(screen.queryByText("/c.ts")).not.toBeInTheDocument();
+
+ fireEvent.click(group);
+ expect(screen.getByText("/c.ts")).toBeInTheDocument();
+ });
+
+ it("narrows the list to steps matching the search", () => {
renderDialog();
- // Fold the default-open agent body back to one line. The `expanded`
- // filter distinguishes the collapse trigger from the timeline segment,
- // which also carries the "Agent" accessible name via its title.
- fireEvent.click(screen.getByRole("button", { name: "Agent", expanded: true }));
+ fireEvent.change(screen.getByLabelText("Search this run…"), {
+ target: { value: "pnpm" },
+ });
+
+ expect(screen.getByRole("button", { name: /pnpm test/ })).toBeInTheDocument();
expect(screen.queryByTestId("rich-content")).not.toBeInTheDocument();
- expect(screen.getByText("Agent summary")).toBeInTheDocument();
+ expect(screen.getByText("1 of 3 steps")).toBeInTheDocument();
+ });
+
+ it("hides the timeline for a run too short for it to say anything", () => {
+ renderDialog();
+
+ expect(screen.queryByText("Model")).not.toBeInTheDocument();
+ expect(screen.queryByText("Tools")).not.toBeInTheDocument();
+ });
- // Open a default-folded thinking row.
- fireEvent.click(screen.getByRole("button", { name: /Thinking summary/ }));
- expect(screen.getByText(/Thinking hidden detail/)).toBeInTheDocument();
+ it("shows model and tool lanes once a run is long enough to have spent time", () => {
+ const at = (seconds: number) =>
+ new Date(Date.parse("2026-06-08T08:00:00Z") + seconds * 1000).toISOString();
+ const longRun: TimelineItem[] = [];
+ for (let i = 0; i < 8; i++) {
+ longRun.push(
+ { seq: i * 2 + 1, type: "tool_use", tool: "Bash", input: { command: `step ${i}` }, created_at: at(i * 40) },
+ { seq: i * 2 + 2, type: "tool_result", tool: "Bash", output: "ok", created_at: at(i * 40 + 20) },
+ );
+ }
+
+ renderDialog(longRun, {
+ task: { ...baseTask, started_at: at(0), completed_at: at(320) },
+ });
+
+ expect(screen.getByText("Model")).toBeInTheDocument();
+ expect(screen.getByText("Tools")).toBeInTheDocument();
});
it("copies RFC 3339 timestamps before event labels", () => {
@@ -442,7 +451,6 @@ describe("AgentTranscriptDialog", () => {
);
});
it("renders a file edit as a diff instead of escaped JSON strings", () => {
- useTranscriptViewStore.setState({ density: "expanded" });
const { container } = renderDialog([
{
seq: 1,
@@ -456,6 +464,8 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
+
// 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) =>
@@ -470,7 +480,6 @@ describe("AgentTranscriptDialog", () => {
});
it("highlights diff rows using the grammar for the file extension", () => {
- useTranscriptViewStore.setState({ density: "expanded" });
const { container } = renderDialog([
{
seq: 1,
@@ -484,6 +493,8 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
+
// `let` is a Rust keyword, so the highlighter must have marked it up.
expect(container.querySelector(".hljs-keyword")?.textContent).toBe("let");
});
@@ -491,7 +502,6 @@ describe("AgentTranscriptDialog", () => {
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,
@@ -501,13 +511,14 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
+
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,
@@ -517,12 +528,13 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
+
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,
@@ -532,6 +544,8 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /^Bash/ }));
+
expect(
screen.getByText("total 0\ndrwxr-xr-x 2 user staff", {
selector: "pre",
@@ -541,7 +555,6 @@ describe("AgentTranscriptDialog", () => {
).toBeInTheDocument();
});
it("shows a whole-file write as plain content with a line count", () => {
- useTranscriptViewStore.setState({ density: "expanded" });
const { container } = renderDialog([
{
seq: 1,
@@ -551,7 +564,10 @@ describe("AgentTranscriptDialog", () => {
},
]);
- expect(screen.getByText("+2")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /Write/ }));
+
+ // The outcome row reports "+2" as well, so scope this to the inspector.
+ expect(within(screen.getByRole("complementary")).getByText("+2")).toBeInTheDocument();
// Plain content: no per-line + gutter and no diff tinting.
const pre = container.querySelector("pre");
expect(pre?.textContent).toBe("alpha\nbeta");
@@ -559,12 +575,13 @@ describe("AgentTranscriptDialog", () => {
});
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 } },
]);
+ fireEvent.click(screen.getByRole("button", { name: /Write/ }));
+
const pre = container.querySelector("pre");
expect(pre?.className).toContain("max-h-52");
expect(pre?.className).toContain("overflow-hidden");
@@ -575,7 +592,6 @@ describe("AgentTranscriptDialog", () => {
});
it("does not clamp a short diff", () => {
- useTranscriptViewStore.setState({ density: "expanded" });
renderDialog([
{
seq: 1,
@@ -585,6 +601,8 @@ describe("AgentTranscriptDialog", () => {
},
]);
+ fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
+
expect(screen.queryByRole("button", { name: "Show all" })).not.toBeInTheDocument();
});
@@ -622,7 +640,8 @@ describe("AgentTranscriptDialog — delivered branch", () => {
await userEvent.click(screen.getByRole("button", { name: "Run details" }));
- expect(screen.getByText("agent/j/abc12345")).toBeInTheDocument();
+ // Also shown as a produced artifact in the outcome row, hence getAllByText.
+ expect(screen.getAllByText("agent/j/abc12345").length).toBeGreaterThan(0);
await userEvent.click(screen.getByTitle("Copy branch name"));
expect(copyTextMock).toHaveBeenCalledWith("agent/j/abc12345");
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index e5fc157f38..457c60c001 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -4,9 +4,8 @@ import { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo, for
import { Virtuoso, type VirtuosoHandle, type Components } from "react-virtuoso";
import {
Bot,
- ChevronRight,
Brain,
- AlertCircle,
+ CircleAlert,
CheckCircle2,
XCircle,
X,
@@ -14,19 +13,25 @@ import {
Clock,
Copy,
Check,
+ ChevronRight,
Filter,
+ FilePen,
+ FileText,
+ Search,
+ Terminal,
+ Wrench,
+ MoreHorizontal,
ArrowDownNarrowWide,
ArrowUpNarrowWide,
- ListCollapse,
Info,
Coins,
+ GitBranch,
} from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
import { Button } from "@multica/ui/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@multica/ui/components/ui/collapsible";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -34,8 +39,6 @@ import {
DropdownMenuSeparator,
DropdownMenuCheckboxItem,
DropdownMenuItem,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
} from "@multica/ui/components/ui/dropdown-menu";
import { ActorAvatar } from "../actor-avatar";
import { AttributionBadge } from "../../issues/components/attribution-badge";
@@ -44,7 +47,6 @@ import { RichContent } from "../../rich-content";
import { api } from "@multica/core/api";
import {
useTranscriptViewStore,
- type TranscriptDetailDensity,
type TranscriptFilterKey,
type TranscriptSortDirection,
} from "@multica/core/agents/stores";
@@ -59,17 +61,39 @@ import {
} from "./transcript-follow";
import type { TimelineItem } from "./build-timeline";
import {
+ buildLanes,
+ buildSteps,
+ groupSteps,
+ isCallStep,
+ isGroupRow,
+ rowCalls,
+ shouldShowTimeline,
+ toolKindTotals,
+ type TraceCallStep,
+ type TraceGroupRow,
+ type TraceMessageStep,
+ type TraceRow,
+ type TraceStep,
+} from "./build-steps";
+import { buildRunOutcome } from "./run-outcome";
+import { RunTimeline } from "./run-timeline";
+import {
+ base64ByteLength,
+ readImageResult,
traceEventCopyText,
- traceEventDefaultExpanded,
traceEventDetail,
- traceEventHasDetail,
- traceEventKind,
traceEventLabel,
traceEventSummary,
- traceEventSummaryIsMono,
+ traceToolArgSummary,
} from "./trace-event-presenter";
-import type { TraceDiffLine, TracePatchFile, TraceSummaryLabels } from "./trace-event-presenter";
-import { highlightBlock, highlightToLines, languageForPath } from "./diff-highlight";
+import type { TraceSummaryLabels } from "./trace-event-presenter";
+import {
+ DiffDetailSurface,
+ FileWriteSurface,
+ PatchDetailSurface,
+ ToolDetailSurface,
+} from "./detail-surfaces";
+import { languageForPath } from "./diff-highlight";
import { useT } from "../../i18n";
import {
formatTokens,
@@ -79,6 +103,11 @@ import {
import "../../editor/styles/code.css";
import "./task-transcript.css";
+// The run surface, read in four layers: what happened (header), what it
+// produced (outcome), where the time went (timeline), and the evidence (steps).
+// Only one layer is expanded at a time — the inspector opens on demand rather
+// than splitting the surface in two before the reader has asked anything.
+
interface AgentTranscriptDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -95,52 +124,11 @@ interface AgentTranscriptDialogProps {
headerSlot?: React.ReactNode;
}
-// ─── Color mapping for timeline segments ────────────────────────────────────
-
-type EventColor = "agent" | "thinking" | "tool" | "result" | "error";
-
-function getEventColor(item: TimelineItem): EventColor {
- switch (item.type) {
- case "text":
- return "agent";
- case "thinking":
- return "thinking";
- case "tool_use":
- return "tool";
- case "tool_result":
- return "result";
- case "error":
- return "error";
- default:
- return "result";
- }
-}
-
-const colorClasses: Record<EventColor, { bg: string; bgActive: string; label: string }> = {
- agent: { bg: "bg-emerald-400/60", bgActive: "bg-emerald-500", label: "bg-emerald-500" },
- thinking: { bg: "bg-violet-400/60", bgActive: "bg-violet-500", label: "bg-violet-500/20 text-violet-700 dark:text-violet-300" },
- tool: { bg: "bg-blue-400/60", bgActive: "bg-blue-500", label: "bg-blue-500/20 text-blue-700 dark:text-blue-300" },
- result: { bg: "bg-slate-300/60 dark:bg-slate-600/60", bgActive: "bg-slate-400 dark:bg-slate-500", label: "bg-muted text-muted-foreground" },
- error: { bg: "bg-red-400/60", bgActive: "bg-red-500", label: "bg-red-500/20 text-red-700 dark:text-red-300" },
-};
-
// ─── Helpers ────────────────────────────────────────────────────────────────
-// Presentation rules (kind/label/summary/default expansion) live in the pure
-// trace-event-presenter module; only view-plumbing helpers remain here.
-
-function getItemFilterKey(item: TimelineItem): TranscriptFilterKey {
- return item.tool && (item.type === "tool_use" || item.type === "tool_result")
- ? `tool:${item.tool}`
- : item.type;
-}
function formatDuration(start: string, end: string): string {
const ms = new Date(end).getTime() - new Date(start).getTime();
- const seconds = Math.floor(ms / 1000);
- if (seconds < 60) return `${seconds}s`;
- const minutes = Math.floor(seconds / 60);
- const secs = seconds % 60;
- return `${minutes}m ${secs}s`;
+ return formatElapsedMs(ms);
}
function formatElapsedMs(ms: number): string {
@@ -151,6 +139,25 @@ function formatElapsedMs(ms: number): string {
return `${minutes}m ${secs}s`;
}
+/** A step's own duration, in the compact form the right column carries. */
+function formatStepDuration(ms: number): string {
+ if (ms < 1000) return `${(ms / 1000).toFixed(1)}s`;
+ if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
+ const minutes = Math.floor(ms / 60_000);
+ const seconds = Math.round((ms % 60_000) / 1000);
+ return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
+}
+
+/** Offset from the run's start, which is what a step's position means. */
+function formatOffset(ms: number): string {
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ if (minutes < 60) return `+${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
+ const hours = Math.floor(minutes / 60);
+ return `+${hours}:${String(minutes % 60).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
+}
+
function formatRunTime(iso: string): string {
return new Date(iso).toLocaleString(undefined, {
month: "short",
@@ -161,6 +168,45 @@ function formatRunTime(iso: string): string {
});
}
+function timeMs(iso: string | undefined): number | undefined {
+ if (!iso) return undefined;
+ const ms = new Date(iso).getTime();
+ return Number.isFinite(ms) ? ms : undefined;
+}
+
+function stepFilterKey(step: TraceStep): TranscriptFilterKey {
+ return step.kind === "call" ? `tool:${step.tool}` : step.kind;
+}
+
+/** Lowercased haystack for the in-run search. Outputs are clipped: a match
+ * past 4KB of command output is not one anybody is scanning for. */
+function stepHaystack(step: TraceStep): string {
+ if (step.kind !== "call") return (step.item.content ?? "").toLowerCase();
+ const input = step.call?.input ? JSON.stringify(step.call.input) : "";
+ return `${step.tool} ${input} ${(step.result?.output ?? "").slice(0, 4000)}`.toLowerCase();
+}
+
+function StepIcon({ step, className }: { step: TraceStep; className?: string }) {
+ if (!isCallStep(step)) {
+ if (step.kind === "thinking") return <Brain className={className} />;
+ if (step.kind === "error") return <CircleAlert className={className} />;
+ return <Bot className={className} />;
+ }
+
+ // Tool names differ per provider, so the input's shape picks the glyph.
+ const input = step.call?.input;
+ if (input) {
+ if (typeof input.command === "string") return <Terminal className={className} />;
+ if (typeof input.old_string === "string" || typeof input.content === "string" || input.changes)
+ return <FilePen className={className} />;
+ if (typeof input.query === "string" || typeof input.pattern === "string")
+ return <Search className={className} />;
+ if (typeof input.file_path === "string" || typeof input.path === "string")
+ return <FileText className={className} />;
+ }
+ return <Wrench className={className} />;
+}
+
// ─── Run detail row (ⓘ popover) ─────────────────────────────────────────────
// One labeled fact in the diagnostic popover. When `onCopy` is given the whole
// row is a copy button (used for the workdir path).
@@ -218,7 +264,7 @@ const VirtuosoList = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElem
return <div ref={ref} {...props} className="divide-y" />;
},
);
-const LIST_COMPONENTS: Components<TimelineItem> = { List: VirtuosoList };
+const LIST_COMPONENTS: Components<TraceRow> = { List: VirtuosoList };
export function AgentTranscriptDialog({
open,
@@ -231,16 +277,14 @@ export function AgentTranscriptDialog({
}: AgentTranscriptDialogProps) {
const { t } = useT("agents");
const [selectedSeq, setSelectedSeq] = useState<number | null>(null);
+ const [expandedGroups, setExpandedGroups] = useState<Set<number>>(() => new Set());
+ const [query, setQuery] = useState("");
const [elapsed, setElapsed] = useState("");
const [copied, setCopied] = useState(false);
const [copiedWorkdir, setCopiedWorkdir] = useState(false);
const [copiedBranch, setCopiedBranch] = useState(false);
const [agentInfo, setAgentInfo] = useState<Agent | null>(null);
const [runtimeInfo, setRuntimeInfo] = useState<AgentRuntime | null>(null);
- // Row-level expand overrides. A row the user toggled follows the toggle; any
- // other row follows the density preference (see traceEventDefaultExpanded).
- // Switching density or task resets the overrides wholesale.
- const [rowOverrides, setRowOverrides] = useState<Map<number, boolean>>(() => new Map());
const sortDirection = useTranscriptViewStore((s) => s.sortDirection);
const setSortDirection = useTranscriptViewStore((s) => s.setSortDirection);
// Filters always persist across opens — a facet a run doesn't have simply
@@ -249,8 +293,6 @@ export function AgentTranscriptDialog({
const selectedFilterKeys = useTranscriptViewStore((s) => s.selectedFilterKeys);
const toggleFilterKey = useTranscriptViewStore((s) => s.toggleFilterKey);
const clearFilters = useTranscriptViewStore((s) => s.clearFilterKeys);
- const density = useTranscriptViewStore((s) => s.density);
- const setDensity = useTranscriptViewStore((s) => s.setDensity);
const virtuosoRef = useRef<VirtuosoHandle>(null);
// Newest-first live follow (#5921): all latch decisions live in the pure
// controller (see transcript-follow.ts for the model); this component only
@@ -282,7 +324,7 @@ export function AgentTranscriptDialog({
};
const onKeyDown = (e: KeyboardEvent) => {
// Only keys aimed at the scroller itself; Space/arrows bubbling from
- // row controls (e.g. a collapsible trigger) are not scroll intent.
+ // row controls are not scroll intent.
if (e.target !== el) return;
if (e.key === "ArrowDown") followCtl.input(LINE_SCROLL_PX);
else if (e.key === "ArrowUp") followCtl.input(-LINE_SCROLL_PX);
@@ -333,27 +375,33 @@ export function AgentTranscriptDialog({
useEffect(() => () => detachScrollerRef.current?.(), []);
+ // A different run is a different reading position: drop the selection and
+ // any group the reader had opened.
useEffect(() => {
- setRowOverrides(new Map());
- }, [task.id, density]);
+ setSelectedSeq(null);
+ setExpandedGroups(new Set());
+ }, [task.id]);
+
+ // ── Derived model ────────────────────────────────────────────────────────
+
+ // One step per tool call, with its result folded in — see build-steps.ts for
+ // why the pairing is positional.
+ const steps = useMemo(() => buildSteps(items), [items]);
- // Derive filter options from each item:
- // tool_use / tool_result → filter value = tool, display = "tool:Bash"
- // other types → display from traceEventLabel
const filterOptions = useMemo(() => {
const options = new Map<string, string>();
- for (const item of items) {
- const key = getItemFilterKey(item);
- if (item.tool && (item.type === "tool_use" || item.type === "tool_result")) {
- if (!options.has(key)) options.set(key, key);
- } else {
- if (!options.has(key)) {
- options.set(key, traceEventLabel(item));
- }
- }
+ for (const step of steps) {
+ const key = stepFilterKey(step);
+ if (options.has(key)) continue;
+ options.set(
+ key,
+ step.kind === "call"
+ ? key
+ : traceEventLabel({ type: step.item.type, tool: step.item.tool }),
+ );
}
return Array.from(options.entries()).sort((a, b) => a[1].localeCompare(b[1]));
- }, [items]);
+ }, [steps]);
const filterOptionKeys = useMemo(
() => new Set(filterOptions.map(([value]) => value)),
@@ -367,21 +415,61 @@ export function AgentTranscriptDialog({
const activeFilterSet = useMemo(() => new Set(activeFilterKeys), [activeFilterKeys]);
- // Strict filter
- const filteredItems = useMemo(() => {
- if (activeFilterSet.size === 0) return items;
- return items.filter((item) => activeFilterSet.has(getItemFilterKey(item)));
- }, [items, activeFilterSet]);
+ const trimmedQuery = query.trim().toLowerCase();
+
+ const filteredSteps = useMemo(() => {
+ if (activeFilterSet.size === 0 && trimmedQuery.length === 0) return steps;
+ return steps.filter((step) => {
+ if (activeFilterSet.size > 0 && !activeFilterSet.has(stepFilterKey(step))) return false;
+ if (trimmedQuery.length > 0 && !stepHaystack(step).includes(trimmedQuery)) return false;
+ return true;
+ });
+ }, [steps, activeFilterSet, trimmedQuery]);
+
+ // Grouping runs on what the reader is looking at: filtering breaks adjacency,
+ // and a group that spans a hidden step would be a lie about what ran.
+ const rows = useMemo(() => groupSteps(filteredSteps), [filteredSteps]);
// Apply user-chosen sort direction. Reverse is a pure presentation concern —
- // the underlying timeline (and its seq numbers) is untouched, so copy/filter
- // and segment navigation continue to work against the same data.
- const displayItems = useMemo(
- () => (sortDirection === "newest_first" ? [...filteredItems].reverse() : filteredItems),
- [filteredItems, sortDirection],
+ // the underlying steps (and their seq numbers) are untouched.
+ const displayRows = useMemo(
+ () => (sortDirection === "newest_first" ? [...rows].reverse() : rows),
+ [rows, sortDirection],
);
+
+ const runStart = task.started_at ?? task.dispatched_at ?? steps[0]?.startedAt;
+ const runStartMs = timeMs(runStart);
+ const lastStamp = useMemo(() => {
+ for (let i = steps.length - 1; i >= 0; i--) {
+ const step = steps[i]!;
+ const stamp = step.kind === "call" ? (step.endedAt ?? step.startedAt) : step.startedAt;
+ if (stamp) return stamp;
+ }
+ return undefined;
+ }, [steps]);
+ const runEnd = task.completed_at ?? lastStamp;
+
+ const lanes = useMemo(() => buildLanes(steps, runStart, runEnd), [steps, runStart, runEnd]);
+ // A short run's timeline says less than the durations already on each row,
+ // so it does not render at all.
+ const showTimeline = shouldShowTimeline(steps, lanes);
+ const toolKinds = useMemo(() => toolKindTotals(steps), [steps]);
+ const outcome = useMemo(() => buildRunOutcome(steps), [steps]);
+
+ const selectedStep = useMemo(() => {
+ if (selectedSeq === null) return null;
+ return steps.find((step) => step.seq === selectedSeq) ?? null;
+ }, [steps, selectedSeq]);
+
+ const selectedOffsetMs =
+ selectedStep && runStartMs !== undefined
+ ? Math.max(0, (timeMs(selectedStep.startedAt) ?? runStartMs) - runStartMs)
+ : undefined;
+
+ // Keyed on the run having produced nothing at all, not on the filtered view
+ // being empty — a filter that hides every step is not a runtime limitation.
const isAntigravityLiveEmpty =
- isLive && displayItems.length === 0 && runtimeInfo?.provider === "antigravity";
+ isLive && steps.length === 0 && runtimeInfo?.provider === "antigravity";
// Newest-first shows live events as PREPENDS, and Virtuoso items opt out of
// native scroll anchoring (`overflow-anchor: none`), so without compensation
@@ -391,17 +479,12 @@ export function AgentTranscriptDialog({
// down from a large base satisfies that while the list only grows. Sort,
// filter, or task changes can shrink the list, so `listEpoch` remounts the
// instance (fresh at top) instead of letting firstItemIndex climb.
- // `scrollToIndex`/`computeItemKey` are unaffected: indices stay data-relative
- // (verified against scrollToIndexSystem — it never reads firstItemIndex).
const firstItemIndex =
- sortDirection === "newest_first" ? 1_000_000 - displayItems.length : 0;
- const listEpoch = `${task.id}:${sortDirection}:${activeFilterKeys.join(",")}`;
+ sortDirection === "newest_first" ? 1_000_000 - displayRows.length : 0;
+ const listEpoch = `${task.id}:${sortDirection}:${activeFilterKeys.join(",")}:${trimmedQuery}`;
- // Toggling direction is a manual user action; jump the scroll container back
- // to the top so the newest end of the timeline (per the chosen direction) is
- // immediately visible. Avoids stranding the user mid-scroll on the wrong end.
const handleSortDirectionChange = useCallback(
- (dir: typeof sortDirection) => {
+ (dir: TranscriptSortDirection) => {
if (dir === sortDirection) return;
setSortDirection(dir);
virtuosoRef.current?.scrollTo({ top: 0 });
@@ -424,11 +507,8 @@ export function AgentTranscriptDialog({
// hold the viewport on the previous first row. Instant (not smooth): a
// smooth animation spans multiple flushes and its in-flight position reads
// as user displacement. The scroll-event enforcement in handleScrollerRef
- // is the authoritative pin (Virtuoso's prepend compensation lands after
- // React effects); this effect just shortens the first-paint gap.
- // Chronological live follow is handled natively by Virtuoso's followOutput
- // below; this pair is its prepend-side counterpart.
- const displayCount = displayItems.length;
+ // is the authoritative pin; this effect just shortens the first-paint gap.
+ const displayCount = displayRows.length;
useLayoutEffect(() => {
if (!followCtl.isFollowing()) return;
virtuosoRef.current?.scrollToIndex({ index: 0, align: "start", behavior: "auto" });
@@ -466,12 +546,9 @@ export function AgentTranscriptDialog({
return () => clearInterval(interval);
}, [isLive, task.started_at, task.dispatched_at]);
- // Rows are virtualized, so an off-screen target is not in the DOM;
- // navigate by index instead of a node ref.
- const handleSegmentClick = useCallback(
+ const scrollToStep = useCallback(
(seq: number) => {
- setSelectedSeq(seq);
- const index = displayItems.findIndex((item) => item.seq === seq);
+ const index = displayRows.findIndex((row) => row.seq === seq || rowCalls(row).some((c) => c.seq === seq));
if (index < 0) return;
// Explicit navigation away from the live end unlatches the newest-first
// follow — otherwise the scroll-event enforcement would pin the viewport
@@ -479,11 +556,27 @@ export function AgentTranscriptDialog({
if (index > 0) followCtl.disengage();
virtuosoRef.current?.scrollToIndex({ index, align: "center", behavior: "smooth" });
},
- [displayItems, followCtl],
+ [displayRows, followCtl],
+ );
+
+ // Clicking the timeline lands on the first step at or after that offset.
+ const handleSeek = useCallback(
+ (offsetMs: number) => {
+ if (runStartMs === undefined) return;
+ const target = runStartMs + offsetMs;
+ let best: TraceStep | null = null;
+ for (const step of steps) {
+ const at = timeMs(step.startedAt);
+ if (at === undefined || at < target) continue;
+ if (!best || at < (timeMs(best.startedAt) ?? Infinity)) best = step;
+ }
+ if (!best) return;
+ setSelectedSeq(best.seq);
+ scrollToStep(best.seq);
+ },
+ [steps, runStartMs, scrollToStep],
);
- // Copy all events as text. Use the displayed order so users get the same
- // sequence they see on screen — matters when sort is set to newest-first.
const handleCopyWorkdir = useCallback(() => {
if (!task.relative_work_dir) return;
void copyText(task.relative_work_dir).then((ok) => {
@@ -506,27 +599,41 @@ export function AgentTranscriptDialog({
const handleCopyAll = useCallback(() => {
// Copy the full body of each event (not the truncated row summary), with
- // the same secret redaction the detail view applies.
- const text = displayItems
- .map((item) => redactSecrets(traceEventCopyText(item)))
- .join("\n\n");
+ // the same secret redaction the detail view applies. A step copies as its
+ // call followed by its result, which is the order it happened in.
+ const events: TimelineItem[] = [];
+ for (const row of displayRows) {
+ if (row.kind === "group") {
+ for (const call of row.steps) {
+ if (call.call) events.push(call.call);
+ if (call.result) events.push(call.result);
+ }
+ continue;
+ }
+ if (row.kind === "call") {
+ if (row.call) events.push(row.call);
+ if (row.result) events.push(row.result);
+ continue;
+ }
+ events.push(row.item);
+ }
+ const text = events.map((event) => redactSecrets(traceEventCopyText(event))).join("\n\n");
void copyText(text).then((ok) => {
if (!ok) return;
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
- }, [displayItems]);
+ }, [displayRows]);
-
- const handleRowExpandedChange = useCallback((seq: number, expanded: boolean) => {
- setRowOverrides((prev) => {
- const next = new Map(prev);
- next.set(seq, expanded);
+ const handleToggleGroup = useCallback((seq: number) => {
+ setExpandedGroups((prev) => {
+ const next = new Set(prev);
+ if (next.has(seq)) next.delete(seq);
+ else next.add(seq);
return next;
});
}, []);
- // Duration
const duration =
task.started_at && task.completed_at
? formatDuration(task.started_at, task.completed_at)
@@ -536,7 +643,7 @@ export function AgentTranscriptDialog({
const copyTranscriptLabel = copied
? t(($) => $.transcript.copied)
- : activeFilterKeys.length > 0
+ : activeFilterKeys.length > 0 || trimmedQuery.length > 0
? t(($) => $.transcript.copy_filtered)
: t(($) => $.transcript.copy_all);
@@ -610,7 +717,7 @@ export function AgentTranscriptDialog({
})();
// Trigger source: one word answering "why does this run exist" — more useful
- // up front than the runtime/provider diagnostics, which move to the ⓘ popover.
+ // up front than the runtime/provider diagnostics, which live in the ⓘ popover.
const triggerLabel = task.parent_task_id
? t(($) => $.transcript.trigger_retry)
: task.kind === "comment" || task.trigger_comment_id
@@ -631,16 +738,6 @@ export function AgentTranscriptDialog({
const createdLabel = task.created_at ? formatRunTime(task.created_at) : null;
const startedLabel = task.started_at ? formatRunTime(task.started_at) : null;
const completedLabel = task.completed_at ? formatRunTime(task.completed_at) : null;
- // "When was this run created" — a read-before-you-read fact worth the toolbar
- // surface (the ⓘ popover keeps the full-precision created/started/completed).
- const createdShort = task.created_at
- ? new Date(task.created_at).toLocaleString(undefined, {
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- })
- : null;
const hasTriggeredBy = !!task.attribution?.initiator;
// This run's own spend. Present on transcripts opened from the issue
// execution log (the endpoint that hydrates usage); absent elsewhere, where
@@ -664,15 +761,15 @@ export function AgentTranscriptDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
- className="!max-w-4xl !w-[calc(100vw-4rem)] !max-h-[calc(100vh-4rem)] !h-[calc(100vh-4rem)] flex flex-col !p-0 !gap-0 overflow-hidden"
+ className="!max-w-5xl !w-[calc(100vw-4rem)] !max-h-[calc(100vh-4rem)] !h-[calc(100vh-4rem)] flex flex-col !p-0 !gap-0 overflow-hidden"
showCloseButton={false}
>
<DialogTitle className="sr-only">{t(($) => $.transcript.dialog_title)}</DialogTitle>
- {/* ── Header: identity only ──────────────────────────────────
- Tier 1 — everything a viewer needs BEFORE reading: outcome
- (status anchors the left), who ran it, why it exists (trigger),
- and who's accountable. All diagnostics move to the ⓘ popover. */}
+ {/* ── Header: outcome, identity, spend ─────────────────────────
+ Everything a viewer needs BEFORE reading: how it ended, who ran
+ it, why it exists, how long it took and what it cost. Diagnostics
+ stay in the ⓘ popover. */}
<div className="border-b px-4 py-3 shrink-0">
<div className="flex min-w-0 items-center gap-3">
{statusBadge}
@@ -707,6 +804,14 @@ export function AgentTranscriptDialog({
</>
)}
<span className="shrink-0">{triggerLabel}</span>
+ {duration && (
+ <>
+ <FactDot />
+ <span className="shrink-0 tabular-nums">
+ {t(($) => $.transcript.fact_took, { duration })}
+ </span>
+ </>
+ )}
</div>
{/* What this run cost, in the header of the run you are reading —
@@ -843,150 +948,17 @@ export function AgentTranscriptDialog({
</div>
</div>
- {/* ── List toolbar: read-before-you-read summary (left) + controls
- (right). Duration + event count fill the left, so the row balances
- instead of leaving dead space. ── */}
- <div className="flex items-center gap-3 border-b px-4 py-1.5 shrink-0">
- <div className="flex min-w-0 flex-1 items-center gap-x-1.5 overflow-hidden whitespace-nowrap text-caption text-muted-foreground">
- {createdShort && (
- <>
- <span>{t(($) => $.transcript.fact_created, { time: createdShort })}</span>
- <FactDot />
- </>
- )}
- {duration && (
- <>
- <span className="tabular-nums">{t(($) => $.transcript.fact_took, { duration })}</span>
- <FactDot />
- </>
- )}
- <span>
- {activeFilterKeys.length > 0
- ? t(($) => $.transcript.events_filtered, { shown: filteredItems.length, total: items.length })
- : t(($) => $.transcript.events, { count: items.length })}
- </span>
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {items.length > 0 && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="ghost"
- size="sm"
- aria-label={t(($) => $.transcript.density_label)}
- className="text-muted-foreground"
- />
- }
- >
- <ListCollapse className="h-3 w-3" />
- <span className="hidden sm:inline">
- {density === "smart"
- ? t(($) => $.transcript.density_smart)
- : density === "expanded"
- ? t(($) => $.transcript.density_expanded)
- : t(($) => $.transcript.density_collapsed)}
- </span>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-64">
- <DropdownMenuRadioGroup
- value={density}
- onValueChange={(value) => setDensity(value as TranscriptDetailDensity)}
- >
- {(
- [
- ["smart", t(($) => $.transcript.density_smart), t(($) => $.transcript.density_smart_desc)],
- ["expanded", t(($) => $.transcript.density_expanded), t(($) => $.transcript.density_expanded_desc)],
- ["collapsed", t(($) => $.transcript.density_collapsed), t(($) => $.transcript.density_collapsed_desc)],
- ] as const
- ).map(([value, name, description]) => (
- <DropdownMenuRadioItem key={value} value={value} className="items-start">
- <span className="flex min-w-0 flex-col gap-0.5">
- <span>{name}</span>
- <span className="text-micro leading-snug text-muted-foreground">
- {description}
- </span>
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- {items.length > 1 && (
- <SortDirectionToggle
- value={sortDirection}
- onChange={handleSortDirectionChange}
- labels={{
- chronological: t(($) => $.transcript.sort_chronological),
- newestFirst: t(($) => $.transcript.sort_newest_first),
- ariaLabel: t(($) => $.transcript.sort_label),
- }}
- />
- )}
- {filterOptions.length > 0 && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={activeFilterKeys.length > 0 ? "brand" : "ghost"}
- size="sm"
- aria-label={t(($) => $.transcript.filter)}
- className={activeFilterKeys.length > 0 ? undefined : "text-muted-foreground"}
- />
- }
- >
- <Filter className="h-3 w-3" />
- <span className="hidden sm:inline">{t(($) => $.transcript.filter)}</span>
- {activeFilterKeys.length > 0 && (
- <span className="ml-0.5 rounded-full bg-brand-foreground/20 px-1.5 py-0 text-micro font-medium tabular-nums">
- {activeFilterKeys.length}
- </span>
- )}
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-auto">
- {filterOptions.map(([value, label]) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={selectedFilterKeys.includes(value)}
- onCheckedChange={() => toggleFilterKey(value)}
- >
- {label}
- </DropdownMenuCheckboxItem>
- ))}
- {selectedFilterKeys.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={clearFilters} className="text-muted-foreground">
- {t(($) => $.transcript.clear_filters)}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- <Button
- variant="ghost"
- size="sm"
- onClick={handleCopyAll}
- aria-label={copyTranscriptLabel}
- className="text-muted-foreground"
- >
- {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
- <span className="hidden sm:inline">{copyTranscriptLabel}</span>
- </Button>
- </div>
- </div>
-
- {/* ── Timeline progress bar ─────────────────────────────── */}
- {displayItems.length > 0 && (
- <div className="border-b px-4 py-2.5 shrink-0">
- <TimelineBar
- items={displayItems}
- selectedSeq={selectedSeq}
- onSegmentClick={handleSegmentClick}
- />
- </div>
+ {/* ── What the run produced ──────────────────────────────────── */}
+ <RunOutcomeRow outcome={outcome} branch={task.branch_name} />
+
+ {/* ── Where the time went ────────────────────────────────────── */}
+ {showTimeline && lanes && (
+ <RunTimeline
+ lanes={lanes}
+ toolKinds={toolKinds}
+ selectedOffsetMs={selectedOffsetMs}
+ onSeek={handleSeek}
+ />
)}
{/* ── Optional header slot (e.g. webhook payload preview) ── */}
@@ -996,73 +968,176 @@ export function AgentTranscriptDialog({
</div>
)}
- {/* ── Event list ─────────────────────────────────────────── */}
- <div className="flex-1 min-h-0">
- {displayItems.length === 0 ? (
- <div className="flex items-center justify-center h-full text-body text-muted-foreground">
- {isAntigravityLiveEmpty ? (
- <div className="flex max-w-md items-center gap-2 px-4 text-center">
- <Clock className="h-4 w-4 shrink-0" />
- {t(($) => $.transcript.antigravity_live_unavailable)}
- </div>
- ) : isLive ? (
- <div className="flex items-center gap-2">
- <Loader2 className="h-4 w-4 animate-spin" />
- {t(($) => $.transcript.waiting_events)}
- </div>
- ) : (
- t(($) => $.transcript.no_data)
- )}
- </div>
- ) : (
- // Virtualized so a multi-thousand-event run mounts a bounded number
- // of DOM rows (#5733). Rows expand/collapse to variable heights;
- // Virtuoso re-measures them via ResizeObserver.
- <Virtuoso
- key={listEpoch}
- ref={virtuosoRef}
- style={{ height: "100%" }}
- data={displayItems}
- firstItemIndex={firstItemIndex}
- // Open a live chronological transcript pinned to the newest
- // event (#5921); the per-listEpoch remount re-applies this after
- // task / sort / filter changes. Completed tasks keep reading
- // from the top, and newest-first has its live end there already.
- initialTopMostItemIndex={
- isLive && sortDirection !== "newest_first"
- ? { index: "LAST", align: "end" }
- : 0
- }
- // Follow appended events while the reader is at the bottom;
- // scrolling up suspends the follow until they return (#5921).
- // Instant, not smooth: transcript flushes append several rows at
- // a time and a still-animating scroll makes the next evaluation
- // read "not at bottom", permanently dropping the follow.
- // Newest-first opts out — its growth is prepends, handled by the
- // scrollToIndex effect above.
- followOutput={(atBottom) =>
- isLive && sortDirection !== "newest_first" && atBottom ? "auto" : false
- }
- atBottomThreshold={FOLLOW_EDGE_THRESHOLD}
- atTopThreshold={FOLLOW_EDGE_THRESHOLD}
- // Back within the top zone (any way you got there) re-engages
- // the newest-first follow. Leaving it does NOT disengage:
- // anchored prepends leave the top zone on their own — only
- // accumulated user input may break the latch (transcript-follow.ts).
- atTopStateChange={(atTop) => followCtl.onAtTopChange(atTop)}
- scrollerRef={handleScrollerRef}
- computeItemKey={(_, item) => item.seq}
- components={LIST_COMPONENTS}
- itemContent={(_, item) => (
- <TranscriptEventRow
- item={item}
- isSelected={selectedSeq === item.seq}
- expanded={
- rowOverrides.get(item.seq) ?? traceEventDefaultExpanded(item, density)
- }
- onExpandedChange={(expanded) => handleRowExpandedChange(item.seq, expanded)}
+ {/* ── List toolbar: search left, the two menus right ── */}
+ <div className="flex items-center gap-2 border-b px-4 py-1.5 shrink-0">
+ <label className="flex h-7 min-w-0 max-w-xs flex-1 items-center gap-1.5 rounded-md bg-muted px-2 text-caption">
+ <Search aria-hidden className="h-3 w-3 shrink-0 text-faint-foreground" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t(($) => $.transcript.search_placeholder)}
+ aria-label={t(($) => $.transcript.search_placeholder)}
+ className="min-w-0 flex-1 bg-transparent text-caption outline-none placeholder:text-faint-foreground"
+ />
+ </label>
+ <span className="ml-auto shrink-0 whitespace-nowrap text-caption text-muted-foreground">
+ {activeFilterKeys.length > 0 || trimmedQuery.length > 0
+ ? t(($) => $.transcript.steps_filtered, {
+ shown: filteredSteps.length,
+ total: steps.length,
+ })
+ : t(($) => $.transcript.steps_count, { count: steps.length })}
+ </span>
+ {filterOptions.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant={activeFilterKeys.length > 0 ? "brand" : "ghost"}
+ size="sm"
+ aria-label={t(($) => $.transcript.filter)}
+ className={activeFilterKeys.length > 0 ? undefined : "text-muted-foreground"}
+ />
+ }
+ >
+ <Filter className="h-3 w-3" />
+ <span className="hidden sm:inline">{t(($) => $.transcript.filter)}</span>
+ {activeFilterKeys.length > 0 && (
+ <span className="ml-0.5 rounded-full bg-brand-foreground/20 px-1.5 py-0 text-micro font-medium tabular-nums">
+ {activeFilterKeys.length}
+ </span>
+ )}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto">
+ {filterOptions.map(([value, label]) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={selectedFilterKeys.includes(value)}
+ onCheckedChange={() => toggleFilterKey(value)}
+ >
+ {label}
+ </DropdownMenuCheckboxItem>
+ ))}
+ {selectedFilterKeys.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={clearFilters} className="text-muted-foreground">
+ {t(($) => $.transcript.clear_filters)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {/* Sort and copy are the run-level actions nobody needs on the way
+ in, so they live behind one overflow control instead of two
+ permanent buttons. */}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.transcript.more_actions)}
+ className="text-muted-foreground"
/>
- )}
+ }
+ >
+ <MoreHorizontal className="h-3.5 w-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuItem
+ onClick={() =>
+ handleSortDirectionChange(
+ sortDirection === "chronological" ? "newest_first" : "chronological",
+ )
+ }
+ >
+ {sortDirection === "chronological" ? (
+ <ArrowUpNarrowWide className="h-3.5 w-3.5" />
+ ) : (
+ <ArrowDownNarrowWide className="h-3.5 w-3.5" />
+ )}
+ {sortDirection === "chronological"
+ ? t(($) => $.transcript.sort_newest_first)
+ : t(($) => $.transcript.sort_chronological)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={handleCopyAll}>
+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
+ {copyTranscriptLabel}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {/* ── Steps, and the inspector when one is selected ───────────── */}
+ <div className="flex min-h-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col">
+ {displayRows.length === 0 ? (
+ <div className="flex h-full items-center justify-center text-body text-muted-foreground">
+ {isAntigravityLiveEmpty ? (
+ <div className="flex max-w-md items-center gap-2 px-4 text-center">
+ <Clock className="h-4 w-4 shrink-0" />
+ {t(($) => $.transcript.antigravity_live_unavailable)}
+ </div>
+ ) : isLive && steps.length === 0 ? (
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t(($) => $.transcript.waiting_events)}
+ </div>
+ ) : steps.length === 0 ? (
+ t(($) => $.transcript.no_data)
+ ) : (
+ t(($) => $.transcript.no_matches)
+ )}
+ </div>
+ ) : (
+ // Virtualized so a multi-thousand-step run mounts a bounded
+ // number of DOM rows (#5733).
+ <Virtuoso
+ key={listEpoch}
+ ref={virtuosoRef}
+ style={{ height: "100%" }}
+ data={displayRows}
+ firstItemIndex={firstItemIndex}
+ // Open a live chronological transcript pinned to the newest
+ // step (#5921); the per-listEpoch remount re-applies this after
+ // task / sort / filter changes.
+ initialTopMostItemIndex={
+ isLive && sortDirection !== "newest_first"
+ ? { index: "LAST", align: "end" }
+ : 0
+ }
+ followOutput={(atBottom) =>
+ isLive && sortDirection !== "newest_first" && atBottom ? "auto" : false
+ }
+ atBottomThreshold={FOLLOW_EDGE_THRESHOLD}
+ atTopThreshold={FOLLOW_EDGE_THRESHOLD}
+ atTopStateChange={(atTop) => followCtl.onAtTopChange(atTop)}
+ scrollerRef={handleScrollerRef}
+ computeItemKey={(_, row) => row.seq}
+ components={LIST_COMPONENTS}
+ itemContent={(_, row) => (
+ <TranscriptRow
+ row={row}
+ agentName={agentName || agentInfo?.name || ""}
+ agentId={task.agent_id}
+ runStartMs={runStartMs}
+ isLive={isLive}
+ selectedSeq={selectedSeq}
+ expanded={row.kind === "group" && expandedGroups.has(row.seq)}
+ onToggleGroup={handleToggleGroup}
+ onSelect={setSelectedSeq}
+ />
+ )}
+ />
+ )}
+ </div>
+ {selectedStep && (
+ <StepInspector
+ step={selectedStep}
+ runStartMs={runStartMs}
+ onClose={() => setSelectedSeq(null)}
/>
)}
</div>
@@ -1071,40 +1146,6 @@ export function AgentTranscriptDialog({
);
}
-// ─── Sort direction toggle ──────────────────────────────────────────────────
-
-interface SortDirectionToggleProps {
- value: TranscriptSortDirection;
- onChange: (dir: TranscriptSortDirection) => void;
- labels: { chronological: string; newestFirst: string; ariaLabel: string };
-}
-
-// Sort is a two-state toggle, not a mode picker: one button showing the
-// current direction that flips on click. Shares the toolbar button chassis so
-// it reads as the same control family as density/filter/copy — no tab strip.
-function SortDirectionToggle({ value, onChange, labels }: SortDirectionToggleProps) {
- const isChronological = value === "chronological";
- return (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onChange(isChronological ? "newest_first" : "chronological")}
- aria-label={labels.ariaLabel}
- title={labels.ariaLabel}
- className="text-muted-foreground"
- >
- {isChronological ? (
- <ArrowDownNarrowWide className="h-3 w-3" />
- ) : (
- <ArrowUpNarrowWide className="h-3 w-3" />
- )}
- <span className="hidden sm:inline">
- {isChronological ? labels.chronological : labels.newestFirst}
- </span>
- </Button>
- );
-}
-
// Provider slugs this view names differently from the runtime list. The daemon
// has no display-name override for Claude, so the shared formatter answers
// "Claude" — but a run's diagnostics have always named the tool "Claude Code",
@@ -1131,91 +1172,167 @@ function FactDot() {
);
}
-// ─── Timeline bar (colored segments) ────────────────────────────────────────
+// ─── Outcome row ────────────────────────────────────────────────────────────
-function TimelineBar({
- items,
- selectedSeq,
- onSegmentClick,
+/**
+ * What the run produced, above the evidence for it. For most readers this is
+ * the whole answer — "it touched these files and ran these commands" settles
+ * "can I trust this" without opening a single step.
+ *
+ * Renders nothing when the run produced nothing nameable; a row of zeroes
+ * would read as "it did nothing" rather than "we have nothing to summarize".
+ */
+function RunOutcomeRow({
+ outcome,
+ branch,
}: {
- items: TimelineItem[];
- selectedSeq: number | null;
- onSegmentClick: (seq: number) => void;
+ outcome: ReturnType<typeof buildRunOutcome>;
+ branch?: string | null;
}) {
- const segments: { startIdx: number; endIdx: number; color: EventColor; count: number }[] = [];
- let currentColor: EventColor | null = null;
- let currentStart = 0;
-
- for (let i = 0; i < items.length; i++) {
- const item = items[i]!;
- const color = getEventColor(item);
- if (color !== currentColor) {
- if (currentColor !== null) {
- segments.push({ startIdx: currentStart, endIdx: i - 1, color: currentColor, count: i - currentStart });
- }
- currentColor = color;
- currentStart = i;
- }
- }
- if (currentColor !== null) {
- segments.push({ startIdx: currentStart, endIdx: items.length - 1, color: currentColor, count: items.length - currentStart });
- }
+ const { t } = useT("agents");
+ if (!outcome) return null;
+ const chip = "inline-flex shrink-0 items-center gap-1.5 rounded-md border bg-surface px-2 py-1 text-caption";
return (
- <div className="flex gap-0.5 h-5 rounded overflow-hidden" role="navigation" aria-label="Timeline">
- {segments.map((seg) => {
- const isSelected = selectedSeq !== null && items.slice(seg.startIdx, seg.endIdx + 1).some((i) => i.seq === selectedSeq);
- const color = colorClasses[seg.color];
- const widthPercent = (seg.count / items.length) * 100;
-
- return (
- <button
- type="button"
- key={seg.startIdx}
- className={cn(
- "h-full transition-all duration-150 hover:opacity-80 relative group",
- isSelected ? color.bgActive : color.bg,
- "min-w-[4px]",
- )}
- style={{ width: `${Math.max(widthPercent, 0.5)}%` }}
- onClick={() => onSegmentClick(items[seg.startIdx]!.seq)}
- title={`${traceEventLabel(items[seg.startIdx]!)}${seg.count > 1 ? ` (+${seg.count - 1} more)` : ""}`}
- >
- <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 hidden group-hover:block z-10 pointer-events-none">
- <div className="rounded bg-popover border px-2 py-1 text-micro text-popover-foreground shadow-md whitespace-nowrap">
- {traceEventLabel(items[seg.startIdx]!)}
- {seg.count > 1 && <span className="text-muted-foreground ml-1">+{seg.count - 1}</span>}
- </div>
- </div>
- </button>
- );
- })}
+ <div className="flex shrink-0 items-center gap-2 overflow-hidden border-b bg-muted/40 px-4 py-1.5">
+ <span className="shrink-0 text-micro text-faint-foreground">
+ {t(($) => $.transcript.outcome_label)}
+ </span>
+ {outcome.paths.length > 0 && (
+ <span className={chip} title={outcome.paths.join("\n")}>
+ <FilePen aria-hidden className="h-3 w-3 text-muted-foreground" />
+ <span className="font-medium">
+ {t(($) => $.transcript.outcome_files, { count: outcome.paths.length })}
+ </span>
+ {outcome.addedLines > 0 && (
+ <span className="tabular-nums text-success">+{outcome.addedLines}</span>
+ )}
+ {outcome.removedLines > 0 && (
+ <span className="tabular-nums text-destructive">−{outcome.removedLines}</span>
+ )}
+ </span>
+ )}
+ {outcome.commandCount > 0 && (
+ <span className={chip}>
+ <Terminal aria-hidden className="h-3 w-3 text-muted-foreground" />
+ <span className="font-medium">
+ {t(($) => $.transcript.outcome_commands, { count: outcome.commandCount })}
+ </span>
+ </span>
+ )}
+ {branch && (
+ <span className={cn(chip, "min-w-0")}>
+ <GitBranch aria-hidden className="h-3 w-3 shrink-0 text-muted-foreground" />
+ <span className="truncate font-mono text-micro">{branch}</span>
+ </span>
+ )}
</div>
);
}
-// ─── Transcript event row ───────────────────────────────────────────────────
+// ─── Rows ───────────────────────────────────────────────────────────────────
-interface TranscriptEventRowProps {
- item: TimelineItem;
- isSelected: boolean;
+interface TranscriptRowProps {
+ row: TraceRow;
+ agentName: string;
+ agentId?: string;
+ runStartMs?: number;
+ isLive: boolean;
+ selectedSeq: number | null;
expanded: boolean;
- onExpandedChange: (expanded: boolean) => void;
+ onToggleGroup: (seq: number) => void;
+ onSelect: (seq: number) => void;
}
-const TranscriptEventRow = ({
- item,
- isSelected,
- expanded,
- onExpandedChange,
-}: TranscriptEventRowProps) => {
+function TranscriptRow(props: TranscriptRowProps) {
+ const { row } = props;
+ if (isGroupRow(row)) return <GroupRow {...props} row={row} />;
+ if (!isCallStep(row) && row.kind === "text") return <ProseRow {...props} row={row} />;
+ return <StepRow {...props} row={row} />;
+}
+
+/** The offset column: where in the run this happened. */
+function OffsetCell({ startedAt, runStartMs }: { startedAt?: string; runStartMs?: number }) {
+ const at = timeMs(startedAt);
+ const label = at !== undefined && runStartMs !== undefined ? formatOffset(at - runStartMs) : "";
+ return (
+ <span
+ className="w-11 shrink-0 pt-0.5 text-right font-mono text-micro tabular-nums text-faint-foreground"
+ title={startedAt ? new Date(startedAt).toLocaleString() : undefined}
+ >
+ {label}
+ </span>
+ );
+}
+
+function DurationCell({ ms, pending }: { ms?: number; pending?: boolean }) {
+ const { t } = useT("agents");
+ if (pending) {
+ return (
+ <span className="shrink-0 pt-0.5 text-micro text-info" title={t(($) => $.transcript.step_running)}>
+ <Loader2 aria-hidden className="h-3 w-3 animate-spin" />
+ <span className="sr-only">{t(($) => $.transcript.step_running)}</span>
+ </span>
+ );
+ }
+ if (ms === undefined) return <span className="w-12 shrink-0" />;
+ return (
+ <span className="w-12 shrink-0 pt-0.5 text-right font-mono text-micro tabular-nums text-faint-foreground">
+ {formatStepDuration(ms)}
+ </span>
+ );
+}
+
+/**
+ * The agent's own words, at body size and in reading measure.
+ *
+ * This is the layer inversion the redesign turns on: the report used to look
+ * exactly like a `Read`, so the one thing worth reading was the hardest thing
+ * to find. Prose is content and stays open; tool calls are evidence and fold.
+ */
+function ProseRow({
+ row,
+ agentName,
+ agentId,
+ runStartMs,
+}: TranscriptRowProps & { row: TraceMessageStep }) {
+ return (
+ <div className="group flex items-start gap-2 px-4 py-2.5">
+ <OffsetCell startedAt={row.startedAt} runStartMs={runStartMs} />
+ <span aria-hidden className="mt-1 w-0.5 self-stretch rounded-full bg-success" />
+ <div className="mt-0.5 shrink-0">
+ {agentId ? (
+ <ActorAvatar actorType="agent" actorId={agentId} size="sm" />
+ ) : (
+ <div className="flex h-5 w-5 items-center justify-center rounded-full bg-info/10 text-info">
+ <Bot className="h-3 w-3" />
+ </div>
+ )}
+ </div>
+ <div className="min-w-0 flex-1 pr-2">
+ {agentName && (
+ <div className="mb-0.5 text-caption font-semibold">{agentName}</div>
+ )}
+ <RichContent
+ content={row.item.content ?? ""}
+ density="compact"
+ className="transcript-prose max-w-[62rem]"
+ />
+ </div>
+ </div>
+ );
+}
+
+/** One call, one thinking block, or one error: a line, with its detail one
+ * click away in the inspector. */
+function StepRow({
+ row,
+ runStartMs,
+ isLive,
+ selectedSeq,
+ onSelect,
+}: TranscriptRowProps & { row: TraceStep }) {
const { t } = useT("agents");
- const kind = traceEventKind(item);
- const color = getEventColor(item);
- const label = traceEventLabel(item);
- // The presenter stays i18n-free, so the localizable phrasing is injected.
- // `extra` counts files beyond the named one, and is deliberately not called
- // `count`: i18next reads `count` as a plural selector.
const summaryLabels = useMemo<TraceSummaryLabels>(
() => ({
morePaths: (path, extraCount) =>
@@ -1223,401 +1340,329 @@ const TranscriptEventRow = ({
}),
[t],
);
- const summary = traceEventSummary(item, summaryLabels);
- const date = useMemo(
- () => (item.created_at ? new Date(item.created_at) : null),
- [item.created_at],
- );
- 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.
- const isProse = kind !== "tool_use" && kind !== "tool_result";
- const showInlineBody = isProse && hasDetail && expanded;
+ const call = isCallStep(row) ? row : null;
+ const label = call
+ ? call.tool || t(($) => $.transcript.kind_tool)
+ : row.kind === "thinking"
+ ? t(($) => $.transcript.kind_thinking)
+ : t(($) => $.transcript.kind_error);
+ const summary = call
+ ? callSummary(call, summaryLabels)
+ : firstLineOf((row as TraceMessageStep).item.content);
+ const pending = call !== null && isLive && !call.result;
+ const selected = selectedSeq === row.seq;
return (
- <div
+ <button
+ type="button"
+ onClick={() => onSelect(row.seq)}
+ aria-current={selected ? "true" : undefined}
className={cn(
- "group transition-colors",
- isSelected && "bg-accent/50",
- kind === "error" && "bg-destructive/5",
+ "group flex w-full items-start gap-2 px-4 py-1.5 text-left transition-colors",
+ selected ? "bg-brand/8" : "hover:bg-accent/40",
+ row.kind === "error" && "bg-destructive/5",
)}
>
- <Collapsible open={expanded} onOpenChange={onExpandedChange}>
- <div className="flex items-start gap-2 px-4 py-2">
- {/* Type label badge */}
- <span
- className={cn(
- "inline-flex items-center shrink-0 rounded px-1.5 py-0.5 text-micro font-medium mt-0.5 min-w-[60px] justify-center",
- colorClasses[color].label,
- )}
- >
- {item.type === "thinking" && <Brain className="h-3 w-3 mr-1 shrink-0" />}
- {item.type === "error" && <AlertCircle className="h-3 w-3 mr-1 shrink-0" />}
- {label}
- </span>
-
- {showInlineBody ? (
- <div className="flex flex-1 items-start gap-1.5 min-w-0">
- <CollapsibleTrigger
- aria-label={label}
- className="shrink-0 mt-0.5 cursor-pointer rounded p-0.5 text-faint-foreground transition-colors hover:text-foreground"
- >
- <ChevronRight className="h-3 w-3 rotate-90 transition-transform" />
- </CollapsibleTrigger>
- <div className="flex-1 min-w-0">
- {kind === "agent" ? (
- <RichContent
- content={item.content ?? ""}
- density="compact"
- className="transcript-prose"
- />
- ) : (
- <div
- className={cn(
- "whitespace-pre-wrap break-words text-caption leading-relaxed",
- kind === "error" ? "text-destructive" : "text-muted-foreground",
- )}
- >
- {item.content ?? ""}
- </div>
- )}
- </div>
- </div>
- ) : (
- <CollapsibleTrigger
- className={cn(
- "flex-1 text-left text-caption min-w-0 py-0.5 transition-colors",
- hasDetail ? "cursor-pointer hover:text-foreground" : "cursor-default",
- kind === "error" ? "text-destructive" : "text-muted-foreground",
- )}
- disabled={!hasDetail}
- >
- <div className="flex items-start gap-1.5">
- {hasDetail && (
- <ChevronRight
- className={cn(
- "h-3 w-3 shrink-0 mt-0.5 text-faint-foreground transition-transform",
- expanded && "rotate-90",
- )}
- />
- )}
- <span
- className={cn(
- "truncate",
- traceEventSummaryIsMono(kind) && summary && "font-mono text-micro",
- !summary && "text-muted-foreground",
- )}
- >
- {summary || t(($) => $.transcript.no_output)}
- </span>
- </div>
- </CollapsibleTrigger>
+ <OffsetCell startedAt={row.startedAt} runStartMs={runStartMs} />
+ <span
+ aria-hidden
+ className={cn(
+ "mt-0.5 w-0.5 self-stretch rounded-full",
+ selected ? "bg-brand" : row.kind === "error" ? "bg-destructive" : "bg-border",
+ )}
+ />
+ <StepIcon
+ step={row}
+ className={cn(
+ "mt-1 h-3 w-3 shrink-0",
+ row.kind === "error" ? "text-destructive" : "text-muted-foreground",
+ )}
+ />
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span
+ className={cn(
+ "shrink-0 text-caption font-medium",
+ row.kind === "error" ? "text-destructive" : "text-foreground",
+ )}
+ >
+ {label}
+ </span>
+ <span
+ className={cn(
+ "truncate text-micro text-muted-foreground",
+ call && "font-mono",
)}
+ >
+ {summary}
+ </span>
+ </span>
+ <DurationCell ms={call?.durationMs} pending={pending} />
+ </button>
+ );
+}
- {/* Seq number / index */}
- <span className="shrink-0 text-micro text-muted-foreground tabular-nums mt-1">
- #{item.seq}
- </span>
+/** Consecutive same-tool calls, folded to one line until asked. */
+function GroupRow({
+ row,
+ runStartMs,
+ selectedSeq,
+ expanded,
+ onToggleGroup,
+ onSelect,
+}: TranscriptRowProps & { row: TraceGroupRow }) {
+ const { t } = useT("agents");
+ const summaryLabels = useMemo<TraceSummaryLabels>(
+ () => ({
+ morePaths: (path, extraCount) =>
+ t(($) => $.transcript.patch_summary_more, { path, extra: extraCount }),
+ }),
+ [t],
+ );
- {/* Timestamp */}
- {date && (
- <span className="shrink-0 text-micro text-muted-foreground tabular-nums mt-1" title={date.toLocaleString()}>
- {date.toLocaleTimeString(undefined, {
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- })}
- </span>
+ return (
+ <div className={cn(selectedSeq !== null && row.steps.some((s) => s.seq === selectedSeq) && "bg-brand/5")}>
+ <button
+ type="button"
+ onClick={() => onToggleGroup(row.seq)}
+ aria-expanded={expanded}
+ className="group flex w-full items-start gap-2 px-4 py-1.5 text-left transition-colors hover:bg-accent/40"
+ >
+ <OffsetCell startedAt={row.startedAt} runStartMs={runStartMs} />
+ <span aria-hidden className="mt-0.5 w-0.5 self-stretch rounded-full bg-border" />
+ <ChevronRight
+ aria-hidden
+ className={cn(
+ "mt-1 h-3 w-3 shrink-0 text-faint-foreground transition-transform",
+ expanded && "rotate-90",
)}
+ />
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span className="shrink-0 text-caption font-medium">{row.tool}</span>
+ {/* Name the first thing it touched, not just how many: "Read · 4
+ calls" hides the one detail that makes a folded group scannable. */}
+ <span className="truncate font-mono text-micro text-muted-foreground">
+ {callSummary(row.steps[0]!, summaryLabels)}
+ </span>
+ <span className="shrink-0 text-micro text-faint-foreground">
+ {t(($) => $.transcript.group_calls, { count: row.steps.length })}
+ </span>
+ </span>
+ <DurationCell ms={row.durationMs} />
+ </button>
+ {expanded && (
+ <div className="ml-[4.4rem] border-l pl-3">
+ {row.steps.map((step) => (
+ <button
+ key={step.seq}
+ type="button"
+ onClick={() => onSelect(step.seq)}
+ className={cn(
+ "flex w-full items-baseline gap-2 rounded px-2 py-1 text-left text-micro transition-colors",
+ selectedSeq === step.seq ? "bg-brand/10" : "hover:bg-accent/40",
+ )}
+ >
+ <span className="truncate font-mono text-muted-foreground">
+ {callSummary(step, summaryLabels) || step.tool}
+ </span>
+ <span className="ml-auto shrink-0 font-mono tabular-nums text-faint-foreground">
+ {step.durationMs === undefined ? "" : formatStepDuration(step.durationMs)}
+ </span>
+ </button>
+ ))}
</div>
-
- {/* Expanded params/output for tool kinds — a quiet, borderless surface
- aligned to the content column. */}
- {!isProse && hasDetail && (
- <CollapsibleContent>
- <div className="px-4 pb-3">
- <div className="ml-[72px] rounded-md bg-muted/40">
- {detail.kind === "diff" ? (
- <DiffDetailSurface lines={detail.lines} path={detail.path} />
- ) : detail.kind === "patch" ? (
- <PatchDetailSurface files={detail.files} truncated={detail.truncated} />
- ) : 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>
- )}
- </Collapsible>
+ )}
</div>
);
-};
-
-// ─── Tool detail surface ────────────────────────────────────────────────────
+}
/**
- * Long content fades out behind a "show all" affordance instead of trapping a
- * nested scrollbar inside the virtualized list.
+ * The one line a call is worth in the list: what it was asked to do.
+ *
+ * Deliberately the call's argument, never the result — the result row is where
+ * base64 screenshots and 8KB command dumps used to land in the middle of the
+ * list. Only a call we never saw falls back to its output.
*/
-type HighlightedSides = Record<"add" | "remove" | "context", string[] | null> | null;
+function callSummary(step: TraceCallStep, labels: TraceSummaryLabels): string {
+ if (step.call) {
+ const summary = traceToolArgSummary(step.call.input, labels);
+ if (summary) return summary;
+ }
+ if (!step.result) return "";
+ if (readImageResult(step.result.output)) return "";
+ return traceEventSummary({ type: "tool_result", output: step.result.output });
+}
+
+function firstLineOf(value: string | undefined): string {
+ return value?.split("\n").find((line) => line.trim().length > 0) ?? "";
+}
+
+// ─── Inspector ──────────────────────────────────────────────────────────────
/**
- * 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.
+ * The evidence for one step, opened on demand.
+ *
+ * Input and result are stacked rather than tabbed: at this width both fit, and
+ * a tab would hide half the evidence behind a click to save nothing.
*/
-function renderDiffRows(lines: TraceDiffLine[], highlighted: HighlightedSides) {
- const cursor: Record<"add" | "remove" | "context", number> = { add: 0, remove: 0, context: 0 };
+function StepInspector({
+ step,
+ runStartMs,
+ onClose,
+}: {
+ step: TraceStep;
+ runStartMs?: number;
+ onClose: () => void;
+}) {
+ const { t } = useT("agents");
+ const [copied, setCopied] = useState(false);
- 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-faint-foreground" aria-hidden>
- {" ⋯"}
- </div>
- );
+ const at = timeMs(step.startedAt);
+ const offset = at !== undefined && runStartMs !== undefined ? formatOffset(at - runStartMs) : null;
+
+ const call = isCallStep(step) ? step : null;
+ const message = call ? null : (step as TraceMessageStep);
+
+ const handleCopy = useCallback(() => {
+ const parts: string[] = [];
+ if (call) {
+ if (call.call) parts.push(traceEventCopyText(call.call));
+ if (call.result) parts.push(traceEventCopyText(call.result));
+ } else if (message) {
+ parts.push(traceEventCopyText(message.item));
}
+ void copyText(redactSecrets(parts.join("\n\n"))).then((ok) => {
+ if (!ok) return;
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ });
+ }, [call, message]);
- const kind = line.kind;
- const html = highlighted?.[kind]?.[cursor[kind]];
- cursor[kind] += 1;
+ const title =
+ call
+ ? call.tool || t(($) => $.transcript.kind_tool)
+ : step.kind === "thinking"
+ ? t(($) => $.transcript.kind_thinking)
+ : t(($) => $.transcript.kind_error);
- 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",
- kind === "add" && "text-success",
- kind === "remove" && "text-destructive",
+ return (
+ <aside className="flex w-[26rem] shrink-0 flex-col border-l bg-muted/25">
+ <div className="flex items-center gap-2 border-b px-3 py-2">
+ <StepIcon step={step} className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="shrink-0 text-label font-semibold">{title}</span>
+ <span className="flex min-w-0 flex-1 items-center gap-1.5 text-micro text-muted-foreground">
+ {offset && <span className="font-mono tabular-nums">{offset}</span>}
+ {call?.durationMs !== undefined && (
+ <>
+ <FactDot />
+ <span className="font-mono tabular-nums">{formatStepDuration(call.durationMs)}</span>
+ </>
)}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={handleCopy}
+ aria-label={t(($) => $.transcript.copy_step)}
+ title={t(($) => $.transcript.copy_step)}
+ className="shrink-0 text-muted-foreground"
+ >
+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onClose}
+ aria-label={t(($) => $.transcript.close_step)}
+ className="shrink-0 text-muted-foreground"
>
- {kind === "add" ? "+" : kind === "remove" ? "-" : " "}
- </span>{" "}
- {html === undefined ? (
- redactSecrets(line.text)
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {call ? (
+ <>
+ {call.call && (
+ <InspectorSection label={t(($) => $.transcript.step_input)}>
+ <StepBody item={call.call} />
+ </InspectorSection>
+ )}
+ {call.result && (
+ <InspectorSection label={t(($) => $.transcript.step_result)}>
+ <StepBody item={call.result} />
+ </InspectorSection>
+ )}
+ </>
) : (
- // 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 }} />
+ <InspectorSection label={title}>
+ <ToolDetailSurface text={redactSecrets(message?.item.content ?? "")} />
+ </InspectorSection>
)}
</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-micro text-success">+{lineCount}</div>
- <ToolDetailSurface text={redactSecrets(text)} language={languageForPath(path)} />
- </div>
+ </aside>
);
}
-/**
- * A multi-file patch: one section per file, each reusing the single-file
- * surfaces. Codex's `patch_apply` routinely touches several files in one call,
- * so collapsing them into a single body would lose which change belongs where.
- */
-function PatchDetailSurface({
- files,
- truncated,
-}: {
- files: TracePatchFile[];
- truncated: boolean;
-}) {
- const { t } = useT("agents");
+function InspectorSection({ label, children }: { label: string; children: React.ReactNode }) {
return (
- <div className="divide-y divide-border/40">
- {files.map((file, index) => (
- // Transcript events are immutable once persisted, so index is stable.
- <div key={`${file.path}:${index}`}>
- <div className="flex items-center gap-2 px-3 pt-2 font-mono text-micro">
- {file.changeKind && (
- <span
- className={cn(
- "shrink-0 uppercase",
- file.changeKind === "add" && "text-success",
- file.changeKind === "delete" && "text-destructive",
- file.changeKind === "update" && "text-muted-foreground",
- )}
- >
- {file.changeKind}
- </span>
- )}
- <span className="truncate text-muted-foreground">{file.path}</span>
- {file.movePath && (
- <>
- <span className="shrink-0 text-faint-foreground" aria-hidden>
- →
- </span>
- <span className="truncate text-muted-foreground">{file.movePath}</span>
- </>
- )}
- </div>
- {file.body.kind === "diff" ? (
- <DiffDetailSurface lines={file.body.lines} path={file.path} />
- ) : file.body.kind === "file" ? (
- <FileWriteSurface
- text={file.body.text}
- lineCount={file.body.lineCount}
- path={file.path}
- />
- ) : (
- <div className="px-3 pb-2 pt-1 font-mono text-micro text-muted-foreground">
- {file.truncated
- ? t(($) => $.transcript.patch_body_truncated)
- : t(($) => $.transcript.patch_no_content)}
- </div>
- )}
- </div>
- ))}
- {truncated && (
- <div className="px-3 py-2 font-mono text-micro text-muted-foreground">
- {t(($) => $.transcript.patch_truncated)}
- </div>
- )}
- </div>
+ <section className="border-b last:border-b-0">
+ <h3 className="px-3 pt-2 text-micro font-medium uppercase tracking-wide text-faint-foreground">
+ {label}
+ </h3>
+ <div className="px-1 pb-2">{children}</div>
+ </section>
);
}
-/**
- * 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 }) {
+/** One payload, rendered as what it is. */
+function StepBody({ item }: { item: TimelineItem }) {
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]);
+ const detail = useMemo(() => traceEventDetail(item), [item]);
+ const image = useMemo(() => readImageResult(item.output), [item.output]);
- return (
- <div className="relative">
- <div className="flex items-center gap-2 px-3 pt-2 font-mono text-micro text-muted-foreground">
- {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-micro 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-micro text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
- >
- {t(($) => $.transcript.show_all)}
- </button>
- </div>
- )}
- </div>
- );
+ // A screenshot is a picture, not a 200KB base64 string in a <pre>.
+ if (image) {
+ return (
+ <figure className="px-2 py-1">
+ <img
+ src={`data:${image.mediaType};base64,${image.base64}`}
+ alt={t(($) => $.transcript.image_result)}
+ className="max-h-80 w-full rounded-md border object-contain"
+ />
+ <figcaption className="pt-1 text-micro text-faint-foreground">
+ {t(($) => $.transcript.image_result)} · {formatBytes(base64ByteLength(image.base64))}
+ </figcaption>
+ </figure>
+ );
+ }
+
+ switch (detail.kind) {
+ case "diff":
+ return <DiffDetailSurface lines={detail.lines} path={detail.path} />;
+ case "patch":
+ return <PatchDetailSurface files={detail.files} truncated={detail.truncated} />;
+ case "file":
+ return (
+ <FileWriteSurface text={detail.text} lineCount={detail.lineCount} path={detail.path} />
+ );
+ default: {
+ const text = detail.text;
+ const clipped =
+ text.length > 8000 ? `${redactSecrets(text.slice(0, 8000))}\n... (truncated)` : redactSecrets(text);
+ const path = item.type === "tool_use" ? readPathFromInput(item.input) : undefined;
+ return <ToolDetailSurface text={clipped} language={path ? languageForPath(path) : undefined} />;
+ }
+ }
}
-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]);
+function readPathFromInput(input: Record<string, unknown> | undefined): string | undefined {
+ if (!input) return undefined;
+ const path = input.file_path ?? input.path;
+ return typeof path === "string" ? path : undefined;
+}
- return (
- <div className="relative">
- <pre
- className={cn(
- "transcript-code p-3 font-mono text-micro text-muted-foreground whitespace-pre-wrap break-all",
- isLong && !showAll && "max-h-52 overflow-hidden",
- )}
- >
- {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)}
- // 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-micro text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
- >
- {t(($) => $.transcript.show_all)}
- </button>
- </div>
- )}
- </div>
- );
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
diff --git a/packages/views/common/task-transcript/build-steps.test.ts b/packages/views/common/task-transcript/build-steps.test.ts
new file mode 100644
index 0000000000..666f803458
--- /dev/null
+++ b/packages/views/common/task-transcript/build-steps.test.ts
@@ -0,0 +1,290 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildLanes,
+ buildSteps,
+ groupSteps,
+ rowCalls,
+ shouldShowTimeline,
+ timelineTicks,
+ toolKindTotals,
+ type TraceCallStep,
+} from "./build-steps";
+import type { TimelineItem } from "./build-timeline";
+
+const T0 = "2026-08-15T10:00:00.000Z";
+function at(seconds: number): string {
+ return new Date(Date.parse(T0) + seconds * 1000).toISOString();
+}
+
+let seq = 0;
+function call(tool: string, seconds: number, input?: Record<string, unknown>): TimelineItem {
+ return { seq: ++seq, type: "tool_use", tool, input, created_at: at(seconds) };
+}
+function result(tool: string, seconds: number, output = "ok"): TimelineItem {
+ return { seq: ++seq, type: "tool_result", tool, output, created_at: at(seconds) };
+}
+function text(seconds: number, content = "done"): TimelineItem {
+ return { seq: ++seq, type: "text", content, created_at: at(seconds) };
+}
+
+describe("buildSteps", () => {
+ it("folds a call and its result into one step", () => {
+ const steps = buildSteps([call("Bash", 0), result("Bash", 4)]);
+
+ expect(steps).toHaveLength(1);
+ const step = steps[0] as TraceCallStep;
+ expect(step.kind).toBe("call");
+ expect(step.tool).toBe("Bash");
+ expect(step.call).toBeDefined();
+ expect(step.result).toBeDefined();
+ expect(step.durationMs).toBe(4000);
+ });
+
+ it("pairs same-tool calls FIFO when two are in flight", () => {
+ const first = call("Bash", 0, { command: "one" });
+ const second = call("Bash", 1, { command: "two" });
+ const steps = buildSteps([
+ first,
+ second,
+ result("Bash", 5, "first done"),
+ result("Bash", 9, "second done"),
+ ]) as TraceCallStep[];
+
+ expect(steps).toHaveLength(2);
+ expect(steps[0]!.call?.input).toEqual({ command: "one" });
+ expect(steps[0]!.result?.output).toBe("first done");
+ expect(steps[1]!.result?.output).toBe("second done");
+ });
+
+ it("does not pair across different tools", () => {
+ const steps = buildSteps([call("Read", 0), result("Bash", 1)]) as TraceCallStep[];
+
+ expect(steps).toHaveLength(2);
+ expect(steps[0]!.result).toBeUndefined();
+ expect(steps[1]!.call).toBeUndefined();
+ expect(steps[1]!.result).toBeDefined();
+ });
+
+ it("keeps a call with no result yet — a running call is not a dropped one", () => {
+ const steps = buildSteps([call("Bash", 0)]) as TraceCallStep[];
+
+ expect(steps).toHaveLength(1);
+ expect(steps[0]!.result).toBeUndefined();
+ expect(steps[0]!.durationMs).toBeUndefined();
+ });
+
+ it("keeps prose, thinking and errors as their own steps", () => {
+ const steps = buildSteps([
+ { seq: 1, type: "thinking", content: "hmm", created_at: at(0) },
+ { seq: 2, type: "text", content: "here is the plan", created_at: at(1) },
+ { seq: 3, type: "error", content: "boom", created_at: at(2) },
+ ]);
+
+ expect(steps.map((s) => s.kind)).toEqual(["thinking", "text", "error"]);
+ });
+
+ it("leaves duration undefined rather than guessing when a timestamp is missing", () => {
+ const steps = buildSteps([
+ { seq: 1, type: "tool_use", tool: "Bash" },
+ { seq: 2, type: "tool_result", tool: "Bash", output: "ok" },
+ ]) as TraceCallStep[];
+
+ expect(steps[0]!.durationMs).toBeUndefined();
+ });
+});
+
+describe("groupSteps", () => {
+ it("folds three or more consecutive same-tool calls", () => {
+ const steps = buildSteps([
+ call("Read", 0),
+ result("Read", 1),
+ call("Read", 2),
+ result("Read", 3),
+ call("Read", 4),
+ result("Read", 5),
+ ]);
+
+ const rows = groupSteps(steps);
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.kind).toBe("group");
+ expect(rowCalls(rows[0]!)).toHaveLength(3);
+ expect(rows[0]!.kind === "group" && rows[0]!.durationMs).toBe(5000);
+ });
+
+ it("leaves two consecutive calls alone — two commands are two things to read", () => {
+ const steps = buildSteps([
+ call("Bash", 0),
+ result("Bash", 1),
+ call("Bash", 2),
+ result("Bash", 3),
+ ]);
+
+ expect(groupSteps(steps).map((r) => r.kind)).toEqual(["call", "call"]);
+ });
+
+ it("never folds shell commands — five commands are five things that happened", () => {
+ const items: TimelineItem[] = [];
+ for (let i = 0; i < 5; i++) {
+ items.push(
+ { seq: ++seq, type: "tool_use", tool: "Bash", input: { command: `step ${i}` }, created_at: at(i * 10) },
+ { seq: ++seq, type: "tool_result", tool: "Bash", output: "ok", created_at: at(i * 10 + 1) },
+ );
+ }
+
+ const rows = groupSteps(buildSteps(items));
+
+ expect(rows).toHaveLength(5);
+ expect(rows.every((row) => row.kind === "call")).toBe(true);
+ });
+
+ it("does not group across a different tool or across prose", () => {
+ const steps = buildSteps([
+ call("Read", 0),
+ result("Read", 1),
+ call("Read", 2),
+ result("Read", 3),
+ text(4),
+ call("Read", 5),
+ result("Read", 6),
+ ]);
+
+ expect(groupSteps(steps).map((r) => r.kind)).toEqual(["call", "call", "text", "call"]);
+ });
+});
+
+describe("buildLanes", () => {
+ it("splits tool spans from the model gaps that surround them", () => {
+ // 0-10 model, 10-40 tool, 40-60 model.
+ const steps = buildSteps([call("Bash", 10), result("Bash", 40)]);
+
+ const lanes = buildLanes(steps, at(0), at(60))!;
+
+ expect(lanes.tool).toEqual([{ startMs: 10_000, durationMs: 30_000, kind: "tool" }]);
+ expect(lanes.model).toEqual([
+ { startMs: 0, durationMs: 10_000, kind: "think" },
+ { startMs: 40_000, durationMs: 20_000, kind: "think" },
+ ]);
+ expect(lanes.toolMs).toBe(30_000);
+ expect(lanes.modelMs).toBe(30_000);
+ expect(lanes.totalMs).toBe(60_000);
+ });
+
+ it("marks the gap a report landed in", () => {
+ const steps = buildSteps([call("Bash", 0), result("Bash", 10), text(20)]);
+
+ const lanes = buildLanes(steps, at(0), at(30))!;
+
+ expect(lanes.model).toEqual([{ startMs: 10_000, durationMs: 20_000, kind: "report" }]);
+ });
+
+ it("marks the gap an error landed in, outranking a report", () => {
+ const steps = buildSteps([
+ call("Bash", 0),
+ result("Bash", 5),
+ text(10),
+ { seq: 99, type: "error", content: "boom", created_at: at(12) },
+ ]);
+
+ const lanes = buildLanes(steps, at(0), at(20))!;
+
+ expect(lanes.model.at(-1)!.kind).toBe("error");
+ });
+
+ it("merges overlapping tool spans so parallel calls are not double-counted", () => {
+ const steps = buildSteps([
+ call("Bash", 0),
+ call("Bash", 5),
+ result("Bash", 20),
+ result("Bash", 30),
+ ]);
+
+ const lanes = buildLanes(steps, at(0), at(30))!;
+
+ expect(lanes.tool).toHaveLength(1);
+ expect(lanes.toolMs).toBe(30_000);
+ expect(lanes.modelMs).toBe(0);
+ });
+
+ it("returns null when no event carries a timestamp", () => {
+ const steps = buildSteps([
+ { seq: 1, type: "tool_use", tool: "Bash" },
+ { seq: 2, type: "tool_result", tool: "Bash", output: "ok" },
+ ]);
+
+ expect(buildLanes(steps, undefined, undefined)).toBeNull();
+ });
+
+ it("returns null for a zero-length run rather than dividing by it", () => {
+ const steps = buildSteps([call("Bash", 0), result("Bash", 0)]);
+
+ expect(buildLanes(steps, at(0), at(0))).toBeNull();
+ });
+});
+
+describe("timelineTicks", () => {
+ it("keeps tick density constant as the track is zoomed", () => {
+ const total = 30 * 60_000;
+
+ // Same run, four times the width: four times the labels, so the on-screen
+ // spacing between them does not thin out.
+ expect(timelineTicks(total, 6).length).toBeLessThanOrEqual(7);
+ expect(timelineTicks(total, 24).length).toBeGreaterThan(timelineTicks(total, 6).length);
+ });
+
+ it("returns nothing for a run with no length", () => {
+ expect(timelineTicks(0)).toEqual([]);
+ });
+});
+
+describe("toolKindTotals", () => {
+ it("splits tool time by what the calls were doing", () => {
+ const steps = buildSteps([
+ { seq: ++seq, type: "tool_use", tool: "Bash", input: { command: "pnpm test" }, created_at: at(0) },
+ { seq: ++seq, type: "tool_result", tool: "Bash", output: "ok", created_at: at(60) },
+ { seq: ++seq, type: "tool_use", tool: "Edit", input: { file_path: "a.ts", old_string: "a", new_string: "b" }, created_at: at(60) },
+ { seq: ++seq, type: "tool_result", tool: "Edit", output: "ok", created_at: at(62) },
+ { seq: ++seq, type: "tool_use", tool: "Read", input: { file_path: "b.ts" }, created_at: at(62) },
+ { seq: ++seq, type: "tool_result", tool: "Read", output: "ok", created_at: at(63) },
+ ]);
+
+ // The lopsidedness is the point: one kind dominates, which is why this is
+ // a tooltip and not three more lanes.
+ expect(toolKindTotals(steps)).toEqual({
+ command: 60_000,
+ write: 2_000,
+ read: 1_000,
+ other: 0,
+ });
+ });
+});
+
+describe("shouldShowTimeline", () => {
+ function longRun(stepCount: number, seconds: number) {
+ const items: TimelineItem[] = [];
+ for (let i = 0; i < stepCount; i++) {
+ const start = (seconds / stepCount) * i;
+ items.push(call("Bash", start), result("Bash", start + 1));
+ }
+ return buildSteps(items);
+ }
+
+ it("shows for a long run with many steps", () => {
+ const steps = longRun(10, 600);
+ expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(600)))).toBe(true);
+ });
+
+ it("hides for a short run — a handful of bars says less than the row durations", () => {
+ const steps = longRun(3, 600);
+ expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(600)))).toBe(false);
+ });
+
+ it("hides for a fast run even with many steps", () => {
+ const steps = longRun(10, 20);
+ expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(20)))).toBe(false);
+ });
+
+ it("hides when lanes could not be built", () => {
+ expect(shouldShowTimeline(longRun(10, 600), null)).toBe(false);
+ });
+});
diff --git a/packages/views/common/task-transcript/build-steps.ts b/packages/views/common/task-transcript/build-steps.ts
new file mode 100644
index 0000000000..ee76f7645d
--- /dev/null
+++ b/packages/views/common/task-transcript/build-steps.ts
@@ -0,0 +1,407 @@
+import type { TimelineItem } from "./build-timeline";
+
+/**
+ * A run's steps, derived from the flat event stream.
+ *
+ * The stream stores a tool call and its result as two independent rows
+ * (`tool_use` then `tool_result`), which is how the transcript ended up twice
+ * as long as the work it describes: a 75-call run rendered 150 rows, and the
+ * output row was where raw base64 and 8KB command dumps landed. A step folds
+ * the pair back together, so one call reads as one line and its result is that
+ * line's detail.
+ *
+ * Pairing is positional because the events carry no call id. `agent.Message`
+ * has `CallID` all the way to the daemon, but `TaskMessageData` drops it before
+ * the report and `task_message` has no column for it — until that lands, a
+ * result belongs to the oldest still-open call with the same tool name.
+ */
+
+/** One tool call. Either side can be missing: a call still running has no
+ * result yet, and a stream that reconnected mid-flight can deliver a result
+ * whose call was never recorded. */
+export interface TraceCallStep {
+ kind: "call";
+ /** Ordering key: the call's seq, or the result's when the call is missing. */
+ seq: number;
+ tool: string;
+ call?: TimelineItem;
+ result?: TimelineItem;
+ startedAt?: string;
+ endedAt?: string;
+ /** Wall-clock ms between call and result. Undefined when either side is
+ * missing a timestamp — never guessed. */
+ durationMs?: number;
+}
+
+/** Agent prose, model thinking, or an error: one message, nothing to pair. */
+export interface TraceMessageStep {
+ kind: "text" | "thinking" | "error";
+ seq: number;
+ item: TimelineItem;
+ startedAt?: string;
+}
+
+export type TraceStep = TraceCallStep | TraceMessageStep;
+
+/** Consecutive same-tool calls, folded. Expands back to its members. */
+export interface TraceGroupRow {
+ kind: "group";
+ seq: number;
+ tool: string;
+ steps: TraceCallStep[];
+ startedAt?: string;
+ endedAt?: string;
+ durationMs?: number;
+}
+
+export type TraceRow = TraceStep | TraceGroupRow;
+
+/**
+ * How many consecutive same-tool calls it takes to fold into one row.
+ *
+ * Three, not two: two file reads are still two lines worth reading, five are
+ * one act.
+ */
+export const MIN_GROUP_SIZE = 3;
+
+/**
+ * A shell call never folds, however many run in a row.
+ *
+ * Reading a run, `pnpm typecheck` and `pnpm exec playwright test` are two
+ * different things that happened; "Bash · 5 calls" hides exactly what the
+ * reader came for, and a group duration spanning the gaps between them reads
+ * as one ten-minute command. Keyed on the input carrying a `command` string
+ * rather than a tool-name allowlist, so it holds for every backend.
+ */
+function isShellCall(step: TraceCallStep): boolean {
+ return typeof step.call?.input?.command === "string";
+}
+
+function timeMs(iso: string | undefined): number | undefined {
+ if (!iso) return undefined;
+ const ms = new Date(iso).getTime();
+ return Number.isFinite(ms) ? ms : undefined;
+}
+
+function durationBetween(start?: string, end?: string): number | undefined {
+ const a = timeMs(start);
+ const b = timeMs(end);
+ if (a === undefined || b === undefined) return undefined;
+ // Clamp rather than drop: the daemon flushes in 500ms batches, so a fast
+ // call can land with its result on the same tick or one tick earlier.
+ return Math.max(0, b - a);
+}
+
+/** Fold `tool_use` / `tool_result` pairs into single steps, in stream order. */
+export function buildSteps(items: TimelineItem[]): TraceStep[] {
+ const steps: TraceStep[] = [];
+ // Open calls per tool, oldest first. FIFO rather than nearest-preceding:
+ // when a provider runs two calls of the same tool in parallel it returns
+ // them in call order more often than in reverse.
+ const open = new Map<string, TraceCallStep[]>();
+
+ for (const item of items) {
+ if (item.type === "tool_use") {
+ const tool = item.tool ?? "";
+ const step: TraceCallStep = {
+ kind: "call",
+ seq: item.seq,
+ tool,
+ call: item,
+ startedAt: item.created_at,
+ };
+ steps.push(step);
+ const queue = open.get(tool);
+ if (queue) queue.push(step);
+ else open.set(tool, [step]);
+ continue;
+ }
+
+ if (item.type === "tool_result") {
+ const tool = item.tool ?? "";
+ const pending = open.get(tool)?.shift();
+ if (pending) {
+ pending.result = item;
+ pending.endedAt = item.created_at;
+ pending.durationMs = durationBetween(pending.startedAt, item.created_at);
+ continue;
+ }
+ // Orphan result: keep it as a step of its own so no output is dropped.
+ steps.push({
+ kind: "call",
+ seq: item.seq,
+ tool,
+ result: item,
+ startedAt: item.created_at,
+ endedAt: item.created_at,
+ });
+ continue;
+ }
+
+ steps.push({
+ kind: item.type,
+ seq: item.seq,
+ item,
+ startedAt: item.created_at,
+ });
+ }
+
+ return steps;
+}
+
+/** Fold runs of `MIN_GROUP_SIZE`+ consecutive same-tool calls into group rows. */
+export function groupSteps(steps: TraceStep[]): TraceRow[] {
+ const rows: TraceRow[] = [];
+ let run: TraceCallStep[] = [];
+
+ const flush = () => {
+ if (run.length === 0) return;
+ if (run.length < MIN_GROUP_SIZE) {
+ rows.push(...run);
+ } else {
+ const first = run[0]!;
+ const last = run[run.length - 1]!;
+ rows.push({
+ kind: "group",
+ seq: first.seq,
+ tool: first.tool,
+ steps: run,
+ startedAt: first.startedAt,
+ endedAt: last.endedAt,
+ durationMs: durationBetween(first.startedAt, last.endedAt),
+ });
+ }
+ run = [];
+ };
+
+ for (const step of steps) {
+ if (
+ step.kind === "call" &&
+ !isShellCall(step) &&
+ (run.length === 0 || run[0]!.tool === step.tool)
+ ) {
+ run.push(step);
+ continue;
+ }
+ flush();
+ if (step.kind === "call") run.push(step);
+ else rows.push(step);
+ }
+ flush();
+
+ return rows;
+}
+
+// `TraceMessageStep` carries three kinds on one interface, so a `kind` check
+// alone narrows the property without dropping the constituent. These predicates
+// are what let callers switch on a row and get a usable type back.
+export function isGroupRow(row: TraceRow): row is TraceGroupRow {
+ return row.kind === "group";
+}
+
+export function isCallStep(row: TraceRow): row is TraceCallStep {
+ return row.kind === "call";
+}
+
+export function isMessageStep(row: TraceRow): row is TraceMessageStep {
+ return row.kind === "text" || row.kind === "thinking" || row.kind === "error";
+}
+
+/** Every call inside a row, so a group and a lone call read the same way. */
+export function rowCalls(row: TraceRow): TraceCallStep[] {
+ if (row.kind === "group") return row.steps;
+ return row.kind === "call" ? [row] : [];
+}
+
+// ─── Lanes ──────────────────────────────────────────────────────────────────
+
+export type LaneSegmentKind = "tool" | "think" | "report" | "error";
+
+export interface LaneSegment {
+ /** ms from the run's start. */
+ startMs: number;
+ durationMs: number;
+ kind: LaneSegmentKind;
+}
+
+export interface TraceLanes {
+ /** Model turns: the complement of the tool lane. */
+ model: LaneSegment[];
+ tool: LaneSegment[];
+ modelMs: number;
+ toolMs: number;
+ totalMs: number;
+}
+
+interface Interval {
+ start: number;
+ end: number;
+}
+
+function mergeIntervals(intervals: Interval[]): Interval[] {
+ const sorted = [...intervals].sort((a, b) => a.start - b.start);
+ const out: Interval[] = [];
+ for (const interval of sorted) {
+ const prev = out[out.length - 1];
+ if (prev && interval.start <= prev.end) {
+ prev.end = Math.max(prev.end, interval.end);
+ continue;
+ }
+ out.push({ ...interval });
+ }
+ return out;
+}
+
+/**
+ * Two lanes: what the tools were doing, and what the model was doing.
+ *
+ * The model lane is derived as the complement of the tool lane rather than
+ * from the model's own events, because that is the only honest source we have
+ * — a `text` or `thinking` row carries one arrival timestamp, not a span. The
+ * gaps between tool calls ARE the model's time, which is what makes the
+ * "28 minutes went where" question answerable at all.
+ *
+ * Returns null when the events carry no usable timestamps; callers drop the
+ * timeline entirely rather than draw an axis that means nothing.
+ */
+export function buildLanes(
+ steps: TraceStep[],
+ runStart: string | undefined,
+ runEnd: string | undefined,
+): TraceLanes | null {
+ const stamps = steps
+ .flatMap((step) => [timeMs(step.startedAt), timeMs(step.kind === "call" ? step.endedAt : undefined)])
+ .filter((ms): ms is number => ms !== undefined);
+ if (stamps.length === 0) return null;
+
+ const startMs = Math.min(timeMs(runStart) ?? Infinity, ...stamps);
+ const endMs = Math.max(timeMs(runEnd) ?? -Infinity, ...stamps);
+ const totalMs = endMs - startMs;
+ if (!Number.isFinite(totalMs) || totalMs <= 0) return null;
+
+ const calls: Interval[] = [];
+ for (const step of steps) {
+ if (step.kind !== "call") continue;
+ const start = timeMs(step.startedAt);
+ const end = timeMs(step.endedAt);
+ if (start === undefined || end === undefined || end <= start) continue;
+ calls.push({
+ start: Math.max(startMs, start),
+ end: Math.min(endMs, end),
+ });
+ }
+
+ const merged = mergeIntervals(calls.filter((c) => c.end > c.start));
+ const tool: LaneSegment[] = merged.map((c) => ({
+ startMs: c.start - startMs,
+ durationMs: c.end - c.start,
+ kind: "tool",
+ }));
+
+ // Model segments fill every gap the tools left, including the head and tail.
+ const model: LaneSegment[] = [];
+ let cursor = startMs;
+ const pushModel = (from: number, to: number) => {
+ if (to <= from) return;
+ model.push({ startMs: from - startMs, durationMs: to - from, kind: kindForGap(steps, from, to) });
+ };
+ for (const interval of merged) {
+ pushModel(cursor, interval.start);
+ cursor = Math.max(cursor, interval.end);
+ }
+ pushModel(cursor, endMs);
+
+ return {
+ model,
+ tool,
+ modelMs: model.reduce((sum, s) => sum + s.durationMs, 0),
+ toolMs: tool.reduce((sum, s) => sum + s.durationMs, 0),
+ totalMs,
+ };
+}
+
+/**
+ * What the model was doing in this gap, judged by the messages that landed in
+ * it: an error outranks a report, a report outranks plain thinking. Colour
+ * therefore carries state (fine / delivered / failed), never taxonomy — the
+ * token set has no categorical ramp to spend on five event types.
+ */
+function kindForGap(steps: TraceStep[], from: number, to: number): LaneSegmentKind {
+ let kind: LaneSegmentKind = "think";
+ for (const step of steps) {
+ if (step.kind === "call") continue;
+ const at = timeMs(step.startedAt);
+ if (at === undefined || at < from || at > to) continue;
+ if (step.kind === "error") return "error";
+ if (step.kind === "text") kind = "report";
+ }
+ return kind;
+}
+
+/**
+ * Axis ticks at a round interval.
+ *
+ * `maxTicks` scales with zoom: a timeline stretched to 4x its container has
+ * four screenfuls to label, so it needs four times the ticks to keep the same
+ * on-screen density.
+ */
+export function timelineTicks(totalMs: number, maxTicks = 6): number[] {
+ if (!Number.isFinite(totalMs) || totalMs <= 0) return [];
+ const steps = [
+ 1_000, 5_000, 15_000, 30_000, 60_000, 2 * 60_000, 5 * 60_000, 10 * 60_000,
+ 15 * 60_000, 30 * 60_000, 60 * 60_000, 2 * 60 * 60_000, 6 * 60 * 60_000,
+ ];
+ const interval = steps.find((step) => totalMs / step <= maxTicks) ?? steps[steps.length - 1]!;
+ const ticks: number[] = [];
+ for (let at = 0; at < totalMs; at += interval) ticks.push(at);
+ ticks.push(totalMs);
+ return ticks;
+}
+
+/**
+ * How the tool lane's time splits by what the calls were doing.
+ *
+ * The lane itself stays whole: in a real run one kind dominates (commands run
+ * for minutes, reads and edits finish in milliseconds), so a lane per kind
+ * would draw three near-empty tracks to say what one line of text says. This
+ * is that line of text.
+ */
+export interface ToolKindTotals {
+ command: number;
+ write: number;
+ read: number;
+ other: number;
+}
+
+export function toolKindTotals(steps: TraceStep[]): ToolKindTotals {
+ const totals: ToolKindTotals = { command: 0, write: 0, read: 0, other: 0 };
+ for (const step of steps) {
+ if (step.kind !== "call" || step.durationMs === undefined) continue;
+ const input = step.call?.input;
+ const kind: keyof ToolKindTotals =
+ typeof input?.command === "string"
+ ? "command"
+ : typeof input?.old_string === "string" ||
+ typeof input?.content === "string" ||
+ input?.changes !== undefined
+ ? "write"
+ : typeof input?.file_path === "string" ||
+ typeof input?.path === "string" ||
+ typeof input?.pattern === "string" ||
+ typeof input?.query === "string"
+ ? "read"
+ : "other";
+ totals[kind] += step.durationMs;
+ }
+ return totals;
+}
+
+/** Below these, a timeline is chrome: it would render a handful of bars that
+ * say less than the durations already on each row. */
+export const TIMELINE_MIN_STEPS = 8;
+export const TIMELINE_MIN_MS = 60_000;
+
+export function shouldShowTimeline(steps: TraceStep[], lanes: TraceLanes | null): boolean {
+ if (!lanes) return false;
+ return steps.length >= TIMELINE_MIN_STEPS && lanes.totalMs >= TIMELINE_MIN_MS;
+}
diff --git a/packages/views/common/task-transcript/detail-surfaces.tsx b/packages/views/common/task-transcript/detail-surfaces.tsx
new file mode 100644
index 0000000000..800e6a7674
--- /dev/null
+++ b/packages/views/common/task-transcript/detail-surfaces.tsx
@@ -0,0 +1,270 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { cn } from "@multica/ui/lib/utils";
+import { redactSecrets } from "./redact";
+import type { TraceDiffLine, TracePatchFile } from "./trace-event-presenter";
+import { highlightBlock, highlightToLines, languageForPath } from "./diff-highlight";
+import { useT } from "../../i18n";
+import "../../editor/styles/code.css";
+import "./task-transcript.css";
+
+// Bodies for one step's input and result. Extracted from the transcript dialog
+// so the dialog file is about the run, and these are about rendering a payload.
+// ─── Tool detail surface ────────────────────────────────────────────────────
+
+/**
+ * Long content fades out behind a "show all" affordance instead of trapping a
+ * nested scrollbar inside the virtualized list.
+ */
+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.
+ */
+export 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-faint-foreground" 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",
+ 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.
+ */
+export function FileWriteSurface({
+ text,
+ lineCount,
+ path,
+}: {
+ text: string;
+ lineCount: number;
+ path: string;
+}) {
+ return (
+ <div>
+ <div className="px-3 pt-2 font-mono text-micro text-success">+{lineCount}</div>
+ <ToolDetailSurface text={redactSecrets(text)} language={languageForPath(path)} />
+ </div>
+ );
+}
+
+/**
+ * A multi-file patch: one section per file, each reusing the single-file
+ * surfaces. Codex's `patch_apply` routinely touches several files in one call,
+ * so collapsing them into a single body would lose which change belongs where.
+ */
+export function PatchDetailSurface({
+ files,
+ truncated,
+}: {
+ files: TracePatchFile[];
+ truncated: boolean;
+}) {
+ const { t } = useT("agents");
+ return (
+ <div className="divide-y divide-border/40">
+ {files.map((file, index) => (
+ // Transcript events are immutable once persisted, so index is stable.
+ <div key={`${file.path}:${index}`}>
+ <div className="flex items-center gap-2 px-3 pt-2 font-mono text-micro">
+ {file.changeKind && (
+ <span
+ className={cn(
+ "shrink-0 uppercase",
+ file.changeKind === "add" && "text-success",
+ file.changeKind === "delete" && "text-destructive",
+ file.changeKind === "update" && "text-muted-foreground",
+ )}
+ >
+ {file.changeKind}
+ </span>
+ )}
+ <span className="truncate text-muted-foreground">{file.path}</span>
+ {file.movePath && (
+ <>
+ <span className="shrink-0 text-faint-foreground" aria-hidden>
+ →
+ </span>
+ <span className="truncate text-muted-foreground">{file.movePath}</span>
+ </>
+ )}
+ </div>
+ {file.body.kind === "diff" ? (
+ <DiffDetailSurface lines={file.body.lines} path={file.path} />
+ ) : file.body.kind === "file" ? (
+ <FileWriteSurface
+ text={file.body.text}
+ lineCount={file.body.lineCount}
+ path={file.path}
+ />
+ ) : (
+ <div className="px-3 pb-2 pt-1 font-mono text-micro text-muted-foreground">
+ {file.truncated
+ ? t(($) => $.transcript.patch_body_truncated)
+ : t(($) => $.transcript.patch_no_content)}
+ </div>
+ )}
+ </div>
+ ))}
+ {truncated && (
+ <div className="px-3 py-2 font-mono text-micro text-muted-foreground">
+ {t(($) => $.transcript.patch_truncated)}
+ </div>
+ )}
+ </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.
+ */
+export 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-micro text-muted-foreground">
+ {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-micro 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-micro text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
+ >
+ {t(($) => $.transcript.show_all)}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export 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(
+ "transcript-code p-3 font-mono text-micro text-muted-foreground whitespace-pre-wrap break-all",
+ isLong && !showAll && "max-h-52 overflow-hidden",
+ )}
+ >
+ {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)}
+ // 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-micro text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
+ >
+ {t(($) => $.transcript.show_all)}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/common/task-transcript/run-outcome.test.ts b/packages/views/common/task-transcript/run-outcome.test.ts
new file mode 100644
index 0000000000..fc984e8e22
--- /dev/null
+++ b/packages/views/common/task-transcript/run-outcome.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vitest";
+import { buildRunOutcome } from "./run-outcome";
+import { buildSteps } from "./build-steps";
+import type { TimelineItem } from "./build-timeline";
+
+let seq = 0;
+function edit(path: string, before: string, after: string): TimelineItem {
+ return {
+ seq: ++seq,
+ type: "tool_use",
+ tool: "Edit",
+ input: { file_path: path, old_string: before, new_string: after },
+ };
+}
+function write(path: string, content: string): TimelineItem {
+ return { seq: ++seq, type: "tool_use", tool: "Write", input: { file_path: path, content } };
+}
+function bash(command: string): TimelineItem {
+ return { seq: ++seq, type: "tool_use", tool: "Bash", input: { command } };
+}
+function read(path: string): TimelineItem {
+ return { seq: ++seq, type: "tool_use", tool: "Read", input: { file_path: path } };
+}
+
+describe("buildRunOutcome", () => {
+ it("counts changed lines from an edit", () => {
+ const outcome = buildRunOutcome(buildSteps([edit("a.ts", "one\ntwo", "one\ntwo\nthree")]))!;
+
+ expect(outcome.paths).toEqual(["a.ts"]);
+ expect(outcome.addedLines).toBe(1);
+ expect(outcome.removedLines).toBe(0);
+ });
+
+ it("counts a whole-file write as additions", () => {
+ const outcome = buildRunOutcome(buildSteps([write("new.ts", "a\nb\nc")]))!;
+
+ expect(outcome.paths).toEqual(["new.ts"]);
+ expect(outcome.addedLines).toBe(3);
+ });
+
+ it("counts each path once across several edits", () => {
+ const outcome = buildRunOutcome(
+ buildSteps([edit("a.ts", "x", "y"), edit("a.ts", "y", "z"), edit("b.ts", "p", "q")]),
+ )!;
+
+ expect(outcome.paths).toEqual(["a.ts", "b.ts"]);
+ });
+
+ it("counts commands by their input shape, not the tool's name", () => {
+ const custom: TimelineItem = {
+ seq: ++seq,
+ type: "tool_use",
+ tool: "run_command",
+ input: { command: "ls" },
+ };
+ const outcome = buildRunOutcome(buildSteps([bash("pnpm test"), custom]))!;
+
+ expect(outcome.commandCount).toBe(2);
+ });
+
+ it("does not count a read as a change", () => {
+ const outcome = buildRunOutcome(buildSteps([read("a.ts"), bash("ls")]))!;
+
+ expect(outcome.paths).toEqual([]);
+ expect(outcome.commandCount).toBe(1);
+ });
+
+ it("sums every file of a multi-file patch", () => {
+ const patch: TimelineItem = {
+ seq: ++seq,
+ type: "tool_use",
+ tool: "apply_patch",
+ input: {
+ changes: [
+ { path: "src/a.go", kind: "update", diff: "@@ -1 +1 @@\n-old\n+new\n+extra\n" },
+ { path: "src/new.go", kind: "add", content: "package main\n" },
+ ],
+ },
+ };
+
+ const outcome = buildRunOutcome(buildSteps([patch]))!;
+
+ expect(outcome.paths).toEqual(["src/a.go", "src/new.go"]);
+ expect(outcome.addedLines).toBe(4);
+ expect(outcome.removedLines).toBe(1);
+ });
+
+ it("returns null when nothing nameable was produced", () => {
+ expect(buildRunOutcome(buildSteps([read("a.ts")]))).toBeNull();
+ expect(buildRunOutcome([])).toBeNull();
+ });
+});
diff --git a/packages/views/common/task-transcript/run-outcome.ts b/packages/views/common/task-transcript/run-outcome.ts
new file mode 100644
index 0000000000..b4dae34ddb
--- /dev/null
+++ b/packages/views/common/task-transcript/run-outcome.ts
@@ -0,0 +1,85 @@
+import { traceEventDetail } from "./trace-event-presenter";
+import type { TraceStep } from "./build-steps";
+
+/**
+ * What a run produced, aggregated from the calls it made.
+ *
+ * This is the layer most readers actually want: "what did it do, can I trust
+ * it" is answerable from the files it touched and the commands it ran, without
+ * reading a single step. Everything here is derived from data we already
+ * persist — deliberately no comment count, which would have to be guessed from
+ * command text, and no pass/fail on commands, which needs an exit code the
+ * stream does not carry.
+ */
+export interface RunOutcome {
+ /** Distinct paths touched, in first-touch order. */
+ paths: string[];
+ addedLines: number;
+ removedLines: number;
+ commandCount: number;
+}
+
+function isEmpty(outcome: RunOutcome): boolean {
+ return outcome.paths.length === 0 && outcome.commandCount === 0;
+}
+
+export function buildRunOutcome(steps: TraceStep[]): RunOutcome | null {
+ const paths: string[] = [];
+ const seen = new Set<string>();
+ let addedLines = 0;
+ let removedLines = 0;
+ let commandCount = 0;
+
+ const touch = (path: string) => {
+ if (path.length === 0 || seen.has(path)) return;
+ seen.add(path);
+ paths.push(path);
+ };
+
+ for (const step of steps) {
+ if (step.kind !== "call" || !step.call) continue;
+ const detail = traceEventDetail(step.call);
+
+ switch (detail.kind) {
+ case "diff": {
+ touch(detail.path);
+ for (const line of detail.lines) {
+ if (line.kind === "add") addedLines += 1;
+ else if (line.kind === "remove") removedLines += 1;
+ }
+ break;
+ }
+ case "file": {
+ touch(detail.path);
+ addedLines += detail.lineCount;
+ break;
+ }
+ case "patch": {
+ for (const file of detail.files) {
+ touch(file.path);
+ if (file.body.kind === "diff") {
+ for (const line of file.body.lines) {
+ if (line.kind === "add") addedLines += 1;
+ else if (line.kind === "remove") removedLines += 1;
+ }
+ } else if (file.body.kind === "file") {
+ addedLines += file.body.lineCount;
+ }
+ }
+ break;
+ }
+ case "text": {
+ // Shell-shaped by input, not by tool name: every backend names its
+ // shell differently (Bash, shell, run_command, terminal) but they all
+ // pass the command in a `command` string.
+ if (typeof step.call.input?.command === "string") commandCount += 1;
+ break;
+ }
+ }
+ }
+
+ const outcome = { paths, addedLines, removedLines, commandCount };
+ // A run that read files and posted a comment produced nothing this row can
+ // name; showing "0 files · 0 commands" would read as "it did nothing".
+ return isEmpty(outcome) ? null : outcome;
+}
diff --git a/packages/views/common/task-transcript/run-timeline.tsx b/packages/views/common/task-transcript/run-timeline.tsx
new file mode 100644
index 0000000000..cee54a90cd
--- /dev/null
+++ b/packages/views/common/task-transcript/run-timeline.tsx
@@ -0,0 +1,278 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Minus, Plus } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import { timelineTicks, type LaneSegment, type TraceLanes, type ToolKindTotals } from "./build-steps";
+import { useT } from "../../i18n";
+
+/**
+ * Where a run's time went, on a real wall-clock axis.
+ *
+ * Two lanes, not one: model turns and tool calls never overlap in an agent
+ * loop, so on a single row they can only occlude each other. Split, each lane
+ * reads as its own comb and carries its own total — "was it the model or the
+ * commands" is answerable without hovering anything.
+ *
+ * Two lanes, not four: the tool lane could split by what the calls did, but in
+ * a real run one kind dominates by orders of magnitude (commands run for
+ * minutes, reads and edits finish in milliseconds), so a lane per kind draws
+ * three near-empty tracks. That breakdown rides the lane's tooltip instead.
+ *
+ * Colour carries state, never taxonomy: the token set has one blue lightness
+ * ramp and no categorical palette, so which lane a bar sits in says what kind
+ * of work it was, and colour is spent on delivered (success) and failed
+ * (destructive) instead.
+ */
+
+const SEGMENT_TONE: Record<LaneSegment["kind"], string> = {
+ tool: "bg-chart-2",
+ think: "bg-chart-3",
+ report: "bg-success",
+ error: "bg-destructive",
+};
+
+/** Fit-to-width, then powers of two. Past 8x a 30-minute run is 20 screens of
+ * scrolling, which stops being navigation. */
+const ZOOM_STEPS = [1, 2, 4, 8] as const;
+const LABEL_WIDTH = "5.75rem";
+
+function formatTick(ms: number): string {
+ const totalSeconds = Math.round(ms / 1000);
+ if (totalSeconds < 60) return `${totalSeconds}s`;
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ if (minutes < 60) return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
+ const hours = Math.floor(minutes / 60);
+ const rest = minutes % 60;
+ return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
+}
+
+export function formatLaneTotal(ms: number): string {
+ const totalSeconds = Math.round(ms / 1000);
+ if (totalSeconds < 60) return `${totalSeconds}s`;
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ if (minutes < 60) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
+ const hours = Math.floor(minutes / 60);
+ return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;
+}
+
+function LaneLabel({ label, total, title }: { label: string; total: string; title?: string }) {
+ return (
+ <div
+ title={title}
+ className="flex h-[15px] items-baseline gap-1.5 pr-2.5 text-micro text-muted-foreground"
+ >
+ <span className="truncate">{label}</span>
+ <span className="ml-auto shrink-0 tabular-nums text-faint-foreground">{total}</span>
+ </div>
+ );
+}
+
+function LaneTrack({
+ label,
+ segments,
+ totalMs,
+ onSeek,
+}: {
+ label: string;
+ segments: LaneSegment[];
+ totalMs: number;
+ onSeek: (ms: number) => void;
+}) {
+ return (
+ <div className="relative h-[15px] rounded-sm bg-muted/55">
+ {segments.map((segment) => (
+ <button
+ key={`${segment.kind}:${segment.startMs}`}
+ type="button"
+ aria-label={`${label} ${formatLaneTotal(segment.durationMs)}`}
+ title={`${label} · ${formatLaneTotal(segment.durationMs)}`}
+ onClick={() => onSeek(segment.startMs)}
+ className={cn(
+ "absolute inset-y-0 rounded-[3px] transition-opacity hover:opacity-80",
+ SEGMENT_TONE[segment.kind],
+ )}
+ style={{
+ left: `${(segment.startMs / totalMs) * 100}%`,
+ // Sub-pixel bars would vanish; a visible minimum keeps a fast call
+ // clickable. Zooming in is what makes the width truthful — which is
+ // the whole reason the track scrolls.
+ width: `max(3px, ${(segment.durationMs / totalMs) * 100}%)`,
+ }}
+ />
+ ))}
+ </div>
+ );
+}
+
+export function RunTimeline({
+ lanes,
+ toolKinds,
+ selectedOffsetMs,
+ onSeek,
+}: {
+ lanes: TraceLanes;
+ /** Breakdown behind the tool lane's total, shown on hover. */
+ toolKinds?: ToolKindTotals;
+ /** Offset of the selected step, drawn as a playhead across both lanes. */
+ selectedOffsetMs?: number;
+ onSeek: (ms: number) => void;
+}) {
+ const { t } = useT("agents");
+ const [zoom, setZoom] = useState(1);
+ const scrollerRef = useRef<HTMLDivElement>(null);
+
+ // More screen means more room for labels: ticks scale with zoom so their
+ // on-screen density stays constant instead of thinning out as you zoom in.
+ const ticks = useMemo(() => timelineTicks(lanes.totalMs, 6 * zoom), [lanes.totalMs, zoom]);
+
+ const setZoomAround = useCallback(
+ (next: number) => {
+ const el = scrollerRef.current;
+ const previous = zoom;
+ setZoom(next);
+ if (!el) return;
+ // Keep whatever is under the middle of the viewport under it after the
+ // zoom, so zooming never teleports the reader somewhere else.
+ const centerRatio = (el.scrollLeft + el.clientWidth / 2) / (el.clientWidth * previous);
+ requestAnimationFrame(() => {
+ el.scrollLeft = centerRatio * el.clientWidth * next - el.clientWidth / 2;
+ });
+ },
+ [zoom],
+ );
+
+ // A selected step off-screen would leave the playhead invisible.
+ useEffect(() => {
+ const el = scrollerRef.current;
+ if (!el || selectedOffsetMs === undefined || zoom === 1) return;
+ const x = (selectedOffsetMs / lanes.totalMs) * el.clientWidth * zoom;
+ if (x < el.scrollLeft || x > el.scrollLeft + el.clientWidth) {
+ el.scrollLeft = Math.max(0, x - el.clientWidth / 2);
+ }
+ }, [selectedOffsetMs, lanes.totalMs, zoom]);
+
+ const zoomIndex = ZOOM_STEPS.indexOf(zoom as (typeof ZOOM_STEPS)[number]);
+ const canZoomIn = zoomIndex >= 0 && zoomIndex < ZOOM_STEPS.length - 1;
+ const canZoomOut = zoomIndex > 0;
+
+ const toolTitle = toolKinds
+ ? [
+ [t(($) => $.transcript.tool_kind_command), toolKinds.command],
+ [t(($) => $.transcript.tool_kind_write), toolKinds.write],
+ [t(($) => $.transcript.tool_kind_read), toolKinds.read],
+ [t(($) => $.transcript.tool_kind_misc), toolKinds.other],
+ ]
+ .filter(([, ms]) => (ms as number) > 0)
+ .map(([name, ms]) => `${name} ${formatLaneTotal(ms as number)}`)
+ .join(" · ")
+ : undefined;
+
+ return (
+ <div className="group/timeline relative shrink-0 border-b px-4 pb-2.5 pt-2">
+ <div className="flex items-start">
+ {/* Labels stay put while the track scrolls — a total that scrolls away
+ is a total you cannot read against the bars it belongs to. */}
+ <div className="shrink-0" style={{ width: LABEL_WIDTH }}>
+ <div className="h-3" />
+ <div className="mt-1 space-y-1">
+ <LaneLabel
+ label={t(($) => $.transcript.lane_model)}
+ total={formatLaneTotal(lanes.modelMs)}
+ />
+ <LaneLabel
+ label={t(($) => $.transcript.lane_tool)}
+ total={formatLaneTotal(lanes.toolMs)}
+ title={toolTitle}
+ />
+ </div>
+ </div>
+
+ <div
+ ref={scrollerRef}
+ className="min-w-0 flex-1 overflow-x-auto overscroll-x-contain"
+ >
+ <div className="relative" style={{ width: `${zoom * 100}%` }}>
+ <div className="relative h-3">
+ {ticks.map((tick, index) => (
+ <span
+ key={tick}
+ className={cn(
+ "absolute top-0 whitespace-nowrap text-micro tabular-nums text-faint-foreground",
+ index === 0
+ ? ""
+ : index === ticks.length - 1
+ ? "-translate-x-full"
+ : "-translate-x-1/2",
+ )}
+ style={{ left: `${(tick / lanes.totalMs) * 100}%` }}
+ >
+ {formatTick(tick)}
+ </span>
+ ))}
+ </div>
+ <div className="mt-1 space-y-1">
+ <LaneTrack
+ label={t(($) => $.transcript.lane_model)}
+ segments={lanes.model}
+ totalMs={lanes.totalMs}
+ onSeek={onSeek}
+ />
+ <LaneTrack
+ label={t(($) => $.transcript.lane_tool)}
+ segments={lanes.tool}
+ totalMs={lanes.totalMs}
+ onSeek={onSeek}
+ />
+ </div>
+ {selectedOffsetMs !== undefined && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute bottom-[-2px] top-2.5 w-0.5 rounded-full bg-brand"
+ style={{
+ left: `${
+ (Math.min(Math.max(selectedOffsetMs, 0), lanes.totalMs) / lanes.totalMs) * 100
+ }%`,
+ }}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Zoom is the answer to a long run compressing its bars to slivers.
+ Resting state stays clean: the control appears on hover, and stays
+ visible once zoomed so the way back is never hidden. */}
+ <div
+ className={cn(
+ "absolute right-3 top-1 flex items-center gap-0.5 rounded-md border bg-surface/95 p-0.5 shadow-sm transition-opacity",
+ zoom > 1 ? "opacity-100" : "opacity-0 focus-within:opacity-100 group-hover/timeline:opacity-100",
+ )}
+ >
+ <button
+ type="button"
+ disabled={!canZoomOut}
+ onClick={() => setZoomAround(ZOOM_STEPS[zoomIndex - 1] ?? 1)}
+ aria-label={t(($) => $.transcript.timeline_zoom_out)}
+ className="flex h-5 w-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent disabled:opacity-40"
+ >
+ <Minus className="h-3 w-3" />
+ </button>
+ <span className="min-w-[2rem] text-center text-micro tabular-nums text-muted-foreground">
+ {zoom}×
+ </span>
+ <button
+ type="button"
+ disabled={!canZoomIn}
+ onClick={() => setZoomAround(ZOOM_STEPS[zoomIndex + 1] ?? zoom)}
+ aria-label={t(($) => $.transcript.timeline_zoom_in)}
+ className="flex h-5 w-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent disabled:opacity-40"
+ >
+ <Plus className="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ );
+}
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 68d7924fd9..750b0507f9 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.test.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.test.ts
@@ -4,7 +4,8 @@ import {
parseUnifiedDiff,
stripShellWrapper,
traceEventCopyText,
- traceEventDefaultExpanded,
+ readImageResult,
+ base64ByteLength,
traceEventDetail,
traceEventHasDetail,
traceEventKind,
@@ -113,27 +114,39 @@ describe("traceEventCopyText", () => {
});
});
-describe("traceEventDefaultExpanded", () => {
- const agent = { type: "text", content: "hello" };
- const error = { type: "error", content: "boom" };
- const thinking = { type: "thinking", content: "hmm" };
- const tool = { type: "tool_use", tool: "Bash", input: { command: "ls" } };
+describe("readImageResult", () => {
+ it("reads a base64 image block so a screenshot renders as a picture", () => {
+ const output = JSON.stringify([
+ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "AAAA" } },
+ ]);
+
+ expect(readImageResult(output)).toEqual({ mediaType: "image/jpeg", base64: "AAAA" });
+ });
+
+ it("defaults the media type when the provider omits it", () => {
+ const output = JSON.stringify({ type: "image", source: { type: "base64", data: "BBBB" } });
- it("smart: agent and error read without a click, process noise stays folded", () => {
- expect(traceEventDefaultExpanded(agent, "smart")).toBe(true);
- expect(traceEventDefaultExpanded(error, "smart")).toBe(true);
- expect(traceEventDefaultExpanded(thinking, "smart")).toBe(false);
- expect(traceEventDefaultExpanded(tool, "smart")).toBe(false);
+ expect(readImageResult(output)?.mediaType).toBe("image/png");
});
- it("expanded/collapsed override the hierarchy wholesale", () => {
- expect(traceEventDefaultExpanded(thinking, "expanded")).toBe(true);
- expect(traceEventDefaultExpanded(agent, "collapsed")).toBe(false);
+ it("ignores ordinary output without paying for a parse", () => {
+ expect(readImageResult('{"ok":true}')).toBeNull();
+ expect(readImageResult("plain terminal output")).toBeNull();
+ expect(readImageResult(undefined)).toBeNull();
+ // Shaped like an image block but not valid JSON.
+ expect(readImageResult('[{"type":"image","source":{"type":"base64"')).toBeNull();
});
- it("a row without detail never expands", () => {
- expect(traceEventDefaultExpanded({ type: "text" }, "expanded")).toBe(false);
+ it("reports the decoded size so the caption is not a base64 length", () => {
+ expect(base64ByteLength("AAAA")).toBe(3);
+ expect(base64ByteLength("AAA=")).toBe(2);
+ });
+});
+
+describe("traceEventHasDetail", () => {
+ it("is false for an empty body", () => {
expect(traceEventHasDetail({ type: "tool_use", input: {} })).toBe(false);
+ expect(traceEventHasDetail({ type: "text" })).toBe(false);
});
});
diff --git a/packages/views/common/task-transcript/trace-event-presenter.ts b/packages/views/common/task-transcript/trace-event-presenter.ts
index f3c93752f9..1eb646cfe4 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.ts
@@ -1,20 +1,17 @@
// Trace Event Presenter — the pure readability layer for the execution
-// transcript. Given one timeline event it decides visual kind, label, one-line
-// summary, and default expansion, encoding the reading hierarchy:
+// transcript. Given one timeline event it decides visual kind, label, and
+// one-line summary, encoding the reading hierarchy:
//
// 1. Agent text is the primary layer and reads without a click.
// 2. Errors stand out and also read without a click.
// 3. Tool calls are compact — provider-native name + most-informative arg.
-// 4. Tool results and thinking are de-emphasized and collapsed by default.
+// 4. Tool results and thinking are de-emphasized; their body opens in the
+// step inspector rather than in the list.
// 5. Unknown event types are retained as a generic event, never dropped.
//
// This module owns no React and no fetching, so it is unit-testable in
// isolation and independent of whichever list shell renders the events.
-import type { TranscriptDetailDensity } from "@multica/core/agents/stores";
-
-export type { TranscriptDetailDensity };
-
export interface TraceEvent {
seq?: number;
type: string;
@@ -545,6 +542,56 @@ export function traceEventDetail(event: TraceEvent): TraceEventDetail {
}
}
+/** An image a tool returned, ready to render. */
+export interface TraceImageResult {
+ mediaType: string;
+ base64: string;
+}
+
+/**
+ * A screenshot tool answers with a base64 image block, which the transcript
+ * used to print as a wall of base64 — the single worst thing on the old
+ * surface. Recognise it so the reader gets the picture instead.
+ *
+ * Only JSON that already looks like an image block is parsed: an 8KB command
+ * output should not pay for a `JSON.parse` on every render.
+ */
+export function readImageResult(output: string | undefined): TraceImageResult | null {
+ if (!output) return null;
+ const head = output.slice(0, 200);
+ if (!head.includes('"image"') || !head.includes('"base64"')) return null;
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(output);
+ } catch {
+ return null;
+ }
+
+ const blocks = Array.isArray(parsed) ? parsed : [parsed];
+ for (const block of blocks) {
+ if (typeof block !== "object" || block === null) continue;
+ const record = block as Record<string, unknown>;
+ if (record.type !== "image") continue;
+ const source = record.source;
+ if (typeof source !== "object" || source === null) continue;
+ const sourceRecord = source as Record<string, unknown>;
+ const data = sourceRecord.data;
+ if (typeof data !== "string" || data.length === 0) continue;
+ const mediaType =
+ typeof sourceRecord.media_type === "string" ? sourceRecord.media_type : "image/png";
+ return { mediaType, base64: data };
+ }
+
+ return null;
+}
+
+/** Rough decoded size of a base64 payload, for a human-readable label. */
+export function base64ByteLength(base64: string): number {
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
+ return Math.max(0, Math.floor((base64.length * 3) / 4) - padding);
+}
+
export function traceEventHasDetail(event: TraceEvent): boolean {
switch (traceEventKind(event)) {
case "tool_use":
@@ -561,23 +608,3 @@ export function traceEventSummaryIsMono(kind: TraceEventKind): boolean {
return kind === "tool_use" || kind === "tool_result";
}
-/**
- * Default expansion under the `smart` density: the reading hierarchy itself.
- * Agent text and errors read without a click; process noise stays folded.
- */
-export function traceEventDefaultExpanded(
- event: TraceEvent,
- density: TranscriptDetailDensity,
-): boolean {
- if (!traceEventHasDetail(event)) return false;
- switch (density) {
- case "expanded":
- return true;
- case "collapsed":
- return false;
- case "smart": {
- const kind = traceEventKind(event);
- return kind === "agent" || kind === "error";
- }
- }
-}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index a795bb3d77..83d22e8cb5 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -801,26 +801,14 @@
"status_failed": "Failed",
"filter": "Filter",
"clear_filters": "Clear filters",
- "events_one": "{{count}} event",
- "events_other": "{{count}} events",
- "events_filtered": "{{shown}} of {{total}} events",
"copy_all": "Copy all",
"copy_filtered": "Copy filtered",
"copied": "Copied",
"waiting_events": "Waiting for events...",
"antigravity_live_unavailable": "Antigravity does not currently provide live execution events. The transcript will be available after the task completes.",
"no_data": "No execution data recorded.",
- "sort_label": "Sort",
"sort_chronological": "Oldest first",
"sort_newest_first": "Newest first",
- "density_label": "Expand mode",
- "density_smart": "Focus",
- "density_smart_desc": "Replies and errors open; thinking and tool steps stay folded",
- "density_expanded": "Expand all",
- "density_expanded_desc": "Every row's full params and output, for step-by-step review",
- "density_collapsed": "Collapse all",
- "density_collapsed_desc": "One line per event — the most compact scan",
- "no_output": "No output",
"show_all": "Show all",
"patch_truncated": "... (truncated)",
"patch_body_truncated": "... (body truncated)",
@@ -857,7 +845,37 @@
"usage_chip_title": "Tokens and estimated cost for this run",
"details_branch": "Branch",
"details_reason": "Reason",
- "copy_branch": "Copy branch name"
+ "copy_branch": "Copy branch name",
+ "lane_model": "Model",
+ "lane_tool": "Tools",
+ "outcome_label": "Produced",
+ "outcome_files_one": "{{count}} file",
+ "outcome_files_other": "{{count}} files",
+ "outcome_commands_one": "{{count}} command",
+ "outcome_commands_other": "{{count}} commands",
+ "search_placeholder": "Search this run…",
+ "no_matches": "No steps match this search.",
+ "more_actions": "More",
+ "kind_tool": "Tool",
+ "kind_thinking": "Thinking",
+ "kind_error": "Error",
+ "group_calls_one": "{{count}} call",
+ "group_calls_other": "{{count}} calls",
+ "step_running": "Still running",
+ "step_input": "Input",
+ "step_result": "Result",
+ "copy_step": "Copy this step",
+ "close_step": "Close details",
+ "image_result": "Image",
+ "steps_count_one": "{{count}} step",
+ "steps_count_other": "{{count}} steps",
+ "steps_filtered": "{{shown}} of {{total}} steps",
+ "timeline_zoom_in": "Zoom in",
+ "timeline_zoom_out": "Zoom out",
+ "tool_kind_command": "Commands",
+ "tool_kind_write": "Edits",
+ "tool_kind_read": "Reads",
+ "tool_kind_misc": "Other"
},
"task_failure": {
"agent_error": "Agent execution error",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 978bd68713..9689cb66d1 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -680,25 +680,14 @@
"status_failed": "失敗",
"filter": "フィルター",
"clear_filters": "フィルターをクリア",
- "events_other": "イベント {{count}} 件",
- "events_filtered": "イベント {{total}} 件中 {{shown}} 件",
"copy_all": "すべてコピー",
"copy_filtered": "フィルター結果をコピー",
"copied": "コピーしました",
"waiting_events": "イベントを待機中...",
"antigravity_live_unavailable": "Antigravity は現在、リアルタイム実行イベントを提供していません。作業完了後に実行記録を確認できます。",
"no_data": "記録された実行データがありません。",
- "sort_label": "並び替え",
"sort_chronological": "古い順",
"sort_newest_first": "新しい順",
- "density_label": "展開モード",
- "density_smart": "重点展開",
- "density_smart_desc": "回答とエラーは展開、思考とツールの過程は折りたたみ",
- "density_expanded": "すべて展開",
- "density_expanded_desc": "各行のパラメータと出力を完全に展開し、逐次レビューに",
- "density_collapsed": "すべて折りたたむ",
- "density_collapsed_desc": "1 行 1 イベントの最もコンパクトな表示",
- "no_output": "出力なし",
"show_all": "すべて表示",
"patch_truncated": "...(切り詰め済み)",
"patch_body_truncated": "...(本文を切り詰めました)",
@@ -735,7 +724,33 @@
"usage_chip_title": "この実行のトークンと推定費用",
"details_branch": "ブランチ",
"details_reason": "理由",
- "copy_branch": "ブランチ名をコピー"
+ "copy_branch": "ブランチ名をコピー",
+ "lane_model": "モデル",
+ "lane_tool": "ツール",
+ "outcome_label": "成果",
+ "outcome_files_other": "{{count}} 件のファイル",
+ "outcome_commands_other": "{{count}} 件のコマンド",
+ "search_placeholder": "この実行を検索…",
+ "no_matches": "一致するステップはありません。",
+ "more_actions": "その他",
+ "kind_tool": "ツール",
+ "kind_thinking": "思考",
+ "kind_error": "エラー",
+ "group_calls_other": "{{count}} 回の呼び出し",
+ "step_running": "実行中",
+ "step_input": "入力",
+ "step_result": "結果",
+ "copy_step": "このステップをコピー",
+ "close_step": "詳細を閉じる",
+ "image_result": "画像",
+ "steps_count_other": "{{count}} ステップ",
+ "steps_filtered": "{{total}} 件中 {{shown}} ステップ",
+ "timeline_zoom_in": "拡大",
+ "timeline_zoom_out": "縮小",
+ "tool_kind_command": "コマンド",
+ "tool_kind_write": "編集",
+ "tool_kind_read": "読み取り",
+ "tool_kind_misc": "その他"
},
"task_failure": {
"agent_error": "エージェント実行エラー",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index f743df0df5..c7d8681587 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -688,25 +688,14 @@
"status_failed": "실패함",
"filter": "필터",
"clear_filters": "필터 지우기",
- "events_other": "이벤트 {{count}}개",
- "events_filtered": "이벤트 {{total}}개 중 {{shown}}개",
"copy_all": "전체 복사",
"copy_filtered": "필터 결과 복사",
"copied": "복사했습니다",
"waiting_events": "이벤트를 기다리는 중...",
"antigravity_live_unavailable": "Antigravity는 현재 실시간 실행 이벤트를 제공하지 않습니다. 작업이 완료되면 실행 기록을 확인할 수 있습니다.",
"no_data": "기록된 실행 데이터가 없습니다.",
- "sort_label": "정렬",
"sort_chronological": "오래된 순",
"sort_newest_first": "최신 순",
- "density_label": "펼치기 방식",
- "density_smart": "핵심 펼치기",
- "density_smart_desc": "응답과 오류는 펼치고, 사고와 도구 과정은 접힌 상태 유지",
- "density_expanded": "모두 펼치기",
- "density_expanded_desc": "각 행의 전체 매개변수와 출력을 펼쳐 단계별 검토에 사용",
- "density_collapsed": "모두 접기",
- "density_collapsed_desc": "이벤트당 한 줄, 가장 간결한 보기",
- "no_output": "출력 없음",
"show_all": "모두 보기",
"patch_truncated": "...(잘림)",
"patch_body_truncated": "...(본문 잘림)",
@@ -743,7 +732,33 @@
"usage_chip_title": "이 실행의 토큰 및 예상 비용",
"details_branch": "브랜치",
"details_reason": "사유",
- "copy_branch": "브랜치 이름 복사"
+ "copy_branch": "브랜치 이름 복사",
+ "lane_model": "모델",
+ "lane_tool": "도구",
+ "outcome_label": "산출물",
+ "outcome_files_other": "파일 {{count}}개",
+ "outcome_commands_other": "명령 {{count}}개",
+ "search_placeholder": "이 작업 검색…",
+ "no_matches": "검색과 일치하는 단계가 없습니다.",
+ "more_actions": "더보기",
+ "kind_tool": "도구",
+ "kind_thinking": "사고",
+ "kind_error": "오류",
+ "group_calls_other": "호출 {{count}}회",
+ "step_running": "진행 중",
+ "step_input": "입력",
+ "step_result": "결과",
+ "copy_step": "이 단계 복사",
+ "close_step": "세부 정보 닫기",
+ "image_result": "이미지",
+ "steps_count_other": "{{count}}단계",
+ "steps_filtered": "{{total}}단계 중 {{shown}}단계",
+ "timeline_zoom_in": "확대",
+ "timeline_zoom_out": "축소",
+ "tool_kind_command": "명령",
+ "tool_kind_write": "편집",
+ "tool_kind_read": "읽기",
+ "tool_kind_misc": "기타"
},
"task_failure": {
"agent_error": "에이전트 실행 오류",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index b38791497a..9dcdc50e8b 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -787,25 +787,14 @@
"status_failed": "失败",
"filter": "筛选",
"clear_filters": "清除筛选",
- "events_other": "{{count}} 个事件",
- "events_filtered": "{{shown}} / {{total}} 个事件",
"copy_all": "全部复制",
"copy_filtered": "复制筛选结果",
"copied": "已复制",
"waiting_events": "等待事件中...",
"antigravity_live_unavailable": "Antigravity 暂不提供实时执行事件。task 完成后即可查看执行记录。",
"no_data": "未记录执行数据。",
- "sort_label": "排序",
"sort_chronological": "最早在前",
"sort_newest_first": "最新在前",
- "density_label": "展开方式",
- "density_smart": "重点展开",
- "density_smart_desc": "汇报与错误展开,思考和工具过程保持折叠",
- "density_expanded": "全部展开",
- "density_expanded_desc": "展开每一行的完整参数与输出,逐条审阅用",
- "density_collapsed": "全部收起",
- "density_collapsed_desc": "一行一事件,最紧凑的扫读视图",
- "no_output": "无输出",
"show_all": "显示全部",
"patch_truncated": "...(已截断)",
"patch_body_truncated": "...(内容已截断)",
@@ -842,7 +831,33 @@
"usage_chip_title": "这次运行消耗的 token 与估算费用",
"details_branch": "分支",
"details_reason": "原因",
- "copy_branch": "复制分支名"
+ "copy_branch": "复制分支名",
+ "lane_model": "模型",
+ "lane_tool": "工具",
+ "outcome_label": "产出",
+ "outcome_files_other": "{{count}} 个文件",
+ "outcome_commands_other": "{{count}} 条命令",
+ "search_placeholder": "搜索这次运行…",
+ "no_matches": "没有匹配的步骤。",
+ "more_actions": "更多",
+ "kind_tool": "工具",
+ "kind_thinking": "思考",
+ "kind_error": "错误",
+ "group_calls_other": "{{count}} 次调用",
+ "step_running": "进行中",
+ "step_input": "输入",
+ "step_result": "结果",
+ "copy_step": "复制这一步",
+ "close_step": "关闭详情",
+ "image_result": "图片",
+ "steps_count_other": "{{count}} 个步骤",
+ "steps_filtered": "{{shown}} / {{total}} 个步骤",
+ "timeline_zoom_in": "放大",
+ "timeline_zoom_out": "缩小",
+ "tool_kind_command": "命令",
+ "tool_kind_write": "编辑",
+ "tool_kind_read": "读取",
+ "tool_kind_misc": "其他"
},
"task_failure": {
"agent_error": "智能体执行出错",