The Open Framework for Building Agents
feat(eve): derive the /traces viewer's colors from the terminal palette (#1486)
Chad Hietala3f4bb9cb39bd
diff --git a/.changeset/trace-viewer-terminal-theme.md b/.changeset/trace-viewer-terminal-theme.mdnew file mode 100644index 000000000..73680d865--- /dev/null+++ b/.changeset/trace-viewer-terminal-theme.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The `/traces` viewer now follows your terminal's colors instead of forcing a hardcoded black/grey truecolor palette. It probes the terminal's default background (OSC 11) and derives its card surfaces from your own theme — subtly elevated bands on dark and light backgrounds alike, with red bands for failures, and card titles that invert to black on light backgrounds so they stay legible. Terminals that don't answer the probe get a clean gutter-rail rendering drawn entirely with the shared TUI theme.diff --git a/packages/eve/src/cli/dev/tui/stream-format.test.ts b/packages/eve/src/cli/dev/tui/stream-format.test.tsindex 3ce5ac7c9..7c87f91a6 100644--- a/packages/eve/src/cli/dev/tui/stream-format.test.ts+++ b/packages/eve/src/cli/dev/tui/stream-format.test.ts@@ -168,6 +168,31 @@ describe("nextKey", () => {expect(nextKey("\r")).toEqual({ key: { type: "enter" }, consumed: 1 });expect(nextKey("\u007f")).toEqual({ key: { type: "backspace" }, consumed: 1 });});++ it("decodes a BEL-terminated OSC reply as one token", () => {+ const buffer = "\x1b]11;rgb:1e1e/2a2a/3b3b\x07";+ expect(nextKey(buffer)).toEqual({+ key: { type: "osc", value: "11;rgb:1e1e/2a2a/3b3b" },+ consumed: buffer.length,+ });+ });++ it("decodes an ST-terminated OSC reply and re-tokenizes what follows", () => {+ const buffer = "\x1b]11;rgb:0000/0000/0000\x1b\\\x1b[A";+ const token = nextKey(buffer);+ expect(token).toEqual({+ key: { type: "osc", value: "11;rgb:0000/0000/0000" },+ consumed: buffer.length - 3,+ });+ expect(nextKey(buffer.slice(token.consumed))).toEqual({ key: { type: "up" }, consumed: 3 });+ });++ it("waits for an OSC terminator that is still arriving", () => {+ expect(nextKey("\x1b]")).toEqual({ consumed: 0, incomplete: true });+ expect(nextKey("\x1b]11;rgb:1e1e")).toEqual({ consumed: 0, incomplete: true });+ // A trailing ESC may be the start of the ST terminator.+ expect(nextKey("\x1b]11;rgb:1e1e/2a2a/3b3b\x1b")).toEqual({ consumed: 0, incomplete: true });+ });});describe("parseKey", () => {diff --git a/packages/eve/src/cli/dev/tui/stream-format.ts b/packages/eve/src/cli/dev/tui/stream-format.tsindex bd872d8d8..00067dc62 100644--- a/packages/eve/src/cli/dev/tui/stream-format.ts+++ b/packages/eve/src/cli/dev/tui/stream-format.ts@@ -45,6 +45,15 @@ export type TerminalKey =| { type: "ctrl-l" }| { type: "ctrl-r" }| { type: "ctrl-c" }+ | {+ /**+ * An OSC sequence from the terminal (`ESC ] … BEL`/`ST`) — a reply to a+ * query such as the OSC 11 background-color probe, never a keypress.+ * `value` is the payload between the opener and the terminator.+ */+ type: "osc";+ value: string;+ }| { type: "ignore" };/** One decoded key plus the UTF-16 code units it consumed from the input buffer. */@@ -98,6 +107,15 @@ export function stripPasteStart(buffer: string): string {return buffer.startsWith(PASTE_START) ? buffer.slice(PASTE_START.length) : buffer;}+/**+ * True when `buffer` opens an OSC sequence whose terminator hasn't arrived.+ * {@link nextKey} reports such a buffer as `incomplete` indefinitely, so the+ * caller needs this to recover if the terminator never comes.+ */+export function isIncompleteOsc(buffer: string): boolean {+ return buffer.startsWith("\x1b]") && !buffer.includes("\x07", 2) && !buffer.includes("\x1b\\", 2);+}+/** Removes C0 control characters and DEL from text intended for the prompt. */export function stripPromptControlCharacters(text: string): string {let printable = "";@@ -151,6 +169,19 @@ export function nextKey(buffer: string): KeyToken {}return { consumed: 0, incomplete: true };}+ if (second === "]") {+ // OSC (`ESC ] … BEL` or `ESC ] … ESC \`): a terminal's reply to a query+ // (e.g. the OSC 11 background-color probe). Tokenized whole so a reply+ // never garbles the key stream; the payload excludes the terminator.+ const bel = buffer.indexOf("\x07", 2);+ const st = buffer.indexOf("\x1b\\", 2);+ if (bel === -1 && st === -1) return { consumed: 0, incomplete: true };+ const end = bel === -1 ? st : st === -1 ? bel : Math.min(bel, st);+ return {+ key: { type: "osc", value: buffer.slice(2, end) },+ consumed: end + (end === bel ? 1 : 2),+ };+ }// `ESC` + another byte (e.g. Alt+key): surface the Escape and re-tokenize.return { key: { type: "escape" }, consumed: 1 };}diff --git a/packages/eve/src/cli/dev/tui/terminal-background.test.ts b/packages/eve/src/cli/dev/tui/terminal-background.test.tsnew file mode 100644index 000000000..f3440f69e--- /dev/null+++ b/packages/eve/src/cli/dev/tui/terminal-background.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";++import { parseBackgroundColorReply } from "./terminal-background.js";++describe("parseBackgroundColorReply", () => {+ it("parses the common 16-bit-per-channel reply", () => {+ expect(parseBackgroundColorReply("11;rgb:1e1e/2a2a/3b3b")).toEqual({+ r: 30,+ g: 42,+ b: 59,+ });+ expect(parseBackgroundColorReply("11;rgb:0000/0000/0000")).toEqual({ r: 0, g: 0, b: 0 });+ expect(parseBackgroundColorReply("11;rgb:ffff/ffff/ffff")).toEqual({+ r: 255,+ g: 255,+ b: 255,+ });+ });++ it("scales each channel by its own hex width", () => {+ expect(parseBackgroundColorReply("11;rgb:ff/ff/ff")).toEqual({ r: 255, g: 255, b: 255 });+ expect(parseBackgroundColorReply("11;rgb:f/f/f")).toEqual({ r: 255, g: 255, b: 255 });+ expect(parseBackgroundColorReply("11;rgb:8/80/800")).toEqual({ r: 136, g: 128, b: 128 });+ });++ it("rejects anything that is not an OSC 11 rgb reply", () => {+ expect(parseBackgroundColorReply("10;rgb:0000/0000/0000")).toBeUndefined();+ expect(parseBackgroundColorReply("11;?")).toBeUndefined();+ expect(parseBackgroundColorReply("11;rgb:zz/zz/zz")).toBeUndefined();+ expect(parseBackgroundColorReply("11;rgb:00000/0000/0000")).toBeUndefined();+ expect(parseBackgroundColorReply("")).toBeUndefined();+ });+});diff --git a/packages/eve/src/cli/dev/tui/terminal-background.ts b/packages/eve/src/cli/dev/tui/terminal-background.tsnew file mode 100644index 000000000..ffe25607b--- /dev/null+++ b/packages/eve/src/cli/dev/tui/terminal-background.ts@@ -0,0 +1,32 @@+/**+ * OSC 11 terminal-background probe: the query sequence and the reply parser.+ *+ * Terminals answer `ESC ] 11 ; ? BEL` with their default background color,+ * which lets full-screen views derive elevated surfaces from the user's own+ * palette instead of hardcoding one. The reply arrives on stdin as an OSC+ * sequence (tokenized by `nextKey`); terminals that don't support the query+ * simply never answer, so callers must treat the color as optional.+ */++/** An sRGB color with 8-bit channels. */+export interface RgbColor {+ readonly r: number;+ readonly g: number;+ readonly b: number;+}++/** Asks the terminal for its default background color (OSC 11 query). */+export const BACKGROUND_COLOR_QUERY = "\x1b]11;?\x07";++/**+ * Parses an OSC 11 reply payload (`11;rgb:RRRR/GGGG/BBBB`) into 8-bit+ * channels. The X11 color spec allows 1–4 hex digits per channel; each is+ * scaled by its own width. Returns `undefined` for anything else.+ */+export function parseBackgroundColorReply(payload: string): RgbColor | undefined {+ const match = /^11;rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/iu.exec(payload.trim());+ if (match === null) return undefined;+ const channel = (hex: string): number =>+ Math.round((Number.parseInt(hex, 16) / (16 ** hex.length - 1)) * 255);+ return { r: channel(match[1]!), g: channel(match[2]!), b: channel(match[3]!) };+}diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 32624c49b..907415037 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -163,6 +163,7 @@ import {formatTokenFlow,formatTurnDuration,typewriterText,+ isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,@@ -171,6 +172,11 @@ import {takeUntil,type TerminalKey,} from "./stream-format.js";+import {+ BACKGROUND_COLOR_QUERY,+ parseBackgroundColorReply,+ type RgbColor,+} from "./terminal-background.js";type SetupOptionPanelState = Exclude<SetupSelectPanelState, { kind: "actions" }>;@@ -554,6 +560,12 @@ export class TerminalRenderer implements AgentTUIRenderer {#flowIdleConsumer?: (key: TerminalKey) => void;/** The open `/traces` viewer session, if the alt-screen viewer is active. */#traceView?: TraceViewerSession;+ /**+ * The terminal's default background from its last OSC 11 reply. Cached so+ * a reopened trace viewer paints its derived card surfaces immediately;+ * every open re-probes in case the user switched terminal themes.+ */+ #terminalBackground?: RgbColor;readonly setupFlow: SetupFlowRenderer = {begin: (title, indicator) => this.#beginSetupFlow(title, indicator),end: (options) => this.#endSetupFlow(options?.preserveDiagnostics ?? true),@@ -2671,9 +2683,15 @@ export class TerminalRenderer implements AgentTUIRenderer {paint: (rows) => this.#altScreen.paint(rows, this.#height()),tracingDisabled: process.env.EVE_TRACES === "off",copyText: (text) => copyTextToClipboard(text, (chunk) => this.#altScreen.writeRaw(chunk)),+ terminalBackground: this.#terminalBackground,});this.#traceView = session;this.#altScreen.enter();+ // Ask the terminal for its background so the viewer can derive card+ // surfaces from the user's own palette. The reply arrives on stdin as an+ // OSC key (see #drainKeys); terminals that never answer leave the viewer+ // on its rail rendering, so no timeout is needed.+ if (this.#theme.color) this.#altScreen.writeRaw(BACKGROUND_COLOR_QUERY);await new Promise<void>((resolve) => {this.#traceViewClose = resolve;this.#consumeKey = (key) => {@@ -2883,6 +2901,17 @@ export class TerminalRenderer implements AgentTUIRenderer {}}, incompletePasteFlushMs);this.#keyFlushTimer.unref?.();+ return;+ }+ // An OSC reply whose terminator never arrives (a garbled terminal answer+ // to the background probe) would otherwise wedge input forever; drop it.+ if (isIncompleteOsc(this.#keyBuffer)) {+ const stuck = this.#keyBuffer;+ this.#keyFlushTimer = setTimeout(() => {+ if (this.#keyBuffer !== stuck) return;+ this.#keyBuffer = "";+ }, incompletePasteFlushMs);+ this.#keyFlushTimer.unref?.();}}@@ -2891,10 +2920,25 @@ export class TerminalRenderer implements AgentTUIRenderer {const token = nextKey(this.#keyBuffer);if (token.incomplete) return;this.#keyBuffer = this.#keyBuffer.slice(token.consumed);- if (token.key && token.key.type !== "ignore") this.#consumeKey?.(token.key);+ if (token.key === undefined || token.key.type === "ignore") continue;+ // OSC sequences are terminal replies (not keystrokes): route them to+ // their handler instead of the active mode's key consumer.+ if (token.key.type === "osc") {+ this.#handleOscReply(token.key.value);+ continue;+ }+ this.#consumeKey?.(token.key);}}+ /** Applies a terminal OSC reply; currently only the OSC 11 background probe. */+ #handleOscReply(value: string): void {+ const background = parseBackgroundColorReply(value);+ if (background === undefined) return;+ this.#terminalBackground = background;+ this.#traceView?.setTerminalBackground(background);+ }+#clearKeyFlush() {if (this.#keyFlushTimer) {clearTimeout(this.#keyFlushTimer);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.tsindex c85825246..6fe0c7792 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts@@ -5,6 +5,7 @@ import type { LocalTrace, LocalTraceSpan } from "#tracing/local-trace-reader.js"import { createTheme } from "../theme.js";import { buildConversationItems, renderConversationItem } from "./trace-conversation.js";+import { deriveTraceViewerSurfaces } from "./trace-surfaces.js";const THEME = createTheme({ color: false, unicode: true });const BASE = 1_700_000_000_000_000_000n;@@ -264,17 +265,19 @@ describe("buildConversationItems", () => {});describe("renderConversationItem", () => {- it("renders the user message as a borderless card", () => {+ it("renders the user message as a railed 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(/^ +$/);+ // Padded header band around the title, one body padding row, content,+ // one padding row — every row padded to the full card width.+ expect(lines[0]!.trimEnd()).toBe(" │");+ expect(lines[1]!.trimEnd()).toBe(" │ user");+ expect(lines[2]!.trimEnd()).toBe(" │");+ expect(lines[3]!.trimEnd()).toBe(" │");+ expect(lines[4]!.trimEnd()).toBe(" │ weather in sf?");+ expect(lines[5]!.trimEnd()).toBe(" │");expect(lines).toHaveLength(6);+ for (const line of lines) expect(visibleLength(line)).toBe(60);});it("renders the assistant title with model on the left and metrics right-aligned", () => {@@ -346,7 +349,7 @@ describe("renderConversationItem", () => {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.+ // Duration is right-aligned at the end of the title 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);@@ -399,11 +402,12 @@ describe("renderConversationItem", () => {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.+ // Thought: header, a blank railed line, the reasoning, a blank railed+ // line, the reply.expect(headerIndex).toBeGreaterThan(-1);- expect(lines[headerIndex + 1]!.trim()).toBe("");+ expect(lines[headerIndex + 1]!.trim()).toBe("│");expect(reasoningIndex).toBe(headerIndex + 2);- expect(lines[reasoningIndex + 1]!.trim()).toBe("");+ expect(lines[reasoningIndex + 1]!.trim()).toBe("│");expect(answerIndex).toBe(reasoningIndex + 2);});@@ -422,32 +426,89 @@ describe("renderConversationItem", () => {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.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", () => {+ it("marks the selected card with a bright bar and rails the rest", () => {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.+ // Bright half-block bar on the left edge, no inverse, no truecolor+ // surface — the terminal's own background shows through.expect(line).toContain("\x1b[97m▌\x1b[39m");expect(line).not.toContain("\x1b[7m");+ expect(line).not.toContain("\x1b[48;2;");}- // 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");+ // Unselected cards carry a dim gutter rail instead.+ expect(unselected[0]).toContain("\x1b[2m│\x1b[22m");+ });++ it("paints error cards with a red rail and a red error mark", () => {+ const items = buildConversationItems(trace(weatherTurn()));+ const tool = items.find((item) => item.kind === "tool")!;+ const failed = { ...tool, error: true };+ const themed = createTheme({ color: true, unicode: true });+ const lines = renderConversationItem(failed, 60, themed, false, false);+ for (const line of lines) expect(line).toContain("\x1b[31m│\x1b[39m");+ expect(lines[1]).toContain("\x1b[31m⨯\x1b[39m");+ });++ it("draws elevated bands when surfaces are provided, on identical geometry", () => {+ const items = buildConversationItems(trace(weatherTurn()));+ const assistant = items.find((item) => item.kind === "assistant")!;+ const themed = createTheme({ color: true, unicode: true });+ // A black background reproduces the viewer's original dark palette.+ const surfaces = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ const banded = renderConversationItem(assistant, 60, themed, false, false, surfaces);+ // Header band rows in near-black, body rows in dark gray.+ for (const line of banded.slice(0, 3)) expect(line).toContain("\x1b[48;2;22;22;22m");+ for (const line of banded.slice(3)) expect(line).toContain("\x1b[48;2;36;36;36m");+ // The band groups the card — no gutter rail.+ expect(stripAnsi(banded[1]!)).not.toContain("│");+ // Surfaced and railed layouts occupy the same rows and cells, so scroll,+ // click, and drag-copy math never depend on the OSC 11 probe's outcome.+ const railed = renderConversationItem(assistant, 60, themed, false, false);+ expect(banded.length).toBe(railed.length);+ for (const [index, line] of banded.entries()) {+ expect(visibleLength(line)).toBe(visibleLength(railed[index]!));+ }+ // The selection bar still marks the selected card in its left margin.+ const selected = renderConversationItem(assistant, 60, themed, true, false, surfaces);+ expect(selected[0]).toContain("\x1b[38;2;255;255;255m▌\x1b[39m");+ // Errors swap in the red bands.+ const failed = { ...items.find((item) => item.kind === "tool")!, error: true };+ const errorLines = renderConversationItem(failed, 60, themed, false, false, surfaces);+ expect(errorLines[0]).toContain("\x1b[48;2;69;32;37m");+ expect(errorLines[3]).toContain("\x1b[48;2;58;26;31m");+ });++ it("inverts primary text on light backgrounds so titles stay legible", () => {+ const assistant = buildConversationItems(trace(weatherTurn())).find(+ (item) => item.kind === "assistant",+ )!;+ const themed = createTheme({ color: true, unicode: true });+ const light = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 });+ const lines = renderConversationItem(assistant, 80, themed, true, false, light);+ // The title renders in black, not the theme's fixed bright white.+ expect(lines[1]).toContain("\x1b[38;2;0;0;0massistant\x1b[39m");+ expect(lines[1]).not.toContain("\x1b[97m");+ // The selection bar follows the same primary so it shows on the white canvas.+ for (const line of lines) expect(line).toContain("\x1b[38;2;0;0;0m▌\x1b[39m");+ // Dark backgrounds keep the bright-white primary.+ const dark = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ const darkLines = renderConversationItem(assistant, 80, themed, true, false, dark);+ expect(darkLines[1]).toContain("\x1b[38;2;255;255;255massistant\x1b[39m");});it("never emits rows wider than the given width", () => {diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.tsindex d4f36bc72..7d8dc9ed6 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts@@ -15,6 +15,8 @@ import { compareLocalTraceSpans } from "#tracing/local-trace-reader.js";import { formatCompactTokenCount } from "../stream-format.js";import type { Theme } from "../theme.js";import { formatPayloadContent, wrapPlainText } from "./trace-content.js";+import type { TraceViewerSurfaces } from "./trace-surfaces.js";+import { SURFACE_CLOSE } from "./trace-surfaces.js";export interface ConversationItem {readonly kind: "system" | "user" | "assistant" | "tool";@@ -214,10 +216,14 @@ function turnSubagent(turn: LocalTraceSpan): ConversationSubagent | undefined {}/**- * 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.+ * Renders one conversation card, width-clipped: a title row (bold kind plus+ * dim metadata, metrics right-aligned) over body rows. With `surfaces`+ * (derived from the terminal's background via the OSC 11 probe) the card+ * draws as two elevated bands; without them it falls back to a gutter rail —+ * the same vocabulary the dev transcript uses. Both layouts occupy identical+ * rows and columns, so scroll/click math and drag-copy column mapping never+ * depend on whether the probe was answered. Collapsed cards cap their+ * payloads; expanded ones render them in full.*/export function renderConversationItem(item: ConversationItem,@@ -225,16 +231,24 @@ export function renderConversationItem(theme: Theme,selected: boolean,expanded: boolean,+ surfaces?: TraceViewerSurfaces,): string[] {const { colors, glyph } = theme;const inner = Math.max(8, width - 8);const expandable = conversationItemExpandable(item, width);+ // Surfaces are only derived for color themes, but guard anyway so a+ // no-color render can never emit their raw SGR sequences.+ const active = theme.color ? surfaces : undefined;+ // Titles read as primary text: the theme's bright white on an unknown+ // background, or the surface-matched primary (white on dark, black on+ // light) once the terminal has answered the background probe.+ const primary = active?.primaryText ?? colors.white;let leftTitle: string;let rightTitle: string;const body: string[] = [];if (item.kind === "tool") {- const name = colors.bold(colors.white(item.name ?? "tool"));+ const name = colors.bold(primary(item.name ?? "tool"));leftTitle = `${foldMarker(expanded, expandable, theme)}${name}`;rightTitle = item.durationMs > 0 ? colors.dim(formatElapsed(item.durationMs)) : "";const argsLines = item.args === undefined ? [] : formatPayloadContent(item.args, inner);@@ -248,12 +262,12 @@ export function renderConversationItem(body.push("", colors.dim("Output:"), "", ...cappedResult);}} else if (item.kind === "system") {- leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(colors.white("system"))}`;+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(primary("system"))}`;rightTitle = colors.dim(`~${formatCompactTokenCount(estimateTokens(item.text ?? ""))} tokens`);const uncapped = wrapPlainText(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"))}${+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(primary("assistant"))}${item.model !== undefined ? colors.dim(` · ${stripTerminalControls(item.model)}`) : ""}`;rightTitle = assistantMetrics(item, glyph, colors);@@ -291,7 +305,7 @@ export function renderConversationItem(// 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))}`;+ leftTitle = `${foldMarker(expanded, expandable, theme)}${colors.bold(primary(label))}`;rightTitle = "";const textUncapped =item.text === undefined || item.text.trim().length === 0@@ -305,6 +319,9 @@ export function renderConversationItem(const label = item.subagent.name === undefined ? "subagent" : `subagent:${item.subagent.name}`;leftTitle += colors.dim(` · ${label}`);}+ // Failures carry the transcript's error vocabulary: a red mark beside the+ // title, echoed by a red rail down the card's left edge.+ if (item.error) leftTitle += ` ${colors.red(glyph.error)}`;// A truncated card advertises its affordance: ellipsis on its own line,// a gap, then the click hint (which flips once open).if (!expanded && expandable) {@@ -315,51 +332,65 @@ export function renderConversationItem(// 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;+ // row at both ends.+ const headerSurface =+ active === undefined ? undefined : item.error ? active.errorHeader : active.header;+ const bodySurface =+ active === undefined ? undefined : item.error ? active.errorBody : active.body;+ const rail = railCell(theme, selected, item.error, active);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),+ cardRow("", width, theme, rail, headerSurface),+ cardSplitRow(leftTitle, rightTitle, width, theme, rail, headerSurface),+ cardRow("", width, theme, rail, headerSurface),+ cardRow("", width, theme, rail, bodySurface),+ ...body.map((line) => cardRow(line, width, theme, rail, bodySurface)),+ cardRow("", width, theme, rail, 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.+ * One card row. With a `surface` the row draws as a padded band on that+ * background — one cell of margin either side of the band, the selection bar+ * in the left margin — and the theme's own colors style the content. Without+ * one, a gutter rail groups the card's rows: dim normally, red when the card+ * failed, a bright half-block bar when selected. Both forms pad to the same+ * visible width (`inner = width - 8`), so the two layouts are cell-for-cell+ * interchangeable and nothing assumes a dark terminal palette.*/-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,+ rail: string,+ 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} `;+ if (surface === undefined || !theme.color) return ` ${rail} ${clipped}${pad} `;+ // The second surface open re-establishes the band past any embedded style+ // reset in the clipped content, so the padding is covered too.+ return ` ${rail}${surface} ${clipped}\x1b[0m${surface}${pad} ${SURFACE_CLOSE} `;+}++/**+ * The card's left-edge cell — constant for every row of one card: selection+ * bar (surface-matched primary so it stays visible on light backgrounds),+ * error rail, dim rail, or plain margin when a band already groups the card.+ */+function railCell(+ theme: Theme,+ selected: boolean,+ error: boolean,+ surfaces: TraceViewerSurfaces | undefined,+): string {+ const { colors, glyph } = theme;+ if (selected) {+ const bar = theme.unicode ? "▌" : glyph.rule;+ return surfaces === undefined ? colors.white(bar) : surfaces.primaryText(bar);+ }+ // Surfaced cards need no rail — the band groups them (error bands are red).+ if (surfaces !== undefined) return " ";+ return error ? colors.red(glyph.rule) : colors.dim(glyph.rule);}/**@@ -372,16 +403,16 @@ function cardSplitRow(right: string,width: number,theme: Theme,- selected: boolean,- surface: string,+ rail: string,+ surface?: string,): string {- if (visibleLength(right) === 0) return cardRow(left, width, theme, selected, surface);+ if (visibleLength(right) === 0) return cardRow(left, width, theme, rail, 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);+ return cardRow(`${leftClipped}${gap}${right}`, width, theme, rail, surface);}/** Right-aligned metrics for an assistant card: duration, tokens, cost. */diff --git a/packages/eve/src/cli/dev/tui/traces/trace-surfaces.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-surfaces.test.tsnew file mode 100644index 000000000..dbf9facf9--- /dev/null+++ b/packages/eve/src/cli/dev/tui/traces/trace-surfaces.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";++import { deriveTraceViewerSurfaces } from "./trace-surfaces.js";++describe("deriveTraceViewerSurfaces", () => {+ it("reproduces the original dark palette on a black background", () => {+ const surfaces = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ expect(surfaces.header).toBe("\x1b[48;2;22;22;22m");+ expect(surfaces.body).toBe("\x1b[48;2;36;36;36m");+ expect(surfaces.errorHeader).toBe("\x1b[48;2;69;32;37m");+ expect(surfaces.errorBody).toBe("\x1b[48;2;58;26;31m");+ });++ it("darkens surfaces on a light background instead of lightening", () => {+ const surfaces = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 });+ expect(surfaces.header).toBe("\x1b[48;2;233;233;233m");+ expect(surfaces.body).toBe("\x1b[48;2;219;219;219m");+ // Error bands blend toward the red accent from the light side: a soft+ // pink instead of a dark maroon.+ expect(surfaces.errorHeader).toBe("\x1b[48;2;248;210;215m");+ expect(surfaces.errorBody).toBe("\x1b[48;2;249;218;222m");+ });++ it("styles primary text for contrast: truecolor white on dark, black on light", () => {+ const dark = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ expect(dark.primaryText("assistant")).toBe("\x1b[38;2;255;255;255massistant\x1b[39m");+ const light = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 });+ expect(light.primaryText("assistant")).toBe("\x1b[38;2;0;0;0massistant\x1b[39m");+ });++ it("anchors muted text as a truecolor grey blended toward the primary", () => {+ const dark = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ expect(dark.mutedText("hints")).toBe("\x1b[38;2;140;140;140mhints\x1b[39m");+ const light = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 });+ expect(light.mutedText("hints")).toBe("\x1b[38;2;115;115;115mhints\x1b[39m");+ });++ it("keys the blend direction on perceived luminance, not raw channels", () => {+ // A saturated blue reads dark despite a maxed channel: lighten it.+ const blue = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 255 });+ expect(blue.header).toBe("\x1b[48;2;22;22;255m");+ // A pale yellow reads light: darken it.+ const yellow = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 200 });+ expect(yellow.header).toBe("\x1b[48;2;233;233;183m");+ });+});diff --git a/packages/eve/src/cli/dev/tui/traces/trace-surfaces.ts b/packages/eve/src/cli/dev/tui/traces/trace-surfaces.tsnew file mode 100644index 000000000..484c5d643--- /dev/null+++ b/packages/eve/src/cli/dev/tui/traces/trace-surfaces.ts@@ -0,0 +1,87 @@+/**+ * Card surfaces for the `/traces` viewer, derived from the terminal's own+ * background color (the OSC 11 probe) so they look native in any theme: a+ * dark background gets slightly lighter bands, a light background slightly+ * darker ones, and error bands blend toward red from either side. When the+ * terminal never answers the probe, the viewer falls back to gutter rails.+ */++import type { RgbColor } from "../terminal-background.js";++/** Truecolor background opens (`ESC[48;2;…m`) for the viewer's card bands. */+export interface TraceViewerSurfaces {+ /** Card title band. */+ readonly header: string;+ /** Card body band, slightly more elevated than the header. */+ readonly body: string;+ readonly errorHeader: string;+ readonly errorBody: string;+ /**+ * Style for primary text over the surfaces (card titles, selection bar,+ * toast): truecolor white on dark backgrounds, truecolor black on light+ * ones. The theme's fixed bright-white primary assumes a dark terminal+ * and washes out on light backgrounds.+ */+ readonly primaryText: (text: string) => string;+ /**+ * Style for secondary text (control hints, header metadata, drawer+ * labels): a truecolor grey blended from the probed background toward the+ * primary, so muted text keeps guaranteed contrast on any background.+ */+ readonly mutedText: (text: string) => string;+}++/** Closes a surface, restoring the terminal's default background. */+export const SURFACE_CLOSE = "\x1b[49m";++// Blend fractions chosen to reproduce the viewer's original dark palette on+// a black background (header 22/22/22, body 36/36/36, error 69/32/37 and+// 58/26/31) so dark terminals look unchanged.+const HEADER_BLEND = 0.086;+const BODY_BLEND = 0.141;+const ERROR_HEADER_BLEND = 0.3;+const ERROR_BODY_BLEND = 0.25;+const ERROR_ACCENT: RgbColor = { r: 230, g: 105, b: 123 };+const WHITE: RgbColor = { r: 255, g: 255, b: 255 };+const BLACK: RgbColor = { r: 0, g: 0, b: 0 };+/** How far muted text blends from the background toward the primary. */+const MUTED_BLEND = 0.55;++/**+ * Derives the viewer's card surfaces from the terminal's background color.+ * Everything — bands and text styles alike — is truecolor: palette colors+ * (SGR 30/97) and SGR dim are theme-remappable, so a terminal like ghostty+ * can render them without contrast against the very background it reported.+ * Truecolor is exempt from palette remapping and always lands as derived.+ */+export function deriveTraceViewerSurfaces(background: RgbColor): TraceViewerSurfaces {+ const dark = relativeLuminance(background) < 0.5;+ const neutral = dark ? WHITE : BLACK;+ const primaryOpen = foregroundOpen(neutral);+ const mutedOpen = foregroundOpen(mix(background, neutral, MUTED_BLEND));+ return {+ header: backgroundOpen(mix(background, neutral, HEADER_BLEND)),+ body: backgroundOpen(mix(background, neutral, BODY_BLEND)),+ errorHeader: backgroundOpen(mix(background, ERROR_ACCENT, ERROR_HEADER_BLEND)),+ errorBody: backgroundOpen(mix(background, ERROR_ACCENT, ERROR_BODY_BLEND)),+ primaryText: (text) => `${primaryOpen}${text}\x1b[39m`,+ mutedText: (text) => `${mutedOpen}${text}\x1b[39m`,+ };+}++function backgroundOpen(color: RgbColor): string {+ return `\x1b[48;2;${color.r};${color.g};${color.b}m`;+}++function foregroundOpen(color: RgbColor): string {+ return `\x1b[38;2;${color.r};${color.g};${color.b}m`;+}++function mix(from: RgbColor, to: RgbColor, amount: number): RgbColor {+ const blend = (a: number, b: number): number => Math.round(a + (b - a) * amount);+ return { r: blend(from.r, to.r), g: blend(from.g, to.g), b: blend(from.b, to.b) };+}++function relativeLuminance(color: RgbColor): number {+ return (0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b) / 255;+}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.tsindex 8c058c1b2..dc31accae 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-view.test.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-view.test.ts@@ -4,6 +4,7 @@ import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";import type { LocalTrace, LocalTraceSpan } from "#tracing/local-trace-reader.js";import { createTheme } from "../theme.js";+import { deriveTraceViewerSurfaces } from "./trace-surfaces.js";import {conversationSelectionText,panelSelectionText,@@ -144,7 +145,7 @@ describe("renderTraceViewer", () => {it("extracts the dragged text from the rendered conversation", () => {const state = viewerState(conversationSpans());- // The system card's title row is line 1 (" ▸ system" once rendered).+ // The system card's title row is line 1 (" │ system" once rendered).const selection = {anchor: { line: 1, column: 0 },head: { line: 1, column: 40 },@@ -221,7 +222,8 @@ describe("renderTraceViewer", () => {);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);+ // The failed card carries a red error mark beside its title.+ expect(frame.rows.some((row) => row.includes("\x1b[31m⨯"))).toBe(true);});it("opens the details drawer on the right with the selected card's attributes", () => {@@ -317,18 +319,70 @@ describe("renderTraceViewer", () => {expect(frame.panelTotalRows).toBe(0);});- it("paints every frame row on the viewer's base canvas at full width", () => {+ it("renders on the terminal's own background — no truecolor surfaces", () => {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);+ expect(row).not.toContain("\x1b[48;2;");+ expect(visibleLength(row)).toBeLessThanOrEqual(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;");+ for (const row of plain.rows) expect(row).not.toContain("\x1b[");+ });++ it("paints card bands and a surfaced toast when the background is known", () => {+ const surfaces = deriveTraceViewerSurfaces({ r: 0, g: 0, b: 0 });+ const frame = renderTraceViewer(viewerState(conversationSpans()), {+ width: 100,+ height: 30,+ theme: THEME,+ surfaces,+ toast: "Copied to clipboard",+ });+ expect(frame.rows.some((row) => row.includes("\x1b[48;2;22;22;22m"))).toBe(true);+ expect(frame.rows.some((row) => row.includes("\x1b[48;2;36;36;36m"))).toBe(true);+ // The toast sits on the body band, message row between its padding rows.+ expect(frame.rows[3]).toContain("\x1b[48;2;36;36;36m");+ expect(stripAnsi(frame.rows[3]!)).toContain("▌ Copied to clipboard");+ // Rows never exceed the terminal width even with the bands painted.+ for (const row of frame.rows) expect(visibleLength(row)).toBeLessThanOrEqual(100);+ // On a light background the toast's primary text inverts to black.+ const lightFrame = renderTraceViewer(viewerState(conversationSpans()), {+ width: 100,+ height: 30,+ theme: THEME,+ surfaces: deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 }),+ toast: "Copied to clipboard",+ });+ expect(lightFrame.rows[3]).toContain("\x1b[38;2;0;0;0m Copied to clipboard \x1b[39m");+ expect(lightFrame.rows[3]).not.toContain("\x1b[97m");+ });++ it("anchors the chrome — header, footer controls, drawer — to the probed background", () => {+ const light = deriveTraceViewerSurfaces({ r: 255, g: 255, b: 255 });+ const frame = renderTraceViewer(+ viewerState(conversationSpans(), { panelOpen: true, selectedRow: 2 }),+ { width: 100, height: 30, theme: THEME, surfaces: light },+ );+ // Header: primary title, muted metadata segments.+ expect(frame.rows[1]).toContain("\x1b[1m\x1b[38;2;0;0;0m▲ traces\x1b[39m\x1b[22m");+ expect(frame.rows[1]).toContain("\x1b[38;2;115;115;115m");+ // Footer control hints render as black-anchored muted text.+ const footer = frame.rows[frame.rows.length - 2]!;+ expect(footer).toContain("\x1b[38;2;115;115;115m");+ expect(footer).toContain("q close");+ // Drawer: primary span name and muted fact labels.+ expect(+ frame.rows.some((row) => row.includes("\x1b[38;2;0;0;0mai.streamText.doStream\x1b[39m")),+ ).toBe(true);+ expect(frame.rows.some((row) => row.includes("\x1b[38;2;115;115;115mstatus"))).toBe(true);+ // Without surfaces the chrome keeps the theme's plain emphasis.+ const plain = render(viewerState(conversationSpans(), { panelOpen: true, selectedRow: 2 }));+ expect(plain.rows[1]).toContain("\x1b[1m▲ traces\x1b[22m");+ expect(plain.rows.join("\n")).not.toContain("\x1b[38;2;");});});diff --git a/packages/eve/src/cli/dev/tui/traces/trace-view.ts b/packages/eve/src/cli/dev/tui/traces/trace-view.tsindex d246f497a..e856dbc32 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-view.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-view.ts@@ -21,6 +21,7 @@ import { describeLocalTraceSpan } from "#tracing/local-trace-reader.js";import type { Theme } from "../theme.js";import { formatAttributeContent } from "./trace-content.js";import { renderConversationItem } from "./trace-conversation.js";+import type { TraceViewerSurfaces } from "./trace-surfaces.js";import type { TextSelectionRange, TraceViewerState } from "./trace-viewer-state.js";import {TRACE_VIEWER_HEADER_ROWS,@@ -58,6 +59,11 @@ export interface RenderTraceViewerOptions {readonly tracingDisabled?: boolean;/** Transient confirmation shown in the header's top-right corner. */readonly toast?: string;+ /**+ * Card surfaces derived from the terminal's background (OSC 11 probe).+ * Absent when the terminal never answered — cards fall back to rails.+ */+ readonly surfaces?: TraceViewerSurfaces;}export function renderTraceViewer(@@ -65,11 +71,12 @@ export function renderTraceViewer(options: RenderTraceViewerOptions,): TraceViewerFrame {const { width, height, theme } = options;+ const chrome = chromeStyles(theme, options.surfaces);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 detailLines = panelDetailLines(state, panelWidth, theme);+ const detailLines = panelDetailLines(state, panelWidth, theme, options.surfaces);const panelViewportRows = bodyRows;const rows: string[] = [];@@ -77,7 +84,7 @@ export function renderTraceViewer(if (state.traces.length === 0) {rows.push(...renderEmptyState(options, theme, bodyRows));} else if (state.trace === undefined) {- rows.push(...center(bodyRows, theme.colors.dim("Loading trace…")));+ rows.push(...center(bodyRows, chrome.muted("Loading trace…")));} else {const body = renderConversation(state, options, timelineWidth, bodyRows);for (let index = 0; index < bodyRows; index += 1) {@@ -98,11 +105,16 @@ export function renderTraceViewer(rows.push(joinPanels(left, timelineWidth, panelLine, width));}}- rows.push(...renderFooter(state, width, theme));- if (options.toast !== undefined) overlayToast(rows, options.toast, width, theme);+ rows.push(...renderFooter(state, width, theme, options.surfaces));+ if (options.toast !== undefined) {+ overlayToast(rows, options.toast, width, theme, options.surfaces);+ }+ // Rows render on the terminal's own background — the alt-screen painter+ // erases the screen before each frame, so no canvas fill is needed and the+ // viewer follows the user's palette like the rest of the TUI.return {- rows: rows.map((row) => withViewerBase(row, width, theme)),+ rows,panelTotalRows: detailLines.length,timelineViewportRows: bodyRows,panelViewportRows,@@ -111,47 +123,52 @@ export function renderTraceViewer(}/**- * 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.+ * Text styles for the viewer's chrome (header, footer controls, drawer,+ * empty states). Once the terminal has answered the background probe, both+ * styles anchor to the probed background — truecolor white-on-dark /+ * black-on-light primary and a truecolor grey muted — instead of trusting+ * how the terminal styles its default foreground. Without a reply they fall+ * back to the theme's plain emphasis.*/-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}`;+function chromeStyles(+ theme: Theme,+ surfaces: TraceViewerSurfaces | undefined,+): { readonly muted: (text: string) => string; readonly primary: (text: string) => string } {+ const active = theme.color ? surfaces : undefined;+ return {+ muted: active?.mutedText ?? theme.colors.dim,+ primary: active?.primaryText ?? ((text: string) => text),+ };}/*** The toast floats over the frame's top-right corner as a small elevated- * surface: a greyish-white half-block bar down its left edge, a padding row- * above and below the message, and one column of canvas as right margin.+ * card: a bright half-block bar down its left edge, a padding row above and+ * below the message, and one column of margin on the right. When card+ * surfaces are available (OSC 11 answered) the toast sits on the body band;+ * otherwise the bar alone carries it.*/-const TOAST_SURFACE = "\x1b[48;2;36;36;36m";-const TOAST_BAR = "\x1b[38;2;210;210;210m▌\x1b[39m";-const TOAST_TEXT = "\x1b[97m";--function overlayToast(rows: string[], message: string, width: number, theme: Theme): void {+function overlayToast(+ rows: string[],+ message: string,+ width: number,+ theme: Theme,+ surfaces?: TraceViewerSurfaces,+): void {const text = stripTerminalControls(message);const inner = ` ${text} `;const innerWidth = visibleLength(inner);- const lines = theme.color- ? [- `${TOAST_SURFACE}${TOAST_BAR}${" ".repeat(innerWidth)}\x1b[0m`,- `${TOAST_SURFACE}${TOAST_BAR}${TOAST_TEXT}${inner}\x1b[0m`,- `${TOAST_SURFACE}${TOAST_BAR}${" ".repeat(innerWidth)}\x1b[0m`,- ]- : [`▌${" ".repeat(innerWidth)}`, `▌${inner}`, `▌${" ".repeat(innerWidth)}`];+ const bar = theme.unicode ? "▌" : theme.glyph.rule;+ const active = theme.color ? surfaces : undefined;+ const surface = active === undefined ? "" : active.body;+ // Surface-matched primary keeps the toast legible on light backgrounds.+ const primary = active?.primaryText ?? theme.colors.white;+ const close = theme.color ? "\x1b[0m" : "";+ const lines = [+ `${surface}${primary(bar)}${" ".repeat(innerWidth)}${close}`,+ `${surface}${primary(bar)}${primary(inner)}${close}`,+ `${surface}${primary(bar)}${" ".repeat(innerWidth)}${close}`,+ ];// Below the title row, so the trace identity stays readable.for (const [offset, line] of lines.entries()) {const index = HEADER_ROWS - 1 + offset;@@ -160,7 +177,7 @@ function overlayToast(rows: string[], message: string, width: number, theme: The}}-/** Splices `segment` over the right end of `row`, keeping `margin` canvas columns. */+/** Splices `segment` over the right end of `row`, keeping `margin` empty columns. */function overlayRight(row: string, segment: string, width: number, margin: number): string {const cut = Math.max(0, width - margin - visibleLength(segment));const rowWidth = visibleLength(row);@@ -188,17 +205,21 @@ export function renderSpanDetail(span: LocalTraceSpan,innerWidth: number,theme: Theme,- options?: { readonly excludeKeys?: ReadonlySet<string> },+ options?: {+ readonly excludeKeys?: ReadonlySet<string>;+ readonly surfaces?: TraceViewerSurfaces;+ },): string[] {const { colors } = theme;+ const { muted, primary } = chromeStyles(theme, options?.surfaces);const lines: string[] = [];const name = stripTerminalControls(span.name);- lines.push(...wrapVisibleLine(colors.bold(name), innerWidth));+ lines.push(...wrapVisibleLine(colors.bold(primary(name)), innerWidth));const summary = describeLocalTraceSpan(span).map(stripTerminalControls);- if (summary.length > 0) lines.push(colors.dim(summary.join(", ")));+ if (summary.length > 0) lines.push(muted(summary.join(", ")));lines.push("");- const fact = (label: string, value: string): string => `${colors.dim(label.padEnd(10))}${value}`;+ const fact = (label: string, value: string): string => `${muted(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))));@@ -212,17 +233,17 @@ export function renderSpanDetail(.filter((key) => options?.excludeKeys?.has(key) !== true).sort();if (keys.length === 0) {- lines.push(colors.dim("no attributes"));+ lines.push(muted("no attributes"));} else {- lines.push(colors.dim(`attributes (${keys.length})`));+ lines.push(muted(`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));+ lines.push(...wrapVisibleLine(`${muted(cleanKey)} ${block[0]}`, innerWidth));} else {- lines.push(colors.dim(cleanKey));+ lines.push(muted(cleanKey));for (const line of block) {lines.push(` ${line}`);}@@ -235,6 +256,7 @@ export function renderSpanDetail(function renderHeader(state: TraceViewerState, options: RenderTraceViewerOptions): string[] {const { theme, width } = options;const { colors, glyph } = theme;+ const { muted, primary } = chromeStyles(theme, options.surfaces);const segments: string[] = [];if (state.trace?.agentName !== undefined) {segments.push(stripTerminalControls(state.trace.agentName));@@ -253,11 +275,11 @@ function renderHeader(state: TraceViewerState, options: RenderTraceViewerOptionsformatElapsed(durationMs(state.trace.startTimeNs, end)),);}- const title = `${colors.bold(`${glyph.brand} traces`)}${- segments.length === 0 ? "" : colors.dim(` · ${segments.join(" · ")}`)+ const title = `${colors.bold(primary(`${glyph.brand} traces`))}${+ segments.length === 0 ? "" : muted(` · ${segments.join(" · ")}`)}`;const position =- state.traces.length === 0 ? "" : colors.dim(`[${state.traceIndex + 1}/${state.traces.length}]`);+ state.traces.length === 0 ? "" : muted(`[${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.@@ -281,14 +303,14 @@ function renderConversation(const { theme } = options;if (state.conversationItems.length === 0) {return [- theme.colors.dim(+ chromeStyles(theme, options.surfaces).muted(" 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 = conversationLines(state, width, theme);+ const allLines = conversationLines(state, width, theme, options.surfaces);const visible = allLines.slice(state.scrollRow, state.scrollRow + bodyRows);if (state.textSelection === undefined || state.textSelection.region !== "conversation") {return visible;@@ -298,7 +320,12 @@ function renderConversation();}-function conversationLines(state: TraceViewerState, width: number, theme: Theme): string[] {+function conversationLines(+ state: TraceViewerState,+ width: number,+ theme: Theme,+ surfaces?: TraceViewerSurfaces,+): string[] {const allLines: string[] = [];for (let index = 0; index < state.conversationItems.length; index += 1) {allLines.push(@@ -308,6 +335,7 @@ function conversationLines(state: TraceViewerState, width: number, theme: Theme)theme,index === state.selectedRow,state.expandedItems.has(index),+ surfaces,),"",);@@ -321,13 +349,19 @@ function conversationLines(state: TraceViewerState, width: number, theme: Theme)* doesn't fit (very narrow terminal) isn't modeled as open — otherwise key* handling would scroll content nobody can see.*/-function panelDetailLines(state: TraceViewerState, panelWidth: number, theme: Theme): string[] {+function panelDetailLines(+ state: TraceViewerState,+ panelWidth: number,+ theme: Theme,+ surfaces?: TraceViewerSurfaces,+): string[] {const selected = selectedTraceViewerSpan(state);if (!state.panelOpen || panelWidth <= 0 || selected === undefined) return [];return ["",...renderSpanDetail(selected, Math.max(16, panelWidth - 3), theme, {excludeKeys: CONVERSATION_CONTENT_KEYS,+ surfaces,}).map((line) => ` ${line}`),];}@@ -341,8 +375,9 @@ export function conversationSelectionText(width: number,theme: Theme,selection: TextSelectionRange,+ surfaces?: TraceViewerSurfaces,): string {- return selectionText(conversationLines(state, width, theme), selection);+ return selectionText(conversationLines(state, width, theme, surfaces), selection);}/**@@ -406,20 +441,26 @@ function highlightSelection(return `${prefix}\x1b[7m${inverted}\x1b[27m${suffix}`;}-function renderFooter(state: TraceViewerState, width: number, theme: Theme): string[] {+function renderFooter(+ state: TraceViewerState,+ width: number,+ theme: Theme,+ surfaces?: TraceViewerSurfaces,+): string[] {const { colors } = theme;+ const { muted } = chromeStyles(theme, surfaces);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 position = itemCount === 0 ? "" : muted(`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(" · "));+ const status = [notice, position].filter((part) => part.length > 0).join(muted(" · "));// A padding row separates the cards from the hints.return ["",- clipVisible(` ${colors.dim(hints)}`, width),+ clipVisible(` ${muted(hints)}`, width),clipVisible(status.length === 0 ? "" : ` ${status}`, width),];}@@ -429,11 +470,12 @@ function renderEmptyState(theme: Theme,bodyRows: number,): string[] {+ const { muted, primary } = chromeStyles(theme, options.surfaces);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."];- return center(bodyRows, theme.colors.bold(first), theme.colors.dim(second));+ return center(bodyRows, theme.colors.bold(primary(first)), muted(second));}/** Fills a `bodyRows`-tall body, centering `lines` as a block within it. */@@ -448,7 +490,7 @@ function center(bodyRows: number, ...lines: string[]): string[] {/*** Joins one conversation row to its drawer row. The single separating column- * carries no divider: the base canvas already separates the two.+ * carries no divider: the blank gap already separates the two.*/function joinPanels(left: string, leftWidth: number, right: string, width: number): string {const rightWidth = Math.max(0, width - leftWidth - 1);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.tsindex bef133ebb..00b8ee3a5 100644--- 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@@ -112,7 +112,7 @@ describe("TraceViewerSession drag copy", () => {const last = frames[frames.length - 1]?.join("\n") ?? "";if (!last.includes("copy me please")) throw new Error("no conversation frame yet");});- // Drag across the user card's text row (two header rows, then the+ // Drag across the user card's text row (three header rows, then the// card's band, title, band, and padding rows): press, motion, release.session.handleKey({ type: "mouse", action: "press", button: 0, x: 1, y: 8 });session.handleKey({ type: "mouse", action: "press", button: 32, x: 40, y: 8 });@@ -134,6 +134,90 @@ describe("TraceViewerSession drag copy", () => {});});+describe("TraceViewerSession background surfaces", () => {+ it("derives card bands from the OSC 11 background reply and repaints", async () => {+ const turn = span("a".repeat(16), "session-mine");+ const model: LocalTraceSpan = {+ ...span("b".repeat(16), "session-mine"),+ name: "ai.streamText.doStream",+ parentSpanId: turn.spanId,+ attributes: {+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),+ "ai.response.text": "reply",+ },+ };+ const store = stubStore([+ {+ endTimeNs: 1_000_000n,+ sessionId: "session-mine",+ sessionIds: ["session-mine"],+ spans: [turn, model],+ startTimeNs: 1_000_000n,+ traceId: "c".repeat(32),+ },+ ]);+ const frames: string[][] = [];+ const session = new TraceViewerSession({+ appRoot: "/nowhere",+ dimensions: () => ({ width: 80, height: 24 }),+ paint: (rows) => frames.push([...rows]),+ store,+ theme: createTheme({ color: true, unicode: true }),+ });+ session.start();+ await vi.waitFor(() => {+ const last = frames[frames.length - 1]?.join("\n") ?? "";+ if (!last.includes("reply")) throw new Error("no conversation frame yet");+ });+ // Before the terminal answers the probe: rail rendering, no truecolor.+ expect(frames[frames.length - 1]!.join("\n")).not.toContain("\x1b[48;2;");+ session.setTerminalBackground({ r: 0, g: 0, b: 0 });+ const surfaced = frames[frames.length - 1]!.join("\n");+ expect(surfaced).toContain("\x1b[48;2;22;22;22m");+ expect(surfaced).toContain("\x1b[48;2;36;36;36m");+ session.dispose();+ });++ it("paints surfaces from the first conversation frame with a cached background", async () => {+ const turn = span("a".repeat(16), "session-mine");+ const model: LocalTraceSpan = {+ ...span("b".repeat(16), "session-mine"),+ name: "ai.streamText.doStream",+ parentSpanId: turn.spanId,+ attributes: {+ "ai.prompt.messages": JSON.stringify([{ role: "user", content: "hi" }]),+ "ai.response.text": "reply",+ },+ };+ const store = stubStore([+ {+ endTimeNs: 1_000_000n,+ sessionId: "session-mine",+ sessionIds: ["session-mine"],+ spans: [turn, model],+ startTimeNs: 1_000_000n,+ traceId: "c".repeat(32),+ },+ ]);+ const frames: string[][] = [];+ const session = new TraceViewerSession({+ appRoot: "/nowhere",+ dimensions: () => ({ width: 80, height: 24 }),+ paint: (rows) => frames.push([...rows]),+ store,+ terminalBackground: { r: 0, g: 0, b: 0 },+ theme: createTheme({ color: true, unicode: true }),+ });+ session.start();+ await vi.waitFor(() => {+ const last = frames[frames.length - 1]?.join("\n") ?? "";+ if (!last.includes("reply")) throw new Error("no conversation frame yet");+ });+ expect(frames[frames.length - 1]!.join("\n")).toContain("\x1b[48;2;22;22;22m");+ session.dispose();+ });+});+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 bydiff --git a/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.tsindex a036af712..8864ecaea 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-viewer-session.ts@@ -6,10 +6,13 @@*/import type { TerminalKey } from "../stream-format.js";+import type { RgbColor } from "../terminal-background.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 type { TraceViewerSurfaces } from "./trace-surfaces.js";+import { deriveTraceViewerSurfaces } from "./trace-surfaces.js";import { conversationSelectionText, panelSelectionText, renderTraceViewer } from "./trace-view.js";import type {TextSelectionRange,@@ -50,6 +53,12 @@ export interface TraceViewerSessionOptions extends TraceViewerOpenOptions {readonly store?: TraceStore;/** Receives drag-selected text (wired to the clipboard by the renderer). */readonly copyText?: (text: string) => void;+ /**+ * The terminal's default background from an earlier OSC 11 reply, so a+ * reopened viewer paints its card surfaces on the first frame instead of+ * waiting for the terminal to answer the probe again.+ */+ readonly terminalBackground?: RgbColor;}export class TraceViewerSession {@@ -72,6 +81,7 @@ export class TraceViewerSession {#disposed = false;#refreshing = false;#refreshAgain = false;+ #surfaces?: TraceViewerSurfaces;#metrics: TraceViewerKeyEnvironment = {timelineViewportRows: 0,panelViewportRows: 0,@@ -82,6 +92,9 @@ export class TraceViewerSession {constructor(options: TraceViewerSessionOptions) {this.#options = options;this.#store = options.store ?? createTraceStore({ appRoot: options.appRoot });+ if (options.terminalBackground !== undefined && options.theme.color) {+ this.#surfaces = deriveTraceViewerSurfaces(options.terminalBackground);+ }if (options.sessionId !== undefined) {this.#preferSessionId = options.sessionId;}@@ -121,6 +134,17 @@ export class TraceViewerSession {return undefined;}+ /**+ * Applies the terminal's OSC 11 background reply: derives the card+ * surfaces from the user's own palette and repaints. No-color themes keep+ * the plain rail rendering.+ */+ setTerminalBackground(background: RgbColor): void {+ if (this.#disposed || !this.#options.theme.color) return;+ this.#surfaces = deriveTraceViewerSurfaces(background);+ this.repaint();+ }+repaint(): void {if (this.#disposed) return;const { width, height } = this.#options.dimensions();@@ -131,6 +155,7 @@ export class TraceViewerSession {tracingDisabled: this.#options.tracingDisabled,activeWindowEndNs: this.#activeWindowEndNs(),toast: this.#toast,+ surfaces: this.#surfaces,});this.#metrics = {timelineViewportRows: frame.timelineViewportRows,@@ -176,6 +201,7 @@ export class TraceViewerSession {this.#metrics.contentWidth,this.#options.theme,selection,+ this.#surfaces,);if (text.trim().length === 0) return;this.#options.copyText?.(text);