Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add the /traces conversation viewer to the dev TUI (#1403)

Chad Hietala9adb455a0da5
diff --git a/.changeset/tricky-turtles-peek.md b/.changeset/tricky-turtles-peek.md
new file mode 100644
index 000000000..c3828e8cf
--- /dev/null
+++ b/.changeset/tricky-turtles-peek.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Adds a `/traces` command to the dev TUI: a full-screen live viewer over the local trace spool that re-tells each trace as a chat-style conversation — system prompt, user and assistant messages, and tool calls render as expandable cards (arrow keys or mouse click to expand/collapse), with a right-side metadata drawer. Subagent turns are badged with their dispatch lineage (`subagent:<name>`), and the viewer opens on the trace containing the current session — including windowed sessions and subagent children recorded into a parent's trace. Expanded cards scroll line-by-line so content taller than the viewport is fully readable. Model spans with errors, token usage, or tool calls (but no text) now appear as cards instead of disappearing. Terminal escape sequences in trace payloads are stripped at render time. Tool-call arguments and results are captured without stripping domain-level `providerOptions`/`providerMetadata` keys. A single prompt message over 32 KiB is truncated at the text level so the serialized JSON stays parseable. Local spans capture system prompt, prompt messages, responses, reasoning, and tool arguments/results (`EVE_TRACES_CONTENT=off` to disable); long conversations truncate oldest messages first with an omission marker.
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index fe170df29..5e6fd100b 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -40,11 +40,12 @@ Each command echoes as an invocation line, asks through a bordered panel that ta
| `/vc:install` | Installs the Vercel CLI. Available locally and on a remote session. |
| `/vc:login` | Logs in to Vercel locally. On a remote session, resolves the deployment's project, refreshes its OIDC token, and confirms any required Trusted Sources rule. |
| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). |
+| `/traces` | Opens the full-screen local trace viewer. See [Inspect traces](#inspect-traces). |
| `/new` | Starts a fresh session. |
| `/exit` | Quits the TUI. |
| `/help` | Lists the commands available for the current local or remote session. |
-`/model`, `/add`, and `/deploy` manage the local agent or its linked project. They are available only when `eve dev` runs the server locally, not when connected to a remote server with `--url`.
+`/model`, `/add`, `/deploy`, and `/traces` manage the local agent or its linked project. They are available only when `eve dev` runs the server locally, not when connected to a remote server with `--url`.
### Configure the model and provider
@@ -106,6 +107,24 @@ Every captured line, tool failure, workflow error, and eve framework log record
Each log has a same-named `.dump` sibling — one JSON document with environment diagnostics (eve, Node.js, and Vercel CLI versions, the Vercel CLI path, and the size of the local session store) plus running session stats: prompts, token usage, tool calls by name, and subagent dispatches. `eve logs --dump` prints the dump and the log together as one parseable report to attach when filing an issue.
+## Inspect traces
+
+`/traces` opens a full-screen viewer over the local trace spool (`.eve/traces/v1`) that `eve dev` writes while you chat — see [Zero-config local traces](instrumentation#zero-config-local-traces). It reads the spool files directly and refreshes about once a second, so spans from the current session stream in live. The viewer takes over the terminal's alternate screen; closing it restores the transcript exactly where you left it.
+
+The viewer opens on your current session's trace (or the most recent one). It re-tells the trace as a chat-like flow of cards: the system prompt sits at the top as a collapsed card, then user and assistant messages (assistant cards carry model, duration, token, and gateway cost metadata), and tool calls show their inputs and results inline. Work a subagent performed appears in the same flow, ordered by when it happened — between the parent's dispatch step and its resumed reply — with a dim `subagent` badge (`subagent:<name>` when the dispatch named one) on every card of the delegated turn; the delegated prompt renders as a `task` card rather than a `user` message. Error spans paint their whole card red. The header names the agent, session, span count, and duration, plus a `● live` badge while spans are still landing. `/traces <trace>` opens a specific trace by id prefix.
+
+| Key | Action |
+| --------- | ------------------------------------------------------------------------ |
+| `↑` / `↓` | Move the card selection (scroll the attributes panel when it has focus). |
+| `←` / `→` | Expand / collapse the selected card (only cards with hidden content). |
+| `Enter` | Open the attributes panel for the selected card; close it when open. |
+| `Tab` | Move focus between the conversation and the attributes panel. |
+| `[` / `]` | Cycle to the next / previous trace. |
+| `Esc` | Close the panel (or unfocus it), otherwise close the viewer. |
+| `q` | Close the viewer. |
+
+`←`/`→` or a mouse click expands a card to its full contents (the system prompt, long payloads) and collapses it back; cards that already fit have nothing to expand. The attributes panel opens on the right and stays metadata-only — status, timing, ids, and the span's non-payload OTLP attributes — since the cards already carry the payloads. Model spans capture the system prompt, the prompt messages (rendered as a chat transcript), and the response (text, tool calls, finish reason); tool-call spans capture the call arguments and result, pretty-printed — each capped at 32 KB, with provider transport metadata stripped. When a conversation's messages exceed the cap, the oldest messages are dropped and the transcript notes how many were omitted. Set `EVE_TRACES_CONTENT=off` to stop capturing payload content. With no spans yet, the viewer shows an empty state and keeps watching; if tracing is disabled (`EVE_TRACES=off`) it says so instead.
+
## Display flags
Density flags control how much of each section renders. They accept `full`, `collapsed`, `auto-collapsed`, or `hidden`.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index d62f6b2bc..f6168c77c 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -13,7 +13,7 @@ When no authored `instrumentation.ts` exists, `eve dev` records agent, AI SDK, a
The directory is an immutable OTLP/JSON spool and remains available after `eve dev` exits, subject to the [retention policy](#local-trace-retention) below. Inspection tools may build a query index from these segments, but the index is derived and can be rebuilt without changing the captured trace data.
-Use `eve traces ls` to list captured traces and `eve traces <trace>` to inspect a session's span tree. Model and tool-call spans also carry the inputs and outputs (system prompt, prompt messages, and response text for models; call arguments and results for tools, each capped at 32 KB) — set `EVE_TRACES_CONTENT=off` to keep payloads out of the spool.
+Use `eve traces ls` to list captured traces and `eve traces <trace>` to inspect a session's span tree. Inside the dev TUI, [`/traces`](dev-tui#inspect-traces) opens a full-screen live viewer that re-tells the trace as a chat-style conversation (expandable message and tool-call cards) with a right-side metadata drawer. Model and tool-call spans also carry the inputs and outputs (system prompt, prompt messages, and response text for models; call arguments and results for tools, each capped at 32 KB) — set `EVE_TRACES_CONTENT=off` to keep payloads out of the spool.
When a model call is served by Vercel AI Gateway, its `agent.step` span also carries the cost the gateway reported: `gen_ai.usage.cost` (raw inference, USD), `gen_ai.usage.gateway_cost` (with the gateway surcharge), `gen_ai.usage.input_cost` / `gen_ai.usage.output_cost` (the split), and `gen_ai.generation.id` for reconciliation with the gateway dashboard. These attributes only exist for gateway-served calls — other providers emit nothing. Cost per turn is the sum across the turn's step spans.
diff --git a/packages/eve/src/cli/dev/tui/command-typeahead.test.ts b/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
index 16cdb20ea..3e69ea956 100644
--- a/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
+++ b/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
@@ -172,7 +172,7 @@ describe("renderCommandSuggestions", () => {
const many = Array.from({ length: 14 }, (_, index) => spec(`command-${index}`));
const state = { ...typeaheadFor(many, "/"), selectedIndex: 13 };
const rows = renderCommandSuggestions(state, theme, 80).map(stripAnsi);
- expect(rows).toHaveLength(10);
+ expect(rows).toHaveLength(11);
expect(rows.some((row) => row.includes("command-13"))).toBe(true);
expect(rows.some((row) => row.includes("command-0"))).toBe(false);
expect(rows.some((row) => row.includes("commands, showing"))).toBe(false);
diff --git a/packages/eve/src/cli/dev/tui/command-typeahead.ts b/packages/eve/src/cli/dev/tui/command-typeahead.ts
index 7eba38746..a90171653 100644
--- a/packages/eve/src/cli/dev/tui/command-typeahead.ts
+++ b/packages/eve/src/cli/dev/tui/command-typeahead.ts
@@ -17,7 +17,7 @@ import { renderCursorRow } from "#setup/cli/option-row.js";
* a command (e.g. `/exit`) out of view — windowing is for longer future lists.
* Keep this >= the number of entries in `PROMPT_COMMANDS`.
*/
-const MAX_VISIBLE_SUGGESTIONS = 10;
+const MAX_VISIBLE_SUGGESTIONS = 11;
export interface CommandTypeaheadState {
/** The prompt text the matches were derived from. */
diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.ts
index 53b778128..b42091222 100644
--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts
@@ -8,6 +8,7 @@ export type PromptCommand =
| { type: "exit" }
| { type: "help" }
| { type: "loglevel"; argument: string }
+ | { type: "traces"; argument: string }
| { type: "extension"; name: PromptCommandExtensionName; argument: string };
/**
@@ -91,6 +92,15 @@ const PROMPT_COMMAND_DEFINITIONS = [
build: (argument) => ({ type: "loglevel", argument }),
targets: ["local", "remote"],
},
+ {
+ name: "traces",
+ aliases: [],
+ description: "Open the local trace viewer",
+ argumentHint: "[trace]",
+ takesArgument: true,
+ build: (argument) => ({ type: "traces", argument }),
+ targets: ["local"],
+ },
{
name: "add",
aliases: [],
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index a9e18debf..544ad7850 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -869,6 +869,61 @@ describe("EveTUIRunner delayed dev build errors", () => {
});
});
+describe("EveTUIRunner /traces", () => {
+ it("opens the renderer's trace viewer with the app root and optional reference", async () => {
+ const prompts: Array<string | undefined> = ["/traces abc123", "/traces", undefined];
+ const open = vi.fn(async () => {});
+ const renderer: AgentTUIRenderer = {
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async () => {}),
+ traceViewer: { open },
+ };
+
+ const runner = new EveTUIRunner({
+ session: sessionYielding([{ type: "session.waiting" }]),
+ renderer,
+ name: "Weather Agent",
+ appRoot: "/tmp/weather-agent",
+ });
+
+ await runner.run();
+
+ expect(open).toHaveBeenCalledTimes(2);
+ expect(open).toHaveBeenNthCalledWith(1, {
+ appRoot: "/tmp/weather-agent",
+ sessionId: undefined,
+ reference: "abc123",
+ });
+ expect(open).toHaveBeenNthCalledWith(2, {
+ appRoot: "/tmp/weather-agent",
+ sessionId: undefined,
+ reference: undefined,
+ });
+ });
+
+ it("renders a local-only notice when the session has no trace viewer", async () => {
+ const prompts: Array<string | undefined> = ["/traces", undefined];
+ const notices: string[] = [];
+ const renderer: AgentTUIRenderer = {
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderNotice: vi.fn((text: string) => {
+ notices.push(text);
+ }),
+ renderStream: vi.fn(async () => {}),
+ };
+
+ const runner = new EveTUIRunner({
+ session: sessionYielding([{ type: "session.waiting" }]),
+ renderer,
+ name: "Weather Agent",
+ });
+
+ await runner.run();
+
+ expect(notices.some((text) => text.includes("/traces is only available"))).toBe(true);
+ });
+});
+
describe("EveTUIRunner initial input", () => {
it("seeds only the first prompt's editable buffer with --input text", async () => {
const seenOptions: Array<AgentTUISessionOptions | undefined> = [];
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 70281a0d1..2be92ad72 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -76,6 +76,7 @@ import {
type SetupIssue,
} from "./setup-issues.js";
import type { SetupFlowRenderer } from "./setup-flow.js";
+import type { TraceViewerRenderer } from "./traces/trace-viewer-session.js";
import type { RemoteDevelopmentTarget } from "./target.js";
import type {
AssistantResponseStatsMode,
@@ -258,6 +259,11 @@ export type AgentTUIRenderer = {
renderCommandInvocation?(text: string, status?: "failed"): void;
renderCommandResult?(text: string, tone?: "success" | "error"): void;
readonly setupFlow?: SetupFlowRenderer;
+ /**
+ * The renderer's full-screen local trace viewer, opened by `/traces`.
+ * The returned promise resolves when the user closes the viewer.
+ */
+ readonly traceViewer?: TraceViewerRenderer;
readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;
/**
* Consumes the next prompt produced by mid-turn input: the Esc-popped
@@ -814,6 +820,16 @@ export class EveTUIRunner {
continue;
}
+ // /traces is renderer-local too: the viewer reads the local spool
+ // from disk and owns the screen until the user closes it.
+ if (command?.type === "traces") {
+ await this.#openTraceViewer(command.argument);
+ pendingInputResponses = undefined;
+ streamWithoutPrompt = false;
+ prompt = undefined;
+ continue;
+ }
+
if (command?.type === "extension") {
try {
await this.#executeExtensionCommand(command, title, { trigger: "command" });
@@ -1452,6 +1468,28 @@ export class EveTUIRunner {
});
}
+ /**
+ * Opens the renderer's trace viewer on the local spool. The viewer owns the
+ * screen until the user closes it; sessions without the capability (or
+ * without a local app root) get a one-line notice instead.
+ */
+ async #openTraceViewer(argument: string): Promise<void> {
+ if (this.#appRoot === undefined || this.#renderer.traceViewer === undefined) {
+ this.#renderCommandOutcome("/traces is only available in local dev sessions.");
+ return;
+ }
+ try {
+ await this.#renderer.traceViewer.open({
+ appRoot: this.#appRoot,
+ sessionId: this.#session.state.sessionId,
+ reference: argument === "" ? undefined : argument,
+ });
+ } catch (error) {
+ if (isInterruptedError(error)) return;
+ throw error;
+ }
+ }
+
/**
* Applies `/loglevel [all|stderr|sandbox|none]` against the renderer's buffered
* log filter and returns the one-line outcome. A bare `/loglevel` reports
diff --git a/packages/eve/src/cli/dev/tui/stream-format.test.ts b/packages/eve/src/cli/dev/tui/stream-format.test.ts
index cf387a0a5..3ce5ac7c9 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.test.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.test.ts
@@ -181,8 +181,25 @@ describe("parseKey", () => {
});
it("decodes ctrl-n and ctrl-p for emacs-style navigation", () => {
- expect(parseKey(Buffer.from("\u000e"))).toEqual({ type: "ctrl-n" });
- expect(parseKey(Buffer.from("\u0010"))).toEqual({ type: "ctrl-p" });
+ expect(parseKey(Buffer.from(""))).toEqual({ type: "ctrl-n" });
+ expect(parseKey(Buffer.from(""))).toEqual({ type: "ctrl-p" });
+ });
+
+ it("decodes SGR mouse press and release with cell coordinates", () => {
+ expect(parseKey(Buffer.from("\x1b[<0;35;12M"))).toEqual({
+ type: "mouse",
+ action: "press",
+ button: 0,
+ x: 35,
+ y: 12,
+ });
+ expect(parseKey(Buffer.from("\x1b[<0;35;12m"))).toEqual({
+ type: "mouse",
+ action: "release",
+ button: 0,
+ x: 35,
+ y: 12,
+ });
});
});
diff --git a/packages/eve/src/cli/dev/tui/stream-format.ts b/packages/eve/src/cli/dev/tui/stream-format.ts
index 86424274a..bd872d8d8 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.ts
@@ -25,6 +25,15 @@ export type TerminalKey =
| { type: "end" }
| { type: "tab" }
| { type: "escape" }
+ | {
+ type: "mouse";
+ action: "press" | "release";
+ /** SGR button code (0 = left). */
+ button: number;
+ /** 1-based terminal cell coordinates. */
+ x: number;
+ y: number;
+ }
| { type: "ctrl-a" }
| { type: "ctrl-e" }
| { type: "ctrl-d" }
@@ -162,9 +171,25 @@ export function nextKey(buffer: string): KeyToken {
return { key: parseKey(Buffer.from(buffer.slice(0, end))), consumed: end };
}
+// SGR mouse reporting (1006): `ESC [ < Cb ; Cx ; Cy M` press, lowercase
+// `m` release. Only decoded while mouse reporting is enabled (the trace
+// viewer's alt screen).
+const SGR_MOUSE = new RegExp(`^${String.fromCharCode(27)}\\[<(\\d+);(\\d+);(\\d+)([Mm])$`, "u");
+
export function parseKey(chunk: Buffer): TerminalKey {
const value = chunk.toString("utf8");
+ const mouse = SGR_MOUSE.exec(value);
+ if (mouse !== null) {
+ return {
+ type: "mouse",
+ action: mouse[4] === "M" ? "press" : "release",
+ button: Number(mouse[1]),
+ x: Number(mouse[2]),
+ y: Number(mouse[3]),
+ };
+ }
+
switch (value) {
case "\u0001":
return { type: "ctrl-a" };
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index d6a7a3465..905a4ad0a 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -112,6 +112,9 @@ import {
type LineState,
} from "./line-editor.js";
import { LiveRegion } from "#cli/ui/live-region.js";
+import { AltScreen } from "#cli/ui/alt-screen.js";
+import type { TraceViewerOpenOptions, TraceViewerRenderer } from "./traces/trace-viewer-session.js";
+import { TraceViewerSession } from "./traces/trace-viewer-session.js";
import { buildStatusLine } from "./status-line.js";
import { nextLogDisplayMode } from "./log-display-mode.js";
import { createTheme, detectUnicode, type Theme } from "./theme.js";
@@ -344,6 +347,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #input: TerminalInput;
readonly #output: TerminalOutput;
readonly #live: LiveRegion;
+ readonly #altScreen: AltScreen;
readonly #theme: Theme;
readonly #tools: TerminalPartDisplayMode;
readonly #reasoning: TerminalPartDisplayMode;
@@ -547,6 +551,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
#flowInterrupt?: () => void;
/** The installed working-state key consumer, so re-arming and disposal can recognize it. */
#flowIdleConsumer?: (key: TerminalKey) => void;
+ /** The open `/traces` viewer session, if the alt-screen viewer is active. */
+ #traceView?: TraceViewerSession;
readonly setupFlow: SetupFlowRenderer = {
begin: (title, indicator) => this.#beginSetupFlow(title, indicator),
end: (options) => this.#endSetupFlow(options?.preserveDiagnostics ?? true),
@@ -565,6 +571,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
waitForInterrupt: (options) => this.#waitForFlowInterrupt(options),
};
+ /** The `/traces` full-screen viewer; resolves when the user closes it. */
+ readonly traceViewer: TraceViewerRenderer = {
+ open: (options) => this.#openTraceViewer(options),
+ };
+
constructor(options?: TerminalRendererOptions) {
this.#input = options?.input ?? process.stdin;
this.#output = options?.output ?? process.stdout;
@@ -573,6 +584,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
// every frame the live region paints would be intercepted as foreign log
// output and re-trigger a paint — unbounded recursion.
this.#live = new LiveRegion(this.#output);
+ this.#altScreen = new AltScreen(this.#output);
this.#theme = createTheme({
color: options?.color ?? true,
unicode: options?.unicode ?? detectUnicode(),
@@ -2640,6 +2652,57 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#onExitRequest?.();
}
+ // ---------------------------------------------------------------------------
+ // Trace viewer (alt-screen)
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Opens the `/traces` viewer on the alternate screen and owns the keyboard
+ * until the user closes it. The transcript's live region stays untouched
+ * underneath — the terminal restores it on exit, so closing just repaints.
+ */
+ async #openTraceViewer(options: TraceViewerOpenOptions): Promise<void> {
+ if (this.#traceView !== undefined || !this.#isInteractive) return;
+ const session = new TraceViewerSession({
+ ...options,
+ theme: this.#theme,
+ dimensions: () => ({ width: this.#width(), height: this.#height() }),
+ paint: (rows) => this.#altScreen.paint(rows, this.#height()),
+ tracingDisabled: process.env.EVE_TRACES === "off",
+ });
+ this.#traceView = session;
+ this.#altScreen.enter();
+ await new Promise<void>((resolve) => {
+ this.#traceViewClose = resolve;
+ this.#consumeKey = (key) => {
+ if (session.handleKey(key) === "close") this.#closeTraceViewer();
+ };
+ this.#attachInput();
+ session.start();
+ });
+ }
+
+ #closeTraceViewer(): void {
+ const session = this.#traceView;
+ if (session === undefined) return;
+ this.#traceView = undefined;
+ session.dispose();
+ this.#detachInput();
+ this.#altScreen.exit();
+ // exit() shows the cursor; hide it before the repaint so it doesn't
+ // blink over the transcript while the live region re-anchors.
+ this.#live.hideCursor();
+ // The main screen comes back exactly as it was (the engine's live-region
+ // row count still matches it), so a normal paint re-anchors cleanly.
+ this.#paint();
+ this.#live.showCursor();
+ const resolve = this.#traceViewClose;
+ this.#traceViewClose = undefined;
+ resolve?.();
+ }
+
+ #traceViewClose?: () => void;
+
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
@@ -2681,6 +2744,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
*/
readonly #onProcessExit = () => {
if (!this.#isInteractive) return;
+ this.#altScreen.exit();
if (this.#input.isTTY) {
this.#live.emitBracketedPaste(false);
this.#input.setRawMode?.(false);
@@ -2689,6 +2753,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
};
#stop() {
+ // An open trace viewer must leave the alt screen before teardown, and its
+ // awaited `open()` resolves so the runner loop can observe the shutdown.
+ this.#closeTraceViewer();
// A reader still awaiting keys can never settle once input detaches;
// rejecting a promise that already settled is a no-op.
const rejectReader = this.#rejectActiveReader;
@@ -3503,6 +3570,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
#paintNow() {
if (!this.#isInteractive) return;
+ // The alt-screen viewer owns the screen while open; resize and stray
+ // paint triggers repaint its frame instead of the transcript.
+ if (this.#traceView !== undefined) {
+ this.#traceView.repaint();
+ return;
+ }
+
const width = this.#width();
const footer = this.#footerRows(width);
const maxBlockRows = Math.max(1, this.#height() - footer.length);
diff --git a/packages/eve/src/cli/dev/tui/test/mock-terminal.ts b/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
index 764675e9d..7edc928a7 100644
--- a/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
+++ b/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
@@ -80,6 +80,7 @@ export class MockScreen extends EventEmitter implements TerminalOutput {
#lines: string[] = [];
#cursorLine = 0;
#cursorColumn = 0;
+ #mainScreen?: { lines: string[]; cursorLine: number; cursorColumn: number };
#waiters: Array<{
text: string;
resolve: () => void;
@@ -249,6 +250,25 @@ export class MockScreen extends EventEmitter implements TerminalOutput {
parameters[0] === undefined || parameters[0] === "" ? fallback : Number(parameters[0]);
if (isPrivate) {
+ // The alternate screen swaps the grid: entering starts the modal view
+ // from a blank screen, leaving restores the transcript snapshot.
+ if (rawParameters === "?1049" && (command === "h" || command === "l")) {
+ if (command === "h") {
+ this.#mainScreen = {
+ lines: this.#lines,
+ cursorLine: this.#cursorLine,
+ cursorColumn: this.#cursorColumn,
+ };
+ this.#lines = [];
+ this.#cursorLine = 0;
+ this.#cursorColumn = 0;
+ } else if (this.#mainScreen !== undefined) {
+ this.#lines = this.#mainScreen.lines;
+ this.#cursorLine = this.#mainScreen.cursorLine;
+ this.#cursorColumn = this.#mainScreen.cursorColumn;
+ this.#mainScreen = undefined;
+ }
+ }
return startIndex + sequence.length;
}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-content.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-content.test.ts
new file mode 100644
index 000000000..795a2898b
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-content.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it } from "vitest";
+
+import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
+
+import { createTheme } from "../theme.js";
+import { formatAttributeContent } from "./trace-content.js";
+
+const THEME = createTheme({ color: false, unicode: true });
+const WIDTH = 60;
+
+function format(key: string, value: unknown, width = WIDTH): string[] {
+ return formatAttributeContent(key, value, THEME, width).map(stripAnsi);
+}
+
+describe("formatAttributeContent", () => {
+ it("passes scalars through on one line", () => {
+ expect(format("gen_ai.request.model", "gpt-5")).toEqual(["gpt-5"]);
+ expect(format("agent.usage.input_tokens", 1234)).toEqual(["1234"]);
+ });
+
+ it("sanitizes non-string attribute values instead of String()ing them", () => {
+ // OTLP array attributes can carry strings with raw escape sequences.
+ // Assert on the unstripped output — stripAnsi would mask an injection.
+ const raw = formatAttributeContent(
+ "agent.session.ids",
+ ["safe", "evil\x1b[2J\x1b]0;owned\x07text"],
+ THEME,
+ WIDTH,
+ ).join("\n");
+ expect(raw).not.toContain("\x1b");
+ expect(raw).not.toContain("\x07");
+ expect(raw).toContain("evil");
+ expect(format("agent.flag", true)).toEqual(["true"]);
+ });
+
+ it("pretty-prints JSON payloads", () => {
+ expect(format("gen_ai.tool.call.arguments", '{"city":"SF","unit":"f"}')).toEqual([
+ "{",
+ ' "city": "SF",',
+ ' "unit": "f"',
+ "}",
+ ]);
+ });
+
+ it("renders prompt messages as role-prefixed blocks", () => {
+ const messages = JSON.stringify([
+ { role: "user", content: "test" },
+ {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "" },
+ { type: "text", text: "Hi! What city?" },
+ { type: "tool-call", toolName: "get_weather", input: { city: "nyc" } },
+ ],
+ },
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolName: "get_weather",
+ output: { type: "text", value: "sunny, 72F" },
+ },
+ ],
+ },
+ ]);
+ expect(format("ai.prompt.messages", messages)).toEqual([
+ "user: test",
+ "assistant: ⟨reasoning⟩",
+ " Hi! What city?",
+ ' → get_weather({"city":"nyc"})',
+ "tool get_weather: sunny, 72F",
+ ]);
+ });
+
+ it("keeps wrapped continuations indented under their block", () => {
+ const longText = "word ".repeat(30).trim();
+ const messages = JSON.stringify([{ role: "assistant", content: longText }]);
+ const lines = format("ai.prompt.messages", messages, 40);
+ expect(lines[0]).toMatch(/^assistant: /);
+ for (const line of lines.slice(1)) expect(line).toMatch(/^ {2}\S/);
+ for (const line of lines) expect(visibleLength(line)).toBeLessThanOrEqual(40);
+ // No content word is lost in wrapping.
+ expect(lines.join(" ").match(/word/g)).toHaveLength(30);
+ });
+
+ it("unwraps typed tool output envelopes", () => {
+ const messages = JSON.stringify([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolName: "get_weather",
+ output: { type: "json", value: { city: "nyc", temperatureF: 72 } },
+ },
+ ],
+ },
+ ]);
+ expect(format("ai.prompt.messages", messages)).toEqual([
+ 'tool get_weather: {"city":"nyc","temperatureF":72}',
+ ]);
+ });
+
+ it("falls back to pretty JSON for non-message payloads", () => {
+ const notMessages = JSON.stringify([{ notARole: true }]);
+ expect(format("ai.prompt.messages", notMessages)).toEqual([
+ "[",
+ " {",
+ ' "notARole": true',
+ " }",
+ "]",
+ ]);
+ });
+
+ it("keeps unparseable strings raw", () => {
+ expect(format("ai.prompt.messages", "not json at all")).toEqual(["not json at all"]);
+ });
+
+ it("renders the truncation marker as a notice before the kept messages", () => {
+ const messages = JSON.stringify([
+ { "eve.truncated": { omittedMessages: 47 } },
+ { role: "user", content: "latest question" },
+ ]);
+ expect(format("ai.prompt.messages", messages)).toEqual([
+ "… 47 earlier messages omitted (long context)",
+ "user: latest question",
+ ]);
+ });
+
+ it("splits embedded newlines in payload text into separate lines", () => {
+ const messages = JSON.stringify([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolName: "load_skill",
+ output: { type: "text", value: "line one.\nline two.\n" },
+ },
+ ],
+ },
+ ]);
+ const lines = format("ai.prompt.messages", messages);
+ expect(lines).toEqual(["tool load_skill: line one.", " line two."]);
+ for (const line of lines) expect(line).not.toContain("\n");
+ });
+
+ it("splits newlines in raw values too", () => {
+ expect(format("custom.payload", "first\nsecond\r\nthird\r")).toEqual([
+ "first",
+ "second",
+ "third",
+ ]);
+ });
+
+ it("strips terminal escape sequences from roles, content, and tool names", () => {
+ const messages = JSON.stringify([
+ { role: "user", content: "hello\x1b[31mred\x1b[0m world" },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "safe\x1b[2Jtext" },
+ { type: "tool-call", toolName: "evil\x1b[?1000h", input: {} },
+ ],
+ },
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolName: "evil\x1b[?1000h",
+ output: { type: "text", value: "r\x1besult" },
+ },
+ ],
+ },
+ ]);
+ const lines = format("ai.prompt.messages", messages);
+ const joined = lines.join("\n");
+ expect(joined).not.toContain("\x1b");
+ expect(joined).toContain("hello");
+ expect(joined).toContain("red");
+ expect(joined).toContain("safe[2Jtext");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-content.ts b/packages/eve/src/cli/dev/tui/traces/trace-content.ts
new file mode 100644
index 000000000..90e3c90df
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-content.ts
@@ -0,0 +1,217 @@
+/**
+ * Formats span attribute values for the `/traces` detail panel. Payload
+ * attributes render as readable structure — prompt messages as a chat-like
+ * transcript with role-prefixed blocks and hanging indents, JSON as
+ * pretty-printed blocks — instead of one wrapped blob. Provider transport
+ * noise was already stripped at capture time (see `agent-otel-provider.ts`),
+ * so what remains here is presentation only.
+ *
+ * Every returned line fits the given width; wrapped continuations keep a
+ * two-space hanging indent so they read as part of their block.
+ */
+
+import { stripTerminalControls, visibleLength, wrapVisibleLine } from "#cli/ui/terminal-text.js";
+
+import type { Theme } from "../theme.js";
+
+/** Indent applied to continuation lines within a block. */
+const CONTINUATION = " ";
+
+/**
+ * Formats one attribute's value into display lines, each at most `width`
+ * columns. A single scalar stays on one line so the panel can keep it beside
+ * its key; multi-line content comes back unindented for the caller to nest
+ * under the key.
+ */
+export function formatAttributeContent(
+ key: string,
+ value: unknown,
+ theme: Theme,
+ width: number,
+): string[] {
+ // Non-string OTLP values include arrays whose elements can carry raw
+ // escape sequences; JSON-encode them (which escapes control characters)
+ // rather than String() them into the frame.
+ if (typeof value !== "string") {
+ if (Array.isArray(value)) return prettyJson(value, width);
+ return [stripTerminalControls(shortJson(value))];
+ }
+ if (key === "ai.prompt.messages") {
+ const transcript = messageTranscript(value, theme, width);
+ if (transcript !== undefined) return transcript;
+ }
+ const parsed = parseJson(value);
+ if (parsed !== undefined && (Array.isArray(parsed) || isRecord(parsed))) {
+ return prettyJson(parsed, width);
+ }
+ return splitEmbeddedNewlines([stripTerminalControls(value)]).flatMap((line) =>
+ wrapVisibleLine(line, width),
+ );
+}
+
+function messageTranscript(raw: string, theme: Theme, width: number): string[] | undefined {
+ const parsed = parseJson(raw);
+ if (!Array.isArray(parsed)) return undefined;
+ // Long conversations are front-truncated at capture time with an
+ // `eve.truncated` marker; it renders as a notice, not a message.
+ let omitted = 0;
+ const messages: Record<string, unknown>[] = [];
+ for (const item of parsed) {
+ if (isRecord(item) && isRecord(item["eve.truncated"])) {
+ const count = item["eve.truncated"].omittedMessages;
+ if (typeof count === "number") {
+ omitted += count;
+ continue;
+ }
+ }
+ messages.push(item);
+ }
+ if (!messages.every((message) => typeof message.role === "string")) {
+ return undefined;
+ }
+ const { colors } = theme;
+ const lines: string[] = [];
+ if (omitted > 0) {
+ lines.push(
+ colors.dim(`… ${omitted} earlier message${omitted === 1 ? "" : "s"} omitted (long context)`),
+ );
+ }
+ for (const message of messages) {
+ const parts = messageContentParts(message.content);
+ const role =
+ message.role === "tool" ? toolRoleLabel(parts) : stripTerminalControls(String(message.role));
+ // The first part sits beside the role prefix; the rest hang underneath.
+ parts.forEach((part, index) => {
+ const prefix = index === 0 ? `${colors.dim(`${role}:`)} ` : CONTINUATION;
+ lines.push(...wrapPrefixed(prefix, part.text, part.dim ? colors.dim : undefined, width));
+ });
+ }
+ return lines;
+}
+
+/** Tool-role messages are about one tool; name it in the role label. */
+function toolRoleLabel(parts: readonly MessageContentPart[]): string {
+ const named = parts.find((part) => part.name !== undefined);
+ return named?.name === undefined ? "tool" : `tool ${named.name}`;
+}
+
+interface MessageContentPart {
+ readonly text: string;
+ readonly dim?: boolean;
+ readonly name?: string;
+}
+
+function messageContentParts(content: unknown): MessageContentPart[] {
+ if (typeof content === "string") return [{ text: stripTerminalControls(content) }];
+ if (!Array.isArray(content)) return [{ text: shortJson(content) }];
+ const parts: MessageContentPart[] = [];
+ for (const part of content) {
+ if (!isRecord(part) || typeof part.type !== "string") {
+ parts.push({ text: shortJson(part) });
+ continue;
+ }
+ if (part.type === "text" && typeof part.text === "string") {
+ parts.push({ text: stripTerminalControls(part.text) });
+ } else if (part.type === "reasoning") {
+ const text = typeof part.text === "string" ? stripTerminalControls(part.text.trim()) : "";
+ parts.push({ dim: true, text: text.length > 0 ? `⟨reasoning⟩ ${text}` : "⟨reasoning⟩" });
+ } else if (part.type === "tool-call" && typeof part.toolName === "string") {
+ const name = stripTerminalControls(part.toolName);
+ parts.push({ name, text: `→ ${name}(${shortJson(part.input)})` });
+ } else if (part.type === "tool-result" && typeof part.toolName === "string") {
+ const name = stripTerminalControls(part.toolName);
+ parts.push({ name, text: toolOutputText(part.output) });
+ } else {
+ parts.push({ text: shortJson(part) });
+ }
+ }
+ if (parts.length === 0) parts.push({ text: shortJson(content) });
+ return parts;
+}
+
+/**
+ * Unwraps the AI SDK's typed output envelopes: `{"type":"text","value":"…"}`
+ * renders as the text, `{"type":"json","value":{…}}` as the inner payload's
+ * compact JSON. Everything else renders as compact JSON.
+ */
+function toolOutputText(output: unknown): string {
+ if (isRecord(output) && typeof output.type === "string" && "value" in output) {
+ if (output.type === "text" && typeof output.value === "string")
+ return stripTerminalControls(output.value);
+ return shortJson(output.value);
+ }
+ return shortJson(output);
+}
+
+/** Pretty-prints a JSON value with two-space indents, wrapped to `width`. */
+export function prettyJson(value: unknown, width: number): string[] {
+ return JSON.stringify(value, null, 2)
+ .split("\n")
+ .flatMap((line) => wrapHanging(line, width, width));
+}
+
+/**
+ * Wraps `text` at `width` with `prefix` (possibly ANSI-styled) on the first
+ * line and the hanging continuation indent on the rest. `dim` styles content
+ * only, keeping wrap points independent of ANSI sequences.
+ */
+function wrapPrefixed(
+ prefix: string,
+ text: string,
+ dim: ((text: string) => string) | undefined,
+ width: number,
+): string[] {
+ const style = dim ?? ((value: string) => value);
+ const lines: string[] = [];
+ splitEmbeddedNewlines([text]).forEach((logical, logicalIndex) => {
+ const head = logicalIndex === 0 ? prefix : CONTINUATION;
+ const headWidth = logicalIndex === 0 ? visibleLength(prefix) : CONTINUATION.length;
+ const firstWidth = Math.max(8, width - headWidth);
+ wrapHanging(logical, width, firstWidth).forEach((chunk, chunkIndex) => {
+ lines.push(chunkIndex === 0 ? `${head}${style(chunk)}` : `${CONTINUATION}${style(chunk)}`);
+ });
+ });
+ return lines;
+}
+
+/** Word-wraps to `width` where the first line may be tighter (`firstWidth`). */
+function wrapHanging(text: string, width: number, firstWidth: number): string[] {
+ const chunks = wrapVisibleLine(text, Math.max(8, width - CONTINUATION.length));
+ if (visibleLength(chunks[0] ?? "") <= firstWidth) return chunks;
+ // The first line shares its row with a prefix: re-wrap just that chunk at
+ // the tighter width and fold the overflow ahead of the remaining chunks.
+ const [head, ...rest] = wrapVisibleLine(chunks[0] ?? "", Math.max(8, firstWidth));
+ return [head ?? "", ...rest, ...chunks.slice(1)];
+}
+
+/**
+ * Payload text can carry real newlines (tool results frequently end with one).
+ * Left raw, they split a composed frame row and inject phantom lines into the
+ * frame. Split them into real display lines; a trailing newline's empty tail
+ * is dropped.
+ */
+export function splitEmbeddedNewlines(lines: readonly string[]): string[] {
+ const split = lines.flatMap((line) => line.split(/\r\n|\r|\n/));
+ while (split.length > 1 && split[split.length - 1] === "") split.pop();
+ return split;
+}
+
+function shortJson(value: unknown): string {
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+}
+
+function parseJson(value: string): unknown {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts
new file mode 100644
index 000000000..d53e9039c
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts
@@ -0,0 +1,425 @@
+import { describe, expect, it } from "vitest";
+
+import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import { createTheme } from "../theme.js";
+import { buildConversationItems, renderConversationItem } from "./trace-conversation.js";
+
+const THEME = createTheme({ color: false, unicode: true });
+const BASE = 1_700_000_000_000_000_000n;
+
+function span(
+ spanId: string,
+ name: string,
+ startMs: number,
+ endMs: number,
+ parentSpanId?: string,
+ attributes: Readonly<Record<string, unknown>> = {},
+ statusCode = 0,
+): LocalTraceSpan {
+ return {
+ attributes,
+ endTimeNs: BASE + BigInt(endMs) * 1_000_000n,
+ name,
+ parentSpanId,
+ spanId,
+ startTimeNs: BASE + BigInt(startMs) * 1_000_000n,
+ statusCode,
+ traceId: "t".repeat(32),
+ };
+}
+
+function trace(spans: readonly LocalTraceSpan[]): LocalTrace {
+ return {
+ endTimeNs: spans.reduce((m, s) => (s.endTimeNs > m ? s.endTimeNs : m), 0n),
+ sessionIds: [],
+ spans,
+ startTimeNs: spans.reduce((m, s) => (s.startTimeNs < m ? s.startTimeNs : m), BASE),
+ traceId: "t".repeat(32),
+ };
+}
+
+function weatherTurn(): LocalTraceSpan[] {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, { "agent.turn.id": "turn_0" });
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {});
+ const messages = JSON.stringify([
+ { role: "user", content: "weather in nyc?" },
+ { role: "assistant", content: "hi" },
+ { role: "user", content: "weather in sf?" },
+ ]);
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 2000, step.spanId, {
+ "gen_ai.request.model": "claude-test",
+ "ai.prompt.messages": messages,
+ "ai.response.text": "Let me check.",
+ "agent.usage.input_tokens": 6200,
+ "agent.usage.output_tokens": 50,
+ });
+ const action = span("d".repeat(16), "agent.action", 2100, 2400, step.spanId, {});
+ const toolCall = span("e".repeat(16), "ai.toolCall", 2100, 2400, action.spanId, {
+ "gen_ai.tool.name": "get_weather",
+ "gen_ai.tool.call.arguments": '{"city":"sf"}',
+ "gen_ai.tool.call.result": '{"temperatureF":72}',
+ });
+ return [turn, step, model, action, toolCall];
+}
+
+describe("buildConversationItems", () => {
+ it("extracts the user message from the turn's first model prompt", () => {
+ const items = buildConversationItems(trace(weatherTurn()));
+ expect(items[0]?.kind).toBe("user");
+ expect(items[0]?.text).toBe("weather in sf?");
+ expect(items[0]?.span.name).toBe("agent.turn");
+ });
+
+ it("builds assistant and tool items in time order", () => {
+ const items = buildConversationItems(trace(weatherTurn()));
+ expect(items.map((item) => item.kind)).toEqual(["user", "assistant", "tool"]);
+ expect(items[1]?.text).toBe("Let me check.");
+ expect(items[1]?.model).toBe("claude-test");
+ expect(items[1]?.inputTokens).toBe(6200);
+ expect(items[2]?.name).toBe("get_weather");
+ expect(items[2]?.args).toBe('{"city":"sf"}');
+ expect(items[2]?.result).toBe('{"temperatureF":72}');
+ });
+
+ it("finds turns parented to a session window span", () => {
+ // Post-windowing capture: turns are children of the `agent.session` root,
+ // so turn discovery must go by name, not root position.
+ const window = span("0".repeat(16), "agent.session", 0, 0, undefined, {
+ "agent.session.window": 0,
+ });
+ const spans = weatherTurn().map((s) =>
+ s.name === "agent.turn" ? { ...s, parentSpanId: window.spanId } : s,
+ );
+ const items = buildConversationItems(trace([window, ...spans]));
+ expect(items.map((item) => item.kind)).toEqual(["user", "assistant", "tool"]);
+ });
+
+ it("marks turns dispatched by another turn as subagent items", () => {
+ const parent = weatherTurn();
+ const childTurn = span("f".repeat(16), "agent.turn", 6000, 6000, undefined, {
+ "agent.parent.call_id": "call-7",
+ "agent.parent.session.id": "session-root",
+ "agent.parent.turn.id": "turn_0",
+ "agent.subagent.name": "echo-marker",
+ });
+ const childStep = span("1".repeat(16), "agent.step", 6010, 8000, childTurn.spanId, {});
+ const childModel = span(
+ "2".repeat(16),
+ "ai.streamText.doStream",
+ 6020,
+ 7000,
+ childStep.spanId,
+ {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "delegated task" }]),
+ "ai.response.text": "delegated reply",
+ },
+ );
+ const items = buildConversationItems(trace([...parent, childTurn, childStep, childModel]));
+ const parentItems = items.filter((item) => item.subagent === undefined);
+ const childItems = items.filter((item) => item.subagent !== undefined);
+ expect(parentItems.length).toBeGreaterThan(0);
+ expect(childItems.map((item) => item.kind)).toEqual(["user", "assistant"]);
+ expect(childItems[0]?.subagent).toEqual({
+ name: "echo-marker",
+ parentCallId: "call-7",
+ parentTurnId: "turn_0",
+ });
+ });
+
+ it("interleaves a subagent's cards between the parent's dispatch and reply", () => {
+ // The parent parks while the child runs: step 1 dispatches, the child
+ // works, step 2 replies with the result. Cards must read in that order,
+ // not with the child appended after the parent's whole turn.
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step1 = span("b".repeat(16), "agent.step", 10, 20, turn.spanId, {});
+ const dispatch = span("c".repeat(16), "ai.streamText.doStream", 12, 18, step1.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "run the subagent" }]),
+ "ai.response.text": "Dispatching.",
+ });
+ const childTurn = span("f".repeat(16), "agent.turn", 30, 30, undefined, {
+ "agent.parent.call_id": "call-1",
+ "agent.parent.session.id": "session-root",
+ "agent.parent.turn.id": "turn_0",
+ "agent.subagent.name": "echo-marker",
+ });
+ const childStep = span("1".repeat(16), "agent.step", 32, 40, childTurn.spanId, {});
+ const childModel = span("2".repeat(16), "ai.streamText.doStream", 34, 38, childStep.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "delegated task" }]),
+ "ai.response.text": "delegated reply",
+ });
+ const step2 = span("3".repeat(16), "agent.step", 50, 60, turn.spanId, {});
+ const reply = span("4".repeat(16), "ai.streamText.doStream", 52, 58, step2.spanId, {
+ "ai.response.text": "The subagent said: delegated reply",
+ });
+ const items = buildConversationItems(
+ trace([turn, step1, dispatch, childTurn, childStep, childModel, step2, reply]),
+ );
+ expect(items.map((item) => [item.kind, item.subagent !== undefined])).toEqual([
+ ["user", false],
+ ["assistant", false],
+ ["user", true],
+ ["assistant", true],
+ ["assistant", false],
+ ]);
+ });
+
+ it("skips model spans with no response text", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 2000, step.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ });
+ const items = buildConversationItems(trace([turn, step, model]));
+ expect(items.map((item) => item.kind)).toEqual(["user"]);
+ });
+
+ it("keeps model spans that failed with an error", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {});
+ const model = span(
+ "c".repeat(16),
+ "ai.streamText.doStream",
+ 20,
+ 2000,
+ step.spanId,
+ { "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]) },
+ 2,
+ );
+ const items = buildConversationItems(trace([turn, step, model]));
+ expect(items.map((item) => item.kind)).toEqual(["user", "assistant"]);
+ expect(items[1]?.error).toBe(true);
+ });
+
+ it("keeps model spans that carry only token usage", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 2000, step.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "agent.usage.input_tokens": 100,
+ "agent.usage.output_tokens": 10,
+ });
+ const items = buildConversationItems(trace([turn, step, model]));
+ expect(items.map((item) => item.kind)).toEqual(["user", "assistant"]);
+ expect(items[1]?.inputTokens).toBe(100);
+ });
+
+ it("flags error tool calls", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 100, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 50, step.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "agent.usage.input_tokens": 10,
+ });
+ const action = span("d".repeat(16), "agent.action", 60, 200, step.spanId, {});
+ const toolCall = span(
+ "e".repeat(16),
+ "ai.toolCall",
+ 60,
+ 200,
+ action.spanId,
+ { "gen_ai.tool.name": "explode" },
+ 2,
+ );
+ const items = buildConversationItems(trace([turn, step, model, action, toolCall]));
+ expect(items.map((item) => item.kind)).toEqual(["user", "assistant", "tool"]);
+ expect(items[2]?.error).toBe(true);
+ });
+});
+
+describe("renderConversationItem", () => {
+ it("renders the user message as a borderless card", () => {
+ const user = buildConversationItems(trace(weatherTurn())).find((item) => item.kind === "user")!;
+ const lines = renderConversationItem(user, 60, THEME, false, false).map(stripAnsi);
+ // Padded header band, one body padding row, content, one padding row.
+ expect(lines[0]).toMatch(/^ +$/);
+ expect(lines[1]).toMatch(/^ {4}user + {4}$/);
+ expect(lines[2]).toMatch(/^ +$/);
+ expect(lines[3]).toMatch(/^ +$/);
+ expect(lines[4]).toMatch(/^ {4}weather in sf\? + {4}$/);
+ expect(lines[5]).toMatch(/^ +$/);
+ expect(lines).toHaveLength(6);
+ });
+
+ it("renders the assistant title with model on the left and metrics right-aligned", () => {
+ const assistant = buildConversationItems(trace(weatherTurn())).find(
+ (item) => item.kind === "assistant",
+ )!;
+ const lines = renderConversationItem(assistant, 80, THEME, false, false).map(stripAnsi);
+ expect(lines[1]).toContain("assistant");
+ expect(lines[1]).toContain("claude-test");
+ // Duration, tokens, and cost are right-aligned at the end of the row.
+ expect(lines[1]!.trimEnd()).toMatch(/2s.*↑6\.2K.*↓50$/);
+ });
+
+ it("badges every card of a subagent turn with the dispatch lineage", () => {
+ const assistant = buildConversationItems(trace(weatherTurn())).find(
+ (item) => item.kind === "assistant",
+ )!;
+ const named = {
+ ...assistant,
+ subagent: { name: "echo-marker", parentCallId: "call-1", parentTurnId: "turn_0" },
+ };
+ const lines = renderConversationItem(named, 80, THEME, false, false).map(stripAnsi);
+ expect(lines[1]).toContain("subagent:echo-marker");
+
+ const anonymous = {
+ ...assistant,
+ subagent: { parentTurnId: "turn_0" },
+ };
+ const anonymousLines = renderConversationItem(anonymous, 80, THEME, false, false).map(
+ stripAnsi,
+ );
+ expect(anonymousLines[1]).toContain("subagent");
+ expect(anonymousLines[1]).not.toContain("subagent:");
+ });
+
+ it("labels a subagent turn's user card as its task", () => {
+ const user = buildConversationItems(trace(weatherTurn())).find((item) => item.kind === "user")!;
+ const delegated = {
+ ...user,
+ subagent: { name: "echo-marker", parentTurnId: "turn_0" },
+ };
+ const lines = renderConversationItem(delegated, 80, THEME, false, false).map(stripAnsi);
+ expect(lines[1]).toContain("task");
+ expect(lines[1]).toContain("subagent:echo-marker");
+ expect(lines[1]).not.toMatch(/\buser\b/);
+ });
+
+ it("shows gateway cost right-aligned when the step span carries it", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {
+ "gen_ai.usage.cost": 0.0031,
+ });
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 2000, step.spanId, {
+ "gen_ai.request.model": "claude-test",
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.response.text": "reply",
+ "agent.usage.input_tokens": 100,
+ });
+ const assistant = buildConversationItems(trace([turn, step, model])).find(
+ (item) => item.kind === "assistant",
+ )!;
+ expect(assistant.costUsd).toBe(0.0031);
+ const lines = renderConversationItem(assistant, 80, THEME, false, false).map(stripAnsi);
+ expect(lines[1]!.trimEnd()).toMatch(/\$0\.0031$/);
+ });
+
+ it("renders tool calls as their own cards with args and result", () => {
+ const items = buildConversationItems(trace(weatherTurn()));
+ const tool = items.find((item) => item.kind === "tool")!;
+ const lines = renderConversationItem(tool, 60, THEME, false, false).map(stripAnsi);
+ expect(lines[1]).toContain("get_weather");
+ // Duration is right-aligned at the end of the header row.
+ expect(lines[1]!.trimEnd()).toMatch(/300ms$/);
+ expect(lines.some((line) => line.includes("Input:"))).toBe(true);
+ expect(lines.some((line) => line.includes('"city": "sf"'))).toBe(true);
+ expect(lines.some((line) => line.includes("Output:"))).toBe(true);
+ expect(lines.some((line) => line.includes('"temperatureF": 72'))).toBe(true);
+ });
+
+ it("renders the system prompt as a card with estimated tokens and a preview", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 100, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 50, step.spanId, {
+ "ai.prompt.system": "You are a test assistant. Be brief.",
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ });
+ const items = buildConversationItems(trace([turn, step, model]));
+ expect(items[0]?.kind).toBe("system");
+
+ const collapsed = renderConversationItem(items[0]!, 60, THEME, false, false).map(stripAnsi);
+ expect(collapsed).toHaveLength(6);
+ expect(collapsed[1]).toContain("system");
+ expect(collapsed[1]!.trimEnd()).toMatch(/~9 tokens$/);
+ // Short prompts fit the cap — no fold marker.
+ expect(collapsed[1]).not.toContain("▸");
+ expect(collapsed[4]).toContain("You are a test assistant. Be brief.");
+
+ const long = {
+ ...items[0]!,
+ text: "You are a test assistant.\n\nBe thorough, precise, and concise.\n".repeat(10),
+ };
+ const truncated = renderConversationItem(long, 60, THEME, false, false).map(stripAnsi);
+ expect(truncated[1]).toContain("▸ system");
+ const expanded = renderConversationItem(long, 60, THEME, false, true).map(stripAnsi);
+ expect(expanded[1]).toContain("▾ system");
+ expect(expanded.length).toBeGreaterThan(truncated.length);
+ });
+
+ it("renders assistant reasoning dim above the reply", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 100, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 50, step.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.response.reasoning": "let me think about this",
+ "ai.response.text": "here is my answer",
+ });
+ const assistant = buildConversationItems(trace([turn, step, model])).find(
+ (item) => item.kind === "assistant",
+ )!;
+ expect(assistant.reasoning).toBe("let me think about this");
+ const lines = renderConversationItem(assistant, 60, THEME, false, false).map(stripAnsi);
+ const headerIndex = lines.findIndex((line) => line.includes("Thought:"));
+ const reasoningIndex = lines.findIndex((line) => line.includes("let me think about this"));
+ const answerIndex = lines.findIndex((line) => line.includes("here is my answer"));
+ // Thought: header, a blank line, the reasoning, a blank line, the reply.
+ expect(headerIndex).toBeGreaterThan(-1);
+ expect(lines[headerIndex + 1]!.trim()).toBe("");
+ expect(reasoningIndex).toBe(headerIndex + 2);
+ expect(lines[reasoningIndex + 1]!.trim()).toBe("");
+ expect(answerIndex).toBe(reasoningIndex + 2);
+ });
+
+ it("keeps reasoning-only responses as assistant cards", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, {});
+ const step = span("b".repeat(16), "agent.step", 10, 100, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 50, step.spanId, {
+ "ai.response.reasoning": "only thinking, no reply text",
+ });
+ const items = buildConversationItems(trace([turn, step, model]));
+ expect(items.map((item) => item.kind)).toEqual(["assistant"]);
+ });
+
+ it("caps collapsed payloads and renders them fully when expanded", () => {
+ const items = buildConversationItems(trace(weatherTurn()));
+ const tool = items.find((item) => item.kind === "tool")!;
+ const long = { ...tool, result: "x".repeat(500) };
+ const collapsed = renderConversationItem(long, 60, THEME, false, false).map(stripAnsi);
+ expect(collapsed.some((line) => line.trim() === "…")).toBe(true);
+ expect(collapsed.some((line) => line.includes("Click to expand"))).toBe(true);
+ const expanded = renderConversationItem(long, 60, THEME, false, true).map(stripAnsi);
+ expect(expanded.length).toBeGreaterThan(collapsed.length);
+ expect(expanded.some((line) => line.includes("Click to collapse"))).toBe(true);
+ });
+
+ it("marks the selected card with a bright bar and a solid surface", () => {
+ const assistant = buildConversationItems(trace(weatherTurn())).find(
+ (item) => item.kind === "assistant",
+ )!;
+ const themed = createTheme({ color: true, unicode: true });
+ const lines = renderConversationItem(assistant, 80, themed, true, false);
+ for (const line of lines) {
+ // Cyan half-block bar on the left edge, no inverse.
+ expect(line).toContain("\x1b[97m▌\x1b[39m");
+ expect(line).not.toContain("\x1b[7m");
+ }
+ // Header band rows in near-black, body rows in dark gray.
+ for (const line of lines.slice(0, 3)) expect(line).toContain("\x1b[48;2;22;22;22m");
+ for (const line of lines.slice(3)) expect(line).toContain("\x1b[48;2;36;36;36m");
+ // The assistant title is bold white.
+ expect(lines[1]).toContain("\x1b[97m");
+ const unselected = renderConversationItem(assistant, 80, themed, false, false);
+ expect(unselected[0]).not.toContain("▌");
+ expect(unselected[0]).toContain("\x1b[48;2;22;22;22m");
+ });
+
+ it("never emits rows wider than the given width", () => {
+ for (const item of buildConversationItems(trace(weatherTurn()))) {
+ for (const line of renderConversationItem(item, 40, THEME, false, false)) {
+ expect(visibleLength(line)).toBeLessThanOrEqual(40);
+ }
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts
new file mode 100644
index 000000000..13692eb3f
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts
@@ -0,0 +1,569 @@
+/**
+ * Conversation view for the `/traces` viewer: the same trace, re-told as a
+ * flow of user messages, assistant replies, and tool calls instead of a
+ * latency waterfall. Items are built from the span tree (turns in order,
+ * subtrees in time order) with text pulled from the content attributes —
+ * the user's message from the turn's first model prompt, replies and tool
+ * calls from response/tool spans.
+ */
+
+import { formatElapsed } from "#cli/format-elapsed.js";
+import {
+ clipVisible,
+ stripTerminalControls,
+ visibleLength,
+ wrapVisibleLine,
+} from "#cli/ui/terminal-text.js";
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+import { compareLocalTraceSpans } from "#harness/local-trace-reader.js";
+
+import { formatCompactTokenCount } from "../stream-format.js";
+import type { Theme } from "../theme.js";
+import { prettyJson, splitEmbeddedNewlines } from "./trace-content.js";
+
+export interface ConversationItem {
+ readonly kind: "system" | "user" | "assistant" | "tool";
+ /** Detail-drawer source for this item (the turn marker span for users). */
+ readonly span: LocalTraceSpan;
+ /** Tool name for tool items. */
+ readonly name?: string;
+ /** Message text for system/user/assistant items. */
+ readonly text?: string;
+ /** Model reasoning for assistant items (shown dim above the reply). */
+ readonly reasoning?: string;
+ /** Tool names from the model's tool-call decision (shown when no text). */
+ readonly toolCallNames?: readonly string[];
+ /** Raw JSON for tool input / output. */
+ readonly args?: string;
+ readonly result?: string;
+ /** Assistant card metadata. */
+ readonly model?: string;
+ readonly inputTokens?: number;
+ readonly outputTokens?: number;
+ /** Gateway-reported inference cost in USD (from the ancestor step span). */
+ readonly costUsd?: number;
+ /** Set when the item's turn was delegated by another turn (a subagent). */
+ readonly subagent?: ConversationSubagent;
+ readonly durationMs: number;
+ readonly error: boolean;
+}
+
+/** Dispatch lineage for a subagent turn, read from the turn span. */
+export interface ConversationSubagent {
+ /** Subagent name, when the turn arrived through the subagent adapter. */
+ readonly name?: string;
+ /** Turn id of the dispatching parent turn. */
+ readonly parentTurnId: string;
+ /** Tool call id of the dispatch, when recorded. */
+ readonly parentCallId?: string;
+}
+
+/** Max rendered lines for one collapsed card payload (args, result, or text). */
+const CARD_PAYLOAD_LINES = 3;
+
+/** Builds the conversation flow for a trace, one item per message/action. */
+export function buildConversationItems(trace: LocalTrace): ConversationItem[] {
+ const byId = new Map(trace.spans.map((span) => [span.spanId, span]));
+ const children = new Map<string, LocalTraceSpan[]>();
+ for (const span of trace.spans) {
+ if (span.parentSpanId === undefined) continue;
+ const siblings = children.get(span.parentSpanId) ?? [];
+ siblings.push(span);
+ children.set(span.parentSpanId, siblings);
+ }
+ for (const siblings of children.values()) siblings.sort(compareLocalTraceSpans);
+
+ // Turns are matched by name, not by root position: they parent to the
+ // `agent.session` window span when one exists (and to nothing on older
+ // spools), and a subagent child's turns sit beside the parent's in the
+ // same trace.
+ const turns = trace.spans.filter((span) => span.name === "agent.turn");
+ turns.sort(compareLocalTraceSpans);
+
+ // Cards order by when their span started, not turn by turn: a parent
+ // parks while its subagent runs and resumes afterwards, so the child's
+ // cards belong between the parent's dispatch step and its final reply.
+ // The system card pins to the front regardless.
+ const entries: { readonly item: ConversationItem; readonly order: bigint }[] = [];
+ for (const root of turns) {
+ const subagent = turnSubagent(root);
+ const subtree: LocalTraceSpan[] = [];
+ const walk = (span: LocalTraceSpan): void => {
+ subtree.push(span);
+ for (const child of children.get(span.spanId) ?? []) walk(child);
+ };
+ walk(root);
+ subtree.sort(compareLocalTraceSpans);
+
+ if (entries.length === 0) {
+ const systemSpan = subtree.find(
+ (span) => isModelSpan(span) && typeof span.attributes["ai.prompt.system"] === "string",
+ );
+ const systemText = systemSpan?.attributes["ai.prompt.system"];
+ if (systemSpan !== undefined && typeof systemText === "string" && systemText.length > 0) {
+ entries.push({
+ item: {
+ kind: "system",
+ durationMs: 0,
+ error: false,
+ span: systemSpan,
+ subagent,
+ text: systemText,
+ },
+ order: 0n,
+ });
+ }
+ }
+ const userText = extractUserText(subtree.find(isModelSpan));
+ if (userText !== undefined) {
+ entries.push({
+ item: {
+ kind: "user",
+ durationMs: 0,
+ error: false,
+ span: root,
+ subagent,
+ text: userText,
+ },
+ order: root.startTimeNs,
+ });
+ }
+ for (const span of subtree) {
+ if (isModelSpan(span)) {
+ const text = stringAttribute(span, "ai.response.text");
+ const reasoning = stringAttribute(span, "ai.response.reasoning");
+ const hasUsage =
+ numberAttribute(span, "agent.usage.input_tokens") !== undefined ||
+ numberAttribute(span, "agent.usage.output_tokens") !== undefined;
+ const hasToolCalls = span.attributes["ai.response.tool_calls"] !== undefined;
+ const isEmpty =
+ (text === undefined || text.trim().length === 0) &&
+ (reasoning === undefined || reasoning.trim().length === 0) &&
+ !hasUsage &&
+ !hasToolCalls &&
+ span.statusCode !== 2;
+ if (isEmpty) continue;
+ entries.push({
+ item: {
+ kind: "assistant",
+ costUsd: stepCostUsd(span, byId),
+ durationMs: spanDurationMs(span),
+ error: span.statusCode === 2,
+ inputTokens: numberAttribute(span, "agent.usage.input_tokens"),
+ model: stringAttribute(span, "gen_ai.request.model"),
+ outputTokens: numberAttribute(span, "agent.usage.output_tokens"),
+ reasoning,
+ span,
+ subagent,
+ text,
+ toolCallNames: hasToolCalls
+ ? parseToolCallNames(stringAttribute(span, "ai.response.tool_calls"))
+ : undefined,
+ },
+ order: span.startTimeNs,
+ });
+ } else if (span.name === "ai.toolCall") {
+ entries.push({
+ item: {
+ kind: "tool",
+ args: stringAttribute(span, "gen_ai.tool.call.arguments"),
+ durationMs: spanDurationMs(span),
+ error: span.statusCode === 2,
+ name: stripTerminalControls(stringAttribute(span, "gen_ai.tool.name") ?? "tool"),
+ result: unwrapJsonString(stringAttribute(span, "gen_ai.tool.call.result")),
+ span,
+ subagent,
+ },
+ order: span.startTimeNs,
+ });
+ }
+ }
+ }
+ // Stable, so equal timestamps keep their per-turn emission order.
+ return entries
+ .sort((left, right) => (left.order === right.order ? 0 : left.order < right.order ? -1 : 1))
+ .map((entry) => entry.item);
+}
+
+/** Reads the dispatch lineage a subagent turn carries on its turn span. */
+function turnSubagent(turn: LocalTraceSpan): ConversationSubagent | undefined {
+ const parentTurnId = stringAttribute(turn, "agent.parent.turn.id");
+ if (parentTurnId === undefined) return undefined;
+ const name = stringAttribute(turn, "agent.subagent.name");
+ return {
+ name: name === undefined ? undefined : stripTerminalControls(name),
+ parentCallId: stringAttribute(turn, "agent.parent.call_id"),
+ parentTurnId,
+ };
+}
+
+/**
+ * Renders one conversation card, width-clipped: message kinds (system, user,
+ * assistant) as rounded text bubbles, tool calls as bordered boxes. Collapsed
+ * cards cap their payloads; expanded ones render them in full. The system
+ * bubble is title-only until expanded.
+ */
+export function renderConversationItem(
+ item: ConversationItem,
+ width: number,
+ theme: Theme,
+ selected: boolean,
+ expanded: boolean,
+): string[] {
+ const { colors, glyph } = theme;
+ const inner = Math.max(8, width - 8);
+ const expandable = conversationItemExpandable(item, width);
+
+ let leftTitle: string;
+ let rightTitle: string;
+ const body: string[] = [];
+ if (item.kind === "tool") {
+ const name = colors.bold(colors.white(item.name ?? "tool"));
+ leftTitle = `${foldMarker(expanded, expandable, theme)}${name}`;
+ rightTitle = item.durationMs > 0 ? colors.dim(formatElapsed(item.durationMs)) : "";
+ const argsLines = item.args === undefined ? [] : payloadJsonLines(item.args, inner);
+ const resultLines = item.result === undefined ? [] : payloadJsonLines(item.result, inner);
+ const cappedArgs = expanded ? argsLines : capLines(argsLines, inner);
+ const cappedResult = expanded ? resultLines : capLines(resultLines, inner);
+ if (cappedArgs.length > 0) {
+ body.push("", colors.dim("Input:"), "", ...cappedArgs);
+ }
+ if (cappedResult.length > 0) {
+ body.push("", colors.dim("Output:"), "", ...cappedResult);
+ }
+ } else if (item.kind === "system") {
+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(colors.white("system"))}`;
+ rightTitle = colors.dim(`~${formatCompactTokenCount(estimateTokens(item.text ?? ""))} tokens`);
+ const uncapped = wrapText(item.text ?? "", inner);
+ body.push(...(expanded ? uncapped : capLines(uncapped, inner)));
+ } else if (item.kind === "assistant") {
+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(colors.white("assistant"))}${
+ item.model !== undefined ? colors.dim(` · ${stripTerminalControls(item.model)}`) : ""
+ }`;
+ rightTitle = assistantMetrics(item, glyph, colors);
+ const reasoningUncapped =
+ item.reasoning === undefined || item.reasoning.trim().length === 0
+ ? []
+ : payloadLines(item.reasoning, inner);
+ const textUncapped =
+ item.text === undefined || item.text.trim().length === 0
+ ? []
+ : payloadLines(item.text, inner);
+ const reasoningLines = (expanded ? reasoningUncapped : capLines(reasoningUncapped, inner)).map(
+ (line) => colors.dim(line),
+ );
+ const textLines = expanded ? textUncapped : capLines(textUncapped, inner);
+ // Reasoning renders as its own headed section so it never reads as part
+ // of the reply, with a blank line separating it from what follows.
+ if (reasoningLines.length > 0) {
+ body.push(colors.dim("Thought:"), "", ...reasoningLines);
+ if (textLines.length > 0) body.push("");
+ }
+ body.push(...textLines);
+ // Tool-call-only response (no text): show the decision as the body.
+ if (
+ (item.text === undefined || item.text.trim().length === 0) &&
+ item.toolCallNames !== undefined &&
+ item.toolCallNames.length > 0
+ ) {
+ if (reasoningLines.length > 0) body.push("");
+ for (const name of item.toolCallNames) {
+ body.push(colors.dim(`→ ${name}`));
+ }
+ }
+ } else {
+ // A subagent's "user" message is the synthesized delegated prompt, not
+ // something the user typed — label it as the task it is.
+ const label = item.kind === "user" && item.subagent !== undefined ? "task" : item.kind;
+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(colors.white(label))}`;
+ rightTitle = "";
+ const textUncapped =
+ item.text === undefined || item.text.trim().length === 0
+ ? []
+ : payloadLines(item.text, inner);
+ body.push(...(expanded ? textUncapped : capLines(textUncapped, inner)));
+ }
+ // Delegated work is called out on every card of the subagent's turn so it
+ // never reads as the main conversation.
+ if (item.subagent !== undefined) {
+ const label = item.subagent.name === undefined ? "subagent" : `subagent:${item.subagent.name}`;
+ leftTitle += colors.dim(` · ${label}`);
+ }
+ // A truncated card advertises its affordance: ellipsis on its own line,
+ // a gap, then the click hint (which flips once open).
+ if (!expanded && expandable) {
+ body.push("…", "", colors.dim("Click to expand"));
+ } else if (expanded && expandable) {
+ body.push("", colors.dim("Click to collapse"));
+ }
+
+ // The header is a band with vertical padding on both sides of the title,
+ // so the card's identity dominates its content; the body gets a padding
+ // row at both ends. Failures paint the whole card red instead of an icon.
+ const headerSurface = item.error ? CARD_ERROR_SURFACE_HEADER : CARD_SURFACE_HEADER;
+ const bodySurface = item.error ? CARD_ERROR_SURFACE_BODY : CARD_SURFACE_BODY;
+ return [
+ cardRow("", width, theme, selected, headerSurface),
+ cardSplitRow(leftTitle, rightTitle, width, theme, selected, headerSurface),
+ cardRow("", width, theme, selected, headerSurface),
+ cardRow("", width, theme, selected, bodySurface),
+ ...body.map((line) => cardRow(line, width, theme, selected, bodySurface)),
+ cardRow("", width, theme, selected, bodySurface),
+ ];
+}
+
+/**
+ * Cards are two-band blocks on the viewer's true-black canvas: a header
+ * band in near-black over body rows in dark gray so the content reads as
+ * the dominant surface, with one cell of margin
+ * on each side (the right margin matching the selection bar's column for
+ * symmetry) and two cells of padding inside. The vocabulary is the Vercel
+ * aesthetic — monochrome surfaces with color reserved for status — and
+ * truecolor is exempt from tinted-theme palette remapping. The selected
+ * card carries a cyan half-block bar down its left edge.
+ */
+const CARD_SURFACE_HEADER = "\x1b[48;2;22;22;22m";
+const CARD_SURFACE_BODY = "\x1b[48;2;36;36;36m";
+const CARD_ERROR_SURFACE_HEADER = "\x1b[48;2;69;32;37m";
+const CARD_ERROR_SURFACE_BODY = "\x1b[48;2;58;26;31m";
+const CARD_SURFACE_CLOSE = "\x1b[49m";
+const RESET_ALL = "\x1b[0m";
+
+function cardRow(
+ line: string,
+ width: number,
+ theme: Theme,
+ selected: boolean,
+ surface: string,
+): string {
+ const bar = selected ? theme.colors.white("▌") : " ";
+ const clipped = clipVisible(line, Math.max(1, width - 8));
+ const pad = " ".repeat(Math.max(0, width - 8 - visibleLength(clipped)));
+ if (!theme.color) return ` ${bar} ${clipped}${pad} `;
+ // The second surface open re-establishes the background past any embedded
+ // style reset in the clipped content, so the padding is covered too. The
+ // cells outside the surface show the viewer's base canvas as margins.
+ return ` ${bar}${surface} ${clipped}${RESET_ALL}${surface}${pad} ${CARD_SURFACE_CLOSE} `;
+}
+
+/**
+ * Like {@link cardRow} but right-aligns `right` against the inner width so
+ * metrics (duration, cost, tokens) line up across cards for quick scanning.
+ * The left side clips first when the two don't fit together.
+ */
+function cardSplitRow(
+ left: string,
+ right: string,
+ width: number,
+ theme: Theme,
+ selected: boolean,
+ surface: string,
+): string {
+ if (visibleLength(right) === 0) return cardRow(left, width, theme, selected, surface);
+ const inner = Math.max(1, width - 8);
+ const rightVis = visibleLength(right);
+ const leftMax = Math.max(1, inner - rightVis - 2);
+ const leftClipped = clipVisible(left, leftMax);
+ const gap = " ".repeat(Math.max(2, inner - visibleLength(leftClipped) - rightVis));
+ return cardRow(`${leftClipped}${gap}${right}`, width, theme, selected, surface);
+}
+
+/** Right-aligned metrics for an assistant card: duration, tokens, cost. */
+function assistantMetrics(
+ item: ConversationItem,
+ glyph: Theme["glyph"],
+ colors: Theme["colors"],
+): string {
+ const parts: string[] = [];
+ if (item.durationMs > 0) parts.push(formatElapsed(item.durationMs));
+ if (item.inputTokens !== undefined)
+ parts.push(`${glyph.arrowUp}${formatCompactTokenCount(item.inputTokens)}`);
+ if (item.outputTokens !== undefined)
+ parts.push(`${glyph.arrowDown}${formatCompactTokenCount(item.outputTokens)}`);
+ if (item.costUsd !== undefined) parts.push(formatCost(item.costUsd));
+ return parts.length === 0 ? "" : colors.dim(parts.join(" · "));
+}
+
+/** Formats a USD cost with enough precision for typical AI inference prices. */
+function formatCost(usd: number): string {
+ if (usd >= 0.01) return `$${usd.toFixed(2)}`;
+ return `$${usd.toFixed(4)}`;
+}
+
+/** Reads the gateway cost from the model span's ancestor step span. */
+function stepCostUsd(
+ modelSpan: LocalTraceSpan,
+ byId: Map<string, LocalTraceSpan>,
+): number | undefined {
+ // The model span (ai.streamText.doStream) is nested under an ai.streamText
+ // outer-op span, which in turn sits under agent.step. Walk up to find it.
+ let span: LocalTraceSpan | undefined = modelSpan;
+ while (span.parentSpanId !== undefined) {
+ span = byId.get(span.parentSpanId);
+ if (span === undefined) return undefined;
+ if (span.name === "agent.step") return numberAttribute(span, "gen_ai.usage.cost");
+ }
+ return undefined;
+}
+
+/** Fold affordance: ▸ when content is hidden behind the cap, ▾ when open. */
+function foldMarker(expanded: boolean, expandable: boolean, theme: Theme): string {
+ if (expanded) return `${theme.colors.dim("▾")} `;
+ return expandable ? `${theme.colors.dim("▸")} ` : "";
+}
+
+function wrapText(text: string, width: number): string[] {
+ return splitEmbeddedNewlines([stripTerminalControls(text)]).flatMap((line) =>
+ wrapVisibleLine(line, width),
+ );
+}
+
+function payloadLines(text: string, width: number): string[] {
+ return wrapText(text, width);
+}
+
+/** Tool payloads pretty-print when they're JSON; text stays text. */
+function payloadJsonLines(text: string, width: number): string[] {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (typeof parsed === "object" && parsed !== null) return prettyJson(parsed, width);
+ } catch {
+ // Not JSON — fall through to plain text.
+ }
+ return payloadLines(text, width);
+}
+
+/** Caps payload lines — the standalone `…` + click hint marks the cut. */
+function capLines(lines: readonly string[], width: number): string[] {
+ if (lines.length <= CARD_PAYLOAD_LINES) return [...lines];
+ return [
+ ...lines.slice(0, CARD_PAYLOAD_LINES - 1),
+ clipVisible(lines[CARD_PAYLOAD_LINES - 1]!, Math.max(1, width)),
+ ];
+}
+
+/** Rendered height of one card — the conversation viewport scrolls by lines. */
+export function conversationItemLineCount(
+ item: ConversationItem,
+ width: number,
+ theme: Theme,
+ expanded: boolean,
+): number {
+ return renderConversationItem(item, width, theme, false, expanded).length;
+}
+
+/** Whether a card has content hidden behind the collapsed cap at this width. */
+export function conversationItemExpandable(item: ConversationItem, width: number): boolean {
+ const inner = Math.max(8, width - 8);
+ if (item.kind === "tool") {
+ const args = item.args === undefined ? 0 : payloadJsonLines(item.args, inner - 2).length;
+ const result = item.result === undefined ? 0 : payloadJsonLines(item.result, inner - 2).length;
+ return args > CARD_PAYLOAD_LINES || result > CARD_PAYLOAD_LINES;
+ }
+ if (item.kind === "system") return wrapText(item.text ?? "", inner).length > CARD_PAYLOAD_LINES;
+ if (item.kind === "user") {
+ const text =
+ item.text === undefined || item.text.trim().length === 0
+ ? 0
+ : payloadLines(item.text, inner).length;
+ return text > CARD_PAYLOAD_LINES;
+ }
+ // assistant
+ const reasoning =
+ item.reasoning === undefined || item.reasoning.trim().length === 0
+ ? 0
+ : payloadLines(item.reasoning, inner).length;
+ const text =
+ item.text === undefined || item.text.trim().length === 0
+ ? 0
+ : payloadLines(item.text, inner).length;
+ return reasoning > CARD_PAYLOAD_LINES || text > CARD_PAYLOAD_LINES;
+}
+
+/** Rough chars-per-token estimate for text with no usage data (system prompts). */
+function estimateTokens(text: string): number {
+ return Math.ceil(text.length / 4);
+}
+
+/** The user's message for a turn = the last user message in its first prompt. */
+function extractUserText(firstModelSpan: LocalTraceSpan | undefined): string | undefined {
+ if (firstModelSpan === undefined) return undefined;
+ const raw = firstModelSpan.attributes["ai.prompt.messages"];
+ if (typeof raw !== "string") return undefined;
+ let messages: unknown;
+ try {
+ messages = JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+ if (!Array.isArray(messages)) return undefined;
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (!isRecord(message) || message.role !== "user") continue;
+ const text = contentText(message.content).trim();
+ if (text.length > 0) return text;
+ }
+ return undefined;
+}
+
+function contentText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .filter(
+ (part): part is { text: string } =>
+ isRecord(part) && part.type === "text" && typeof part.text === "string",
+ )
+ .map((part) => part.text)
+ .join("\n");
+}
+
+/** Text tool results are stored JSON-encoded; unwrap them to plain text. */
+function unwrapJsonString(raw: string | undefined): string | undefined {
+ if (raw === undefined) return undefined;
+ try {
+ const parsed = JSON.parse(raw);
+ return typeof parsed === "string" ? parsed : raw;
+ } catch {
+ return raw;
+ }
+}
+
+function isModelSpan(span: LocalTraceSpan): boolean {
+ return span.name.startsWith("ai.") && span.name.includes("do");
+}
+
+/** Extracts tool names from the `ai.response.tool_calls` JSON array. */
+function parseToolCallNames(raw: string | undefined): readonly string[] | undefined {
+ if (raw === undefined) return undefined;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return undefined;
+ return parsed
+ .filter(
+ (entry): entry is { toolName: string } =>
+ isRecord(entry) && typeof entry.toolName === "string",
+ )
+ .map((entry) => entry.toolName);
+ } catch {
+ return undefined;
+ }
+}
+
+function stringAttribute(span: LocalTraceSpan, key: string): string | undefined {
+ const value = span.attributes[key];
+ return typeof value === "string" ? value : undefined;
+}
+
+function numberAttribute(span: LocalTraceSpan, key: string): number | undefined {
+ const value = span.attributes[key];
+ return typeof value === "number" ? value : undefined;
+}
+
+function spanDurationMs(span: LocalTraceSpan): number {
+ return Math.max(0, Number(span.endTimeNs - span.startTimeNs) / 1_000_000);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-store.integration.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-store.integration.test.ts
new file mode 100644
index 000000000..cb3433e73
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-store.integration.test.ts
@@ -0,0 +1,145 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createTraceStore } from "./trace-store.js";
+
+const TRACE_ONE = "1".repeat(32);
+const TRACE_TWO = "2".repeat(32);
+
+describe("trace store", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+ });
+
+ it("lists no traces when the spool does not exist", async () => {
+ const store = createTraceStore({ appRoot: await createRoot() });
+ expect(await store.list()).toEqual([]);
+ });
+
+ it("lists traces newest-activity first and reads spans", async () => {
+ const appRoot = await createRoot();
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "a".repeat(16),
+ name: "agent.turn",
+ start: 100,
+ end: 200,
+ });
+ await writeSegment(appRoot, TRACE_TWO, {
+ spanId: "b".repeat(16),
+ name: "agent.turn",
+ start: 300,
+ end: 400,
+ });
+
+ const store = createTraceStore({ appRoot });
+ const entries = await store.list();
+ expect(entries.map((entry) => entry.traceId).sort()).toEqual([TRACE_ONE, TRACE_TWO].sort());
+
+ const trace = await store.read(TRACE_ONE);
+ expect(trace?.spans).toHaveLength(1);
+ expect(trace?.spans[0]?.name).toBe("agent.turn");
+ });
+
+ it("picks up spans appended between reads without re-parsing", async () => {
+ const appRoot = await createRoot();
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "a".repeat(16),
+ name: "agent.turn",
+ start: 100,
+ end: 200,
+ });
+ const store = createTraceStore({ appRoot });
+ expect((await store.read(TRACE_ONE))?.spans).toHaveLength(1);
+
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "b".repeat(16),
+ name: "agent.step",
+ start: 110,
+ end: 150,
+ parentSpanId: "a".repeat(16),
+ });
+ const grown = await store.read(TRACE_ONE);
+ expect(grown?.spans).toHaveLength(2);
+ expect(grown?.spans.map((span) => span.name)).toEqual(["agent.turn", "agent.step"]);
+ });
+
+ it("skips malformed segments without failing the trace", async () => {
+ const appRoot = await createRoot();
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "a".repeat(16),
+ name: "agent.turn",
+ start: 100,
+ end: 200,
+ });
+ const directory = join(appRoot, ".eve", "traces", "v1", TRACE_ONE, "segments");
+ await writeFile(join(directory, `${"c".repeat(16)}.otlp.json`), "not json{");
+
+ const store = createTraceStore({ appRoot });
+ expect((await store.read(TRACE_ONE))?.spans).toHaveLength(1);
+ });
+
+ it("forgets a trace when retention prunes it between reads", async () => {
+ const appRoot = await createRoot();
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "a".repeat(16),
+ name: "agent.turn",
+ start: 100,
+ end: 200,
+ });
+ const store = createTraceStore({ appRoot });
+ expect(await store.read(TRACE_ONE)).toBeDefined();
+
+ await rm(join(appRoot, ".eve", "traces", "v1", TRACE_ONE), { recursive: true, force: true });
+ expect(await store.read(TRACE_ONE)).toBeUndefined();
+ });
+
+ async function createRoot(): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), "eve-trace-store-"));
+ roots.push(root);
+ return root;
+ }
+});
+
+interface SegmentInput {
+ readonly spanId: string;
+ readonly name: string;
+ readonly start: number;
+ readonly end: number;
+ readonly parentSpanId?: string;
+}
+
+async function writeSegment(appRoot: string, traceId: string, value: SegmentInput): Promise<void> {
+ const directory = join(appRoot, ".eve", "traces", "v1", traceId, "segments");
+ await mkdir(directory, { recursive: true });
+ await writeFile(
+ join(directory, `${value.spanId}.otlp.json`),
+ JSON.stringify({
+ resourceSpans: [
+ {
+ scopeSpans: [
+ {
+ scope: { name: "eve.agent" },
+ spans: [
+ {
+ attributes: [],
+ endTimeUnixNano: String(value.end * 1_000_000),
+ name: value.name,
+ parentSpanId: value.parentSpanId,
+ spanId: value.spanId,
+ startTimeUnixNano: String(value.start * 1_000_000),
+ status: { code: 0 },
+ traceId,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ }),
+ );
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-store.ts b/packages/eve/src/cli/dev/tui/traces/trace-store.ts
new file mode 100644
index 000000000..e22f6e3f4
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-store.ts
@@ -0,0 +1,125 @@
+/**
+ * Live reader over the local trace spool for the `/traces` viewer.
+ *
+ * The spool's segments are immutable — one file per span, written atomically,
+ * never rewritten — so reads cache parsed spans by span id and only parse
+ * files that appeared since the last poll. Listing stats directories instead
+ * of parsing spans, keeping a 1s poll cheap even with a large spool.
+ */
+
+import { readdir, readFile, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+import { assembleLocalTrace, parseLocalTraceSegment } from "#harness/local-trace-reader.js";
+import {
+ resolveLocalTraceSchemaDirectory,
+ resolveLocalTraceSegmentsDirectory,
+} from "#harness/local-trace-span-processor.js";
+
+const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/u;
+const SPAN_FILE_PATTERN = /^[0-9a-f]{16}\.otlp\.json$/u;
+const MAX_SEGMENT_BYTES = 8 * 1024 * 1024;
+
+export interface TraceStoreEntry {
+ readonly traceId: string;
+ /** Mtime of the trace's segments directory — the instant it last received a span. */
+ readonly lastActivityMs: number;
+}
+
+export interface TraceStore {
+ /** Lists stored traces, most recent activity first. */
+ list(): Promise<readonly TraceStoreEntry[]>;
+ /**
+ * Reads one trace, parsing only segments not seen by earlier reads.
+ * Returns `undefined` when the trace is missing or has no valid spans
+ * (e.g. retention pruned it between list and read).
+ */
+ read(traceId: string): Promise<LocalTrace | undefined>;
+}
+
+export function createTraceStore(options: { readonly appRoot: string }): TraceStore {
+ const schemaRoot = resolveLocalTraceSchemaDirectory(options.appRoot);
+ const caches = new Map<
+ string,
+ { seen: Set<string>; spans: Map<string, LocalTraceSpan>; assembled?: LocalTrace }
+ >();
+
+ return {
+ async list() {
+ let entries;
+ try {
+ entries = await readdir(schemaRoot, { withFileTypes: true });
+ } catch (error) {
+ if (isMissing(error)) return [];
+ throw error;
+ }
+ const traces: TraceStoreEntry[] = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !TRACE_ID_PATTERN.test(entry.name)) continue;
+ try {
+ const segments = await stat(
+ resolveLocalTraceSegmentsDirectory(options.appRoot, entry.name),
+ );
+ traces.push({ traceId: entry.name, lastActivityMs: segments.mtimeMs });
+ } catch (error) {
+ if (!isMissing(error)) throw error;
+ }
+ }
+ return traces.sort((left, right) =>
+ right.lastActivityMs === left.lastActivityMs
+ ? left.traceId.localeCompare(right.traceId)
+ : right.lastActivityMs - left.lastActivityMs,
+ );
+ },
+
+ async read(traceId) {
+ const segmentsRoot = resolveLocalTraceSegmentsDirectory(options.appRoot, traceId);
+ let entries;
+ try {
+ entries = await readdir(segmentsRoot, { withFileTypes: true });
+ } catch (error) {
+ if (isMissing(error)) {
+ caches.delete(traceId);
+ return undefined;
+ }
+ throw error;
+ }
+
+ let cache = caches.get(traceId);
+ if (cache === undefined) {
+ cache = { seen: new Set(), spans: new Map() };
+ caches.set(traceId, cache);
+ }
+ let changed = false;
+ for (const entry of entries) {
+ if (!entry.isFile() || !SPAN_FILE_PATTERN.test(entry.name)) continue;
+ if (cache.seen.has(entry.name)) continue;
+ cache.seen.add(entry.name);
+ let content: string;
+ try {
+ const path = join(segmentsRoot, entry.name);
+ if ((await stat(path)).size > MAX_SEGMENT_BYTES) continue;
+ content = await readFile(path, "utf8");
+ } catch {
+ continue;
+ }
+ for (const span of parseLocalTraceSegment(content, traceId)) {
+ if (!cache.spans.has(span.spanId)) {
+ cache.spans.set(span.spanId, span);
+ changed = true;
+ }
+ }
+ }
+ if (cache.spans.size === 0) return undefined;
+ if (changed || cache.assembled === undefined) {
+ cache.assembled = assembleLocalTrace(traceId, [...cache.spans.values()]);
+ }
+ return cache.assembled;
+ },
+ };
+}
+
+function isMissing(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException).code === "ENOENT";
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-view.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-view.test.ts
new file mode 100644
index 000000000..6bda56b15
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-view.test.ts
@@ -0,0 +1,273 @@
+import { describe, expect, it } from "vitest";
+
+import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import { createTheme } from "../theme.js";
+import { renderSpanDetail, renderTraceViewer } from "./trace-view.js";
+import type { TraceViewerState } from "./trace-viewer-state.js";
+import { applyLoadedTrace, applyTraceList, createTraceViewerState } from "./trace-viewer-state.js";
+
+const THEME = createTheme({ color: true, unicode: true });
+const NO_COLOR_THEME = createTheme({ color: false, unicode: true });
+const BASE = 1_700_000_000_000_000_000n;
+
+function span(
+ spanId: string,
+ name: string,
+ startMs: number,
+ endMs: number,
+ parentSpanId?: string,
+ attributes: Readonly<Record<string, unknown>> = {},
+ statusCode = 0,
+): LocalTraceSpan {
+ return {
+ attributes,
+ endTimeNs: BASE + BigInt(endMs) * 1_000_000n,
+ name,
+ parentSpanId,
+ spanId,
+ startTimeNs: BASE + BigInt(startMs) * 1_000_000n,
+ statusCode,
+ traceId: "t".repeat(32),
+ };
+}
+
+/** A turn with a user message, an assistant reply, and a tool call. */
+function conversationSpans(): LocalTraceSpan[] {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0, undefined, { "agent.turn.id": "turn_0" });
+ const step = span("b".repeat(16), "agent.step", 10, 5000, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 2000, step.spanId, {
+ "gen_ai.request.model": "gpt-5",
+ "agent.usage.input_tokens": 1234,
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.prompt.system": "You are a test assistant.",
+ "ai.response.text": "reply",
+ });
+ const action = span("d".repeat(16), "agent.action", 2100, 2400, step.spanId, {});
+ const toolCall = span("e".repeat(16), "ai.toolCall", 2100, 2400, action.spanId, {
+ "gen_ai.tool.name": "get_weather",
+ "gen_ai.tool.call.arguments": '{"city":"sf"}',
+ });
+ return [turn, step, model, action, toolCall];
+}
+
+function viewerState(
+ spans: readonly LocalTraceSpan[],
+ overrides: Partial<TraceViewerState> = {},
+): TraceViewerState {
+ const traceId = "t".repeat(32);
+ const starts = spans.map((s) => s.startTimeNs);
+ const ends = spans.map((s) => s.endTimeNs);
+ const trace: LocalTrace = {
+ agentName: "weather",
+ endTimeNs: ends.reduce((a, b) => (b > a ? b : a), 0n),
+ sessionId: "session-123",
+ sessionIds: ["session-123"],
+ spans,
+ startTimeNs: starts.reduce((a, b) => (b < a ? b : a), starts[0] ?? 0n),
+ traceId,
+ };
+ let state = applyTraceList(createTraceViewerState(), [{ traceId, lastActivityMs: Date.now() }]);
+ state = applyLoadedTrace(state, trace);
+ return { ...state, ...overrides };
+}
+
+function render(state: TraceViewerState, width = 100, height = 30) {
+ return renderTraceViewer(state, { width, height, theme: THEME });
+}
+
+function clockTimeOf(nanoseconds: bigint): string {
+ const date = new Date(Number(nanoseconds / 1_000_000n));
+ const pad = (value: number, length = 2) => String(value).padStart(length, "0");
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
+}
+
+describe("renderTraceViewer", () => {
+ it("renders the header with full session id, start time, counts, and position", () => {
+ const frame = render(viewerState(conversationSpans()));
+ const header = stripAnsi(frame.rows[0]!);
+ expect(header).toContain("traces");
+ expect(header).toContain("weather");
+ expect(header).toContain("session session-123");
+ expect(header).toContain(clockTimeOf(BASE));
+ expect(header).toContain("5 spans");
+ expect(header).toContain("[1/1]");
+ });
+
+ it("renders the conversation cards, selecting the first card", () => {
+ const frame = render(viewerState(conversationSpans()));
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).toContain("system");
+ expect(body).toContain("user");
+ expect(body).toContain("assistant");
+ expect(body).toContain("reply");
+ expect(body).toContain("get_weather");
+ // First card (system) is selected: white half-block bar on its rows.
+ const selectedRows = frame.rows.filter((row) => row.includes("\x1b[97m▌"));
+ expect(selectedRows.length).toBeGreaterThan(0);
+ });
+
+ it("marks error cards and shows the error status in the detail panel", () => {
+ const turn = span("a".repeat(16), "agent.turn", 0, 0);
+ const step = span("b".repeat(16), "agent.step", 10, 300, turn.spanId, {});
+ const model = span("c".repeat(16), "ai.streamText.doStream", 20, 100, step.spanId, {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.response.text": "reply",
+ "agent.usage.input_tokens": 10,
+ });
+ const action = span("d".repeat(16), "agent.action", 110, 200, step.spanId, {});
+ const failingToolCall = {
+ ...span("f".repeat(16), "ai.toolCall", 110, 200, action.spanId, {
+ "gen_ai.tool.name": "explode",
+ }),
+ statusCode: 2,
+ };
+ const frame = render(
+ viewerState([turn, step, model, action, failingToolCall], {
+ panelOpen: true,
+ selectedRow: 2,
+ }),
+ );
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).toContain("explode");
+ expect(frame.rows.some((row) => row.includes("\x1b[48;2;69;32;37m"))).toBe(true);
+ });
+
+ it("opens the details drawer on the right with the selected card's attributes", () => {
+ const frame = render(viewerState(conversationSpans(), { panelOpen: true, selectedRow: 2 }));
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).toContain("gen_ai.request.model gpt-5");
+ expect(body).toContain("agent.usage.input_tokens 1234");
+ expect(frame.panelTotalRows).toBeGreaterThan(3);
+ // No rule divider between cards and drawer — padded space only.
+ expect(frame.rows.some((row) => row.includes("│ gen_ai"))).toBe(false);
+ });
+
+ it("skips payload keys in the drawer since the cards already carry them", () => {
+ const frame = render(viewerState(conversationSpans(), { panelOpen: true, selectedRow: 2 }));
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).not.toContain("ai.prompt.messages");
+ expect(body).not.toContain("ai.response.text");
+ expect(body).toContain("agent.usage.input_tokens 1234");
+ });
+
+ it("scrolls the drawer by slicing detail lines with panelScroll", () => {
+ const attributes = Object.fromEntries(
+ Array.from({ length: 30 }, (_, index) => [`key.${index}`, `value-${index}`]),
+ );
+ const turn = span("a".repeat(16), "agent.turn", 0, 0);
+ const action = span("d".repeat(16), "agent.action", 100, 200, turn.spanId, {});
+ const toolCall = span("f".repeat(16), "ai.toolCall", 100, 200, action.spanId, attributes);
+ const state = viewerState([turn, action, toolCall], {
+ panelOpen: true,
+ selectedRow: 0,
+ panelScroll: 15,
+ });
+ const frame = render(state);
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).toContain("key.15 value-15");
+ expect(body).not.toContain("key.0 value-0");
+ });
+
+ it("renders the empty state and the EVE_TRACES=off copy", () => {
+ const empty = createTraceViewerState();
+ expect(stripAnsi(render(empty).rows.join("\n"))).toContain("No local traces yet.");
+ const disabled = renderTraceViewer(empty, {
+ width: 100,
+ height: 30,
+ theme: THEME,
+ tracingDisabled: true,
+ });
+ expect(stripAnsi(disabled.rows.join("\n"))).toContain("EVE_TRACES=off");
+ });
+
+ it("shows the footer hints and the card position", () => {
+ const frame = render(viewerState(conversationSpans()));
+ const footer = frame.rows.map(stripAnsi).slice(-2).join("\n");
+ expect(footer).toContain("select");
+ expect(footer).toContain("expand");
+ expect(footer).toContain("q close");
+ expect(footer).toContain("item 1/");
+ expect(footer).not.toContain(" v ");
+ });
+
+ it("never emits rows wider than the terminal", () => {
+ for (const width of [40, 60, 80, 120]) {
+ const frame = render(viewerState(conversationSpans(), { panelOpen: true }), width, 24);
+ for (const row of frame.rows) {
+ expect(visibleLength(row)).toBeLessThanOrEqual(width);
+ }
+ }
+ });
+
+ it("never emits a raw newline inside a frame row, even from \n-laden payloads", () => {
+ // A tool result ending in a real newline used to split its composed row
+ // and inject a phantom blank line into the frame.
+ const turn = span("a".repeat(16), "agent.turn", 0, 0);
+ const selected = span("f".repeat(16), "ai.toolCall", 100, 200, turn.spanId, {
+ "gen_ai.tool.call.result": "When the user asks about weather, call the tool.\n",
+ "gen_ai.tool.name": "load_skill",
+ });
+ const frame = render(viewerState([turn, selected], { panelOpen: true }), 100, 24);
+ for (const row of frame.rows) {
+ expect(row).not.toContain("\n");
+ expect(row).not.toContain("\r");
+ }
+ const body = frame.rows.map(stripAnsi).join("\n");
+ expect(body).toContain("call the");
+ });
+
+ it("reports viewport metrics for key handling", () => {
+ const frame = render(viewerState(conversationSpans()), 100, 30);
+ expect(frame.timelineViewportRows).toBe(27);
+ expect(frame.panelViewportRows).toBe(27);
+ expect(frame.panelTotalRows).toBe(0);
+ });
+
+ it("paints every frame row on the viewer's base canvas at full width", () => {
+ const frame = render(viewerState(conversationSpans()), 100, 30);
+ for (const row of frame.rows) {
+ expect(row).toContain("\x1b[48;2;0;0;0m");
+ expect(visibleLength(row)).toBe(100);
+ }
+ const plain = renderTraceViewer(viewerState(conversationSpans()), {
+ width: 100,
+ height: 30,
+ theme: NO_COLOR_THEME,
+ });
+ for (const row of plain.rows) expect(row).not.toContain("\x1b[48;2;");
+ });
+});
+
+describe("renderSpanDetail", () => {
+ it("renders facts and a sorted attributes table", () => {
+ const detail = renderSpanDetail(
+ span("f".repeat(16), "agent.action", 100, 200, "b".repeat(16), {
+ "z.key": "last",
+ "a.key": "first",
+ }),
+ 40,
+ NO_COLOR_THEME,
+ );
+ const text = detail.join("\n");
+ expect(text).toContain("agent.action");
+ expect(text).toContain("status");
+ expect(text).toContain("ok");
+ expect(text).toContain("duration");
+ expect(text).toContain("parent");
+ expect(text.indexOf("a.key first")).toBeLessThan(text.indexOf("z.key last"));
+ });
+
+ it("wraps long values to the panel width", () => {
+ const detail = renderSpanDetail(
+ span("f".repeat(16), "span", 100, 200, undefined, { "long.value": "x".repeat(200) }),
+ 30,
+ NO_COLOR_THEME,
+ );
+ for (const line of detail) {
+ expect(visibleLength(line)).toBeLessThanOrEqual(30);
+ }
+ expect(detail.length).toBeGreaterThan(8);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-view.ts b/packages/eve/src/cli/dev/tui/traces/trace-view.ts
new file mode 100644
index 000000000..5511b562f
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-view.ts
@@ -0,0 +1,347 @@
+/**
+ * Pure frame renderer for the `/traces` conversation viewer: state in,
+ * styled rows out. The layout is a header (trace identity), a body (the
+ * conversation cards, plus the optional details drawer on the right), and a
+ * footer (key hints + position/notice). Every row is clipped to the
+ * terminal width so the alt-screen painter can write rows verbatim.
+ */
+
+import { formatElapsed } from "#cli/format-elapsed.js";
+import {
+ clipVisible,
+ stripTerminalControls,
+ visibleLength,
+ wrapVisibleLine,
+} from "#cli/ui/terminal-text.js";
+import type { LocalTraceSpan } from "#harness/local-trace-reader.js";
+import { describeLocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import type { Theme } from "../theme.js";
+import { formatAttributeContent } from "./trace-content.js";
+import { renderConversationItem } from "./trace-conversation.js";
+import type { TraceViewerState } from "./trace-viewer-state.js";
+import { selectedTraceViewerSpan } from "./trace-viewer-state.js";
+
+const HEADER_ROWS = 1;
+const FOOTER_ROWS = 2;
+/** The body always keeps at least this many columns. */
+const BODY_MIN_WIDTH = 20;
+const PANEL_MIN_WIDTH = 20;
+const PANEL_MAX_WIDTH = 64;
+
+export interface TraceViewerFrame {
+ readonly rows: readonly string[];
+ /** Detail rows the panel has for the selected span — fed back into key handling. */
+ readonly panelTotalRows: number;
+ /** Body rows available to the conversation. */
+ readonly timelineViewportRows: number;
+ /** Body rows available to the panel. */
+ readonly panelViewportRows: number;
+ /** Column width the body renders at (expandability is width-dependent). */
+ readonly contentWidth: number;
+}
+
+export interface RenderTraceViewerOptions {
+ readonly width: number;
+ readonly height: number;
+ readonly theme: Theme;
+ /** The viewed trace received spans recently — the window extends to "now". */
+ readonly activeWindowEndNs?: bigint;
+ /** Tracing is disabled via `EVE_TRACES=off` (empty-state copy). */
+ readonly tracingDisabled?: boolean;
+}
+
+export function renderTraceViewer(
+ state: TraceViewerState,
+ options: RenderTraceViewerOptions,
+): TraceViewerFrame {
+ const { width, height, theme } = options;
+ const bodyRows = Math.max(1, height - HEADER_ROWS - FOOTER_ROWS);
+ const panelWidth = state.panelOpen ? panelWidthFor(width) : 0;
+ const timelineWidth = Math.max(20, width - (panelWidth === 0 ? 0 : panelWidth + 1));
+
+ const selected = selectedTraceViewerSpan(state);
+ // A panel that doesn't fit (very narrow terminal) isn't modeled as open —
+ // otherwise key handling would scroll content nobody can see. The drawer
+ // gets one row of top padding and one column of side padding.
+ const detailLines =
+ state.panelOpen && panelWidth > 0 && selected !== undefined
+ ? [
+ "",
+ ...renderSpanDetail(selected, Math.max(16, panelWidth - 3), theme, {
+ excludeKeys: CONVERSATION_CONTENT_KEYS,
+ }).map((line) => ` ${line}`),
+ ]
+ : [];
+ const panelViewportRows = bodyRows;
+
+ const rows: string[] = [];
+ rows.push(...renderHeader(state, options));
+ if (state.traces.length === 0) {
+ rows.push(...padBody(renderEmptyState(options, theme, bodyRows), bodyRows));
+ } else if (state.trace === undefined) {
+ rows.push(...padBody(center(bodyRows, theme.colors.dim("Loading trace…")), bodyRows));
+ } else {
+ const body = renderConversation(state, options, timelineWidth, bodyRows);
+ for (let index = 0; index < bodyRows; index += 1) {
+ const left = body[index] ?? "";
+ if (panelWidth === 0) {
+ rows.push(left);
+ continue;
+ }
+ // No divider: the base canvas separates the cards and drawer by itself.
+ const separator = " ";
+ const panelLine = detailLines[state.panelScroll + index] ?? "";
+ rows.push(joinPanels(left, timelineWidth, separator, panelLine, width));
+ }
+ }
+ rows.push(...renderFooter(state, width, theme));
+
+ return {
+ rows: rows.map((row) => withViewerBase(row, width, theme)),
+ panelTotalRows: detailLines.length,
+ timelineViewportRows: bodyRows,
+ panelViewportRows,
+ contentWidth: timelineWidth,
+ };
+}
+
+/**
+ * The viewer's canvas: Catppuccin Macchiato `base` behind every row, so the
+ * whole screen reads as one surface and the `surface1` cards elevate above
+ * it. Rows are padded to full width; embedded style resets AND bg-closes are
+ * followed by a base re-open so neither a truncated line nor a card's
+ * trailing bg-close can drop the canvas (card bg-closes once let the
+ * terminal's default background bleed through the drawer). Truecolor is
+ * exempt from tinted-theme palette remapping.
+ */
+const VIEWER_BASE_OPEN = "\x1b[48;2;0;0;0m";
+const VIEWER_BASE_REOPEN = `\x1b[0m${VIEWER_BASE_OPEN}`;
+const VIEWER_BASE_REOPEN_BG = `\x1b[49m${VIEWER_BASE_OPEN}`;
+const RESET_ALL = "\x1b[0m";
+
+function withViewerBase(row: string, width: number, theme: Theme): string {
+ if (!theme.color) return row;
+ const padded = visibleLength(row) >= width ? row : row + " ".repeat(width - visibleLength(row));
+ return `${VIEWER_BASE_OPEN}${padded
+ .replaceAll("\x1b[0m", VIEWER_BASE_REOPEN)
+ .replaceAll("\x1b[49m", VIEWER_BASE_REOPEN_BG)}${RESET_ALL}`;
+}
+
+/** Renders the attributes panel body for one span (name, facts, attributes). */
+/**
+ * Payload attributes the conversation cards already show; the drawer skips
+ * them in conversation mode so it stays metadata-focused.
+ */
+const CONVERSATION_CONTENT_KEYS: ReadonlySet<string> = new Set([
+ "ai.prompt.messages",
+ "ai.prompt.system",
+ "ai.response.text",
+ "ai.response.tool_calls",
+ "gen_ai.tool.call.arguments",
+ "gen_ai.tool.call.result",
+]);
+
+export function renderSpanDetail(
+ span: LocalTraceSpan,
+ innerWidth: number,
+ theme: Theme,
+ options?: { readonly excludeKeys?: ReadonlySet<string> },
+): string[] {
+ const { colors } = theme;
+ const lines: string[] = [];
+ const name = stripTerminalControls(span.name);
+ lines.push(...wrapVisibleLine(colors.bold(name), innerWidth));
+ const summary = describeLocalTraceSpan(span).map(stripTerminalControls);
+ if (summary.length > 0) lines.push(colors.dim(summary.join(", ")));
+ lines.push("");
+
+ const fact = (label: string, value: string): string => `${colors.dim(label.padEnd(10))}${value}`;
+ const error = span.statusCode === 2;
+ lines.push(fact("status", error ? colors.red("ERROR") : colors.green("ok")));
+ lines.push(fact("duration", formatElapsed(durationMs(span.startTimeNs, span.endTimeNs))));
+ lines.push(fact("started", clockTime(span.startTimeNs)));
+ lines.push(fact("span", span.spanId));
+ if (span.parentSpanId !== undefined) lines.push(fact("parent", span.parentSpanId));
+ if (span.scope !== undefined) lines.push(fact("scope", stripTerminalControls(span.scope)));
+ lines.push("");
+
+ const keys = Object.keys(span.attributes)
+ .filter((key) => options?.excludeKeys?.has(key) !== true)
+ .sort();
+ if (keys.length === 0) {
+ lines.push(colors.dim("no attributes"));
+ } else {
+ lines.push(colors.dim(`attributes (${keys.length})`));
+ for (const key of keys) {
+ const block = formatAttributeContent(key, span.attributes[key], theme, innerWidth - 2);
+ const cleanKey = stripTerminalControls(key);
+ if (block.length === 1) {
+ // Scalars stay beside the key; multi-line content nests beneath it.
+ lines.push(...wrapVisibleLine(`${colors.dim(cleanKey)} ${block[0]}`, innerWidth));
+ } else {
+ lines.push(colors.dim(cleanKey));
+ for (const line of block) {
+ lines.push(` ${line}`);
+ }
+ }
+ }
+ }
+ return lines.map((line) => clipVisible(line, innerWidth));
+}
+
+function renderHeader(state: TraceViewerState, options: RenderTraceViewerOptions): string[] {
+ const { theme, width } = options;
+ const { colors, glyph } = theme;
+ const segments: string[] = [];
+ if (state.trace?.agentName !== undefined) {
+ segments.push(stripTerminalControls(state.trace.agentName));
+ }
+ if (state.trace?.sessionId !== undefined) {
+ segments.push(`session ${stripTerminalControls(state.trace.sessionId)}`);
+ }
+ if (state.trace !== undefined) {
+ const end =
+ options.activeWindowEndNs !== undefined && options.activeWindowEndNs > state.trace.endTimeNs
+ ? options.activeWindowEndNs
+ : state.trace.endTimeNs;
+ segments.push(
+ clockTime(state.trace.startTimeNs),
+ `${state.trace.spans.length} span${state.trace.spans.length === 1 ? "" : "s"}`,
+ formatElapsed(durationMs(state.trace.startTimeNs, end)),
+ );
+ }
+ const title = `${colors.bold(`${glyph.brand} traces`)}${
+ segments.length === 0 ? "" : colors.dim(` · ${segments.join(" · ")}`)
+ }`;
+ const position =
+ state.traces.length === 0 ? "" : colors.dim(`[${state.traceIndex + 1}/${state.traces.length}]`);
+ const live = options.activeWindowEndNs !== undefined ? colors.green("● live") : "";
+ const right = [live, position].filter((part) => part.length > 0).join(" ");
+ // The badge keeps its room: the title (full session id and all) clips first.
+ const header = joinRight(
+ clipVisible(title, Math.max(0, width - visibleLength(right) - 1)),
+ right,
+ width,
+ );
+ return [clipVisible(header, width)];
+}
+
+/** The conversation flow: user/assistant/tool cards in turn order. */
+function renderConversation(
+ state: TraceViewerState,
+ options: RenderTraceViewerOptions,
+ width: number,
+ bodyRows: number,
+): string[] {
+ const { theme } = options;
+ if (state.conversationItems.length === 0) {
+ return [
+ theme.colors.dim(
+ " No conversation content in this trace — content capture may be off (EVE_TRACES_CONTENT).",
+ ),
+ ];
+ }
+ // Render all cards, then apply the line-level scroll offset so expanded
+ // cards taller than the viewport can be scrolled through to the end.
+ const allLines: string[] = [];
+ for (let index = 0; index < state.conversationItems.length; index += 1) {
+ allLines.push(
+ ...renderConversationItem(
+ state.conversationItems[index]!,
+ width,
+ theme,
+ index === state.selectedRow,
+ state.expandedItems.has(index),
+ ),
+ "",
+ );
+ }
+ return allLines.slice(state.scrollRow, state.scrollRow + bodyRows);
+}
+
+function renderFooter(state: TraceViewerState, width: number, theme: Theme): string[] {
+ const { colors } = theme;
+ const [upDown, leftRight] = theme.unicode ? ["↑↓", "←→"] : ["^/v", "</>"];
+ const hints = state.panelFocus
+ ? `${upDown} scroll · tab cards · esc back`
+ : `${upDown} select · ${leftRight} expand · enter attrs · tab focus · [ ] traces · q close`;
+ const itemCount = state.conversationItems.length;
+ const position = itemCount === 0 ? "" : colors.dim(`item ${state.selectedRow + 1}/${itemCount}`);
+ const notice = state.notice === undefined ? "" : colors.yellow(state.notice);
+ const status = [notice, position].filter((part) => part.length > 0).join(colors.dim(" · "));
+ return [
+ clipVisible(` ${colors.dim(hints)}`, width),
+ clipVisible(status.length === 0 ? "" : ` ${status}`, width),
+ ];
+}
+
+function renderEmptyState(
+ options: RenderTraceViewerOptions,
+ theme: Theme,
+ bodyRows: number,
+): string[] {
+ const [first, second] =
+ options.tracingDisabled === true
+ ? ["Tracing is disabled (EVE_TRACES=off).", "Re-enable it and spans stream in live."]
+ : ["No local traces yet.", "Chat with your agent — spans stream in live."];
+ const lines = Array.from({ length: bodyRows }, () => "");
+ const top = Math.max(0, Math.floor(bodyRows / 2) - 1);
+ if (top < bodyRows) lines[top] = theme.colors.bold(first);
+ if (top + 1 < bodyRows) lines[top + 1] = theme.colors.dim(second);
+ return lines;
+}
+
+function center(bodyRows: number, line: string): string[] {
+ const top = Math.max(0, Math.floor(bodyRows / 2) - 1);
+ const lines = Array.from({ length: bodyRows }, () => "");
+ if (top < lines.length) lines[top] = line;
+ return lines;
+}
+
+function padBody(lines: readonly string[], bodyRows: number): string[] {
+ const padded = [...lines];
+ while (padded.length < bodyRows) padded.push("");
+ return padded.slice(0, bodyRows);
+}
+
+function joinPanels(
+ left: string,
+ leftWidth: number,
+ separator: string,
+ right: string,
+ width: number,
+): string {
+ const rightWidth = Math.max(0, width - leftWidth - 1);
+ return `${padTo(left, leftWidth)}${separator}${clipVisible(right, rightWidth)}`;
+}
+
+function joinRight(left: string, right: string, width: number): string {
+ if (right.length === 0) return left;
+ const gap = Math.max(1, width - visibleLength(left) - visibleLength(right));
+ return `${left}${" ".repeat(gap)}${right}`;
+}
+
+function padTo(line: string, width: number): string {
+ const visible = visibleLength(line);
+ return visible >= width ? clipVisible(line, width) : line + " ".repeat(width - visible);
+}
+
+function panelWidthFor(width: number): number {
+ if (width < BODY_MIN_WIDTH + PANEL_MIN_WIDTH + 2) return 0;
+ return Math.min(
+ PANEL_MAX_WIDTH,
+ Math.max(PANEL_MIN_WIDTH, Math.floor(width * 0.42)),
+ width - BODY_MIN_WIDTH - 1,
+ );
+}
+
+function durationMs(start: bigint, end: bigint): number {
+ return Math.max(0, Number(end - start) / 1_000_000);
+}
+
+function clockTime(nanoseconds: bigint): string {
+ const date = new Date(Number(nanoseconds / 1_000_000n));
+ const pad = (value: number, length = 2) => String(value).padStart(length, "0");
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.test.ts
new file mode 100644
index 000000000..c711f0b80
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import { createTheme } from "../theme.js";
+import type { TraceStore } from "./trace-store.js";
+import { TraceViewerSession } from "./trace-viewer-session.js";
+
+const THEME = createTheme({ color: false, unicode: true });
+
+function span(spanId: string, sessionId: string): LocalTraceSpan {
+ return {
+ attributes: {
+ "agent.name": "tester",
+ "agent.session.id": sessionId,
+ "agent.turn.id": "turn_0",
+ },
+ endTimeNs: 1_000_000n,
+ name: "agent.turn",
+ spanId,
+ startTimeNs: 1_000_000n,
+ statusCode: 0,
+ traceId: "unused",
+ };
+}
+
+function trace(traceId: string, sessionIds: readonly string[]): LocalTrace {
+ const spans = sessionIds.map((sessionId, index) =>
+ span(String(index).padStart(16, "0"), sessionId),
+ );
+ return {
+ endTimeNs: 1_000_000n,
+ sessionId: sessionIds[0],
+ sessionIds,
+ spans,
+ startTimeNs: 1_000_000n,
+ traceId,
+ };
+}
+
+function stubStore(traces: readonly LocalTrace[]): TraceStore & { reads: string[] } {
+ const reads: string[] = [];
+ return {
+ reads,
+ async list() {
+ // Newest activity first, mirroring the real store's ordering.
+ return traces.map((entry, index) => ({
+ traceId: entry.traceId,
+ lastActivityMs: traces.length - index,
+ }));
+ },
+ async read(traceId) {
+ reads.push(traceId);
+ return traces.find((entry) => entry.traceId === traceId);
+ },
+ };
+}
+
+async function openViewer(store: TraceStore, sessionId?: string) {
+ const frames: string[][] = [];
+ const session = new TraceViewerSession({
+ appRoot: "/nowhere",
+ dimensions: () => ({ width: 80, height: 24 }),
+ paint: (rows) => frames.push([...rows]),
+ sessionId,
+ store,
+ theme: THEME,
+ });
+ session.start();
+ await vi.waitFor(() => {
+ const last = frames[frames.length - 1]?.join("\n") ?? "";
+ if (!last.includes("session")) throw new Error("no trace frame yet");
+ });
+ session.dispose();
+ return frames[frames.length - 1]!.join("\n");
+}
+
+describe("TraceViewerSession session preference", () => {
+ it("opens on the trace containing the current session, not the newest", async () => {
+ // Trace ids are provider-generated, so the session's trace is found by
+ // matching sessionIds — here the session lives in the older trace.
+ const store = stubStore([
+ trace("a".repeat(32), ["session-other"]),
+ trace("b".repeat(32), ["session-mine"]),
+ ]);
+ const frame = await openViewer(store, "session-mine");
+ expect(frame).toContain("session session-mine");
+ expect(frame).toContain("[2/2]");
+ });
+
+ it("matches a subagent session to the parent trace it recorded into", async () => {
+ const store = stubStore([
+ trace("a".repeat(32), ["session-root", "session-child"]),
+ trace("b".repeat(32), ["session-other"]),
+ ]);
+ const frame = await openViewer(store, "session-child");
+ expect(frame).toContain("session session-root");
+ expect(frame).toContain("[1/2]");
+ });
+
+ it("falls back to the newest trace when the session has no trace yet", async () => {
+ const store = stubStore([
+ trace("a".repeat(32), ["session-other"]),
+ trace("b".repeat(32), ["session-older"]),
+ ]);
+ const frame = await openViewer(store, "session-unseen");
+ expect(frame).toContain("session session-other");
+ expect(frame).toContain("[1/2]");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts
new file mode 100644
index 000000000..5ed933c47
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts
@@ -0,0 +1,233 @@
+/**
+ * Owns one open `/traces` viewer: the store poller, the navigation state, and
+ * frame production. The terminal renderer wires it to the alt screen and the
+ * keyboard; everything else lives here so `terminal-renderer.ts` stays small
+ * and the poll/repaint lifecycle is testable without a TTY.
+ */
+
+import type { TerminalKey } from "../stream-format.js";
+import type { Theme } from "../theme.js";
+import type { TraceStore, TraceStoreEntry } from "./trace-store.js";
+import { createTraceStore } from "./trace-store.js";
+import { conversationItemLineCount } from "./trace-conversation.js";
+import { renderTraceViewer } from "./trace-view.js";
+import type { TraceViewerState } from "./trace-viewer-state.js";
+import {
+ applyLoadedTrace,
+ applyTraceList,
+ createTraceViewerState,
+ reduceTraceViewerKey,
+} from "./trace-viewer-state.js";
+
+const POLL_INTERVAL_MS = 1_000;
+/** A trace whose last span landed this recently renders its window up to "now". */
+const LIVE_WINDOW_MS = 3_000;
+
+export interface TraceViewerOpenOptions {
+ readonly appRoot: string;
+ /** Current chat session — its trace opens first. */
+ readonly sessionId?: string;
+ /** Optional trace id (prefix) from `/traces <trace>`. */
+ readonly reference?: string;
+}
+
+/** The renderer capability the runner's `/traces` dispatch awaits. */
+export interface TraceViewerRenderer {
+ open(options: TraceViewerOpenOptions): Promise<void>;
+}
+
+export interface TraceViewerSessionOptions extends TraceViewerOpenOptions {
+ readonly theme: Theme;
+ readonly paint: (rows: readonly string[]) => void;
+ readonly dimensions: () => { readonly width: number; readonly height: number };
+ readonly tracingDisabled?: boolean;
+ readonly store?: TraceStore;
+}
+
+export class TraceViewerSession {
+ readonly #options: TraceViewerSessionOptions;
+ readonly #store: TraceStore;
+ #state: TraceViewerState = createTraceViewerState();
+ /** Pending one-time selection preference resolved from `/traces <prefix>`. */
+ #preferTraceId?: string;
+ /**
+ * Pending one-time preference for the current chat session. Trace ids are
+ * provider-generated, so the session's trace is found by reading candidates
+ * newest-first and matching `sessionIds` — a windowed session resolves to
+ * its most recently active window, and a subagent session to the parent
+ * trace it recorded into.
+ */
+ #preferSessionId?: string;
+ #pollTimer?: ReturnType<typeof setInterval>;
+ #disposed = false;
+ #refreshing = false;
+ #refreshAgain = false;
+ #metrics: {
+ timelineViewportRows: number;
+ panelViewportRows: number;
+ panelTotalRows: number;
+ contentWidth: number;
+ conversationLineCounts?: readonly number[];
+ } = { timelineViewportRows: 0, panelViewportRows: 0, panelTotalRows: 0, contentWidth: 0 };
+
+ constructor(options: TraceViewerSessionOptions) {
+ this.#options = options;
+ this.#store = options.store ?? createTraceStore({ appRoot: options.appRoot });
+ if (options.sessionId !== undefined) {
+ this.#preferSessionId = options.sessionId;
+ }
+ if (options.reference !== undefined) {
+ this.#preferSessionId = undefined;
+ this.#state = {
+ ...this.#state,
+ notice: `No local trace matches "${options.reference}" yet.`,
+ };
+ }
+ }
+
+ start(): void {
+ this.repaint();
+ void this.#refresh();
+ this.#pollTimer = setInterval(() => void this.#refresh(), POLL_INTERVAL_MS);
+ this.#pollTimer.unref?.();
+ }
+
+ /** Feeds one key through the reducer; returns `"close"` when the viewer should close. */
+ handleKey(key: TerminalKey): "close" | undefined {
+ if (this.#disposed) return "close";
+ // Manual trace switching cancels any pending one-time preference.
+ if (key.type === "text" && (key.value === "[" || key.value === "]")) {
+ this.#preferTraceId = undefined;
+ this.#preferSessionId = undefined;
+ }
+ const hadTrace = this.#state.trace !== undefined;
+ const { state, effect } = reduceTraceViewerKey(this.#state, key, this.#metrics);
+ this.#state = state;
+ if (effect === "close") return "close";
+ this.repaint();
+ // A trace switch cleared the timeline — fetch the newly selected trace
+ // immediately instead of leaving a Loading frame up for a full poll.
+ if (hadTrace && state.trace === undefined) void this.#refresh();
+ return undefined;
+ }
+
+ repaint(): void {
+ if (this.#disposed) return;
+ const { width, height } = this.#options.dimensions();
+ const frame = renderTraceViewer(this.#state, {
+ width,
+ height,
+ theme: this.#options.theme,
+ tracingDisabled: this.#options.tracingDisabled,
+ activeWindowEndNs: this.#activeWindowEndNs(),
+ });
+ this.#metrics = {
+ timelineViewportRows: frame.timelineViewportRows,
+ panelViewportRows: frame.panelViewportRows,
+ panelTotalRows: frame.panelTotalRows,
+ contentWidth: frame.contentWidth,
+ conversationLineCounts: this.#state.conversationItems.map((item, index) =>
+ conversationItemLineCount(
+ item,
+ frame.contentWidth,
+ this.#options.theme,
+ this.#state.expandedItems.has(index),
+ ),
+ ),
+ };
+ this.#options.paint(frame.rows);
+ }
+
+ dispose(): void {
+ this.#disposed = true;
+ if (this.#pollTimer !== undefined) {
+ clearInterval(this.#pollTimer);
+ this.#pollTimer = undefined;
+ }
+ }
+
+ async #refresh(): Promise<void> {
+ if (this.#disposed) return;
+ // Coalesce overlapping polls (a slow disk must not queue repaint storms).
+ if (this.#refreshing) {
+ this.#refreshAgain = true;
+ return;
+ }
+ this.#refreshing = true;
+ try {
+ do {
+ this.#refreshAgain = false;
+ await this.#refreshOnce();
+ } while (this.#refreshAgain && !this.#disposed);
+ } finally {
+ this.#refreshing = false;
+ }
+ }
+
+ async #refreshOnce(): Promise<void> {
+ try {
+ const entries = await this.#store.list();
+ let prefer = this.#preferTraceId;
+ const reference = this.#options.reference;
+ if (prefer === undefined && reference !== undefined) {
+ prefer = entries.find((entry) => entry.traceId.startsWith(reference))?.traceId;
+ }
+ if (prefer === undefined && this.#preferSessionId !== undefined) {
+ prefer = await this.#resolveSessionTrace(entries, this.#preferSessionId);
+ }
+ if (this.#disposed) return;
+ // Stash the resolution: the post-read re-apply must still honor it,
+ // and a manual trace switch during the reads clears it via handleKey.
+ if (prefer !== undefined) this.#preferTraceId = prefer;
+ const state0 = applyTraceList(this.#state, entries, { preferTraceId: prefer });
+ const traceId = entries[state0.traceIndex]?.traceId;
+ const trace = traceId === undefined ? undefined : await this.#store.read(traceId);
+ if (this.#disposed) return;
+ // Re-apply against the live state so key presses during the disk
+ // reads (navigation, expansion, trace switches) survive the poll.
+ // A trace switch during the read leaves trace undefined so the
+ // refresh triggered by handleKey fills it in on the next pass.
+ let state = applyTraceList(this.#state, entries, { preferTraceId: this.#preferTraceId });
+ if (
+ this.#preferTraceId !== undefined &&
+ entries[state.traceIndex]?.traceId === this.#preferTraceId
+ ) {
+ this.#preferTraceId = undefined;
+ this.#preferSessionId = undefined;
+ if (state.notice?.startsWith("No local trace matches")) {
+ state = { ...state, notice: undefined };
+ }
+ }
+ if (entries[state.traceIndex]?.traceId === traceId) {
+ state = applyLoadedTrace(state, trace);
+ }
+ this.#state = state;
+ this.repaint();
+ } catch {
+ // Spool reads race the writer and retention; keep showing the last good frame.
+ }
+ }
+
+ /**
+ * Finds the trace holding the session by reading candidates newest-first.
+ * Store reads cache parsed segments, so repeat polls only touch new files.
+ */
+ async #resolveSessionTrace(
+ entries: readonly TraceStoreEntry[],
+ sessionId: string,
+ ): Promise<string | undefined> {
+ for (const entry of entries) {
+ const trace = await this.#store.read(entry.traceId);
+ if (this.#disposed) return undefined;
+ if (trace?.sessionIds.includes(sessionId)) return entry.traceId;
+ }
+ return undefined;
+ }
+
+ #activeWindowEndNs(): bigint | undefined {
+ const entry = this.#state.traces[this.#state.traceIndex];
+ if (entry === undefined || this.#state.trace === undefined) return undefined;
+ if (Date.now() - entry.lastActivityMs > LIVE_WINDOW_MS) return undefined;
+ return BigInt(Date.now()) * 1_000_000n;
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.test.ts
new file mode 100644
index 000000000..b086a3a15
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.test.ts
@@ -0,0 +1,381 @@
+import { describe, expect, it } from "vitest";
+
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import type { TraceStoreEntry } from "./trace-store.js";
+import type { TerminalKey } from "../stream-format.js";
+import {
+ applyLoadedTrace,
+ applyTraceList,
+ createTraceViewerState,
+ reduceTraceViewerKey,
+} from "./trace-viewer-state.js";
+
+let spanSequence = 0;
+
+function span(overrides: Partial<LocalTraceSpan> = {}): LocalTraceSpan {
+ spanSequence += 1;
+ const startTimeNs = overrides.startTimeNs ?? BigInt(spanSequence) * 1_000_000n;
+ return {
+ attributes: {},
+ endTimeNs: startTimeNs + 500_000n,
+ name: `span-${spanSequence}`,
+ spanId: String(spanSequence).padStart(16, "0"),
+ startTimeNs,
+ statusCode: 0,
+ traceId: "t".repeat(32),
+ ...overrides,
+ };
+}
+
+function trace(spans: readonly LocalTraceSpan[], traceId = "t".repeat(32)): LocalTrace {
+ const starts = spans.map((s) => s.startTimeNs);
+ const ends = spans.map((s) => s.endTimeNs);
+ return {
+ endTimeNs: ends.reduce((a, b) => (b > a ? b : a), 0n),
+ sessionIds: [],
+ spans,
+ startTimeNs: starts.reduce((a, b) => (b < a ? b : a), starts[0] ?? 0n),
+ traceId,
+ };
+}
+
+/** A turn with a user message, an assistant reply, and a tool call. */
+function conversationTrace(options: { readonly longReply?: boolean } = {}): LocalTrace {
+ const turn = span({ name: "agent.turn", spanId: "a".repeat(16) });
+ const step = span({ name: "agent.step", spanId: "b".repeat(16), parentSpanId: turn.spanId });
+ const model = span({
+ name: "ai.streamText.doStream",
+ spanId: "c".repeat(16),
+ parentSpanId: step.spanId,
+ attributes: {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.response.text": options.longReply === true ? "a long reply. ".repeat(60) : "reply",
+ },
+ });
+ const action = span({ name: "agent.action", spanId: "d".repeat(16), parentSpanId: step.spanId });
+ const toolCall = span({
+ name: "ai.toolCall",
+ spanId: "e".repeat(16),
+ parentSpanId: action.spanId,
+ attributes: { "gen_ai.tool.name": "get_weather" },
+ });
+ return trace([turn, step, model, action, toolCall]);
+}
+
+function entry(traceId: string, lastActivityMs = 0): TraceStoreEntry {
+ return { traceId, lastActivityMs };
+}
+
+const ENV = {
+ timelineViewportRows: 10,
+ panelViewportRows: 10,
+ panelTotalRows: 30,
+ contentWidth: 80,
+};
+
+function key(type: TerminalKey["type"], value?: string): TerminalKey {
+ if (type === "text") return { type: "text", value: value ?? "", framing: "unframed" };
+ return { type } as TerminalKey;
+}
+
+describe("reduceTraceViewerKey", () => {
+ it("moves the selection with up/down and clamps at the ends", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ const count = state.conversationItems.length;
+ expect(count).toBeGreaterThan(1);
+ state = reduceTraceViewerKey(state, key("up"), ENV).state;
+ expect(state.selectedRow).toBe(0);
+ for (let index = 0; index < count + 2; index += 1) {
+ state = reduceTraceViewerKey(state, key("down"), ENV).state;
+ }
+ expect(state.selectedRow).toBe(count - 1);
+ state = reduceTraceViewerKey(state, key("up"), ENV).state;
+ expect(state.selectedRow).toBe(count - 2);
+ });
+
+ it("jumps home and end", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = reduceTraceViewerKey(state, key("end"), ENV).state;
+ expect(state.selectedRow).toBe(state.conversationItems.length - 1);
+ state = reduceTraceViewerKey(state, key("home"), ENV).state;
+ expect(state.selectedRow).toBe(0);
+ });
+
+ it("opens the details drawer with enter and closes with enter and escape", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = reduceTraceViewerKey(state, key("enter"), ENV).state;
+ expect(state.panelOpen).toBe(true);
+ state = reduceTraceViewerKey(state, key("enter"), ENV).state;
+ expect(state.panelOpen).toBe(false);
+ state = reduceTraceViewerKey(state, key("enter"), ENV).state;
+ state = reduceTraceViewerKey(state, key("escape"), ENV).state;
+ expect(state.panelOpen).toBe(false);
+ });
+
+ it("tab moves focus into the drawer so arrows scroll it", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = reduceTraceViewerKey(state, key("enter"), ENV).state;
+ state = reduceTraceViewerKey(state, key("tab"), ENV).state;
+ expect(state.panelFocus).toBe(true);
+ state = reduceTraceViewerKey(state, key("down"), ENV).state;
+ expect(state.panelScroll).toBe(1);
+ expect(state.selectedRow).toBe(0);
+ state = reduceTraceViewerKey(state, key("escape"), ENV).state;
+ expect(state.panelFocus).toBe(false);
+ expect(state.panelOpen).toBe(true);
+ });
+
+ it("clamps drawer scroll to the content height", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = reduceTraceViewerKey(state, key("enter"), ENV).state;
+ state = reduceTraceViewerKey(state, key("tab"), ENV).state;
+ for (let index = 0; index < 50; index += 1) {
+ state = reduceTraceViewerKey(state, key("down"), ENV).state;
+ }
+ expect(state.panelScroll).toBe(20);
+ });
+
+ it("closes the viewer on q, ctrl-c, and escape with the drawer closed", () => {
+ const state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ expect(reduceTraceViewerKey(state, key("text", "q"), ENV).effect).toBe("close");
+ expect(reduceTraceViewerKey(state, key("ctrl-c"), ENV).effect).toBe("close");
+ expect(reduceTraceViewerKey(state, key("escape"), ENV).effect).toBe("close");
+ });
+
+ it("switches traces with [ and ], clamped to the list", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = applyTraceList(state, [entry("a".repeat(32)), entry("b".repeat(32))]);
+ state = reduceTraceViewerKey(state, key("text", "["), ENV).state;
+ expect(state.traceIndex).toBe(1);
+ state = reduceTraceViewerKey(state, key("text", "["), ENV).state;
+ expect(state.traceIndex).toBe(1);
+ expect(state.conversationItems).toEqual([]);
+ state = reduceTraceViewerKey(state, key("text", "]"), ENV).state;
+ expect(state.traceIndex).toBe(0);
+ });
+
+ it("only expands conversation cards whose content is capped", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ const assistantIndex = state.conversationItems.findIndex((item) => item.kind === "assistant");
+ state = { ...state, selectedRow: assistantIndex };
+
+ // A short reply fits the cap: ←/→ is a no-op, nothing to expand.
+ state = reduceTraceViewerKey(state, key("right"), ENV).state;
+ expect(state.expandedItems.has(assistantIndex)).toBe(false);
+
+ // A long reply truncates: it can expand, and collapses back.
+ state = applyLoadedTrace(state, conversationTrace({ longReply: true }));
+ state = reduceTraceViewerKey(state, key("right"), ENV).state;
+ expect(state.expandedItems.has(assistantIndex)).toBe(true);
+ state = reduceTraceViewerKey(state, key("left"), ENV).state;
+ expect(state.expandedItems.has(assistantIndex)).toBe(false);
+ });
+
+ it("expands and collapses cards on mouse clicks", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace({ longReply: true }));
+ const env = {
+ ...ENV,
+ conversationLineCounts: state.conversationItems.map(() => 6),
+ };
+ const assistantIndex = state.conversationItems.findIndex((item) => item.kind === "assistant");
+ // Cards occupy 7 lines each (6 + separator); assistant starts at line
+ // assistantIndex*7. Click one row into it (y=2 is first body row, so
+ // bodyRow = clickY-2 maps to absolute line scrollRow+bodyRow).
+ const clickY = 2 + assistantIndex * 7 + 1;
+
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "press", button: 0, x: 10, y: clickY },
+ env,
+ ).state;
+ expect(state.selectedRow).toBe(assistantIndex);
+ expect(state.expandedItems.has(assistantIndex)).toBe(true);
+
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "press", button: 0, x: 10, y: clickY },
+ env,
+ ).state;
+ expect(state.expandedItems.has(assistantIndex)).toBe(false);
+
+ // A release is not a click.
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "release", button: 0, x: 10, y: clickY },
+ env,
+ ).state;
+ expect(state.expandedItems.has(assistantIndex)).toBe(false);
+ });
+
+ it("scrolls the viewport on mouse wheel events", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ // 10 cards, each 5 lines + separator; viewport holds 12 lines.
+ const items = Array.from({ length: 10 }, (_, index) => ({
+ ...state.conversationItems[state.conversationItems.length - 1]!,
+ span: {
+ ...state.conversationItems[state.conversationItems.length - 1]!.span,
+ spanId: String(index).padStart(16, "0"),
+ },
+ }));
+ state = { ...state, conversationItems: items };
+ const env = {
+ ...ENV,
+ timelineViewportRows: 12,
+ conversationLineCounts: items.map(() => 5),
+ };
+ expect(state.scrollRow).toBe(0);
+ // Wheel down (button 65): scroll forward.
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "press", button: 65, x: 10, y: 5 },
+ env,
+ ).state;
+ expect(state.scrollRow).toBe(3);
+ // The selection stays on the same card even when it scrolls out of view.
+ expect(state.selectedRow).toBe(0);
+ // Wheel up (button 64): scroll back.
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "press", button: 64, x: 10, y: 5 },
+ env,
+ ).state;
+ expect(state.scrollRow).toBe(0);
+ expect(state.selectedRow).toBe(0);
+ // Clamps at the end.
+ for (let i = 0; i < 20; i += 1) {
+ state = reduceTraceViewerKey(
+ state,
+ { type: "mouse", action: "press", button: 65, x: 10, y: 5 },
+ env,
+ ).state;
+ }
+ // Total lines = 10*6 = 60; max scroll = 60-12 = 48.
+ expect(state.scrollRow).toBe(48);
+ expect(state.selectedRow).toBe(0);
+ });
+
+ it("scrolls the conversation by line offset, including separators, to fit the last card", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ // Pretend the trace holds several turns' worth of cards by cloning items.
+ const items = Array.from({ length: 10 }, (_, index) => ({
+ ...state.conversationItems[state.conversationItems.length - 1]!,
+ span: {
+ ...state.conversationItems[state.conversationItems.length - 1]!.span,
+ spanId: String(index).padStart(16, "0"),
+ },
+ }));
+ state = { ...state, conversationItems: items };
+ // Each card is 5 lines + 1 separator; the viewport holds 12 lines.
+ const env = {
+ ...ENV,
+ timelineViewportRows: 12,
+ conversationLineCounts: items.map(() => 5),
+ };
+ for (let index = 0; index < 9; index += 1) {
+ state = reduceTraceViewerKey(state, key("down"), env).state;
+ }
+ expect(state.selectedRow).toBe(9);
+ // Card 9 starts at line 9*6=54; it ends at 54+5=59. To fit 59 in a
+ // 12-line viewport, scroll to 59-12=47 (line offset into all cards).
+ expect(state.scrollRow).toBe(47);
+ // One more down at the end is a no-op but keeps the card in view.
+ state = reduceTraceViewerKey(state, key("down"), env).state;
+ expect(state.scrollRow).toBe(47);
+ });
+});
+
+describe("applyTraceList", () => {
+ it("keeps the viewed trace by identity when the list reorders", () => {
+ const initial = applyTraceList(createTraceViewerState(), [
+ entry("a".repeat(32), 2),
+ entry("b".repeat(32), 1),
+ ]);
+ expect(initial.traceIndex).toBe(0);
+ const reordered = applyTraceList({ ...initial, traceIndex: 1 }, [
+ entry("b".repeat(32), 3),
+ entry("a".repeat(32), 2),
+ ]);
+ expect(reordered.traces[reordered.traceIndex]!.traceId).toBe("b".repeat(32));
+ });
+
+ it("prefers the requested trace id on first load", () => {
+ const state = applyTraceList(
+ createTraceViewerState(),
+ [entry("a".repeat(32)), entry("b".repeat(32))],
+ { preferTraceId: "b".repeat(32) },
+ );
+ expect(state.traceIndex).toBe(1);
+ });
+
+ it("selects the preferred trace even when a fallback is already viewed", () => {
+ // The viewer opened with a fallback trace because the preferred one
+ // hadn't appeared yet. Once it shows up, the preference must win.
+ let state = applyTraceList(createTraceViewerState(), [entry("a".repeat(32))]);
+ expect(state.traceIndex).toBe(0);
+ state = applyTraceList(state, [entry("a".repeat(32)), entry("b".repeat(32))], {
+ preferTraceId: "b".repeat(32),
+ });
+ expect(state.traceIndex).toBe(1);
+ });
+
+ it("resets the view when the viewed trace disappears", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = { ...state, selectedRow: 1, panelOpen: true };
+ state = applyTraceList(state, [entry("b".repeat(32))]);
+ expect(state.traceIndex).toBe(0);
+ expect(state.trace).toBeUndefined();
+ expect(state.conversationItems).toEqual([]);
+ expect(state.panelOpen).toBe(false);
+ });
+
+ it("announces an empty spool and clears the notice when traces arrive", () => {
+ let state = applyTraceList(createTraceViewerState(), []);
+ expect(state.notice).toContain("No local traces");
+ state = applyTraceList(state, [entry("a".repeat(32))]);
+ expect(state.notice).toBeUndefined();
+ });
+});
+
+describe("applyLoadedTrace", () => {
+ it("keeps the conversation selection when cards share one span", () => {
+ // System and the first assistant both point at the model span; matching
+ // on span id alone used to jump the selection to system on every poll.
+ let state = applyLoadedTrace(
+ createTraceViewerState(),
+ trace([
+ span({ name: "agent.turn", spanId: "a".repeat(16) }),
+ span({ name: "agent.step", spanId: "b".repeat(16), parentSpanId: "a".repeat(16) }),
+ span({
+ name: "ai.streamText.doStream",
+ spanId: "c".repeat(16),
+ parentSpanId: "b".repeat(16),
+ attributes: {
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),
+ "ai.prompt.system": "system prompt",
+ "ai.response.text": "reply",
+ },
+ }),
+ ]),
+ );
+ expect(state.conversationItems.map((item) => item.kind)).toEqual([
+ "system",
+ "user",
+ "assistant",
+ ]);
+ state = reduceTraceViewerKey(state, key("down"), ENV).state;
+ state = reduceTraceViewerKey(state, key("down"), ENV).state;
+ expect(state.selectedRow).toBe(2);
+ // Simulate a poll: the selection must stay on the assistant card.
+ state = applyLoadedTrace(state, state.trace!);
+ expect(state.selectedRow).toBe(2);
+ expect(state.conversationItems[state.selectedRow]?.kind).toBe("assistant");
+ });
+
+ it("clears the view with a notice when the trace is pruned", () => {
+ let state = applyLoadedTrace(createTraceViewerState(), conversationTrace());
+ state = applyLoadedTrace(state, undefined);
+ expect(state.conversationItems).toEqual([]);
+ expect(state.notice).toContain("pruned");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.ts b/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.ts
new file mode 100644
index 000000000..686d31353
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/traces/trace-viewer-state.ts
@@ -0,0 +1,389 @@
+/**
+ * Navigation state for the `/traces` conversation viewer — a pure reducer in
+ * the style of `select-state.ts`: keys go in, a new state (plus an optional
+ * `close` effect) comes out, and rendering lives elsewhere. Data updates
+ * from the store poller arrive through {@link applyTraceList}/
+ * {@link applyLoadedTrace} so a live trace can grow underneath an open
+ * viewer without losing the user's selection.
+ */
+
+import type { LocalTrace, LocalTraceSpan } from "#harness/local-trace-reader.js";
+
+import type { ConversationItem } from "#cli/dev/tui/traces/trace-conversation.js";
+import {
+ buildConversationItems,
+ conversationItemExpandable,
+} from "#cli/dev/tui/traces/trace-conversation.js";
+import type { TraceStoreEntry } from "#cli/dev/tui/traces/trace-store.js";
+import type { TerminalKey } from "#cli/dev/tui/stream-format.js";
+
+export interface TraceViewerState {
+ /** Stored traces, most recent activity first. */
+ readonly traces: readonly TraceStoreEntry[];
+ /** Index into `traces` of the trace being viewed. */
+ readonly traceIndex: number;
+ /** The loaded trace, or `undefined` while it has no readable spans. */
+ readonly trace?: LocalTrace;
+ /** The trace re-told as conversation items (system/user/assistant/tool cards). */
+ readonly conversationItems: readonly ConversationItem[];
+ /** Conversation cards toggled open (the system card starts collapsed). */
+ readonly expandedItems: ReadonlySet<number>;
+ /** Index into `conversationItems` of the highlighted card. */
+ readonly selectedRow: number;
+ /** First conversation line painted (line-level scroll offset). */
+ readonly scrollRow: number;
+ readonly panelOpen: boolean;
+ /** Whether ↑/↓ scroll the details drawer instead of moving the selection. */
+ readonly panelFocus: boolean;
+ readonly panelScroll: number;
+ /** One-line status for edge cases (trace pruned, tracing disabled, …). */
+ readonly notice?: string;
+}
+
+/** Viewport metrics the controller measures so scrolling math stays pure. */
+export interface TraceViewerKeyEnvironment {
+ /** Body rows available to the conversation. */
+ readonly timelineViewportRows: number;
+ /** Body rows available to the detail panel. */
+ readonly panelViewportRows: number;
+ /** Total detail rows the panel would paint for the selected span. */
+ readonly panelTotalRows: number;
+ /** Body column width — card expandability is width-dependent. */
+ readonly contentWidth: number;
+ /**
+ * Rendered height of each conversation card. The conversation viewport
+ * scrolls by lines, not items — without these, long conversations overflow
+ * the screen with no way to reach lower cards.
+ */
+ readonly conversationLineCounts?: readonly number[];
+}
+
+export interface TraceViewerKeyResult {
+ readonly state: TraceViewerState;
+ readonly effect?: "close";
+}
+
+export function createTraceViewerState(): TraceViewerState {
+ return {
+ traces: [],
+ traceIndex: 0,
+ conversationItems: [],
+ expandedItems: new Set(),
+ selectedRow: 0,
+ scrollRow: 0,
+ panelOpen: false,
+ panelFocus: false,
+ panelScroll: 0,
+ };
+}
+
+export function selectedTraceViewerSpan(state: TraceViewerState): LocalTraceSpan | undefined {
+ return state.conversationItems[state.selectedRow]?.span;
+}
+
+/** The number of selectable cards. */
+export function traceViewerItemCount(state: TraceViewerState): number {
+ return state.conversationItems.length;
+}
+
+/**
+ * Applies a fresh trace listing. The viewed trace is kept by identity across
+ * reorders (a live trace climbs the list as spans land); when it disappears,
+ * selection falls back to the newest trace. `preferTraceId` wins on first
+ * load — the viewer opens on the current chat session's trace.
+ */
+export function applyTraceList(
+ state: TraceViewerState,
+ entries: readonly TraceStoreEntry[],
+ options: { readonly preferTraceId?: string } = {},
+): TraceViewerState {
+ const current = state.traces[state.traceIndex]?.traceId;
+ // A one-time preference (current session, /traces <prefix>) wins over the
+ // existing selection — the fallback was only chosen because the preferred
+ // trace hadn't appeared yet.
+ let traceIndex =
+ options.preferTraceId !== undefined
+ ? entries.findIndex((entry) => entry.traceId === options.preferTraceId)
+ : -1;
+ if (traceIndex === -1) {
+ traceIndex = current === undefined ? -1 : entries.findIndex((e) => e.traceId === current);
+ }
+ if (traceIndex === -1) traceIndex = entries.length === 0 ? 0 : Math.max(0, state.traceIndex);
+ if (traceIndex >= entries.length) traceIndex = Math.max(0, entries.length - 1);
+ const switched = entries[traceIndex]?.traceId !== current;
+ const notice =
+ entries.length === 0
+ ? (state.notice ?? "No local traces yet — chat with your agent and spans stream in live.")
+ : state.notice?.startsWith("No local traces")
+ ? undefined
+ : state.notice;
+ if (!switched) return { ...state, traces: entries, traceIndex, notice };
+ return {
+ ...state,
+ traces: entries,
+ traceIndex,
+ notice,
+ trace: undefined,
+ conversationItems: [],
+ expandedItems: new Set(),
+ selectedRow: 0,
+ scrollRow: 0,
+ panelOpen: false,
+ panelFocus: false,
+ panelScroll: 0,
+ };
+}
+
+/**
+ * Applies a freshly read trace. Selection follows the previously selected
+ * card (span id + kind — cards can share spans) so live growth never jumps
+ * the cursor; a pruned trace clears the view with a notice instead of
+ * pretending stale data is current.
+ */
+export function applyLoadedTrace(
+ state: TraceViewerState,
+ trace: LocalTrace | undefined,
+): TraceViewerState {
+ if (trace === undefined) {
+ if (state.trace === undefined) return state;
+ return {
+ ...state,
+ trace: undefined,
+ conversationItems: [],
+ selectedRow: 0,
+ scrollRow: 0,
+ panelOpen: false,
+ panelFocus: false,
+ panelScroll: 0,
+ notice: "This trace was pruned — pick another with [ and ].",
+ };
+ }
+ const selectedSpanId = selectedTraceViewerSpan(state)?.spanId;
+ const selectedItemKind = state.conversationItems[state.selectedRow]?.kind;
+ const conversationItems = buildConversationItems(trace);
+ let selectedRow: number;
+ if (selectedSpanId === undefined) {
+ selectedRow = state.selectedRow;
+ } else {
+ selectedRow = conversationItems.findIndex(
+ (item) => item.span.spanId === selectedSpanId && item.kind === selectedItemKind,
+ );
+ }
+ if (selectedRow === -1) {
+ selectedRow = Math.min(state.selectedRow, conversationItems.length - 1);
+ }
+ if (selectedRow < 0) selectedRow = 0;
+ const notice = state.notice?.startsWith("This trace was pruned") ? undefined : state.notice;
+ return { ...state, trace, conversationItems, selectedRow, notice };
+}
+
+/** The one key handler: navigation, expansion, the details drawer, closing. */
+export function reduceTraceViewerKey(
+ state: TraceViewerState,
+ key: TerminalKey,
+ environment: TraceViewerKeyEnvironment,
+): TraceViewerKeyResult {
+ const panelMaxScroll = Math.max(0, environment.panelTotalRows - environment.panelViewportRows);
+ const base: TraceViewerState =
+ state.panelScroll > panelMaxScroll ? { ...state, panelScroll: panelMaxScroll } : state;
+
+ switch (key.type) {
+ case "escape": {
+ if (base.panelFocus) return { state: { ...base, panelFocus: false } };
+ if (base.panelOpen) return { state: { ...base, panelOpen: false, panelScroll: 0 } };
+ return { state: base, effect: "close" };
+ }
+ case "ctrl-c": {
+ return { state: base, effect: "close" };
+ }
+ case "mouse": {
+ if (key.action !== "press") return { state: base };
+ // Scroll wheel (SGR button 64/65): scroll the conversation viewport.
+ if (key.button === 64 || key.button === 65) {
+ const delta = key.button === 64 ? -3 : 3;
+ return { state: scrollConversation(base, delta, environment) };
+ }
+ if (key.button !== 0) return { state: base };
+ // Left click selects and expands/collapses cards.
+ const bodyIndex = key.y - 2; // one header row, 1-based coordinates
+ if (bodyIndex < 0) return { state: base };
+ const itemIndex = conversationItemAtBodyRow(base, environment, bodyIndex);
+ if (itemIndex === undefined) return { state: base };
+ const item = base.conversationItems[itemIndex];
+ const expandedItems = new Set(base.expandedItems);
+ if (
+ item !== undefined &&
+ !expandedItems.has(itemIndex) &&
+ conversationItemExpandable(item, environment.contentWidth)
+ ) {
+ expandedItems.add(itemIndex);
+ } else {
+ expandedItems.delete(itemIndex);
+ }
+ return { state: { ...base, selectedRow: itemIndex, expandedItems } };
+ }
+ case "enter": {
+ if (traceViewerItemCount(base) === 0) return { state: base };
+ if (base.panelOpen) return { state: { ...base, panelOpen: false, panelFocus: false } };
+ return { state: { ...base, panelOpen: true, panelScroll: 0 } };
+ }
+ case "tab": {
+ if (!base.panelOpen) return { state: base };
+ return { state: { ...base, panelFocus: !base.panelFocus } };
+ }
+ case "up":
+ case "ctrl-p": {
+ if (base.panelFocus) {
+ return { state: { ...base, panelScroll: Math.max(0, base.panelScroll - 1) } };
+ }
+ return { state: moveSelection(base, -1, environment) };
+ }
+ case "down":
+ case "ctrl-n": {
+ if (base.panelFocus) {
+ return { state: { ...base, panelScroll: Math.min(panelMaxScroll, base.panelScroll + 1) } };
+ }
+ return { state: moveSelection(base, 1, environment) };
+ }
+ case "home": {
+ if (base.panelFocus) return { state: { ...base, panelScroll: 0 } };
+ return { state: moveSelection(base, -base.selectedRow, environment) };
+ }
+ case "end": {
+ if (base.panelFocus) return { state: { ...base, panelScroll: panelMaxScroll } };
+ return {
+ state: moveSelection(base, traceViewerItemCount(base) - 1 - base.selectedRow, environment),
+ };
+ }
+ case "left":
+ case "right": {
+ if (base.panelFocus) return { state: base };
+ const item = base.conversationItems[base.selectedRow];
+ if (
+ item === undefined ||
+ (!base.expandedItems.has(base.selectedRow) &&
+ !conversationItemExpandable(item, environment.contentWidth))
+ ) {
+ return { state: base };
+ }
+ const expandedItems = new Set(base.expandedItems);
+ if (expandedItems.has(base.selectedRow)) {
+ expandedItems.delete(base.selectedRow);
+ } else {
+ expandedItems.add(base.selectedRow);
+ }
+ // Recalculate the scroll offset: expanding changes card heights, so
+ // the previous offset may leave the selected card's bottom cut off.
+ const scrolled = { ...base, expandedItems };
+ return { state: { ...scrolled, scrollRow: conversationScrollRow(scrolled, environment) } };
+ }
+ case "text": {
+ if (key.framing === "bracketed-paste") return { state: base };
+ if (key.value === "q") return { state: base, effect: "close" };
+ if (key.value === "[" || key.value === "]") {
+ const delta = key.value === "[" ? 1 : -1;
+ return { state: switchTrace(base, delta) };
+ }
+ return { state: base };
+ }
+ default:
+ return { state: base };
+ }
+}
+
+function switchTrace(state: TraceViewerState, delta: number): TraceViewerState {
+ if (state.traces.length === 0) return state;
+ const traceIndex = Math.min(Math.max(0, state.traceIndex + delta), state.traces.length - 1);
+ if (traceIndex === state.traceIndex) return state;
+ return {
+ ...state,
+ traceIndex,
+ trace: undefined,
+ conversationItems: [],
+ expandedItems: new Set(),
+ selectedRow: 0,
+ scrollRow: 0,
+ panelOpen: false,
+ panelFocus: false,
+ panelScroll: 0,
+ };
+}
+
+function moveSelection(
+ state: TraceViewerState,
+ delta: number,
+ environment: TraceViewerKeyEnvironment,
+): TraceViewerState {
+ const itemCount = traceViewerItemCount(state);
+ if (itemCount === 0) return state;
+ const selectedRow = Math.min(Math.max(0, state.selectedRow + delta), itemCount - 1);
+ return {
+ ...state,
+ selectedRow,
+ panelScroll: 0,
+ scrollRow: conversationScrollRow({ ...state, selectedRow }, environment),
+ };
+}
+
+/** First line offset that keeps the selected card's last line visible. */
+function conversationScrollRow(
+ state: TraceViewerState,
+ environment: TraceViewerKeyEnvironment,
+): number {
+ const counts = environment.conversationLineCounts;
+ if (counts === undefined) return state.scrollRow;
+ const viewportRows = environment.timelineViewportRows;
+ // Line range of the selected card (card lines + separator after each).
+ let cardStart = 0;
+ for (let index = 0; index < state.selectedRow; index += 1) {
+ cardStart += (counts[index] ?? 1) + 1;
+ }
+ const cardHeight = counts[state.selectedRow] ?? 1;
+ const cardEnd = cardStart + cardHeight;
+ // Already visible? Keep the current offset.
+ if (state.scrollRow <= cardStart && cardEnd <= state.scrollRow + viewportRows) {
+ return state.scrollRow;
+ }
+ // Card taller than the viewport: align its top so the user can scroll
+ // down through the rest. Otherwise scroll just enough to show the end.
+ if (cardHeight > viewportRows) return cardStart;
+ return Math.max(0, cardEnd - viewportRows);
+}
+
+/** Maps a click's body row to a card index, walking card heights + separators. */
+function conversationItemAtBodyRow(
+ state: TraceViewerState,
+ environment: TraceViewerKeyEnvironment,
+ bodyRow: number,
+): number | undefined {
+ const counts = environment.conversationLineCounts;
+ if (counts === undefined) return undefined;
+ const absoluteLine = state.scrollRow + bodyRow;
+ let line = 0;
+ for (let index = 0; index < state.conversationItems.length; index += 1) {
+ const cardHeight = (counts[index] ?? 1) + 1; // card lines + separator
+ if (absoluteLine < line + cardHeight) return index;
+ line += cardHeight;
+ }
+ return undefined;
+}
+
+/** Scrolls the conversation viewport by `delta` lines (mouse wheel). */
+function scrollConversation(
+ state: TraceViewerState,
+ delta: number,
+ environment: TraceViewerKeyEnvironment,
+): TraceViewerState {
+ const counts = environment.conversationLineCounts;
+ if (counts === undefined || state.conversationItems.length === 0) return state;
+ const viewportRows = environment.timelineViewportRows;
+ // Total lines including separators.
+ let totalLines = 0;
+ for (const count of counts) totalLines += count + 1;
+ const maxScroll = Math.max(0, totalLines - viewportRows);
+ const scrollRow = Math.min(maxScroll, Math.max(0, state.scrollRow + delta));
+ if (scrollRow === state.scrollRow) return state;
+ // The selection stays on the same card even when it scrolls out of view;
+ // arrow keys re-scroll to bring it back (conversationScrollRow).
+ return { ...state, scrollRow };
+}
diff --git a/packages/eve/src/cli/ui/alt-screen.test.ts b/packages/eve/src/cli/ui/alt-screen.test.ts
new file mode 100644
index 000000000..32d26474b
--- /dev/null
+++ b/packages/eve/src/cli/ui/alt-screen.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+
+import { AltScreen } from "./alt-screen.js";
+
+function collectingOutput() {
+ const writes: string[] = [];
+ return {
+ writes,
+ output: {
+ write(chunk: string) {
+ writes.push(chunk);
+ return true;
+ },
+ },
+ };
+}
+
+describe("AltScreen", () => {
+ it("enters and exits the alternate buffer once", () => {
+ const { writes, output } = collectingOutput();
+ const screen = new AltScreen(output);
+ screen.enter();
+ screen.enter();
+ expect(writes.join("")).toBe("\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h");
+ expect(screen.active).toBe(true);
+ screen.exit();
+ screen.exit();
+ expect(writes.join("")).toBe(
+ "\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?1006l\x1b[?1000l\x1b[?25h\x1b[?1049l",
+ );
+ expect(screen.active).toBe(false);
+ });
+
+ it("paints frames with absolute row positions, clipped to the height", () => {
+ const { writes, output } = collectingOutput();
+ const screen = new AltScreen(output);
+ screen.paint(["ignored"], 10);
+ expect(writes).toHaveLength(0);
+ screen.enter();
+ screen.paint(["one", "two", "three"], 2);
+ // Per-row CUP: no reliance on autowrap-pending behavior for full-width rows.
+ expect(writes[1]).toBe("\x1b[?2026h\x1b[H\x1b[0J\x1b[1Hone\x1b[2Htwo\x1b[?2026l");
+ });
+});
diff --git a/packages/eve/src/cli/ui/alt-screen.ts b/packages/eve/src/cli/ui/alt-screen.ts
new file mode 100644
index 000000000..94962120a
--- /dev/null
+++ b/packages/eve/src/cli/ui/alt-screen.ts
@@ -0,0 +1,74 @@
+/**
+ * Alternate-screen mode for full-screen modal views (the `/traces` viewer).
+ *
+ * The dev TUI's transcript deliberately streams into native scrollback (see
+ * `live-region.ts`), but a modal viewer wants the whole terminal without
+ * fighting the transcript's repaint cycle. Entering the alternate buffer
+ * gives the viewer a blank screen it fully owns; leaving restores the
+ * transcript exactly where the user left it.
+ *
+ * Like {@link LiveRegion}, writes go through the terminal's original `write`
+ * captured at construction so foreign-output capture never sees the paints.
+ */
+
+const ESC = "\x1b";
+const ALT_SCREEN_ON = `${ESC}[?1049h`;
+const ALT_SCREEN_OFF = `${ESC}[?1049l`;
+const MOUSE_ON = `${ESC}[?1000h${ESC}[?1006h`;
+const MOUSE_OFF = `${ESC}[?1006l${ESC}[?1000l`;
+const HIDE_CURSOR = `${ESC}[?25l`;
+const SHOW_CURSOR = `${ESC}[?25h`;
+const CLEAR_TO_END = `${ESC}[0J`;
+const CURSOR_HOME = `${ESC}[H`;
+const SYNC_START = `${ESC}[?2026h`;
+const SYNC_END = `${ESC}[?2026l`;
+
+export interface AltScreenOutput {
+ write(chunk: string): boolean;
+}
+
+export class AltScreen {
+ readonly #write: (chunk: string) => boolean;
+ #active = false;
+
+ constructor(output: AltScreenOutput) {
+ this.#write = output.write.bind(output);
+ }
+
+ get active(): boolean {
+ return this.#active;
+ }
+
+ /** Switches to the alternate buffer, hides the cursor, enables SGR mouse. */
+ enter(): void {
+ if (this.#active) return;
+ this.#write(`${ALT_SCREEN_ON}${HIDE_CURSOR}${MOUSE_ON}`);
+ this.#active = true;
+ }
+
+ /**
+ * Paints a full-screen frame. Each row must already be styled and fit
+ * within the terminal width (one row == one screen line); rows beyond the
+ * terminal height are dropped. The screen is erased before the rows are
+ * written — terminals only erase via explicit sequences, so a shrinking
+ * frame would otherwise leave stale text behind.
+ *
+ * Rows are placed with absolute cursor positions rather than `\n`: a row
+ * filling the last column leaves terminals in an autowrap-pending state
+ * whose interaction with `\n` varies (immediate-wrap terminals insert a
+ * phantom line). Absolute positioning is immune to all of it.
+ */
+ paint(rows: readonly string[], height: number): void {
+ if (!this.#active) return;
+ const visible = rows.slice(0, Math.max(0, height));
+ const body = visible.map((row, index) => `${ESC}[${index + 1}H${row}`).join("");
+ this.#write(`${SYNC_START}${CURSOR_HOME}${CLEAR_TO_END}${body}${SYNC_END}`);
+ }
+
+ /** Restores the main screen, cursor, and mouse reporting. */
+ exit(): void {
+ if (!this.#active) return;
+ this.#write(`${MOUSE_OFF}${SHOW_CURSOR}${ALT_SCREEN_OFF}`);
+ this.#active = false;
+ }
+}
diff --git a/packages/eve/test/tui-client/tui-traces.ts b/packages/eve/test/tui-client/tui-traces.ts
new file mode 100644
index 000000000..f49baafe7
--- /dev/null
+++ b/packages/eve/test/tui-client/tui-traces.ts
@@ -0,0 +1,399 @@
+import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { Client } from "eve/client";
+import {
+ createPromptCommandHandler,
+ EveTUIRunner,
+ MockScreen,
+ MockUserInput,
+ promptCommandsFor,
+} from "./lib/tui.ts";
+
+import { theme } from "./lib/theme.ts";
+
+/**
+ * End-to-end proof of the `/traces` alt-screen conversation viewer.
+ *
+ * 1. `/traces` opens on a seeded spool: system, user, assistant, and tool
+ * cards render; the long system prompt starts capped behind its card.
+ * 2. `→`/`←` expand and collapse the selected card; a mouse click toggles
+ * it too.
+ * 3. Enter opens the details drawer: metadata only — payload attributes
+ * stay on the cards and never leak into the drawer.
+ * 4. `[` cycles to the older trace; Escape returns to the prompt with the
+ * transcript restored.
+ * 5. An empty spool renders the empty state instead of an error.
+ *
+ * Needs no agent server and no model credentials.
+ */
+const UNREACHABLE_HOST = "http://127.0.0.1:49214";
+process.env.EVE_TUI_UNICODE = "1";
+
+const TRACE_ONE = "1".repeat(32);
+const TRACE_TWO = "2".repeat(32);
+
+const SYSTEM_PROMPT_TAIL = "END-OF-SYSTEM-PROMPT-MARKER";
+// Long enough to wrap past the collapsed card's preview cap, so the system
+// card has content hidden behind the expand affordance.
+const SYSTEM_PROMPT = `${"smoke system prompt guidance. ".repeat(24)}${SYSTEM_PROMPT_TAIL}`;
+
+void (async () => {
+ const appRoot = await mkdtemp(join(tmpdir(), "eve-tui-traces-"));
+ const client = new Client({ host: UNREACHABLE_HOST });
+ const screen = new MockScreen({ columns: 110, rows: 40 });
+ const input = new MockUserInput();
+ const runner = new EveTUIRunner({
+ session: client.session(),
+ client,
+ screen,
+ userInput: input,
+ name: "TUI traces",
+ appRoot,
+ availablePromptCommands: promptCommandsFor("local"),
+ promptCommandHandler: createPromptCommandHandler({
+ target: { kind: "local", serverUrl: UNREACHABLE_HOST, workspaceRoot: appRoot },
+ }),
+ });
+ const runPromise = runner.run();
+
+ try {
+ const sessionWindow = "9".repeat(16);
+ const turn = "a".repeat(16);
+ const step = "b".repeat(16);
+ const model = "c".repeat(16);
+ const action = "e".repeat(16);
+ const toolCall = "f".repeat(16);
+ // A real capture roots turns under the session's window span, so the
+ // fixture does too — turn discovery must not depend on root position.
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: sessionWindow,
+ name: "agent.session",
+ start: 900,
+ end: 900,
+ attributes: {
+ "agent.session.id": "session-smoke",
+ "agent.name": "smoke-agent",
+ "agent.session.window": 0,
+ },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: turn,
+ name: "agent.turn",
+ start: 1_000,
+ end: 1_000,
+ parentSpanId: sessionWindow,
+ attributes: { "agent.session.id": "session-smoke", "agent.name": "smoke-agent" },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: step,
+ name: "agent.step",
+ start: 1_500,
+ end: 9_000,
+ parentSpanId: turn,
+ attributes: { "agent.step.index": 0 },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: model,
+ name: "ai.streamText.doStream",
+ start: 2_000,
+ end: 5_000,
+ parentSpanId: step,
+ attributes: {
+ "gen_ai.request.model": "smoke-model-v1",
+ "ai.prompt.system": SYSTEM_PROMPT,
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "smoke prompt" }]),
+ "ai.response.text": "smoke reply",
+ },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: action,
+ name: "agent.action",
+ start: 6_000,
+ end: 6_300,
+ parentSpanId: step,
+ attributes: { "agent.action.kind": "tool", "agent.action.name": "get_weather" },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: toolCall,
+ name: "ai.toolCall",
+ start: 6_000,
+ end: 6_300,
+ parentSpanId: action,
+ attributes: {
+ "gen_ai.tool.call.arguments": '{"city":"San Francisco"}',
+ "gen_ai.tool.call.result": '{"temperature":72}',
+ "gen_ai.tool.name": "get_weather",
+ },
+ });
+ // A subagent child turn recorded into the same trace, carrying its
+ // dispatch lineage (#1433 attributes).
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "8".repeat(16),
+ name: "agent.turn",
+ start: 7_000,
+ end: 7_000,
+ parentSpanId: sessionWindow,
+ attributes: {
+ "agent.session.id": "child-session",
+ "agent.parent.session.id": "session-smoke",
+ "agent.parent.turn.id": "turn_0",
+ "agent.parent.call_id": "call-1",
+ "agent.subagent.name": "echo",
+ },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "7".repeat(16),
+ name: "agent.step",
+ start: 7_100,
+ end: 8_000,
+ parentSpanId: "8".repeat(16),
+ attributes: { "agent.step.index": 0 },
+ });
+ await writeSegment(appRoot, TRACE_ONE, {
+ spanId: "6".repeat(16),
+ name: "ai.streamText.doStream",
+ start: 7_200,
+ end: 7_900,
+ parentSpanId: "7".repeat(16),
+ attributes: {
+ "gen_ai.request.model": "smoke-model-v1",
+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "delegated task" }]),
+ "ai.response.text": "delegated reply",
+ },
+ });
+ await writeSegment(appRoot, TRACE_TWO, {
+ spanId: "d".repeat(16),
+ name: "agent.turn",
+ start: 500,
+ end: 900,
+ attributes: { "agent.session.id": "older-session" },
+ });
+ // The viewer lists traces by segments-dir mtime (last span activity);
+ // same-millisecond writes would race, so pin the ordering explicitly.
+ const now = new Date();
+ await utimes(join(appRoot, ".eve", "traces", "v1", TRACE_ONE, "segments"), now, now);
+ const older = new Date(now.getTime() - 60_000);
+ await utimes(join(appRoot, ".eve", "traces", "v1", TRACE_TWO, "segments"), older, older);
+
+ await screen.waitForIdlePrompt(5_000);
+ input.type("/traces");
+ input.enter();
+
+ // The viewer opens in the conversation view: message cards with tool
+ // calls nested inside the assistant card, no chat prompt leaking.
+ await screen.waitForText("smoke prompt", 5_000);
+ await screen.waitForText("smoke reply", 5_000);
+ await screen.waitForText("get_weather", 5_000);
+ if (screen.snapshot().includes("›")) {
+ throw new Error(`The chat prompt leaked into the viewer frame:\n${screen.snapshot()}`);
+ }
+ console.log(theme.muted("[tui-traces] /traces opened on the conversation cards"));
+
+ // The long system prompt starts capped behind the collapsed card.
+ await screen.waitForText("Click to expand", 5_000);
+ if (screen.snapshot().includes(SYSTEM_PROMPT_TAIL)) {
+ throw new Error(`The system card did not cap its preview:\n${screen.snapshot()}`);
+ }
+
+ // → expands the selected (system) card; ← collapses it again.
+ input.right();
+ await screen.waitForText(SYSTEM_PROMPT_TAIL, 5_000);
+ await screen.waitForText("Click to collapse", 5_000);
+ input.left();
+ await screen.waitForText("Click to expand", 5_000);
+ if (screen.snapshot().includes(SYSTEM_PROMPT_TAIL)) {
+ throw new Error(`The system card did not collapse:\n${screen.snapshot()}`);
+ }
+ console.log(theme.muted("[tui-traces] arrow keys expand and collapse cards"));
+
+ // A mouse click toggles a card open too: an SGR press at row 3 lands
+ // inside the first card (one header row, 1-based coordinates).
+ input.send("\x1b[<0;10;3M");
+ await screen.waitForText(SYSTEM_PROMPT_TAIL, 5_000);
+ console.log(theme.muted("[tui-traces] mouse click expands a card"));
+ input.left();
+ await screen.waitForText("Click to expand", 5_000);
+
+ // The details drawer stays metadata-only: the tool card carries the call
+ // payload inline ("city" in its Input section), while the drawer lists
+ // facts and metadata attributes — never the content keys.
+ input.down();
+ input.down();
+ input.down();
+ input.enter();
+ await screen.waitForText("status", 5_000);
+ await screen.waitForText("duration", 5_000);
+ await screen.waitForText("gen_ai.tool.name", 5_000);
+ if (!screen.snapshot().includes('"city"')) {
+ throw new Error(`The tool card lost its inline payload:\n${screen.snapshot()}`);
+ }
+ if (screen.snapshot().includes("gen_ai.tool.call.arguments")) {
+ throw new Error(
+ `The drawer leaked a payload attribute in conversation mode:\n${screen.snapshot()}`,
+ );
+ }
+ console.log(theme.muted("[tui-traces] details drawer shows metadata only"));
+
+ // Escape closes the drawer first: an ESC immediately followed by another
+ // key merges into an unfinished CSI in the input tokenizer and wedges
+ // every key after it (the lone-ESC flush never fires).
+ input.send("\x1b");
+ await waitForAbsence(screen, "gen_ai.tool.name", 5_000);
+
+ // The subagent child turn renders below the fold; End jumps to its cards,
+ // which carry the dispatch lineage badge.
+ input.send("\x1b[F");
+ await screen.waitForText("subagent:echo", 5_000);
+ await screen.waitForText("delegated reply", 5_000);
+ console.log(theme.muted("[tui-traces] subagent turn is badged with its lineage"));
+ input.send("\x1b[H");
+ await screen.waitForText("Click to expand", 5_000);
+
+ // `[` cycles to the older trace — a turn with no model spans, so it
+ // renders the no-conversation placeholder.
+ input.type("[");
+ await screen.waitForText("older-se", 5_000);
+ await screen.waitForText("No conversation content", 5_000);
+ if (!screen.snapshot().includes("[2/2]")) {
+ throw new Error(`Trace cycling did not reach the older trace:\n${screen.snapshot()}`);
+ }
+ console.log(theme.muted("[tui-traces] [ cycled to the older trace"));
+
+ // The trace switch reset the drawer, so one Escape closes the viewer.
+ input.send("\x1b");
+ await screen.waitForIdlePrompt(5_000);
+ if (screen.snapshot().includes("Click to expand")) {
+ throw new Error(`The viewer did not restore the transcript:\n${screen.snapshot()}`);
+ }
+ console.log(theme.muted("[tui-traces] escape closed the viewer back to the prompt"));
+
+ // Empty spool → the live empty state, not an error.
+ const emptyRoot = await mkdtemp(join(tmpdir(), "eve-tui-traces-empty-"));
+ try {
+ const emptyRunner = bootRunner(emptyRoot);
+ try {
+ await emptyRunner.screen.waitForIdlePrompt(5_000);
+ emptyRunner.input.type("/traces");
+ emptyRunner.input.enter();
+ await emptyRunner.screen.waitForText("No local traces yet.", 5_000);
+ console.log(theme.muted("[tui-traces] empty spool rendered the empty state"));
+ emptyRunner.input.type("q");
+ await emptyRunner.screen.waitForIdlePrompt(5_000);
+ emptyRunner.input.type("/exit");
+ emptyRunner.input.enter();
+ await withTimeout(emptyRunner.runPromise, 5_000, "empty /exit did not terminate");
+ } finally {
+ emptyRunner.input.ctrlC();
+ await emptyRunner.runPromise.catch(() => {});
+ }
+ } finally {
+ await rm(emptyRoot, { recursive: true, force: true });
+ }
+
+ input.type("/exit");
+ input.enter();
+ await withTimeout(runPromise, 5_000, "/exit did not terminate the runner");
+ } catch (error) {
+ // Failures can leave the alt-screen viewer open: close it (q), wait for
+ // the prompt, then interrupt. A bare Ctrl+C would land in the viewer.
+ input.type("q");
+ await screen.waitForIdlePrompt(2_000).catch(() => {});
+ input.ctrlC();
+ input.ctrlC();
+ await runPromise.catch(() => {});
+ throw error;
+ } finally {
+ await rm(appRoot, { recursive: true, force: true });
+ }
+})().catch((error: unknown) => {
+ console.error(theme.danger("\n[tui] tui-traces smoke test failed:"), error);
+ process.exitCode = 1;
+});
+
+function bootRunner(appRoot: string) {
+ const client = new Client({ host: UNREACHABLE_HOST });
+ const screen = new MockScreen({ columns: 110, rows: 40 });
+ const input = new MockUserInput();
+ const runner = new EveTUIRunner({
+ session: client.session(),
+ client,
+ screen,
+ userInput: input,
+ name: "TUI traces empty",
+ appRoot,
+ availablePromptCommands: promptCommandsFor("local"),
+ promptCommandHandler: createPromptCommandHandler({
+ target: { kind: "local", serverUrl: UNREACHABLE_HOST, workspaceRoot: appRoot },
+ }),
+ });
+ return { screen, input, runPromise: runner.run() };
+}
+
+interface SegmentInput {
+ readonly spanId: string;
+ readonly name: string;
+ readonly start: number;
+ readonly end: number;
+ readonly parentSpanId?: string;
+ readonly attributes?: Record<string, string | number>;
+}
+
+async function writeSegment(appRoot: string, traceId: string, value: SegmentInput): Promise<void> {
+ const directory = join(appRoot, ".eve", "traces", "v1", traceId, "segments");
+ await mkdir(directory, { recursive: true });
+ await writeFile(
+ join(directory, `${value.spanId}.otlp.json`),
+ JSON.stringify({
+ resourceSpans: [
+ {
+ scopeSpans: [
+ {
+ scope: { name: "eve.agent" },
+ spans: [
+ {
+ attributes: Object.entries(value.attributes ?? {}).map(([key, attribute]) => ({
+ key,
+ value:
+ typeof attribute === "number"
+ ? { intValue: attribute }
+ : { stringValue: attribute },
+ })),
+ endTimeUnixNano: String(value.end * 1_000_000),
+ name: value.name,
+ parentSpanId: value.parentSpanId,
+ spanId: value.spanId,
+ startTimeUnixNano: String(value.start * 1_000_000),
+ status: { code: 0 },
+ traceId,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ }),
+ );
+}
+
+async function waitForAbsence(screen: MockScreen, text: string, ms: number): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ if (!screen.snapshot().includes(text)) return;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ throw new Error(`Text did not leave the screen: ${text}\n\nScreen:\n${screen.snapshot()}`);
+}
+
+async function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(message)), ms);
+ });
+ try {
+ return await Promise.race([promise, timeout]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}