Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): parser-backed markdown and semantic tool activity in the dev TUI (#882)

Rui1f04ff7a4f17
diff --git a/.changeset/dev-tui-rendering.md b/.changeset/dev-tui-rendering.md
new file mode 100644
index 000000000..ae1d68d50
--- /dev/null
+++ b/.changeset/dev-tui-rendering.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The dev TUI renders Markdown through a real GFM parser (width-fitted tables, code blocks, task lists, links), presents every builtin tool with semantic activity copy (`Fetch <url>`, `Run <command>`, `Search <query>` — including `web_search` across provider input shapes, `todo`, `ask_question`, `agent`, and `connection_search`), and shows rejected tool approvals as denied instead of successful. Tool activity now accumulates in place: an in-flight batch renders as one counted header with its newest calls listed first behind a `│` rail and a `… (N more)` elision, then collapses to a single past-tense line (`▪ Fetched 30 URLs`) once every call settles — failures keep their itemized per-call error rail — and each `write_file` keeps its own block rendering a real line diff (`+`/`-` rows with context, computed from content the session has already seen — prior writes and full-file reads; new files show all additions). `ask_question` prompts open as a numbered overlay panel above the input (number keys select directly, the "Type your own answer" row focuses its inline editor on reach, Esc dismisses to plain text input), committing as `? question ⎿ answer` in the transcript. The `todo` tool no longer emits transcript blocks; it drives a pinned panel above the input showing per-task state, which commits as a completed block once every task settles. An empty prompt now shows a quiet `›` mark with a rotating placeholder of things to try, switching to the active `❯` once typing starts. Reasoning defaults to a fixed one-line thinking indicator that updates in place (persisting as `○ Thought for 12s` only for long thoughts; `--reasoning full` restores the streaming trace), the prompt stays anchored during a turn with Enter inert (the draft carries into the next prompt), and completed turns close with a `└ Done in <duration>` stats coda (per-turn token flow, context fill) when the turn was long or expensive. Subagent calls render as individual `※ subagent(<name>) #N` sections in the tool column whose child rows window to the three most recently active (failures stay itemized while settled work condenses to one counted row) and close on a corner that reports `Done` once the call's final message arrives; captured server output renders as one open-railed `○ stderr` / `○ stdout` stream section per source (streams are continuous — no closing corner, and interleaved activity never fragments them): the section sits at its newest write's position — everything that happened after the last error displays after it — and shows only that newest write, with earlier ones behind an `… (N more)` count (the stored-diagnostics pointer carries the history); the status bar names the model's actual routing and credential (`via ai-gateway(oidc:<project>)`, `via ai-gateway(api-key)`, or `via <provider>⌝` for a directly-authored endpoint); an empty prompt no longer submits; and a mid-conversation session replacement marks the context cut with a `┌── Session restarted, clear context.` boundary line.
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 588cfe16c..5d507caa4 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -344,6 +344,7 @@
"jose": "6.2.3",
"jsonc-parser": "3.3.1",
"just-bash": "3.0.1",
+ "marked": "catalog:",
"microsandbox": "0.5.5",
"next": "catalog:",
"picocolors": "catalog:",
diff --git a/packages/eve/scripts/vendor-compiled/declarations/marked.d.ts b/packages/eve/scripts/vendor-compiled/declarations/marked.d.ts
new file mode 100644
index 000000000..a86d7cb7f
--- /dev/null
+++ b/packages/eve/scripts/vendor-compiled/declarations/marked.d.ts
@@ -0,0 +1,24 @@
+export interface Token {
+ readonly type: string;
+ readonly raw?: string;
+ readonly text?: string;
+ readonly depth?: number;
+ readonly lang?: string;
+ readonly ordered?: boolean;
+ readonly start?: number | string;
+ readonly checked?: boolean;
+ readonly href?: string;
+ readonly title?: string | null;
+ readonly tokens?: readonly Token[];
+ readonly items?: readonly Token[];
+ readonly header?: readonly TableCell[];
+ readonly rows?: readonly (readonly TableCell[])[];
+ readonly align?: readonly ("center" | "left" | "right" | null)[];
+}
+
+export interface TableCell {
+ readonly text: string;
+ readonly tokens: readonly Token[];
+}
+
+export function lexer(markdown: string): readonly Token[];
diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjs
index 027905d89..6a8c930e7 100644
--- a/packages/eve/scripts/vendor-compiled/index.mjs
+++ b/packages/eve/scripts/vendor-compiled/index.mjs
@@ -37,6 +37,7 @@ import grayMatter from "./gray-matter.mjs";
import jose from "./jose.mjs";
import jsoncParser from "./jsonc-parser.mjs";
import jsonSchema from "./json-schema.mjs";
+import marked from "./marked.mjs";
import picocolors from "./picocolors.mjs";
import semver from "./semver.mjs";
import turndown from "./turndown.mjs";
@@ -59,6 +60,7 @@ export const MODULES = [
jose,
jsoncParser,
jsonSchema,
+ marked,
mcp,
openai,
opentelemetryApi,
diff --git a/packages/eve/scripts/vendor-compiled/marked.mjs b/packages/eve/scripts/vendor-compiled/marked.mjs
new file mode 100644
index 000000000..ca7308df5
--- /dev/null
+++ b/packages/eve/scripts/vendor-compiled/marked.mjs
@@ -0,0 +1,8 @@
+import { loadDeclaration } from "./_shared.mjs";
+
+export default {
+ packageName: "marked",
+ compiledPath: "marked",
+ bundling: "standalone",
+ declaration: await loadDeclaration("marked.d.ts"),
+};
diff --git a/packages/eve/src/cli/banner.ts b/packages/eve/src/cli/banner.ts
index 2a63503d8..9f48a8a92 100644
--- a/packages/eve/src/cli/banner.ts
+++ b/packages/eve/src/cli/banner.ts
@@ -13,3 +13,12 @@ export function eveCliBanner(): string {
const { version } = resolveInstalledPackageInfo();
return `${pc.bgBlack(pc.white(`☰${EVE_WORDMARK} `))} ${pc.dim(`v${version}`)}`;
}
+
+/**
+ * The unstyled wordmark-and-version tag (`☰eve v0.24.5`) — the boot banner's
+ * plain-text form. The dev TUI dims it as its parting line on teardown.
+ */
+export function eveVersionTag(): string {
+ const { version } = resolveInstalledPackageInfo();
+ return `☰${EVE_WORDMARK} v${version}`;
+}
diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.ts
index bd91ef0fb..8bb79ac47 100644
--- a/packages/eve/src/cli/dev/tui/blocks.test.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts
@@ -1,19 +1,20 @@
import { describe, expect, it } from "vitest";
-import { type Block, renderBlockLines } from "./blocks.js";
+import { type DisplayBlock, renderBlockLines } from "./blocks.js";
+import { maxVisibleToolGroupItems } from "./tool-rows.js";
import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
import { createTheme } from "./theme.js";
const theme = createTheme({ color: false, unicode: true });
-const ctx = { spinner: "⠋" };
+const ctx = { activityPulse: "▪" };
-function render(block: Block, width = 60): string[] {
+function render(block: DisplayBlock, width = 60): string[] {
return renderBlockLines(block, width, theme, ctx).map(stripAnsi);
}
describe("renderBlockLines", () => {
it("renders a user message behind a left bar", () => {
- expect(render({ kind: "user", body: "hello there" })).toEqual(["▌ hello there"]);
+ expect(render({ kind: "user", body: "hello there" })).toEqual(["│ hello there"]);
});
it("marks the assistant with the brand triangle", () => {
@@ -29,13 +30,208 @@ describe("renderBlockLines", () => {
status: "done",
result: "73°F",
});
- expect(lines[0]).toBe('✓ get_weather city="SF"');
- expect(lines[1]).toBe(" → 73°F");
+ expect(lines[0]).toBe(' ▪ get_weather city="SF"');
+ expect(lines[1]).toBe(" → 73°F");
});
- it("shows a spinner while a tool runs", () => {
+ it("swaps in the past-tense title once the call settles", () => {
+ const running = render({
+ kind: "tool",
+ title: "Fetch https://one.example",
+ doneTitle: "Fetched https://one.example",
+ status: "running",
+ });
+ expect(running[0]).toBe(" ▪ Fetch https://one.example");
+
+ const done = render({
+ kind: "tool",
+ title: "Fetch https://one.example",
+ doneTitle: "Fetched https://one.example",
+ status: "done",
+ });
+ expect(done).toEqual([" ▪ Fetched https://one.example"]);
+ });
+
+ it("bolds only the leading verb of a tool header", () => {
+ const colored = createTheme({ color: true, unicode: true });
+ const [header] = renderBlockLines(
+ { kind: "tool", title: "Ran find /workspace -maxdepth 3", status: "done" },
+ 80,
+ colored,
+ ctx,
+ );
+ // The verb closes bold before its argument begins; the argument is dim.
+ expect(header).toContain("\x1b[1mRan\x1b[22m\x1b[2m find /workspace -maxdepth 3\x1b[22m");
+ });
+
+ it("shows the shared square pulse while a tool runs", () => {
const lines = render({ kind: "tool", title: "search", status: "running", live: true });
- expect(lines[0]).toBe("⠋ search");
+ expect(lines[0]).toBe(" ▪ search");
+ });
+
+ it("renders a coalesced tool presentation as a railed item region", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Fetch 2 URLs",
+ status: "running",
+ toolGroupItems: [{ text: "https://two.example" }, { text: "https://one.example" }],
+ });
+ expect(lines).toEqual([
+ " ▪ Fetch 2 URLs",
+ " │ https://two.example",
+ " │ https://one.example",
+ " └",
+ ]);
+ });
+
+ it("caps a coalesced batch's item list behind an elision line", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Fetch 30 URLs",
+ status: "running",
+ toolGroupItems: Array.from({ length: 30 }, (_, index) => ({
+ text: `https://example.com/${index + 1}`,
+ })),
+ });
+ expect(lines).toHaveLength(1 + maxVisibleToolGroupItems + 2);
+ expect(lines[1]).toBe(" │ https://example.com/1");
+ expect(lines[maxVisibleToolGroupItems]).toBe(
+ ` │ https://example.com/${maxVisibleToolGroupItems}`,
+ );
+ expect(lines.at(-2)).toBe(" │ … (25 more)");
+ expect(lines.at(-1)).toBe(" └");
+ });
+
+ it("renders a coalesced failed batch as an aligned per-item summary table", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Fetch 2 URLs",
+ status: "error",
+ toolGroupItems: [
+ { text: "https://one.example", result: "status 403" },
+ { text: "https://two.example/nested", result: "status 429" },
+ ],
+ });
+ expect(lines).toEqual([
+ " ⨯ Fetch 2 URLs",
+ " │ https://one.example status 403",
+ " │ https://two.example/nested status 429",
+ " └",
+ ]);
+ });
+
+ it("keeps a write's railed content visible after the call settles", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Write ~/app/package.json",
+ doneTitle: "Wrote ~/app/package.json",
+ status: "done",
+ detailLines: [{ text: "{" }, { text: ' "name": "app"' }, { text: "}" }],
+ keepDetailWhenDone: true,
+ });
+ expect(lines).toEqual([
+ " ▪ Wrote ~/app/package.json",
+ " │ {",
+ ' │ "name": "app"',
+ " │ }",
+ " └",
+ ]);
+ });
+
+ it("renders a write diff with marker-aligned added and removed rows", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Write ~/app/package.json",
+ doneTitle: "Wrote ~/app/package.json",
+ status: "done",
+ detailLines: [
+ { text: ' "dev": "eve dev",' },
+ { text: ' "typecheck": "eve build && tsc"', kind: "added" },
+ { text: ' "zod": "^5.6.0"', kind: "removed" },
+ { text: "", kind: "gap" },
+ { text: " }" },
+ ],
+ keepDetailWhenDone: true,
+ });
+ expect(lines).toEqual([
+ " ▪ Wrote ~/app/package.json",
+ ' │ "dev": "eve dev",',
+ ' │+ "typecheck": "eve build && tsc"',
+ ' │- "zod": "^5.6.0"',
+ " │ …",
+ " │ }",
+ " └",
+ ]);
+ });
+
+ it("drops non-write detail once the call settles", () => {
+ const lines = render({
+ kind: "tool",
+ title: "Run pnpm test",
+ doneTitle: "Ran pnpm test",
+ status: "done",
+ detailLines: [{ text: "line one" }, { text: "line two" }],
+ });
+ expect(lines).toEqual([" ▪ Ran pnpm test"]);
+ });
+
+ it("renders the end-of-turn stats as a dim cornered coda", () => {
+ expect(render({ kind: "turn-stats", body: "Done in 3min 24s ── ↑ 32.4K ↓ 682" })).toEqual([
+ "└ Done in 3min 24s ── ↑ 32.4K ↓ 682",
+ ]);
+ });
+
+ it("renders a counted subagent header for coalesced parallel calls", () => {
+ const lines = render({
+ kind: "subagent",
+ title: "echo-marker",
+ subtitle: "3 calls",
+ live: false,
+ });
+ expect(lines).toEqual([" ※ subagent(echo-marker) 3 calls"]);
+ });
+
+ it("folds the ordinal into a completed header without a Done suffix", () => {
+ // Completion reports on the closing corner; the header only flips its
+ // mark to green.
+ const lines = render({
+ kind: "subagent",
+ title: "agent",
+ subtitle: "#4",
+ status: "done",
+ live: false,
+ });
+ expect(lines).toEqual([" ※ subagent(self:4)"]);
+ });
+
+ it("collapses a child message to its first line inside the section", () => {
+ const lines = render({
+ kind: "subagent-step",
+ depth: 1,
+ collapsed: true,
+ body: "The trade-off is abstraction.\n\nMore detail…",
+ live: false,
+ });
+ expect(lines).toEqual([" │ The trade-off is abstraction."]);
+
+ // `--subagents full` keeps the verbatim prose.
+ const full = render({
+ kind: "subagent-step",
+ depth: 1,
+ body: "First paragraph.\n\nSecond paragraph.",
+ live: false,
+ });
+ expect(full.length).toBeGreaterThan(1);
+ });
+
+ it("renders an elided stand-in row inside the subagent gutter", () => {
+ const lines = render({
+ kind: "subagent-step",
+ depth: 1,
+ live: false,
+ elided: 6,
+ });
+ expect(lines).toEqual([" │ … (6 more)"]);
});
it("nests subagent tools under the orange rule", () => {
@@ -46,7 +242,7 @@ describe("renderBlockLines", () => {
status: "done",
result: "ok",
});
- expect(lines[0]?.startsWith("│ ✓ fetch")).toBe(true);
+ expect(lines[0]?.startsWith(" │ ▪ fetch")).toBe(true);
});
it("collapses reasoning to a single line when requested", () => {
@@ -75,31 +271,50 @@ describe("renderBlockLines", () => {
}
});
+ it("hangs a question's answer under the elbow with the shared indent", () => {
+ const lines = render({
+ kind: "question",
+ title: "Choose access",
+ body: "⎿ AI Gateway",
+ });
+ expect(lines).toEqual(["? Choose access", " ⎿ AI Gateway"]);
+ });
+
it("renders a dim notice line", () => {
expect(render({ kind: "notice", body: "Started a new session." })).toEqual([
"· Started a new session.",
]);
});
- it("renders a multi-line log run with the label once and a hanging indent", () => {
- const indent = " ".repeat("stderr · ".length);
+ it("renders a multi-line log write as one closed section", () => {
const lines = render({
kind: "log",
title: "stderr",
body: "turn completed {\n sessionId: 'x',\n turnId: 't',\n sequence: 0\n}",
});
expect(lines).toEqual([
- "│ stderr · turn completed {",
- `│ ${indent} sessionId: 'x',`,
- `│ ${indent} turnId: 't',`,
- `│ ${indent} sequence: 0`,
- `│ ${indent}}`,
+ "○ stderr",
+ "│ turn completed {",
+ "│ sessionId: 'x',",
+ "│ turnId: 't',",
+ "│ sequence: 0",
+ "│ }",
]);
});
- it("renders a one-line log with its source label", () => {
+ it("renders a coalesced run's elided count under the section header", () => {
+ const lines = render({
+ kind: "log",
+ title: "stderr",
+ body: "newest line",
+ elided: 52,
+ });
+ expect(lines).toEqual(["○ stderr", "│ … (52 more)", "│ newest line"]);
+ });
+
+ it("renders a one-line log under its source header", () => {
const lines = render({ kind: "log", title: "stdout", body: "weather lookup { city: 'SF' }" });
- expect(lines).toEqual(["│ stdout · weather lookup { city: 'SF' }"]);
+ expect(lines).toEqual(["○ stdout", "│ weather lookup { city: 'SF' }"]);
});
it("renders sandbox lifecycle lines as first-class progress", () => {
@@ -122,28 +337,17 @@ describe("renderBlockLines", () => {
},
80,
theme,
- { spinner: "⠋", previous: { kind: "sandbox" } },
+ { activityPulse: "▪", previous: { kind: "sandbox" } },
).map(stripAnsi);
expect(lines).toEqual([`│ ${indent}sandbox template "root" (microsandbox): apt-get update`]);
});
- it("suppresses the label when a log continues a same-source run", () => {
- const indent = " ".repeat("stdout · ".length);
- const lines = renderBlockLines(
- { kind: "log", title: "stdout", body: "weather lookup { city: 'LA' }" },
- 60,
- theme,
- { spinner: "⠋", previous: { kind: "log", title: "stdout" } },
- ).map(stripAnsi);
- expect(lines).toEqual([`│ ${indent}weather lookup { city: 'LA' }`]);
- });
-
- it("keeps the label when the previous log block has a different source", () => {
+ it("renders a log section identically regardless of what precedes it", () => {
const lines = renderBlockLines({ kind: "log", title: "stderr", body: "boom" }, 60, theme, {
- spinner: "⠋",
- previous: { kind: "log", title: "stdout" },
+ activityPulse: "▪",
+ previous: { kind: "log", title: "stderr" },
}).map(stripAnsi);
- expect(lines).toEqual(["│ stderr · boom"]);
+ expect(lines).toEqual(["○ stderr", "│ boom"]);
});
it("renders an error's diagnostic detail beneath the headline", () => {
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index 8a11397c0..18ac322a1 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -11,10 +11,18 @@
*/
import { renderMarkdown } from "./markdown.js";
+import type { ToolDetailLine } from "./line-diff.js";
import type { Theme } from "./theme.js";
+import type { ToolGroupPresentation } from "./tool-presentation.js";
import { isPromptControlCommand } from "./prompt-commands.js";
-import { formatValuePretty, truncate } from "./tool-format.js";
-import { sliceVisible, visibleLength, wrapVisibleLine } from "#cli/ui/terminal-text.js";
+import { renderTool } from "./tool-rows.js";
+import { elisionText, TOOL_COLUMN_LEAD } from "./rail.js";
+import {
+ clipVisible,
+ sliceVisible,
+ visibleLength,
+ wrapVisibleLine,
+} from "#cli/ui/terminal-text.js";
export type ToolStatus = "running" | "done" | "error" | "denied" | "approval";
@@ -33,9 +41,13 @@ export type BlockKind =
| "subagent"
| "subagent-step"
| "subagent-tool"
+ | "subagent-close"
| "connection-auth"
| "sandbox"
| "log"
+ | "turn-stats"
+ | "session-boundary"
+ | "todo-list"
| "agent-header";
/**
@@ -48,11 +60,13 @@ export interface Block {
id?: string;
/** Nesting depth: 0 = top level, 1 = inside a subagent, etc. */
depth?: number;
- /** Whether the block is still streaming / mutating (drives the spinner). */
+ /** Whether the block is still streaming / mutating (drives the activity pulse). */
live?: boolean;
/** Primary label — tool name, subagent name, log source, error title. */
title?: string;
+ /** Past-tense tool label swapped in once the call settles successfully. */
+ doneTitle?: string;
/** Compact secondary text — summarized tool args. */
subtitle?: string;
/** Main multi-line content (markdown for prose, plain for logs). */
@@ -82,16 +96,62 @@ export interface Block {
/** Raw tool input / output for the expanded view. */
toolInput?: unknown;
toolOutput?: unknown;
+ /** Original execution name, kept separate from a semantic display title. */
+ toolName?: string;
+ /** Optional aggregation metadata; execution state remains on this call's block. */
+ toolGroup?: ToolGroupPresentation;
+ /** Salient body lines rendered behind the `│` rail under the tool header. */
+ detailLines?: readonly ToolDetailLine[];
+ /** When true, `detailLines` stay visible after the call settles (writes). */
+ keepDetailWhenDone?: boolean;
+ /** Links a subagent section's header and children so calls can coalesce. */
+ subagentCallId?: string;
+ /**
+ * Monotonic activity stamp, bumped on every push and in-place update.
+ * Recency windows key on it so a parallel-announced call that just
+ * settled counts as newer than a later-announced one still idle.
+ */
+ updateSeq?: number;
+}
+
+/**
+ * What the renderers actually draw: an execution {@link Block} plus the
+ * synthesized presentation the display grouping may attach. Only the
+ * grouping layer creates these fields, so an execution block can never
+ * smuggle display state — the type boundary enforces what used to be a
+ * comment.
+ */
+export interface DisplayBlock extends Block {
+ /** Items listed when equivalent tool calls are coalesced into one row. */
+ toolGroupItems?: readonly ToolGroupItem[];
+ /**
+ * Stand-in for this many earlier sibling rows elided from a capped
+ * subagent run; renders as a single dim `… +N more` line.
+ */
+ elided?: number;
+ /**
+ * This block is the last of its section, so its final row swaps the
+ * nesting rule for the closing `└` — the rail ends on the newest child
+ * instead of a bare corner row.
+ */
+ closesRail?: boolean;
+}
+
+/** One coalesced call's row beneath an aggregated tool header. */
+export interface ToolGroupItem {
+ readonly text: string;
+ /** Per-call failure summary, present when a failed batch is aggregated. */
+ readonly result?: string;
}
export interface RenderBlockContext {
- /** Current spinner frame for live blocks. */
- spinner: string;
+ /** Current shared square-pulse frame for live activity blocks. */
+ activityPulse: string;
/**
* Kind and title of the block rendered immediately above this one. Lets a
- * log block detect that it continues a same-source run (label suppressed,
- * lines hang under the previous block's label) without any mutable run
- * state — each captured write stays its own immediately-committed block.
+ * sandbox block detect that it continues a run (label suppressed, lines
+ * hang under the previous block's label) without any mutable run state —
+ * each captured write stays its own immediately-committed block.
*/
previous?: { kind: BlockKind; title?: string };
}
@@ -101,7 +161,7 @@ export interface RenderBlockContext {
* to `width` visible columns.
*/
export function renderBlockLines(
- block: Block,
+ block: DisplayBlock,
width: number,
theme: Theme,
context: RenderBlockContext,
@@ -110,25 +170,44 @@ export function renderBlockLines(
const prefix = nestingPrefix(depth, theme);
const avail = Math.max(8, width - visibleLength(prefix));
const rows = renderBody(block, avail, theme, context);
+ // The section's last row carries the closing corner in place of its rule.
+ if (block.closesRail === true && depth > 0) {
+ const corner = closingPrefix(depth, theme);
+ return rows.map((row, index) => `${index === rows.length - 1 ? corner : prefix}${row}`);
+ }
return rows.map((row) => `${prefix}${row}`);
}
/**
- * The gutter prefix repeated for each nesting level: a Vercel-orange vertical
- * rule that visually contains a subagent's output beneath its header.
+ * The gutter prefix for nested rows: the section's two-cell tool-column
+ * indent, then a dim vertical rule per nesting level to contain a
+ * subagent's output beneath its header — the `※` mark alone carries the
+ * section's orange.
*/
function nestingPrefix(depth: number, theme: Theme): string {
if (depth <= 0) return "";
- const rule = `${theme.colors.orange(theme.glyph.rule)} `;
- return rule.repeat(depth);
+ const rule = `${theme.colors.dim(theme.glyph.rule)} `;
+ return `${TOOL_COLUMN_LEAD}${rule.repeat(depth)}`;
+}
+
+/** The nesting prefix with its innermost rule swapped for the closing `└`. */
+function closingPrefix(depth: number, theme: Theme): string {
+ const rule = `${theme.colors.dim(theme.glyph.rule)} `;
+ return `${TOOL_COLUMN_LEAD}${rule.repeat(depth - 1)}${theme.colors.dim(theme.glyph.corner)} `;
}
function renderBody(
- block: Block,
+ block: DisplayBlock,
width: number,
theme: Theme,
context: RenderBlockContext,
): string[] {
+ // The subagent stand-in row, indented one cell so it aligns with the
+ // tool marks beside it; other kinds (a coalesced log run) render their
+ // elided count inside their own section.
+ if (block.elided !== undefined && block.kind === "subagent-step") {
+ return [` ${elisionText(block.elided, theme)}`];
+ }
switch (block.kind) {
case "user":
return renderUser(block, width, theme);
@@ -158,11 +237,24 @@ function renderBody(
case "sandbox":
return renderSandbox(block, width, theme, context);
case "log":
- return renderLog(block, width, theme, context);
+ return renderLog(block, width, theme);
case "subagent":
return renderSubagentHeader(block, width, theme);
+ case "subagent-close": {
+ // Closes the section's rail. A completed section's corner carries
+ // the collapsed activity footnote instead of railed children.
+ const corner = `${TOOL_COLUMN_LEAD}${theme.colors.dim(theme.glyph.corner)}`;
+ if (block.body !== undefined && block.body.length > 0) {
+ return [clipVisible(`${corner} ${theme.colors.dim(block.body)}`, Math.max(1, width))];
+ }
+ return [corner];
+ }
+ case "turn-stats":
+ return renderTurnStats(block, width, theme);
+ case "session-boundary":
+ case "todo-list":
case "agent-header":
- // Rows arrive fully styled and width-fit from `buildAgentHeader`.
+ // Rows arrive fully styled and width-fit from their builders.
return (block.body ?? "").split("\n");
}
}
@@ -176,7 +268,20 @@ function renderUser(block: Block, width: number, theme: Theme): string[] {
function renderProse(block: Block, width: number, theme: Theme): string[] {
const rows: string[] = [];
const isSubagent = block.kind === "subagent-step";
- const glyph = isSubagent ? "" : `${theme.colors.bold(theme.colors.white(theme.glyph.brand))} `;
+ // A collapsed child message is one activity row in its section — the
+ // parent's own `▲` reply carries the conclusion. `--subagents full`
+ // restores the verbatim prose.
+ if (isSubagent && block.collapsed === true) {
+ const line =
+ firstNonEmptyLine(block.body) ??
+ (block.reasoning === undefined ? undefined : firstNonEmptyLine(block.reasoning));
+ if (line === undefined) return [];
+ return [theme.colors.dim(sliceVisible(line, Math.max(1, width)))];
+ }
+ // Bold at the terminal's DEFAULT foreground: black on a light theme,
+ // white on a dark one. Explicit bright-white (SGR 97) would vanish on
+ // light backgrounds.
+ const glyph = isSubagent ? "" : `${theme.colors.bold(theme.glyph.brand)} `;
const indent = isSubagent ? "" : " ";
if (block.reasoning && block.reasoning.trim().length > 0) {
@@ -189,7 +294,7 @@ function renderProse(block: Block, width: number, theme: Theme): string[] {
}
if (body.length > 0) {
- const rendered = renderMarkdown(body)
+ const rendered = renderMarkdown(body, width - indent.length)
.split("\n")
.flatMap((line) => wrapVisibleLine(line, width - indent.length));
rendered.forEach((line, index) => {
@@ -206,7 +311,11 @@ function renderProse(block: Block, width: number, theme: Theme): string[] {
function renderReasoning(block: Block, width: number, theme: Theme): string[] {
if (block.collapsed) {
- return [`${theme.colors.gray(theme.glyph.reasoning)} ${theme.colors.dim("thinking")}`];
+ // A persisted thought labels itself (`Thought for 12s`); a still-live
+ // collapse keeps the generic marker.
+ return [
+ `${theme.colors.gray(theme.glyph.reasoning)} ${theme.colors.dim(block.title ?? "thinking")}`,
+ ];
}
return renderReasoningLines(block.body ?? "", width, theme, theme.glyph.reasoning);
}
@@ -221,87 +330,6 @@ function renderReasoningLines(text: string, width: number, theme: Theme, glyph?:
});
}
-function renderTool(
- block: Block,
- width: number,
- theme: Theme,
- context: RenderBlockContext,
-): string[] {
- const { icon, accent } = toolGlyph(block.status ?? "running", theme, context);
- const name = block.title ?? "tool";
- const headerWidth = width - 2;
- const namePlain = truncatePlain(name, headerWidth);
- let header = `${icon} ${theme.colors.bold(namePlain)}`;
- const argsBudget = headerWidth - namePlain.length - 2;
- const args = block.subtitle ?? "";
- if (args.length > 0 && argsBudget >= 6) {
- header += ` ${theme.colors.gray(truncate(args, argsBudget))}`;
- }
-
- const rows = [header];
-
- if (block.expanded) {
- rows.push(...renderToolExpanded(block, width, theme));
- } else if (block.status === "done" && block.result && block.result.length > 0) {
- rows.push(resultLine(theme.glyph.arrow, block.result, width, theme, accent));
- } else if (block.status === "error" && block.result) {
- rows.push(resultLine(theme.glyph.arrow, block.result, width, theme, theme.colors.red));
- } else if (block.status === "denied") {
- rows.push(resultLine(theme.glyph.arrow, "denied", width, theme, theme.colors.yellow));
- }
-
- return rows;
-}
-
-function renderToolExpanded(block: Block, width: number, theme: Theme): string[] {
- const rows: string[] = [];
- const push = (label: string, value: unknown, color: (text: string) => string) => {
- if (value === undefined) return;
- rows.push(` ${theme.colors.dim(label)}`);
- for (const line of wrap(formatValuePretty(value), width - 4)) {
- rows.push(` ${color(line)}`);
- }
- };
- push("input", block.toolInput, theme.colors.gray);
- if (block.status === "error" && block.result) {
- push("error", block.result, theme.colors.red);
- } else {
- push("output", block.toolOutput, theme.colors.gray);
- }
- return rows;
-}
-
-function resultLine(
- marker: string,
- text: string,
- width: number,
- theme: Theme,
- color: (text: string) => string,
-): string {
- const budget = width - 4;
- return ` ${theme.colors.dim(marker)} ${color(truncate(text, budget))}`;
-}
-
-function toolGlyph(
- status: ToolStatus,
- theme: Theme,
- context: RenderBlockContext,
-): { icon: string; accent: (text: string) => string } {
- switch (status) {
- case "done":
- return { icon: theme.colors.green(theme.glyph.success), accent: theme.colors.gray };
- case "error":
- return { icon: theme.colors.red(theme.glyph.error), accent: theme.colors.red };
- case "denied":
- return { icon: theme.colors.yellow(theme.glyph.warning), accent: theme.colors.yellow };
- case "approval":
- return { icon: theme.colors.yellow(theme.glyph.question), accent: theme.colors.yellow };
- case "running":
- default:
- return { icon: theme.colors.yellow(context.spinner), accent: theme.colors.gray };
- }
-}
-
/**
* Diagnostic dumps below an error headline are capped to this many physical
* lines — enough for the error class plus the top of the stack, without a
@@ -395,8 +423,9 @@ function paintCommands(line: string, theme: Theme): string {
/**
* A slash command invocation under the user gutter. Automatic commands use
- * the same row so their result can follow it. The `❯` glyph remains exclusive
- * to live input because the TUI tests use it to detect a ready prompt.
+ * the same row so their result can follow it. The `❯`/`›` glyphs remain
+ * exclusive to live input because the TUI tests use `›` (the empty prompt's
+ * quiet mark) to detect a ready prompt.
*/
function renderCommand(block: Block, theme: Theme): string[] {
const c = theme.colors;
@@ -428,7 +457,7 @@ function renderFlow(block: Block, width: number, theme: Theme): string[] {
/**
* One command's outcome, hung under its invocation with the elbow connector
* (` ⎿ Login interrupted` in Claude Code's grammar), indented so the body
- * nests under the echoed command's text rather than its `▌` marker.
+ * nests under the echoed command's text rather than its `│` marker.
*/
function renderResult(block: Block, width: number, theme: Theme): string[] {
const marker = theme.colors.dim(theme.glyph.elbow);
@@ -449,6 +478,9 @@ function renderPreformatted(block: Block, width: number, theme: Theme): string[]
block.kind === "connection-auth"
? theme.colors.yellow(theme.glyph.connection)
: theme.colors.yellow(theme.colors.bold(theme.glyph.question));
+ // A question's `⎿` answer row hangs one cell past the prompt text so the
+ // elbow reads as nested under it.
+ const bodyIndent = block.kind === "question" ? " " : " ";
// The title is agent-authored prose (a question prompt, a connection name)
// and can exceed the width; an overflowing row soft-wraps in the terminal
// and breaks the live region's one-row-one-line accounting, leaking a
@@ -461,8 +493,8 @@ function renderPreformatted(block: Block, width: number, theme: Theme): string[]
index === 0 ? `${glyph} ${theme.colors.bold(line)}` : ` ${theme.colors.bold(line)}`,
);
for (const raw of (block.body ?? "").split("\n")) {
- for (const line of wrapVisibleLine(raw, width - 2)) {
- rows.push(` ${line}`);
+ for (const line of wrapVisibleLine(raw, Math.max(1, width - bodyIndent.length))) {
+ rows.push(`${bodyIndent}${line}`);
}
}
return rows;
@@ -493,49 +525,73 @@ function renderSandbox(
}
/**
- * Renders one captured server-output write. The source label (`stdout ·` /
- * `stderr ·`) appears on the first row; every following line — wrapped
- * continuations included — hangs indented beneath it. When the block
- * directly continues a same-source log block (`context.previous`), the label
- * is suppressed entirely so consecutive writes read as one run, while each
- * write remains its own immediately-committed block (no unbounded live
- * state). A rendered block is never truncated: a transcript can't be clicked
- * open, so the full output is shown, kept legible by the `│` rule and the
- * hanging indent. Whether a source renders at all is the renderer's
- * `LogDisplayMode` filter — this function only ever sees visible blocks.
+ * Renders captured server output: a `○ stderr` (or `○ stdout`) header with
+ * body lines — wrapped continuations included — behind a `│` rail. The rail
+ * stays open (no closing corner): a process stream is continuous, and the
+ * next write may extend it. A lone write shows its full body; a coalesced
+ * run (contiguous writes merged by the display grouping) arrives
+ * pre-windowed to its newest lines with the older count on `elided`,
+ * rendered as an `… (N more)` row under the header. Whether a source
+ * renders at all is the renderer's `LogDisplayMode` filter — this function
+ * only ever sees visible blocks.
*/
-function renderLog(
- block: Block,
- width: number,
- theme: Theme,
- context: RenderBlockContext,
-): string[] {
+function renderLog(block: DisplayBlock, width: number, theme: Theme): string[] {
const isErr = block.title === "stderr";
const color = isErr ? theme.colors.red : theme.colors.gray;
const rule = theme.colors.dim(theme.glyph.rule);
const source = isErr ? "stderr" : "stdout";
- const label = theme.colors.dim(`${source} ${theme.glyph.dot} `);
- const labelWidth = visibleLength(label);
- const labelIndent = " ".repeat(labelWidth);
- const continuesRun = context.previous?.kind === "log" && context.previous.title === block.title;
- const logical = (block.body ?? "").split("\n");
- const rows: string[] = [];
- for (const raw of logical) {
- const wrapped = wrapVisibleLine(raw, Math.max(1, width - 2 - labelWidth));
- for (const line of wrapped) {
- const prefix = rows.length === 0 && !continuesRun ? label : labelIndent;
- rows.push(`${rule} ${prefix}${theme.colors.dim(color(line))}`);
+ const rows = [`${theme.colors.dim(theme.glyph.reasoning)} ${theme.colors.dim(source)}`];
+ if (block.elided !== undefined && block.elided > 0) {
+ rows.push(`${rule} ${elisionText(block.elided, theme)}`);
+ }
+ for (const raw of (block.body ?? "").split("\n")) {
+ for (const line of wrapVisibleLine(raw, Math.max(1, width - 2))) {
+ rows.push(`${rule} ${theme.colors.dim(color(line))}`);
}
}
- return rows.length > 0 ? rows : [`${rule}`];
+ return rows;
+}
+
+/**
+ * The end-of-turn coda: `└ Done in 3min 24s ── ↑ 32.4K ↓ 682`, dim,
+ * closing the turn under the assistant's final prose. The corner is the
+ * settled form of the live `▪ Working… <duration> ── <flow>` turn bar; the
+ * body arrives fully composed from the renderer's shared stats builder.
+ */
+function renderTurnStats(block: Block, width: number, theme: Theme): string[] {
+ const line = `${theme.glyph.corner} ${block.body ?? ""}`;
+ return [theme.colors.dim(truncatePlain(line, Math.max(1, width)))];
}
function renderSubagentHeader(block: Block, width: number, theme: Theme): string[] {
- const name = truncatePlain(block.title ?? "subagent", Math.max(8, width - 14));
- return [
- `${theme.colors.orange(theme.glyph.subagent)} ${theme.colors.bold(name)} ${theme.colors.dim("subagent")}`,
- ];
+ // `subagent(<name>)`; the generic self-delegation tool (literally named
+ // `agent`) reads as `subagent(self)`. Only the `※` mark carries orange —
+ // lead, rails, and name stay quiet around it.
+ const isSelf = block.title === undefined || block.title === "agent";
+ const rawName = isSelf ? "self" : block.title!;
+ const name = truncatePlain(rawName, Math.max(8, width - 16));
+ const lead = TOOL_COLUMN_LEAD;
+ // The ordinal rides inside the parens (`subagent(self:4)`) in every
+ // state. Completion reports on the closing corner (`└ Done…`); the
+ // header only flips its mark from working orange to done green.
+ const isOrdinal = block.subtitle !== undefined && block.subtitle.startsWith("#");
+ const ordinal = isOrdinal ? `:${block.subtitle!.slice(1)}` : "";
+ const mark =
+ block.status === "done"
+ ? theme.colors.green(theme.glyph.subagent)
+ : theme.colors.orange(theme.glyph.subagent);
+ let header = `${lead}${mark} ${theme.colors.bold(`subagent(${name}${ordinal})`)}`;
+ if (!isOrdinal && block.subtitle !== undefined && block.subtitle.length > 0) {
+ header += ` ${theme.colors.dim(block.subtitle)}`;
+ }
+ return [header];
+}
+
+function firstNonEmptyLine(text: string | undefined): string | undefined {
+ if (text === undefined) return undefined;
+ const line = text.split(/\r?\n/u).find((candidate) => candidate.trim().length > 0);
+ return line?.trim();
}
function wrap(text: string, width: number): string[] {
diff --git a/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts b/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts
index 12bc45687..a90263d82 100644
--- a/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts
+++ b/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts
@@ -18,6 +18,7 @@ describe("presentDiagnostic", () => {
".eve/logs/dev.log",
);
+ // The first line already names the error; stack frames add no headline.
expect(presentation).toEqual({
kind: "stored",
summary: "Error: request failed",
@@ -28,4 +29,56 @@ describe("presentDiagnostic", () => {
expect(formatStoredDiagnostic(presentation)).toContain("details: .eve/logs/dev.log");
}
});
+
+ it("surfaces the error headline of a collapsed logger dump", () => {
+ const presentation = presentDiagnostic(
+ [
+ "[eve:harness.tool-loop] tool execution failed {",
+ " toolName: 'get_weather',",
+ " toolCallId: 'c1',",
+ " error: {",
+ " errorId: 'ab12',",
+ " message: 'fetch failed',",
+ " name: 'TypeError',",
+ " detail: 'TypeError: fetch failed'",
+ " }",
+ "}",
+ ].join("\n"),
+ ".eve/logs/dev.log",
+ );
+
+ expect(presentation).toMatchObject({
+ kind: "stored",
+ summary: "[eve:harness.tool-loop] tool execution failed {",
+ headline: "message: 'fetch failed',",
+ omittedLines: 8,
+ });
+ if (presentation.kind === "stored") {
+ expect(formatStoredDiagnostic(presentation)).toBe(
+ [
+ "[eve:harness.tool-loop] tool execution failed {",
+ "message: 'fetch failed',",
+ "… 8 diagnostic lines · details: .eve/logs/dev.log",
+ ].join("\n"),
+ );
+ }
+ });
+
+ it("surfaces a stack headline buried under prose", () => {
+ const presentation = presentDiagnostic(
+ [
+ "worker crashed while processing the queue",
+ "",
+ "RangeError: Maximum call stack size exceeded",
+ " at recurse (worker.ts:10)",
+ " at recurse (worker.ts:10)",
+ ].join("\n"),
+ ".eve/logs/dev.log",
+ );
+
+ expect(presentation).toMatchObject({
+ summary: "worker crashed while processing the queue",
+ headline: "RangeError: Maximum call stack size exceeded",
+ });
+ });
});
diff --git a/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts b/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts
index 1bb9900c4..19f4775b0 100644
--- a/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts
+++ b/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts
@@ -2,11 +2,20 @@ const INLINE_DIAGNOSTIC_MAX_LINES = 4;
const INLINE_DIAGNOSTIC_MAX_CHARACTERS = 600;
const DIAGNOSTIC_SUMMARY_MAX_CHARACTERS = 240;
+/**
+ * A line that names the failure inside a collapsed dump: the pinned
+ * `message:` / `name:` fields of a `formatError` object dump, or the
+ * `SomeError: …` headline of a raw stack trace.
+ */
+const ERROR_HEADLINE_PATTERN = /^\s*(?:message|name):\s*\S|^\s*[A-Z][\w$]*Error\b/u;
+
export type DiagnosticPresentation =
| { readonly kind: "inline"; readonly text: string }
| {
readonly kind: "stored";
readonly summary: string;
+ /** First error-naming line of the collapsed body, when one exists. */
+ readonly headline?: string;
readonly omittedLines: number;
readonly path: string;
};
@@ -21,17 +30,21 @@ export function presentDiagnostic(text: string, path: string): DiagnosticPresent
return { kind: "inline", text };
}
- const first = lines.find((line) => line.trim().length > 0)?.trim() ?? "Diagnostic output";
- const summary =
- first.length <= DIAGNOSTIC_SUMMARY_MAX_CHARACTERS
- ? first
- : `${first.slice(0, DIAGNOSTIC_SUMMARY_MAX_CHARACTERS - 1)}…`;
- return {
+ const firstIndex = lines.findIndex((line) => line.trim().length > 0);
+ const first = firstIndex === -1 ? "Diagnostic output" : lines[firstIndex]!.trim();
+ const headline = lines
+ .slice(firstIndex + 1)
+ .find((line) => ERROR_HEADLINE_PATTERN.test(line))
+ ?.trim();
+
+ const shown = 1 + (headline === undefined ? 0 : 1);
+ const presentation: DiagnosticPresentation = {
kind: "stored",
- summary,
- omittedLines: Math.max(0, lines.length - 1),
+ summary: clip(first),
+ omittedLines: Math.max(0, lines.length - shown),
path,
};
+ return headline === undefined ? presentation : { ...presentation, headline: clip(headline) };
}
export function formatStoredDiagnostic(
@@ -40,5 +53,14 @@ export function formatStoredDiagnostic(
const count = presentation.omittedLines;
const omitted =
count === 0 ? "diagnostic details" : `${count} diagnostic line${count === 1 ? "" : "s"}`;
- return `${presentation.summary}\n… ${omitted} · details: ${presentation.path}`;
+ const rows = [presentation.summary];
+ if (presentation.headline !== undefined) rows.push(presentation.headline);
+ rows.push(`… ${omitted} · details: ${presentation.path}`);
+ return rows.join("\n");
+}
+
+function clip(line: string): string {
+ return line.length <= DIAGNOSTIC_SUMMARY_MAX_CHARACTERS
+ ? line
+ : `${line.slice(0, DIAGNOSTIC_SUMMARY_MAX_CHARACTERS - 1)}…`;
}
diff --git a/packages/eve/src/cli/dev/tui/file-content-cache.test.ts b/packages/eve/src/cli/dev/tui/file-content-cache.test.ts
new file mode 100644
index 000000000..90ef3c2eb
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/file-content-cache.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import { FileContentCache } from "./file-content-cache.js";
+
+describe("FileContentCache", () => {
+ it("returns what a write replaced, fed by an earlier write", () => {
+ const cache = new FileContentCache();
+
+ expect(cache.observeWrite({ path: "/w/a.txt", content: "one", callId: "c1" })).toBeUndefined();
+ expect(cache.observeWrite({ path: "/w/a.txt", content: "two", callId: "c2" })).toBe("one");
+ });
+
+ it("keeps the same previous content across re-observations of one call", () => {
+ const cache = new FileContentCache();
+ cache.observeWrite({ path: "/w/a.txt", content: "one", callId: "c1" });
+
+ // The tool block re-renders on the call's result event; the write must
+ // not diff against itself.
+ expect(cache.observeWrite({ path: "/w/a.txt", content: "two", callId: "c2" })).toBe("one");
+ expect(cache.observeWrite({ path: "/w/a.txt", content: "two", callId: "c2" })).toBe("one");
+ });
+
+ it("reconstructs a full read result into exact file content", () => {
+ const cache = new FileContentCache();
+ cache.observeRead({
+ content: "1: alpha\n2: beta",
+ path: "/w/read.txt",
+ totalLines: 2,
+ truncated: false,
+ });
+
+ expect(cache.observeWrite({ path: "/w/read.txt", content: "alpha\ngamma", callId: "c1" })).toBe(
+ "alpha\nbeta",
+ );
+ });
+
+ it("ignores truncated and windowed reads", () => {
+ const cache = new FileContentCache();
+ cache.observeRead({
+ content: "1: alpha",
+ path: "/w/read.txt",
+ totalLines: 5,
+ truncated: true,
+ });
+ cache.observeRead({
+ content: "3: gamma\n4: delta",
+ path: "/w/read.txt",
+ totalLines: 4,
+ truncated: false,
+ });
+
+ expect(
+ cache.observeWrite({ path: "/w/read.txt", content: "next", callId: "c1" }),
+ ).toBeUndefined();
+ });
+
+ it("ignores outputs that are not read-file results", () => {
+ const cache = new FileContentCache();
+ cache.observeRead({ existed: true, path: "/w/a.txt" });
+ cache.observeRead(undefined);
+ cache.observeRead("plain text");
+
+ expect(cache.observeWrite({ path: "/w/a.txt", content: "x", callId: "c1" })).toBeUndefined();
+ });
+
+ it("handles an empty file read", () => {
+ const cache = new FileContentCache();
+ cache.observeRead({ content: "", path: "/w/empty.txt", totalLines: 0, truncated: false });
+
+ expect(cache.observeWrite({ path: "/w/empty.txt", content: "filled", callId: "c1" })).toBe("");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/file-content-cache.ts b/packages/eve/src/cli/dev/tui/file-content-cache.ts
new file mode 100644
index 000000000..9643ebec3
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/file-content-cache.ts
@@ -0,0 +1,97 @@
+/**
+ * Session-local knowledge of file contents, so the write block can show a
+ * real diff without any protocol addition. Two feeds keep it current: every
+ * `write_file` input is a full replacement (exact), and every full-file
+ * `read_file` result reconstructs to the file's exact lines. Files touched
+ * outside these two paths (e.g. by `bash`) are invisible here — a write over
+ * unknown prior content renders plain rather than pretending to be a diff.
+ */
+
+/** Contents past this size are not cached or diffed. */
+const MAX_CACHED_CONTENT_CHARS = 200_000;
+
+interface FileSnapshot {
+ content: string;
+ /** What `content` replaced, kept while `writerCallId`'s call re-renders. */
+ previous?: string;
+ writerCallId?: string;
+}
+
+export class FileContentCache {
+ readonly #byPath = new Map<string, FileSnapshot>();
+
+ /**
+ * Records one write and returns the content it replaced. Tool blocks
+ * re-render on every lifecycle event of the same call, so a repeated
+ * observation of `callId` keeps returning the original previous content
+ * instead of diffing the write against itself.
+ */
+ observeWrite(input: { path: string; content: string; callId: string }): string | undefined {
+ const entry = this.#byPath.get(input.path);
+ if (entry?.writerCallId === input.callId) return entry.previous;
+
+ if (input.content.length > MAX_CACHED_CONTENT_CHARS) {
+ this.#byPath.delete(input.path);
+ return undefined;
+ }
+
+ const previous = entry?.content;
+ const snapshot: FileSnapshot = { content: input.content, writerCallId: input.callId };
+ if (previous !== undefined) snapshot.previous = previous;
+ this.#byPath.set(input.path, snapshot);
+ return previous;
+ }
+
+ /**
+ * Forgets everything. A new conversation runs against a fresh session —
+ * possibly a fresh sandbox — so stale bases would produce confidently
+ * wrong diffs.
+ */
+ clear(): void {
+ this.#byPath.clear();
+ }
+
+ /**
+ * Records a read result when it provably covers the whole file: not
+ * truncated, starting at line 1, with exactly `totalLines` numbered lines.
+ * Partial or truncated reads are ignored — caching them would produce
+ * confidently wrong diffs later.
+ */
+ observeRead(output: unknown): void {
+ const result = readFileResultShape(output);
+ if (result === undefined || result.truncated) return;
+ if (result.content.length > MAX_CACHED_CONTENT_CHARS) return;
+
+ const lines = reconstructNumberedLines(result.content);
+ if (lines === undefined || lines.length !== result.totalLines) return;
+
+ this.#byPath.set(result.path, { content: lines.join("\n") });
+ }
+}
+
+/** Duck-types the shared read-file result, whatever the tool was named. */
+function readFileResultShape(
+ output: unknown,
+): { content: string; path: string; totalLines: number; truncated: boolean } | undefined {
+ if (output === null || typeof output !== "object" || Array.isArray(output)) return undefined;
+ const record = output as Record<string, unknown>;
+ const { content, path, totalLines, truncated } = record;
+ if (typeof content !== "string" || typeof path !== "string") return undefined;
+ if (typeof totalLines !== "number" || typeof truncated !== "boolean") return undefined;
+ return { content, path, totalLines, truncated };
+}
+
+/**
+ * Strips the `N: ` prefixes of a read result. Returns `undefined` unless the
+ * numbering is contiguous from 1 — anything else means a windowed read.
+ */
+function reconstructNumberedLines(content: string): string[] | undefined {
+ if (content === "") return [];
+ const lines: string[] = [];
+ for (const [index, raw] of content.split("\n").entries()) {
+ const match = /^(\d+): (.*)$/su.exec(raw);
+ if (match === null || Number(match[1]) !== index + 1) return undefined;
+ lines.push(match[2]!);
+ }
+ return lines;
+}
diff --git a/packages/eve/src/cli/dev/tui/line-diff.test.ts b/packages/eve/src/cli/dev/tui/line-diff.test.ts
new file mode 100644
index 000000000..18df933e4
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/line-diff.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import { diffWriteDetail } from "./line-diff.js";
+
+describe("diffWriteDetail", () => {
+ it("marks every line added for a file that did not exist", () => {
+ expect(diffWriteDetail(undefined, "knicks\n", false)).toEqual([
+ { text: "knicks", kind: "added" },
+ ]);
+ });
+
+ it("renders plain content when prior state is unknown", () => {
+ expect(diffWriteDetail(undefined, "a\nb")).toEqual([{ text: "a" }, { text: "b" }]);
+ });
+
+ it("diffs an overwrite into context, removed, and added rows", () => {
+ const previous = ["{", ' "dev": "eve dev",', ' "zod": "^5.6.0"', "}"].join("\n");
+ const next = ["{", ' "dev": "eve dev",', ' "zod": "catalog:"', "}"].join("\n");
+
+ expect(diffWriteDetail(previous, next)).toEqual([
+ { text: "{" },
+ { text: ' "dev": "eve dev",' },
+ { text: ' "zod": "^5.6.0"', kind: "removed" },
+ { text: ' "zod": "catalog:"', kind: "added" },
+ { text: "}" },
+ ]);
+ });
+
+ it("collapses unchanged stretches beyond the hunk context into a gap", () => {
+ const unchanged = Array.from({ length: 10 }, (_, index) => `line ${index + 1}`);
+ const previous = [...unchanged, "old tail"].join("\n");
+ const next = [...unchanged, "new tail"].join("\n");
+
+ const detail = diffWriteDetail(previous, next);
+ expect(detail[0]).toEqual({ text: "", kind: "gap" });
+ expect(detail.slice(1)).toEqual([
+ { text: "line 9" },
+ { text: "line 10" },
+ { text: "old tail", kind: "removed" },
+ { text: "new tail", kind: "added" },
+ ]);
+ });
+
+ it("windows identical content down to nothing", () => {
+ expect(diffWriteDetail("same\n", "same\n")).toEqual([]);
+ });
+
+ it("does not turn a trailing newline into a phantom change", () => {
+ expect(diffWriteDetail("a\nb", "a\nb\n")).toEqual([]);
+ });
+
+ it("drops trailing blank lines from the rail entirely", () => {
+ expect(diffWriteDetail(undefined, "one\ntwo\n\n\n", false)).toEqual([
+ { text: "one", kind: "added" },
+ { text: "two", kind: "added" },
+ ]);
+ });
+
+ it("falls back to plain content when the diff would be too large", () => {
+ const previous = Array.from({ length: 600 }, (_, index) => `p${index}`).join("\n");
+ const next = Array.from({ length: 600 }, (_, index) => `n${index}`).join("\n");
+
+ const detail = diffWriteDetail(previous, next);
+ expect(detail).toHaveLength(600);
+ expect(detail.every((line) => line.kind === undefined)).toBe(true);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/line-diff.ts b/packages/eve/src/cli/dev/tui/line-diff.ts
new file mode 100644
index 000000000..b04db5363
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/line-diff.ts
@@ -0,0 +1,129 @@
+/**
+ * Pure line diffing for the write block's rail. The TUI computes diffs
+ * client-side from content it has already seen (write inputs, full-file read
+ * results) — putting prior content into the tool's output would feed it
+ * straight back into model context, paying tokens for something only the
+ * terminal needs.
+ */
+
+/** One rail row under a tool header. `kind` is unset for plain/context text. */
+export interface ToolDetailLine {
+ readonly text: string;
+ readonly kind?: "added" | "removed" | "gap";
+}
+
+/** Unchanged lines kept around each hunk so a change reads in place. */
+const HUNK_CONTEXT_LINES = 2;
+
+/**
+ * The LCS table is quadratic; past this many cells the diff is abandoned and
+ * the caller falls back to plain content.
+ */
+const MAX_DIFF_CELLS = 250_000;
+
+/**
+ * Builds the write rail for `content` against what it replaced.
+ *
+ * - `previous` known → a windowed line diff (changes with two context lines,
+ * unchanged stretches collapsed behind `gap` rows); identical content
+ * yields no rows.
+ * - `previous` unknown but the file provably did not exist → every line is
+ * an addition.
+ * - otherwise → plain content rows, because inventing `+` markers for an
+ * overwrite would misread as "everything changed".
+ */
+export function diffWriteDetail(
+ previous: string | undefined,
+ content: string,
+ existed?: boolean,
+): ToolDetailLine[] {
+ const nextLines = splitContentLines(content);
+ if (previous === undefined) {
+ if (existed === false) {
+ return nextLines.map((text) => ({ text, kind: "added" }));
+ }
+ return nextLines.map((text) => ({ text }));
+ }
+
+ const previousLines = splitContentLines(previous);
+ if ((previousLines.length + 1) * (nextLines.length + 1) > MAX_DIFF_CELLS) {
+ return nextLines.map((text) => ({ text }));
+ }
+
+ return windowHunks(lcsDiff(previousLines, nextLines));
+}
+
+/**
+ * Trailing newlines and blank lines are not rail rows: the region shows what
+ * the file says, and empty tail rows only push the corner away from it.
+ */
+function splitContentLines(content: string): string[] {
+ const lines = content.split(/\r?\n/u);
+ while (lines.length > 0 && lines.at(-1)?.trim() === "") lines.pop();
+ return lines;
+}
+
+/** Classic LCS backtrack producing removed-before-added hunks. */
+function lcsDiff(a: readonly string[], b: readonly string[]): ToolDetailLine[] {
+ const width = b.length + 1;
+ const table = new Uint32Array((a.length + 1) * width);
+ for (let i = a.length - 1; i >= 0; i -= 1) {
+ for (let j = b.length - 1; j >= 0; j -= 1) {
+ table[i * width + j] =
+ a[i] === b[j]
+ ? table[(i + 1) * width + j + 1]! + 1
+ : Math.max(table[(i + 1) * width + j]!, table[i * width + j + 1]!);
+ }
+ }
+
+ const lines: ToolDetailLine[] = [];
+ let i = 0;
+ let j = 0;
+ while (i < a.length && j < b.length) {
+ if (a[i] === b[j]) {
+ lines.push({ text: a[i]! });
+ i += 1;
+ j += 1;
+ } else if (table[(i + 1) * width + j]! >= table[i * width + j + 1]!) {
+ lines.push({ text: a[i]!, kind: "removed" });
+ i += 1;
+ } else {
+ lines.push({ text: b[j]!, kind: "added" });
+ j += 1;
+ }
+ }
+ for (; i < a.length; i += 1) lines.push({ text: a[i]!, kind: "removed" });
+ for (; j < b.length; j += 1) lines.push({ text: b[j]!, kind: "added" });
+ return lines;
+}
+
+/**
+ * Keeps each change with {@link HUNK_CONTEXT_LINES} unchanged lines around
+ * it and collapses longer unchanged stretches into one `gap` row. A diff
+ * with no changes windows down to nothing.
+ */
+function windowHunks(lines: readonly ToolDetailLine[]): ToolDetailLine[] {
+ const changed = lines.map((line) => line.kind === "added" || line.kind === "removed");
+ if (!changed.includes(true)) return [];
+
+ const keep = lines.map((_, index) => {
+ for (
+ let probe = Math.max(0, index - HUNK_CONTEXT_LINES);
+ probe <= Math.min(lines.length - 1, index + HUNK_CONTEXT_LINES);
+ probe += 1
+ ) {
+ if (changed[probe]) return true;
+ }
+ return false;
+ });
+
+ const windowed: ToolDetailLine[] = [];
+ for (const [index, line] of lines.entries()) {
+ if (keep[index]) {
+ windowed.push(line);
+ } else if (windowed.at(-1)?.kind !== "gap") {
+ windowed.push({ text: "", kind: "gap" });
+ }
+ }
+ return windowed;
+}
diff --git a/packages/eve/src/cli/dev/tui/markdown.test.ts b/packages/eve/src/cli/dev/tui/markdown.test.ts
index 933f51aa3..939a2a58e 100644
--- a/packages/eve/src/cli/dev/tui/markdown.test.ts
+++ b/packages/eve/src/cli/dev/tui/markdown.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { renderMarkdown } from "./markdown.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
describe("renderMarkdown", () => {
it("preserves underscores inside URLs", () => {
@@ -27,4 +28,27 @@ describe("renderMarkdown", () => {
const rendered = renderMarkdown("see _https://example.com/a_b_ now");
expect(rendered).toContain("https://example.com/a_b");
});
+
+ it("renders fenced code, task lists, links, and strikethrough semantically", () => {
+ const rendered = renderMarkdown(
+ "- [x] Read [the docs](https://example.com)\n\n~~~ts\nconst ok = true;\n~~~\n\n~~old~~",
+ );
+
+ expect(rendered).toContain("• ☑ Read the docs (\x1b[36mhttps://example.com\x1b[39m)");
+ expect(rendered).toContain(" \x1b[2mts\x1b[22m");
+ expect(rendered).toContain("\x1b[2m│\x1b[22m \x1b[36mconst ok = true;\x1b[39m");
+ expect(rendered).toContain("\x1b[9mold\x1b[29m");
+ });
+
+ it("fits wide tables to the available terminal width", () => {
+ const rendered = renderMarkdown(
+ "| Name | Description |\n| --- | --- |\n| alpha | a very long description |",
+ 24,
+ );
+
+ for (const line of rendered.split("\n")) {
+ expect(stripAnsi(line).length).toBeLessThanOrEqual(24);
+ }
+ expect(rendered).toContain("…");
+ });
});
diff --git a/packages/eve/src/cli/dev/tui/markdown.ts b/packages/eve/src/cli/dev/tui/markdown.ts
index 19bf6849a..596a1a7b8 100644
--- a/packages/eve/src/cli/dev/tui/markdown.ts
+++ b/packages/eve/src/cli/dev/tui/markdown.ts
@@ -1,227 +1,234 @@
-import { visibleLength } from "#cli/ui/terminal-text.js";
+import { lexer, type TableCell, type Token } from "#compiled/marked/index.js";
+
+import { sliceVisible, visibleLength } from "#cli/ui/terminal-text.js";
type TableAlignment = "left" | "center" | "right";
const ansi = {
bold: "\x1b[1m",
boldOff: "\x1b[22m",
+ cyan: "\x1b[36m",
+ cyanOff: "\x1b[39m",
+ dim: "\x1b[2m",
+ dimOff: "\x1b[22m",
italic: "\x1b[3m",
italicOff: "\x1b[23m",
+ strike: "\x1b[9m",
+ strikeOff: "\x1b[29m",
};
const tableSeparator = "─";
-export function renderMarkdown(input: string): string {
- const lines = input.split("\n");
- const output: string[] = [];
-
- for (let index = 0; index < lines.length; index += 1) {
- const table = parseTable(lines, index);
-
- if (table != null) {
- output.push(...renderTable(table));
- index = table.endIndex - 1;
- continue;
- }
-
- output.push(renderMarkdownLine(lines[index] ?? ""));
- }
-
- return output.join("\n");
+/** Renders parsed GFM blocks to terminal text, fitting tables to `width`. */
+export function renderMarkdown(input: string, width = Number.POSITIVE_INFINITY): string {
+ return trimTrailingBlankRows(renderBlocks(lexer(input), width)).join("\n");
}
-function renderMarkdownLine(line: string): string {
- if (line.startsWith("### ")) {
- return renderInlineMarkdown(`▶ ${line.slice(4)}`);
- }
-
- if (line.startsWith("## ")) {
- return renderInlineMarkdown(`■ ${line.slice(3)}`);
- }
-
- if (line.startsWith("# ")) {
- return renderInlineMarkdown(`█ ${line.slice(2)}`);
- }
-
- const unorderedListItem = line.match(/^(\s*)[-+*]\s+(.*)$/);
- if (unorderedListItem) {
- const [, indentation, text = ""] = unorderedListItem;
- return renderInlineMarkdown(`${indentation}•${text.length > 0 ? ` ${text}` : ""}`);
- }
-
- if (/^\d+\. /.test(line)) {
- return renderInlineMarkdown(line.replace(/^(\d+)\. /, "$1. "));
- }
-
- if (line.startsWith("> ")) {
- return renderInlineMarkdown(`│ ${line.slice(2)}`);
- }
-
- return renderInlineMarkdown(line);
-}
-
-function renderInlineMarkdown(input: string): string {
- // Shield URLs before applying emphasis so underscores/asterisks inside a
- // link (e.g. a Vercel Connect `sca_…` token or a hook callback path) are not
- // misread as markdown emphasis and silently stripped from the rendered URL.
- // Sentinels use Unicode Private Use Area characters, which never appear in
- // real input and are not control characters (avoids no-control-regex).
- const urls: string[] = [];
- const shielded = input.replaceAll(/https?:\/\/\S+/g, (match) => {
- const token = `\uE000${urls.length}\uE001`;
- urls.push(match);
- return token;
- });
-
- const styled = shielded
- .replaceAll(/`([^`]+)`/g, "$1")
- .replaceAll(/\*\*([^*\n]+)\*\*/g, `${ansi.bold}$1${ansi.boldOff}`)
- .replaceAll(/__([^_\n]+)__/g, `${ansi.bold}$1${ansi.boldOff}`)
- .replaceAll(/\*([^*\n]+)\*/g, `${ansi.italic}$1${ansi.italicOff}`)
- .replaceAll(/_([^_\n]+)_/g, `${ansi.italic}$1${ansi.italicOff}`);
-
- return styled.replaceAll(/\uE000(\d+)\uE001/g, (_match, index) => urls[Number(index)] ?? "");
-}
-
-type ParsedTable = {
- alignments: TableAlignment[];
- endIndex: number;
- header: string[];
- rows: string[][];
-};
-
-function parseTable(lines: string[], startIndex: number): ParsedTable | undefined {
- const header = parseTableCells(lines[startIndex] ?? "");
- if (header == null || header.length < 2) {
- return undefined;
- }
-
- const separatorCells = parseTableCells(lines[startIndex + 1] ?? "");
- if (separatorCells == null || separatorCells.length !== header.length) {
- return undefined;
- }
-
- const alignments = parseTableAlignments(separatorCells);
- if (alignments == null) {
- return undefined;
- }
-
- const rows: string[][] = [];
- let endIndex = startIndex + 2;
-
- while (endIndex < lines.length) {
- const row = parseTableCells(lines[endIndex] ?? "");
- if (row == null) {
- break;
+function renderBlocks(tokens: readonly Token[], width: number): string[] {
+ const rows: string[] = [];
+ for (const token of tokens) {
+ switch (token.type) {
+ case "space":
+ pushBlankRow(rows);
+ break;
+ case "heading": {
+ const glyph = token.depth === 1 ? "█" : token.depth === 2 ? "■" : "▶";
+ rows.push(`${glyph} ${ansi.bold}${renderInline(token.tokens)}${ansi.boldOff}`);
+ break;
+ }
+ case "paragraph":
+ case "text":
+ rows.push(...renderInline(token.tokens, token.text).split("\n"));
+ break;
+ case "code":
+ rows.push(...renderCodeBlock(token));
+ break;
+ case "blockquote":
+ rows.push(
+ ...renderBlocks(token.tokens ?? [], Math.max(8, width - 2)).map(
+ (row) => `${ansi.dim}│${ansi.dimOff} ${row}`,
+ ),
+ );
+ break;
+ case "list":
+ rows.push(...renderList(token, width));
+ break;
+ case "table":
+ rows.push(...renderTable(token, width));
+ break;
+ case "hr":
+ rows.push(ansi.dim + tableSeparator.repeat(horizontalRuleWidth(width)) + ansi.dimOff);
+ break;
+ case "html":
+ rows.push(...(token.text ?? token.raw ?? "").split("\n"));
+ break;
+ case "def":
+ break;
+ default:
+ if (token.tokens !== undefined) {
+ rows.push(...renderBlocks(token.tokens, width));
+ } else if (token.text !== undefined) {
+ rows.push(token.text);
+ }
+ break;
}
-
- rows.push(normalizeTableRow(row, header.length));
- endIndex += 1;
}
-
- return {
- alignments,
- endIndex,
- header,
- rows,
- };
+ return rows;
}
-function parseTableCells(line: string): string[] | undefined {
- if (!line.includes("|")) {
- return undefined;
- }
-
- let tableLine = line.trim();
- if (tableLine.startsWith("|")) {
- tableLine = tableLine.slice(1);
- }
- if (tableLine.endsWith("|") && !tableLine.endsWith("\\|")) {
- tableLine = tableLine.slice(0, -1);
+function renderCodeBlock(token: Token): string[] {
+ const rows: string[] = [];
+ if (token.lang?.trim()) rows.push(` ${ansi.dim}${token.lang.trim()}${ansi.dimOff}`);
+ const codeRows = (token.text ?? "").replace(/\n$/u, "").split("\n");
+ for (const row of codeRows) {
+ rows.push(`${ansi.dim}│${ansi.dimOff} ${ansi.cyan}${row}${ansi.cyanOff}`);
}
+ return rows;
+}
- const cells: string[] = [];
- let cell = "";
+function renderList(token: Token, width: number): string[] {
+ const rows: string[] = [];
+ let ordinal = typeof token.start === "number" ? token.start : 1;
+ for (const item of token.items ?? []) {
+ const marker = token.ordered ? `${ordinal}.` : "•";
+ const task = item.checked === true ? "☑ " : item.checked === false ? "☐ " : "";
+ const itemRows = renderBlocks(item.tokens ?? [], Math.max(8, width - marker.length - 1));
+ const nonemptyRows = itemRows.length === 0 ? [""] : itemRows;
+ nonemptyRows.forEach((row, index) => {
+ rows.push(index === 0 ? `${marker} ${task}${row}` : `${" ".repeat(marker.length + 1)}${row}`);
+ });
+ ordinal += 1;
+ }
+ return rows;
+}
- for (let index = 0; index < tableLine.length; index += 1) {
- const character = tableLine[index];
- const nextCharacter = tableLine[index + 1];
+function renderInline(tokens: readonly Token[] | undefined, fallback = ""): string {
+ if (tokens === undefined) return fallback;
+ return tokens.map(renderInlineToken).join("");
+}
- if (character === "\\" && nextCharacter === "|") {
- cell += "|";
- index += 1;
- continue;
+function renderInlineToken(token: Token): string {
+ switch (token.type) {
+ case "text":
+ return renderInline(token.tokens, token.text ?? "");
+ case "strong":
+ return `${ansi.bold}${renderInline(token.tokens, token.text)}${ansi.boldOff}`;
+ case "em":
+ return `${ansi.italic}${renderInline(token.tokens, token.text)}${ansi.italicOff}`;
+ case "del":
+ return `${ansi.strike}${renderInline(token.tokens, token.text)}${ansi.strikeOff}`;
+ case "codespan":
+ return `${ansi.cyan}${token.text ?? ""}${ansi.cyanOff}`;
+ case "link": {
+ const label = renderInline(token.tokens, token.text);
+ const href = token.href ?? "";
+ if (href.length === 0 || label === href) return `${ansi.cyan}${label}${ansi.cyanOff}`;
+ return `${label} (${ansi.cyan}${href}${ansi.cyanOff})`;
}
-
- if (character === "|") {
- cells.push(cell.trim());
- cell = "";
- continue;
+ case "image": {
+ const label = token.text?.trim() || "image";
+ const href = token.href ?? "";
+ return href.length === 0 ? `[${label}]` : `[${label}] (${ansi.cyan}${href}${ansi.cyanOff})`;
}
-
- cell += character;
+ case "br":
+ return "\n";
+ case "checkbox":
+ return token.checked ? "☑ " : "☐ ";
+ case "escape":
+ return token.text ?? "";
+ case "html":
+ return token.text ?? token.raw ?? "";
+ default:
+ return renderInline(token.tokens, token.text ?? token.raw ?? "");
}
-
- cells.push(cell.trim());
-
- return cells;
}
-function parseTableAlignments(cells: string[]): TableAlignment[] | undefined {
- const alignments: TableAlignment[] = [];
-
- for (const cell of cells) {
- const match = cell.match(/^(:)?-{3,}(:)?$/);
- if (match == null) {
- return undefined;
- }
+function renderTable(token: Token, width: number): string[] {
+ const header = token.header ?? [];
+ if (header.length === 0) return [];
+ const alignments = header.map((_, index) => normalizeAlignment(token.align?.[index]));
+ const renderedHeader = header.map(renderTableCell);
+ const renderedRows = (token.rows ?? []).map((row) =>
+ normalizeTableRow(row, header.length).map(renderTableCell),
+ );
+ const allRows = [renderedHeader, ...renderedRows];
+ const widths = alignments.map((_, column) =>
+ Math.max(3, ...allRows.map((row) => visibleLength(row[column] ?? ""))),
+ );
+ fitTableWidths(widths, width);
- const [, left, right] = match;
- alignments.push(left != null && right != null ? "center" : right != null ? "right" : "left");
- }
+ const boldHeader = renderedHeader.map((cell) => `${ansi.bold}${cell}${ansi.boldOff}`);
+ return [
+ formatTableRow(boldHeader, widths, alignments),
+ widths.map((columnWidth) => tableSeparator.repeat(columnWidth)).join(" "),
+ ...renderedRows.map((row) => formatTableRow(row, widths, alignments)),
+ ];
+}
- return alignments;
+function renderTableCell(cell: TableCell): string {
+ return renderInline(cell.tokens, cell.text).replaceAll("\n", " ");
}
-function normalizeTableRow(row: string[], length: number): string[] {
- return Array.from({ length }, (_, index) => row[index] ?? "");
+function normalizeTableRow(row: readonly TableCell[], length: number): TableCell[] {
+ return Array.from({ length }, (_, index) => row[index] ?? { text: "", tokens: [] });
}
-function renderTable(table: ParsedTable): string[] {
- const header = table.header.map(
- (cell) => `${ansi.bold}${renderInlineMarkdown(cell)}${ansi.boldOff}`,
- );
- const rows = table.rows.map((row) => row.map(renderInlineMarkdown));
- const tableRows = [header, ...rows];
- const widths = table.alignments.map((_, columnIndex) =>
- Math.max(3, ...tableRows.map((row) => visibleLength(row[columnIndex] ?? ""))),
- );
+function normalizeAlignment(value: "center" | "left" | "right" | null | undefined): TableAlignment {
+ return value ?? "left";
+}
- return [
- formatTableRow(header, widths, table.alignments),
- widths.map((width) => tableSeparator.repeat(width)).join(" "),
- ...rows.map((row) => formatTableRow(row, widths, table.alignments)),
- ];
+function fitTableWidths(widths: number[], width: number): void {
+ if (!Number.isFinite(width)) return;
+ const separators = Math.max(0, widths.length - 1) * 2;
+ const budget = Math.max(widths.length * 3, Math.floor(width) - separators);
+ while (widths.reduce((sum, value) => sum + value, 0) > budget) {
+ const widest = Math.max(...widths);
+ const index = widths.findIndex((value) => value === widest && value > 3);
+ if (index === -1) return;
+ widths[index] = widest - 1;
+ }
}
-function formatTableRow(row: string[], widths: number[], alignments: TableAlignment[]): string {
+function formatTableRow(
+ row: readonly string[],
+ widths: readonly number[],
+ alignments: readonly TableAlignment[],
+): string {
return row
- .map((cell, index) => alignTableCell(cell, widths[index] ?? 0, alignments[index] ?? "left"))
+ .map((cell, index) =>
+ alignTableCell(
+ fitTableCell(cell, widths[index] ?? 3),
+ widths[index] ?? 3,
+ alignments[index] ?? "left",
+ ),
+ )
.join(" ");
}
+function fitTableCell(cell: string, width: number): string {
+ if (visibleLength(cell) <= width) return cell;
+ return `${sliceVisible(cell, Math.max(1, width - 1))}…`;
+}
+
function alignTableCell(cell: string, width: number, alignment: TableAlignment): string {
const paddingWidth = Math.max(0, width - visibleLength(cell));
-
- if (alignment === "right") {
- return `${" ".repeat(paddingWidth)}${cell}`;
- }
-
+ if (alignment === "right") return `${" ".repeat(paddingWidth)}${cell}`;
if (alignment === "center") {
const leftPadding = Math.floor(paddingWidth / 2);
- const rightPadding = paddingWidth - leftPadding;
- return `${" ".repeat(leftPadding)}${cell}${" ".repeat(rightPadding)}`;
+ return `${" ".repeat(leftPadding)}${cell}${" ".repeat(paddingWidth - leftPadding)}`;
}
-
return `${cell}${" ".repeat(paddingWidth)}`;
}
+
+function horizontalRuleWidth(width: number): number {
+ return Number.isFinite(width) ? Math.max(3, Math.min(40, Math.floor(width))) : 40;
+}
+
+function pushBlankRow(rows: string[]): void {
+ if (rows.length > 0 && rows.at(-1) !== "") rows.push("");
+}
+
+function trimTrailingBlankRows(rows: string[]): string[] {
+ while (rows.at(-1) === "") rows.pop();
+ return rows;
+}
diff --git a/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts b/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts
new file mode 100644
index 000000000..ee4782a52
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ PROMPT_PLACEHOLDER_MESSAGES,
+ promptPlaceholder,
+ promptPlaceholderCycleMs,
+} from "./prompt-placeholder.js";
+
+describe("promptPlaceholder", () => {
+ it("holds each message for one cycle and rotates through the whole set", () => {
+ expect(promptPlaceholder(0)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ expect(promptPlaceholder(promptPlaceholderCycleMs - 1)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ expect(promptPlaceholder(promptPlaceholderCycleMs)).toBe(PROMPT_PLACEHOLDER_MESSAGES[1]);
+ expect(promptPlaceholder(promptPlaceholderCycleMs * PROMPT_PLACEHOLDER_MESSAGES.length)).toBe(
+ PROMPT_PLACEHOLDER_MESSAGES[0],
+ );
+ });
+
+ it("clamps a negative clock to the first message", () => {
+ expect(promptPlaceholder(-100)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/prompt-placeholder.ts b/packages/eve/src/cli/dev/tui/prompt-placeholder.ts
new file mode 100644
index 000000000..66b10d3f1
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/prompt-placeholder.ts
@@ -0,0 +1,22 @@
+/**
+ * The empty prompt's rotating invitation, written in the agent's own voice
+ * ("my capabilities") since the prompt is a message to it. Messages point at
+ * things an eve agent can actually do out of the box, so an idle prompt
+ * doubles as a hint surface. The caret-blink repaint keeps the rotation
+ * moving without its own timer.
+ */
+
+export const PROMPT_PLACEHOLDER_MESSAGES: readonly string[] = [
+ "Ask about my capabilities",
+ "Have me explore the workspace",
+ "Refine my instructions",
+];
+
+/** How long each message holds before the rotation advances. */
+export const promptPlaceholderCycleMs = 6_000;
+
+/** Picks the message for the given time since the renderer started. */
+export function promptPlaceholder(elapsedMs: number): string {
+ const index = Math.floor(Math.max(0, elapsedMs) / promptPlaceholderCycleMs);
+ return PROMPT_PLACEHOLDER_MESSAGES[index % PROMPT_PLACEHOLDER_MESSAGES.length]!;
+}
diff --git a/packages/eve/src/cli/dev/tui/question-panel.test.ts b/packages/eve/src/cli/dev/tui/question-panel.test.ts
new file mode 100644
index 000000000..1037e0c4f
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/question-panel.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+
+import { EMPTY_LINE, type LineState } from "./line-editor.js";
+import { renderQuestionPanel } from "./question-panel.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
+import { createTheme } from "./theme.js";
+
+const theme = createTheme({ color: false, unicode: true });
+
+function render(state: {
+ cursor: number;
+ allowFreeform?: boolean;
+ editor?: LineState;
+ caretVisible?: boolean;
+}): string[] {
+ return renderQuestionPanel(
+ {
+ prompt: "What type of options would you like to see?",
+ options: [
+ { id: "tools", label: "Available Tools", description: "See 4 tools I can use" },
+ { id: "services", label: "Connected Services" },
+ ],
+ cursor: state.cursor,
+ allowFreeform: state.allowFreeform ?? true,
+ editor: state.editor ?? EMPTY_LINE,
+ caretVisible: state.caretVisible ?? true,
+ },
+ theme,
+ 60,
+ ).map(stripAnsi);
+}
+
+describe("renderQuestionPanel", () => {
+ it("opens with the rule hugging the prompt and closes on the dismiss hint", () => {
+ const rows = render({ cursor: 0 });
+
+ expect(rows[0]).toBe("▔".repeat(60));
+ expect(rows).toContain(" What type of options would you like to see?");
+ expect(rows.find((row) => row.includes("1. Available Tools"))).toContain("▶");
+ expect(rows).toContain(" See 4 tools I can use");
+ expect(rows).toContain(" 2. Connected Services");
+ // The rule hugs the question; the panel closes on its one quiet hint.
+ expect(rows[1]).toBe(" What type of options would you like to see?");
+ expect(rows.at(-1)).toBe(" Esc to dismiss");
+ });
+
+ it("marks only the cursor row with the pointer and enter badge", () => {
+ const rows = render({ cursor: 1 });
+ const selected = rows.find((row) => row.includes("Connected Services"));
+
+ expect(selected).toContain(" ▶ 2. Connected Services ");
+ expect(selected).toContain("↵");
+ expect(rows.find((row) => row.includes("Available Tools"))).not.toContain("▶");
+ });
+
+ it("keeps every row's number and label in the same columns as the cursor moves", () => {
+ const columnsOf = (rows: string[]) =>
+ rows
+ .filter((row) => row.includes("Connected Services"))
+ .map((row) => row.indexOf("2. Connected Services"));
+
+ // Selected and unselected variants of the same row must not drift.
+ expect(columnsOf(render({ cursor: 1 }))).toEqual(columnsOf(render({ cursor: 0 })));
+ });
+
+ it("shows the elbow editor only while the freeform row is focused or drafted", () => {
+ expect(render({ cursor: 0 }).some((row) => row.includes("⎿"))).toBe(false);
+
+ const focused = render({ cursor: 2 });
+ expect(focused.some((row) => row.includes("⎿"))).toBe(true);
+
+ // A draft typed then abandoned stays visible under the row.
+ const drafted = render({ cursor: 0, editor: { text: "custom", cursor: 6 } });
+ expect(drafted.find((row) => row.includes("⎿"))).toContain("custom");
+ });
+
+ it("splits a multi-paragraph prompt into real rows before wrapping", () => {
+ const rows = renderQuestionPanel(
+ {
+ prompt: "Pick an idea:\n\n- **Coding** – learn a framework\n- **Data** – analytics",
+ options: [{ id: "a", label: "Coding" }],
+ cursor: 0,
+ allowFreeform: false,
+ editor: EMPTY_LINE,
+ caretVisible: true,
+ },
+ theme,
+ 60,
+ ).map(stripAnsi);
+
+ // Every prompt paragraph is its own row — a row secretly holding
+ // newlines breaks the live region's row accounting and leaks duplicate
+ // frames into scrollback on repaint.
+ expect(rows).toContain(" Pick an idea:");
+ expect(rows).toContain(" - **Coding** – learn a framework");
+ expect(rows).toContain(" - **Data** – analytics");
+ expect(rows.every((row) => !row.includes("\n"))).toBe(true);
+ });
+
+ it("clips every row to the panel width", () => {
+ for (const row of render({ cursor: 0 })) {
+ expect(row.length).toBeLessThanOrEqual(60);
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/question-panel.ts b/packages/eve/src/cli/dev/tui/question-panel.ts
new file mode 100644
index 000000000..22054f8ee
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/question-panel.ts
@@ -0,0 +1,116 @@
+/**
+ * Pure rendering for the HITL question panel — the overlay the agent's
+ * `ask_question` tool opens above the input area. A full-width rule separates
+ * it from the transcript, options render as numbered rows with their
+ * descriptions always visible, and the trailing "Type your own answer" row
+ * carries an inline elbow editor that receives focus the moment the cursor
+ * rests on it (the provider-key grammar from the setup panel). The renderer
+ * hosts lifecycle and keys; this module only paints rows.
+ */
+
+import type { AgentTUIInputOption } from "./runner.js";
+import { visibleLine, type LineState } from "./line-editor.js";
+import type { Theme } from "./theme.js";
+import { clipVisible, renderInputWithBlockCursor, wrapVisibleLine } from "#cli/ui/terminal-text.js";
+
+const FREEFORM_ROW_LABEL = "Type your own answer";
+
+export interface QuestionPanelState {
+ readonly prompt: string;
+ readonly options: readonly AgentTUIInputOption[];
+ /** Row index under the cursor; `options.length` is the freeform row. */
+ readonly cursor: number;
+ /** Whether the trailing freeform row exists. */
+ readonly allowFreeform: boolean;
+ /** The freeform row's inline editor; focused while the cursor rests on it. */
+ readonly editor: LineState;
+ readonly caretVisible: boolean;
+}
+
+/** Rows under the cursor paint like the setup panel's selected option. */
+function selectedRow(text: string, theme: Theme): string {
+ const c = theme.colors;
+ return `${c.inverse(c.blue(` ${theme.glyph.selectedPointer} ${text} `))} ${c.dim("↵")}`;
+}
+
+export function renderQuestionPanel(
+ state: QuestionPanelState,
+ theme: Theme,
+ width: number,
+): string[] {
+ const c = theme.colors;
+ const g = theme.glyph;
+ // The rule hugs the question — no blank row between them.
+ const rows: string[] = [c.dim(g.hrule.repeat(Math.max(1, width)))];
+
+ // The prompt is model-authored and can span paragraphs. Embedded newlines
+ // MUST split before width-wrapping: a row that secretly holds newlines
+ // occupies more terminal rows than the live region accounts for, leaking a
+ // duplicate frame into scrollback on every repaint.
+ for (const logical of state.prompt.split(/\r?\n/u)) {
+ for (const line of wrapVisibleLine(logical, Math.max(8, width - 2))) {
+ rows.push(` ${c.bold(line)}`);
+ }
+ }
+ rows.push("");
+
+ for (const [index, option] of state.options.entries()) {
+ rows.push(...optionRows(option.label, option.description, index, state, theme));
+ }
+ if (state.allowFreeform) {
+ const index = state.options.length;
+ const focused = state.cursor === index;
+ rows.push(...optionRows(FREEFORM_ROW_LABEL, undefined, index, state, theme));
+ if (focused || state.editor.text.length > 0) {
+ rows.push(` ${c.dim(g.elbow)} ${freeformEditorBody(state, focused, theme, width)}`);
+ }
+ }
+
+ // One quiet hint; arrow/enter affordances are carried by the cursor row
+ // itself. The overlay suppresses the footer's status hint row entirely.
+ rows.push("", ` ${c.dim("Esc to dismiss")}`);
+ return rows.map((row) => clipVisible(row, width));
+}
+
+function optionRows(
+ label: string,
+ description: string | undefined,
+ index: number,
+ state: QuestionPanelState,
+ theme: Theme,
+): string[] {
+ const c = theme.colors;
+ const numbered = `${index + 1}. ${label}`;
+ // Both variants put the number at column 5 and the label at column 8 —
+ // the selected row's extra cells are its pointer and padding, so moving
+ // the cursor never shifts the text horizontally.
+ const rows = [
+ state.cursor === index
+ ? ` ${selectedRow(numbered, theme)}`
+ : ` ${c.dim(`${index + 1}.`)} ${label}`,
+ ];
+ if (description !== undefined && description.length > 0) {
+ rows.push(` ${c.dim(description)}`);
+ }
+ return rows;
+}
+
+function freeformEditorBody(
+ state: QuestionPanelState,
+ focused: boolean,
+ theme: Theme,
+ width: number,
+): string {
+ const c = theme.colors;
+ // Reserve the elbow gutter plus the block cursor's trailing cell.
+ const budget = Math.max(4, width - 12);
+ if (!focused) {
+ const preserved = visibleLine(state.editor, budget, theme.glyph.ellipsis);
+ return c.dim(`${preserved.before}${preserved.under}${preserved.after}`);
+ }
+ return renderInputWithBlockCursor({
+ ...visibleLine(state.editor, budget, theme.glyph.ellipsis),
+ visible: state.caretVisible,
+ inverse: c.inverse,
+ });
+}
diff --git a/packages/eve/src/cli/dev/tui/rail.ts b/packages/eve/src/cli/dev/tui/rail.ts
new file mode 100644
index 000000000..f5db56053
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/rail.ts
@@ -0,0 +1,20 @@
+/**
+ * The shared atoms of the transcript's rail grammar. Persistent sections
+ * (tool rows, subagent sections, the todo panel) all hang their marks at the
+ * same two-cell tool column and elide overflow with the same counted row —
+ * one definition keeps the alignment a checked fact instead of a set of
+ * parallel comments.
+ */
+
+import type { Theme } from "./theme.js";
+
+/**
+ * The two-cell indent that puts a section's mark at the prose text column
+ * (the character after the `│`/`▲` gutter marks).
+ */
+export const TOOL_COLUMN_LEAD = " ";
+
+/** The dim `… (N more)` elision label used by every capped region. */
+export function elisionText(hidden: number, theme: Theme): string {
+ return theme.colors.dim(`${theme.glyph.ellipsis} (${hidden} more)`);
+}
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 60c68c4b1..510355625 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
Client,
@@ -145,6 +145,14 @@ const AGENT_INFO: AgentInfoResult = {
},
};
+beforeEach(() => {
+ // The runner normalizes header endpoints from the real process.env; a
+ // developer shell exporting gateway credentials must not leak into these
+ // boot-state assertions.
+ vi.stubEnv("AI_GATEWAY_API_KEY", "");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", "");
+});
+
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
@@ -1392,6 +1400,64 @@ describe("EveTUIRunner replay guards", () => {
},
]);
});
+
+ it("preserves a rejected action result instead of rendering it as success", async () => {
+ const prompts: Array<string | undefined> = ["run the tool", undefined];
+ const emitted: AgentTUIStreamEvent[] = [];
+ const session = sessionYielding([
+ {
+ type: "actions.requested",
+ data: {
+ actions: [
+ {
+ callId: "call-rejected",
+ input: { command: "rm something" },
+ kind: "tool-call",
+ toolName: "bash",
+ },
+ ],
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn_0",
+ },
+ },
+ {
+ type: "action.result",
+ data: {
+ error: { code: "USER_REJECTED", message: "Denied by user." },
+ result: {
+ callId: "call-rejected",
+ kind: "tool-result",
+ output: null,
+ },
+ sequence: 0,
+ status: "rejected",
+ stepIndex: 0,
+ turnId: "turn_0",
+ },
+ },
+ { type: "session.waiting", data: { wait: "next-user-message" } },
+ ]);
+ const renderer: AgentTUIRenderer = {
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {
+ emitted.push(event);
+ }
+ }),
+ };
+
+ await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();
+
+ expect(emitted.filter((event) => event.type === "tool-result")).toEqual([]);
+ expect(emitted.filter((event) => event.type === "tool-rejected")).toEqual([
+ {
+ type: "tool-rejected",
+ toolCallId: "call-rejected",
+ reason: "Denied by user.",
+ },
+ ]);
+ });
});
describe("parsePromptCommand", () => {
@@ -1775,6 +1841,86 @@ describe("EveTUIRunner renderer teardown", () => {
expect(shutdown).toHaveBeenCalledTimes(1);
});
+ it("finishes the section on the child's own turn boundary, before subagent.completed", async () => {
+ const client = stubClient();
+ const childSession = client.session({ sessionId: "child-session", streamIndex: 0 });
+ vi.spyOn(client, "session").mockReturnValue(childSession);
+ vi.spyOn(childSession, "stream").mockImplementation(() => ({
+ async *[Symbol.asyncIterator]() {
+ yield {
+ type: "message.completed",
+ data: {
+ finishReason: "stop",
+ message: "final answer",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn-child",
+ },
+ } as HandleMessageStreamEvent;
+ yield {
+ type: "session.waiting",
+ data: { wait: "next-user-message" },
+ } as HandleMessageStreamEvent;
+ },
+ }));
+
+ const completeSubagent = vi.fn();
+ const completed = createDeferred<void>();
+ const runner = new EveTUIRunner({
+ client,
+ name: "Weather Agent",
+ renderer: fakeRenderer({
+ // Hold the second prompt open until the child boundary finishes the
+ // section — exiting the run loop aborts the child pump.
+ readPrompt: vi
+ .fn()
+ .mockResolvedValueOnce("delegate")
+ .mockImplementationOnce(async () => {
+ await completed.promise;
+ return undefined;
+ }),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) void event;
+ }),
+ subagents: {
+ begin: vi.fn(),
+ upsertStep: vi.fn(),
+ upsertTool: vi.fn(),
+ removeTool: vi.fn(),
+ markChildToolCallId: vi.fn(),
+ complete: (update: { callId: string }) => {
+ completeSubagent(update);
+ completed.resolve();
+ },
+ },
+ }),
+ session: sessionYielding([
+ {
+ type: "subagent.called",
+ data: {
+ callId: "call-child",
+ childSessionId: "child-session",
+ name: "weather-child",
+ sequence: 0,
+ sessionId: "parent-session",
+ toolName: "delegate_weather",
+ turnId: "turn-parent",
+ workflowId: "workflow-parent",
+ },
+ },
+ // The parent stream never reports subagent.completed — the child's
+ // own boundary must finish the section.
+ { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },
+ { type: "session.waiting", data: { wait: "next-user-message" } },
+ ]),
+ });
+
+ await runner.run();
+ await completed.promise;
+
+ expect(completeSubagent).toHaveBeenCalledWith({ callId: "call-child" });
+ });
+
it("aborts child-session streams when Ctrl-C exits the runner", async () => {
const client = stubClient();
const childSession = client.session({ sessionId: "child-session", streamIndex: 0 });
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 05341165c..0720625cb 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -18,7 +18,6 @@ import {
type SubagentCompletedStreamEvent,
Client,
ClientSession,
- isCurrentTurnBoundaryEvent,
} from "#client/index.js";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import { subscribeDevelopmentSandboxPrewarmLogs } from "#execution/sandbox/development-prewarm.js";
@@ -27,6 +26,13 @@ import {
type DevelopmentRuntimeArtifactRefresher,
} from "#services/dev-client.js";
import { toErrorMessage } from "#shared/errors.js";
+import { SubagentPump, type SubagentPumpOptions, type SubagentView } from "./subagent-pump.js";
+export type {
+ SubagentRun,
+ SubagentStepUpdate,
+ SubagentToolUpdate,
+ SubagentView,
+} from "./subagent-pump.js";
import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-progress.js";
import {
@@ -35,7 +41,6 @@ import {
formatFailureDetail,
formatFailureHint,
formatFailureMessage,
- isAbortLikeError,
isInterruptedError,
localFailureHint,
} from "./errors.js";
@@ -117,10 +122,12 @@ export type AgentTUIStreamEvent =
| { type: "assistant-complete"; id: string; text?: string | null }
| { type: "reasoning-delta"; id: string; delta: string }
| { type: "reasoning-complete"; id: string }
+ | { type: "tool-call-preparing"; toolCallId: string; toolName: string }
| { type: "tool-call"; toolCallId: string; toolName: string; input: unknown }
| { type: "tool-approval-request"; approvalId: string; toolCallId: string }
| { type: "tool-result"; toolCallId: string; output: unknown }
| { type: "tool-error"; toolCallId: string; errorText: string }
+ | { type: "tool-rejected"; toolCallId: string; reason: string }
| { type: "error"; errorText: string; hint?: string; detail?: string }
| { type: "finish"; usage?: AgentTUIStreamUsage };
@@ -203,6 +210,12 @@ export type AgentTUIRenderer = {
* recovery and slash-command results. Optional.
*/
renderNotice?(text: string): void;
+ /**
+ * Commits the session boundary (`┌── Session restarted, clear context.`)
+ * when a dead session is replaced mid-conversation. Optional; renderers
+ * without it get the plain notice.
+ */
+ renderSessionBoundary?(): void;
/**
* Commits one development sandbox lifecycle line to the transcript.
* Optional so non-terminal renderers can ignore local prewarm progress.
@@ -226,22 +239,13 @@ export type AgentTUIRenderer = {
): Promise<AgentTUIInputQuestionResponse | undefined>;
renderStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;
/**
- * Out-of-band update for one child step (reasoning + message text) of a
- * subagent dispatch. Called by the runner as child-session stream events
- * arrive. The renderer renders this as a body section colored by the
- * subagent palette.
+ * The renderer's whole subagent surface — sections, nested steps and
+ * tools, ghost sweeps, completion. One optional capability with required
+ * members: a renderer either has a subagent view or it doesn't, and a
+ * type-legal partial implementation (which would ghost placeholders or
+ * duplicate parent tool rows) cannot exist.
*/
- upsertSubagentStep?(update: SubagentStepUpdate): void;
- /**
- * Out-of-band update for one child tool call of a subagent dispatch.
- */
- upsertSubagentTool?(update: SubagentToolUpdate): void;
- /**
- * Registers a tool call id as originating from a subagent's child
- * session. The renderer must skip or remove parent-level tool blocks for
- * these ids — they are surfaced via {@link upsertSubagentTool} instead.
- */
- markChildToolCallId?(callId: string): void;
+ readonly subagents?: SubagentView;
/**
* Out-of-band update for one MCP connection authorization lifecycle.
* Called by the runner as `authorization.*` events arrive.
@@ -462,13 +466,12 @@ export class EveTUIRunner {
* Each run holds per-step text accumulators (so reasoning + message land
* in the same section per child step) and per-tool state.
*/
- readonly #subagentRuns = new Map<string, SubagentRun>();
+ readonly #subagentPump: SubagentPump;
/**
* callId → AbortController for the parallel child-session stream pump
* launched on `subagent.called`. Cancelled on `subagent.completed`, when
* the session resets, or when the runner shuts down.
*/
- readonly #subagentChildPumps = new Map<string, AbortController>();
/**
* name → latest known state for one MCP connection
* authorization lifecycle. Persists across turns because a turn that
@@ -498,6 +501,10 @@ export class EveTUIRunner {
this.#session = options.session;
if (options.client !== undefined) this.#client = options.client;
this.#renderer = createRenderer(options);
+ const pumpOptions: SubagentPumpOptions = { formatActionResultError };
+ if (this.#client !== undefined) pumpOptions.client = this.#client;
+ if (this.#renderer.subagents !== undefined) pumpOptions.view = this.#renderer.subagents;
+ this.#subagentPump = new SubagentPump(pumpOptions);
this.#name = options.name ?? "eve";
this.#tools = options.tools ?? "full";
this.#reasoning = options.reasoning ?? "full";
@@ -618,7 +625,7 @@ export class EveTUIRunner {
} finally {
this.#disposed = true;
this.#authProbeAbort.abort();
- this.#abortSubagentChildPumps();
+ this.#subagentPump.abortAll();
// Restore captured stdout/stderr before a fatal error reaches the CLI.
this.#unsubscribeDevelopmentSandboxLogs?.();
this.#unsubscribeDevelopmentSandboxLogs = undefined;
@@ -819,6 +826,15 @@ export class EveTUIRunner {
}
}
+ if (responses.length === 0) {
+ // Every pending question was dismissed without an answer. Fall
+ // back to the prompt rather than resuming with an empty
+ // response set: the turn stays parked, and the user's next
+ // message resumes it with the unanswered requests recorded as
+ // `ignored` (the server's continued-without-responding path).
+ break;
+ }
+
streamWithoutPrompt = true;
pendingInputResponses = responses;
prompt = undefined;
@@ -869,11 +885,19 @@ export class EveTUIRunner {
if (this.#sessionFailed) {
this.#sessionFailed = false;
this.#startNewSession();
- this.#renderer.renderNotice?.(
- result.turnState?.aborted
- ? "Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server."
- : "Session ended — started a new session. Earlier context was cleared.",
- );
+ // An aborted turn keeps its explicit notice — the boundary line alone
+ // would hide that the interrupted turn may still run on the server.
+ if (result.turnState?.aborted) {
+ this.#renderer.renderNotice?.(
+ "Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.",
+ );
+ } else if (this.#renderer.renderSessionBoundary !== undefined) {
+ this.#renderer.renderSessionBoundary();
+ } else {
+ this.#renderer.renderNotice?.(
+ "Session ended — started a new session. Earlier context was cleared.",
+ );
+ }
}
}
}
@@ -885,8 +909,7 @@ export class EveTUIRunner {
* In-flight subagent child-session streams are aborted.
*/
#startNewSession(): void {
- this.#abortSubagentChildPumps();
- this.#subagentRuns.clear();
+ this.#subagentPump.abortAll();
this.#pendingInputRequests.clear();
this.#connectionAuthRuns.clear();
this.#pendingConnectionAuths.clear();
@@ -898,13 +921,6 @@ export class EveTUIRunner {
this.#runtimeArtifacts?.clear();
}
- #abortSubagentChildPumps(): void {
- for (const controller of this.#subagentChildPumps.values()) {
- controller.abort();
- }
- this.#subagentChildPumps.clear();
- }
-
async #readPromptWithIdleRefresh(options: AgentTUISessionOptions): Promise<string | undefined> {
if (!this.#renderer.readPrompt) {
return undefined;
@@ -1041,10 +1057,9 @@ export class EveTUIRunner {
events: eveEventsToTUIStream({
events,
pendingInputRequests: this.#pendingInputRequests,
- subagentRuns: this.#subagentRuns,
turnState,
- onSubagentCalled: (called) => this.#startSubagentChildPump(called),
- onSubagentCompleted: (callId) => this.#stopSubagentChildPump(callId),
+ onSubagentCalled: (called) => this.#subagentPump.begin(called),
+ onSubagentCompleted: (callId) => this.#subagentPump.settle(callId),
onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),
onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),
onTerminalFailure: () => {
@@ -1430,268 +1445,6 @@ export class EveTUIRunner {
if (run.reason !== undefined) update.reason = run.reason;
this.#renderer.upsertConnectionAuth?.(update);
}
-
- /**
- * Opens a parallel stream over the child session and folds its events into
- * nested subagent blocks.
- *
- * Pumps are fire-and-forget and must never be awaited at a turn boundary:
- * a subagent dispatched in `task` mode that parks for HITL never emits a
- * turn-boundary event on its own stream (`harness/tool-loop.ts` gates
- * `emitTurnEpilogue` on `mode === "conversation"`), so blocking on a child
- * stream would stall the prompt until the subagent's serverless function
- * times out. Pumps stay open across HITL prompts and resume rendering when
- * the subagent unparks; they end on the child's own boundary or via abort.
- */
- #startSubagentChildPump(called: SubagentCalledStreamEvent) {
- const callId = called.data.callId;
- if (this.#subagentChildPumps.has(callId)) return;
- const client = this.#client;
- if (!client) return;
-
- const controller = new AbortController();
- this.#subagentChildPumps.set(callId, controller);
-
- void (async () => {
- try {
- const childSession = client.session({
- sessionId: called.data.childSessionId,
- streamIndex: 0,
- });
- const stream = childSession.stream({ signal: controller.signal });
- for await (const event of stream) {
- if (controller.signal.aborted) break;
- this.#applyChildEvent(callId, event);
- if (isCurrentTurnBoundaryEvent(event)) {
- // Child completed its turn — close the parallel stream
- // gracefully. The parent's `subagent.completed` is a separate
- // signal that arrives independently and is handled by
- // `#stopSubagentChildPump`.
- break;
- }
- }
- } catch (error) {
- if (!isAbortLikeError(error)) {
- const errorText = toErrorMessage(error);
- const run = this.#subagentRuns.get(callId);
- if (run) {
- const { key, step } = openCurrentSubagentSection(run);
- step.message = step.message
- ? `${step.message}\n\nstream error: ${errorText}`
- : `stream error: ${errorText}`;
- step.finalized = true;
- run.currentSectionKey = null;
- this.#renderer.upsertSubagentStep?.({
- callId,
- subagentName: run.name,
- sectionKey: key,
- reasoning: step.reasoning,
- message: step.message,
- finalized: true,
- });
- }
- }
- } finally {
- this.#subagentChildPumps.delete(callId);
- }
- })();
- }
-
- #registerChildTool(
- callId: string,
- run: SubagentRun,
- request: {
- childCallId: string;
- toolName: string;
- input: unknown;
- status: SubagentToolState["status"];
- },
- ): void {
- const existing = run.tools.get(request.childCallId);
- const tool: SubagentToolState = existing ?? {
- toolName: request.toolName,
- input: request.input,
- status: request.status,
- };
- if (existing) {
- // Promote status only when the new status is "stronger" — e.g.
- // approval-requested → executing once the parent approves, but
- // never demote from done/failed back to executing.
- const priority: Record<SubagentToolState["status"], number> = {
- "approval-requested": 0,
- executing: 1,
- done: 2,
- failed: 2,
- };
- if (priority[request.status] > priority[existing.status]) {
- existing.status = request.status;
- }
- existing.input = request.input;
- } else {
- run.tools.set(request.childCallId, tool);
- }
- this.#renderer.markChildToolCallId?.(request.childCallId);
- this.#renderer.upsertSubagentTool?.({
- callId,
- subagentName: run.name,
- childCallId: request.childCallId,
- toolName: tool.toolName,
- input: tool.input,
- status: tool.status,
- });
- }
-
- #stopSubagentChildPump(callId: string) {
- // Parent reports subagent.completed. The child stream pump terminates
- // itself on the child's own turn boundary; we do NOT abort here,
- // because the child's `message.completed` event may still be in flight
- // (the parent and child streams are independent HTTP connections).
- // Re-emit a finalized snapshot for any sections that are still
- // streaming so their right-title flips off `streaming` even if the
- // child's boundary event hasn't arrived yet.
- const run = this.#subagentRuns.get(callId);
- if (!run) return;
- for (const [sectionKey, step] of run.steps) {
- if (!step.finalized) {
- step.finalized = true;
- this.#renderer.upsertSubagentStep?.({
- callId,
- subagentName: run.name,
- sectionKey,
- reasoning: step.reasoning,
- message: step.message,
- finalized: true,
- });
- }
- }
- run.currentSectionKey = null;
- }
-
- #applyChildEvent(callId: string, event: HandleMessageStreamEvent) {
- const run = this.#subagentRuns.get(callId);
- if (!run) return;
- const renderer = this.#renderer;
-
- const emit = (key: number, step: SubagentChildStep) => {
- renderer.upsertSubagentStep?.({
- callId,
- subagentName: run.name,
- sectionKey: key,
- reasoning: step.reasoning,
- message: step.message,
- finalized: step.finalized,
- });
- };
-
- const finalizeCurrent = () => {
- if (run.currentSectionKey === null) return;
- const step = run.steps.get(run.currentSectionKey);
- if (step) {
- step.finalized = true;
- emit(run.currentSectionKey, step);
- }
- run.currentSectionKey = null;
- };
-
- switch (event.type) {
- case "reasoning.appended": {
- const { key, step } = openCurrentSubagentSection(run);
- step.reasoning = step.reasoning + event.data.reasoningDelta;
- emit(key, step);
- break;
- }
- case "reasoning.completed":
- // Reasoning closes within a section but does not close the section
- // itself — a following `message.appended` should land in the same
- // box. The section closes on `message.completed` or
- // `step.completed`.
- break;
- case "message.appended": {
- const { key, step } = openCurrentSubagentSection(run);
- step.message = step.message + event.data.messageDelta;
- emit(key, step);
- break;
- }
- case "message.completed": {
- const { key, step } = openCurrentSubagentSection(run);
- if (event.data.message !== null && step.message.length === 0) {
- // Some channels emit only `message.completed` without per-delta
- // `message.appended` events. Capture the full text in that case.
- step.message = event.data.message;
- }
- step.finalized = true;
- emit(key, step);
- run.currentSectionKey = null;
- break;
- }
- case "step.completed":
- finalizeCurrent();
- break;
- case "actions.requested": {
- // Close any pending text section before the tool call so the
- // tool box renders below it — and the next post-tool message
- // opens a fresh section.
- finalizeCurrent();
- for (const action of event.data.actions) {
- if (action.kind !== "tool-call") continue;
- this.#registerChildTool(callId, run, {
- childCallId: action.callId,
- toolName: action.toolName,
- input: action.input,
- status: "executing",
- });
- }
- break;
- }
- case "input.requested": {
- // Tools that need approval skip `actions.requested` and arrive
- // here as `input.requested` with the action embedded. Register
- // the tool section the same way (status: "approval-requested")
- // so the parent's stale tool box can be suppressed and the
- // child tool appears under the subagent flow.
- finalizeCurrent();
- for (const request of event.data.requests) {
- if (request.action.kind !== "tool-call") continue;
- this.#registerChildTool(callId, run, {
- childCallId: request.action.callId,
- toolName: request.action.toolName,
- input: request.action.input,
- status: "approval-requested",
- });
- }
- break;
- }
- case "action.result": {
- const result = event.data.result;
- if (result.kind !== "tool-result") break;
- const tool = run.tools.get(result.callId);
- if (!tool) break;
- if (event.data.status === "failed") {
- tool.status = "failed";
- tool.errorText = formatActionResultError(event);
- } else {
- tool.status = "done";
- tool.output = result.output;
- }
- const update: SubagentToolUpdate = {
- callId,
- subagentName: run.name,
- childCallId: result.callId,
- toolName: tool.toolName,
- input: tool.input,
- status: tool.status,
- };
- if (tool.output !== undefined) update.output = tool.output;
- if (tool.errorText !== undefined) update.errorText = tool.errorText;
- renderer.upsertSubagentTool?.(update);
- break;
- }
- default:
- // Other events (session.*, turn.*, step.started, etc.) carry no
- // visible text — ignore.
- break;
- }
- }
}
function createRenderer(options: EveTUIRunnerOptions): AgentTUIRenderer {
@@ -1734,7 +1487,6 @@ function formatAgentUpdateNotice(
type EveStreamTranslatorInput = {
events: AsyncIterable<HandleMessageStreamEvent>;
pendingInputRequests: Map<string, InputRequest>;
- subagentRuns: Map<string, SubagentRun>;
turnState: AgentTUITurnState;
onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;
onSubagentCompleted?: (callId: string) => void;
@@ -1760,7 +1512,6 @@ async function* eveEventsToTUIStream(
const {
events,
pendingInputRequests,
- subagentRuns,
turnState,
onSubagentCalled,
onSubagentCompleted,
@@ -2011,18 +1762,28 @@ async function* eveEventsToTUIStream(
// have no tool block to attach to.
break;
}
- if (resultEvent.data.status === "failed") {
- yield {
- type: "tool-error",
- toolCallId: callId,
- errorText: formatActionResultError(resultEvent),
- };
- } else {
- yield {
- type: "tool-result",
- toolCallId: callId,
- output: resultEvent.data.result.output,
- };
+ switch (resultEvent.data.status) {
+ case "completed":
+ yield {
+ type: "tool-result",
+ toolCallId: callId,
+ output: resultEvent.data.result.output,
+ };
+ break;
+ case "failed":
+ yield {
+ type: "tool-error",
+ toolCallId: callId,
+ errorText: formatActionResultError(resultEvent),
+ };
+ break;
+ case "rejected":
+ yield {
+ type: "tool-rejected",
+ toolCallId: callId,
+ reason: formatActionResultError(resultEvent),
+ };
+ break;
}
break;
}
@@ -2071,21 +1832,9 @@ async function* eveEventsToTUIStream(
break;
case "subagent.called": {
- const called = event as SubagentCalledStreamEvent;
- if (!subagentRuns.has(called.data.callId)) {
- subagentRuns.set(called.data.callId, {
- name: called.data.name,
- steps: new Map(),
- currentSectionKey: null,
- nextSectionKey: 0,
- tools: new Map(),
- });
- } else {
- // Idempotent re-entry (e.g. SSE resume): just refresh the name.
- const run = subagentRuns.get(called.data.callId);
- if (run) run.name = called.data.name;
- }
- onSubagentCalled?.(called);
+ // Run creation (idempotent for SSE-resume re-entries) lives in the
+ // pump's begin().
+ onSubagentCalled?.(event as SubagentCalledStreamEvent);
break;
}
@@ -2334,61 +2083,6 @@ function toAgentTUIInputQuestion(request: InputRequest): AgentTUIInputQuestion {
return question;
}
-type SubagentChildStep = {
- reasoning: string;
- message: string;
- finalized: boolean;
-};
-
-type SubagentToolState = {
- toolName: string;
- input: unknown;
- status: "approval-requested" | "executing" | "done" | "failed";
- output?: unknown;
- errorText?: string;
-};
-
-export type SubagentRun = {
- name: string;
- /**
- * One entry per logical "child message" — independent of the child's
- * `stepIndex` field, which the harness can reuse across multiple
- * assistant messages within a turn (e.g. a message before a tool call
- * and another message after the tool result both arrive under
- * `stepIndex: 0`). The key is a monotonic counter so each
- * `message.completed` opens a new box on the next inbound delta.
- */
- steps: Map<number, SubagentChildStep>;
- /**
- * Section currently accepting reasoning/message deltas. `null` means
- * the next delta opens a new section.
- */
- currentSectionKey: number | null;
- /** Monotonic counter for new section keys. */
- nextSectionKey: number;
- tools: Map<string, SubagentToolState>;
-};
-
-export type SubagentStepUpdate = {
- callId: string;
- subagentName: string;
- sectionKey: number;
- reasoning: string;
- message: string;
- finalized: boolean;
-};
-
-export type SubagentToolUpdate = {
- callId: string;
- subagentName: string;
- childCallId: string;
- toolName: string;
- input: unknown;
- status: "approval-requested" | "executing" | "done" | "failed";
- output?: unknown;
- errorText?: string;
-};
-
export type ConnectionAuthChallenge = {
url?: string;
userCode?: string;
@@ -2414,18 +2108,3 @@ type ConnectionAuthRun = {
webhookUrl?: string;
reason?: string;
};
-
-function openCurrentSubagentSection(run: SubagentRun): {
- key: number;
- step: SubagentChildStep;
-} {
- if (run.currentSectionKey === null) {
- run.currentSectionKey = run.nextSectionKey++;
- run.steps.set(run.currentSectionKey, { reasoning: "", message: "", finalized: false });
- }
- const step = run.steps.get(run.currentSectionKey);
- if (!step) {
- throw new Error("invariant: subagent section state missing for current key");
- }
- return { key: run.currentSectionKey, step };
-}
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
index 4be38e3ed..ea0769f59 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
@@ -141,7 +141,10 @@ describe("runTuiSetupCommand", () => {
kind: "done",
modelMessage: "Model changed to openai/gpt-5.5. Live on your next prompt.",
providerOutcome: {
- credential: "AI_GATEWAY_API_KEY",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ },
status: { kind: "gateway-project", projectName: "my-agent" },
},
})),
@@ -160,7 +163,7 @@ describe("runTuiSetupCommand", () => {
runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({
kind: "done",
providerOutcome: {
- credential: "VERCEL_OIDC_TOKEN",
+ resolution: { credential: "oidc", file: ".env.local" },
status: { kind: "gateway-project", projectName: "my-agent", teamName: "my-team" },
},
})),
@@ -172,13 +175,44 @@ describe("runTuiSetupCommand", () => {
});
});
+ it("names the shadow when a gateway key outranks the freshly linked OIDC token", async () => {
+ const flows = fakeFlows({
+ runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({
+ kind: "done",
+ providerOutcome: {
+ resolution: {
+ credential: "api-key",
+ source: { kind: "shell" },
+ shadowedOidc: {},
+ },
+ status: { kind: "gateway-project", projectName: "my-agent", teamName: "my-team" },
+ },
+ })),
+ });
+ await expect(run({ command: "model", flows })).resolves.toEqual({
+ message:
+ "Project linked. AI_GATEWAY_API_KEY (shell) outranks the project's " +
+ "VERCEL_OIDC_TOKEN and stays the active credential — unset it in your shell to run " +
+ "on the project.",
+ preserveFlowDiagnostics: false,
+ effect: { kind: "model-access-changed" },
+ });
+ });
+
it("does not claim a link for a pasted key — the outcome names the env file", async () => {
const flows = fakeFlows({
runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({
kind: "done",
providerOutcome: {
- credential: "AI_GATEWAY_API_KEY",
- status: { kind: "gateway-key", envKey: "AI_GATEWAY_API_KEY", envFile: ".env.local" },
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ },
+ status: {
+ kind: "gateway-key",
+ envKey: "AI_GATEWAY_API_KEY",
+ source: { kind: "env-file", path: ".env.local" },
+ },
},
})),
});
@@ -502,11 +536,14 @@ describe("runTuiSetupCommand", () => {
resolve({
kind: "done",
providerOutcome: {
- credential: "AI_GATEWAY_API_KEY",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ },
status: {
kind: "gateway-key",
envKey: "AI_GATEWAY_API_KEY",
- envFile: ".env.local",
+ source: { kind: "env-file", path: ".env.local" },
},
},
}),
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.ts
index 8c1fbf2c5..63af3e0ed 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts
@@ -484,14 +484,33 @@ function pendingChannelsResult(message: string): TuiSetupCommandResult {
* without linking anything.
*/
function providerOutcomeMessage(outcome: ModelProviderOutcome): string {
- const { credential, status } = outcome;
+ const { resolution, status } = outcome;
if (status.kind === "gateway-project") {
- return credential === undefined
- ? "Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local."
- : `Project linked. Connected to AI Gateway via ${credential}.`;
+ if (resolution === undefined) {
+ return "Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local.";
+ }
+ if (resolution.credential === "oidc") {
+ return "Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.";
+ }
+ // A gateway key outranks the project's OIDC token at runtime — claiming
+ // the OIDC connection while the key authenticates every call would split
+ // this message from the status bar and the actual resolution.
+ if (resolution.shadowedOidc !== undefined) {
+ const from = resolution.source.kind === "shell" ? "shell" : resolution.source.path;
+ const remove =
+ resolution.source.kind === "shell"
+ ? "unset it in your shell"
+ : `remove it from ${resolution.source.path}`;
+ return (
+ `Project linked. AI_GATEWAY_API_KEY (${from}) outranks the project's ` +
+ `VERCEL_OIDC_TOKEN and stays the active credential — ${remove} to run on the project.`
+ );
+ }
+ return "Project linked. Connected to AI Gateway via AI_GATEWAY_API_KEY.";
}
if (status.kind === "gateway-key") {
- return `Connected to AI Gateway via ${status.envKey} in ${status.envFile}.`;
+ const where = status.source.kind === "shell" ? "your shell" : status.source.path;
+ return `Connected to AI Gateway via ${status.envKey} in ${where}.`;
}
return "Provider updated — no gateway credential detected; set AI_GATEWAY_API_KEY in .env.local.";
}
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.ts b/packages/eve/src/cli/dev/tui/setup-issues.ts
index ca69b51c6..44bc0510f 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.ts
@@ -1,6 +1,7 @@
import { join } from "node:path";
import type { AgentInfoResult } from "#client/index.js";
+import { hasEnvValue, resolveGatewayCredential } from "#internal/resolve-model-endpoint-status.js";
import { pathExists } from "#setup/path-exists.js";
/** One boot-time setup problem the TUI can point at a fixing command. */
@@ -44,11 +45,6 @@ type ModelProviderAccess =
| { status: "unknown" };
};
-function hasEnvValue(env: Record<string, string | undefined>, key: string): boolean {
- const value = env[key];
- return value !== undefined && value.trim().length > 0;
-}
-
/**
* Resolves the local TUI's current model-provider state into the agent-info
* snapshot it caches. The local TUI and dev server share `process.env`, so a
@@ -91,9 +87,15 @@ function modelProviderAccess(
if (model?.routing?.kind === "external") return { kind: "external" };
if (model?.routing?.kind !== "gateway") return { kind: "unknown" };
- // The compiled routing decides whether gateway credentials apply. A freshly
- // loaded API key outranks a stale OIDC endpoint, matching gateway resolution.
- if (hasEnvValue(context.env, "AI_GATEWAY_API_KEY")) {
+ // The compiled routing decides whether gateway credentials apply. Local
+ // ranking delegates to the one precedence authority; the server-reported
+ // endpoint snapshot slots between a freshly loaded key (which outranks a
+ // stale snapshot) and a local OIDC token (which the snapshot outranks).
+ const local = resolveGatewayCredential({
+ apiKeyInEnv: hasEnvValue(context.env["AI_GATEWAY_API_KEY"]),
+ oidcAvailable: hasEnvValue(context.env["VERCEL_OIDC_TOKEN"]),
+ });
+ if (local?.credential === "api-key") {
return { kind: "gateway", runtime: { status: "connected", credential: "api-key" } };
}
const endpoint = model.endpoint;
@@ -103,8 +105,8 @@ function modelProviderAccess(
runtime: { status: "connected", credential: endpoint.credential },
};
}
- if (hasEnvValue(context.env, "VERCEL_OIDC_TOKEN")) {
- return { kind: "gateway", runtime: { status: "connected", credential: "oidc" } };
+ if (local !== undefined) {
+ return { kind: "gateway", runtime: { status: "connected", credential: local.credential } };
}
if (endpoint?.kind === "gateway") return { kind: "gateway", runtime: { status: "disconnected" } };
return { kind: "gateway", runtime: { status: "unknown" } };
diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.ts
index 68651bbd7..a0d2c35c7 100644
--- a/packages/eve/src/cli/dev/tui/status-line.test.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts
@@ -59,7 +59,7 @@ describe("buildStatusLine", () => {
width: 120,
});
- expect(line).toBe("anthropic/claude-sonnet-5 AI Gateway (my-agent) /deploy pending");
+ expect(line).toBe("anthropic/claude-sonnet-5 via ai-gateway(oidc:my-agent) /deploy pending");
});
it("folds the reasoning level and Fast mode marker into the model segment", () => {
@@ -73,7 +73,7 @@ describe("buildStatusLine", () => {
width: 120,
});
- expect(line).toBe("xai/grok-4.5@xhigh ↯ AI Gateway (my-agent)");
+ expect(line).toBe("xai/grok-4.5@xhigh ↯ via ai-gateway(oidc:my-agent)");
});
it("dims the whole model segment, reasoning level and fast marker included", () => {
@@ -134,16 +134,16 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(withProject).toBe("m AI Gateway (my-agent)");
+ expect(withProject).toBe("m via ai-gateway(oidc:my-agent)");
- // Connected without a linked project (a raw key): bare "AI Gateway".
+ // OIDC without a resolved project name: bare scope.
const noProject = buildStatusLine({
model: "m",
endpoint: connected,
theme: plain,
width: 120,
});
- expect(noProject).toBe("m AI Gateway");
+ expect(noProject).toBe("m via ai-gateway(oidc)");
});
it("renders the pending marker even when no segment else resolved", () => {
@@ -190,10 +190,10 @@ describe("buildStatusLine", () => {
theme: plain,
};
const full = buildStatusLine({ ...input, width: 200 })!;
- expect(full).toContain("AI Gateway (my-agent)");
+ expect(full).toContain("via ai-gateway(oidc:my-agent)");
const noEndpoint = buildStatusLine({ ...input, width: visibleLength(full) - 1 })!;
- expect(noEndpoint).not.toContain("AI Gateway");
+ expect(noEndpoint).not.toContain("ai-gateway");
expect(noEndpoint).toContain("anthropic/claude-sonnet-5");
const noModel = buildStatusLine({ ...input, width: visibleLength(noEndpoint) - 1 })!;
@@ -207,7 +207,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(external).toBe("anthropic/claude-sonnet-5 External endpoint");
+ expect(external).toBe("anthropic/claude-sonnet-5 via anthropic⌝");
const linked = buildStatusLine({
model: "m",
@@ -216,7 +216,26 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(linked).toBe("m AI Gateway (my-agent)");
+ expect(linked).toBe("m via ai-gateway(oidc:my-agent)");
+
+ const apiKey = buildStatusLine({
+ model: "m",
+ endpoint: { kind: "gateway", connected: true, credential: "api-key" },
+ // A linked project must NOT surface here: the key is what
+ // authenticates, and the bar reports the credential in use.
+ vercel: { identity, pendingDeploy: false },
+ theme: plain,
+ width: 120,
+ });
+ expect(apiKey).toBe("m via ai-gateway(api-key)");
+
+ const chatgpt = buildStatusLine({
+ model: "openai/gpt-5.6-sol",
+ endpoint: { kind: "external", provider: "codex" },
+ theme: plain,
+ width: 120,
+ });
+ expect(chatgpt).toBe("openai/gpt-5.6-sol via chatgpt-sub⌝");
const notConnected = buildStatusLine({
model: "m",
@@ -224,7 +243,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(notConnected).toBe("m ⚠ AI Gateway");
+ expect(notConnected).toBe("m ⚠ ai-gateway");
});
it("paints only the not-connected endpoint yellow", () => {
@@ -233,14 +252,28 @@ describe("buildStatusLine", () => {
theme,
width: 120,
});
- expect(notConnected).toContain("\x1b[33m⚠ AI Gateway\x1b[39m");
+ expect(notConnected).toContain("\x1b[33m⚠ ai-gateway\x1b[39m");
const linked = buildStatusLine({
endpoint: connected,
theme,
width: 120,
});
- expect(linked).toContain("\x1b[2mAI Gateway\x1b[22m");
+ // Only the gateway stands at the terminal's default foreground — no
+ // explicit white, no bold; via/scope stay dim around it.
+ expect(linked).toContain("\x1b[2mvia \x1b[22mai-gateway\x1b[2m(oidc)\x1b[22m");
+ expect(linked).not.toContain("\x1b[97m");
+ expect(linked).not.toContain("\x1b[1mai-gateway");
+
+ // External providers render quiet — no bright token — with only the
+ // authored-endpoint mark at the default foreground.
+ const external = buildStatusLine({
+ endpoint: { kind: "external", provider: "codex" },
+ theme,
+ width: 120,
+ });
+ expect(external).toContain("\x1b[2mvia chatgpt-sub\x1b[22m⌝");
+ expect(external).not.toContain("\x1b[1m");
});
it("renders ASCII glyphs when unicode is unavailable", () => {
@@ -250,7 +283,7 @@ describe("buildStatusLine", () => {
theme: ascii,
width: 120,
});
- expect(stripAnsi(line!)).toBe("m ! AI Gateway");
+ expect(stripAnsi(line!)).toBe("m ! ai-gateway");
});
it("renders the remote badge first and projects each authentication state", () => {
@@ -357,7 +390,7 @@ describe("buildStatusLine", () => {
width: 120,
})!;
- expect(stripAnsi(line)).not.toContain("AI Gateway");
+ expect(stripAnsi(line)).not.toContain("ai-gateway");
expect(
stripAnsi(
buildStatusLine({
diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.ts
index 24c81c140..2d5597000 100644
--- a/packages/eve/src/cli/dev/tui/status-line.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.ts
@@ -60,17 +60,49 @@ function renderServerPort(
return c.inverse(c.gray(` :${input.serverPort} `));
}
+/** Provider slugs whose display name differs from the AI SDK's identifier. */
+const EXTERNAL_PROVIDER_DISPLAY_NAMES: Readonly<Record<string, string>> = {
+ // `experimental_chatgpt` wraps the Codex backend; what the user connected
+ // is their ChatGPT subscription, so the bar names that, not the transport.
+ codex: "chatgpt-sub",
+};
+
+/**
+ * The endpoint reads as the model's routing clause (`via ai-gateway(oidc:…)`),
+ * so it fuses onto the model segment with a plain space instead of standing
+ * behind a `·` separator. Only the disconnected warning stands alone. The
+ * clause is keyed strictly off the credential the AI SDK will actually use —
+ * an `api-key` never shows the linked project, because the link is not what
+ * authenticates the call.
+ */
function renderEndpoint(
input: Pick<StatusLineInput, "endpoint" | "remote" | "theme" | "vercel">,
-): string | undefined {
+): { readonly text: string; readonly standalone: boolean } | undefined {
if (input.remote !== undefined || input.endpoint === undefined) return undefined;
const c = input.theme.colors;
- if (input.endpoint.kind === "external") return c.dim("External endpoint");
- if (!input.endpoint.connected) return c.yellow(`${input.theme.glyph.warning} AI Gateway`);
-
+ const g = input.theme.glyph;
+ // Only the gateway stands at the terminal's DEFAULT foreground — plain,
+ // not bold — while `via` and the credential scope stay dim around it;
+ // external providers render fully quiet. Explicit bright-white (SGR 97)
+ // would vanish on light themes.
+ const clause = (name: string, suffix: string) => `${c.dim("via ")}${name}${c.dim(suffix)}`;
+ if (input.endpoint.kind === "external") {
+ const provider =
+ EXTERNAL_PROVIDER_DISPLAY_NAMES[input.endpoint.provider] ?? input.endpoint.provider;
+ // The `⌝` mark stays at the terminal's default foreground — full
+ // intensity on any theme — while the clause around it is dim.
+ return { text: `${c.dim(`via ${provider}`)}${g.external}`, standalone: false };
+ }
+ if (!input.endpoint.connected) {
+ return { text: c.yellow(`${g.warning} ai-gateway`), standalone: true };
+ }
+ if (input.endpoint.credential === "api-key") {
+ return { text: clause("ai-gateway", "(api-key)"), standalone: false };
+ }
const projectName = input.vercel?.identity?.projectName;
- return c.dim(projectName === undefined ? "AI Gateway" : `AI Gateway (${projectName})`);
+ const scope = projectName === undefined ? "oidc" : `oidc:${projectName}`;
+ return { text: clause("ai-gateway", `(${scope})`), standalone: false };
}
/**
@@ -92,6 +124,12 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
const leading = remote?.full ?? serverPort;
const badge = remote?.badge ?? serverPort;
+ // A routing clause rides the model segment itself; the disconnected
+ // warning (or a clause with no model to attach to) stays its own segment.
+ const fused = endpoint !== undefined && !endpoint.standalone && model !== undefined;
+ const modelSegment = fused ? `${model} ${endpoint.text}` : model;
+ const endpointSegment = endpoint === undefined || fused ? undefined : endpoint.text;
+
// Whitespace separators: the dim segments read as columns without bullets.
const separator = " ";
const compose = (
@@ -107,7 +145,7 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
// leads every variant and gets the final stand-alone fallback. Without one,
// the logs hint retains its previous priority.
const variants = [
- compose(leading, [logLevel, model, endpoint, pending]),
+ compose(leading, [logLevel, modelSegment, endpointSegment, pending]),
compose(leading, [logLevel, model, pending]),
compose(leading, [logLevel, pending]),
compose(leading, [logLevel]),
@@ -119,7 +157,7 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
for (const variant of variants) {
if (variant.length > 0 && visibleLength(variant) <= width) return variant;
}
- // Later variants can be empty, for example when a model-only line has no tokens.
+ // Later variants can be empty, for example when a badge-only line has no hint.
const narrowest = variants.findLast((variant) => variant.length > 0)!;
return clipVisible(narrowest, width);
}
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 9722d4fd2..cf387a0a5 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.test.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
formatCompactTokenCount,
formatTokenFlow,
+ formatTurnDuration,
+ typewriterText,
isIncompletePaste,
nextKey,
parseKey,
@@ -73,6 +75,27 @@ describe("formatTokenFlow", () => {
});
});
+describe("typewriterText", () => {
+ it("reveals one character per step, then holds the full text", () => {
+ expect(typewriterText("Working…", 0, 80)).toBe("W");
+ expect(typewriterText("Working…", 79, 80)).toBe("W");
+ expect(typewriterText("Working…", 160, 80)).toBe("Wor");
+ expect(typewriterText("Working…", 560, 80)).toBe("Working…");
+ expect(typewriterText("Working…", 60_000, 80)).toBe("Working…");
+ });
+});
+
+describe("formatTurnDuration", () => {
+ it("scales through seconds, minutes, and hours", () => {
+ expect(formatTurnDuration(400)).toBe("1s");
+ expect(formatTurnDuration(42_000)).toBe("42s");
+ expect(formatTurnDuration(204_000)).toBe("3min 24s");
+ expect(formatTurnDuration(300_000)).toBe("5min");
+ expect(formatTurnDuration(4_320_000)).toBe("1h 12min");
+ expect(formatTurnDuration(3_600_000)).toBe("1h");
+ });
+});
+
describe("nextKey", () => {
it("decodes a complete CSI arrow sequence", () => {
expect(nextKey("\x1b[A")).toEqual({ key: { type: "up" }, consumed: 3 });
diff --git a/packages/eve/src/cli/dev/tui/stream-format.ts b/packages/eve/src/cli/dev/tui/stream-format.ts
index 8853d180e..86424274a 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.ts
@@ -282,9 +282,36 @@ export function formatCompactTokenCount(count: number): string {
}
/**
- * The status line's token-flow segment: `↑ 394.4K ↓ 4.3K`, input (prompt)
- * tokens up, output tokens down, both from the latest usage report. A known
- * `--context-size` appends the context-fill percentage of the input side.
+ * Reveals `text` one character per `stepMs` of elapsed time, typewriter
+ * style: the first character shows immediately, the full text after
+ * `(length - 1) * stepMs`. Painted on the shared ticker beat, so no timer
+ * of its own.
+ */
+export function typewriterText(text: string, elapsedMs: number, stepMs: number): string {
+ const visible = Math.floor(Math.max(0, elapsedMs) / stepMs) + 1;
+ return visible >= text.length ? text : text.slice(0, visible);
+}
+
+/**
+ * Formats a turn's wall-clock duration for the end-of-turn stats line:
+ * `42s`, `3min 24s`, `1h 12min`. Sub-second turns round up to `1s` — a
+ * `0s` coda would read as a measurement error.
+ */
+export function formatTurnDuration(elapsedMs: number): string {
+ const totalSeconds = Math.max(1, Math.round(elapsedMs / 1000));
+ const seconds = totalSeconds % 60;
+ const totalMinutes = Math.floor(totalSeconds / 60);
+ if (totalMinutes === 0) return `${seconds}s`;
+ const minutes = totalMinutes % 60;
+ const hours = Math.floor(totalMinutes / 60);
+ if (hours === 0) return seconds === 0 ? `${minutes}min` : `${minutes}min ${seconds}s`;
+ return minutes === 0 ? `${hours}h` : `${hours}h ${minutes}min`;
+}
+
+/**
+ * The turn bar and coda's token-flow segment: `↑ 394.4K ↓ 4.3K`, input
+ * (prompt) tokens up, output tokens down. A known `--context-size` appends
+ * the context-fill percentage of the input side.
*/
export function formatTokenFlow(
flow: { inputTokens: number; outputTokens: number; contextSize?: number },
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.ts
new file mode 100644
index 000000000..be56e1967
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts
@@ -0,0 +1,501 @@
+/**
+ * The subagent child-stream subsystem: for every `subagent.called` on the
+ * parent stream, a parallel pump over the child session folds its events
+ * into the renderer's nested subagent view. Extracted from the runner —
+ * the subsystem touches nothing but its own run state, the client, and the
+ * {@link SubagentView} seam.
+ */
+
+import type { Client } from "#client/index.js";
+import {
+ isCurrentTurnBoundaryEvent,
+ type ActionResultStreamEvent,
+ type HandleMessageStreamEvent,
+ type SubagentCalledStreamEvent,
+} from "#protocol/message.js";
+import { toErrorMessage } from "#shared/errors.js";
+
+import { isAbortLikeError } from "./errors.js";
+
+/**
+ * The renderer's subagent surface. One cohesive capability: a renderer that
+ * implements it renders whole sections — header, nested steps and tools,
+ * ghost sweeps, completion — and a renderer without it simply has no
+ * subagent view. Individually-optional methods would let a renderer
+ * implement a type-legal subset that ghosts placeholders or duplicates
+ * parent tool rows.
+ */
+export interface SubagentView {
+ /** Opens a call's section the moment its dispatch is announced. */
+ begin(update: { callId: string; name: string }): void;
+ upsertStep(update: SubagentStepUpdate): void;
+ upsertTool(update: SubagentToolUpdate): void;
+ /** Drops a child tool row whose call never materialized. */
+ removeTool(update: { callId: string; childCallId: string }): void;
+ /** Marks a call complete so its section collapses on `└ Done…`. */
+ complete(update: { callId: string }): void;
+ /** Suppresses the parent-level tool row for a child-owned call id. */
+ markChildToolCallId(callId: string): void;
+}
+
+type SubagentChildStep = {
+ reasoning: string;
+ message: string;
+ finalized: boolean;
+};
+
+type SubagentToolStatus =
+ | "preparing"
+ | "approval-requested"
+ | "executing"
+ | "done"
+ | "failed"
+ | "rejected";
+
+type SubagentToolState = {
+ toolName: string;
+ input: unknown;
+ status: SubagentToolStatus;
+ output?: unknown;
+ errorText?: string;
+};
+
+export type SubagentRun = {
+ name: string;
+ /**
+ * The run's one lifecycle authority. `settled` means the final assistant
+ * message is in (the child's turn boundary, or the parent's
+ * `subagent.completed` fallback); a late child event — a HITL-parked
+ * turn resuming — explicitly reopens the run rather than mutating a
+ * completed section by accident.
+ */
+ status: "running" | "settled";
+ /**
+ * One entry per logical "child message" — independent of the child's
+ * `stepIndex` field, which the harness can reuse across multiple
+ * assistant messages within a turn (e.g. a message before a tool call
+ * and another message after the tool result both arrive under
+ * `stepIndex: 0`). The key is a monotonic counter so each
+ * `message.completed` opens a new box on the next inbound delta.
+ */
+ steps: Map<number, SubagentChildStep>;
+ /**
+ * Section currently accepting reasoning/message deltas. `null` means
+ * the next delta opens a new section.
+ */
+ currentSectionKey: number | null;
+ /** Monotonic counter for new section keys. */
+ nextSectionKey: number;
+ tools: Map<string, SubagentToolState>;
+};
+
+export type SubagentStepUpdate = {
+ callId: string;
+ subagentName: string;
+ sectionKey: number;
+ reasoning: string;
+ message: string;
+ finalized: boolean;
+};
+
+export type SubagentToolUpdate = {
+ callId: string;
+ subagentName: string;
+ childCallId: string;
+ toolName: string;
+ input: unknown;
+ status: SubagentToolStatus;
+ output?: unknown;
+ errorText?: string;
+};
+
+export interface SubagentPumpOptions {
+ client?: Client;
+ view?: SubagentView;
+ formatActionResultError: (event: ActionResultStreamEvent) => string;
+}
+
+export class SubagentPump {
+ readonly #client: Client | undefined;
+ readonly #view: SubagentView | undefined;
+ readonly #formatActionResultError: (event: ActionResultStreamEvent) => string;
+ readonly #runs = new Map<string, SubagentRun>();
+ readonly #pumps = new Map<string, AbortController>();
+
+ constructor(options: SubagentPumpOptions) {
+ this.#client = options.client;
+ this.#view = options.view;
+ this.#formatActionResultError = options.formatActionResultError;
+ }
+
+ /**
+ * The moment a dispatch is known to be a subagent call, its section
+ * header replaces the parent-level tool row (or its still-preparing
+ * placeholder — subagent dispatches never upgrade one, since their
+ * actions are not tool-call kind). Without this the placeholder is
+ * swept at the step boundary and nothing shows until the child's first
+ * content arrives. Idempotent for SSE-resume re-entries, which only
+ * refresh the name.
+ */
+ begin(called: SubagentCalledStreamEvent): void {
+ const callId = called.data.callId;
+ const existing = this.#runs.get(callId);
+ if (existing === undefined) {
+ this.#runs.set(callId, {
+ name: called.data.name,
+ status: "running",
+ steps: new Map(),
+ currentSectionKey: null,
+ nextSectionKey: 0,
+ tools: new Map(),
+ });
+ } else {
+ existing.name = called.data.name;
+ }
+ this.#view?.markChildToolCallId(callId);
+ this.#view?.begin({ callId, name: called.data.name });
+ this.#startPump(called);
+ }
+
+ /**
+ * Parent reports subagent.completed. The child stream pump terminates
+ * itself on the child's own turn boundary — the authoritative finish
+ * signal, which already finalized the section — so this is a fallback
+ * for runs whose boundary never reached us (a dropped child stream, a
+ * HITL-parked turn resuming later). We do NOT abort the pump here,
+ * because the child's `message.completed` event may still be in flight
+ * (the parent and child streams are independent HTTP connections).
+ */
+ settle(callId: string): void {
+ this.#finalizeRun(callId);
+ }
+
+ abortAll(): void {
+ for (const controller of this.#pumps.values()) {
+ controller.abort();
+ }
+ this.#pumps.clear();
+ this.#runs.clear();
+ }
+
+ /**
+ * Opens a parallel stream over the child session and folds its events into
+ * nested subagent blocks.
+ *
+ * Pumps are fire-and-forget and must never be awaited at a turn boundary:
+ * a subagent dispatched in `task` mode that parks for HITL never emits a
+ * turn-boundary event on its own stream (`harness/tool-loop.ts` gates
+ * `emitTurnEpilogue` on `mode === "conversation"`), so blocking on a child
+ * stream would stall the prompt until the subagent's serverless function
+ * times out. Pumps stay open across HITL prompts and resume rendering when
+ * the subagent unparks; they end on the child's own boundary or via abort.
+ */
+ #startPump(called: SubagentCalledStreamEvent) {
+ const callId = called.data.callId;
+ if (this.#pumps.has(callId)) return;
+ const client = this.#client;
+ if (!client) return;
+
+ const controller = new AbortController();
+ this.#pumps.set(callId, controller);
+
+ void (async () => {
+ let boundaryReached = false;
+ try {
+ const childSession = client.session({
+ sessionId: called.data.childSessionId,
+ streamIndex: 0,
+ });
+ const stream = childSession.stream({ signal: controller.signal });
+ for await (const event of stream) {
+ if (controller.signal.aborted) break;
+ this.#applyChildEvent(callId, event);
+ if (isCurrentTurnBoundaryEvent(event)) {
+ // The child's own turn boundary — its final assistant message
+ // is in — is what finishes the section. The parent's
+ // `subagent.completed` arrives independently (often later, once
+ // the parent's turn resumes) and only acts as a fallback.
+ boundaryReached = true;
+ break;
+ }
+ }
+ } catch (error) {
+ if (!isAbortLikeError(error)) {
+ const errorText = toErrorMessage(error);
+ const run = this.#runs.get(callId);
+ if (run) {
+ const { key, step } = openCurrentSubagentSection(run);
+ step.message = step.message
+ ? `${step.message}\n\nstream error: ${errorText}`
+ : `stream error: ${errorText}`;
+ step.finalized = true;
+ run.currentSectionKey = null;
+ this.#view?.upsertStep({
+ callId,
+ subagentName: run.name,
+ sectionKey: key,
+ reasoning: step.reasoning,
+ message: step.message,
+ finalized: true,
+ });
+ }
+ }
+ } finally {
+ this.#pumps.delete(callId);
+ }
+ if (boundaryReached) this.#finalizeRun(callId);
+ })();
+ }
+
+ #registerChildTool(
+ callId: string,
+ run: SubagentRun,
+ request: {
+ childCallId: string;
+ toolName: string;
+ input: unknown;
+ status: SubagentToolState["status"];
+ },
+ ): void {
+ const existing = run.tools.get(request.childCallId);
+ const tool: SubagentToolState = existing ?? {
+ toolName: request.toolName,
+ input: request.input,
+ status: request.status,
+ };
+ if (existing) {
+ // Promote status only when the new status is "stronger" — e.g.
+ // approval-requested → executing once the parent approves, but
+ // never demote from done/failed back to executing.
+ const priority: Record<SubagentToolState["status"], number> = {
+ preparing: 0,
+ "approval-requested": 1,
+ executing: 2,
+ done: 3,
+ failed: 3,
+ rejected: 3,
+ };
+ if (priority[request.status] > priority[existing.status]) {
+ existing.status = request.status;
+ }
+ // A late `preparing` announcement must not wipe input the full call
+ // already delivered.
+ if (request.input !== undefined) {
+ existing.input = request.input;
+ }
+ } else {
+ run.tools.set(request.childCallId, tool);
+ }
+ this.#view?.markChildToolCallId(request.childCallId);
+ this.#view?.upsertTool({
+ callId,
+ subagentName: run.name,
+ childCallId: request.childCallId,
+ toolName: tool.toolName,
+ input: tool.input,
+ status: tool.status,
+ });
+ }
+
+ /**
+ * Settles a subagent section: re-emits a finalized snapshot for any
+ * still-streaming step (flipping its right-title off `streaming`), sweeps
+ * preparing ghosts, and marks the section Done. The run's status field is
+ * the idempotency authority — the child's turn boundary and the parent's
+ * `subagent.completed` can both land here.
+ */
+ #finalizeRun(callId: string): void {
+ const run = this.#runs.get(callId);
+ if (!run || run.status === "settled") return;
+ run.status = "settled";
+ for (const [sectionKey, step] of run.steps) {
+ if (!step.finalized) {
+ step.finalized = true;
+ this.#view?.upsertStep({
+ callId,
+ subagentName: run.name,
+ sectionKey,
+ reasoning: step.reasoning,
+ message: step.message,
+ finalized: true,
+ });
+ }
+ }
+ run.currentSectionKey = null;
+ this.#sweepPreparingTools(callId, run);
+ this.#view?.complete({ callId });
+ }
+
+ /**
+ * Drops child tool placeholders that never left `preparing` — their input
+ * never parsed (the child model emitted bad JSON, or the stream ended
+ * mid-generation), so no upgrade is coming and the row would linger as a
+ * `Search …` ghost inside the section.
+ */
+ #sweepPreparingTools(callId: string, run: SubagentRun): void {
+ for (const [childCallId, tool] of run.tools) {
+ if (tool.status !== "preparing") continue;
+ run.tools.delete(childCallId);
+ this.#view?.removeTool({ callId, childCallId });
+ }
+ }
+
+ #applyChildEvent(callId: string, event: HandleMessageStreamEvent) {
+ const run = this.#runs.get(callId);
+ if (!run) return;
+ // A child event after settle is a HITL-parked turn resuming: reopen the
+ // run explicitly (begin clears the header's Done mark) instead of
+ // mutating a completed section by accident.
+ if (run.status === "settled") {
+ run.status = "running";
+ this.#view?.begin({ callId, name: run.name });
+ }
+ const view = this.#view;
+
+ const emit = (key: number, step: SubagentChildStep) => {
+ view?.upsertStep({
+ callId,
+ subagentName: run.name,
+ sectionKey: key,
+ reasoning: step.reasoning,
+ message: step.message,
+ finalized: step.finalized,
+ });
+ };
+
+ const finalizeCurrent = () => {
+ if (run.currentSectionKey === null) return;
+ const step = run.steps.get(run.currentSectionKey);
+ if (step) {
+ step.finalized = true;
+ emit(run.currentSectionKey, step);
+ }
+ run.currentSectionKey = null;
+ };
+
+ switch (event.type) {
+ case "reasoning.appended": {
+ const { key, step } = openCurrentSubagentSection(run);
+ step.reasoning = step.reasoning + event.data.reasoningDelta;
+ emit(key, step);
+ break;
+ }
+ case "reasoning.completed":
+ // Reasoning closes within a section but does not close the section
+ // itself — a following `message.appended` should land in the same
+ // box. The section closes on `message.completed` or
+ // `step.completed`.
+ break;
+ case "message.appended": {
+ const { key, step } = openCurrentSubagentSection(run);
+ step.message = step.message + event.data.messageDelta;
+ emit(key, step);
+ break;
+ }
+ case "message.completed": {
+ const { key, step } = openCurrentSubagentSection(run);
+ if (event.data.message !== null && step.message.length === 0) {
+ // Some channels emit only `message.completed` without per-delta
+ // `message.appended` events. Capture the full text in that case.
+ step.message = event.data.message;
+ }
+ step.finalized = true;
+ emit(key, step);
+ run.currentSectionKey = null;
+ break;
+ }
+ case "step.completed":
+ finalizeCurrent();
+ // A valid child call upgrades from `preparing` within its own step;
+ // one still preparing at the boundary never parsed and would linger
+ // as a placeholder ghost in the section.
+ this.#sweepPreparingTools(callId, run);
+ break;
+ case "actions.requested": {
+ // Close any pending text section before the tool call so the
+ // tool box renders below it — and the next post-tool message
+ // opens a fresh section.
+ finalizeCurrent();
+ for (const action of event.data.actions) {
+ if (action.kind !== "tool-call") continue;
+ this.#registerChildTool(callId, run, {
+ childCallId: action.callId,
+ toolName: action.toolName,
+ input: action.input,
+ status: "executing",
+ });
+ }
+ break;
+ }
+ case "input.requested": {
+ // Tools that need approval skip `actions.requested` and arrive
+ // here as `input.requested` with the action embedded. Register
+ // the tool section the same way (status: "approval-requested")
+ // so the parent's stale tool box can be suppressed and the
+ // child tool appears under the subagent flow.
+ finalizeCurrent();
+ for (const request of event.data.requests) {
+ if (request.action.kind !== "tool-call") continue;
+ this.#registerChildTool(callId, run, {
+ childCallId: request.action.callId,
+ toolName: request.action.toolName,
+ input: request.action.input,
+ status: "approval-requested",
+ });
+ }
+ break;
+ }
+ case "action.result": {
+ const result = event.data.result;
+ if (result.kind !== "tool-result") break;
+ const tool = run.tools.get(result.callId);
+ if (!tool) break;
+ switch (event.data.status) {
+ case "completed":
+ tool.status = "done";
+ tool.output = result.output;
+ break;
+ case "failed":
+ tool.status = "failed";
+ tool.errorText = this.#formatActionResultError(event);
+ break;
+ case "rejected":
+ tool.status = "rejected";
+ tool.errorText = this.#formatActionResultError(event);
+ break;
+ }
+ const update: SubagentToolUpdate = {
+ callId,
+ subagentName: run.name,
+ childCallId: result.callId,
+ toolName: tool.toolName,
+ input: tool.input,
+ status: tool.status,
+ };
+ if (tool.output !== undefined) update.output = tool.output;
+ if (tool.errorText !== undefined) update.errorText = tool.errorText;
+ view?.upsertTool(update);
+ break;
+ }
+ default:
+ // Other events (session.*, turn.*, step.started, etc.) carry no
+ // visible text — ignore.
+ break;
+ }
+ }
+}
+
+function openCurrentSubagentSection(run: SubagentRun): {
+ key: number;
+ step: SubagentChildStep;
+} {
+ if (run.currentSectionKey === null) {
+ run.currentSectionKey = run.nextSectionKey++;
+ run.steps.set(run.currentSectionKey, { reasoning: "", message: "", finalized: false });
+ }
+ const step = run.steps.get(run.currentSectionKey);
+ if (!step) {
+ throw new Error("invariant: subagent section state missing for current key");
+ }
+ return { key: run.currentSectionKey, step };
+}
diff --git a/packages/eve/src/cli/dev/tui/subagent-section.test.ts b/packages/eve/src/cli/dev/tui/subagent-section.test.ts
new file mode 100644
index 000000000..2746749d7
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/subagent-section.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+
+import { renderBlockLines, type Block } from "./blocks.js";
+import { groupToolBlocksForDisplay } from "./tool-block-groups.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
+import { createTheme } from "./theme.js";
+
+const theme = createTheme({ color: false, unicode: true });
+
+describe("subagent section rendering", () => {
+ it("renders a settled section MRU-down with grouped errors and a closing corner", () => {
+ const call = "call-3";
+ const tool = (over: Partial<Block>): Block => ({
+ kind: "subagent-tool",
+ subagentCallId: call,
+ depth: 1,
+ live: false,
+ status: "done",
+ ...over,
+ });
+ const search = (n: number) =>
+ tool({
+ title: `Search q${n}`,
+ toolName: "web_search",
+ toolGroup: {
+ verb: "Search",
+ pastVerb: "Searched",
+ singularNoun: "query",
+ pluralNoun: "queries",
+ item: `q${n}`,
+ },
+ });
+ const fetchTool = (n: number, over: Partial<Block> = {}) =>
+ tool({
+ title: `Fetch url${n}`,
+ toolName: "fetch_url",
+ toolGroup: {
+ verb: "Fetch",
+ pastVerb: "Fetched",
+ singularNoun: "URL",
+ pluralNoun: "URLs",
+ item: `url${n}`,
+ },
+ ...over,
+ });
+
+ const blocks: Block[] = [
+ { kind: "subagent", subagentCallId: call, title: "agent", subtitle: "#3", live: true },
+ ...Array.from({ length: 10 }, (_, i) => search(i)),
+ fetchTool(1),
+ fetchTool(2),
+ fetchTool(3),
+ fetchTool(99, { status: "error", result: "Response too large (exceeds 5 MB limit)." }),
+ tool({ title: "Update todo list", subtitle: "3 tasks", toolName: "todo" }),
+ {
+ kind: "subagent-step",
+ subagentCallId: call,
+ depth: 1,
+ body: "# Vercel eve competitive capability comparison",
+ collapsed: true,
+ live: false,
+ },
+ ];
+
+ // The renderer stamps every block it pushes; mirror that here so the
+ // MRU window has real recency to rank on.
+ blocks.forEach((block, index) => {
+ block.updateSeq = index + 1;
+ });
+ const rows = groupToolBlocksForDisplay(blocks).flatMap((group) =>
+ renderBlockLines(group.display, 78, theme, { activityPulse: "▪" }).map(stripAnsi),
+ );
+
+ // A live section shows only its most recently active row; everything
+ // earlier waits behind the elision (the completed footnote carries the
+ // full counted story).
+ expect(rows).toEqual([
+ " ※ subagent(self:3)",
+ " │ … (15 more)",
+ " └ # Vercel eve competitive capability comparison",
+ ]);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 28cbcaeb9..afe52441f 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -10,8 +10,9 @@ import {
formatChangeDetectedLogLine,
} from "#internal/nitro/host/dev-watcher-log.js";
-import type { AgentTUIStreamEvent, AgentTUIStreamResult } from "./runner.js";
+import type { AgentTUIStreamEvent, AgentTUIStreamResult, SubagentToolUpdate } from "./runner.js";
import { promptCommandsFor } from "./prompt-commands.js";
+import { PROMPT_PLACEHOLDER_MESSAGES } from "./prompt-placeholder.js";
import { TerminalRenderer } from "./terminal-renderer.js";
import { MockScreen, MockUserInput } from "./test/mock-terminal.js";
@@ -145,6 +146,28 @@ function agentInfoWithModel(
}
describe("TerminalRenderer (inline scrollback)", () => {
+ it("prints the dim wordmark tag as the parting line after a Ctrl-C exit", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const prompt = renderer.readPrompt();
+ // Ctrl-C at the prompt restores the terminal inside the reader itself;
+ // the runner's teardown-time shutdown() must still print the tag.
+ input.ctrlC();
+ await expect(prompt).rejects.toThrow("Interrupted");
+ renderer.shutdown();
+
+ const lines = screen.snapshot().trimEnd().split("\n");
+ expect(lines.at(-1)).toMatch(/^☰eve {2}v\d+\.\d+\.\d+/u);
+ expect(screen.rawOutput()).toContain(`\x1b[2m☰eve v`);
+ // Once, ever — repeated teardown must not repeat the tag.
+ renderer.shutdown();
+ expect(screen.snapshot().match(/☰eve/gu)).toHaveLength(1);
+
+ // A renderer that never went live exits silently.
+ const idle = makeRenderer();
+ idle.renderer.shutdown();
+ expect(idle.screen.snapshot()).not.toContain("☰eve");
+ });
+
it("renders the brand line with the agent name and a tip", () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({
@@ -222,6 +245,178 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot).toContain("It's 73°F in SF.");
});
+ it("renders rejected tools as denied", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "bash",
+ input: { command: "rm something" },
+ },
+ { type: "tool-rejected", toolCallId: "c1", reason: "Denied by user." },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "remove it", continueSession: false },
+ );
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("Run rm something");
+ expect(snapshot).toContain("denied");
+ expect(snapshot).not.toContain("✓ Run");
+ renderer.shutdown();
+ });
+
+ it("renders web_fetch as a concise semantic activity", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "fetch-1",
+ toolName: "web_fetch",
+ input: {
+ format: "markdown",
+ url: "https://github.com/vercel/eve/issues/648",
+ },
+ },
+ {
+ type: "tool-result",
+ toolCallId: "fetch-1",
+ output: { content: "large fetched page" },
+ },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "fetch the issue", continueSession: false },
+ );
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("Fetched https://github.com/vercel/eve/issues/648");
+ expect(snapshot).not.toContain("format=markdown");
+ expect(snapshot).not.toContain("large fetched page");
+ renderer.shutdown();
+ });
+
+ it("coalesces a same-status fetch cohort without merging call state", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "fetch-1",
+ toolName: "web_fetch",
+ input: { url: "https://one.example" },
+ },
+ {
+ type: "tool-call",
+ toolCallId: "fetch-2",
+ toolName: "web_fetch",
+ input: { url: "https://two.example" },
+ },
+ { type: "tool-result", toolCallId: "fetch-1", output: { content: "one" } },
+ { type: "tool-result", toolCallId: "fetch-2", output: { content: "two" } },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "call fetch twice in parallel", continueSession: false },
+ );
+
+ const snapshot = screen.snapshot();
+ // A fully settled batch collapses to one past-tense line; the item rail
+ // is gone from the transcript.
+ expect(snapshot).toContain("│ call fetch twice in parallel\n\n ▪ Fetched 2 URLs");
+ expect(snapshot).not.toContain("https://one.example");
+ expect(snapshot).not.toContain("https://two.example");
+ renderer.shutdown();
+ });
+
+ it("partitions a fetch cohort with interleaved failures into per-outcome groups", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "fetch-1",
+ toolName: "web_fetch",
+ input: { url: "https://one.example" },
+ },
+ {
+ type: "tool-call",
+ toolCallId: "fetch-2",
+ toolName: "web_fetch",
+ input: { url: "https://two.example" },
+ },
+ {
+ type: "tool-call",
+ toolCallId: "fetch-3",
+ toolName: "web_fetch",
+ input: { url: "https://three.example" },
+ },
+ {
+ type: "tool-call",
+ toolCallId: "fetch-4",
+ toolName: "web_fetch",
+ input: { url: "https://four.example" },
+ },
+ { type: "tool-result", toolCallId: "fetch-1", output: { content: "one" } },
+ { type: "tool-error", toolCallId: "fetch-2", errorText: "status 403" },
+ { type: "tool-result", toolCallId: "fetch-3", output: { content: "three" } },
+ { type: "tool-error", toolCallId: "fetch-4", errorText: "status 429" },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "fetch four urls", continueSession: false },
+ );
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ // Successes collapse to a counted past-tense line; failures keep their
+ // itemized rail, newest call first, closed by the corner.
+ expect(snapshot).toContain("▪ Fetched 2 URLs");
+ expect(snapshot).not.toContain("https://one.example");
+ expect(snapshot).toContain(
+ " ⨯ Fetch 2 URLs\n │ https://four.example status 429\n │ https://two.example status 403\n └",
+ );
+ });
+
+ it("renders a write as an all-added diff for a new file and a real diff after a read", async () => {
+ const { screen, renderer } = makeRenderer(120, 60);
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "write-1",
+ toolName: "write_file",
+ input: { filePath: "/workspace/knicks.txt", content: "knicks\n" },
+ },
+ {
+ type: "tool-result",
+ toolCallId: "write-1",
+ output: { existed: false, path: "/workspace/knicks.txt" },
+ },
+ {
+ type: "tool-call",
+ toolCallId: "write-2",
+ toolName: "write_file",
+ input: { filePath: "/workspace/knicks.txt", content: "knicks\nnets\n" },
+ },
+ {
+ type: "tool-result",
+ toolCallId: "write-2",
+ output: { existed: true, path: "/workspace/knicks.txt" },
+ },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "write the teams", continueSession: false },
+ );
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ // First write: the file did not exist, so its content is all additions.
+ expect(snapshot).toContain(" ▪ Wrote /workspace/knicks.txt\n │+ knicks\n └");
+ // Second write diffs against the first write's cached content.
+ expect(snapshot).toContain(" │ knicks\n │+ nets\n └");
+ });
+
it("renders interleaved tool lifecycles in arrival order", async () => {
const { screen, renderer } = makeRenderer();
await renderer.renderStream(
@@ -246,9 +441,9 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
const snapshot = screen.snapshot();
- expect(snapshot).toContain("✓ first_search");
+ expect(snapshot).toContain("▪ first_search");
expect(snapshot).toContain("first result");
- expect(snapshot).toContain("✓ second_search");
+ expect(snapshot).toContain("▪ second_search");
expect(snapshot).toContain("second result");
expect(snapshot.indexOf("first_search")).toBeLessThan(snapshot.indexOf("second_search"));
renderer.shutdown();
@@ -280,17 +475,87 @@ describe("TerminalRenderer (inline scrollback)", () => {
});
}
- await screen.waitForText("tri-state-100");
+ await screen.waitForText("Search 100 queries");
const snapshot = screen.snapshot();
- expect(snapshot.match(/web_search/g)).toHaveLength(100);
- expect(snapshot).not.toContain("✓ web_search");
+ // Semantic copy coalesces the running batch into one counted row that
+ // lists the newest calls first and elides the rest; nothing may render
+ // as completed yet.
+ expect(snapshot.match(/tri-state-\d+/g)).toHaveLength(5);
+ expect(snapshot).toContain("tri-state-100");
+ expect(snapshot).toContain("(95 more)");
+ expect(snapshot).not.toContain("Searched");
+ expect(snapshot).not.toContain("web_search");
controller?.close();
await rendering;
renderer.shutdown();
});
+ it("shows a placeholder while a call's input streams, then upgrades it in place", async () => {
+ const { screen, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "fetch the page", continueSession: true },
+ );
+
+ const controller = streamController;
+ controller?.enqueue({ type: "step-start" });
+ controller?.enqueue({ type: "tool-call-preparing", toolCallId: "c1", toolName: "web_fetch" });
+ await screen.waitForText("Fetch …");
+
+ controller?.enqueue({
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "web_fetch",
+ input: { url: "https://example.com" },
+ });
+ await screen.waitForText("Fetch https://example.com");
+
+ const snapshot = screen.snapshot();
+ // The placeholder upgraded in place: one block, no leftover "Fetch …" row.
+ expect(snapshot).not.toContain("Fetch …");
+ expect(countOccurrences(snapshot, "Fetch https://example.com")).toBe(1);
+
+ controller?.close();
+ await rendering;
+ renderer.shutdown();
+ });
+
+ it("renders a preparing subagent tool row and upgrades it with the full call", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ renderer.upsertSubagentTool({
+ callId: "s1",
+ subagentName: "researcher",
+ childCallId: "cc1",
+ toolName: "web_fetch",
+ input: undefined,
+ status: "preparing",
+ });
+ expect(screen.snapshot()).toContain("Fetch …");
+
+ renderer.upsertSubagentTool({
+ callId: "s1",
+ subagentName: "researcher",
+ childCallId: "cc1",
+ toolName: "web_fetch",
+ input: { url: "https://example.com" },
+ status: "executing",
+ });
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("Fetch https://example.com");
+ expect(snapshot).not.toContain("Fetch …");
+ renderer.shutdown();
+ });
+
it("omits the interrupt hint while waiting for the first stream event", async () => {
const { screen, renderer } = makeRenderer();
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
@@ -306,7 +571,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await Promise.resolve();
- expect(screen.snapshot()).toContain("Working…");
+ expect(screen.snapshot()).toContain("W 1s");
expect(screen.snapshot()).not.toContain("Ctrl+C to interrupt");
streamController?.close();
@@ -330,14 +595,15 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await Promise.resolve();
- expect(screen.snapshot()).toContain("Waiting for connection authorization…");
+ // The bar renders; connection state lives in its own section.
+ expect(screen.snapshot()).toContain("W 1s");
streamController?.close();
await rendering;
renderer.shutdown();
});
- it("uses the turn pulse while waiting for the first stream event", async () => {
+ it("shows the live turn bar while waiting for the first stream event", async () => {
vi.useFakeTimers();
try {
const { screen, renderer } = makeRenderer();
@@ -360,18 +626,23 @@ describe("TerminalRenderer (inline scrollback)", () => {
await Promise.resolve();
let lines = screen.snapshot().split("\n");
- let workingRow = lines.findIndex((line) => line === " ⊙ Working…");
- expect(workingRow).toBeGreaterThan(-1);
- expect(lines[workingRow + 1]).toBe("");
- expect(lines[workingRow + 2]).toContain("gpt-5");
-
- vi.advanceTimersByTime(450);
- expect(screen.snapshot()).not.toContain("⊙ Working…");
+ // The label types itself out: one character at t=0.
+ let barRow = lines.findIndex((line) => line === "▪ W 1s");
+ expect(barRow).toBeGreaterThan(-1);
+ // The pending prompt row wears the same quiet `›` as the idle one
+ // beneath the bar; the status line follows it.
+ expect(lines[barRow + 1]).toBe("");
+ expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 4]).toContain("gpt-5");
+
+ // The duration ticks live while the pulse blinks on the shared beat.
+ await vi.advanceTimersByTimeAsync(2_000);
lines = screen.snapshot().split("\n");
- workingRow = lines.findIndex((line) => line === " Working…");
- expect(workingRow).toBeGreaterThan(-1);
- expect(lines[workingRow + 1]).toBe("");
- expect(lines[workingRow + 2]).toContain("gpt-5");
+ // Fully revealed once the reveal window has passed.
+ barRow = lines.findIndex((line) => line.includes("Working for 2s"));
+ expect(barRow).toBeGreaterThan(-1);
+ expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 4]).toContain("gpt-5");
streamController?.close();
await rendering;
@@ -396,7 +667,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
input.enter();
expect(await prompt).toBe("hello");
- expect(screen.snapshot()).toContain(" o Working…");
+ expect(screen.snapshot()).toContain("* W 1s");
expect(screen.snapshot()).not.toContain("⊙");
renderer.shutdown();
});
@@ -632,8 +903,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
]),
{ submittedPrompt: "list files", continueSession: true },
);
- expect(screen.snapshot()).toContain("bash");
- expect(screen.snapshot()).not.toContain("✓ bash");
+ expect(screen.snapshot()).toContain("Run ls");
+ expect(screen.snapshot()).not.toContain("Ran ls");
await renderer.renderStream(
streamOf([
@@ -649,7 +920,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
const snapshot = screen.snapshot();
- expect(snapshot).toContain("✓ bash");
+ expect(snapshot).toContain("▪ Ran ls");
});
it("settles an authorization block when its callback arrives in a later stream pass", async () => {
@@ -812,12 +1083,280 @@ describe("TerminalRenderer (inline scrollback)", () => {
});
const snapshot = screen.snapshot();
- expect(snapshot).toContain("researcher");
- expect(snapshot).toContain("subagent");
+ expect(snapshot).toContain("※ subagent(researcher)");
expect(snapshot).toContain("get_weather");
renderer.shutdown();
});
+ it("swaps a dispatch's preparing placeholder for the section header", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { continueSession: true },
+ );
+
+ // The model commits to the `agent` tool; its input streams.
+ streamController?.enqueue({
+ type: "tool-call-preparing",
+ toolCallId: "sub1",
+ toolName: "agent",
+ });
+ await screen.waitForText("Delegate");
+
+ // Subagent dispatches never upgrade the placeholder (their actions are
+ // not tool-call kind) — subagent.called supersedes it with the section.
+ renderer.markChildToolCallId("sub1");
+ renderer.beginSubagent({ callId: "sub1", name: "agent" });
+ await screen.waitForText("※ subagent(self)");
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("※ subagent(self)");
+ expect(snapshot).not.toContain("Delegate");
+
+ streamController?.close();
+ await rendering;
+ renderer.shutdown();
+
+ // The step-boundary ghost sweep must not take the section with it.
+ expect(screen.snapshot()).toContain("※ subagent(self)");
+ });
+
+ it("windows subagent children by latest activity, not announce order", () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+
+ // A parallel batch: every call announced up front…
+ const names = ["web_fetch", "web_search", "bash", "read_file"];
+ const upsert = (i: number, status: "executing" | "done") => {
+ const update: SubagentToolUpdate = {
+ callId: "s1",
+ subagentName: "agent",
+ childCallId: `c${i}`,
+ toolName: names[i % names.length]!,
+ input: { url: `u${i}`, query: `q${i}`, command: `cmd${i}`, filePath: `f${i}` },
+ status,
+ };
+ if (status === "done") update.output = { ok: true };
+ renderer.upsertSubagentTool(update);
+ };
+ for (let i = 1; i <= 8; i += 1) upsert(i, "executing");
+ // …then the FIRST two settle: they are the most recent activity and
+ // must enter the window, displacing later-announced idle calls.
+ upsert(1, "done");
+ upsert(2, "done");
+
+ const snapshot = screen.snapshot();
+ // The window is the single most recently active call — c2 settled last.
+ expect(snapshot).toContain("Ran cmd2");
+ expect(snapshot).toContain("(7 more)");
+ expect(snapshot).not.toContain("cmd6");
+ renderer.shutdown();
+ });
+
+ it("collapses a completed section to its Done header and activity footnote", () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ renderer.upsertSubagentStep({
+ callId: "s1",
+ subagentName: "echo-marker",
+ sectionKey: 0,
+ reasoning: "",
+ message: "SUBAGENT_TOKEN=echo-marker-9F2X",
+ finalized: true,
+ });
+ renderer.upsertSubagentTool({
+ callId: "s1",
+ subagentName: "echo-marker",
+ childCallId: "cc1",
+ toolName: "web_fetch",
+ input: { url: "https://one.example" },
+ status: "done",
+ output: { ok: true },
+ });
+
+ // Mid-flight the section shows its newest child and closes on a bare
+ // corner (the tool arrived after the message, so it holds the window).
+ expect(screen.snapshot()).toContain("Fetched https://one.example");
+ expect(screen.snapshot()).not.toContain("Done");
+
+ renderer.completeSubagent({ callId: "s1" });
+ const snapshot = screen.snapshot();
+ // Completed: the corner reports Done with the counted footnote and the
+ // children fold away — the parent's reply carries the conclusion.
+ expect(snapshot).toContain("※ subagent(echo-marker)");
+ expect(snapshot).toContain(" └ Done. Fetched 1 URL");
+ expect(snapshot).not.toContain("SUBAGENT_TOKEN=echo-marker-9F2X");
+ renderer.shutdown();
+ });
+
+ it("renders parallel calls to the same subagent as ordinal-numbered sections", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const calls = [
+ ["s1", "echo-marker-1"],
+ ["s2", "echo-marker-2"],
+ ["s3", "echo-marker-3"],
+ ] as const;
+ for (const finalized of [false, true]) {
+ for (const [callId, token] of calls) {
+ renderer.upsertSubagentStep({
+ callId,
+ subagentName: "echo-marker",
+ sectionKey: 0,
+ reasoning: "",
+ message: `SUBAGENT_TOKEN=${token}`,
+ finalized,
+ });
+ }
+ }
+ await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ // Each call keeps its own persistent section, told apart by ordinal.
+ expect(countOccurrences(snapshot, "※ subagent(echo-marker:")).toBe(3);
+ expect(snapshot).toContain("※ subagent(echo-marker:1)");
+ expect(snapshot).toContain("※ subagent(echo-marker:2)");
+ expect(snapshot).toContain("※ subagent(echo-marker:3)");
+ expect(snapshot).toContain("SUBAGENT_TOKEN=echo-marker-1");
+ expect(snapshot).toContain("SUBAGENT_TOKEN=echo-marker-2");
+ expect(snapshot).toContain("SUBAGENT_TOKEN=echo-marker-3");
+ });
+
+ it("windows one subagent's children to the most recent row", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ for (let step = 1; step <= 8; step += 1) {
+ renderer.upsertSubagentStep({
+ callId: "s1",
+ subagentName: "echo-marker",
+ sectionKey: step,
+ reasoning: "",
+ message: `SUBAGENT_TOKEN=token-${step}`,
+ finalized: true,
+ });
+ }
+ await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ expect(countOccurrences(snapshot, "※ subagent(echo-marker)")).toBe(1);
+ // A lone call carries no ordinal; only the newest child row shows.
+ expect(snapshot).not.toContain("#1");
+ expect(snapshot).toContain("(7 more)");
+ expect(snapshot).not.toContain("SUBAGENT_TOKEN=token-7");
+ expect(snapshot).toContain("SUBAGENT_TOKEN=token-8");
+ });
+
+ it("commits the one-line session boundary", () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderNotice("anchor");
+ renderer.renderSessionBoundary();
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("┌── Session restarted, clear context.");
+ });
+
+ it("closes the dying turn's coda and dismisses the todo panel at the boundary", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const prompt = renderer.readPrompt();
+ input.type("hey agent");
+ input.enter();
+ expect(await prompt).toBe("hey agent");
+
+ await renderer.renderStream(
+ streamOf([
+ { type: "step-start" },
+ {
+ type: "tool-call",
+ toolCallId: "t1",
+ toolName: "todo",
+ input: {
+ todos: [
+ { content: "first task", status: "in_progress" },
+ { content: "second task", status: "pending" },
+ ],
+ },
+ },
+ { type: "assistant-delta", id: "m1", delta: "working" },
+ { type: "assistant-complete", id: "m1" },
+ { type: "step-finish", usage: { inputTokens: 25_000, outputTokens: 40 } },
+ { type: "finish", usage: { inputTokens: 25_000, outputTokens: 40 } },
+ ]),
+ { continueSession: true },
+ );
+ expect(screen.snapshot()).toContain("first task");
+
+ renderer.renderSessionBoundary();
+ const snapshot = screen.snapshot();
+ // The dead turn's stats close before the boundary, not after it…
+ expect(snapshot.indexOf("└ Done in")).toBeGreaterThan(-1);
+ expect(snapshot.indexOf("└ Done in")).toBeLessThan(snapshot.indexOf("┌── Session restarted"));
+ // …and the discarded session's plan dismisses instead of lingering.
+ expect(snapshot).not.toContain("first task");
+
+ // Control returning to the prompt must not add a second coda.
+ const second = renderer.readPrompt();
+ expect(countOccurrences(screen.snapshot(), "└ Done in")).toBe(1);
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
+ renderer.shutdown();
+ });
+
+ it("shows a typed mid-stream draft behind a dim inert prompt mark", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "hello", continueSession: true },
+ );
+ await Promise.resolve();
+
+ // Empty: the quiet idle mark.
+ expect(screen.snapshot()).toContain("›");
+
+ // A typed draft flips to the active mark, but dim — Enter is inert, so
+ // the cyan ready state would overclaim.
+ input.type("next question");
+ await screen.waitForText("❯ next question");
+ expect(screen.rawOutput()).toContain("\x1b[2m❯\x1b[22m");
+ expect(screen.rawOutput()).not.toContain("\x1b[36m❯");
+
+ streamController?.close();
+ await rendering;
+ renderer.shutdown();
+ });
+
+ it("never submits an empty or whitespace-only prompt", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.enter();
+ input.type(" ");
+ input.enter();
+ // The reader is still armed: only real content resolves it.
+ input.type("hello");
+ input.enter();
+ expect(await prompt).toBe(" hello");
+ renderer.shutdown();
+ });
+
it("recalls a previous prompt with the up arrow", async () => {
const { input, renderer } = makeRenderer();
@@ -853,67 +1392,235 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.renderSetupWarning("1 setup issue: not logged in · /vc:login");
expect(screen.snapshot()).toContain("not logged in");
- renderer.clearSetupWarning();
- expect(screen.snapshot()).not.toContain("not logged in");
+ renderer.clearSetupWarning();
+ expect(screen.snapshot()).not.toContain("not logged in");
+ renderer.shutdown();
+ });
+
+ it("hangs a command outcome under its invocation with the elbow connector", () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderCommandResult("/model dismissed.");
+ renderer.shutdown();
+
+ expect(screen.snapshot()).toContain("\u23bf /model dismissed.");
+ });
+
+ it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderCommandInvocation("/vc:login", "failed");
+ renderer.renderCommandResult(
+ "Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" +
+ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",
+ );
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("│ ⨯ /vc:login");
+ expect(snapshot).toContain("⎿ Authentication was refreshed");
+ expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");
+ expect(snapshot).not.toContain("· Authentication was refreshed");
+ });
+
+ it("invites with a quiet placeholder until typing starts", async () => {
+ const { screen, input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ // A bare prompt before any info/turn has no status row (no ↑ 0 ↓ 0 counter).
+ expect(screen.snapshot()).not.toContain("↑ 0");
+ // Empty buffer: the quiet `›` gutter with the rotation's first message.
+ expect(screen.snapshot()).toContain(`› ${PROMPT_PLACEHOLDER_MESSAGES[0]}`);
+ expect(screen.snapshot()).not.toContain("❯");
+ expect(screen.rawOutput()).not.toContain("\x1b[48;5;");
+
+ input.type("hello");
+ // Typing swaps in the active prompt mark and clears the invitation.
+ expect(screen.snapshot()).toContain("❯ hello");
+ expect(screen.snapshot()).not.toContain(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ input.enter();
+ expect(screen.snapshot()).toContain("W 1s");
+ expect(await prompt).toBe("hello");
+ renderer.shutdown();
+ });
+
+ it("shows the live turn bar as soon as the prompt is submitted", async () => {
+ vi.useFakeTimers();
+ try {
+ const { screen, input, renderer } = makeRenderer();
+ const prompt = renderer.readPrompt();
+
+ input.type("hello");
+ input.enter();
+
+ expect(await prompt).toBe("hello");
+ expect(screen.snapshot()).toContain("▪ W 1s");
+
+ // The typewriter label advances while the submit wait ticks.
+ vi.advanceTimersByTime(450);
+ expect(screen.snapshot()).toContain("Workin");
+
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { continueSession: true },
+ );
+ await Promise.resolve();
+ // The stream keeps the same bar — one working indicator end to end.
+ expect(screen.snapshot()).not.toContain("⊙");
+ expect(screen.snapshot()).toContain(" 1s");
+
+ streamController?.close();
+ await rendering;
+ renderer.shutdown();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("commits an end-of-turn stats coda when control returns to the prompt", async () => {
+ const { screen, input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.type("hey agent");
+ input.enter();
+ expect(await prompt).toBe("hey agent");
+
+ await renderer.renderStream(
+ streamOf([
+ { type: "step-start" },
+ { type: "assistant-delta", id: "m1", delta: "Hello!" },
+ { type: "step-finish", usage: { inputTokens: 18_000, outputTokens: 40 } },
+ { type: "step-start" },
+ { type: "assistant-complete", id: "m1" },
+ { type: "step-finish", usage: { inputTokens: 2_500, outputTokens: 3 } },
+ // The finish event repeats the last step's usage; it must not
+ // double-count into the turn total.
+ { type: "finish", usage: { inputTokens: 2_500, outputTokens: 3 } },
+ ]),
+ { continueSession: true },
+ );
+ // Mid-turn (before control returns to the prompt) there is no coda —
+ // multi-pass turns must end with exactly one.
+ expect(screen.snapshot()).not.toContain("\n└ ");
+
+ const second = renderer.readPrompt();
+ // Tokens are the turn's summed step usage, not the last report; the sum
+ // crossing the 20K input threshold is what earns the row.
+ expect(screen.snapshot()).toContain("└ Done in 1s ── ↑ 20.5K ↓ 43");
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
renderer.shutdown();
});
- it("hangs a command outcome under its invocation with the elbow connector", () => {
- const { screen, renderer } = makeRenderer();
- renderer.renderCommandResult("/model dismissed.");
- renderer.shutdown();
+ it("closes a quick, cheap turn without a stats coda", async () => {
+ const { screen, input, renderer } = makeRenderer();
- expect(screen.snapshot()).toContain("\u23bf /model dismissed.");
- });
+ const prompt = renderer.readPrompt();
+ input.type("hey");
+ input.enter();
+ expect(await prompt).toBe("hey");
- it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {
- const { screen, renderer } = makeRenderer();
- renderer.renderCommandInvocation("/vc:login", "failed");
- renderer.renderCommandResult(
- "Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" +
- "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",
+ await renderer.renderStream(
+ streamOf([
+ { type: "step-start" },
+ { type: "assistant-delta", id: "m1", delta: "Hi!" },
+ { type: "assistant-complete", id: "m1" },
+ { type: "step-finish", usage: { inputTokens: 4_500, outputTokens: 43 } },
+ { type: "finish", usage: { inputTokens: 4_500, outputTokens: 43 } },
+ ]),
+ { continueSession: true },
);
- renderer.shutdown();
- const snapshot = screen.snapshot();
- expect(snapshot).toContain("▌ ⨯ /vc:login");
- expect(snapshot).toContain("⎿ Authentication was refreshed");
- expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");
- expect(snapshot).not.toContain("· Authentication was refreshed");
+ // Under 10s and under 20K turn input: no coda row.
+ const second = renderer.readPrompt();
+ expect(screen.snapshot()).not.toContain("\n└ ");
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
+ renderer.shutdown();
});
- it("shows a bare prompt with no placeholder and accepts typing", async () => {
+ it("retires the placeholder after the first user message", async () => {
const { screen, input, renderer } = makeRenderer();
- const prompt = renderer.readPrompt();
- // A bare prompt before any info/turn has no status row (no ↑ 0 ↓ 0 counter).
- expect(screen.snapshot()).not.toContain("↑ 0");
- expect(screen.snapshot()).toContain("❯");
- expect(screen.snapshot()).not.toContain("Type to chat");
- expect(screen.rawOutput()).not.toContain("\x1b[48;5;");
-
+ const first = renderer.readPrompt();
+ expect(screen.snapshot()).toContain(`› ${PROMPT_PLACEHOLDER_MESSAGES[0]}`);
input.type("hello");
input.enter();
- expect(screen.snapshot()).toContain("Working…");
- expect(await prompt).toBe("hello");
+ expect(await first).toBe("hello");
+
+ // Once the user has spoken, the empty prompt keeps the quiet `›` but
+ // drops the invitation text; typing still swaps in the active `❯`.
+ const second = renderer.readPrompt();
+ expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).not.toContain("❯");
+ expect(screen.snapshot()).not.toContain(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ input.type("again");
+ expect(screen.snapshot()).toContain("❯ again");
+ input.ctrlC();
+ expect(screen.snapshot()).not.toContain("❯");
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
+ renderer.shutdown();
+ });
+
+ it("keeps collapsed reasoning out of the transcript behind the turn bar", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({
+ name: "Weather Agent",
+ serverUrl: "http://localhost:3000",
+ info: agentInfoWithModel("gpt-5"),
+ });
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "weather in SF", continueSession: true },
+ );
+
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain(" 1s");
+ });
+ streamController?.enqueue({
+ type: "reasoning-delta",
+ id: "r1",
+ delta: "the plan is to check the forecast",
+ });
+ await Promise.resolve();
+ // The trace never reaches the screen; the bar carries the turn.
+ const lines = screen.snapshot().split("\n");
+ const barRow = lines.findIndex((line) => line.includes(" 1s"));
+ expect(barRow).toBeGreaterThan(-1);
+ expect(screen.snapshot()).not.toContain("the plan is to check the forecast");
+ // The pending prompt row holds its place below, then the status line.
+ expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 4]).toContain("gpt-5");
+
+ streamController?.enqueue({ type: "reasoning-complete", id: "r1" });
+ streamController?.close();
+ await rendering;
+ expect(screen.snapshot()).not.toContain("the plan is to check the forecast");
+ expect(screen.snapshot()).not.toContain("Thought for");
renderer.shutdown();
});
- it("starts the turn pulse as soon as the prompt is submitted", async () => {
+ it("closes a long thinking turn with the coda, not a thought bar", async () => {
vi.useFakeTimers();
try {
const { screen, input, renderer } = makeRenderer();
const prompt = renderer.readPrompt();
-
- input.type("hello");
+ input.type("hard question");
input.enter();
-
- expect(await prompt).toBe("hello");
- expect(screen.snapshot()).toContain(" ⊙ Working…");
-
- vi.advanceTimersByTime(450);
- expect(screen.snapshot()).not.toContain("⊙ Working…");
- expect(screen.snapshot()).toContain(" Working…");
+ expect(await prompt).toBe("hard question");
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
const rendering = renderer.renderStream(
@@ -926,25 +1633,27 @@ describe("TerminalRenderer (inline scrollback)", () => {
},
{ continueSession: true },
);
- await Promise.resolve();
- expect(screen.snapshot()).not.toContain("⊙ Working…");
- expect(screen.snapshot()).toContain(" Working…");
-
+ streamController?.enqueue({ type: "reasoning-delta", id: "r1", delta: "hm" });
+ await vi.advanceTimersByTimeAsync(12_000);
+ streamController?.enqueue({ type: "reasoning-complete", id: "r1" });
streamController?.close();
await rendering;
+
+ // 12s of wall clock qualifies the coda; the thought itself leaves no
+ // separate transcript bar.
+ const second = renderer.readPrompt();
+ expect(screen.snapshot()).toContain("└ Done in 12s");
+ expect(screen.snapshot()).not.toContain("Thought for");
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
renderer.shutdown();
} finally {
vi.useRealTimers();
}
});
- it("removes the turn indicator when reasoning starts", async () => {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({
- name: "Weather Agent",
- serverUrl: "http://localhost:3000",
- info: agentInfoWithModel("gpt-5"),
- });
+ it("keeps the prompt in place during a turn with Enter inert, carrying the draft", async () => {
+ const { screen, input, renderer } = makeRenderer();
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
const rendering = renderer.renderStream(
{
@@ -954,29 +1663,59 @@ describe("TerminalRenderer (inline scrollback)", () => {
},
}),
},
- { submittedPrompt: "weather in SF", continueSession: true },
+ { submittedPrompt: "long task", continueSession: true },
);
- streamController?.enqueue({ type: "reasoning-delta", id: "r1", delta: "thinking" });
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("thinking");
+ // Empty draft: the pending prompt wears the same quiet `›` as idle
+ // (readiness is signalled by the turn bar's absence, not the glyph).
+ expect(screen.snapshot()).toContain("›");
});
- const lines = screen.snapshot().split("\n");
- const thinkingRow = lines.findIndex((line) => line.includes("thinking"));
- const workingRow = lines.findIndex(
- (line) => line.includes("Working…") || line.includes("Responding…"),
+ input.type("follow-up question");
+ // Enter is inert mid-turn — nothing submits, the draft stays.
+ input.enter();
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("❯ follow-up question");
+ });
+
+ streamController?.close();
+ await rendering;
+
+ // The draft seeds the next prompt instead of being lost.
+ const prompt = renderer.readPrompt();
+ expect(screen.snapshot()).toContain("❯ follow-up question");
+ input.enter();
+ expect(await prompt).toBe("follow-up question");
+ renderer.shutdown();
+ });
+
+ it("waitForIdlePrompt ignores the pending prompt and resolves only at idle", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
);
- const modelRow = lines.findIndex((line) => line.includes("gpt-5"));
- const inputRow = lines.findIndex((line) => line.includes("❯"));
- expect(thinkingRow).toBeGreaterThan(-1);
- expect(workingRow).toBe(-1);
- expect(lines[thinkingRow + 1]).toBe("");
- expect(modelRow).toBe(thinkingRow + 2);
- expect(inputRow).toBe(-1);
+ await vi.waitFor(() => {
+ // The pending prompt already shows `›` — but the live bar keeps the
+ // idle predicate false.
+ expect(screen.snapshot()).toContain("›");
+ });
+ await expect(screen.waitForIdlePrompt(200)).rejects.toThrow(/idle prompt/u);
streamController?.close();
await rendering;
+ const prompt = renderer.readPrompt();
+ await screen.waitForIdlePrompt(1_000);
+ input.ctrlC();
+ await expect(prompt).rejects.toThrow();
renderer.shutdown();
});
@@ -1019,7 +1758,38 @@ describe("TerminalRenderer (inline scrollback)", () => {
input.type("no");
input.enter();
await answer;
- expect(screen.snapshot()).toContain("⊙ Working…");
+ expect(screen.snapshot()).toContain("W 1s");
+ renderer.shutdown();
+ });
+
+ it("breathes between an answered question and the next tool block", async () => {
+ const { screen, input, renderer } = makeRenderer();
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "Which framework do you mean?",
+ display: "text",
+ });
+ input.type("eve");
+ input.enter();
+ await answer;
+
+ await renderer.renderStream(
+ streamOf([
+ { type: "step-start" },
+ {
+ type: "tool-call",
+ toolCallId: "t1",
+ toolName: "web_search",
+ input: { query: "eve framework" },
+ },
+ { type: "finish" },
+ ]),
+ { continueSession: true },
+ );
+
+ // The answered question and the following tool are separated by air.
+ expect(screen.snapshot()).toContain("⎿ eve\n\n");
renderer.shutdown();
});
@@ -1040,7 +1810,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("renders the selected question option as a padded inverse-blue label", async () => {
+ it("renders the question overlay with numbered rows and an inverse-blue cursor", async () => {
const { screen, input, renderer } = makeRenderer();
const answer = renderer.readInputQuestion({
@@ -1053,26 +1823,213 @@ describe("TerminalRenderer (inline scrollback)", () => {
],
});
- const selected = screen
- .snapshot()
- .split("\n")
- .find((line) => line.includes("AI Gateway"));
- expect(selected).toContain(" ▶ AI Gateway ");
+ const snapshot = screen.snapshot();
+ const lines = snapshot.split("\n");
+ const selected = lines.find((line) => line.includes("AI Gateway"));
+ expect(selected).toContain(" ▶ 1. AI Gateway ");
+ expect(selected).toContain("↵");
expect(screen.rawOutput()).toContain("\x1b[7m");
expect(screen.rawOutput()).toContain("\x1b[34m");
+ // Every option's description rides its own row, cursor or not.
+ expect(lines).toContain(" Managed access");
+ expect(lines).toContain(" Direct access");
+ // The panel carries its one quiet hint; no status hint row beneath it.
+ expect(snapshot).toContain("Esc to dismiss");
+ expect(snapshot).not.toContain("Enter to select");
+ expect(countOccurrences(snapshot, "Esc to")).toBe(1);
- const selectedDescriptionColumn = selected?.indexOf("— Managed access");
- expect(selectedDescriptionColumn).toBeGreaterThanOrEqual(0);
input.down();
const unselected = screen
.snapshot()
.split("\n")
.find((line) => line.includes("AI Gateway"));
- expect(unselected?.indexOf("— Managed access")).toBe(selectedDescriptionColumn);
+ expect(unselected).toContain("1. AI Gateway");
+ expect(unselected).not.toContain("▶");
input.up();
input.enter();
await expect(answer).resolves.toEqual({ optionId: "gateway" });
+ // The committed transcript hangs the answer under the question's elbow.
+ expect(screen.snapshot()).toContain("? Choose access");
+ expect(screen.snapshot()).toContain("⎿ AI Gateway");
+ renderer.shutdown();
+ });
+
+ it("dismisses the question with Esc, recording it compactly", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ // A lone ESC is held briefly in case it starts an arrow sequence.
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "Choose access",
+ display: "select",
+ options: [
+ { id: "gateway", label: "AI Gateway", description: "Managed access" },
+ { id: "external", label: "Other providers", description: "Direct access" },
+ ],
+ });
+ expect(screen.snapshot()).toContain("Esc to dismiss");
+
+ await escape();
+ // No answer travels; the runner returns to the prompt and the server
+ // records the parked request as ignored on the next message.
+ await expect(answer).resolves.toBeUndefined();
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("? Choose access");
+ expect(snapshot).toContain("⎿ Dismissed.");
+ // The option list does not survive the dismissal.
+ expect(snapshot).not.toContain("Managed access");
+ expect(snapshot).not.toContain("Enter to select");
+ renderer.shutdown();
+ });
+
+ it("clears a freeform draft on the first Esc and dismisses on the second", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "Choose access",
+ display: "select",
+ options: [{ id: "gateway", label: "AI Gateway" }],
+ allowFreeform: true,
+ });
+ input.type("2");
+ input.type("draft answer");
+ expect(screen.snapshot()).toContain("⎿ draft answer");
+
+ await escape();
+ expect(screen.snapshot()).not.toContain("draft answer");
+ expect(screen.snapshot()).toContain("Esc to dismiss");
+
+ await escape();
+ await expect(answer).resolves.toBeUndefined();
+ expect(screen.snapshot()).toContain("⎿ Dismissed.");
+ renderer.shutdown();
+ });
+
+ it("sweeps a preparing placeholder whose call never parses", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ { type: "step-start" },
+ // Announced, but no tool-call ever follows (the model emitted
+ // unparsable input and retried under a fresh id next step).
+ { type: "tool-call-preparing", toolCallId: "ghost-1", toolName: "web_search" },
+ { type: "step-finish", usage: { inputTokens: 10, outputTokens: 5 } },
+ { type: "step-start" },
+ {
+ type: "tool-call",
+ toolCallId: "retry-1",
+ toolName: "web_search",
+ input: { query: "eve framework" },
+ },
+ { type: "tool-result", toolCallId: "retry-1", output: { results: [] } },
+ { type: "step-finish", usage: { inputTokens: 10, outputTokens: 5 } },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "search", continueSession: false },
+ );
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ // The retry renders; the ghost placeholder never commits.
+ expect(snapshot).toContain("Searched eve framework");
+ expect(snapshot).not.toContain("Search …");
+ });
+
+ it("suppresses the tool block for ask_question calls", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "ask-1",
+ toolName: "ask_question",
+ input: { prompt: "Pick a color." },
+ },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "ask me", continueSession: false },
+ );
+ renderer.shutdown();
+
+ // The question surface is the call's representation; no `Ask …` block.
+ expect(screen.snapshot()).not.toContain("Ask Pick a color.");
+ });
+
+ it("selects a question option directly by its number key", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "Choose access",
+ display: "select",
+ options: [
+ { id: "gateway", label: "AI Gateway" },
+ { id: "external", label: "Other providers" },
+ ],
+ });
+ input.type("2");
+
+ await expect(answer).resolves.toEqual({ optionId: "external" });
+ renderer.shutdown();
+ });
+
+ it("focuses the freeform editor when the cursor reaches its row", async () => {
+ const { screen, input, renderer } = makeRenderer();
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "Choose access",
+ display: "select",
+ options: [
+ { id: "gateway", label: "AI Gateway" },
+ { id: "external", label: "Other providers" },
+ ],
+ allowFreeform: true,
+ });
+
+ expect(screen.snapshot()).toContain("3. Type your own answer");
+ // The freeform row's number moves focus into its inline editor; typing
+ // lands there without a separate enter.
+ input.type("3");
+ input.type("neither");
+ expect(screen.snapshot()).toContain("⎿ neither");
+ input.enter();
+
+ await expect(answer).resolves.toEqual({ text: "neither" });
+ renderer.shutdown();
+ });
+
+ it("dismisses a text question with Esc once its draft is cleared", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "What city are you in?",
+ display: "text",
+ });
+ input.type("New York");
+ await escape();
+ // First Esc only clears the draft; the question is still answerable.
+ expect(screen.snapshot()).toContain("? What city are you in?");
+
+ await escape();
+ await expect(answer).resolves.toBeUndefined();
+ expect(screen.snapshot()).toContain("⎿ Dismissed.");
renderer.shutdown();
});
@@ -1154,7 +2111,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
// The echo anchors in the user-message grammar (gutter bar), never the
// prompt glyph: that one is the live-input rendezvous marker.
- expect(screen.snapshot()).toContain("\u258c /new");
+ expect(screen.snapshot()).toContain("\u2502 /new");
expect(screen.snapshot()).not.toContain("\u276f /new");
});
@@ -1185,7 +2142,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("coalesces consecutive same-source writes into one labeled log run", () => {
+ it("coalesces a source's writes into one section showing the newest write", () => {
const screen = new MockScreen({ columns: 80, rows: 30 });
const input = new MockUserInput();
const renderer = new TerminalRenderer({
@@ -1199,20 +2156,20 @@ describe("TerminalRenderer (inline scrollback)", () => {
process.stdout.write("weather lookup { city: 'NY' }\n");
process.stdout.write("weather lookup { city: 'LA' }\n");
- // A non-log block ends the run…
renderer.renderNotice("turn boundary");
- // …so the next write starts a fresh labeled run.
process.stdout.write("post-turn line\n");
renderer.shutdown();
const snapshot = screen.snapshot();
- // Two runs → the source label appears exactly twice, not once per line.
- expect(countOccurrences(snapshot, "stdout ·")).toBe(2);
- expect(snapshot).toContain("weather lookup { city: 'NY' }");
- expect(snapshot).toContain("weather lookup { city: 'LA' }");
- expect(snapshot).toContain("post-turn line");
- // The open run at shutdown is committed, not wiped with the live region.
- expect(snapshot.indexOf("post-turn line")).toBeGreaterThan(snapshot.indexOf("turn boundary"));
+ // A stream is continuous: every stdout write — the notice interleaving
+ // included — merges into ONE section anchored at the newest write,
+ // showing only that write with the rest behind the elided count.
+ expect(countOccurrences(snapshot, "○ stdout")).toBe(1);
+ expect(snapshot).toContain("│ … (2 more)");
+ expect(snapshot).toContain("│ post-turn line");
+ expect(snapshot).not.toContain("city: 'NY'");
+ // The section sits at the last write's position — after the notice.
+ expect(snapshot.indexOf("○ stdout")).toBeGreaterThan(snapshot.indexOf("turn boundary"));
});
it("retroactively hides and restores buffered logs when the level changes", () => {
@@ -1240,8 +2197,9 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.setLogDisplayMode("all");
renderer.shutdown();
- // Restored lines reappear at their original transcript positions:
- // stdout before the notice, stderr after it.
+ // Restored sections sit at their newest write's position: stdout
+ // before the notice, stderr after it — later events display after the
+ // last error, never behind it.
const restored = screen.snapshot();
expect(restored.indexOf("before-boundary stdout")).toBeGreaterThan(-1);
expect(restored.indexOf("before-boundary stdout")).toBeLessThan(
@@ -1489,13 +2447,15 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
const snapshot = screen.snapshot();
+ // The buffered write reappears at its own position, before the notice
+ // that followed it.
expect(snapshot.indexOf("captured while hidden")).toBeGreaterThan(-1);
expect(snapshot.indexOf("captured while hidden")).toBeLessThan(
snapshot.indexOf("after the log"),
);
});
- it("keeps log-run labels consistent with what is visible", () => {
+ it("keeps a hidden write out of the stream section until its filter shows it", () => {
const screen = new MockScreen({ columns: 80, rows: 30 });
const input = new MockUserInput();
const renderer = new TerminalRenderer({
@@ -1511,23 +2471,23 @@ describe("TerminalRenderer (inline scrollback)", () => {
process.stdout.write("interleaved stdout line\n");
process.stderr.write("second stderr line\n");
- // The hidden stdout line must not split the visible stderr run.
- expect(countOccurrences(screen.snapshot(), "stderr ·")).toBe(1);
+ // Both stderr writes merge into one stream section; the hidden stdout
+ // write contributes no section of its own.
+ expect(countOccurrences(screen.snapshot(), "○ stderr")).toBe(1);
+ expect(screen.snapshot()).not.toContain("○ stdout");
renderer.setLogDisplayMode("all");
renderer.shutdown();
- // Once visible, the stdout line splits the stderr run in two — labels
- // re-derive from what is actually rendered, not from capture order.
+ // Once visible, stdout gets its own section; the stderr stream stays
+ // whole and ordered.
const snapshot = screen.snapshot();
- expect(countOccurrences(snapshot, "stderr ·")).toBe(2);
- expect(countOccurrences(snapshot, "stdout ·")).toBe(1);
+ expect(countOccurrences(snapshot, "○ stderr")).toBe(1);
+ expect(countOccurrences(snapshot, "○ stdout")).toBe(1);
expect(snapshot.indexOf("first stderr line")).toBeLessThan(
- snapshot.indexOf("interleaved stdout line"),
- );
- expect(snapshot.indexOf("interleaved stdout line")).toBeLessThan(
snapshot.indexOf("second stderr line"),
);
+ expect(snapshot).toContain("interleaved stdout line");
});
it("shows sandbox stdout lines and hides ordinary stdout under the sandbox log level", () => {
@@ -1555,8 +2515,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot).not.toContain("initializing 3 sandbox templates");
expect(snapshot).not.toContain("checking cached snapshot");
expect(snapshot).not.toContain("ordinary stdout log");
- expect(snapshot).not.toContain("stdout ·");
- expect(snapshot).not.toContain("stderr ·");
+ expect(snapshot).not.toContain("○ stdout");
+ expect(snapshot).not.toContain("○ stderr");
});
it("hides sandbox lines under the none log level", () => {
@@ -1625,7 +2585,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot).not.toContain("initializing 3 sandbox templates");
expect(snapshot).not.toContain("checking Docker daemon");
expect(snapshot).not.toContain("ordinary stdout log");
- expect(snapshot).not.toContain("stdout ·");
+ expect(snapshot).not.toContain("○ stdout");
});
it("cycles the log mode on Ctrl+L with a transient status hint that clears after 5s", () => {
@@ -1634,7 +2594,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
const screen = new MockScreen({ columns: 100, rows: 30 });
const input = new MockUserInput();
const renderer = new TerminalRenderer({ input, output: screen, unicode: true });
- void renderer.readPrompt();
+ // Abandoned on purpose; shutdown() rejects it with InterruptedError.
+ renderer.readPrompt().catch(() => {});
// Ctrl+R only redraws — it must not cycle the mode or show the hint.
input.type("\u0012");
@@ -1690,7 +2651,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(live).not.toContain("agent/agent.ts");
expect(live).not.toContain("change detected");
expect(live).not.toContain("/outside/src");
- expect(countOccurrences(live, "stdout ·")).toBe(1);
+ expect(countOccurrences(live, "○ stdout")).toBe(1);
// Shutdown settles the status row into scrollback instead of wiping it.
renderer.shutdown();
@@ -1796,9 +2757,9 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot.indexOf("turn boundary")).toBeLessThan(
snapshot.indexOf(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),
);
- expect(snapshot.indexOf(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)).toBeLessThan(
- snapshot.indexOf("tools/lookup.ts changed · rebuilding…"),
- );
+ // The orphaned outcome line is an ordinary write now — it rides the
+ // stream section at the live edge, after the in-place status row.
+ expect(snapshot).toContain("tools/lookup.ts changed · rebuilding…");
});
it("delays dev rebuild errors until explicitly flushed", () => {
@@ -1819,7 +2780,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.flushDelayedDevBuildErrors();
- expect(screen.snapshot()).toContain("stderr · [eve:dev] rebuild failed");
+ expect(screen.snapshot()).toContain("│ [eve:dev] rebuild failed");
expect(screen.snapshot()).toContain("expected default export");
renderer.shutdown();
});
@@ -1882,7 +2843,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
process.stderr.write("[eve:dev] rebuild failed: missing export\n");
- expect(screen.snapshot()).toContain("stderr · [eve:dev] rebuild failed");
+ expect(screen.snapshot()).toContain("│ [eve:dev] rebuild failed");
expect(screen.snapshot()).toContain("missing export");
renderer.shutdown();
});
@@ -1905,7 +2866,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
});
input.type("n");
expect(await approval).toEqual({ approved: false, reason: "Denied by user." });
- expect(screen.snapshot()).toContain("⊙ Working…");
+ expect(screen.snapshot()).toContain("W 1s");
renderer.shutdown();
const snapshot = screen.snapshot();
@@ -2957,7 +3918,7 @@ describe("TerminalRenderer command echo spacing", () => {
renderer.shutdown();
const lines = screen.snapshot().split("\n");
- const echoIndex = lines.findIndex((line) => line.includes("▌ /channels"));
+ const echoIndex = lines.findIndex((line) => line.includes("│ /channels"));
expect(echoIndex).toBeGreaterThan(0);
expect(lines[echoIndex - 1]).toBe("");
const resultIndex = lines.findIndex((line) => line.includes("⎿ Project linked."));
@@ -2976,7 +3937,7 @@ describe("TerminalRenderer command typeahead", () => {
expect(snapshot).toContain("Show available commands");
expect(snapshot).toContain("Configure the agent's model and provider");
const promptLine = snapshot.split("\n").find((line) => line.includes("❯ /"));
- expect(promptLine?.startsWith(" ❯ /")).toBe(true);
+ expect(promptLine?.startsWith("❯ /")).toBe(true);
input.enter();
// The highlighted default — /help leads the registry — is what a bare
@@ -3025,7 +3986,7 @@ describe("TerminalRenderer command typeahead", () => {
expect(await prompt).toBe("/channels");
renderer.shutdown();
- expect(screen.snapshot()).toContain("▌ /channels");
+ expect(screen.snapshot()).toContain("│ /channels");
expect(screen.snapshot()).not.toContain("❯ /channels");
});
@@ -3038,7 +3999,7 @@ describe("TerminalRenderer command typeahead", () => {
expect(await prompt).toBe("/quit");
renderer.shutdown();
- expect(screen.snapshot()).toContain("▌ /quit");
+ expect(screen.snapshot()).toContain("│ /quit");
});
it("moves the suggestion highlight with arrows instead of recalling history", async () => {
@@ -3132,7 +4093,7 @@ describe("TerminalRenderer command typeahead", () => {
await expect(prompt).resolves.toBe("/model");
renderer.shutdown();
- expect(screen.snapshot()).toContain("▌ /model");
+ expect(screen.snapshot()).toContain("│ /model");
expect(screen.snapshot()).not.toContain("❯ /model");
});
});
@@ -3157,7 +4118,7 @@ describe("TerminalRenderer status line", () => {
const prompt = renderer.readPrompt();
renderer.setVercelStatus(vercelStatus);
- expect(screen.snapshot()).toContain("⚠ AI Gateway");
+ expect(screen.snapshot()).toContain("⚠ ai-gateway");
renderer.renderAgentHeader({
name: "Weather Agent",
@@ -3170,19 +4131,21 @@ describe("TerminalRenderer status line", () => {
});
const lines = screen.snapshot().split("\n");
- const promptRow = lines.findIndex((line) => line.includes("❯"));
+ const promptRow = lines.findIndex((line) => line.includes("›"));
expect(promptRow).toBeGreaterThan(-1);
const statusRow = lines.slice(promptRow + 1).join("\n");
expect(statusRow).toContain(":3000");
expect(statusRow).toContain("anthropic/claude-sonnet-5");
expect(statusRow.indexOf(":3000")).toBeLessThan(statusRow.indexOf("anthropic/claude-sonnet-5"));
// The linked project folds into the connected gateway label.
- expect(statusRow).toContain("AI Gateway (my-agent)");
- expect(statusRow).not.toContain("⚠ AI Gateway");
+ expect(statusRow).toContain("via ai-gateway(oidc:my-agent)");
+ expect(statusRow).not.toContain("⚠ ai-gateway");
// No token segment before any turn reports usage (↑ 0 ↓ 0 is noise).
expect(statusRow).not.toContain("↑ 0");
expect(statusRow).not.toContain("/deploy pending");
+ // An empty Enter is inert; the reader needs content to settle.
+ input.type("done");
input.enter();
await prompt;
renderer.shutdown();
@@ -3211,13 +4174,13 @@ describe("TerminalRenderer status line", () => {
}),
});
renderer.setVercelStatus(vercelStatus);
- expect(screen.snapshot()).toContain("AI Gateway (my-agent)");
+ expect(screen.snapshot()).toContain("via ai-gateway(oidc:my-agent)");
renderer.setupFlow.begin("Connect to Vercel");
- expect(screen.snapshot()).not.toContain("AI Gateway (my-agent)");
+ expect(screen.snapshot()).not.toContain("via ai-gateway(oidc:my-agent)");
renderer.setupFlow.end({ preserveDiagnostics: false });
- expect(screen.snapshot()).toContain("AI Gateway (my-agent)");
+ expect(screen.snapshot()).toContain("via ai-gateway(oidc:my-agent)");
renderer.shutdown();
});
@@ -3271,13 +4234,15 @@ describe("TerminalRenderer status line", () => {
{ type: "step-start" },
{ type: "assistant-delta", id: "t1", delta: "Hi." },
{ type: "assistant-complete", id: "t1" },
+ { type: "step-finish", usage: { inputTokens: 500, outputTokens: 300 } },
{ type: "finish", usage: { inputTokens: 500, outputTokens: 300 } },
]),
{ submittedPrompt: "hello", continueSession: true },
);
+ // Token flow belongs to the end-of-turn coda; the settled footer keeps
+ // only the quiet `· Ready` row and its turn-scoped stats.
const snapshot = screen.snapshot();
- expect(snapshot).not.toContain("Ready");
expect(snapshot).not.toContain("↑ 500");
expect(snapshot).not.toContain("↓ 300");
renderer.shutdown();
@@ -3358,7 +4323,7 @@ describe("TerminalRenderer status line", () => {
const snapshot = screen.snapshot();
expect(snapshot).toContain("anthropic/claude-sonnet-5");
- expect(snapshot).toContain("AI Gateway (my-agent)");
+ expect(snapshot).toContain("via ai-gateway(oidc:my-agent)");
expect(snapshot).toContain("/deploy pending");
// A fresh conversation clears the token flow entirely (↑ 0 ↓ 0 is noise).
expect(snapshot).not.toContain("↑ 0");
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index 9b8abd141..06ee5d74d 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -14,6 +14,7 @@ import type {
AgentTUIToolApprovalResponse,
ConnectionAuthUpdate,
SubagentStepUpdate,
+ SubagentView,
SubagentToolUpdate,
} from "./runner.js";
import { interruptedError } from "./errors.js";
@@ -86,6 +87,7 @@ import {
import { toErrorMessage } from "#shared/errors.js";
import {
type Block,
+ type DisplayBlock,
type BlockKind,
type ToolStatus,
renderAttentionRows,
@@ -122,7 +124,26 @@ import {
} from "#cli/ui/terminal-text.js";
import type { VercelStatusSnapshot } from "./vercel-status.js";
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
-import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";
+import {
+ isPanelRoutedTool,
+ presentPreparingTool,
+ presentTool,
+ readWriteFileInput,
+ toolBaseName,
+ type ToolPresentationContext,
+} from "./tool-presentation.js";
+import { FileContentCache } from "./file-content-cache.js";
+import { groupToolBlocksForDisplay } from "./tool-block-groups.js";
+import { renderQuestionPanel } from "./question-panel.js";
+import { promptPlaceholder } from "./prompt-placeholder.js";
+import { TurnClock } from "./turn-clock.js";
+import {
+ allTodoItemsSettled,
+ readTodoToolItems,
+ renderFinishedTodoRows,
+ renderTodoPanelRows,
+ type TodoPanelItem,
+} from "./todo-panel.js";
import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";
import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";
import {
@@ -130,9 +151,13 @@ import {
PROGRESS_PULSE_ASCII_GLYPH,
PROGRESS_PULSE_GLYPH,
} from "#cli/ui/progress-pulse.js";
+import { eveVersionTag } from "#cli/banner.js";
import { readGatewayServiceTier } from "#shared/gateway-service-tier.js";
import {
formatAssistantResponseStats,
+ formatTokenFlow,
+ formatTurnDuration,
+ typewriterText,
isIncompletePaste,
nextKey,
sanitizePastedText,
@@ -195,10 +220,7 @@ type SetupFlowStatusState =
| { kind: "progress"; text: string }
| { kind: "external-action"; text: string; emphasis: string };
-type TurnIndicatorState =
- | { kind: "idle" }
- | { kind: "waiting"; startedAtMs: number }
- | { kind: "answering" };
+type TurnIndicatorState = { kind: "idle" } | { kind: "waiting"; startedAtMs: number };
type SetupFlowState = {
title: string;
@@ -214,6 +236,11 @@ type SetupFlowState = {
taskListLineStart?: number;
/** Task-list questions render their latest outcomes inside the question. */
hideLinesWhileQuestion?: boolean;
+ /**
+ * Fabricated by {@link TerminalRenderer.#requireSetupFlow} for a bare
+ * question without a begin/end pair; closed with the question.
+ */
+ implicit?: boolean;
};
/**
@@ -264,7 +291,6 @@ type RenderTurnState = {
text: Map<string, string>;
reasoning: Map<string, string>;
tools: Map<string, NativeToolState>;
- hasPendingToolResults: boolean;
};
type NativeToolState = {
@@ -272,14 +298,14 @@ type NativeToolState = {
toolName: string;
input: unknown;
status: ToolStatus;
+ /** True while the model is still streaming this call's input. */
+ preparing?: boolean;
output?: unknown;
errorText?: string;
};
const caretBlinkMs = 500;
const tickMs = 90;
-const TURN_PULSE_GLYPH = "⊙";
-const TURN_PULSE_ASCII_GLYPH = "o";
// How long to wait on a lone `ESC` before treating it as the Escape key, so a
// split arrow sequence (`ESC` then `[A`) has time to reassemble first.
const escFlushMs = 30;
@@ -293,12 +319,20 @@ const logLevelHintMs = 5_000;
const STATUS = {
processing: "Working…",
- toolResults: "Reading results…",
- streaming: "Responding…",
- executingTools: "Running tools…",
connectionAuth: "Waiting for connection authorization…",
} as const;
+/**
+ * The end-of-turn stats coda renders only for turns that were long or
+ * expensive: past this wall-clock duration, or past this many input tokens
+ * summed across the turn's own steps. A quick cheap exchange closes silently.
+ */
+const turnStatsMinDurationMs = 10_000;
+const turnStatsMinInputTokens = 20_000;
+
+/** One typed character of the turn bar's label per this many milliseconds. */
+const turnBarTypewriterMs = 80;
+
export class TerminalRenderer implements AgentTUIRenderer {
readonly #input: TerminalInput;
readonly #output: TerminalOutput;
@@ -331,6 +365,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #childToolCallIds = new Set<string>();
readonly #parentToolBlockIds = new Map<string, string>();
+ /** Monotonic counter behind every block's `updateSeq` activity stamp. */
+ #updateSequence = 0;
+ /** Call ids per subagent name, for the sections' ordinal subtitles. */
+ readonly #subagentCallsByName = new Map<string, string[]>();
+ /** Session-local file contents, so write blocks can render real diffs. */
+ readonly #fileContents = new FileContentCache();
readonly #subagentHeaders = new Set<string>();
#agentHeader?: AgentHeaderOptions;
#agentHeaderRendered = false;
@@ -366,13 +406,53 @@ export class TerminalRenderer implements AgentTUIRenderer {
* a `/`-prefixed freeform answer must never sprout suggestions.
*/
#typeahead?: CommandTypeaheadState;
+ /**
+ * Whether the empty input row invites with a rotating placeholder. Only
+ * the main chat prompt turns this on — a freeform question's empty input
+ * must not suggest unrelated things to try.
+ */
+ #promptPlaceholderActive = false;
+ readonly #promptPlaceholderStartedAtMs = Date.now();
+ /** Placeholder retires for good once the user has sent a first message. */
+ #hasUserMessage = false;
+ /** Armed by a chat submit; the end-of-turn stats line consumes it. */
+ readonly #turnClock = new TurnClock();
+ /**
+ * Draft typed while a turn streams. The prompt row stays in place with
+ * Enter inert (no mid-turn submits yet); the draft seeds the next prompt.
+ */
+ #streamDraft: LineState = EMPTY_LINE;
+ /** True while renderStream owns the keyboard — gates the inert prompt row. */
+ #streamDraftActive = false;
+ /**
+ * Token usage summed across the turn's steps — what this message actually
+ * cost, unlike the last step's report (whose input restates the whole
+ * context). Accumulated on `step-finish` only: the `finish` event repeats
+ * the final step's usage and would double-count it.
+ */
#turnIndicator: TurnIndicatorState = { kind: "idle" };
+ /** Rejects the reader currently awaiting keys, so #stop never strands it. */
+ #rejectActiveReader?: (error: Error) => void;
#status: string = STATUS.processing;
+ /**
+ * A flowless setup spinner's text ("Checking the project…"). Rendered as
+ * its own status row — the text is the information — instead of the live
+ * turn bar the waiting indicator would otherwise show.
+ */
+ #flowlessStatus?: string;
#title = "eve";
#isInteractive = false;
+ /**
+ * Whether this renderer ever ran a live session — the parting-line gate.
+ * `#isInteractive` is useless for that: Ctrl-C tears down via `#stop()`
+ * inside the reader before the runner's `shutdown()` ever observes it.
+ */
+ #everInteractive = false;
+ #partingLinePrinted = false;
#interrupted = false;
#caretVisible = true;
#spinnerIndex = 0;
+ #activityPulseStartedAtMs = Date.now();
#caretTimer?: ReturnType<typeof setInterval>;
#tickTimer?: ReturnType<typeof setInterval>;
#logLevelHintTimer?: ReturnType<typeof setTimeout>;
@@ -390,6 +470,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
#paintAgain = false;
#totalTokens?: number;
+ /** Input (prompt) tokens from the latest usage report — the ↑ side. */
+ #promptTokens?: number;
+ #contextSize?: number;
#assistantOutputTokens?: number;
#assistantTokensPerSecond?: number;
/** Wall-clock start of the current stream, for the tok/s status stat. */
@@ -410,10 +493,24 @@ export class TerminalRenderer implements AgentTUIRenderer {
/** Monotonic id source — committed cycle ids must never be reused. */
#devRebuildSequence = 0;
#pendingEchoedPrompt?: string;
+ /** The open HITL question overlay, painted above the input area. */
+ #questionPanel?: (width: number) => string[];
/** The active setup flow's bordered panel: progress, question, status. */
#setupFlow?: SetupFlowState;
/** The clearable setup attention line (`⚠ … · /vc:login`), rendered in the live footer. */
#setupAttention?: string;
+ /**
+ * The pinned todo panel above the input, replaced wholesale by each `todo`
+ * tool-call input. Cleared (and committed to the transcript) once every
+ * item settles.
+ */
+ #todoItems?: readonly TodoPanelItem[];
+ /**
+ * Signature of the last todo list committed as a finished transcript block.
+ * The result event re-plays the same call through {@link #upsertNativeTool},
+ * so committing must be idempotent per list content.
+ */
+ #todoCommittedSignature?: string;
/** Armed by {@link SetupFlowRenderer.waitForInterrupt}; fired by the idle key trap. */
#flowInterrupt?: () => void;
/** The installed working-state key consumer, so re-arming and disposal can recognize it. */
@@ -447,10 +544,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
unicode: options?.unicode ?? detectUnicode(),
});
this.#tools = options?.tools ?? "auto-collapsed";
- this.#reasoning = options?.reasoning ?? "full";
+ this.#reasoning = options?.reasoning ?? "auto-collapsed";
this.#subagents = options?.subagents ?? "auto-collapsed";
this.#connectionAuth = options?.connectionAuth ?? "full";
this.#assistantResponseStats = options?.assistantResponseStats ?? defaultAssistantResponseStats;
+ this.#contextSize = options?.contextSize;
this.#captureForeignOutput = options?.captureForeignOutput ?? this.#output === process.stdout;
this.#diagnostics = options?.diagnostics;
this.#logs = options?.logs ?? "none";
@@ -490,10 +588,17 @@ export class TerminalRenderer implements AgentTUIRenderer {
async readPrompt(options?: AgentTUISessionOptions): Promise<string> {
this.#start(options);
this.#stopTicker();
+ this.#commitTurnStats();
this.#inputActive = true;
+ this.#promptPlaceholderActive = true;
this.#turnIndicator = { kind: "idle" };
this.#status = "";
- let editor: LineState = lineOf(stripPromptControlCharacters(options?.initialDraft ?? ""));
+ // A draft typed during the turn carries into the prompt; an explicit
+ // initial draft (`eve dev --input`) wins over it.
+ let editor: LineState = lineOf(
+ stripPromptControlCharacters(options?.initialDraft ?? this.#streamDraft.text),
+ );
+ this.#streamDraft = EMPTY_LINE;
this.#promptHistory.begin(editor.text);
this.#syncInput(editor);
this.#typeahead = typeaheadFor(this.#availablePromptCommands, editor.text);
@@ -501,6 +606,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
return await new Promise((resolve, reject) => {
+ this.#rejectActiveReader = reject;
const apply = (next: LineState) => {
editor = next;
this.#showCaret();
@@ -585,11 +691,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
selected !== undefined && parsePromptCommand(editor.text) === null
? typeaheadCompletion(selected).trimEnd()
: editor.text;
+ // An empty (or whitespace-only) buffer never submits.
+ if (prompt.trim().length === 0) break;
this.#typeahead = undefined;
this.#promptHistory.add(prompt);
this.#inputActive = false;
this.#stopCaretBlink();
- this.#startWorking();
this.#status = STATUS.processing;
if (isPromptControlCommand(prompt)) {
// Commands echo as their own line (blue, under the prompt
@@ -601,8 +708,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
live: false,
});
} else {
+ this.#startWorking();
this.#addUserBlock(prompt);
this.#pendingEchoedPrompt = prompt;
+ this.#turnClock.arm();
}
this.#syncInput(EMPTY_LINE);
this.#paint();
@@ -663,8 +772,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#status = this.#connectionAuthPendingCount > 0 ? STATUS.connectionAuth : STATUS.processing;
this.#addSubmittedPrompt(options?.submittedPrompt);
if (options?.submittedPrompt !== undefined) this.#diagnostics?.recordPrompt();
+ // A turn not born at the prompt (`eve dev --input`) arms its own clock;
+ // continuation passes (no submitted prompt) keep the original.
+ if (options?.submittedPrompt !== undefined && !this.#turnClock.armed) {
+ this.#turnClock.arm();
+ }
this.#interrupted = false;
this.#totalTokens = undefined;
+ this.#promptTokens = undefined;
this.#assistantOutputTokens = undefined;
this.#assistantTokensPerSecond = undefined;
this.#streamStartedAt = Date.now();
@@ -674,6 +789,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
assistantResponseStats: options?.assistantResponseStats ?? this.#assistantResponseStats,
};
this.#startTicker();
+ this.#streamDraftActive = true;
this.#paint();
const streamInterrupted = new Promise<void>((resolve) => {
@@ -685,7 +801,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
text: new Map(),
reasoning: new Map(),
tools: new Map(),
- hasPendingToolResults: false,
};
try {
@@ -711,10 +826,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (this.#interrupted) result.abort?.();
this.#detachInput();
this.#stopTicker();
+ this.#streamDraftActive = false;
if (this.#turnIndicator.kind === "waiting") {
this.#turnIndicator = { kind: "idle" };
}
this.#status = completedTurnStatus(this.#interrupted, options?.continueSession === true);
+ // Placeholders whose call never materialized (interrupted mid-input)
+ // must vanish rather than commit.
+ this.#sweepPreparingToolBlocks(turnState);
+ // An interrupted turn gets no terminal updates for its in-flight
+ // calls; a block left `running` would keep the settled prefix wedged
+ // and freeze scrollback for the rest of the session.
+ if (this.#interrupted) this.#settleInterruptedToolBlocks();
this.#finalizeAllBlocks();
this.#diagnostics?.reportStats();
this.#paint();
@@ -738,6 +861,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
return await new Promise((resolve, reject) => {
+ this.#rejectActiveReader = reject;
this.#consumeKey = (key) => {
switch (key.type) {
case "text": {
@@ -785,6 +909,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#start(options);
this.#stopTicker();
this.#inputActive = false;
+ this.#promptPlaceholderActive = false;
this.#turnIndicator = { kind: "idle" };
this.#interrupted = false;
@@ -795,50 +920,91 @@ export class TerminalRenderer implements AgentTUIRenderer {
const totalRows = optionList.length + (hasFreeformRow ? 1 : 0);
const sectionKey = questionSectionId(question.requestId);
- let mode: "select" | "text" = hasOptions ? "select" : "text";
+ // The overlay is the primary surface for option questions; text mode
+ // serves prompts without options. Esc (with nothing to clear) dismisses
+ // the question: it resolves `undefined`, the runner returns to the
+ // prompt, and the server records the still-parked request as `ignored`
+ // when the user's next message resumes the turn.
+ let mode: "overlay" | "text" = hasOptions ? "overlay" : "text";
let cursorIndex = 0;
let editor = EMPTY_LINE;
const isOnFreeformRow = () => hasFreeformRow && cursorIndex === optionList.length;
- const renderSection = () => {
+ // The panel closure reads the mutable interaction state at paint time,
+ // so key handlers only update it and repaint.
+ const overlayPanel = (width: number): string[] =>
+ renderQuestionPanel(
+ {
+ prompt: stripTerminalControls(question.prompt),
+ options: optionList,
+ cursor: cursorIndex,
+ allowFreeform: hasFreeformRow,
+ editor,
+ caretVisible: this.#caretVisible,
+ },
+ this.#theme,
+ width,
+ );
+
+ const renderTextSection = () => {
this.#upsertBlock({
id: sectionKey,
kind: "question",
title: stripTerminalControls(question.prompt),
- body: formatQuestionContent(question, cursorIndex, this.#theme),
+ body: formatQuestionContent(question, undefined, this.#theme),
preformatted: true,
live: true,
});
};
- const repaintStatus = () => {
- if (mode === "select") {
- const confirm = isOnFreeformRow() ? "type" : "select";
- this.#status = `↑/↓ move · enter ${confirm} · Ctrl+C quit`;
- this.#inputActive = false;
+ const syncFreeformCaret = () => {
+ if (isOnFreeformRow()) {
+ this.#startCaretBlink();
} else {
- this.#inputActive = true;
- this.#syncInput(editor);
- this.#status = "";
+ this.#stopCaretBlink();
+ this.#showCaret();
}
+ };
+
+ const enterOverlay = () => {
+ mode = "overlay";
+ this.#inputActive = false;
+ this.#removeBlock(sectionKey);
+ this.#questionPanel = overlayPanel;
+ this.#status = "";
+ syncFreeformCaret();
this.#paint();
};
- renderSection();
- if (mode === "text") this.#startCaretBlink();
- repaintStatus();
+ const enterTextMode = () => {
+ mode = "text";
+ this.#questionPanel = undefined;
+ renderTextSection();
+ this.#inputActive = true;
+ this.#syncInput(editor);
+ this.#status = "";
+ this.#startCaretBlink();
+ this.#paint();
+ };
+
+ if (mode === "overlay") {
+ enterOverlay();
+ } else {
+ enterTextMode();
+ }
const finalize = (resolved: {
optionId?: string;
text?: string;
label: string;
}): AgentTUIInputQuestionResponse => {
+ this.#questionPanel = undefined;
this.#upsertBlock({
id: sectionKey,
kind: "question",
title: stripTerminalControls(question.prompt),
- body: ` ${this.#theme.colors.green(this.#theme.glyph.success)} ${stripTerminalControls(resolved.label)}`,
+ body: `${this.#theme.colors.dim(this.#theme.glyph.elbow)} ${stripTerminalControls(resolved.label)}`,
preformatted: true,
live: false,
});
@@ -854,16 +1020,55 @@ export class TerminalRenderer implements AgentTUIRenderer {
return response;
};
- return await new Promise<AgentTUIInputQuestionResponse | undefined>((resolve, reject) => {
+ // Dismissal resolves `undefined` — no answer travels; the transcript
+ // records the question compactly instead of preserving its option list.
+ const dismiss = () => {
+ this.#questionPanel = undefined;
+ this.#upsertBlock({
+ id: sectionKey,
+ kind: "question",
+ title: stripTerminalControls(question.prompt),
+ body: `${this.#theme.colors.dim(this.#theme.glyph.elbow)} ${this.#theme.colors.dim("Dismissed.")}`,
+ preformatted: true,
+ live: false,
+ });
+ this.#inputActive = false;
+ this.#status = "";
+ this.#stopCaretBlink();
+ this.#detachInput();
+ this.#paint();
+ resolve(undefined);
+ };
+
+ const moveCursor = (delta: number) => {
+ if (totalRows === 0) return;
+ cursorIndex = (cursorIndex + delta + totalRows) % totalRows;
+ syncFreeformCaret();
+ this.#paint();
+ };
+
+ const selectOptionAt = (index: number) => {
+ const option = optionList[index];
+ if (option) resolve(finalize({ optionId: option.id, label: option.label }));
+ };
+
+ let resolve!: (value: AgentTUIInputQuestionResponse | undefined) => void;
+
+ return await new Promise<AgentTUIInputQuestionResponse | undefined>((res, reject) => {
+ this.#rejectActiveReader = reject;
+ resolve = res;
this.#consumeKey = (key) => {
if (key.type === "ctrl-c") {
- if (mode === "text" && editor.text.length > 0) {
+ const editing = mode === "text" || isOnFreeformRow();
+ if (editing && editor.text.length > 0) {
editor = EMPTY_LINE;
this.#showCaret();
- repaintStatus();
+ if (mode === "text") this.#syncInput(editor);
+ this.#paint();
return;
}
this.#interrupted = true;
+ this.#questionPanel = undefined;
this.#stopCaretBlink();
this.#stop();
reject(interruptedError());
@@ -875,38 +1080,58 @@ export class TerminalRenderer implements AgentTUIRenderer {
return;
}
- if (mode === "select") {
+ if (mode === "overlay") {
switch (key.type) {
case "up":
case "ctrl-p":
- if (totalRows > 0) {
- cursorIndex = (cursorIndex - 1 + totalRows) % totalRows;
- renderSection();
- repaintStatus();
- }
+ moveCursor(-1);
break;
case "down":
case "ctrl-n":
- if (totalRows > 0) {
- cursorIndex = (cursorIndex + 1) % totalRows;
- renderSection();
- repaintStatus();
- }
+ moveCursor(1);
break;
case "enter": {
if (isOnFreeformRow()) {
- mode = "text";
- editor = EMPTY_LINE;
- this.#startCaretBlink();
- repaintStatus();
+ const resolvedText = resolveQuestionText(editor.text, question);
+ if (resolvedText !== undefined) resolve(finalize(resolvedText));
break;
}
- const option = optionList[cursorIndex];
- if (option) resolve(finalize({ optionId: option.id, label: option.label }));
+ selectOptionAt(cursorIndex);
break;
}
- default:
+ case "escape":
+ if (isOnFreeformRow() && editor.text.length > 0) {
+ editor = EMPTY_LINE;
+ this.#showCaret();
+ this.#paint();
+ break;
+ }
+ dismiss();
+ break;
+ default: {
+ if (isOnFreeformRow()) {
+ const edited = applyLineEditorKey(editor, key);
+ if (edited !== undefined) {
+ editor = edited;
+ this.#showCaret();
+ this.#paint();
+ }
+ break;
+ }
+ // A number press selects its row directly; the freeform row's
+ // number moves focus into its inline editor instead.
+ if (key.type === "text" && /^[1-9]$/u.test(key.value)) {
+ const rowIndex = Number(key.value) - 1;
+ if (rowIndex < optionList.length) {
+ selectOptionAt(rowIndex);
+ } else if (rowIndex === optionList.length && hasFreeformRow) {
+ cursorIndex = rowIndex;
+ syncFreeformCaret();
+ this.#paint();
+ }
+ }
break;
+ }
}
return;
}
@@ -915,7 +1140,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (edited !== undefined) {
editor = edited;
this.#showCaret();
- repaintStatus();
+ this.#syncInput(editor);
+ this.#paint();
return;
}
@@ -926,7 +1152,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (moved !== undefined) {
editor = moved;
this.#showCaret();
- repaintStatus();
+ this.#syncInput(editor);
+ this.#paint();
}
break;
}
@@ -937,23 +1164,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
break;
}
case "escape":
- if (hasOptions) {
- if (editor.text.length > 0) {
- editor = EMPTY_LINE;
- this.#showCaret();
- repaintStatus();
- break;
- }
- mode = "select";
+ if (editor.text.length > 0) {
editor = EMPTY_LINE;
- this.#inputActive = false;
- this.#stopCaretBlink();
- repaintStatus();
+ this.#showCaret();
+ this.#syncInput(editor);
+ this.#paint();
break;
}
- editor = EMPTY_LINE;
- this.#showCaret();
- repaintStatus();
+ dismiss();
break;
default:
break;
@@ -980,9 +1198,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#upsertBlock({
id: subagentStepSectionId(update.callId, update.sectionKey),
kind: "subagent-step",
+ subagentCallId: update.callId,
depth: 1,
reasoning: reasoningText,
body: messageText,
+ // Child prose collapses to one activity row; the parent's reply is
+ // the conclusion. `--subagents full` keeps the verbatim text.
+ collapsed: this.#subagents !== "full",
live: !update.finalized,
});
this.#paint();
@@ -1007,24 +1229,109 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
const status = subagentToolStatus(update.status);
+ // Subagents share the session's sandbox, so their reads and writes feed
+ // the same file-content cache and their write blocks diff the same way.
+ const presentation =
+ update.status === "preparing"
+ ? presentPreparingTool(update.toolName)
+ : presentTool(
+ update.toolName,
+ update.input,
+ this.#toolPresentationContext({
+ input: update.input,
+ output: update.output,
+ toolCallId: update.childCallId,
+ toolName: update.toolName,
+ }),
+ );
const block: Block = {
id: subagentToolSectionId(update.callId, update.childCallId),
kind: "subagent-tool",
+ subagentCallId: update.callId,
depth: 1,
- title: stripTerminalControls(update.toolName),
- subtitle: summarizeToolArgs(update.input),
+ title: stripTerminalControls(presentation.title),
+ subtitle: stripTerminalControls(presentation.subtitle),
status,
live: status === "running" || status === "approval",
expanded: this.#subagents === "full",
+ toolName: update.toolName,
+ toolGroup: presentation.group,
toolInput: update.input,
};
+ if (presentation.doneTitle !== undefined) {
+ block.doneTitle = stripTerminalControls(presentation.doneTitle);
+ }
+ if (presentation.detail !== undefined) {
+ block.detailLines = presentation.detail;
+ block.keepDetailWhenDone = presentation.keepDetailWhenDone === true;
+ }
if (update.output !== undefined) {
- block.result = summarizeToolResult(update.output);
+ block.result = presentation.summarizeResult(update.output);
block.toolOutput = update.output;
} else if (update.errorText !== undefined) {
block.result = stripTerminalControls(update.errorText);
}
this.#upsertBlock(block);
+ this.#syncSubagentChildLiveness(update.callId);
+ this.#paint();
+ }
+
+ /**
+ * Cohort liveness for one section's child tools, mirroring the top-level
+ * `#syncNativeToolBlockLiveness`: while any of a call's children still
+ * runs, settled siblings stay live so an in-flight batch accumulates as
+ * one group instead of fragmenting on every status flip.
+ */
+ #syncSubagentChildLiveness(callId: string): void {
+ applyCohortLiveness(
+ this.#blocks
+ .filter((block) => block.kind === "subagent-tool" && block.subagentCallId === callId)
+ .map((block) => ({ block, active: isActiveToolStatus(block.status) })),
+ );
+ }
+
+ removeSubagentTool(update: { callId: string; childCallId: string }): void {
+ this.#removeBlock(subagentToolSectionId(update.callId, update.childCallId));
+ this.#paint();
+ }
+
+ /**
+ * The runner-facing subagent surface (see {@link SubagentView}); the
+ * public methods below are its implementation and the unit tests' seam.
+ */
+ readonly subagents: SubagentView = {
+ begin: (update) => this.beginSubagent(update),
+ upsertStep: (update) => this.upsertSubagentStep(update),
+ upsertTool: (update) => this.upsertSubagentTool(update),
+ removeTool: (update) => this.removeSubagentTool(update),
+ complete: (update) => this.completeSubagent(update),
+ markChildToolCallId: (callId) => this.markChildToolCallId(callId),
+ };
+
+ /**
+ * Opens a subagent's section as soon as the dispatch is announced, so the
+ * transcript flows from the `Delegate …` placeholder straight into the
+ * `※ subagent(<name>)` header instead of going blank until the child's
+ * first content streams in. Re-opening a completed section (a HITL-parked
+ * child resuming) clears its Done mark.
+ */
+ beginSubagent(update: { callId: string; name: string }): void {
+ if (this.#subagents === "hidden") return;
+ this.#ensureSubagentHeader(update.callId, update.name);
+ const header = this.#blockById.get(subagentHeaderId(update.callId));
+ if (header?.status === "done") delete header.status;
+ this.#paint();
+ }
+
+ /**
+ * Marks a subagent call complete — its final message has arrived — so the
+ * section's closing corner reports `Done`. The header stays live until the
+ * turn finalizes (committing mid-turn would freeze its child window).
+ */
+ completeSubagent(update: { callId: string }): void {
+ const header = this.#blockById.get(subagentHeaderId(update.callId));
+ if (header === undefined) return;
+ header.status = "done";
this.#paint();
}
@@ -1103,13 +1410,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
// its rows are only re-emitted via renderAgentHeader.
this.#agentHeaderRendered = false;
this.#agentHeaderBody = undefined;
- this.#childToolCallIds.clear();
- this.#parentToolBlockIds.clear();
- this.#subagentHeaders.clear();
+ this.#clearConversationState();
+ // A fresh conversation gets the invitation back.
+ this.#hasUserMessage = false;
this.#pendingEchoedPrompt = undefined;
this.#devRebuild = undefined;
this.#connectionAuthPendingCount = 0;
this.#totalTokens = undefined;
+ this.#promptTokens = undefined;
this.#assistantOutputTokens = undefined;
this.#assistantTokensPerSecond = undefined;
this.#streamStartedAt = undefined;
@@ -1119,6 +1427,44 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
+ /**
+ * The mid-conversation session boundary: one opening-corner line marking
+ * where the server-side context was cut and a fresh session took over.
+ */
+ renderSessionBoundary(): void {
+ // The dying turn's stats coda closes before the boundary — it belongs
+ // to the session that ended, not the fresh one.
+ this.#commitTurnStats();
+ this.#clearConversationState();
+
+ const c = this.#theme.colors;
+ const g = this.#theme.glyph;
+ const body = c.dim(`${g.cornerOpen}${g.dash.repeat(2)} Session restarted, clear context.`);
+ this.#pushBlock({ kind: "session-boundary", body, live: false });
+ this.#paint();
+ }
+
+ /**
+ * THE one authority for state scoped to a server-side conversation
+ * context. Called by both context cuts — `/new` (`reset`) and the
+ * mid-conversation session replacement (`renderSessionBoundary`) — so the
+ * two can never drift on what dies with the old context: the pinned todo
+ * list (its tasks were not finished — dismiss, don't commit), write-diff
+ * bases (a fresh session may run a fresh sandbox, where stale bases
+ * render confidently wrong diffs), subagent call identity (ordinals must
+ * not count across a cut), tool-call ownership maps, and the turn clock.
+ */
+ #clearConversationState(): void {
+ this.#childToolCallIds.clear();
+ this.#parentToolBlockIds.clear();
+ this.#subagentHeaders.clear();
+ this.#subagentCallsByName.clear();
+ this.#todoItems = undefined;
+ this.#todoCommittedSignature = undefined;
+ this.#fileContents.clear();
+ this.#turnClock.reset();
+ }
+
/**
* Commits a single dim informational line to the transcript (e.g. the
* session-recovery notice after a terminal server failure). No-op when the
@@ -1917,13 +2263,19 @@ export class TerminalRenderer implements AgentTUIRenderer {
indicator: { kind: "spinner" },
lines: [],
outputBuffer: [],
+ // Fabricated for a bare question (no begin/end pair) — closed with
+ // the question, or it would mask the prompt's footer forever.
+ implicit: true,
};
}
return this.#setupFlow;
}
#closeSetupQuestion(): void {
- if (this.#setupFlow !== undefined) {
+ if (this.#setupFlow?.implicit === true) {
+ // A flow fabricated for this one question dies with it.
+ this.#setupFlow = undefined;
+ } else if (this.#setupFlow !== undefined) {
this.#setupFlow.question = undefined;
this.#setupFlow.hideLinesWhileQuestion = false;
}
@@ -1931,7 +2283,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#detachInput();
// Back to the working state: the interrupt trap covers the gap until the
// next question (or the flow's end).
- this.#armFlowIdleTrap();
+ if (this.#setupFlow !== undefined) this.#armFlowIdleTrap();
this.#paint();
}
@@ -1969,6 +2321,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#closeSetupQuestion();
rejectPromise(error);
};
+ // See #armFlowIdleTrap: stale deferred keys die with the old consumer.
+ this.#clearKeyFlush();
this.#consumeKey = (key) => consume(key, settle, reject);
this.#attachInput();
return { promise, settle };
@@ -2010,6 +2364,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (key.type === "ctrl-r") this.#paint();
};
this.#flowIdleConsumer = consumer;
+ // A deferred ESC/paste flush armed under the previous consumer must not
+ // fire into this one.
+ this.#clearKeyFlush();
this.#consumeKey = consumer;
this.#attachInput();
}
@@ -2045,16 +2402,21 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
return;
}
+ if (this.#inputActive || this.#streamDraftActive) {
+ // The prompt or a streaming turn owns the footer; a flowless spinner
+ // must not steal its ticker or indicator.
+ return;
+ }
if (content === undefined) {
this.#turnIndicator = { kind: "idle" };
- this.#status = "";
+ this.#flowlessStatus = undefined;
this.#stopTicker();
this.#paint();
return;
}
this.#start();
this.#startWorking();
- this.#status = content.text;
+ this.#flowlessStatus = content.text;
this.#paint();
}
@@ -2108,6 +2470,15 @@ export class TerminalRenderer implements AgentTUIRenderer {
shutdown(): void {
this.#stop();
+ // The parting line: the boot banner's dim counterpart, written after the
+ // terminal is restored so it lands as the session's last scrollback row.
+ // Gated on the session having ever gone live (Ctrl-C stops the terminal
+ // inside the reader long before the runner's teardown reaches here) and
+ // printed at most once.
+ if (this.#everInteractive && !this.#partingLinePrinted) {
+ this.#partingLinePrinted = true;
+ this.#output.write(`${this.#theme.colors.dim(eveVersionTag())}\n`);
+ }
}
// ---------------------------------------------------------------------------
@@ -2116,10 +2487,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
#start(options?: AgentTUISessionOptions) {
this.#title = options?.title ?? this.#title;
+ if (options?.contextSize !== undefined) this.#contextSize = options.contextSize;
if (this.#isInteractive) return;
this.#isInteractive = true;
+ this.#everInteractive = true;
this.#live.reset();
this.#live.hideCursor();
this.#installLogCapture();
@@ -2140,6 +2513,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
#stop() {
+ // 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;
+ this.#rejectActiveReader = undefined;
+ rejectReader?.(interruptedError());
this.#detachInput();
this.#stopCaretBlink();
this.#stopTicker();
@@ -2153,9 +2531,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
// Commit any leading finalized blocks (e.g. freshly captured log lines)
// before the live region is wiped, so they land in scrollback instead of
- // vanishing with the repaint area. The in-place rebuild status settles
- // first so its last state survives as scrollback too.
+ // vanishing with the repaint area. The in-place rebuild status and any
+ // open log run settle first so their last state survives as scrollback.
this.#settleDevRebuildStatus();
+ for (const block of this.#blocks) {
+ if (block.kind === "log" && block.id === undefined) block.live = false;
+ }
this.#paint();
this.#live.clear();
@@ -2185,13 +2566,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
// subscription would deliver every key twice.
this.#input.off("data", this.#feedRaw);
this.#input.on("data", this.#feedRaw);
+ // Replay keys carried over from the previous mode's detach. Deferred a
+ // microtask so the new mode finishes installing #consumeKey first.
+ if (this.#keyBuffer.length > 0) {
+ queueMicrotask(() => {
+ if (this.#consumeKey !== undefined && this.#keyBuffer.length > 0) {
+ this.#drainKeys();
+ this.#armKeyFlush();
+ }
+ });
+ }
}
#detachInput() {
this.#input.off("data", this.#feedRaw);
this.#clearKeyFlush();
- this.#keyBuffer = "";
- this.#inputDecoder = new StringDecoder("utf8");
+ // The undrained tail of the current chunk survives the handoff: a mode
+ // ending mid-chunk (Enter in a paste, `y` for the first of two queued
+ // approvals) must not eat the keys behind it. The next #attachInput
+ // drains the carry-over into the new consumer.
this.#consumeKey = undefined;
}
@@ -2278,8 +2671,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
break;
- default:
+ case "enter":
+ // Inert while the turn streams — no mid-turn submits yet. The draft
+ // carries into the next prompt instead.
+ break;
+ default: {
+ const edited = applyLineEditorKey(this.#streamDraft, key, { multiline: true });
+ if (edited !== undefined) {
+ this.#streamDraft = edited;
+ this.#paint();
+ }
break;
+ }
}
}
@@ -2315,7 +2718,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
#startWorking(): void {
- this.#turnIndicator = { kind: "waiting", startedAtMs: Date.now() };
+ const startedAtMs = Date.now();
+ this.#activityPulseStartedAtMs = startedAtMs;
+ this.#turnIndicator = { kind: "waiting", startedAtMs };
this.#startTicker();
}
@@ -2337,15 +2742,48 @@ export class TerminalRenderer implements AgentTUIRenderer {
*/
#pushBlock(block: Block) {
if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();
+ block.updateSeq = ++this.#updateSequence;
this.#blocks.push(block);
if (block.id) this.#blockById.set(block.id, block);
}
#addUserBlock(prompt: string) {
+ this.#hasUserMessage = true;
this.#pushBlock({ kind: "user", body: stripTerminalControls(prompt), live: false });
this.#paint();
}
+ /**
+ * Commits the end-of-turn coda — wall-clock duration plus token flow —
+ * when control returns to the prompt after a chat turn. Consuming the
+ * armed timestamp here (not at stream end) spans multi-pass turns:
+ * question answers and connection authorizations re-stream without
+ * re-arming, so one turn gets one line.
+ */
+ #commitTurnStats(): void {
+ const settled = this.#turnClock.settle();
+ if (settled === undefined) return;
+
+ // Quick, cheap turns close silently — the coda earns its row only when
+ // the turn was long or expensive.
+ if (
+ settled.elapsedMs <= turnStatsMinDurationMs &&
+ settled.inputTokens <= turnStatsMinInputTokens
+ ) {
+ return;
+ }
+
+ let body = `Done in ${this.#turnStatsBody(settled.elapsedMs)}`;
+ // Context fill is a different measurement than the turn's summed flow —
+ // it reads off the last step's absolute input — so it rides separately.
+ const contextTokens = this.#promptTokens ?? 0;
+ if (this.#contextSize !== undefined && this.#contextSize > 0 && contextTokens > 0) {
+ const fill = Math.round((contextTokens / this.#contextSize) * 100);
+ body += ` ${this.#theme.glyph.dot} ${fill}% context`;
+ }
+ this.#pushBlock({ kind: "turn-stats", body, live: false });
+ }
+
#addSubmittedPrompt(prompt: string | undefined) {
if (prompt == null) return;
if (this.#pendingEchoedPrompt === prompt) {
@@ -2392,12 +2830,30 @@ export class TerminalRenderer implements AgentTUIRenderer {
#ensureSubagentHeader(callId: string, name: string) {
if (this.#subagentHeaders.has(callId)) return;
this.#subagentHeaders.add(callId);
- this.#pushBlock({
+
+ // Parallel calls to the same subagent are individual sections; ordinal
+ // subtitles (`#1`, `#2`) tell them apart. The first call gains its `#1`
+ // retroactively the moment a sibling appears.
+ const cleanName = stripTerminalControls(name);
+ const siblings = this.#subagentCallsByName.get(cleanName) ?? [];
+ siblings.push(callId);
+ this.#subagentCallsByName.set(cleanName, siblings);
+ if (siblings.length === 2) {
+ const firstHeader = this.#blockById.get(subagentHeaderId(siblings[0]!));
+ if (firstHeader !== undefined) firstHeader.subtitle = "#1";
+ }
+
+ const block: Block = {
id: subagentHeaderId(callId),
kind: "subagent",
- title: stripTerminalControls(name),
- live: false,
- });
+ subagentCallId: callId,
+ title: cleanName,
+ // Live until the turn's #finalizeAllBlocks: committing a section
+ // mid-turn would freeze its child window in scrollback.
+ live: true,
+ };
+ if (siblings.length > 1) block.subtitle = `#${siblings.length}`;
+ this.#pushBlock(block);
}
#upsertBlock(block: Block) {
@@ -2407,6 +2863,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
const existing = block.id ? this.#blockById.get(block.id) : undefined;
if (existing) {
Object.assign(existing, block);
+ // An in-place update is activity: recency windows must treat this
+ // block as the newest, not leave it at its announce position.
+ existing.updateSeq = ++this.#updateSequence;
return;
}
this.#pushBlock(block);
@@ -2439,26 +2898,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
turnState: RenderTurnState,
): void {
switch (event.type) {
- case "step-start":
- this.#setStreamStatus(
- turnState.hasPendingToolResults ? STATUS.toolResults : STATUS.processing,
- );
- turnState.hasPendingToolResults = false;
- break;
-
case "step-finish":
// Step usage reports are per-step deltas (extractStepUsage in the
// harness), so summing them yields true session totals. The
// `finish` event replays the last step's usage — don't sum there.
this.#diagnostics?.recordStepUsage(event.usage);
+ if (event.usage !== undefined) {
+ this.#turnClock.addUsage(event.usage);
+ }
+ // A valid call upgrades from its `preparing` placeholder within its
+ // own step; one still preparing at the boundary never parsed (the
+ // model emitted bad JSON and will retry under a fresh call id) and
+ // must not linger as a `Search …` ghost.
+ this.#sweepPreparingToolBlocks(turnState);
this.#applyUsage(event.usage);
this.#paint();
break;
case "assistant-delta": {
const text = (turnState.text.get(event.id) ?? "") + stripTerminalControls(event.delta);
- this.#showAnswerContent(text);
- this.#setStreamStatus(STATUS.streaming);
turnState.text.set(event.id, text);
this.#upsertAssistantBlock(event.id, text, true);
break;
@@ -2470,7 +2928,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
event.text !== undefined && existing.length === 0
? stripTerminalControls(event.text ?? "")
: existing;
- this.#showAnswerContent(text);
turnState.text.set(event.id, text);
this.#upsertAssistantBlock(event.id, text, false);
break;
@@ -2479,25 +2936,47 @@ export class TerminalRenderer implements AgentTUIRenderer {
case "reasoning-delta": {
if (displayModes.reasoning === "hidden") break;
const text = (turnState.reasoning.get(event.id) ?? "") + stripTerminalControls(event.delta);
- this.#showAnswerContent(text);
- this.#setStreamStatus(STATUS.streaming);
turnState.reasoning.set(event.id, text);
- this.#upsertReasoningBlock(event.id, text, true, displayModes);
+ if (displayModes.reasoning === "full") {
+ this.#upsertReasoningBlock(event.id, text, true, displayModes);
+ break;
+ }
+ // Collapsed modes: the trace never reaches the transcript — the live
+ // turn bar and the end-of-turn coda carry the turn's progress.
break;
}
case "reasoning-complete": {
if (displayModes.reasoning === "hidden") break;
const text = turnState.reasoning.get(event.id) ?? "";
- this.#showAnswerContent(text);
- this.#upsertReasoningBlock(event.id, text, false, displayModes);
+ if (displayModes.reasoning === "full") {
+ this.#upsertReasoningBlock(event.id, text, false, displayModes);
+ break;
+ }
break;
}
+ case "tool-call-preparing":
+ if (displayModes.tools === "hidden") break;
+ // Panel-routed tools need the real input; their placeholder would
+ // misread an input-less call (e.g. as a todo read).
+ if (isPanelRoutedTool(event.toolName)) break;
+ this.#upsertNativeTool(
+ {
+ input: undefined,
+ preparing: true,
+ status: "running",
+ toolCallId: event.toolCallId,
+ toolName: event.toolName,
+ },
+ displayModes,
+ turnState,
+ );
+ break;
+
case "tool-call":
this.#diagnostics?.recordToolCall(event.toolName);
if (displayModes.tools === "hidden") break;
- this.#setStreamStatus(STATUS.executingTools);
this.#upsertNativeTool(
{
input: event.input,
@@ -2522,8 +3001,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (displayModes.tools === "hidden") break;
const existing = this.#resolveNativeToolState(event.toolCallId, turnState);
if (existing === undefined) break;
- turnState.hasPendingToolResults = true;
- this.#setStreamStatus(STATUS.toolResults);
this.#upsertNativeTool(
{ ...existing, output: event.output, status: "done" },
displayModes,
@@ -2542,8 +3019,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
});
if (displayModes.tools === "hidden") break;
if (existing === undefined) break;
- turnState.hasPendingToolResults = true;
- this.#setStreamStatus(STATUS.toolResults);
this.#upsertNativeTool(
{ ...existing, errorText: event.errorText, status: "error" },
displayModes,
@@ -2552,6 +3027,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
break;
}
+ case "tool-rejected": {
+ if (displayModes.tools === "hidden") break;
+ const existing = this.#resolveNativeToolState(event.toolCallId, turnState);
+ if (existing === undefined) break;
+ this.#upsertNativeTool(
+ { ...existing, errorText: event.reason, status: "denied" },
+ displayModes,
+ turnState,
+ );
+ break;
+ }
+
case "error":
this.#addErrorBlock("Error", event.errorText, { detail: event.detail, hint: event.hint });
break;
@@ -2563,17 +3050,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
- #setStreamStatus(status: string): void {
- const next = this.#connectionAuthPendingCount > 0 ? STATUS.connectionAuth : status;
- if (this.#status === next) return;
- this.#status = next;
- this.#paint();
- }
-
- #showAnswerContent(text: string): void {
- if (text.trim().length > 0) this.#turnIndicator = { kind: "answering" };
- }
-
#upsertAssistantBlock(id: string, text: string, live: boolean): void {
const content = stripTerminalControls(text).trim();
if (content.length === 0) return;
@@ -2601,13 +3077,137 @@ export class TerminalRenderer implements AgentTUIRenderer {
): void {
turnState.tools.set(tool.toolCallId, tool);
if (this.#childToolCallIds.has(tool.toolCallId)) return;
+ if (this.#applyTodoToolCall(tool)) return;
+ // The question surface — overlay while open, `? … ⎿ …` once answered —
+ // is the whole story of an ask_question call; a tool block beside it
+ // would narrate the same thing twice. Together with #applyTodoToolCall
+ // this is the full-call half of isPanelRoutedTool (read-only todo calls
+ // deliberately fall through to an ordinary block).
+ if (toolBaseName(tool.toolName) === "ask_question") return;
const id = toolSectionId(tool.toolCallId);
this.#parentToolBlockIds.set(tool.toolCallId, id);
- this.#upsertBlock(renderNativeToolBlock(tool, id, displayModes.tools === "full"));
+ const context = this.#toolPresentationContext(tool);
+ this.#upsertBlock(renderNativeToolBlock(tool, id, displayModes.tools === "full", context));
+ this.#syncNativeToolBlockLiveness(turnState);
this.#paint();
}
+ /**
+ * Feeds the file-content cache from the call and derives the presentation
+ * context a write needs for its diff. Read results (full-file only) and
+ * write inputs are the two exact sources the session has.
+ */
+ #toolPresentationContext(tool: {
+ readonly input?: unknown;
+ readonly output?: unknown;
+ readonly toolCallId: string;
+ readonly toolName: string;
+ }): ToolPresentationContext | undefined {
+ if (tool.output !== undefined) this.#fileContents.observeRead(tool.output);
+
+ const context: { previousContent?: string; existed?: boolean; isSubagent?: boolean } = {};
+ if (this.#isSubagentToolName(tool.toolName)) context.isSubagent = true;
+
+ const write = readWriteFileInput(tool.toolName, tool.input);
+ if (write === undefined) {
+ return context.isSubagent === true ? context : undefined;
+ }
+ const previous = this.#fileContents.observeWrite({
+ path: write.path,
+ content: write.content,
+ callId: tool.toolCallId,
+ });
+ if (previous !== undefined) context.previousContent = previous;
+ const existed = writeExistedFlag(tool.output);
+ if (existed !== undefined) context.existed = existed;
+ return context;
+ }
+
+ /** True when a tool name matches a subagent from the agent's roster. */
+ #isSubagentToolName(toolName: string): boolean {
+ const local = this.#agentHeader?.info?.subagents.local;
+ if (local === undefined || local.length === 0) return false;
+ const baseName = toolBaseName(toolName);
+ return local.some((subagent) => subagent.name === baseName);
+ }
+
+ /**
+ * Flips still-running tool blocks of an interrupted turn to a terminal
+ * state. Approval-parked blocks are spared — a later pass can still
+ * settle them.
+ */
+ #settleInterruptedToolBlocks(): void {
+ for (const block of this.#blocks) {
+ if (block.kind !== "tool" && block.kind !== "subagent-tool") continue;
+ if (block.status !== "running") continue;
+ block.status = "error";
+ block.result = "interrupted";
+ block.live = false;
+ }
+ }
+
+ /**
+ * Removes tool blocks that never left their `preparing` placeholder. Runs
+ * at step boundaries and at stream teardown: an announced call whose input
+ * never parsed (invalid JSON, an interrupted generation) has no
+ * `actions.requested` coming and would otherwise commit as a `… ` ghost.
+ */
+ #sweepPreparingToolBlocks(turnState: RenderTurnState): void {
+ for (const [toolCallId, tool] of turnState.tools) {
+ if (tool.preparing !== true) continue;
+ turnState.tools.delete(toolCallId);
+ const id = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);
+ this.#removeBlock(id);
+ this.#parentToolBlockIds.delete(toolCallId);
+ }
+ }
+
+ /**
+ * Routes a `todo` replacement write into the pinned panel instead of a
+ * transcript tool block. The whole list arrives with every call, so the
+ * panel is replaced wholesale; once every item settles the finished list
+ * commits to the transcript and the panel clears. Returns `false` for
+ * non-todo calls and read-only todo calls, which keep their ordinary block.
+ */
+ #applyTodoToolCall(tool: NativeToolState): boolean {
+ const items = readTodoToolItems(tool.toolName, tool.input);
+ if (items === undefined) return false;
+
+ if (items.length > 0 && allTodoItemsSettled(items)) {
+ // The call's result event re-plays through here; commit only once per
+ // list content.
+ const signature = JSON.stringify(items);
+ if (this.#todoCommittedSignature !== signature) {
+ this.#todoCommittedSignature = signature;
+ this.#pushBlock({
+ kind: "todo-list",
+ body: renderFinishedTodoRows(items, this.#width(), this.#theme).join("\n"),
+ live: false,
+ });
+ }
+ this.#todoItems = undefined;
+ } else {
+ this.#todoItems = items.length > 0 ? items : undefined;
+ this.#todoCommittedSignature = undefined;
+ }
+ this.#paint();
+ return true;
+ }
+
+ /** Keeps one parallel tool cohort mutable until every independent call settles. */
+ #syncNativeToolBlockLiveness(turnState: RenderTurnState): void {
+ const entries: Array<{ block: Block; active: boolean }> = [];
+ for (const tool of turnState.tools.values()) {
+ if (this.#childToolCallIds.has(tool.toolCallId)) continue;
+ const id = this.#parentToolBlockIds.get(tool.toolCallId) ?? toolSectionId(tool.toolCallId);
+ const block = this.#blockById.get(id);
+ if (block?.kind !== "tool") continue;
+ entries.push({ block, active: isActiveToolStatus(tool.status) });
+ }
+ applyCohortLiveness(entries);
+ }
+
#resolveNativeToolState(
toolCallId: string,
turnState: RenderTurnState,
@@ -2630,7 +3230,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
output: block.toolOutput,
status: block.status ?? "running",
toolCallId,
- toolName: block.title ?? "tool",
+ toolName: block.toolName ?? block.title ?? "tool",
};
}
@@ -2640,6 +3240,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (inputTokens != null || outputTokens != null) {
this.#totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);
}
+ this.#promptTokens = inputTokens ?? this.#promptTokens;
this.#assistantOutputTokens = outputTokens ?? this.#assistantOutputTokens;
if (this.#assistantOutputTokens != null && this.#streamStartedAt !== undefined) {
@@ -2686,16 +3287,32 @@ export class TerminalRenderer implements AgentTUIRenderer {
// blocks still enter the block history (so a later `/loglevel` can render
// them) but contribute no rows and leave `previous` untouched — gap and
// log-run decisions must behave as if the hidden block were not there.
- while (this.#blocks.length > 0 && this.#blocks[0]!.live === false) {
- const block = this.#blocks.shift()!;
- this.#transcriptBlocks.push(block);
- if (block.id) {
- this.#committedIds.add(block.id);
- this.#blockById.delete(block.id);
+ const groups = groupToolBlocksForDisplay(this.#blocks);
+ let settled = 0;
+ // A group's display carries the liveness of its whole run (a counted
+ // subagent header stays live while its children stream), so the settled
+ // prefix is judged on displays, not on raw leading blocks.
+ while (settled < groups.length && groups[settled]!.display.live === false) settled += 1;
+
+ if (settled > 0) {
+ // Coalesced groups can skip interleaved members of another outcome or
+ // call, so committed members must be removed by identity.
+ const committedMembers = new Set(groups.slice(0, settled).flatMap((group) => group.members));
+ for (let i = this.#blocks.length - 1; i >= 0; i -= 1) {
+ if (committedMembers.has(this.#blocks[i]!)) this.#blocks.splice(i, 1);
}
- if (this.#isHiddenLog(block)) continue;
- const rows = this.#renderBlock(block, width, previous);
- previous = previousBlockOf(block);
+ }
+ for (const group of groups.slice(0, settled)) {
+ for (const block of group.members) {
+ this.#transcriptBlocks.push(block);
+ if (block.id) {
+ this.#committedIds.add(block.id);
+ this.#blockById.delete(block.id);
+ }
+ }
+ if (this.#isHiddenLog(group.display)) continue;
+ const rows = this.#renderBlock(group.display, width, previous);
+ previous = previousBlockOf(group.display);
this.#lastCommitted = previous;
committed.push(...rows);
this.#committedTranscriptRows.push(...rows);
@@ -2705,7 +3322,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
// a live block may rewrap or receive new deltas on the next paint, and
// terminal scrollback cannot be corrected once written.
const flat: Array<{ block: Block; row: string }> = [];
- for (const block of this.#blocks) {
+ for (const { display: block } of groups.slice(settled)) {
if (this.#isHiddenLog(block)) continue;
const rows = this.#renderBlock(block, width, previous);
previous = previousBlockOf(block);
@@ -2738,7 +3355,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
let previous = this.#lastCommitted;
const flat: string[] = [];
- for (const block of this.#blocks) {
+ for (const { display: block } of groupToolBlocksForDisplay(this.#blocks)) {
if (this.#isHiddenLog(block)) continue;
const rows = this.#renderBlock(block, width, previous);
previous = previousBlockOf(block);
@@ -2777,7 +3394,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const body = this.#delayedDevBuildError;
if (body === undefined) return;
this.#delayedDevBuildError = undefined;
- this.#pushBlock({ kind: "log", title: "stderr", body, live: false });
+ this.#pushBlock({ kind: "log", title: "stderr", body, live: true });
this.#paint();
}
@@ -2808,7 +3425,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
const width = this.#width();
this.#committedTranscriptRows.length = 0;
let previous: PreviousBlock | undefined;
- for (const block of this.#transcriptBlocks) {
+ // Committed log writes re-render at their committed positions —
+ // window-scoped stream coalescing would relocate every past write to
+ // the end of the transcript on a `/loglevel` toggle.
+ for (const { display: block } of groupToolBlocksForDisplay(this.#transcriptBlocks, {
+ logCoalescing: "runs",
+ })) {
if (this.#isHiddenLog(block)) continue;
const rows = this.#renderBlock(block, width, previous);
previous = previousBlockOf(block);
@@ -2830,8 +3452,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
return buildAgentHeader(input);
}
- #renderBlock(block: Block, width: number, previous: PreviousBlock | undefined): string[] {
- const context: Parameters<typeof renderBlockLines>[3] = { spinner: this.#spinnerFrame() };
+ #renderBlock(block: DisplayBlock, width: number, previous: PreviousBlock | undefined): string[] {
+ const context: Parameters<typeof renderBlockLines>[3] = {
+ activityPulse: this.#progressPulseGlyph(
+ this.#activityPulseStartedAtMs,
+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
+ ),
+ };
if (previous !== undefined) context.previous = previous;
const rows = renderBlockLines(block, width, this.#theme, context);
if ((block.depth ?? 0) === 0 && leadsWithGap(block, previous)) {
@@ -2865,6 +3492,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
const c = this.#theme.colors;
const rows: string[] = [""];
+ // The HITL question overlay owns the footer down to the status bar —
+ // no indicator or hint row beneath it (the panel carries its own).
+ if (this.#questionPanel !== undefined) {
+ rows.push(...this.#questionPanel(width), "");
+ this.#pushStatusLine(rows, width);
+ return rows;
+ }
+
const flow = this.#setupFlow;
if (flow !== undefined) {
// No status line under an open flow panel: the flow is mutating the
@@ -2908,6 +3543,24 @@ export class TerminalRenderer implements AgentTUIRenderer {
return rows;
}
+ // The pinned todo panel holds its place above the prompt, updated in
+ // place by each `todo` tool call rather than scrolling with the stream.
+ if (this.#todoItems !== undefined) {
+ rows.push(
+ ...renderTodoPanelRows({
+ items: this.#todoItems,
+ width,
+ theme: this.#theme,
+ working: this.#streamDraftActive || this.#turnIndicator.kind === "waiting",
+ pulse: this.#progressPulseGlyph(
+ this.#activityPulseStartedAtMs,
+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
+ ),
+ }),
+ "",
+ );
+ }
+
// The setup attention line rides just above the prompt as a live element,
// so resolving its issue clears it instead of leaving it stale in scrollback.
if (this.#setupAttention !== undefined) {
@@ -2937,53 +3590,146 @@ export class TerminalRenderer implements AgentTUIRenderer {
// prompt. Everything already in `rows` has higher-level footer ownership
// (attention or typeahead), so the prompt receives only what remains.
const maxPromptRows = Math.max(1, this.#height() - 1 - rows.length - 1 - statusRows.length);
- rows.push(
- ...promptInputRows({
- text: this.#inputText,
- cursor: this.#inputCursor,
- width,
- theme: this.#theme,
- caretVisible: this.#caretVisible,
- isCommand,
- ghost,
- maxRows: maxPromptRows,
- }),
- );
+ const promptRows: Parameters<typeof promptInputRows>[0] = {
+ text: this.#inputText,
+ cursor: this.#inputCursor,
+ width,
+ theme: this.#theme,
+ caretVisible: this.#caretVisible,
+ isCommand,
+ ghost,
+ maxRows: maxPromptRows,
+ };
+ // An empty chat prompt always wears the quiet `›`; the rotating
+ // invitation text rides it only until the user's first message.
+ if (this.#promptPlaceholderActive && this.#inputText.length === 0) {
+ promptRows.placeholder = this.#hasUserMessage
+ ? ""
+ : promptPlaceholder(Date.now() - this.#promptPlaceholderStartedAtMs);
+ }
+ rows.push(...promptInputRows(promptRows));
rows.push(...statusRows);
return rows;
}
const turnIndicator = this.#turnIndicator;
- if (turnIndicator.kind === "answering") {
+ // Every waiting state — a streaming turn, a just-submitted prompt, a
+ // question answer or approval resuming — shows the one live turn bar,
+ // with the inert prompt anchored beneath it while a stream owns the
+ // turn. The `└ Done in …` coda is this bar's settled form.
+ const waitingOnStream = turnIndicator.kind === "waiting" && this.#flowlessStatus === undefined;
+ if (this.#streamDraftActive || waitingOnStream) {
+ rows.push(this.#streamingTurnBar(width));
+ this.#pushStreamingPrompt(rows, width);
+ const statusRows: string[] = [];
+ this.#pushStatusLine(statusRows, width);
+ if (!this.#streamDraftActive && statusRows.length > 0) rows.push("");
+ rows.push(...statusRows);
+ return rows;
+ }
+
+ // A draft carried out of a finished turn renders ACTIVE immediately —
+ // the dim inert mark must not linger once the agent has returned. Keys
+ // pressed in this gap buffer and replay into the next prompt, so the
+ // cyan mark is honest.
+ if (this.#streamDraft.text.length > 0) {
+ this.#pushDraftPrompt(rows, width, { inert: false });
this.#pushStatusLine(rows, width);
return rows;
}
- const working = turnIndicator.kind === "waiting";
- const icon = working
- ? c.green(
- this.#progressPulseGlyph(
- turnIndicator.startedAtMs,
- this.#theme.unicode ? TURN_PULSE_GLYPH : TURN_PULSE_ASCII_GLYPH,
- ),
- )
- : c.dim(this.#theme.glyph.dot);
- const statusText = this.#status.length > 0 ? this.#status : "Ready";
- // Dim the live streaming status (the pulse carries the eye); keep
- // interactive prompts (approvals, questions) at full intensity.
- const status = working ? c.dim(statusText) : statusText;
+
+ // Interactive prompts (approvals, connection auth), the flowless setup
+ // spinner, and transitional states render as a quiet dot-led status row.
+ const statusText = this.#flowlessStatus ?? (this.#status.length > 0 ? this.#status : "Ready");
const meta = this.#statusMeta();
- const indent = working ? " " : "";
+ const icon = c.dim(this.#theme.glyph.dot);
const line = meta
- ? `${indent}${icon} ${status} ${c.dim(this.#theme.glyph.dot)} ${meta}`
- : `${indent}${icon} ${status}`;
+ ? `${icon} ${statusText} ${c.dim(this.#theme.glyph.dot)} ${meta}`
+ : `${icon} ${statusText}`;
rows.push(clip(line, width));
- const statusRows: string[] = [];
- this.#pushStatusLine(statusRows, width);
- if (working && statusRows.length > 0) rows.push("");
- rows.push(...statusRows);
+ this.#pushStatusLine(rows, width);
return rows;
}
+ /**
+ * The live turn bar: `▪ Working for 3min 24s ── ↑ 32.4K ↓ 682`. Duration and
+ * token flow tick live on the shared paint beat; the `└`-cornered coda
+ * is this bar's settled form.
+ */
+ #streamingTurnBar(width: number): string {
+ const c = this.#theme.colors;
+ const pulse = this.#progressPulseGlyph(
+ this.#activityPulseStartedAtMs,
+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
+ );
+ // A waiting state without an armed turn clock (a /command flash, an
+ // isolated approval) still gets a ticking duration from its own start.
+ const turnIndicator = this.#turnIndicator;
+ const startedAtMs =
+ this.#turnClock.startedAtMs ??
+ this.#streamStartedAt ??
+ (turnIndicator.kind === "waiting" ? turnIndicator.startedAtMs : Date.now());
+ const elapsedMs = Date.now() - startedAtMs;
+ // Anchored to the turn clock, the label's reveal plays once per turn —
+ // a question answer's continuation pass resumes fully typed.
+ const label = typewriterText("Working for", elapsedMs, turnBarTypewriterMs);
+ const body = `${label} ${this.#turnStatsBody(elapsedMs)}`;
+ // Column 0: the bar shares the gutter with the conversation markers and
+ // its own settled `└` coda.
+ return clip(`${c.yellow(pulse)} ${c.dim(body)}`, width);
+ }
+
+ /**
+ * The shared body of the live turn bar and the settled coda:
+ * `3min 24s ── ↑ 32.4K ↓ 682` (token flow only once the turn has moved a
+ * token). `MockScreen.waitForIdlePrompt` recognizes the live bar by its
+ * typewriter `Working` label followed by this duration.
+ */
+ #turnStatsBody(elapsedMs: number): string {
+ return `${formatTurnDuration(elapsedMs)}${this.#turnFlowSuffix()}`;
+ }
+
+ /** ` ── ↑ 32.4K ↓ 682` once the turn has moved a token; empty before. */
+ #turnFlowSuffix(): string {
+ const { inputTokens, outputTokens } = this.#turnClock.usage;
+ if (inputTokens === 0 && outputTokens === 0) return "";
+ const seg = this.#theme.glyph.dash.repeat(2);
+ return ` ${seg} ${formatTokenFlow({ inputTokens, outputTokens }, this.#theme.glyph)}`;
+ }
+
+ /**
+ * The prompt row held in place while a turn streams: the draft under a
+ * live caret, Enter inert. Keeps the input anchored instead of vanishing
+ * for the duration of the turn.
+ */
+ #pushStreamingPrompt(rows: string[], width: number): void {
+ if (!this.#streamDraftActive) return;
+ // An empty pending prompt wears the same quiet `›` as the idle one; a
+ // typed draft flips to a DIM `❯` (inert — Enter does nothing yet).
+ // Readiness is therefore NOT detectable from the glyph — MockScreen's
+ // `waitForIdlePrompt` discriminates by the live turn bar's absence.
+ this.#pushDraftPrompt(rows, width, { inert: true });
+ }
+
+ /** The `#streamDraft` rendered as a prompt row — inert mid-turn, active in
+ * the gap between the turn ending and the next prompt arming. */
+ #pushDraftPrompt(rows: string[], width: number, options: { inert: boolean }): void {
+ rows.push("");
+ const prompt: Parameters<typeof promptInputRows>[0] = {
+ text: this.#streamDraft.text,
+ cursor: this.#streamDraft.cursor,
+ width,
+ theme: this.#theme,
+ caretVisible: true,
+ isCommand: false,
+ ghost: "",
+ maxRows: 4,
+ inert: options.inert,
+ };
+ if (options.inert && this.#streamDraft.text.length === 0) prompt.placeholder = "";
+ rows.push(...promptInputRows(prompt));
+ }
+
/** Appends the persistent bottom status line below the prompt when it has content. */
#pushStatusLine(rows: string[], width: number): void {
const padding = this.#remoteConnection === undefined ? "" : STATUS_LINE_LEFT_PADDING;
@@ -3011,6 +3757,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
// header, so the status bar consumes that shared snapshot.
const endpoint = agentModel?.endpoint;
if (endpoint !== undefined) input.endpoint = endpoint;
+ // Token flow lives in the end-of-turn coda, not the persistent bar — a
+ // live counter mostly restates the last step's context size.
if (this.#vercelStatus !== undefined) input.vercel = this.#vercelStatus;
if (this.#remoteConnection !== undefined) input.remote = this.#remoteConnection;
const line = buildStatusLine(input);
@@ -3176,7 +3924,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const body = pending.join("\n");
pending = [];
if (body.trim().length === 0) return;
- this.#pushBlock({ kind: "log", title: "stdout", body, live: false });
+ this.#pushBlock({ kind: "log", title: "stdout", body, live: true });
};
for (const line of content.split("\n")) {
@@ -3205,12 +3953,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
});
if (failedIndex === -1) {
if (this.#diagnostics === undefined) {
- this.#pushBlock({ kind: "log", title: "stderr", body: content, live: false });
+ this.#pushBlock({ kind: "log", title: "stderr", body: content, live: true });
return;
}
const presentation = presentDiagnostic(content, this.#diagnostics.displayPath);
if (presentation.kind === "inline") {
- this.#pushBlock({ kind: "log", title: "stderr", body: presentation.text, live: false });
+ this.#pushBlock({ kind: "log", title: "stderr", body: presentation.text, live: true });
return;
}
this.#pushBlock({
@@ -3218,21 +3966,21 @@ export class TerminalRenderer implements AgentTUIRenderer {
title: "stderr",
body: formatStoredDiagnostic(presentation),
logVisibility: "stderr-only",
- live: false,
+ live: true,
});
this.#pushBlock({
kind: "log",
title: "stderr",
body: content,
logVisibility: "all-only",
- live: false,
+ live: true,
});
return;
}
const previous = lines.slice(0, failedIndex).join("\n");
if (previous.trim().length > 0) {
- this.#pushBlock({ kind: "log", title: "stderr", body: previous, live: false });
+ this.#pushBlock({ kind: "log", title: "stderr", body: previous, live: true });
}
const failedBody = lines.slice(failedIndex).join("\n");
this.#handleDevRebuildFailure(failedBody);
@@ -3241,7 +3989,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
#handleDevRebuildFailure(body: string): void {
if (this.#logs === "all") {
if (body.trim().length === 0) return;
- this.#pushBlock({ kind: "log", title: "stderr", body, live: false });
+ this.#pushBlock({ kind: "log", title: "stderr", body, live: true });
return;
}
this.#delayedDevBuildError = body;
@@ -3289,7 +4037,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
return;
}
if (update.kind === "rebuilt") this.#delayedDevBuildError = undefined;
- this.#pushBlock({ kind: "log", title: "stdout", body: line, live: false });
+ this.#pushBlock({ kind: "log", title: "stdout", body: line, live: true });
}
/** The rebuild status block still cycling in place, if any. */
@@ -3379,6 +4127,14 @@ interface PromptInputRowsInput {
readonly isCommand: boolean;
readonly ghost: string;
readonly maxRows: number;
+ /**
+ * Present on an empty chat prompt: switches the gutter to the quiet `›`.
+ * Non-empty text renders dim behind the caret; the empty string keeps the
+ * quiet mark with a bare caret (the post-first-message state).
+ */
+ placeholder?: string;
+ /** Anchored-but-inert prompt (streaming turn): typed drafts show a dim `❯`. */
+ inert?: boolean;
}
/**
@@ -3396,8 +4152,28 @@ function promptInputRows({
isCommand,
ghost,
maxRows,
+ placeholder,
+ inert,
}: PromptInputRowsInput): string[] {
const c = theme.colors;
+
+ if (text.length === 0 && placeholder !== undefined) {
+ // The empty state trades the active `❯` for a quiet `›` and lets the
+ // caret rest on the placeholder's first character, like the setup
+ // panel's text fields.
+ const body = renderInputWithBlockCursor({
+ ...visibleLine(
+ { text: placeholder, cursor: 0 },
+ Math.max(1, width - 3),
+ theme.glyph.ellipsis,
+ ),
+ visible: caretVisible,
+ inverse: c.inverse,
+ render: (segment) => c.dim(renderInputText(segment)),
+ });
+ return [clip(`${c.dim(theme.glyph.promptIdle)} ${body}`, width), ""];
+ }
+
const style = (segment: string): string => {
const rendered = renderInputText(segment);
return isCommand && rendered.length > 0 ? c.blue(rendered) : rendered;
@@ -3409,10 +4185,14 @@ function promptInputRows({
0,
Math.min(layout.caretRow - visibleCount + 1, layout.rows.length - visibleCount),
);
- const promptGlyph = c.cyan(theme.glyph.prompt);
+ // An inert prompt's typed draft flips the mark like the active prompt,
+ // but keeps it dim: the state is legible without claiming readiness.
+ const promptGlyph = inert === true ? c.dim(theme.glyph.prompt) : c.cyan(theme.glyph.prompt);
const ellipsis = c.dim(theme.glyph.ellipsis);
- // Reserve the leading pad, gutter, and block cursor's trailing cell at end-of-line.
- const budget = Math.max(1, width - 4);
+ // Reserve the gutter and the block cursor's trailing cell at end-of-line.
+ // The gutter sits at column 0, sharing a column with the conversation
+ // markers (`│`, `▲`).
+ const budget = Math.max(1, width - 3);
const out: string[] = [];
for (let r = top; r < top + visibleCount; r += 1) {
const row = layout.rows[r]!;
@@ -3443,7 +4223,7 @@ function promptInputRows({
} else {
body = style(row.text);
}
- out.push(clip(` ${gutter} ${body}`, width));
+ out.push(clip(`${gutter} ${body}`, width));
}
out.push("");
return out;
@@ -3460,23 +4240,44 @@ function previousBlockOf(block: Block): PreviousBlock {
/**
* Decides whether a block gets a blank line above it. Top-level "speakers"
- * (user, assistant, reasoning, …) always breathe; tool rows stay tight under
- * the message they belong to. Log runs breathe on both sides — the run leads
- * with a gap and whatever follows it gets one too — except between
- * consecutive same-source log blocks, which read as one continuous run
- * (their labels are suppressed by the renderer for the same reason).
+ * (user, assistant, reasoning, …) always breathe. The first tool block after
+ * a user prompt breathes too; subsequent tool rows stay tight within the run.
+ * Log sections breathe on both sides — every captured write renders as a
+ * closed `○ <source> … └` section, so consecutive writes get air between
+ * their corners and headers.
*/
+/** A call still holding the cohort open: executing, or parked on approval. */
+function isActiveToolStatus(status: ToolStatus | undefined): boolean {
+ return status === "running" || status === "approval";
+}
+
+/**
+ * One parallel cohort stays mutable until every independent call settles:
+ * while any member is active, settled siblings stay live so an in-flight
+ * batch accumulates as one group instead of fragmenting per status flip.
+ * Shared by the top-level tool cohort and each subagent section's children.
+ */
+function applyCohortLiveness(entries: ReadonlyArray<{ block: Block; active: boolean }>): void {
+ const cohortActive = entries.some((entry) => entry.active);
+ for (const entry of entries) {
+ entry.block.live = cohortActive || entry.active;
+ }
+}
+
function leadsWithGap(block: Block, previous: PreviousBlock | undefined): boolean {
+ // A tool run breathes after whoever spoke last — the prompt, the agent's
+ // own prose, or an answered question — and stays tight within the run.
+ if (
+ block.kind === "tool" &&
+ (previous?.kind === "user" || previous?.kind === "assistant" || previous?.kind === "question")
+ ) {
+ return true;
+ }
if (block.kind === "sandbox" && previous?.kind === "sandbox") {
return false;
}
if (previous?.kind === "sandbox" && block.kind !== "sandbox") return true;
- if (block.kind === "log" && previous?.kind === "log") {
- // stdout → stderr (or vice versa) gets air; a same-source continuation
- // stays tight beneath the run it extends.
- return previous.title !== block.title;
- }
- if (previous?.kind === "log" && block.kind !== "log") return true;
+ if (previous?.kind === "log") return true;
switch (block.kind) {
case "user":
case "assistant":
@@ -3494,6 +4295,9 @@ function leadsWithGap(block: Block, previous: PreviousBlock | undefined): boolea
case "command":
case "warning":
case "flow":
+ case "turn-stats":
+ case "session-boundary":
+ case "todo-list":
case "agent-header":
return true;
// The elbow result hangs tight under its invocation — never a gap.
@@ -3561,20 +4365,38 @@ function collapseReasoning(mode: TerminalPartDisplayMode, isLastPart: boolean):
}
}
-function renderNativeToolBlock(tool: NativeToolState, id: string, expanded: boolean): Block {
+function renderNativeToolBlock(
+ tool: NativeToolState,
+ id: string,
+ expanded: boolean,
+ context?: ToolPresentationContext,
+): Block {
+ const presentation =
+ tool.preparing === true
+ ? presentPreparingTool(tool.toolName, context)
+ : presentTool(tool.toolName, tool.input, context);
const block: Block = {
id,
kind: "tool",
- title: stripTerminalControls(tool.toolName),
- subtitle: summarizeToolArgs(tool.input),
+ title: stripTerminalControls(presentation.title),
+ subtitle: stripTerminalControls(presentation.subtitle),
status: tool.status,
live: tool.status === "running" || tool.status === "approval",
expanded,
toolInput: tool.input,
+ toolName: tool.toolName,
+ toolGroup: presentation.group,
};
+ if (presentation.doneTitle !== undefined) {
+ block.doneTitle = stripTerminalControls(presentation.doneTitle);
+ }
+ if (presentation.detail !== undefined) {
+ block.detailLines = presentation.detail;
+ block.keepDetailWhenDone = presentation.keepDetailWhenDone === true;
+ }
if (tool.output !== undefined) {
- block.result = summarizeToolResult(tool.output);
+ block.result = presentation.summarizeResult(tool.output);
block.toolOutput = tool.output;
} else if (tool.errorText !== undefined) {
block.result = stripTerminalControls(tool.errorText);
@@ -3583,8 +4405,17 @@ function renderNativeToolBlock(tool: NativeToolState, id: string, expanded: bool
return block;
}
+/** Reads the shared write-file result's `existed` flag, whatever the tool. */
+function writeExistedFlag(output: unknown): boolean | undefined {
+ if (output === null || typeof output !== "object" || Array.isArray(output)) return undefined;
+ const existed = (output as Record<string, unknown>)["existed"];
+ return typeof existed === "boolean" ? existed : undefined;
+}
+
function subagentToolStatus(status: SubagentToolUpdate["status"]): ToolStatus {
switch (status) {
+ case "preparing":
+ return "running";
case "approval-requested":
return "approval";
case "executing":
@@ -3593,6 +4424,8 @@ function subagentToolStatus(status: SubagentToolUpdate["status"]): ToolStatus {
return "done";
case "failed":
return "error";
+ case "rejected":
+ return "denied";
}
}
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 0bd14e1a9..764675e9d 100644
--- a/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
+++ b/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
@@ -125,6 +125,37 @@ export class MockScreen extends EventEmitter implements TerminalOutput {
return this.#rawOutput;
}
+ /**
+ * Resolves once the runner parks at an idle prompt: a column-0 `›` row
+ * with no live turn bar on screen. A streaming turn keeps an identical
+ * `›` prompt anchored (Enter inert), so the glyph alone cannot signal
+ * readiness — the bar's absence is the discriminator.
+ */
+ async waitForIdlePrompt(timeoutMs = 1000) {
+ // The live turn bar: `▪ Working for <duration>…` at column 0 (pulse-off
+ // frames blank the mark; the label may be mid-typewriter but is always
+ // an exact prefix of "Working for", and the duration follows it). The
+ // exact-prefix alternation plus the digit keeps it from matching the
+ // `└ Done in …` coda, prompt rows, ordinary prose, and the todo panel.
+ const barLabel = "Working for";
+ const labelPrefixes = Array.from({ length: barLabel.length }, (_, index) =>
+ barLabel.slice(0, index + 1),
+ );
+ const liveTurnBar = new RegExp(`^[▪* ] (?:${labelPrefixes.join("|")}) \\d`, "mu");
+ // Unicode glyphs only: the ASCII prompt mark (`>`) is ambiguous with the
+ // ASCII brand mark, and every TUI smoke script pins EVE_TUI_UNICODE=1.
+ const idle = () => {
+ const snapshot = this.snapshot();
+ return /^[›❯]/mu.test(snapshot) && !liveTurnBar.test(snapshot);
+ };
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (idle()) return;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ throw new Error(`Timed out waiting for an idle prompt.\n\nScreen:\n${this.snapshot()}`);
+ }
+
async waitForText(text: string, timeoutMs = 1000, getDebugOutput = () => this.snapshot()) {
if (this.snapshot().includes(text)) {
return;
diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.ts
index d20cf71b3..9b8a5902f 100644
--- a/packages/eve/src/cli/dev/tui/theme.ts
+++ b/packages/eve/src/cli/dev/tui/theme.ts
@@ -61,17 +61,27 @@ export interface ThemeColors {
export interface ThemeGlyphs {
/** `▲` — the Vercel/eve brand mark; prefixes the agent's own output. */
brand: string;
- /** `▌` — left gutter bar marking a user message. */
+ /** `│` — left gutter bar marking a user message. */
user: string;
/** `○` — reasoning / "thinking" marker (Next.js "wait" glyph). */
reasoning: string;
+ /** `▪` — static tool-activity mark (the settled form of the activity pulse). */
+ square: string;
+ /** `└` — closes a `│`-railed detail region under a tool header. */
+ corner: string;
+ /** `┌` — opens a region; pairs with `corner` at session boundaries. */
+ cornerOpen: string;
+ /** `⌝` — marks a provider endpoint authored in the agent's own code. */
+ external: string;
+ /** `⏺` — the in-progress todo item (pulses while the turn runs). */
+ dotActive: string;
/** `✓` — a completed tool or success state. */
success: string;
/** `⨯` — an error or failed tool. */
error: string;
/** `⚠` — a warning / attention state. */
warning: string;
- /** `◆` — a subagent region header. */
+ /** `※` — a subagent region header. */
subagent: string;
/** `│` — vertical rule drawn in the gutter to nest subagent output. */
rule: string;
@@ -89,10 +99,14 @@ export interface ThemeGlyphs {
option: string;
/** `❯` — the input prompt mark. */
prompt: string;
+ /** `›` — the prompt mark's quiet form while the buffer is empty. */
+ promptIdle: string;
/** `⎿` — hangs a command's result under its invocation. */
elbow: string;
/** `▔` — strong full-width rule opening the bottom question panel. */
hrule: string;
+ /** `─` — light rule segment framing the end-of-turn stats line. */
+ dash: string;
/** `▏` — the synthetic input caret. */
caret: string;
/** `·` — inline separator for header / status segments. */
@@ -121,12 +135,17 @@ export interface ThemeGlyphs {
const UNICODE_GLYPHS: ThemeGlyphs = {
brand: "▲",
- user: "▌",
+ user: "│",
reasoning: "○",
+ square: "▪",
+ corner: "└",
+ cornerOpen: "┌",
+ external: "⌝",
+ dotActive: "⏺",
success: "✓",
error: "⨯",
warning: "⚠",
- subagent: "◆",
+ subagent: "※",
rule: "│",
question: "?",
connection: "●",
@@ -135,8 +154,10 @@ const UNICODE_GLYPHS: ThemeGlyphs = {
selectedPointer: "▶",
option: "◦",
prompt: "❯",
+ promptIdle: "›",
elbow: "⎿",
hrule: "▔",
+ dash: "─",
caret: "▏",
dot: "·",
ellipsis: "…",
@@ -155,6 +176,11 @@ const ASCII_GLYPHS: ThemeGlyphs = {
brand: ">",
user: "|",
reasoning: "o",
+ square: "*",
+ corner: "`",
+ cornerOpen: ",",
+ external: "^",
+ dotActive: "*",
success: "+",
error: "x",
warning: "!",
@@ -167,8 +193,10 @@ const ASCII_GLYPHS: ThemeGlyphs = {
selectedPointer: ">",
option: ".",
prompt: ">",
+ promptIdle: ">",
elbow: "`-",
hrule: "=",
+ dash: "-",
caret: "_",
dot: "-",
ellipsis: "...",
diff --git a/packages/eve/src/cli/dev/tui/todo-panel.test.ts b/packages/eve/src/cli/dev/tui/todo-panel.test.ts
new file mode 100644
index 000000000..bfb65262e
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/todo-panel.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ allTodoItemsSettled,
+ readTodoToolItems,
+ renderFinishedTodoRows,
+ renderTodoPanelRows,
+ type TodoPanelItem,
+} from "./todo-panel.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
+import { createTheme } from "./theme.js";
+
+const theme = createTheme({ color: false, unicode: true });
+
+function render(items: readonly TodoPanelItem[], working = true, pulse = "▪"): string[] {
+ return renderTodoPanelRows({ items, width: 60, theme, working, pulse }).map(stripAnsi);
+}
+
+describe("readTodoToolItems", () => {
+ it("parses a replacement write into panel items", () => {
+ expect(
+ readTodoToolItems("todo", {
+ todos: [
+ { content: "one", status: "completed", priority: "high" },
+ { content: "two", status: "in_progress", priority: "low" },
+ ],
+ }),
+ ).toEqual([
+ { content: "one", status: "completed" },
+ { content: "two", status: "in_progress" },
+ ]);
+ });
+
+ it("recognizes namespaced todo tools", () => {
+ expect(readTodoToolItems("eve.todo", { todos: [{ content: "x", status: "pending" }] })).toEqual(
+ [{ content: "x", status: "pending" }],
+ );
+ });
+
+ it("returns undefined for read-only calls and other tools", () => {
+ expect(readTodoToolItems("todo", {})).toBeUndefined();
+ expect(readTodoToolItems("todo", undefined)).toBeUndefined();
+ expect(readTodoToolItems("bash", { todos: [] })).toBeUndefined();
+ });
+
+ it("rejects malformed items rather than rendering a partial list", () => {
+ expect(readTodoToolItems("todo", { todos: [{ content: 4, status: "pending" }] })).toBe(
+ undefined,
+ );
+ expect(readTodoToolItems("todo", { todos: [{ content: "x", status: "later" }] })).toBe(
+ undefined,
+ );
+ });
+
+ it("keeps only the first line of a multi-line task", () => {
+ expect(readTodoToolItems("todo", { todos: [{ content: "a\nb", status: "pending" }] })).toEqual([
+ { content: "a", status: "pending" },
+ ]);
+ });
+});
+
+describe("allTodoItemsSettled", () => {
+ it("treats completed and cancelled as terminal", () => {
+ expect(
+ allTodoItemsSettled([
+ { content: "a", status: "completed" },
+ { content: "b", status: "cancelled" },
+ ]),
+ ).toBe(true);
+ expect(
+ allTodoItemsSettled([
+ { content: "a", status: "completed" },
+ { content: "b", status: "in_progress" },
+ ]),
+ ).toBe(false);
+ });
+});
+
+describe("renderFinishedTodoRows", () => {
+ it("checks every item on the rail and closes with Done", () => {
+ const rows = renderFinishedTodoRows(
+ [
+ { content: "scope the review", status: "completed" },
+ { content: "run the checks", status: "completed" },
+ { content: "optional pass", status: "cancelled" },
+ ],
+ 60,
+ theme,
+ ).map(stripAnsi);
+
+ expect(rows).toEqual([
+ " ✓ Todo",
+ " │ ✓ scope the review",
+ " │ ✓ run the checks",
+ " │ ⨯ optional pass",
+ " └ Done",
+ ]);
+ });
+});
+
+describe("renderTodoPanelRows", () => {
+ it("rails settled items and closes the rail at the active item", () => {
+ const rows = render([
+ { content: "theme glyphs", status: "completed" },
+ { content: "setup verbiage", status: "completed" },
+ { content: "status line", status: "in_progress" },
+ { content: "keep blue", status: "pending" },
+ { content: "root menu", status: "pending" },
+ ]);
+
+ expect(rows).toEqual([
+ " ▪ Todo",
+ " │ ✓ theme glyphs",
+ " │ ✓ setup verbiage",
+ " └ ⏺ status line",
+ " ○ keep blue",
+ " ○ root menu",
+ ]);
+ });
+
+ it("holds the header steady while only the active item pulses", () => {
+ const rows = render(
+ [
+ { content: "a", status: "completed" },
+ { content: "b", status: "in_progress" },
+ ],
+ true,
+ " ",
+ );
+
+ // Off-beat frame: the header mark stays, the active item's dot blinks.
+ expect(rows[0]).toBe(" ▪ Todo");
+ expect(rows[2]).toBe(" └ b");
+ });
+
+ it("shows settled progress instead of the pulse while the prompt is idle", () => {
+ const rows = render(
+ [
+ { content: "a", status: "completed" },
+ { content: "b", status: "cancelled" },
+ { content: "c", status: "pending" },
+ ],
+ false,
+ );
+
+ expect(rows[0]).toBe(" ▪ 2/3 tasks");
+ expect(rows[1]).toBe(" │ ✓ a");
+ expect(rows[2]).toBe(" │ ⨯ b");
+ expect(rows[3]).toBe(" └ ○ c");
+ });
+
+ it("clips rows to the panel width", () => {
+ const rows = renderTodoPanelRows({
+ items: [{ content: "x".repeat(120), status: "pending" }],
+ width: 24,
+ theme,
+ working: true,
+ pulse: "▪",
+ });
+ for (const row of rows) {
+ expect(stripAnsi(row).length).toBeLessThanOrEqual(24);
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/todo-panel.ts b/packages/eve/src/cli/dev/tui/todo-panel.ts
new file mode 100644
index 000000000..e1f205550
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/todo-panel.ts
@@ -0,0 +1,164 @@
+/**
+ * The pinned todo panel: pure parsing and rendering for the task list the
+ * model maintains through the framework `todo` tool. The tool writes the
+ * whole list on every call, so the panel is driven entirely from tool-call
+ * inputs — no protocol addition and no durable client state. The renderer
+ * owns lifecycle (when a call updates the panel, when the finished list
+ * commits to the transcript); this module only reads inputs and paints rows.
+ */
+
+import type { Theme } from "./theme.js";
+import { toolBaseName } from "./tool-presentation.js";
+import { TOOL_COLUMN_LEAD } from "./rail.js";
+import { clipVisible, stripTerminalControls } from "#cli/ui/terminal-text.js";
+
+/** One panel row parsed from the `todo` tool's replacement-write input. */
+export interface TodoPanelItem {
+ readonly content: string;
+ readonly status: "pending" | "in_progress" | "completed" | "cancelled";
+}
+
+const TODO_STATUSES: ReadonlySet<TodoPanelItem["status"]> = new Set([
+ "pending",
+ "in_progress",
+ "completed",
+ "cancelled",
+]);
+
+/**
+ * Extracts the panel items from a tool call when — and only when — it is a
+ * `todo` replacement write. Read-only calls (no `todos`) and malformed items
+ * return `undefined` so they fall through to the ordinary tool block.
+ */
+export function readTodoToolItems(toolName: string, input: unknown): TodoPanelItem[] | undefined {
+ if (toolBaseName(toolName) !== "todo") return undefined;
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const todos = (input as Record<string, unknown>)["todos"];
+ if (!Array.isArray(todos)) return undefined;
+
+ const items: TodoPanelItem[] = [];
+ for (const todo of todos) {
+ if (todo === null || typeof todo !== "object" || Array.isArray(todo)) return undefined;
+ const record = todo as Record<string, unknown>;
+ const content = record["content"];
+ const status = record["status"];
+ if (typeof content !== "string") return undefined;
+ if (typeof status !== "string" || !TODO_STATUSES.has(status as TodoPanelItem["status"])) {
+ return undefined;
+ }
+ items.push({
+ content: firstLine(stripTerminalControls(content)),
+ status: status as TodoPanelItem["status"],
+ });
+ }
+ return items;
+}
+
+/** True when every item reached a terminal status (completed or cancelled). */
+export function allTodoItemsSettled(items: readonly TodoPanelItem[]): boolean {
+ return items.every((item) => item.status === "completed" || item.status === "cancelled");
+}
+
+export interface TodoPanelRowsInput {
+ readonly items: readonly TodoPanelItem[];
+ readonly width: number;
+ readonly theme: Theme;
+ /** True while the turn is running: pulses the header and the active item. */
+ readonly working: boolean;
+ /** Current shared pulse frame (the glyph, or a space on the off beat). */
+ readonly pulse: string;
+}
+
+/**
+ * Paints the pinned panel, indented so its marks share the tool column.
+ * Settled items ride a `│` rail under the header; the
+ * first unsettled item closes the rail with `└` and everything after hangs
+ * indented — the list reads as progress flowing through the corner.
+ */
+export function renderTodoPanelRows(input: TodoPanelRowsInput): string[] {
+ const { items, width, theme } = input;
+ const c = theme.colors;
+ const g = theme.glyph;
+
+ const settled = items.filter(
+ (item) => item.status === "completed" || item.status === "cancelled",
+ ).length;
+ // The header mark holds steady in both states — the active item's `⏺` is
+ // the panel's only pulse.
+ const lead = TOOL_COLUMN_LEAD;
+ const header = input.working
+ ? `${lead}${c.gray(g.square)} ${c.dim("Todo")}`
+ : `${lead}${c.gray(g.square)} ${c.dim(`${settled}/${items.length} tasks`)}`;
+
+ const rows = [header];
+ let railClosed = false;
+ for (const item of items) {
+ const isSettled = item.status === "completed" || item.status === "cancelled";
+ let rail: string;
+ if (railClosed) {
+ rail = " ";
+ } else if (isSettled) {
+ rail = c.dim(g.rule);
+ } else {
+ rail = c.dim(g.corner);
+ railClosed = true;
+ }
+ rows.push(`${TOOL_COLUMN_LEAD}${rail} ${todoItemBody(item, input, theme)}`);
+ }
+ return rows.map((row) => clipVisible(row, width));
+}
+
+/**
+ * The transcript form of a finished list: every item checked on the rail,
+ * closed by `└ Done`. Committed verbatim (pre-styled rows) once every item
+ * settles.
+ */
+export function renderFinishedTodoRows(
+ items: readonly TodoPanelItem[],
+ width: number,
+ theme: Theme,
+): string[] {
+ const c = theme.colors;
+ const g = theme.glyph;
+ const rows = [`${TOOL_COLUMN_LEAD}${c.green(g.success)} ${c.dim("Todo")}`];
+ for (const item of items) {
+ rows.push(
+ `${TOOL_COLUMN_LEAD}${c.dim(g.rule)} ${settledMark(item, theme)} ${c.dim(item.content)}`,
+ );
+ }
+ rows.push(`${TOOL_COLUMN_LEAD}${c.dim(g.corner)} ${c.green("Done")}`);
+ return rows.map((row) => clipVisible(row, width));
+}
+
+function settledMark(item: TodoPanelItem, theme: Theme): string {
+ return item.status === "cancelled"
+ ? theme.colors.red(theme.glyph.error)
+ : theme.colors.green(theme.glyph.success);
+}
+
+function todoItemBody(item: TodoPanelItem, input: TodoPanelRowsInput, theme: Theme): string {
+ const c = theme.colors;
+ const g = theme.glyph;
+ switch (item.status) {
+ case "completed":
+ return `${c.green(g.success)} ${c.dim(item.content)}`;
+ case "cancelled":
+ return `${c.red(g.error)} ${c.dim(item.content)}`;
+ case "in_progress": {
+ // The active item pulses on the shared beat while the turn runs, and
+ // holds a steady mark between turns so the panel never looks dead.
+ const mark = input.working
+ ? input.pulse.trim().length > 0
+ ? g.dotActive
+ : " "
+ : g.dotActive;
+ return `${c.yellow(mark)} ${item.content}`;
+ }
+ case "pending":
+ return `${c.dim(g.reasoning)} ${c.dim(item.content)}`;
+ }
+}
+
+function firstLine(text: string): string {
+ return text.split(/\r?\n/u, 1)[0] ?? "";
+}
diff --git a/packages/eve/src/cli/dev/tui/tool-block-groups.test.ts b/packages/eve/src/cli/dev/tui/tool-block-groups.test.ts
new file mode 100644
index 000000000..ce12404d0
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/tool-block-groups.test.ts
@@ -0,0 +1,584 @@
+import { describe, expect, it } from "vitest";
+
+import type { Block } from "./blocks.js";
+import { groupToolBlocksForDisplay, maxVisibleSubagentRunChildren } from "./tool-block-groups.js";
+
+function fetchBlock(
+ id: string,
+ item: string,
+ status: "running" | "done" | "error",
+ result?: string,
+ options?: { live?: boolean },
+): Block {
+ const block: Block = {
+ kind: "tool",
+ id,
+ live: options?.live ?? status === "running",
+ status,
+ title: `Fetch ${item}`,
+ toolGroup: {
+ verb: "Fetch",
+ pastVerb: "Fetched",
+ singularNoun: "URL",
+ pluralNoun: "URLs",
+ item,
+ },
+ };
+ if (result !== undefined) block.result = result;
+ return block;
+}
+
+function subagentHeader(callId: string, name: string): Block {
+ return {
+ kind: "subagent",
+ id: `subagent:${callId}:header`,
+ subagentCallId: callId,
+ title: name,
+ live: false,
+ };
+}
+
+function subagentStep(callId: string, body: string, live = false): Block {
+ return {
+ kind: "subagent-step",
+ id: `subagent:${callId}:step:0`,
+ subagentCallId: callId,
+ depth: 1,
+ body,
+ live,
+ };
+}
+
+describe("groupToolBlocksForDisplay", () => {
+ it("collapses a settled run to one counted, past-tense header without items", () => {
+ const first = fetchBlock("one", "https://one.example", "done");
+ const second = fetchBlock("two", "https://two.example", "done");
+ const [group] = groupToolBlocksForDisplay([first, second]);
+
+ expect(group?.members).toEqual([first, second]);
+ expect(group?.display).toMatchObject({
+ id: undefined,
+ title: "Fetch 2 URLs",
+ doneTitle: "Fetched 2 URLs",
+ });
+ expect(group?.display.toolGroupItems).toBeUndefined();
+ });
+
+ it("accumulates a live run into one group with items listed newest first", () => {
+ // The renderer's cohort liveness keeps every member of an in-flight batch
+ // live, settled or not — mirrored here so mixed statuses share one run.
+ const settled = fetchBlock("one", "https://one.example", "done", undefined, { live: true });
+ const running = fetchBlock("two", "https://two.example", "running");
+ const newest = fetchBlock("three", "https://three.example", "running");
+ const [group] = groupToolBlocksForDisplay([settled, running, newest]);
+
+ expect(group?.members).toEqual([settled, running, newest]);
+ expect(group?.display).toMatchObject({
+ id: undefined,
+ live: true,
+ status: "running",
+ title: "Fetch 3 URLs",
+ toolGroupItems: [
+ { text: "https://three.example" },
+ { text: "https://two.example" },
+ { text: "https://one.example" },
+ ],
+ });
+ });
+
+ it("keeps calls separate when status or intervening content differs", () => {
+ const blocks: Block[] = [
+ fetchBlock("one", "https://one.example", "done"),
+ { kind: "assistant", body: "between", live: false },
+ fetchBlock("two", "https://two.example", "running"),
+ ];
+
+ expect(groupToolBlocksForDisplay(blocks).map((group) => group.members.length)).toEqual([
+ 1, 1, 1,
+ ]);
+ });
+
+ it("partitions interleaved successes and failures into one group each", () => {
+ const failedFirst = fetchBlock("f1", "https://a.example", "error", "status 403");
+ const doneOne = fetchBlock("d1", "https://b.example", "done");
+ const doneTwo = fetchBlock("d2", "https://c.example", "done");
+ const failedSecond = fetchBlock("f2", "https://d.example", "error", "status 429");
+ const doneThree = fetchBlock("d3", "https://e.example", "done");
+
+ const groups = groupToolBlocksForDisplay([
+ failedFirst,
+ doneOne,
+ doneTwo,
+ failedSecond,
+ doneThree,
+ ]);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0]?.members).toEqual([failedFirst, failedSecond]);
+ // Failures keep their itemized rail, newest call first.
+ expect(groups[0]?.display).toMatchObject({
+ title: "Fetch 2 URLs",
+ status: "error",
+ toolGroupItems: [
+ { text: "https://d.example", result: "status 429" },
+ { text: "https://a.example", result: "status 403" },
+ ],
+ });
+ expect(groups[1]?.members).toEqual([doneOne, doneTwo, doneThree]);
+ expect(groups[1]?.display).toMatchObject({
+ title: "Fetch 3 URLs",
+ doneTitle: "Fetched 3 URLs",
+ status: "done",
+ });
+ expect(groups[1]?.display.toolGroupItems).toBeUndefined();
+ });
+
+ it("keeps a lone failure as its own block with the original result line", () => {
+ const done = fetchBlock("d1", "https://a.example", "done");
+ const failed = fetchBlock("f1", "https://b.example", "error", "status 404");
+
+ const groups = groupToolBlocksForDisplay([done, failed]);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0]?.display).toBe(done);
+ expect(groups[1]?.display).toBe(failed);
+ expect(groups[1]?.display.result).toBe("status 404");
+ });
+
+ it("condenses a settled child-tool run into one counted row once a message follows", () => {
+ const child = (id: string, toolName: string, verb: [string, string], noun: [string, string]) =>
+ ({
+ kind: "subagent-tool",
+ id,
+ subagentCallId: "c1",
+ depth: 1,
+ live: false,
+ status: "done",
+ toolName,
+ title: `${verb[0]} x`,
+ toolGroup: {
+ verb: verb[0],
+ pastVerb: verb[1],
+ singularNoun: noun[0],
+ pluralNoun: noun[1],
+ item: "x",
+ },
+ }) satisfies Block;
+
+ const run = [
+ child("b1", "bash", ["Run", "Ran"], ["command", "commands"]),
+ child("r1", "read_file", ["Read", "Read"], ["file", "files"]),
+ {
+ kind: "subagent-tool",
+ id: "w1",
+ subagentCallId: "c1",
+ depth: 1,
+ live: false,
+ status: "done",
+ toolName: "write_file",
+ title: "Write /a",
+ } satisfies Block,
+ {
+ kind: "subagent-tool",
+ id: "s1",
+ subagentCallId: "c1",
+ depth: 1,
+ live: false,
+ status: "done",
+ toolName: "web_search",
+ title: "Search x",
+ toolGroup: {
+ verb: "Search",
+ pastVerb: "Searched",
+ singularNoun: "query",
+ pluralNoun: "queries",
+ item: "x",
+ },
+ } satisfies Block,
+ ];
+ const step: Block = {
+ kind: "subagent-step",
+ id: "m1",
+ subagentCallId: "c1",
+ depth: 1,
+ live: false,
+ body: "Here is what I found.",
+ };
+
+ const groups = groupToolBlocksForDisplay([subagentHeader("c1", "researcher"), ...run, step]);
+
+ // header, the condensed run elided behind the stand-in, then the
+ // message (the newest row) closing the rail.
+ expect(groups).toHaveLength(3);
+ expect(groups[1]?.members).toEqual(run);
+ expect(groups[1]?.display).toMatchObject({ kind: "subagent-step", elided: 4 });
+ expect(groups[2]?.members).toEqual([step]);
+ expect(groups[2]?.display).toEqual({ ...step, closesRail: true });
+ });
+
+ it("leaves a settled child-tool run itemized when no message follows", () => {
+ const tool = (id: string): Block => ({
+ kind: "subagent-tool",
+ id,
+ subagentCallId: "c1",
+ depth: 1,
+ live: false,
+ status: "done",
+ toolName: "bash",
+ title: "Run x",
+ toolGroup: {
+ verb: "Run",
+ pastVerb: "Ran",
+ singularNoun: "command",
+ pluralNoun: "commands",
+ item: "x",
+ },
+ });
+
+ const groups = groupToolBlocksForDisplay([
+ subagentHeader("c1", "researcher"),
+ tool("b1"),
+ tool("b2"),
+ ]);
+
+ // Falls back to the ordinary per-kind aggregation, items intact.
+ expect(groups[1]?.display).toMatchObject({ title: "Run 2 commands" });
+ });
+
+ it("keeps interleaved different-named subagent calls as whole sections", () => {
+ const ha = subagentHeader("ca", "researcher");
+ const hb = subagentHeader("cb", "reviewer");
+ const a1 = { ...subagentStep("ca", "finding one"), id: "ca:1", subagentCallId: "ca" };
+ const b1 = { ...subagentStep("cb", "critique one"), id: "cb:1", subagentCallId: "cb" };
+ const a2 = { ...subagentStep("ca", "finding two"), id: "ca:2", subagentCallId: "ca" };
+
+ // Parallel different subagents interleave; neither may fragment the
+ // other into headerless children.
+ const groups = groupToolBlocksForDisplay([ha, hb, a1, b1, a2]);
+
+ expect(groups.map((group) => group.display)).toEqual([
+ ha,
+ { kind: "subagent-step", depth: 1, live: false, elided: 1 },
+ { ...a2, closesRail: true },
+ hb,
+ { ...b1, closesRail: true },
+ ]);
+ });
+
+ it("does not condense a run against a sibling section's message", () => {
+ const tool = (id: string): Block => ({
+ kind: "subagent-tool",
+ id,
+ subagentCallId: "ca",
+ depth: 1,
+ live: false,
+ status: "done",
+ toolName: "bash",
+ title: "Run x",
+ toolGroup: {
+ verb: "Run",
+ pastVerb: "Ran",
+ singularNoun: "command",
+ pluralNoun: "commands",
+ item: "x",
+ },
+ });
+ const foreignStep: Block = {
+ kind: "subagent-step",
+ id: "cb:1",
+ subagentCallId: "cb",
+ depth: 1,
+ live: false,
+ body: "sibling's message",
+ };
+
+ // Headerless layout (worst case): the foreign message directly follows
+ // the run but belongs to another call — no condensation.
+ const groups = groupToolBlocksForDisplay([tool("a"), tool("b"), foreignStep]);
+
+ expect(groups[0]?.display).toMatchObject({ title: "Run 2 commands" });
+ expect(groups[0]?.display.title).not.toContain("Ran");
+ });
+
+ it("passes captured log blocks through a subagent run without splitting it", () => {
+ const header = subagentHeader("c1", "researcher");
+ const s1 = subagentStep("c1", "finding one");
+ const stderr: Block = {
+ kind: "log",
+ title: "stderr",
+ body: "tool execution failed",
+ live: false,
+ };
+ const s2 = subagentStep("c2", "other call");
+
+ // The stderr write spliced itself between the run's children; the
+ // section must stay whole, with the log re-emitted after it.
+ const groups = groupToolBlocksForDisplay([
+ header,
+ stderr,
+ { ...s1, id: "c1:s1" },
+ subagentHeader("c2", "researcher"),
+ { ...s2, id: "c2:s2", subagentCallId: "c2" },
+ ]);
+
+ expect(groups.map((group) => group.display.kind)).toEqual([
+ "subagent",
+ "subagent-step",
+ "subagent",
+ "subagent-step",
+ "log",
+ ]);
+ });
+
+ it("hands trailing logs back to the main loop after a run", () => {
+ const header = subagentHeader("c1", "researcher");
+ const step = subagentStep("c1", "finding");
+ const stderr: Block = { kind: "log", title: "stderr", body: "late failure", live: false };
+
+ const groups = groupToolBlocksForDisplay([header, step, stderr]);
+
+ expect(groups.map((group) => group.display.kind)).toEqual(["subagent", "subagent-step", "log"]);
+ });
+
+ it("keeps interleaved same-subagent calls as separate sections with rebucketed children", () => {
+ const h1 = subagentHeader("c1", "echo-marker");
+ const s1 = subagentStep("c1", "token one");
+ const h2 = subagentHeader("c2", "echo-marker");
+ const s2 = subagentStep("c2", "token two");
+ const h3 = subagentHeader("c3", "echo-marker");
+ const s3 = subagentStep("c3", "token three");
+
+ // Children arrive interleaved; each call's section reassembles its own.
+ const groups = groupToolBlocksForDisplay([h1, h2, h3, s1, s2, s3]);
+
+ expect(groups.map((group) => group.display)).toEqual([
+ h1,
+ { ...s1, closesRail: true },
+ h2,
+ { ...s2, closesRail: true },
+ h3,
+ { ...s3, closesRail: true },
+ ]);
+ });
+
+ it("keeps a section live while its own children stream, independent of siblings", () => {
+ const settledHeader = { ...subagentHeader("c1", "echo-marker"), live: false };
+ const liveChildHeader = { ...subagentHeader("c2", "echo-marker"), live: false };
+ const groups = groupToolBlocksForDisplay([
+ settledHeader,
+ subagentStep("c1", "token one"),
+ liveChildHeader,
+ subagentStep("c2", "token two", true),
+ ]);
+
+ expect(groups[0]?.display.live).toBe(false);
+ expect(groups[2]?.display.live).toBe(true);
+ });
+
+ it("keeps the run live while a header still is, even after every child settles", () => {
+ const groups = groupToolBlocksForDisplay([
+ { ...subagentHeader("c1", "echo-marker"), live: true },
+ subagentStep("c1", "token one"),
+ { ...subagentHeader("c2", "echo-marker"), live: true },
+ subagentStep("c2", "token two"),
+ ]);
+
+ expect(groups[0]?.display.live).toBe(true);
+ });
+
+ it("windows each section to its newest children independently", () => {
+ const blocks: Block[] = [subagentHeader("c1", "echo-marker")];
+ const first: Block[] = [];
+ for (let index = 1; index <= maxVisibleSubagentRunChildren + 3; index += 1) {
+ const step = { ...subagentStep("c1", `one ${index}`), id: `c1:step:${index}` };
+ blocks.push(step);
+ first.push(step);
+ }
+ blocks.push(subagentHeader("c2", "echo-marker"), subagentStep("c2", "two 1"));
+
+ const groups = groupToolBlocksForDisplay(blocks);
+
+ // First section: header, one elision stand-in, then its newest window.
+ expect(groups[1]?.members).toEqual(first.slice(0, 3));
+ expect(groups[1]?.display).toMatchObject({ kind: "subagent-step", elided: 3 });
+ expect(groups.slice(2, 2 + maxVisibleSubagentRunChildren).map((g) => g.display)).toEqual([
+ ...first.slice(3, -1),
+ { ...first.at(-1)!, closesRail: true },
+ ]);
+ // The second section is untouched by the first one's overflow.
+ const secondHeader = groups.findIndex(
+ (group) => group.display.kind === "subagent" && group.display.subagentCallId === "c2",
+ );
+ expect(secondHeader).toBeGreaterThan(-1);
+ expect(groups[secondHeader + 1]?.display.body).toBe("two 1");
+ });
+
+ it("caps a single call's long child list too", () => {
+ const header = subagentHeader("c1", "researcher");
+ const steps = Array.from({ length: maxVisibleSubagentRunChildren + 2 }, (_, index) => ({
+ ...subagentStep("c1", `finding ${index + 1}`),
+ id: `subagent:c1:step:${index}`,
+ }));
+
+ const groups = groupToolBlocksForDisplay([header, ...steps]);
+
+ expect(groups[1]?.display.elided).toBe(2);
+ expect(groups[1]?.members).toEqual(steps.slice(0, 2));
+ expect(groups.slice(2).map((group) => group.display)).toEqual([
+ ...steps.slice(2, -1),
+ { ...steps.at(-1)!, closesRail: true },
+ ]);
+ });
+
+ it("does not elide a run at or under the visible cap", () => {
+ const header = subagentHeader("c1", "researcher");
+ const steps = Array.from({ length: maxVisibleSubagentRunChildren }, (_, index) => ({
+ ...subagentStep("c1", `finding ${index + 1}`),
+ id: `subagent:c1:step:${index}`,
+ }));
+
+ const groups = groupToolBlocksForDisplay([header, ...steps]);
+
+ expect(groups).toHaveLength(1 + maxVisibleSubagentRunChildren);
+ expect(groups.every((group) => group.display.elided === undefined)).toBe(true);
+ });
+
+ it("does not merge sections of differently named subagents", () => {
+ const groups = groupToolBlocksForDisplay([
+ subagentHeader("c1", "echo-marker"),
+ subagentStep("c1", "token one"),
+ subagentHeader("c2", "researcher"),
+ subagentStep("c2", "finding"),
+ ]);
+
+ const sections = groups.filter((group) => group.display.kind !== "subagent-close");
+ expect(sections.map((group) => group.display.title ?? group.display.body)).toEqual([
+ "echo-marker",
+ "token one",
+ "researcher",
+ "finding",
+ ]);
+ expect(groups[0]?.display.subtitle).toBeUndefined();
+ });
+
+ it("keeps a single subagent section untouched", () => {
+ const header = subagentHeader("c1", "researcher");
+ const step = subagentStep("c1", "finding");
+
+ const groups = groupToolBlocksForDisplay([header, step]);
+
+ expect(groups.map((group) => group.display)).toEqual([header, { ...step, closesRail: true }]);
+ });
+
+ it("coalesces a contiguous run of same-source log writes into one section", () => {
+ const write = (title: string, body: string, live = false): Block => ({
+ kind: "log",
+ title,
+ body,
+ live,
+ });
+
+ const groups = groupToolBlocksForDisplay([
+ write("stderr", "warning one\ndetail one"),
+ write("stderr", "warning two", true),
+ ]);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.members).toHaveLength(2);
+ // The merged section shows only the newest write — every stored
+ // diagnostic points at the log file, so on-screen history is redundant
+ // — and stays live while any write still is.
+ expect(groups[0]?.display).toMatchObject({
+ kind: "log",
+ title: "stderr",
+ body: "warning two",
+ live: true,
+ elided: 1,
+ });
+ });
+
+ it("buckets a log run by source and visibility without merging across them", () => {
+ const concise: Block = {
+ kind: "log",
+ title: "stderr",
+ body: "concise one",
+ logVisibility: "stderr-only",
+ live: false,
+ };
+ const raw: Block = {
+ kind: "log",
+ title: "stderr",
+ body: "raw one",
+ logVisibility: "all-only",
+ live: false,
+ };
+ const conciseTwo: Block = { ...concise, body: "concise two" };
+ const rawTwo: Block = { ...raw, body: "raw two" };
+
+ const groups = groupToolBlocksForDisplay([concise, raw, conciseTwo, rawTwo]);
+
+ // The concise/raw diagnostic twins each merge with their own kind — a
+ // mixed section would double the content under one log filter.
+ expect(groups).toHaveLength(2);
+ expect(groups[0]?.display).toMatchObject({
+ body: "concise two",
+ elided: 1,
+ logVisibility: "stderr-only",
+ });
+ expect(groups[1]?.display).toMatchObject({
+ body: "raw two",
+ elided: 1,
+ logVisibility: "all-only",
+ });
+ });
+
+ it("keeps a lone write and in-place log status blocks out of coalescing", () => {
+ const lone: Block = {
+ kind: "log",
+ title: "stderr",
+ body: Array.from({ length: 15 }, (_, i) => `line ${i}`).join("\n"),
+ live: false,
+ };
+ const status: Block = {
+ kind: "log",
+ id: "dev-rebuild:1",
+ title: "stdout",
+ body: "3 files changed · rebuilding…",
+ live: true,
+ };
+ const write: Block = { kind: "log", title: "stdout", body: "ordinary", live: false };
+
+ const groups = groupToolBlocksForDisplay([lone, status, write]);
+
+ // A lone write is never windowed, and the rebuild status row must not
+ // absorb (or be absorbed by) neighboring writes. Single-member buckets
+ // sit at their own positions.
+ expect(groups.map((group) => group.display)).toEqual([lone, status, write]);
+ });
+
+ it("merges a source's writes across interleaved blocks in window mode only", () => {
+ const write = (body: string): Block => ({ kind: "log", title: "stderr", body, live: false });
+ const notice: Block = { kind: "notice", body: "boundary", live: false };
+ const blocks = [write("early failure"), notice, write("late failure")];
+
+ // Window mode: one stream section anchored at the newest write, so
+ // everything that happened after the last error displays after it.
+ const windowed = groupToolBlocksForDisplay(blocks);
+ expect(windowed.map((group) => group.display.kind)).toEqual(["notice", "log"]);
+ expect(windowed[1]?.display).toMatchObject({ body: "late failure", elided: 1 });
+
+ // Runs mode (transcript rebuilds): committed positions stay put.
+ const runs = groupToolBlocksForDisplay(blocks, { logCoalescing: "runs" });
+ expect(runs.map((group) => group.display.kind)).toEqual(["log", "notice", "log"]);
+ });
+
+ it("does not group a settled call with a still-running one", () => {
+ const done = fetchBlock("d1", "https://a.example", "done");
+ const running = fetchBlock("r1", "https://b.example", "running");
+
+ expect(groupToolBlocksForDisplay([done, running]).map((group) => group.members)).toEqual([
+ [done],
+ [running],
+ ]);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/tool-block-groups.ts b/packages/eve/src/cli/dev/tui/tool-block-groups.ts
new file mode 100644
index 000000000..faab1a2b1
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/tool-block-groups.ts
@@ -0,0 +1,570 @@
+import type { Block, DisplayBlock, ToolGroupItem } from "./blocks.js";
+import { toolBaseName } from "./tool-presentation.js";
+
+export interface ToolBlockDisplayGroup {
+ readonly members: readonly Block[];
+ readonly display: DisplayBlock;
+}
+
+/**
+ * Coalesces presentation only; each member keeps its call id and lifecycle.
+ *
+ * A contiguous run of equivalent tool calls is partitioned by status, so a
+ * batch with interleaved outcomes renders as one succeeded aggregate and one
+ * failed aggregate instead of fragmenting on every status flip. A contiguous
+ * run of same-named subagent calls coalesces the repeated headers into one
+ * counted header, reorders the interleaved children call by call, and elides
+ * all but the newest {@link maxVisibleSubagentRunChildren} children behind a
+ * `… +N more` row. Captured log writes coalesce per
+ * {@link GroupToolBlocksOptions.logCoalescing}. Because of all this, a
+ * group's members are not always contiguous in the input: callers that
+ * consume a group must remove its members by identity, never by prefix
+ * length.
+ */
+export interface GroupToolBlocksOptions {
+ /**
+ * How captured log writes coalesce. `"window"` (the default, for the live
+ * block window) merges every write of one source across the whole input
+ * into a single section appended after the rest — a process stream is
+ * continuous, so interleaved activity must not fragment it — and the
+ * section commits as one cluster at the turn boundary. `"runs"` (for
+ * committed-transcript rebuilds) merges only contiguous writes, so a
+ * `/loglevel` toggle re-renders history at its committed positions instead
+ * of relocating every past write to the end.
+ */
+ readonly logCoalescing?: "window" | "runs";
+}
+
+export function groupToolBlocksForDisplay(
+ blocks: readonly Block[],
+ options: GroupToolBlocksOptions = {},
+): ToolBlockDisplayGroup[] {
+ if ((options.logCoalescing ?? "window") === "window") {
+ // Bucket every write by (source, visibility) and anchor each bucket's
+ // ready-made merged group at its NEWEST member: the section renders
+ // where the last write landed, so everything that happened after it
+ // displays after it. Non-anchor members simply drop from the walk —
+ // they ride the anchored group's member list.
+ const buckets = new Map<string, Block[]>();
+ for (const block of blocks) {
+ if (!isGroupableLogWrite(block)) continue;
+ const key = logBucketKey(block);
+ const bucket = buckets.get(key);
+ if (bucket === undefined) buckets.set(key, [block]);
+ else bucket.push(block);
+ }
+ const anchors = new Map<Block, ToolBlockDisplayGroup>();
+ for (const members of buckets.values()) {
+ anchors.set(members.at(-1)!, coalesceLogBucket(members));
+ }
+ return groupBlocks(blocks, anchors);
+ }
+ return groupBlocks(blocks);
+}
+
+function groupBlocks(
+ blocks: readonly Block[],
+ logAnchors?: ReadonlyMap<Block, ToolBlockDisplayGroup>,
+): ToolBlockDisplayGroup[] {
+ const groups: ToolBlockDisplayGroup[] = [];
+ for (let index = 0; index < blocks.length;) {
+ const first = blocks[index]!;
+ if (isGroupableLogWrite(first)) {
+ if (logAnchors !== undefined) {
+ // Window mode: only a bucket's newest member emits its prebuilt
+ // merged group, at the last write's position.
+ const group = logAnchors.get(first);
+ if (group !== undefined) groups.push(group);
+ index += 1;
+ continue;
+ }
+ const run = [first];
+ while (
+ index + run.length < blocks.length &&
+ isGroupableLogWrite(blocks[index + run.length]!)
+ ) {
+ run.push(blocks[index + run.length]!);
+ }
+ groups.push(...coalesceLogWrites(run));
+ index += run.length;
+ continue;
+ }
+ if (first.kind === "subagent" && first.subagentCallId !== undefined) {
+ const run = collectSubagentRun(blocks, index, logAnchors);
+ groups.push(...run.groups);
+ index += run.consumed;
+ continue;
+ }
+ // Inside a subagent's flow, a settled tool run directly followed by a
+ // message condenses to one multi-kind row — the message is the story,
+ // the tools its footnote. Failed calls ride the run without breaking
+ // it: they group with the other tools but stay itemized as their own
+ // rows, because an error must not vanish into a count.
+ if (isCondensableChildTool(first)) {
+ const run = [first];
+ while (index + run.length < blocks.length) {
+ const candidate = blocks[index + run.length]!;
+ if (candidate.subagentCallId !== first.subagentCallId) break;
+ if (!isCondensableChildTool(candidate) && !isItemizedChildFailure(candidate)) break;
+ run.push(candidate);
+ }
+ const next = blocks[index + run.length];
+ const condensable = run.filter(isCondensableChildTool);
+ if (
+ condensable.length >= 2 &&
+ next?.kind === "subagent-step" &&
+ // The message must belong to the same call — a sibling section's
+ // prose must not trigger a foreign run's condensation.
+ next.subagentCallId === first.subagentCallId
+ ) {
+ groups.push({ members: condensable, display: condenseChildToolRun(condensable) });
+ for (const failure of run) {
+ if (!isCondensableChildTool(failure)) {
+ groups.push({ members: [failure], display: failure });
+ }
+ }
+ index += run.length;
+ continue;
+ }
+ }
+
+ if (!isGroupable(first)) {
+ groups.push({ members: [first], display: first });
+ index += 1;
+ continue;
+ }
+
+ const run = [first];
+ while (index + run.length < blocks.length) {
+ const candidate = blocks[index + run.length]!;
+ if (!isGroupable(candidate) || !sameRun(first, candidate)) break;
+ run.push(candidate);
+ }
+
+ // A run with any call still executing accumulates as one group — mixed
+ // settled/running statuses must not fragment the batch mid-flight. Only a
+ // fully settled run partitions by outcome (collapsed successes, itemized
+ // failures).
+ const running = run.some((block) => block.status === "running");
+ if (running && run.length > 1) {
+ groups.push({ members: run, display: aggregateLiveToolBlocks(run) });
+ } else {
+ groups.push(...partitionRunByStatus(run));
+ }
+ index += run.length;
+ }
+ return groups;
+}
+
+function isGroupable(block: Block): boolean {
+ return (
+ (block.kind === "tool" || block.kind === "subagent-tool") &&
+ block.toolGroup !== undefined &&
+ block.expanded !== true &&
+ (block.status === "running" ||
+ block.status === "error" ||
+ (block.status === "done" && block.result === undefined))
+ );
+}
+
+function sameRun(first: Block, candidate: Block): boolean {
+ return (
+ candidate.kind === first.kind &&
+ candidate.depth === first.depth &&
+ candidate.live === first.live &&
+ // Copy derives from the tool name, so name equality implies equal copy.
+ candidate.toolName === first.toolName
+ );
+}
+
+/** Splits one run into per-status groups, ordered by each status's first call. */
+function partitionRunByStatus(run: readonly Block[]): ToolBlockDisplayGroup[] {
+ const partitions = new Map<Block["status"], Block[]>();
+ for (const block of run) {
+ const partition = partitions.get(block.status);
+ if (partition === undefined) {
+ partitions.set(block.status, [block]);
+ } else {
+ partition.push(block);
+ }
+ }
+
+ return [...partitions.values()].map((members) => ({
+ members,
+ display:
+ members.length === 1
+ ? members[0]!
+ : members[0]!.status === "done"
+ ? collapseSettledToolBlocks(members)
+ : aggregateToolBlocks(members),
+ }));
+}
+
+/**
+ * A live subagent section shows only its most recently active child row;
+ * everything earlier collapses into a single `… (N more)` line under the
+ * header. The completed section's counted footnote carries the full story.
+ */
+export const maxVisibleSubagentRunChildren = 1;
+
+/**
+ * An ordinary captured write. In-place log status blocks (the dev rebuild
+ * cycle) carry an id and must never merge into a run.
+ */
+function isGroupableLogWrite(block: Block): boolean {
+ return block.kind === "log" && block.id === undefined;
+}
+
+/** The (source, visibility) identity a write merges under. */
+function logBucketKey(block: Block): string {
+ return `${block.title ?? ""}\u0000${block.logVisibility ?? ""}`;
+}
+
+/**
+ * Coalesces captured writes into one section per (source, visibility)
+ * bucket, so a stream renders as a single `○ stderr` section instead of one
+ * per write. Bucketing keeps the concise/raw diagnostic twins apart — only
+ * one of the pair is visible under any log filter, and a merged display can
+ * carry only one visibility. The section shows only the NEWEST write —
+ * every stored diagnostic points at the log file, so history on screen is
+ * redundant — with earlier writes collapsed into the elided count.
+ */
+function coalesceLogWrites(run: readonly Block[]): ToolBlockDisplayGroup[] {
+ const buckets = new Map<string, Block[]>();
+ for (const block of run) {
+ const key = logBucketKey(block);
+ const bucket = buckets.get(key);
+ if (bucket === undefined) {
+ buckets.set(key, [block]);
+ } else {
+ bucket.push(block);
+ }
+ }
+ return [...buckets.values()].map(coalesceLogBucket);
+}
+
+/** One already-bucketed stream's merged group: the newest write, counted. */
+function coalesceLogBucket(members: readonly Block[]): ToolBlockDisplayGroup {
+ if (members.length === 1) return { members, display: members[0]! };
+ const newest = members.at(-1)!;
+ const display: DisplayBlock = {
+ kind: "log",
+ live: members.some((member) => member.live !== false),
+ body: newest.body ?? "",
+ elided: members.length - 1,
+ };
+ if (newest.title !== undefined) display.title = newest.title;
+ if (newest.logVisibility !== undefined) display.logVisibility = newest.logVisibility;
+ return { members, display };
+}
+
+/**
+ * Block kinds that may splice into a subagent run (captured output, stream
+ * errors, notices) without belonging to it. They pass through and re-emit
+ * after the sections they interrupted instead of splitting a run into
+ * headerless fragments.
+ */
+const RUN_PASS_THROUGH_KINDS: ReadonlySet<Block["kind"]> = new Set([
+ "log",
+ "sandbox",
+ "error",
+ "warning",
+ "notice",
+]);
+
+/**
+ * Unscrambles a run of interleaved subagent calls — any names — into
+ * individual sections: each call keeps its own header (ordinal subtitles
+ * tell parallel same-named calls apart) followed by its own newest-window
+ * of child rows. Collection is run-wide because parallel calls' children
+ * arrive interleaved in block order.
+ */
+function collectSubagentRun(
+ blocks: readonly Block[],
+ start: number,
+ logAnchors?: ReadonlyMap<Block, ToolBlockDisplayGroup>,
+): { consumed: number; groups: ToolBlockDisplayGroup[] } {
+ const first = blocks[start]!;
+ const headers = [first];
+ const childrenByCall = new Map<string, Block[]>([[first.subagentCallId!, []]]);
+ const passThrough: Block[] = [];
+ let consumed = 1;
+ for (; start + consumed < blocks.length; consumed += 1) {
+ const candidate = blocks[start + consumed]!;
+ if (RUN_PASS_THROUGH_KINDS.has(candidate.kind)) {
+ passThrough.push(candidate);
+ continue;
+ }
+ if (candidate.kind === "subagent") {
+ if (candidate.subagentCallId === undefined) break;
+ if (childrenByCall.has(candidate.subagentCallId)) break;
+ headers.push(candidate);
+ childrenByCall.set(candidate.subagentCallId, []);
+ continue;
+ }
+ const children =
+ candidate.subagentCallId === undefined
+ ? undefined
+ : childrenByCall.get(candidate.subagentCallId);
+ if (children === undefined) break;
+ children.push(candidate);
+ }
+ // Trailing pass-through blocks did not interrupt anything — hand them
+ // back to the main loop so they keep their position after the run.
+ while (passThrough.length > 0 && blocks[start + consumed - 1] === passThrough.at(-1)) {
+ passThrough.pop();
+ consumed -= 1;
+ }
+
+ const groups: ToolBlockDisplayGroup[] = [];
+ for (const header of headers) {
+ const children = childrenByCall.get(header.subagentCallId!)!;
+ // A section stays live while its own header or any of its children
+ // still streams; sibling calls settle independently.
+ const live = header.live !== false || children.some((child) => child.live !== false);
+ const headerDisplay: DisplayBlock =
+ live === (header.live !== false) ? header : { ...header, live };
+
+ // A completed call collapses whole: the header reports Done and the
+ // children fold into one counted footnote on the closing corner (the
+ // parent's own reply carries the conclusion). Members still ride the
+ // groups so they commit and clear by identity.
+ if (header.status === "done") {
+ const summary = condensedChildSummary(children);
+ groups.push({ members: [header], display: headerDisplay });
+ groups.push({
+ members: children,
+ display: {
+ kind: "subagent-close",
+ subagentCallId: header.subagentCallId!,
+ live,
+ body: summary === undefined ? "Done" : `Done. ${summary}`,
+ },
+ });
+ continue;
+ }
+
+ groups.push({ members: [header], display: headerDisplay });
+
+ // Group the full child list first — so a condensed row counts every
+ // call it stands for — then order MRU-down: each group sorts by its
+ // newest member, so the latest activity sits nearest the live edge and
+ // an accumulating batch sinks as it receives calls. The window keeps
+ // the most recent display rows; dropped groups' blocks stay members
+ // (they must still commit and clear by identity) but collapse into one
+ // display-only `… (N more)` row that counts raw events, not display
+ // rows.
+ // Activity stamps rank a just-updated call above a later-announced idle
+ // one. The renderer stamps every push and in-place update; grouping
+ // reads exactly one ordering semantic.
+ const recency = (group: ToolBlockDisplayGroup) =>
+ group.members.reduce((max, member) => Math.max(max, updateRecency(member)), -1);
+ const childGroups = groupToolBlocksForDisplay(children)
+ .slice()
+ .sort((a, b) => recency(a) - recency(b));
+ const dropped = childGroups.slice(
+ 0,
+ Math.max(0, childGroups.length - maxVisibleSubagentRunChildren),
+ );
+ const kept = childGroups.slice(dropped.length);
+ const elidedMembers = dropped.flatMap((group) => group.members);
+ if (elidedMembers.length > 0) {
+ groups.push({
+ members: elidedMembers,
+ display: { kind: "subagent-step", depth: 1, live, elided: elidedMembers.length },
+ });
+ }
+ // The rail closes on the newest child instead of a bare corner row:
+ // the last kept group's display (a clone — displays can be original
+ // blocks, and the flag must re-derive per paint) carries the corner.
+ groups.push(...kept.slice(0, -1));
+ const lastKept = kept.at(-1);
+ if (lastKept !== undefined) {
+ groups.push({
+ members: lastKept.members,
+ display: { ...lastKept.display, closesRail: true },
+ });
+ }
+ }
+ // Interrupting pass-through blocks render after the sections they
+ // spliced into. In window mode a spliced log write emits only if it is
+ // its bucket's anchor (the merged section); earlier members ride that
+ // group instead.
+ for (const block of passThrough) {
+ if (logAnchors !== undefined && isGroupableLogWrite(block)) {
+ const group = logAnchors.get(block);
+ if (group !== undefined) groups.push(group);
+ continue;
+ }
+ groups.push({ members: [block], display: block });
+ }
+ return { consumed, groups };
+}
+
+function aggregateToolBlocks(members: readonly Block[]): DisplayBlock {
+ const first = members[0]!;
+ const group = first.toolGroup!;
+ const count = members.length;
+ return {
+ ...first,
+ id: undefined,
+ result: undefined,
+ title: `${group.verb} ${count} ${count === 1 ? group.singularNoun : group.pluralNoun}`,
+ toolGroupItems: newestFirstItems(members),
+ };
+}
+
+/**
+ * The accumulating form of an in-flight batch: one counted header whose items
+ * list every announced call, newest first, so fresh calls surface at the top
+ * of the rail while earlier ones slide toward the elision line.
+ */
+function aggregateLiveToolBlocks(members: readonly Block[]): DisplayBlock {
+ return {
+ ...aggregateToolBlocks(members),
+ status: "running",
+ live: true,
+ };
+}
+
+/**
+ * The settled form of a successful batch: the counted header alone, past
+ * tense, with the item rail dropped — completed activity compresses to one
+ * line in the transcript.
+ */
+function collapseSettledToolBlocks(members: readonly Block[]): DisplayBlock {
+ const first = members[0]!;
+ const group = first.toolGroup!;
+ const count = members.length;
+ const noun = count === 1 ? group.singularNoun : group.pluralNoun;
+ return {
+ ...first,
+ id: undefined,
+ result: undefined,
+ title: `${group.verb} ${count} ${noun}`,
+ doneTitle: `${group.pastVerb} ${count} ${noun}`,
+ };
+}
+
+/**
+ * A settled child tool can fold into the multi-kind condensed row once a
+ * message follows it. Failures stay itemized — an error must not vanish
+ * into a count.
+ */
+function isCondensableChildTool(block: Block): boolean {
+ return block.kind === "subagent-tool" && block.status === "done" && block.expanded !== true;
+}
+
+/** A failed child call: rides a condensable run but keeps its own row. */
+function isItemizedChildFailure(block: Block): boolean {
+ return block.kind === "subagent-tool" && block.status === "error" && block.expanded !== true;
+}
+
+/** The (past verb, noun) copy one condensed-count entry renders with. */
+interface CondensedKindCopy {
+ readonly pastVerb: string;
+ readonly singularNoun: string;
+ readonly pluralNoun: string;
+}
+
+/** How many tool kinds the condensed row names before "and more". */
+const maxCondensedKinds = 3;
+
+/**
+ * The counted multi-kind summary of a settled child-tool run:
+ * `Ran 17 commands, Read 10 files, Wrote 6 files, and more`.
+ */
+function condensedRunTitle(run: readonly Block[]): string {
+ const counts = new Map<string, { copy: CondensedKindCopy; count: number }>();
+ for (const block of run) {
+ const copy = condensedKindCopy(block);
+ const key = `${copy.pastVerb} ${copy.pluralNoun}`;
+ const entry = counts.get(key);
+ if (entry === undefined) {
+ counts.set(key, { copy, count: 1 });
+ } else {
+ entry.count += 1;
+ }
+ }
+
+ const ranked = [...counts.values()].sort((a, b) => b.count - a.count);
+ const named = ranked
+ .slice(0, maxCondensedKinds)
+ .map(
+ ({ copy, count }) =>
+ `${copy.pastVerb} ${count} ${count === 1 ? copy.singularNoun : copy.pluralNoun}`,
+ );
+ return ranked.length > maxCondensedKinds ? `${named.join(", ")}, and more` : named.join(", ");
+}
+
+/**
+ * The whole activity footnote of a completed section: counted settled work
+ * plus a failure count — an error may fold into the collapsed form, but it
+ * must never vanish from it. `undefined` when the child ran no tools.
+ */
+function condensedChildSummary(children: readonly Block[]): string | undefined {
+ const tools = children.filter((block) => block.kind === "subagent-tool");
+ if (tools.length === 0) return undefined;
+ const settled = tools.filter((block) => block.status === "done");
+ const failed = tools.filter((block) => block.status === "error").length;
+ const parts: string[] = [];
+ if (settled.length > 0) parts.push(condensedRunTitle(settled));
+ if (failed > 0) parts.push(`${failed} failed`);
+ return parts.length > 0 ? parts.join(", ") : undefined;
+}
+
+/**
+ * Folds one settled child-tool run into a single counted row.
+ */
+function condenseChildToolRun(run: readonly Block[]): DisplayBlock {
+ const title = condensedRunTitle(run);
+ const first = run[0]!;
+ return {
+ kind: "subagent-tool",
+ subagentCallId: first.subagentCallId,
+ depth: first.depth,
+ live: first.live,
+ status: "done",
+ title,
+ doneTitle: title,
+ subtitle: "",
+ };
+}
+
+function condensedKindCopy(block: Block): CondensedKindCopy {
+ const group = block.toolGroup;
+ if (group !== undefined) {
+ return {
+ pastVerb: group.pastVerb,
+ singularNoun: group.singularNoun,
+ pluralNoun: group.pluralNoun,
+ };
+ }
+ if (toolBaseName(block.toolName ?? "") === "write_file") {
+ return { pastVerb: "Wrote", singularNoun: "file", pluralNoun: "files" };
+ }
+ return { pastVerb: "Made", singularNoun: "tool call", pluralNoun: "tool calls" };
+}
+
+/** A block's activity stamp; unstamped (test-built) blocks all tie at 0. */
+function updateRecency(block: Block): number {
+ return block.updateSeq ?? 0;
+}
+
+/**
+ * Most recently active call first: the rail reads bottom-up, like changes
+ * arriving. Activity stamps put a just-settled parallel call ahead of a
+ * later-announced one still idle.
+ */
+function newestFirstItems(members: readonly Block[]): ToolGroupItem[] {
+ return members
+ .map((member, position) => ({ member, order: updateRecency(member), position }))
+ .sort((a, b) => b.order - a.order || b.position - a.position)
+ .map(({ member }): ToolGroupItem => {
+ const item: ToolGroupItem = { text: member.toolGroup!.item };
+ // Failed calls keep their individual error summaries visible per row.
+ return member.status === "error" && member.result !== undefined
+ ? { ...item, result: member.result }
+ : item;
+ });
+}
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
new file mode 100644
index 000000000..e4b25af13
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it } from "vitest";
+
+import { getAllFrameworkToolNames } from "#runtime/framework-tools/index.js";
+
+import { presentPreparingTool, presentTool } from "./tool-presentation.js";
+
+describe("presentPreparingTool", () => {
+ it("leads with the activity verb while the input still streams", () => {
+ expect(presentPreparingTool("web_fetch").title).toBe("Fetch …");
+ expect(presentPreparingTool("bash").title).toBe("Run …");
+ expect(presentPreparingTool("write_file").title).toBe("Write …");
+ expect(presentPreparingTool("eve.web_search").title).toBe("Search …");
+ expect(presentPreparingTool("final_output").title).toBe("Return final output");
+ });
+
+ it("keeps unknown tools on their name with a quiet hint", () => {
+ const presentation = presentPreparingTool("linear__list_issues");
+ expect(presentation.title).toBe("linear__list_issues");
+ expect(presentation.subtitle).toBe("preparing…");
+ });
+});
+
+describe("presentTool", () => {
+ it("renders web_fetch as a semantic URL activity", () => {
+ const presentation = presentTool("web_fetch", {
+ format: "markdown",
+ url: "https://github.com/vercel/eve/issues/648",
+ });
+
+ expect(presentation.title).toBe("Fetch https://github.com/vercel/eve/issues/648");
+ expect(presentation.subtitle).toBe("");
+ expect(presentation.summarizeResult({ content: "large page" })).toBeUndefined();
+ expect(presentation.doneTitle).toBe("Fetched https://github.com/vercel/eve/issues/648");
+ expect(presentation.group).toEqual({
+ verb: "Fetch",
+ pastVerb: "Fetched",
+ singularNoun: "URL",
+ pluralNoun: "URLs",
+ item: "https://github.com/vercel/eve/issues/648",
+ });
+ });
+
+ it("recognizes namespaced web_fetch tools", () => {
+ expect(presentTool("eve.web_fetch", { url: "https://example.com" }).title).toBe(
+ "Fetch https://example.com",
+ );
+ });
+
+ it("neutralizes terminal controls in a model-controlled URL", () => {
+ const presentation = presentTool("web_fetch", {
+ url: "https://example.com/\u001b[2J\u0007path",
+ });
+
+ // Control code points are removed; printable remnants are harmless.
+ expect(presentation.title).toBe("Fetch https://example.com/[2Jpath");
+ expect(presentation.group?.item).toBe("https://example.com/[2Jpath");
+ expect(presentation.group?.item).not.toContain("\u001b");
+ expect(presentation.group?.item).not.toContain("\u0007");
+ });
+
+ it("maps every single-argument builtin through the shared copy table", () => {
+ expect(presentTool("bash", { command: "pnpm test" }).title).toBe("Run pnpm test");
+ expect(presentTool("glob", { pattern: "**/*.ts" }).title).toBe("Glob **/*.ts");
+ expect(presentTool("grep", { pattern: "useEve" }).title).toBe("Grep useEve");
+ expect(presentTool("load_skill", { skill: "commit" }).title).toBe("Load commit");
+ expect(presentTool("read_file", { filePath: "/workspace/agent.ts" })).toMatchObject({
+ title: "Read /workspace/agent.ts",
+ group: { verb: "Read", singularNoun: "file", pluralNoun: "files" },
+ });
+ expect(presentTool("write_file", { content: "x", filePath: "/workspace/a.ts" }).title).toBe(
+ "Write /workspace/a.ts",
+ );
+ });
+
+ it("keeps a write un-aggregated with its content as persistent rail detail", () => {
+ const presentation = presentTool("write_file", {
+ filePath: "/workspace/a.ts",
+ content: "const a = 1;\nconst b = 2;",
+ });
+
+ expect(presentation.title).toBe("Write /workspace/a.ts");
+ expect(presentation.doneTitle).toBe("Wrote /workspace/a.ts");
+ expect(presentation.group).toBeUndefined();
+ expect(presentation.detail).toEqual([{ text: "const a = 1;" }, { text: "const b = 2;" }]);
+ expect(presentation.keepDetailWhenDone).toBe(true);
+ });
+
+ it("diffs a write against the prior content the renderer provides", () => {
+ const created = presentTool(
+ "write_file",
+ { filePath: "/workspace/a.txt", content: "knicks\n" },
+ { existed: false },
+ );
+ expect(created.detail).toEqual([{ text: "knicks", kind: "added" }]);
+
+ const overwritten = presentTool(
+ "write_file",
+ { filePath: "/workspace/a.txt", content: "knicks\nnets\n" },
+ { previousContent: "knicks\n" },
+ );
+ expect(overwritten.detail).toEqual([{ text: "knicks" }, { text: "nets", kind: "added" }]);
+ });
+
+ it("collapses a multiline salient argument to its first non-empty line", () => {
+ const presentation = presentTool("bash", { command: "\n pnpm build\npnpm test" });
+
+ expect(presentation.title).toBe("Run pnpm build");
+ expect(presentation.group?.item).toBe("pnpm build");
+ });
+
+ it("renders web_search across both provider input shapes", () => {
+ // Anthropic's provider-managed tool sends a top-level query.
+ expect(presentTool("web_search", { query: "eve framework" })).toMatchObject({
+ title: "Search eve framework",
+ group: { verb: "Search", singularNoun: "query", pluralNoun: "queries" },
+ });
+
+ // Provider-managed variants send an objective/search_query pair.
+ expect(
+ presentTool("web_search", {
+ objective: "Find confirmed public events",
+ search_query: "public events 2026",
+ }).title,
+ ).toBe("Search Find confirmed public events");
+ expect(presentTool("web_search", { search_query: "public events 2026" }).title).toBe(
+ "Search public events 2026",
+ );
+
+ // OpenAI nests the argument under `action`.
+ expect(
+ presentTool("web_search", { action: { type: "search", queries: ["smoke"] } }).title,
+ ).toBe("Search smoke");
+ expect(presentTool("web_search", { action: { queries: ["alpha", "beta"] } }).title).toBe(
+ "Search alpha, beta",
+ );
+ expect(
+ presentTool("web_search", { action: { type: "openPage", url: "https://example.com" } }).title,
+ ).toBe("Search https://example.com");
+ expect(
+ presentTool("web_search", { action: { type: "findInPage", pattern: "pricing" } }).title,
+ ).toBe("Search pricing");
+ });
+
+ it("renders todo maintenance without dumping the list", () => {
+ const update = presentTool("todo", {
+ todos: [
+ { content: "a", status: "completed", priority: "high" },
+ { content: "b", status: "in_progress", priority: "low" },
+ ],
+ });
+ expect(update.title).toBe("Update todo list");
+ expect(update.subtitle).toBe("2 tasks");
+ expect(update.summarizeResult({ counts: { total: 2 } })).toBeUndefined();
+
+ expect(presentTool("todo", {}).title).toBe("Read todo list");
+ expect(presentTool("todo", undefined).title).toBe("Read todo list");
+ });
+
+ it("renders the remaining structured builtins semantically", () => {
+ expect(presentTool("ask_question", { prompt: "Which environment?" }).title).toBe(
+ "Ask Which environment?",
+ );
+ expect(presentTool("agent", { message: "Audit the auth flow.\nDetails…" }).title).toBe(
+ "Delegate Audit the auth flow.",
+ );
+ expect(presentTool("connection_search", { keywords: "linear issues" }).title).toBe(
+ "Discover linear issues",
+ );
+ expect(presentTool("final_output", { anything: true }).title).toBe("Return final output");
+ });
+
+ it("covers every framework builtin with semantic copy", () => {
+ const representativeInputs: Record<string, unknown> = {
+ agent: { message: "audit the auth flow" },
+ ask_question: { prompt: "Which environment?" },
+ bash: { command: "ls" },
+ glob: { pattern: "**/*.ts" },
+ grep: { pattern: "useEve" },
+ load_skill: { skill: "commit" },
+ read_file: { filePath: "/workspace/a.ts" },
+ todo: { todos: [] },
+ web_fetch: { url: "https://example.com" },
+ web_search: { query: "eve framework" },
+ write_file: { filePath: "/workspace/a.ts", content: "x" },
+ };
+
+ for (const name of getAllFrameworkToolNames()) {
+ const input = representativeInputs[name];
+ expect(
+ input,
+ `framework tool "${name}" has no representative input — add semantic copy for it in tool-presentation.ts and cover it here`,
+ ).toBeDefined();
+ expect(presentTool(name, input).title, name).not.toBe(name);
+ }
+ });
+
+ it("falls back to the generic formatter for malformed input", () => {
+ const presentation = presentTool("web_fetch", { format: "markdown" });
+
+ expect(presentation.title).toBe("web_fetch");
+ expect(presentation.subtitle).toContain('format="markdown"');
+ });
+
+ it("presents a named subagent dispatch as a delegation", () => {
+ const parsed = presentTool(
+ "stock-price",
+ { message: "Look up GOOG.\nDetails…" },
+ { isSubagent: true },
+ );
+ expect(parsed.title).toBe("Delegate stock-price");
+ expect(parsed.doneTitle).toBe("Delegated stock-price");
+ expect(parsed.subtitle).toBe("Look up GOOG.");
+
+ // The tool's name carries the target, so it shows before args parse.
+ expect(presentPreparingTool("stock-price", { isSubagent: true }).title).toBe(
+ "Delegate stock-price …",
+ );
+ // Without roster knowledge the generic formatter keeps its shape.
+ expect(presentTool("stock-price", { message: "x" }).title).toBe("stock-price");
+ });
+
+ it("keeps unknown tools on the generic formatter", () => {
+ const presentation = presentTool("linear__list_issues", { teamId: "T1" });
+
+ expect(presentation.title).toBe("linear__list_issues");
+ expect(presentation.subtitle).toContain('teamId="T1"');
+ expect(presentation.group).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.ts
new file mode 100644
index 000000000..0bd23fbb8
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts
@@ -0,0 +1,376 @@
+import { diffWriteDetail, type ToolDetailLine } from "./line-diff.js";
+import { stripTerminalControls } from "#cli/ui/terminal-text.js";
+import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";
+
+/** Renderer-ready copy derived from a tool call without owning its lifecycle. */
+export interface ToolPresentation {
+ readonly title: string;
+ readonly subtitle: string;
+ readonly summarizeResult: (output: unknown) => string | undefined;
+ readonly group?: ToolGroupPresentation;
+ /** Past-tense title used once the call settles successfully. */
+ readonly doneTitle?: string;
+ /** Salient body lines shown behind the `│` rail under the header. */
+ readonly detail?: readonly ToolDetailLine[];
+ /** When true, `detail` stays visible after the call settles (writes). */
+ readonly keepDetailWhenDone?: boolean;
+}
+
+/**
+ * Renderer-owned knowledge a presentation may fold in: what a write replaced
+ * (from the session's file-content cache) and whether the file existed (from
+ * the call's result, once it arrives).
+ */
+export interface ToolPresentationContext {
+ readonly previousContent?: string;
+ readonly existed?: boolean;
+ /**
+ * True when the tool dispatches a named subagent (each subagent exposes a
+ * tool bearing its own name). The presentation reads as a delegation —
+ * `Delegate stock-price` — instead of a generic tool call.
+ */
+ readonly isSubagent?: boolean;
+}
+
+/** Copy needed to aggregate equivalent calls without merging their state. */
+export interface ToolGroupPresentation {
+ readonly verb: string;
+ readonly pastVerb: string;
+ readonly singularNoun: string;
+ readonly pluralNoun: string;
+ readonly item: string;
+}
+
+/** Semantic activity copy for one builtin tool with a single telling argument. */
+interface BuiltinToolCopy {
+ readonly verb: string;
+ readonly pastVerb: string;
+ readonly argKey: string;
+ /**
+ * Tool-specific extraction for provider-managed input shapes the plain
+ * `argKey` lookup can't reach (alternate key names, nested objects).
+ * Runs after `argKey` misses.
+ */
+ readonly extractItem?: (input: unknown) => string | undefined;
+ readonly singularNoun: string;
+ readonly pluralNoun: string;
+}
+
+/** Copy shared by the full presenters and their preparing placeholders. */
+const WRITE_FILE_VERB = "Write";
+const DELEGATE_VERB = "Delegate";
+const FINAL_OUTPUT_TITLE = "Return final output";
+
+/**
+ * Builtin tools whose calls read as one verb plus one argument. Runs group
+ * by tool name; equal copy across two tools only merges their entries in a
+ * completed section's counted summary, which reads fine.
+ */
+const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {
+ agent: {
+ verb: "Delegate",
+ pastVerb: "Delegated",
+ argKey: "message",
+ singularNoun: "task",
+ pluralNoun: "tasks",
+ },
+ ask_question: {
+ verb: "Ask",
+ pastVerb: "Asked",
+ argKey: "prompt",
+ singularNoun: "question",
+ pluralNoun: "questions",
+ },
+ bash: {
+ verb: "Run",
+ pastVerb: "Ran",
+ argKey: "command",
+ singularNoun: "command",
+ pluralNoun: "commands",
+ },
+ connection_search: {
+ verb: "Discover",
+ pastVerb: "Discovered",
+ argKey: "keywords",
+ singularNoun: "tool search",
+ pluralNoun: "tool searches",
+ },
+ glob: {
+ verb: "Glob",
+ pastVerb: "Globbed",
+ argKey: "pattern",
+ singularNoun: "pattern",
+ pluralNoun: "patterns",
+ },
+ grep: {
+ verb: "Grep",
+ pastVerb: "Grepped",
+ argKey: "pattern",
+ singularNoun: "pattern",
+ pluralNoun: "patterns",
+ },
+ load_skill: {
+ verb: "Load",
+ pastVerb: "Loaded",
+ argKey: "skill",
+ singularNoun: "skill",
+ pluralNoun: "skills",
+ },
+ read_file: {
+ verb: "Read",
+ pastVerb: "Read",
+ argKey: "filePath",
+ singularNoun: "file",
+ pluralNoun: "files",
+ },
+ web_fetch: {
+ verb: "Fetch",
+ pastVerb: "Fetched",
+ argKey: "url",
+ singularNoun: "URL",
+ pluralNoun: "URLs",
+ },
+ web_search: {
+ verb: "Search",
+ pastVerb: "Searched",
+ argKey: "query",
+ // Provider-managed variants disagree on the argument shape: some send
+ // an `objective`/`search_query` pair instead of Anthropic's `query`,
+ // and OpenAI nests it under `action`.
+ extractItem: (input) =>
+ salientArg(input, "objective") ??
+ salientArg(input, "search_query") ??
+ salientArg(input, "searchQuery") ??
+ webSearchActionArg(input),
+ singularNoun: "query",
+ pluralNoun: "queries",
+ },
+};
+
+/**
+ * A write is never aggregated: each written file keeps its own block, and the
+ * written content stays visible after the call settles — the change itself is
+ * the story, unlike other builtin outputs. Lines arrive uncapped; the block
+ * renderer windows them so a large generated file cannot flood the transcript.
+ */
+function presentWriteFileTool(
+ toolName: string,
+ input: unknown,
+ context: ToolPresentationContext | undefined,
+): ToolPresentation {
+ const write = readWriteFileInput(toolName, input);
+ if (write === undefined) {
+ return {
+ title: toolName,
+ subtitle: summarizeToolArgs(input),
+ summarizeResult: summarizeToolResult,
+ };
+ }
+
+ // Diff on raw content; model-controlled text loses its terminal controls
+ // only at the display boundary so the comparison stays exact.
+ const detail = diffWriteDetail(context?.previousContent, write.content, context?.existed).map(
+ (line) => (line.kind === "gap" ? line : { ...line, text: stripTerminalControls(line.text) }),
+ );
+
+ return {
+ title: `${WRITE_FILE_VERB} ${salientLine(write.path) ?? write.path}`,
+ doneTitle: `Wrote ${salientLine(write.path) ?? write.path}`,
+ subtitle: "",
+ summarizeResult: () => undefined,
+ detail,
+ keepDetailWhenDone: true,
+ };
+}
+
+/**
+ * Extracts a write tool call's full-replacement payload. Exported so the
+ * renderer can feed its file-content cache from the same contract the
+ * presentation reads.
+ */
+export function readWriteFileInput(
+ toolName: string,
+ input: unknown,
+): { path: string; content: string } | undefined {
+ if (toolBaseName(toolName) !== "write_file") return undefined;
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const record = input as Record<string, unknown>;
+ const path = record["filePath"];
+ const content = record["content"];
+ if (typeof path !== "string" || path.trim().length === 0) return undefined;
+ if (typeof content !== "string") return undefined;
+ return { path, content };
+}
+
+/**
+ * Turns known tool contracts into concise activity copy. Unknown or malformed
+ * calls keep the generic formatter, so presentation can never break execution.
+ */
+export function presentTool(
+ toolName: string,
+ input: unknown,
+ context?: ToolPresentationContext,
+): ToolPresentation {
+ const baseName = toolBaseName(toolName);
+ if (baseName === "todo") return presentTodoTool(input);
+ if (baseName === "write_file") return presentWriteFileTool(toolName, input, context);
+ if (context?.isSubagent === true) {
+ // Named subagent dispatch: the tool name is the delegation target; the
+ // message rides as the quiet subtitle. The block is transient — the
+ // nested subagent section replaces it once the child registers.
+ return {
+ title: `${DELEGATE_VERB} ${baseName}`,
+ doneTitle: `Delegated ${baseName}`,
+ subtitle: salientArg(input, "message") ?? "",
+ summarizeResult: () => undefined,
+ };
+ }
+ if (baseName === "final_output") {
+ // Task-mode terminal signal (subagent streams): its input is the
+ // structured result itself, kept behind the expanded `--tools full` view.
+ return { title: FINAL_OUTPUT_TITLE, subtitle: "", summarizeResult: () => undefined };
+ }
+
+ const copy = BUILTIN_TOOL_COPY[baseName];
+ if (copy !== undefined) {
+ const item = salientArg(input, copy.argKey) ?? copy.extractItem?.(input);
+ if (item !== undefined) {
+ return {
+ title: `${copy.verb} ${item}`,
+ doneTitle: `${copy.pastVerb} ${item}`,
+ subtitle: "",
+ // The salient argument is the story; builtin outputs (page content,
+ // file bodies, stdout) stay behind the expanded `--tools full` view.
+ summarizeResult: () => undefined,
+ group: {
+ verb: copy.verb,
+ pastVerb: copy.pastVerb,
+ singularNoun: copy.singularNoun,
+ pluralNoun: copy.pluralNoun,
+ item,
+ },
+ };
+ }
+ }
+
+ return {
+ title: toolName,
+ subtitle: summarizeToolArgs(input),
+ summarizeResult: summarizeToolResult,
+ };
+}
+
+/**
+ * Placeholder copy for a call whose input is still streaming from the model
+ * (`action.preparing`). Known tools lead with their activity verb so the row
+ * already reads as intent (`Fetch …`); unknown tools keep their name with a
+ * quiet hint. The full presentation replaces this once the input arrives.
+ */
+export function presentPreparingTool(
+ toolName: string,
+ context?: ToolPresentationContext,
+): ToolPresentation {
+ const baseName = toolBaseName(toolName);
+ if (baseName === "final_output") {
+ return { title: FINAL_OUTPUT_TITLE, subtitle: "", summarizeResult: () => undefined };
+ }
+ if (context?.isSubagent === true) {
+ // A named subagent's tool carries the delegation target in its name —
+ // showable before the message finishes streaming.
+ return {
+ title: `${DELEGATE_VERB} ${baseName} …`,
+ subtitle: "",
+ summarizeResult: () => undefined,
+ };
+ }
+ const verb = baseName === "write_file" ? WRITE_FILE_VERB : BUILTIN_TOOL_COPY[baseName]?.verb;
+ return {
+ title: verb === undefined ? toolName : `${verb} …`,
+ subtitle: verb === undefined ? "preparing…" : "",
+ summarizeResult: () => undefined,
+ };
+}
+
+/**
+ * Tools whose whole story renders through a dedicated surface — the pinned
+ * todo panel, the question overlay — instead of a transcript tool block.
+ * Both the preparing announcement and the full call must agree on this
+ * set, or a panel-routed tool ghosts as a preparing block.
+ */
+export function isPanelRoutedTool(toolName: string): boolean {
+ const baseName = toolBaseName(toolName);
+ return baseName === "todo" || baseName === "ask_question";
+}
+
+/** The tool's short name with any connection/server namespace stripped. */
+export function toolBaseName(toolName: string): string {
+ return toolName.split(/[.:/]/u).at(-1) ?? toolName;
+}
+
+/**
+ * `todo` writes the whole list (or reads it when `todos` is omitted), so its
+ * call reads as list maintenance, not as one salient argument. The list body
+ * stays behind the expanded `--tools full` view, like other builtin outputs.
+ */
+function presentTodoTool(input: unknown): ToolPresentation {
+ const todos =
+ input !== null && typeof input === "object" && !Array.isArray(input)
+ ? (input as Record<string, unknown>)["todos"]
+ : undefined;
+ if (!Array.isArray(todos)) {
+ return { title: "Read todo list", subtitle: "", summarizeResult: () => undefined };
+ }
+ return {
+ title: "Update todo list",
+ subtitle: `${todos.length} task${todos.length === 1 ? "" : "s"}`,
+ summarizeResult: () => undefined,
+ };
+}
+
+/**
+ * OpenAI's provider-managed web search nests its argument under `action`
+ * (`search` carries `query`/`queries`, `openPage` a `url`, `findInPage` a
+ * `pattern`); Anthropic's sends a top-level `query`, which the plain
+ * `argKey` lookup already covers.
+ */
+function webSearchActionArg(input: unknown): string | undefined {
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const action = (input as Record<string, unknown>)["action"];
+ if (action === null || typeof action !== "object" || Array.isArray(action)) return undefined;
+ const record = action as Record<string, unknown>;
+ const queries = record["queries"];
+ if (Array.isArray(queries)) {
+ const items = queries.filter((query) => typeof query === "string").map(salientLine);
+ const joined = items.filter((item) => item !== undefined).join(", ");
+ if (joined.length > 0) return joined;
+ }
+ for (const key of ["query", "url", "pattern"]) {
+ const value = record[key];
+ if (typeof value === "string") {
+ const line = salientLine(value);
+ if (line !== undefined) return line;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * The one argument worth rendering, reduced to a single safe line. `group.item`
+ * renders verbatim in aggregated rows, so a model-controlled value must lose
+ * its terminal controls here, not at the render call sites.
+ */
+function salientArg(input: unknown, key: string): string | undefined {
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const value = (input as Record<string, unknown>)[key];
+ if (typeof value !== "string") return undefined;
+ return salientLine(value);
+}
+
+/** Reduces a model-controlled string to its first non-empty, control-free line. */
+function salientLine(value: string): string | undefined {
+ const line = stripTerminalControls(value)
+ .split(/\r?\n/u)
+ .find((candidate) => candidate.trim().length > 0);
+ const trimmed = line?.trim() ?? "";
+ return trimmed.length > 0 ? trimmed : undefined;
+}
diff --git a/packages/eve/src/cli/dev/tui/tool-rows.ts b/packages/eve/src/cli/dev/tui/tool-rows.ts
new file mode 100644
index 000000000..2c43d87d1
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/tool-rows.ts
@@ -0,0 +1,243 @@
+/**
+ * Renders a tool block's terminal rows: the indented header (status glyph,
+ * verb-bold title, summarized args), the `│`-railed detail region —
+ * aggregated batch items or a write's diffed content — closed by a `└`
+ * corner, and the settled result line. Split from `blocks.ts` so the block
+ * model and its per-kind renderers stay separable concerns.
+ */
+
+import type { DisplayBlock, RenderBlockContext, ToolGroupItem, ToolStatus } from "./blocks.js";
+import type { ToolDetailLine } from "./line-diff.js";
+import type { Theme } from "./theme.js";
+import { formatValuePretty, truncate } from "./tool-format.js";
+import { elisionText } from "./rail.js";
+import { clipVisible, visibleLength, wrapVisibleLine } from "#cli/ui/terminal-text.js";
+
+export function renderTool(
+ block: DisplayBlock,
+ width: number,
+ theme: Theme,
+ context: RenderBlockContext,
+): string[] {
+ // Top-level tool rows sit one extra level in so their marks start at the
+ // prose text column (the character after the `│`/`▲` gutter). Nested
+ // subagent rows keep the tighter lead inside their section's rail.
+ if ((block.depth ?? 0) === 0) {
+ // One cell here plus the row's own one-cell indent lands the mark at
+ // the shared tool column.
+ return renderToolRows(block, width - 1, theme, context).map((row) => ` ${row}`);
+ }
+ return renderToolRows(block, width, theme, context);
+}
+
+function renderToolRows(
+ block: DisplayBlock,
+ width: number,
+ theme: Theme,
+ context: RenderBlockContext,
+): string[] {
+ const { icon, accent } = toolGlyph(block.status ?? "running", theme, context);
+ const name =
+ block.status === "done" && block.doneTitle !== undefined
+ ? block.doneTitle
+ : (block.title ?? "tool");
+ // The header is indented one cell so its glyph shares a column with the
+ // `│`/`└` rail beneath it.
+ const headerWidth = width - 3;
+ const namePlain = clipVisible(name, headerWidth);
+ let header = ` ${icon} ${boldLeadingWord(namePlain, theme)}`;
+ const argsBudget = headerWidth - namePlain.length - 2;
+ const args = block.subtitle ?? "";
+ if (args.length > 0 && argsBudget >= 6) {
+ header += ` ${theme.colors.gray(truncate(args, argsBudget))}`;
+ }
+
+ const rows = [header];
+
+ // Detail region: `│`-railed rows closed by a `└` corner. Group items and
+ // write bodies share the rail so every accumulating tool reads the same.
+ const railRows: string[] = [];
+ if (block.toolGroupItems !== undefined) {
+ railRows.push(...toolGroupItemRows(block.toolGroupItems, width, theme));
+ } else if (!block.expanded && showToolDetail(block)) {
+ railRows.push(...detailLineRows(block.detailLines ?? [], width, theme));
+ }
+ if (railRows.length > 0) {
+ rows.push(...railRows, ` ${theme.colors.dim(theme.glyph.corner)}`);
+ }
+
+ if (block.expanded) {
+ rows.push(...renderToolExpanded(block, width, theme));
+ } else if (block.status === "done" && block.result && block.result.length > 0) {
+ rows.push(resultLine(theme.glyph.arrow, block.result, width, theme, accent));
+ } else if (block.status === "error" && block.result) {
+ // The failure summary hangs on a corner aligned under the title text,
+ // reading as the call's closing line rather than a returned value.
+ rows.push(errorDetailLine(block.result, width, theme));
+ } else if (block.status === "denied") {
+ rows.push(resultLine(theme.glyph.arrow, "denied", width, theme, theme.colors.yellow));
+ }
+
+ return rows;
+}
+
+/**
+ * Only the verb carries the header's weight: `Ran find /workspace …` reads
+ * as a bold action with its argument dimmed behind it, not one long banner.
+ */
+function boldLeadingWord(text: string, theme: Theme): string {
+ const split = text.indexOf(" ");
+ if (split === -1) return theme.colors.bold(text);
+ return `${theme.colors.bold(text.slice(0, split))}${theme.colors.dim(text.slice(split))}`;
+}
+
+/** Detail stays up while the call runs; after settling only writes keep it. */
+function showToolDetail(block: DisplayBlock): boolean {
+ if (block.detailLines === undefined || block.detailLines.length === 0) return false;
+ const status = block.status ?? "running";
+ if (status === "running" || status === "approval") return true;
+ return block.keepDetailWhenDone === true;
+}
+
+/**
+ * An aggregated tool row lists at most this many member items; the rest
+ * collapse into a single `… (N more)` line above the closing corner.
+ */
+export const maxVisibleToolGroupItems = 5;
+
+/** A write's visible content is windowed to this many rail rows. */
+const maxVisibleToolDetailLines = 10;
+
+function railRow(body: string, theme: Theme): string {
+ return ` ${theme.colors.dim(theme.glyph.rule)} ${body}`;
+}
+
+function elisionRow(hidden: number, theme: Theme): string {
+ return railRow(elisionText(hidden, theme), theme);
+}
+
+function toolGroupItemRows(items: readonly ToolGroupItem[], width: number, theme: Theme): string[] {
+ const visible = items.slice(0, maxVisibleToolGroupItems);
+ const hidden = items.length - visible.length;
+ const rows = itemRows(visible, width, theme);
+ if (hidden > 0) {
+ rows.push(elisionRow(hidden, theme));
+ }
+ return rows;
+}
+
+function detailLineRows(lines: readonly ToolDetailLine[], width: number, theme: Theme): string[] {
+ const c = theme.colors;
+ const visible = lines.slice(0, maxVisibleToolDetailLines);
+ const hidden = lines.length - visible.length;
+ // A region with changes gets a marker column so `+`/`-` rows and their
+ // context stay aligned; plain content keeps the tighter rail.
+ const hasDiff = visible.some((line) => line.kind === "added" || line.kind === "removed");
+ const budget = Math.max(1, width - (hasDiff ? 5 : 4));
+
+ // Content lines clip rather than wrap: file bodies read best one row per
+ // logical line, and the window cap already bounds the region's height.
+ const rows = visible.map((line) => {
+ if (line.kind === "gap") {
+ return railRow(c.dim(theme.glyph.ellipsis), theme);
+ }
+ const text = clipVisible(line.text, budget);
+ switch (line.kind) {
+ case "added":
+ return ` ${c.dim(theme.glyph.rule)}${c.green("+")} ${c.green(text)}`;
+ case "removed":
+ return ` ${c.dim(theme.glyph.rule)}${c.red("-")} ${c.red(text)}`;
+ default:
+ return hasDiff
+ ? ` ${c.dim(theme.glyph.rule)} ${c.gray(text)}`
+ : railRow(c.gray(text), theme);
+ }
+ });
+ if (hidden > 0) rows.push(elisionRow(hidden, theme));
+ return rows;
+}
+
+function itemRows(items: readonly ToolGroupItem[], width: number, theme: Theme): string[] {
+ const budget = Math.max(1, width - 4);
+ const hasResults = items.some((item) => item.result !== undefined && item.result.length > 0);
+ if (!hasResults) {
+ return items.map((item) => railRow(theme.colors.gray(truncate(item.text, budget)), theme));
+ }
+
+ // Failure summaries align into one column so a mixed batch scans like a
+ // table; long items yield to keep at least a short summary visible.
+ const textColumn = Math.min(
+ Math.max(...items.map((item) => visibleLength(item.text))),
+ Math.max(8, budget - 9),
+ );
+ const resultBudget = Math.max(8, budget - textColumn - 1);
+ return items.map((item) => {
+ const text = truncate(item.text, textColumn);
+ if (item.result === undefined || item.result.length === 0) {
+ return railRow(theme.colors.gray(text), theme);
+ }
+ const padded = text + " ".repeat(Math.max(0, textColumn - visibleLength(text)));
+ return railRow(
+ `${theme.colors.gray(padded)} ${theme.colors.red(truncate(item.result, resultBudget))}`,
+ theme,
+ );
+ });
+}
+
+function renderToolExpanded(block: DisplayBlock, width: number, theme: Theme): string[] {
+ const rows: string[] = [];
+ const push = (label: string, value: unknown, color: (text: string) => string) => {
+ if (value === undefined) return;
+ rows.push(` ${theme.colors.dim(label)}`);
+ for (const raw of formatValuePretty(value).split("\n")) {
+ for (const line of wrapVisibleLine(raw, Math.max(1, width - 4))) {
+ rows.push(` ${color(line)}`);
+ }
+ }
+ };
+ push("input", block.toolInput, theme.colors.gray);
+ if (block.status === "error" && block.result) {
+ push("error", block.result, theme.colors.red);
+ } else {
+ push("output", block.toolOutput, theme.colors.gray);
+ }
+ return rows;
+}
+
+function resultLine(
+ marker: string,
+ text: string,
+ width: number,
+ theme: Theme,
+ color: (text: string) => string,
+): string {
+ const budget = width - 4;
+ return ` ${theme.colors.dim(marker)} ${color(truncate(text, budget))}`;
+}
+
+function errorDetailLine(text: string, width: number, theme: Theme): string {
+ const budget = width - 5;
+ return ` ${theme.colors.dim(theme.glyph.corner)} ${theme.colors.red(truncate(text, budget))}`;
+}
+
+function toolGlyph(
+ status: ToolStatus,
+ theme: Theme,
+ context: RenderBlockContext,
+): { icon: string; accent: (text: string) => string } {
+ switch (status) {
+ case "done":
+ // The settled form of the running pulse (`▪` held steady), not a green
+ // check: completed activity reads as a quiet one-line summary.
+ return { icon: theme.colors.gray(theme.glyph.square), accent: theme.colors.gray };
+ case "error":
+ return { icon: theme.colors.red(theme.glyph.error), accent: theme.colors.red };
+ case "denied":
+ return { icon: theme.colors.yellow(theme.glyph.warning), accent: theme.colors.yellow };
+ case "approval":
+ return { icon: theme.colors.yellow(theme.glyph.question), accent: theme.colors.yellow };
+ case "running":
+ default:
+ return { icon: theme.colors.yellow(context.activityPulse), accent: theme.colors.gray };
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/turn-clock.ts b/packages/eve/src/cli/dev/tui/turn-clock.ts
new file mode 100644
index 000000000..e7cccb558
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/turn-clock.ts
@@ -0,0 +1,54 @@
+/**
+ * One turn's wall clock and summed token flow. "When did this turn start"
+ * is a single fact; this object is its single representation — armed once
+ * per turn (a prompt submit, or an `--input` turn arming itself), fed by
+ * step usage reports, and consumed exactly once by the end-of-turn coda.
+ * Multi-pass turns (question answers, connection authorizations) re-stream
+ * without re-arming, so one turn gets one coda.
+ */
+export class TurnClock {
+ #startedAtMs?: number;
+ #usage = { inputTokens: 0, outputTokens: 0 };
+
+ /** Starts the turn: resets the summed flow and stamps the clock. */
+ arm(): void {
+ this.#startedAtMs = Date.now();
+ this.#usage = { inputTokens: 0, outputTokens: 0 };
+ }
+
+ get armed(): boolean {
+ return this.#startedAtMs !== undefined;
+ }
+
+ get startedAtMs(): number | undefined {
+ return this.#startedAtMs;
+ }
+
+ get usage(): { readonly inputTokens: number; readonly outputTokens: number } {
+ return this.#usage;
+ }
+
+ addUsage(usage: { inputTokens?: number; outputTokens?: number }): void {
+ this.#usage.inputTokens += usage.inputTokens ?? 0;
+ this.#usage.outputTokens += usage.outputTokens ?? 0;
+ }
+
+ /**
+ * Consumes the armed clock, returning the turn's elapsed time and summed
+ * flow — or `undefined` when no turn was armed (the coda's "already
+ * settled" signal). The flow survives the settle so a repaint between the
+ * coda and the next arm still reads the last turn's numbers.
+ */
+ settle(): { elapsedMs: number; inputTokens: number; outputTokens: number } | undefined {
+ const startedAtMs = this.#startedAtMs;
+ if (startedAtMs === undefined) return undefined;
+ this.#startedAtMs = undefined;
+ return { elapsedMs: Date.now() - startedAtMs, ...this.#usage };
+ }
+
+ /** Drops the clock without a coda (conversation boundaries). */
+ reset(): void {
+ this.#startedAtMs = undefined;
+ this.#usage = { inputTokens: 0, outputTokens: 0 };
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/types.ts b/packages/eve/src/cli/dev/tui/types.ts
index db33f9e66..509774b33 100644
--- a/packages/eve/src/cli/dev/tui/types.ts
+++ b/packages/eve/src/cli/dev/tui/types.ts
@@ -60,8 +60,8 @@ export type TuiDisplayOptions = {
/**
* The model context window size in tokens.
*
- * When provided, the terminal UI shows the current total token usage as a
- * percentage of this context window.
+ * When provided, the end-of-turn stats line shows the context fill as a
+ * percentage of this window.
*/
contextSize?: number;
diff --git a/packages/eve/src/cli/dev/ui-options.ts b/packages/eve/src/cli/dev/ui-options.ts
index 920a58ee2..d87a0d4b8 100644
--- a/packages/eve/src/cli/dev/ui-options.ts
+++ b/packages/eve/src/cli/dev/ui-options.ts
@@ -32,7 +32,9 @@ export function resolveDevUiMode(input: {
export function resolveTuiDisplayOptions(options: DevelopmentTuiOptions): TuiDisplayOptions {
const display: TuiDisplayOptions = {
logs: options.logs ?? "stderr",
- reasoning: options.reasoning ?? "full",
+ // Collapsed reasoning renders as the fixed thinking line; `--reasoning
+ // full` restores the streaming transcript trace.
+ reasoning: options.reasoning ?? "auto-collapsed",
tools: options.tools ?? "auto-collapsed",
};
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index 4a4119a24..5ee643ca9 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -493,10 +493,12 @@ describe("resolveDevUiMode", () => {
});
describe("resolveTuiDisplayOptions", () => {
- it("defaults tools to auto-collapsed, reasoning to full, and stderr logs visible", () => {
+ it("defaults tools and reasoning to auto-collapsed with stderr logs visible", () => {
expect(resolveTuiDisplayOptions({})).toEqual({
logs: "stderr",
- reasoning: "full",
+ // Collapsed reasoning is the fixed thinking line; `--reasoning full`
+ // restores the streaming transcript trace.
+ reasoning: "auto-collapsed",
tools: "auto-collapsed",
});
});
diff --git a/packages/eve/src/internal/nitro/routes/info.ts b/packages/eve/src/internal/nitro/routes/info.ts
index b657fcc12..7b7c7b246 100644
--- a/packages/eve/src/internal/nitro/routes/info.ts
+++ b/packages/eve/src/internal/nitro/routes/info.ts
@@ -1,4 +1,5 @@
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { hasEnvValue } from "#internal/resolve-model-endpoint-status.js";
import { buildAgentInfoResponseFromManifest } from "#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js";
import {
loadAgentInfoManifestData,
@@ -19,10 +20,6 @@ async function createAgentInfoPayload(input: NitroArtifactsConfig) {
});
}
-function hasEnvValue(value: string | undefined): boolean {
- return value !== undefined && value.trim() !== "";
-}
-
/**
* Mirrors the AI Gateway credential selection order. The Vercel OIDC SDK owns
* request-context, environment, and linked-project token resolution; lookup
diff --git a/packages/eve/src/internal/resolve-model-endpoint-status.test.ts b/packages/eve/src/internal/resolve-model-endpoint-status.test.ts
index 053de2cec..c589ccb8a 100644
--- a/packages/eve/src/internal/resolve-model-endpoint-status.test.ts
+++ b/packages/eve/src/internal/resolve-model-endpoint-status.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
-import { resolveModelEndpointStatus } from "./resolve-model-endpoint-status.js";
+import {
+ resolveGatewayCredential,
+ resolveModelEndpointStatus,
+} from "./resolve-model-endpoint-status.js";
describe("resolveModelEndpointStatus", () => {
it("reports an external endpoint without a connectedness claim", () => {
@@ -39,3 +42,35 @@ describe("resolveModelEndpointStatus", () => {
).toEqual({ kind: "gateway", connected: false });
});
});
+
+describe("resolveGatewayCredential", () => {
+ it("ranks an env-file key first, attributing its location", () => {
+ expect(
+ resolveGatewayCredential({ apiKeyFile: ".env.local", apiKeyInEnv: true, oidcFile: ".env" }),
+ ).toEqual({
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ shadowedOidc: { file: ".env" },
+ });
+ });
+
+ it("ranks a shell key over the OIDC token it shadows", () => {
+ expect(resolveGatewayCredential({ apiKeyInEnv: true, oidcAvailable: true })).toEqual({
+ credential: "api-key",
+ source: { kind: "shell" },
+ shadowedOidc: {},
+ });
+ });
+
+ it("falls to oidc only when no key exists anywhere", () => {
+ expect(resolveGatewayCredential({ oidcFile: ".env.local" })).toEqual({
+ credential: "oidc",
+ file: ".env.local",
+ });
+ expect(resolveGatewayCredential({ oidcAvailable: true })).toEqual({ credential: "oidc" });
+ });
+
+ it("resolves nothing when no credential is observable", () => {
+ expect(resolveGatewayCredential({})).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/internal/resolve-model-endpoint-status.ts b/packages/eve/src/internal/resolve-model-endpoint-status.ts
index 553f07ffc..b1f9e3c0a 100644
--- a/packages/eve/src/internal/resolve-model-endpoint-status.ts
+++ b/packages/eve/src/internal/resolve-model-endpoint-status.ts
@@ -13,14 +13,80 @@ export interface GatewayCredentialPresence {
readonly oidc: boolean;
}
+/** True when an environment value is present and non-blank. */
+export function hasEnvValue(value: string | undefined): boolean {
+ return value !== undefined && value.trim().length > 0;
+}
+
+/** Where a winning gateway API key was observed. */
+export type GatewayCredentialSource = { kind: "env-file"; path: string } | { kind: "shell" };
+
+/**
+ * Everywhere the two gateway credentials can be observed. Callers fill in
+ * whatever their vantage point can see — env files on disk, the process
+ * environment, an SDK token lookup — and the resolver ranks it.
+ */
+export interface GatewayCredentialEvidence {
+ /** `AI_GATEWAY_API_KEY` found in an app env file (the file's name). */
+ readonly apiKeyFile?: string;
+ /** `AI_GATEWAY_API_KEY` present in the process environment. */
+ readonly apiKeyInEnv?: boolean;
+ /** `VERCEL_OIDC_TOKEN` found in an app env file (the file's name). */
+ readonly oidcFile?: string;
+ /** An OIDC token is otherwise available (env or linked-project lookup). */
+ readonly oidcAvailable?: boolean;
+}
+
+export type GatewayCredentialResolution =
+ | {
+ credential: "api-key";
+ /** Where the winning key lives; a shell export is not eve's to remove. */
+ source: GatewayCredentialSource;
+ /** Present when an OIDC token exists that the key shadows. */
+ shadowedOidc?: { file?: string };
+ }
+ | { credential: "oidc"; file?: string };
+
+/**
+ * THE one encoding of gateway credential precedence: `AI_GATEWAY_API_KEY`
+ * (env file first for attribution, then the shell) outranks the OIDC token,
+ * exactly as the AI SDK gateway provider resolves them. Every surface that
+ * reports or ranks gateway credentials — the endpoint status, the /model
+ * provider row, the link outcome, boot detection — must route through this
+ * function so they can never disagree.
+ */
+export function resolveGatewayCredential(
+ evidence: GatewayCredentialEvidence,
+): GatewayCredentialResolution | undefined {
+ const source: GatewayCredentialSource | undefined =
+ evidence.apiKeyFile !== undefined
+ ? { kind: "env-file", path: evidence.apiKeyFile }
+ : evidence.apiKeyInEnv === true
+ ? { kind: "shell" }
+ : undefined;
+ const hasOidc = evidence.oidcFile !== undefined || evidence.oidcAvailable === true;
+
+ if (source !== undefined) {
+ const resolution: GatewayCredentialResolution = { credential: "api-key", source };
+ if (hasOidc) {
+ resolution.shadowedOidc = evidence.oidcFile === undefined ? {} : { file: evidence.oidcFile };
+ }
+ return resolution;
+ }
+ if (hasOidc) {
+ return evidence.oidcFile === undefined
+ ? { credential: "oidc" }
+ : { credential: "oidc", file: evidence.oidcFile };
+ }
+ return undefined;
+}
+
/**
* Composes the build-time {@link ModelRouting} with runtime credential presence
* into the consumer-facing {@link ModelEndpointStatus}.
*
* Credentials matter only for gateway routing; an external endpoint makes no
- * connectedness claim. `api-key` outranks `oidc` to match the AI SDK gateway
- * provider, which uses `AI_GATEWAY_API_KEY` when present and otherwise the OIDC
- * token.
+ * connectedness claim. Ranking delegates to {@link resolveGatewayCredential}.
*/
export function resolveModelEndpointStatus(
routing: ModelRouting,
@@ -29,11 +95,12 @@ export function resolveModelEndpointStatus(
if (routing.kind === "external") {
return { kind: "external", provider: routing.provider };
}
- if (credentials.apiKey) {
- return { kind: "gateway", connected: true, credential: "api-key" };
- }
- if (credentials.oidc) {
- return { kind: "gateway", connected: true, credential: "oidc" };
+ const resolution = resolveGatewayCredential({
+ apiKeyInEnv: credentials.apiKey,
+ oidcAvailable: credentials.oidc,
+ });
+ if (resolution === undefined) {
+ return { kind: "gateway", connected: false };
}
- return { kind: "gateway", connected: false };
+ return { kind: "gateway", connected: true, credential: resolution.credential };
}
diff --git a/packages/eve/src/setup/flows/link.test.ts b/packages/eve/src/setup/flows/link.test.ts
index 24040b3d2..fb2742f96 100644
--- a/packages/eve/src/setup/flows/link.test.ts
+++ b/packages/eve/src/setup/flows/link.test.ts
@@ -1,6 +1,6 @@
import { stripVTControlCharacters } from "node:util";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
import type { ApplyAiGatewayCredentialDeps } from "#setup/boxes/apply-ai-gateway-credential.js";
@@ -84,7 +84,74 @@ function flowDeps(args: {
};
}
+beforeEach(() => {
+ // The flow reads the shell for a gateway key that would shadow the pulled
+ // OIDC token; a developer shell exporting one must not leak in.
+ vi.stubEnv("AI_GATEWAY_API_KEY", "");
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
describe("runLinkFlow", () => {
+ it("reports the gateway key as the active credential when it shadows the pulled OIDC token", async () => {
+ const { prompter } = createFakePrompter({
+ single: (opts) => {
+ if (stripVTControlCharacters(opts.message) === "Vercel project") return "new";
+ throw new Error(`Unexpected select: ${opts.message}`);
+ },
+ });
+ const deps = flowDeps({
+ envFilesByKey: { VERCEL_OIDC_TOKEN: ".env.local", AI_GATEWAY_API_KEY: ".env.local" },
+ });
+
+ const result = await runLinkFlow({
+ appRoot: APP_ROOT,
+ prompter,
+ deps,
+ projectSelection: "create-or-link",
+ });
+
+ // Runtime resolution ranks the key first; reporting OIDC here would
+ // claim a credential that never authenticates a call.
+ expect(result).toEqual({
+ kind: "done",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ shadowedOidc: { file: ".env.local" },
+ },
+ });
+ });
+
+ it("reports a shell-exported gateway key shadowing the pulled OIDC token", async () => {
+ vi.stubEnv("AI_GATEWAY_API_KEY", "vck_shell");
+ const { prompter } = createFakePrompter({
+ single: (opts) => {
+ if (stripVTControlCharacters(opts.message) === "Vercel project") return "new";
+ throw new Error(`Unexpected select: ${opts.message}`);
+ },
+ });
+ const deps = flowDeps({ envFilesByKey: { VERCEL_OIDC_TOKEN: ".env.local" } });
+
+ const result = await runLinkFlow({
+ appRoot: APP_ROOT,
+ prompter,
+ deps,
+ projectSelection: "create-or-link",
+ });
+
+ expect(result).toEqual({
+ kind: "done",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "shell" },
+ shadowedOidc: { file: ".env.local" },
+ },
+ });
+ });
+
it("shows the current link, then goes directly from team to the existing-project picker", async () => {
const { prompter, selectMessages } = createFakePrompter({
single: (opts) => {
@@ -104,7 +171,10 @@ describe("runLinkFlow", () => {
const result = await runLinkFlow({ appRoot: APP_ROOT, prompter, deps });
- expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });
+ expect(result).toEqual({
+ kind: "done",
+ resolution: { credential: "oidc", file: ".env.local" },
+ });
expect(selectMessages).toHaveLength(1);
expect(stripVTControlCharacters(selectMessages[0] ?? "")).toBe(
"This directory is already linked to\nweather-app in Acme",
@@ -148,7 +218,10 @@ describe("runLinkFlow", () => {
teamSelectMessage,
});
- expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });
+ expect(result).toEqual({
+ kind: "done",
+ resolution: { credential: "oidc", file: ".env.local" },
+ });
// The create path runs the new-project namer and never reaches the
// existing-project picker — the opposite of the existing-only default.
expect(deps.resolveProvisioning?.pickNewProjectName).toHaveBeenCalled();
diff --git a/packages/eve/src/setup/flows/link.ts b/packages/eve/src/setup/flows/link.ts
index 3db9afd63..bcfabbfa4 100644
--- a/packages/eve/src/setup/flows/link.ts
+++ b/packages/eve/src/setup/flows/link.ts
@@ -1,5 +1,10 @@
import { interactiveAsker, withAnswers } from "../ask.js";
import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
+import {
+ hasEnvValue,
+ resolveGatewayCredential,
+ type GatewayCredentialResolution,
+} from "#internal/resolve-model-endpoint-status.js";
import {
applyAiGatewayCredential,
type ApplyAiGatewayCredentialDeps,
@@ -24,6 +29,8 @@ import { inProjectSetupState, prompterSink } from "./in-project.js";
export interface LinkFlowDeps {
detectProjectIdentity: typeof detectProjectIdentity;
findEnvFileWithKey: typeof findEnvFileWithKey;
+ /** Shell environment probed for a gateway key that would shadow OIDC. */
+ env: Record<string, string | undefined>;
resolveProvisioning?: ResolveProvisioningDeps;
linkProject?: LinkProjectDeps;
applyAiGatewayCredential?: ApplyAiGatewayCredentialDeps;
@@ -32,8 +39,12 @@ export interface LinkFlowDeps {
export type LinkFlowResult =
| {
kind: "done";
- /** The model credential verified in an env file, when one landed. */
- credential?: "VERCEL_OIDC_TOKEN" | typeof AI_GATEWAY_API_KEY_ENV_VAR;
+ /**
+ * The credential the runtime will actually resolve, from the one
+ * precedence authority ({@link resolveGatewayCredential}): a gateway
+ * API key — env file or shell — outranks the pulled OIDC token.
+ */
+ resolution?: GatewayCredentialResolution;
}
| { kind: "cancelled" };
@@ -53,6 +64,10 @@ export type LinkFlowResult =
* Ends by verifying a model credential actually landed (`VERCEL_OIDC_TOKEN`
* or `AI_GATEWAY_API_KEY` in an env file) — an env pull can succeed without
* granting gateway access, and the difference is what the user acts on next.
+ * The reported credential mirrors runtime resolution — `AI_GATEWAY_API_KEY`
+ * (env file or shell) outranks the OIDC token, exactly as the AI SDK gateway
+ * provider resolves it — so the outcome message, the status bar, and the
+ * actual authentication can never disagree.
*/
export async function runLinkFlow(input: {
appRoot: string;
@@ -71,6 +86,7 @@ export async function runLinkFlow(input: {
const deps: LinkFlowDeps = {
detectProjectIdentity,
findEnvFileWithKey,
+ env: process.env,
...input.deps,
};
@@ -168,7 +184,17 @@ export async function runLinkFlow(input: {
);
}
const done: LinkFlowResult = { kind: "done" };
- if (oidcFile !== undefined) done.credential = "VERCEL_OIDC_TOKEN";
- else if (gatewayKeyFile !== undefined) done.credential = AI_GATEWAY_API_KEY_ENV_VAR;
+ // The link provisioned OIDC, but reporting it while a key shadows it
+ // would claim a credential that never authenticates a call — the one
+ // precedence authority decides what actually won.
+ const evidence: {
+ apiKeyInEnv: boolean;
+ apiKeyFile?: string;
+ oidcFile?: string;
+ } = { apiKeyInEnv: hasEnvValue(deps.env[AI_GATEWAY_API_KEY_ENV_VAR]) };
+ if (gatewayKeyFile !== undefined) evidence.apiKeyFile = gatewayKeyFile;
+ if (oidcFile !== undefined) evidence.oidcFile = oidcFile;
+ const resolution = resolveGatewayCredential(evidence);
+ if (resolution !== undefined) done.resolution = resolution;
return done;
}
diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.ts
index 61fba624d..df4b90939 100644
--- a/packages/eve/src/setup/flows/model.test.ts
+++ b/packages/eve/src/setup/flows/model.test.ts
@@ -287,7 +287,11 @@ describe("runModelFlow", () => {
}),
detectProviderStatus: vi.fn(
async () =>
- ({ kind: "gateway-key", envKey: "AI_GATEWAY_API_KEY", envFile: ".env.local" }) as const,
+ ({
+ kind: "gateway-key",
+ envKey: "AI_GATEWAY_API_KEY",
+ source: { kind: "env-file", path: ".env.local" },
+ }) as const,
),
});
@@ -338,7 +342,7 @@ describe("runModelFlow", () => {
({
kind: "gateway-key",
envKey: "AI_GATEWAY_API_KEY",
- envFile: ".env.local",
+ source: { kind: "env-file", path: ".env.local" },
}) as const,
),
});
@@ -517,14 +521,24 @@ describe("runModelFlow", () => {
.mockResolvedValueOnce({ kind: "unset" })
.mockResolvedValueOnce({ kind: "gateway-project", projectName: "my-agent" });
const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(
- async () => ({ kind: "done", credential: "AI_GATEWAY_API_KEY" }) as const,
+ async () =>
+ ({
+ kind: "done",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ },
+ }) as const,
);
const deps = flowDeps({ detectProviderStatus, runProviderFlow });
await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
kind: "done",
providerOutcome: {
- credential: "AI_GATEWAY_API_KEY",
+ resolution: {
+ credential: "api-key",
+ source: { kind: "env-file", path: ".env.local" },
+ },
status: { kind: "gateway-project", projectName: "my-agent" },
},
});
@@ -540,7 +554,8 @@ describe("runModelFlow", () => {
it("honors confirmed provider entry when link metadata looks configured", async () => {
const { prompter, menuPaints } = scriptedPrompter({ menu: [] });
const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(
- async () => ({ kind: "done", credential: "VERCEL_OIDC_TOKEN" }) as const,
+ async () =>
+ ({ kind: "done", resolution: { credential: "oidc", file: ".env.local" } }) as const,
);
const deps = flowDeps({ runProviderFlow });
@@ -554,7 +569,7 @@ describe("runModelFlow", () => {
).resolves.toEqual({
kind: "done",
providerOutcome: {
- credential: "VERCEL_OIDC_TOKEN",
+ resolution: { credential: "oidc", file: ".env.local" },
status: { kind: "gateway-project", projectName: "my-agent" },
},
});
@@ -572,11 +587,14 @@ describe("runModelFlow", () => {
.mockResolvedValueOnce({
kind: "gateway-key",
envKey: "AI_GATEWAY_API_KEY",
- envFile: ".env.local",
+ source: { kind: "env-file", path: ".env.local" },
});
const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => {
controller.abort();
- return { kind: "done", credential: "AI_GATEWAY_API_KEY" };
+ return {
+ kind: "done",
+ resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },
+ };
});
const deps = flowDeps({ detectProviderStatus, runProviderFlow });
@@ -591,11 +609,11 @@ describe("runModelFlow", () => {
).resolves.toEqual({
kind: "done",
providerOutcome: {
- credential: "AI_GATEWAY_API_KEY",
+ resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },
status: {
kind: "gateway-key",
envKey: "AI_GATEWAY_API_KEY",
- envFile: ".env.local",
+ source: { kind: "env-file", path: ".env.local" },
},
},
});
diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.ts
index 4b9bc7a82..5860f2b87 100644
--- a/packages/eve/src/setup/flows/model.ts
+++ b/packages/eve/src/setup/flows/model.ts
@@ -1,3 +1,9 @@
+import {
+ hasEnvValue,
+ resolveGatewayCredential,
+ type GatewayCredentialResolution,
+} from "#internal/resolve-model-endpoint-status.js";
+
import { inspectApplication } from "#services/inspect-application.js";
import type {
AgentModelSettingsPatch,
@@ -126,7 +132,8 @@ export type { ModelProviderStatus };
* disk — so it never surfaces as an outcome.
*/
export interface ModelProviderOutcome {
- credential?: "VERCEL_OIDC_TOKEN" | typeof AI_GATEWAY_API_KEY_ENV_VAR;
+ /** The credential resolution the runtime will honor; see {@link LinkFlowResult}. */
+ resolution?: GatewayCredentialResolution;
status: ModelProviderStatus;
}
@@ -166,7 +173,8 @@ function providerStatusHint(
: `${emphasis(provider.projectName)} in ${emphasis(provider.teamName)}`;
return `AI Gateway (Linked to ${where})`;
}
- return `AI Gateway (${provider.envKey} in ${provider.envFile})`;
+ const where = provider.source.kind === "shell" ? "your shell" : provider.source.path;
+ return `AI Gateway (${provider.envKey} in ${where})`;
}
/**
@@ -283,6 +291,7 @@ function modelMenuRows(
export async function detectModelProviderStatus(
appRoot: string,
options: VercelProjectOperationOptions = {},
+ env: Record<string, string | undefined> = process.env,
): Promise<ModelProviderStatus> {
const [identity, gatewayKeyFile, oidcFile] = await Promise.all([
detectProjectIdentity(appRoot, options),
@@ -297,13 +306,22 @@ export async function detectModelProviderStatus(
if (identity.teamName !== undefined) status.teamName = identity.teamName;
return status;
}
- if (gatewayKeyFile !== undefined) {
- return { kind: "gateway-key", envKey: AI_GATEWAY_API_KEY_ENV_VAR, envFile: gatewayKeyFile };
- }
- if (oidcFile !== undefined) {
- return { kind: "gateway-key", envKey: "VERCEL_OIDC_TOKEN", envFile: oidcFile };
+ const evidence: { apiKeyInEnv: boolean; apiKeyFile?: string; oidcFile?: string } = {
+ apiKeyInEnv: hasEnvValue(env[AI_GATEWAY_API_KEY_ENV_VAR]),
+ };
+ if (gatewayKeyFile !== undefined) evidence.apiKeyFile = gatewayKeyFile;
+ if (oidcFile !== undefined) evidence.oidcFile = oidcFile;
+ const resolution = resolveGatewayCredential(evidence);
+ if (resolution === undefined) return { kind: "unset" };
+ if (resolution.credential === "api-key") {
+ return { kind: "gateway-key", envKey: AI_GATEWAY_API_KEY_ENV_VAR, source: resolution.source };
}
- return { kind: "unset" };
+ return {
+ kind: "gateway-key",
+ envKey: "VERCEL_OIDC_TOKEN",
+ // The resolver only reports an OIDC file we handed it, so it is set here.
+ source: { kind: "env-file", path: resolution.file! },
+ };
}
/**
@@ -497,7 +515,9 @@ export async function runModelFlow(input: {
// TUI can refresh the state that is already on disk.
provider = await withSpinner(prompter, "Checking the project…", () => detectProvider(false));
providerOutcome = { status: provider };
- if (result.credential !== undefined) providerOutcome.credential = result.credential;
+ if (result.kind === "done" && result.resolution !== undefined) {
+ providerOutcome.resolution = result.resolution;
+ }
commitDraft = true;
break;
}
diff --git a/packages/eve/src/setup/flows/provider.test.ts b/packages/eve/src/setup/flows/provider.test.ts
index 0fbac32f0..9ef703478 100644
--- a/packages/eve/src/setup/flows/provider.test.ts
+++ b/packages/eve/src/setup/flows/provider.test.ts
@@ -20,7 +20,7 @@ function createDeps() {
getVercelAuthStatus: vi.fn(async (): Promise<VercelAuthStatus> => "authenticated"),
runLinkFlow: vi.fn<ProviderFlowDeps["runLinkFlow"]>(async () => ({
kind: "done",
- credential: "VERCEL_OIDC_TOKEN",
+ resolution: { credential: "oidc", file: ".env.local" },
})),
appendEnv: vi.fn<ProviderFlowDeps["appendEnv"]>(async () => ({
written: ["AI_GATEWAY_API_KEY"],
@@ -54,7 +54,10 @@ describe("runProviderFlow", () => {
deps,
});
- expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });
+ expect(result).toEqual({
+ kind: "done",
+ resolution: { credential: "oidc", file: ".env.local" },
+ });
expect(deps.runLinkFlow).toHaveBeenCalledExactlyOnceWith({
appRoot: APP_ROOT,
prompter: fake.prompter,
@@ -103,7 +106,7 @@ describe("runProviderFlow", () => {
currentProvider: {
kind: "gateway-key",
envKey: "AI_GATEWAY_API_KEY",
- envFile: ".env.local",
+ source: { kind: "env-file", path: ".env.local" },
},
deps,
});
@@ -140,7 +143,10 @@ describe("runProviderFlow", () => {
deps,
});
- expect(result).toEqual({ kind: "done", credential: "AI_GATEWAY_API_KEY" });
+ expect(result).toEqual({
+ kind: "done",
+ resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },
+ });
expect(deps.validateGatewayApiKey).toHaveBeenCalledExactlyOnceWith(
"sk-inline",
expect.any(AbortSignal),
@@ -182,7 +188,7 @@ describe("runProviderFlow", () => {
await expect(execution).resolves.toEqual({
kind: "done",
- credential: "AI_GATEWAY_API_KEY",
+ resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },
});
});
diff --git a/packages/eve/src/setup/flows/provider.ts b/packages/eve/src/setup/flows/provider.ts
index ee2483a28..c6b310f2f 100644
--- a/packages/eve/src/setup/flows/provider.ts
+++ b/packages/eve/src/setup/flows/provider.ts
@@ -16,6 +16,8 @@ import {
} from "../vercel-project.js";
import { withSpinner } from "../with-spinner.js";
+import type { GatewayCredentialSource } from "#internal/resolve-model-endpoint-status.js";
+
import { runLinkFlow, type LinkFlowResult } from "./link.js";
export type ProviderConnection = "project" | "own-key" | "external";
@@ -32,7 +34,8 @@ export type ModelProviderStatus =
| {
kind: "gateway-key";
envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR | "VERCEL_OIDC_TOKEN";
- envFile: string;
+ /** Where the credential lives — an env file, or the shell for a key. */
+ source: GatewayCredentialSource;
};
export const PROVIDER_QUESTION = "Which model provider do you want to use?";
@@ -118,7 +121,8 @@ function providerOptions(
hint: "⎿ type your key",
};
if (current?.kind === "gateway-key") {
- ownKey = { ...ownKey, checked: true, hint: `${current.envKey} set in ${current.envFile}` };
+ const where = current.source.kind === "shell" ? "your shell" : current.source.path;
+ ownKey = { ...ownKey, checked: true, hint: `${current.envKey} set in ${where}` };
}
return [
@@ -258,5 +262,8 @@ export async function runProviderFlow(input: {
// remaining UI, but the caller must still refresh model access for the key
// that is now on disk.
prompter.log.success(`${location.envKey} set.`);
- return { kind: "done", credential: location.envKey };
+ return {
+ kind: "done",
+ resolution: { credential: "api-key", source: { kind: "env-file", path: location.envFile } },
+ };
}
diff --git a/packages/eve/test/tui-client/target/local-environment.ts b/packages/eve/test/tui-client/target/local-environment.ts
index 90a6a3552..ab7f1459f 100644
--- a/packages/eve/test/tui-client/target/local-environment.ts
+++ b/packages/eve/test/tui-client/target/local-environment.ts
@@ -1,4 +1,5 @@
import { mkdtemp, rm } from "node:fs/promises";
+import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -14,6 +15,23 @@ import type {
const DEFAULT_LOCAL_TARGET_PORT = Number(process.env.PORT ?? 3000);
+/**
+ * True when nothing on this machine already listens on the port. Default
+ * allocation must skip a developer's own `eve dev` (or anything else) parked
+ * on 3000 — the harness would otherwise probe the foreign server, see the
+ * wrong agent name, and fail the whole smoke run.
+ */
+function portIsFree(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const probe = createServer();
+ probe.unref();
+ probe.once("error", () => resolve(false));
+ probe.listen({ host: "127.0.0.1", port }, () => {
+ probe.close(() => resolve(true));
+ });
+ });
+}
+
interface LocalTargetRecord {
readonly startEnvKey: string;
readonly target: TestTarget;
@@ -50,7 +68,7 @@ export function createLocalTestEnvironment(
}
const targetId = `${input.kind}:${input.app}`;
- const port = input.port ?? resolveDefaultPort({ defaultPortByTarget, targetId });
+ const port = input.port ?? (await resolveDefaultPort({ defaultPortByTarget, targetId }));
if (input.port === undefined && port === nextPort) {
nextPort += 1;
}
@@ -148,14 +166,14 @@ export function createLocalTestEnvironment(
},
};
- function resolveDefaultPort(input: {
+ async function resolveDefaultPort(input: {
readonly defaultPortByTarget: Map<string, number>;
readonly targetId: string;
- }): number {
+ }): Promise<number> {
const existingPort = input.defaultPortByTarget.get(input.targetId);
if (existingPort !== undefined) return existingPort;
- while (portOwners.has(nextPort)) {
+ while (portOwners.has(nextPort) || !(await portIsFree(nextPort))) {
nextPort += 1;
}
diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.ts
index 44693a5d1..635da139e 100644
--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts
+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts
@@ -210,7 +210,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// ---- Turn 1: stub-mcp, ends in `authorized` ----
@@ -315,7 +315,7 @@ void (async () => {
// The turn is complete; wait until the runner is back at the prompt so
// Ctrl+C exits the session. A Ctrl+C mid-stream now only interrupts the
// turn and returns to the prompt (Claude Code's two-step exit).
- await screen.waitForText("❯", 10_000);
+ await screen.waitForIdlePrompt(10_000);
input.ctrlC();
await runPromise;
} catch (error) {
diff --git a/packages/eve/test/tui-client/tui-log-modes.ts b/packages/eve/test/tui-client/tui-log-modes.ts
index 3161e2318..bd314b6c6 100644
--- a/packages/eve/test/tui-client/tui-log-modes.ts
+++ b/packages/eve/test/tui-client/tui-log-modes.ts
@@ -47,7 +47,7 @@ async function snapshotForMode(mode: "all" | "stderr" | "sandbox" | "none"): Pro
throw error;
});
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Foreign writes are captured synchronously, so the snapshot reflects
// them immediately.
diff --git a/packages/eve/test/tui-client/tui-loglevel.ts b/packages/eve/test/tui-client/tui-loglevel.ts
index 3aee7be07..1bccfd4c4 100644
--- a/packages/eve/test/tui-client/tui-loglevel.ts
+++ b/packages/eve/test/tui-client/tui-loglevel.ts
@@ -15,8 +15,9 @@ import { theme } from "./lib/theme.ts";
*
* - `/loglevel none` hides log lines already in the transcript
* - lines captured while hidden stay buffered, invisible
- * - `/loglevel all` restores every buffered line at its original
- * chronological position
+ * - `/loglevel all` restores the streams: each source renders one
+ * section showing its NEWEST write, with earlier writes behind an
+ * `… (N more)` count (the diagnostics file carries the history)
*
* Needs no agent server and no model credentials.
*/
@@ -47,7 +48,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Foreign writes are captured synchronously, so snapshots reflect them
// immediately.
@@ -78,20 +79,13 @@ void (async () => {
await screen.waitForText("Showing all logs", 5_000);
const restored = screen.snapshot();
- const positions = [
- restored.indexOf(VISIBLE_STDOUT_MARK),
- restored.indexOf(VISIBLE_STDERR_MARK),
- restored.indexOf("Logs hidden"),
- restored.indexOf(HIDDEN_STDOUT_MARK),
- ];
- if (positions.some((index) => index === -1)) {
- throw new Error(`/loglevel all should restore every buffered line:\n${restored}`);
+ // The stdout section shows only its newest write (the one captured
+ // while hidden); the earlier mark sits behind the elided count.
+ if (!restored.includes(HIDDEN_STDOUT_MARK) || !restored.includes(VISIBLE_STDERR_MARK)) {
+ throw new Error(`/loglevel all should restore each stream's newest write:\n${restored}`);
}
- const ordered = positions.every((index, i) => i === 0 || index > positions[i - 1]!);
- if (!ordered) {
- throw new Error(
- `restored logs should keep their original chronological order (${positions.join(", ")}):\n${restored}`,
- );
+ if (restored.includes(VISIBLE_STDOUT_MARK) || !restored.includes("(1 more)")) {
+ throw new Error(`earlier writes should collapse behind the elided count:\n${restored}`);
}
input.type("/exit");
@@ -99,7 +93,7 @@ void (async () => {
await runPromise;
process.stdout.write(
- `${theme.muted("[tui-loglevel] buffered hide/restore with stable ordering verified")}\n`,
+ `${theme.muted("[tui-loglevel] buffered hide/restore with newest-write sections verified")}\n`,
);
} catch (error) {
process.stdout.write(
diff --git a/packages/eve/test/tui-client/tui-packed-install-model.ts b/packages/eve/test/tui-client/tui-packed-install-model.ts
index 70310a608..e0d88ae03 100644
--- a/packages/eve/test/tui-client/tui-packed-install-model.ts
+++ b/packages/eve/test/tui-client/tui-packed-install-model.ts
@@ -37,6 +37,7 @@ interface PackedTuiHarness {
EveTUIRunner: new (options: Record<string, unknown>) => { run(): Promise<void> };
MockScreen: new (size: { columns: number; rows: number }) => {
waitForText(text: string, timeoutMs: number): Promise<unknown>;
+ waitForIdlePrompt(timeoutMs: number): Promise<unknown>;
snapshot(): string;
};
MockUserInput: new () => {
@@ -143,7 +144,7 @@ void (async () => {
await screen.waitForText("Change model", 5_000);
input.send("\x1b");
await screen.waitForText("/model dismissed.", 5_000);
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("/exit");
input.enter();
diff --git a/packages/eve/test/tui-client/tui-questions-freeform.ts b/packages/eve/test/tui-client/tui-questions-freeform.ts
index 147d50adf..1e3c93af7 100644
--- a/packages/eve/test/tui-client/tui-questions-freeform.ts
+++ b/packages/eve/test/tui-client/tui-questions-freeform.ts
@@ -38,7 +38,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
throw error;
});
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
const promptLines = [
"Use the ask_question tool exactly once to ask me to choose an environment.",
@@ -53,7 +53,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.type(promptLines.join(" · "));
input.enter();
- await screen.waitForText("▶ Production", 60_000);
+ await screen.waitForText("▶ 1. Production", 60_000);
console.log(theme.muted("[tui-freeform] select UI live, highlight on Production"));
await sleep(500);
@@ -62,26 +62,24 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.emit("data", Buffer.from("\x1B[B")); // → Staging
input.emit("data", Buffer.from("\x1B[B")); // → Preview
input.emit("data", Buffer.from("\x1B[B")); // → Type your own answer
- await screen.waitForText("▶ Type your own answer", 2_000);
+ await screen.waitForText("▶ 4. Type your own answer", 2_000);
console.log(theme.muted("[tui-freeform] highlight moved to freeform row"));
- // Enter on the freeform row activates text mode. Text mode clears the
- // status hints, so the proof it is active is the typed text rendering
- // in the input row before we submit it.
- input.enter();
+ // The freeform row focuses its inline elbow editor the moment the cursor
+ // reaches it — typing lands there directly, no Enter required.
input.type(FREEFORM_ANSWER);
await screen.waitForText(FREEFORM_ANSWER, 2_000);
- console.log(theme.muted("[tui-freeform] text mode active, answer typed"));
+ console.log(theme.muted("[tui-freeform] inline editor active, answer typed"));
input.enter();
- await screen.waitForText(`✓ ${FREEFORM_ANSWER}`, 5_000);
+ await screen.waitForText(`⎿ ${FREEFORM_ANSWER}`, 5_000);
console.log(theme.muted("[tui-freeform] freeform answer recorded in body"));
// The follow-up assistant turn renders a `▲`-prefixed section below
// the answered question that echoes the freeform text.
await waitForCondition(
- () => assistantReplyAfter(screen.snapshot(), `✓ ${FREEFORM_ANSWER}`, FREEFORM_ANSWER),
+ () => assistantReplyAfter(screen.snapshot(), `⎿ ${FREEFORM_ANSWER}`, FREEFORM_ANSWER),
{
timeoutMs: 60_000,
label: "follow-up assistant section echoing the freeform answer",
@@ -102,7 +100,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
// The turn is complete; wait until the runner is back at the prompt so
// Ctrl+C exits the session. A Ctrl+C mid-stream now only interrupts the
// turn and returns to the prompt (Claude Code's two-step exit).
- await screen.waitForText("❯", 30_000);
+ await screen.waitForIdlePrompt(30_000);
input.ctrlC();
await runPromise;
});
diff --git a/packages/eve/test/tui-client/tui-questions.ts b/packages/eve/test/tui-client/tui-questions.ts
index bcddcd42c..40848792b 100644
--- a/packages/eve/test/tui-client/tui-questions.ts
+++ b/packages/eve/test/tui-client/tui-questions.ts
@@ -18,10 +18,10 @@ import { theme } from "./lib/theme.ts";
* 2. Boot an `EveTUIRunner` with a mock terminal.
* 3. Type a prompt that asks the model to call `ask_question` with
* two options (red/blue).
- * 4. Wait for the question section to display the select indicator
- * (`▶ <label>`), which proves the dedicated question UI is up.
+ * 4. Wait for the question overlay to display the numbered select
+ * indicator (`▶ 1. <label>`), which proves the question UI is up.
* 5. Send Down arrow + Enter to pick the second option (blue).
- * 6. Wait for the answered marker in the body section.
+ * 6. Wait for the answered marker (`⎿ <label>`) in the transcript.
* 7. Wait for the post-answer assistant turn to render. The runner
* only returns to its prompt-reading state if the chosen option
* flowed through to the agent and resolved the pending input.
@@ -50,7 +50,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
throw error;
});
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
const promptLines = [
"Use the ask_question tool exactly once to ask me which color I prefer.",
@@ -63,7 +63,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.type(promptLines.join(" · "));
input.enter();
- await screen.waitForText("▶ Red", 60_000);
+ await screen.waitForText("▶ 1. Red", 60_000);
console.log(theme.muted("[tui-questions] select UI is live, highlight on Red"));
// Bridges a server-side race where the park hook isn't yet
@@ -73,22 +73,22 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
await sleep(500);
input.emit("data", Buffer.from("\x1B[B"));
- await screen.waitForText("▶ Blue", 2_000);
+ await screen.waitForText("▶ 2. Blue", 2_000);
console.log(theme.muted("[tui-questions] highlight moved to Blue"));
input.enter();
- await screen.waitForText("✓ Blue", 5_000);
+ await screen.waitForText("⎿ Blue", 5_000);
console.log(theme.muted("[tui-questions] answer recorded in body"));
// The post-answer turn must produce a `▲`-prefixed assistant
// section whose body contains "blue", proof that the chosen
// optionId flowed through to the agent and the model produced a
// reply reflecting the choice. We only search the region after the
- // "✓ Blue" answer marker to avoid a false positive from the marker
+ // "⎿ Blue" answer marker to avoid a false positive from the marker
// itself (transcript blocks commit in order, so the follow-up reply
// always renders below the answered question).
- await waitForCondition(() => assistantReplyAfter(screen.snapshot(), "✓ Blue", "blue"), {
+ await waitForCondition(() => assistantReplyAfter(screen.snapshot(), "⎿ Blue", "blue"), {
timeoutMs: 60_000,
label: "follow-up assistant section mentioning blue",
});
@@ -102,7 +102,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
// The turn is complete; wait until the runner is back at the prompt so
// Ctrl+C exits the session. A Ctrl+C mid-stream now only interrupts the
// turn and returns to the prompt (Claude Code's two-step exit).
- await screen.waitForText("❯", 30_000);
+ await screen.waitForIdlePrompt(30_000);
input.ctrlC();
await runPromise;
});
diff --git a/packages/eve/test/tui-client/tui-rebuild-status.ts b/packages/eve/test/tui-client/tui-rebuild-status.ts
index dd4766b01..df9c5bd55 100644
--- a/packages/eve/test/tui-client/tui-rebuild-status.ts
+++ b/packages/eve/test/tui-client/tui-rebuild-status.ts
@@ -47,7 +47,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Two full rebuild cycles, producer-authentic lines. Foreign writes are
// captured synchronously, so snapshots reflect them immediately.
diff --git a/packages/eve/test/tui-client/tui-server-logs.ts b/packages/eve/test/tui-client/tui-server-logs.ts
index 6feba9926..0b1fee57a 100644
--- a/packages/eve/test/tui-client/tui-server-logs.ts
+++ b/packages/eve/test/tui-client/tui-server-logs.ts
@@ -42,7 +42,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Submit a prompt, then emit a foreign stderr write before the turn
// renders, the order the in-process server produces it in.
@@ -50,12 +50,16 @@ void (async () => {
input.enter();
console.warn(WARNING);
- await screen.waitForText("stderr ·", 5_000);
+ await screen.waitForText("○ stderr", 5_000);
await screen.waitForText(WARNING, 5_000);
- // The warning must live inside the server-log lane, not shred the prompt.
+ // The warning must ride the section's rail, not shred the prompt.
const snapshot = screen.snapshot();
- if (!snapshot.split("\n").some((line) => line.includes(WARNING) && line.includes("stderr ·"))) {
+ if (
+ !snapshot
+ .split("\n")
+ .some((line) => line.includes(WARNING) && line.trimStart().startsWith("│"))
+ ) {
throw new Error(`warning was not rendered in the server-log lane:\n${snapshot}`);
}
@@ -70,7 +74,7 @@ void (async () => {
);
}
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("/exit");
input.enter();
await runPromise;
diff --git a/packages/eve/test/tui-client/tui-slash-commands.ts b/packages/eve/test/tui-client/tui-slash-commands.ts
index 2c1d6e4f2..6e682de6a 100644
--- a/packages/eve/test/tui-client/tui-slash-commands.ts
+++ b/packages/eve/test/tui-client/tui-slash-commands.ts
@@ -58,7 +58,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("boom");
input.enter();
@@ -67,10 +67,10 @@ void (async () => {
// Wait until `readPrompt` is active again so the next keystrokes
// aren't dropped in the gap between turns.
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("/new");
input.enter();
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
if (screen.snapshot().includes("Error")) {
throw new Error(`/new did not clear the transcript:\n${screen.snapshot()}`);
}
@@ -82,7 +82,7 @@ void (async () => {
await screen.waitForText("/deploy needs eve dev running the local server", 5_000);
console.log(theme.muted("[tui-slash-commands] /deploy rendered the local-only notice"));
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("/exit");
input.enter();
@@ -129,13 +129,13 @@ async function runLocalChannelsCancellation(): Promise<void> {
"utf8",
);
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("/channels");
input.enter();
await screen.waitForText("Where will you chat with your agent?", 10_000);
input.send("\x1b");
await screen.waitForText("/channels dismissed.", 5_000);
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
console.log(theme.muted("[tui-slash-commands] local /channels cancelled back to prompt"));
input.type("/exit");
diff --git a/packages/eve/test/tui-client/tui-status-line.ts b/packages/eve/test/tui-client/tui-status-line.ts
index d7b64319b..1641d847a 100644
--- a/packages/eve/test/tui-client/tui-status-line.ts
+++ b/packages/eve/test/tui-client/tui-status-line.ts
@@ -18,7 +18,8 @@ import { theme } from "./lib/theme.ts";
* 4. An unlinked directory renders no Vercel segment at all.
*
* The linked project identity is no longer a standalone status-line segment;
- * it folds into the model-endpoint segment (`AI Gateway (project)`), which only
+ * it folds into the model-endpoint segment (`via ai-gateway(oidc:project)`),
+ * which only
* renders for a reachable server that reports a gateway-routed model on
* `/eve/v1/info`. That path is covered by the unit tests in `status-line.test.ts`
* and the server-backed evals — not here, where the host is unreachable.
@@ -62,7 +63,7 @@ async function runPendingDeployCycle(): Promise<void> {
const runPromise = runner.run();
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
await screen.waitForText(` :${new URL(UNREACHABLE_HOST).port} `, 5_000);
console.log(theme.muted("[tui-status-line] local loopback badge rendered"));
@@ -74,7 +75,7 @@ async function runPendingDeployCycle(): Promise<void> {
input.type("/new");
input.enter();
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
if (!screen.snapshot().includes("deploy pending")) {
throw new Error(`/new dropped the pending-deploy flag:\n${screen.snapshot()}`);
}
@@ -120,12 +121,12 @@ async function runUnlinkedShowsNoVercelSegment(): Promise<void> {
const runPromise = runner.run();
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Allow the unlinked probe to land and repaint before judging the footer.
await new Promise((resolve) => setTimeout(resolve, 300));
const lines = screen.snapshot().split("\n");
- const promptRow = lines.findLastIndex((line) => line.includes("❯"));
+ const promptRow = lines.findLastIndex((line) => line.includes("›"));
const footer = lines.slice(promptRow + 1).join("\n");
if (footer.includes("▲")) {
throw new Error(`unlinked footer rendered a Vercel segment:\n${screen.snapshot()}`);
diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.ts
index 1c0af8597..f3561dc4a 100644
--- a/packages/eve/test/tui-client/tui-subagents-weather.ts
+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts
@@ -17,14 +17,16 @@ import { theme } from "./lib/theme.ts";
* landing under `stepIndex: 0` and collapsing into one box.
*
* Pass conditions:
- * 1. A `◆ stock-price subagent` region header exists.
+ * 1. A `※ subagent(stock-price…)` region header exists.
* 2. The child's `get_stock_price` tool row renders nested inside the
* subagent's `│` rule gutter (proves the child tool surfaces under
* the subagent flow).
* 3. NO parent-level `get_stock_price` tool row exists (proves the
* parent-tool suppression for child tool calls removes the stale
* block, not just blocks future renders).
- * 4. The price (178.92) appears inside the nested subagent region.
+ * 4. The price (178.92) appears inside the nested subagent region —
+ * or the section already settled to its `└ Done` footnote (a
+ * completed subagent collapses, so nested rows are transient).
* 5. The parent's final assistant reply (a top-level `▲` section)
* also contains the price.
*/
@@ -61,7 +63,7 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
throw error;
});
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
// Delegate explicitly. An implicit prompt ("what is the value of GOOG?")
// leaves the choice to the model, which may answer directly instead of
@@ -73,7 +75,7 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
input.enter();
// The subagent region header should appear once the parent delegates.
- await waitForCondition(() => screen.snapshot().includes("stock-price subagent"), {
+ await waitForCondition(() => screen.snapshot().includes("※ subagent(stock-price"), {
timeoutMs: 120_000,
label: "subagent region header",
onTimeout: () => screen.snapshot(),
@@ -105,29 +107,49 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
});
console.log(theme.muted(`[tui-weather] price ${PRICE} landed in body`));
- // The child's tool row renders nested inside the subagent's `│`
- // rule gutter — the line carries both the rule glyph and the tool name.
- await waitForCondition(() => /│.*get_stock_price/u.test(screen.snapshot()), {
- timeoutMs: 60_000,
- label: "nested subagent tool row",
- });
- console.log(theme.muted("[tui-weather] nested subagent tool row rendered"));
+ // The child's tool row renders nested inside the subagent's `│` rule
+ // gutter — unless the section already settled and collapsed past it.
+ await waitForCondition(
+ () =>
+ /│.*get_stock_price/u.test(screen.snapshot()) ||
+ screen
+ .snapshot()
+ .split("\n")
+ .some((line) => line.includes("└") && line.includes("Done")),
+ {
+ timeoutMs: 60_000,
+ label: "nested subagent tool row (or the section settled)",
+ onTimeout: () => screen.snapshot(),
+ },
+ );
+ console.log(theme.muted("[tui-weather] nested subagent tool row rendered (or settled)"));
- // The price must render inside the nested subagent region (tool result
- // or post-tool message), proving child output reaches the parent TUI.
+ // The price renders inside the nested subagent region (tool result or
+ // post-tool message) while the child is still live — but a settled child
+ // collapses its section to the `└ Done…` footnote, so losing that race
+ // must not fail the smoke. Child-side delivery was already proven by the
+ // body wait above; the parent-echo wait below proves the full round trip.
await waitForCondition(
() =>
screen
.snapshot()
.split("\n")
- .some((line) => line.includes("│") && line.includes(PRICE)),
+ .some(
+ // The nested price row can carry either rail glyph — the `└`
+ // corner when it is the section's last row (the rail closes on
+ // the newest child), `│` otherwise — and a fully settled
+ // section shows the `└ Done…` footnote instead.
+ (line) =>
+ ((line.includes("│") || line.includes("└")) && line.includes(PRICE)) ||
+ (line.includes("└") && line.includes("Done")),
+ ),
{
timeoutMs: 120_000,
- label: `price ${PRICE} inside the nested subagent region`,
+ label: `price ${PRICE} inside the nested subagent region (or the section settled)`,
onTimeout: () => screen.snapshot(),
},
);
- console.log(theme.muted("[tui-weather] price rendered inside the subagent region"));
+ console.log(theme.muted("[tui-weather] subagent region carried the price or settled to Done"));
// Wait for the parent's follow-up assistant section (top-level `▲`
// prose, not nested under the rule gutter) to echo the price.
@@ -140,11 +162,11 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
const finalSnapshot = screen.snapshot();
// No parent-level tool row for the child's call should remain: a tool
- // row at the parent level starts with a status glyph at column 0
- // (e.g. `✓ get_stock_price`), while the legitimate one is prefixed by
- // the subagent's `│` rule. Assistant prose lines start with `▲ ` or
- // indentation, so they cannot false-positive here.
- const parentToolRowRegex = /^[^\s│▲▌] get_stock_price/mu;
+ // row at the parent level is a status glyph in the indented header cell
+ // (e.g. ` ▪ get_stock_price`), while the legitimate one is prefixed by
+ // the subagent's `│` rule. Assistant prose lines start with `▲ `, so
+ // they cannot false-positive here.
+ const parentToolRowRegex = /^ {0,2}[^\s│▲] get_stock_price/mu;
if (parentToolRowRegex.test(finalSnapshot)) {
throw new Error(
`Final screen still contains a parent-level tool row for the child's get_stock_price call. The nested subagent region should be the only place it appears.\n\n${finalSnapshot}`,
@@ -159,7 +181,7 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
// The turn is complete; wait until the runner is back at the prompt so
// Ctrl+C exits the session. A Ctrl+C mid-stream now only interrupts the
// turn and returns to the prompt (Claude Code's two-step exit).
- await screen.waitForText("❯", 30_000);
+ await screen.waitForIdlePrompt(30_000);
input.ctrlC();
await runPromise;
});
diff --git a/packages/eve/test/tui-client/tui-subagents.ts b/packages/eve/test/tui-client/tui-subagents.ts
index 002831e67..ae7075dcc 100644
--- a/packages/eve/test/tui-client/tui-subagents.ts
+++ b/packages/eve/test/tui-client/tui-subagents.ts
@@ -23,7 +23,7 @@ import { theme } from "./lib/theme.ts";
* 1. Start the apps/fixtures/agent-tui-client server.
* 2. Boot an `EveTUIRunner` with a mock terminal.
* 3. Type the same delegation prompt the non-TUI subagent smoke uses.
- * 4. Wait for the `◆ echo-marker subagent` region header to appear.
+ * 4. Wait for the `※ subagent(echo-marker…)` region header to appear.
* 5. Wait for the nested region to contain the marker token.
* 6. Verify the parent assistant message also contains the token. The
* rendering side-channel must not have broken the harness path.
@@ -52,14 +52,14 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
throw error;
});
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type(
"Use the echo marker subagent to process the input 'ping'. Once it returns, reply with the subagent's exact output included verbatim in your message.",
);
input.enter();
- await screen.waitForText("echo-marker subagent", 90_000);
+ await screen.waitForText("※ subagent(echo-marker", 90_000);
console.log(theme.muted("[tui-subagents] subagent region header appeared"));
await waitForCondition(() => screen.snapshot().includes(SUBAGENT_TOKEN), {
@@ -68,23 +68,17 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
});
console.log(theme.muted("[tui-subagents] subagent message text landed in body"));
- // Wait for the token to appear twice, once inside the subagent step
- // section, once in the parent's follow-up Assistant reply. This is the
- // proof that (a) the child stream subscription rendered the subagent's
- // output, and (b) the parent's verbatim echo flowed through after.
- await waitForCondition(() => countOccurrences(screen.snapshot(), SUBAGENT_TOKEN) >= 2, {
- timeoutMs: 120_000,
- label: "token rendered in both subagent + parent",
- });
- console.log(theme.muted("[tui-subagents] token rendered in subagent step + parent assistant"));
-
- // The parent's own reply must carry the token inside a top-level
- // `▲`-prefixed assistant section — not just inside the nested `│`
- // subagent region. Whether the model also emits a pre-delegation
- // message is model-dependent, so the section count is not asserted.
+ // The child side is proven above (the token streamed into the live
+ // subagent body). Once the child settles, its section collapses to the
+ // `└ Done` footnote and the token leaves the screen — so the parent side
+ // is proven on its own: the verbatim echo must land in a top-level
+ // `▲`-prefixed assistant section, not just inside the nested `│` region.
+ // Whether the model also emits a pre-delegation message is
+ // model-dependent, so the section count is not asserted.
await waitForCondition(() => assistantSectionContains(screen.snapshot(), SUBAGENT_TOKEN), {
- timeoutMs: 30_000,
+ timeoutMs: 120_000,
label: "parent assistant section containing the token",
+ onTimeout: () => screen.snapshot(),
});
console.log(theme.muted("[tui-subagents] parent assistant reply rendered with token"));
@@ -96,23 +90,11 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
// The turn is complete; wait until the runner is back at the prompt so
// Ctrl+C exits the session. A Ctrl+C mid-stream now only interrupts the
// turn and returns to the prompt (Claude Code's two-step exit).
- await screen.waitForText("❯", 30_000);
+ await screen.waitForIdlePrompt(30_000);
input.ctrlC();
await runPromise;
});
-function countOccurrences(haystack: string, needle: string): number {
- if (needle.length === 0) return 0;
- let count = 0;
- let index = 0;
- while (true) {
- const next = haystack.indexOf(needle, index);
- if (next === -1) return count;
- count += 1;
- index = next + needle.length;
- }
-}
-
/**
* True when a top-level assistant section (a `▲ `-prefixed line and its
* two-space-indented continuations) contains `needle`.
@@ -135,7 +117,7 @@ function assistantSectionContains(snapshot: string, needle: string): boolean {
async function waitForCondition(
predicate: () => boolean,
- options: { timeoutMs: number; label: string; intervalMs?: number },
+ options: { timeoutMs: number; label: string; intervalMs?: number; onTimeout?: () => string },
): Promise<void> {
const intervalMs = options.intervalMs ?? 100;
const deadline = Date.now() + options.timeoutMs;
@@ -143,5 +125,6 @@ async function waitForCondition(
if (predicate()) return;
await sleep(intervalMs);
}
- throw new Error(`Timed out waiting for: ${options.label}`);
+ const detail = options.onTimeout === undefined ? "" : `\n${options.onTimeout()}`;
+ throw new Error(`Timed out waiting for: ${options.label}${detail}`);
}
diff --git a/packages/eve/test/tui-client/tui-transport-error.ts b/packages/eve/test/tui-client/tui-transport-error.ts
index 503916d3b..c6d235adb 100644
--- a/packages/eve/test/tui-client/tui-transport-error.ts
+++ b/packages/eve/test/tui-client/tui-transport-error.ts
@@ -37,7 +37,7 @@ void (async () => {
});
try {
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
input.type("Trigger a transport failure.");
input.enter();
@@ -47,7 +47,7 @@ void (async () => {
// The runner must survive the failure and return to the prompt rather
// than tear down.
- await screen.waitForText("❯", 5_000);
+ await screen.waitForIdlePrompt(5_000);
console.log(theme.muted("[tui-transport-error] runner returned to prompt"));
input.ctrlC();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e673ce2e5..ff0773e14 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -45,6 +45,9 @@ catalogs:
ai:
specifier: ^7.0.26
version: 7.0.26
+ marked:
+ specifier: 17.0.6
+ version: 17.0.6
next:
specifier: 16.3.0-preview.6
version: 16.3.0-preview.6
@@ -1292,6 +1295,9 @@ importers:
just-bash:
specifier: 3.0.1
version: 3.0.1
+ marked:
+ specifier: 'catalog:'
+ version: 17.0.6
microsandbox:
specifier: 0.5.5
version: 0.5.5
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 22725ef8c..45b8ab99b 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -33,6 +33,7 @@ catalog:
"@vercel/connect": "0.4.0"
"@vercel/sandbox": "2.3.0"
ai: "^7.0.26"
+ marked: "17.0.6"
next: "16.3.0-preview.6"
phase: "0.0.1"
picocolors: "1.1.1"