Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): show tasks as start and end lines with a live task panel in the TUI (#3957)

Andrew Barba315b3533cc17
diff --git a/.changeset/tui-subagents-modes.md b/.changeset/tui-subagents-modes.md
new file mode 100644
index 000000000..d5a2d69e6
--- /dev/null
+++ b/.changeset/tui-subagents-modes.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+`eve dev --subagents` now accepts `full`, `collapsed`, or `hidden`, and defaults to `collapsed`. `auto-collapsed` was removed because it rendered the same as `collapsed`; pass `collapsed` instead.
diff --git a/.changeset/tui-task-activity.md b/.changeset/tui-task-activity.md
new file mode 100644
index 000000000..40addc344
--- /dev/null
+++ b/.changeset/tui-task-activity.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The `eve dev` terminal UI now shows each task, such as a subagent call, as one line when it starts and one when it finishes, fails, or is stopped, with a panel above the prompt showing what every working task is doing. The transcript no longer jumps or rewrites while tasks work, the model's own `task_wait` and `task_cancel` calls no longer appear in the terminal UI or Slack typing indicators, and tools with a `label` show it instead of their raw arguments.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index b63905c91..4f978a890 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -450,7 +450,7 @@ The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method
### Delivery
-The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.
+The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. Labels leave out the model's own `task_wait` and `task_cancel` calls. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.
The built-in `message.completed` handler renders responses up to 12,000 characters inline. Longer responses are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope. Upload failures are logged by the channel dispatcher; they do not trigger a model retry. An authored `events["message.completed"]` handler replaces this behavior and owns its own delivery limits.
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index 7e0a7dfeb..6da0616c8 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -94,7 +94,9 @@ Required authorization or deployment setup still runs for the selected item. Pre
Type a message and press `Enter` to send it. When the agent asks a question or requests tool approval, respond in the prompt shown by the UI. Connection authorization can open a browser; keep local `eve dev` running until the browser returns to it.
-The activity line shows **Thinking** while the model reasons or waits to respond, **Generating** while it writes a response or tool input, and **Running** while tools execute. A blinking dot and elapsed time indicate progress, with token counts shown when available. The activity line disappears when the turn finishes or needs your input.
+The activity line shows **Thinking** while the model reasons or waits to respond, **Generating** while it writes a response or tool input, **Running** while tools execute, and **Waiting for** followed by task names while the turn waits on [tasks](../tools/tasks). A blinking dot and elapsed time indicate progress, with token counts shown when available. The activity line disappears when the turn finishes or needs your input.
+
+A task, such as a call to a subagent, writes one line to the transcript when it starts and one when it finishes, fails, or is stopped. The finished line names how long the task took and, for a subagent, what it did, such as `Read 3 files, Ran 2 commands`. While tasks work, a panel above the prompt shows each task's current activity and elapsed time. The UI does not show the model's own `task_wait` and `task_cancel` calls; their effect appears as the waiting activity line and a stopped task's line.
While a turn is running, `Enter` sends your message immediately as steering. Before assistant output begins, the runtime interrupts pending model generation and continues the same turn with your correction. Executing tools finish safely. After output begins, steering applies at the next workflow boundary and preserves streamed text.
@@ -126,6 +128,8 @@ Use `eve dev` flags to control tool calls, reasoning, subagents, connection auth
eve dev --tools full --reasoning collapsed --logs all
```
+`--subagents` accepts `collapsed` (the default), `full`, or `hidden`. `full` also writes each subagent message and tool call to the transcript as it finishes, and `hidden` leaves subagent tasks out of the transcript and the task panel.
+
Use `--host` and `--port` to bind the local server, or `--no-ui` to run without the terminal UI. Set `EVE_TUI_RENDER_MARKDOWN=0` to show assistant and subagent responses without Markdown parsing or styling; `1` (the default) enables Markdown rendering. See the [`eve dev` CLI reference](../reference/cli#eve-dev) for the complete option list, accepted values, and defaults.
## Connect to a deployment
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 22563a652..ffb5d6586 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -219,7 +219,7 @@ Starts a local development server and terminal UI. To connect the UI to an exist
| `--input <text>` | string | none | Pre-fill the prompt input |
| `--tools <mode>` | enum | `auto-collapsed` | Tool-call rendering |
| `--reasoning <mode>` | enum | `full` | Reasoning rendering |
-| `--subagents <mode>` | enum | `auto-collapsed` | Subagent-section rendering |
+| `--subagents <mode>` | enum | `collapsed` | Subagent task rendering: `full`, `collapsed`, or `hidden` |
| `--connection-auth <mode>` | enum | `full` | Connection-authorization rendering |
| `--assistant-response-stats <mode>` | enum | `tokensPerSecond` | Assistant header statistic |
| `--context-size <tokens>` | number | none | Model context window size |
diff --git a/docs/tools/tasks.md b/docs/tools/tasks.md
index dcc36cae6..9387c0e1a 100644
--- a/docs/tools/tasks.md
+++ b/docs/tools/tasks.md
@@ -272,7 +272,10 @@ otherwise. `status` is `"completed"`, `"failed"`, or `"cancelled"`. A completed
when an `execute` call opened it. Results reach the model as a message in its history, not as a
stream event, so read outcomes from `task.settled`. An `input.requested`,
`authorization.required`, or `authorization.completed` event from a task's run carries its
-`taskId`. Hooks subscribe to the same events. See
+`taskId`. Hooks subscribe to the same events. The stream also carries the model's `task_wait` and
+`task_cancel` calls as ordinary `actions.requested` tool calls, so evals can assert on them. The
+`eve dev` terminal UI and Slack typing indicators leave those calls out; the terminal UI shows each
+task's start and end instead. See
[Sessions, runs, and streaming](/docs/concepts/sessions-runs-and-streaming#task-events) and
[Follow a subagent](/docs/guides/client/streaming#follow-a-subagent).
diff --git a/packages/eve/src/cli/dev/command-options.ts b/packages/eve/src/cli/dev/command-options.ts
index 80167097a..50430df05 100644
--- a/packages/eve/src/cli/dev/command-options.ts
+++ b/packages/eve/src/cli/dev/command-options.ts
@@ -2,6 +2,7 @@ import type { DevelopmentRequestHeaders } from "#cli/dev/url-target.js";
import type {
AssistantResponseStatsMode,
LogDisplayMode,
+ SubagentDisplayMode,
TerminalPartDisplayMode,
} from "#cli/dev/tui/types.js";
@@ -20,7 +21,7 @@ export interface DevelopmentCliOptions {
port?: number;
reasoning?: TerminalPartDisplayMode;
resume?: boolean;
- subagents?: TerminalPartDisplayMode;
+ subagents?: SubagentDisplayMode;
tools?: TerminalPartDisplayMode;
ui?: boolean;
url?: string;
diff --git a/packages/eve/src/cli/dev/command.ts b/packages/eve/src/cli/dev/command.ts
index 768454ea9..14b852970 100644
--- a/packages/eve/src/cli/dev/command.ts
+++ b/packages/eve/src/cli/dev/command.ts
@@ -28,6 +28,7 @@ import {
parseLogsMode,
parsePortOption,
parseStatsMode,
+ parseSubagentDisplayMode,
} from "../option-parsers.js";
interface DevelopmentCommandLogger {
@@ -120,8 +121,8 @@ export function registerRemoteCommands(input: {
)
.option(
"--subagents <mode>",
- "How subagent sections render: full | collapsed | auto-collapsed | hidden",
- parseDisplayMode,
+ "How subagent tasks render: full | collapsed | hidden",
+ parseSubagentDisplayMode,
)
.option(
"--connection-auth <mode>",
@@ -205,8 +206,8 @@ export function registerDevelopmentCommand(input: {
)
.option(
"--subagents <mode>",
- "How subagent sections render: full | collapsed | auto-collapsed | hidden",
- parseDisplayMode,
+ "How subagent tasks render: full | collapsed | hidden",
+ parseSubagentDisplayMode,
)
.option(
"--connection-auth <mode>",
diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.ts
index 5d2946b48..3cc06d791 100644
--- a/packages/eve/src/cli/dev/tui/blocks.test.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts
@@ -262,27 +262,20 @@ describe("renderBlockLines", () => {
]);
});
- 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("writes a task's start and end as single lines", () => {
+ const agent = { kind: "task", taskKind: "agent", title: "researcher", live: false } as const;
+ expect(render({ ...agent, subtitle: "Find the Q3 revenue numbers" })).toEqual([
+ " ※ researcher Find the Q3 revenue numbers",
+ ]);
+ expect(
+ render({ ...agent, status: "done", body: "finished in 1min 12s · Read 3 files" }),
+ ).toEqual([" ✓ researcher finished in 1min 12s · Read 3 files"]);
+ expect(render({ ...agent, status: "error", body: "failed · Rate limited" })).toEqual([
+ " ⨯ researcher failed · Rate limited",
+ ]);
+ expect(render({ ...agent, status: "denied", body: "stopped" })).toEqual([
+ " ▪ researcher stopped",
+ ]);
});
it("renders steered and queued messages without extra arrow rows", () => {
@@ -319,50 +312,21 @@ describe("renderBlockLines", () => {
expect(rows).toEqual(["│ \x1b[1mhello\x1b[22m"]);
});
- it("pulses the in-progress subagent mark by intensity, with a quiet label", () => {
- const colorTheme = createTheme({ color: true, unicode: true });
- const running = { kind: "subagent", title: "echo-marker", live: true } as const;
- const onBeat = renderBlockLines(running, 80, colorTheme, { activityPulse: "▪" })[0] ?? "";
- const offBeat = renderBlockLines(running, 80, colorTheme, { activityPulse: " " })[0] ?? "";
-
- // The mark rides the shared beat: orange on, dim off — the glyph never
- // blanks, so the section keeps its anchor.
- expect(onBeat).toContain("\x1b[38;5;208m※");
- expect(offBeat).toContain("\x1b[2m※");
- expect(stripAnsi(offBeat)).toBe(" ※ subagent(echo-marker)");
-
- // The label stays quiet — no bold anywhere in the header.
- expect(onBeat).not.toContain("\x1b[1m");
- });
-
- 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({
+ it("names the agent above the first of its rows, not above each one", () => {
+ const row = {
kind: "subagent-step",
+ subagentCallId: "call-1",
+ agentName: "researcher",
depth: 1,
+ body: "Checked the filings.",
live: false,
- elided: 6,
- });
- expect(lines).toEqual([" │ … (6 more)"]);
+ } as const;
+ expect(render(row)).toEqual([" ※ researcher", " │ Checked the filings."]);
+ const continued = renderBlockLines(row, 80, theme, {
+ activityPulse: "▪",
+ previous: { kind: "subagent-tool", subagentCallId: "call-1" },
+ }).map(stripAnsi);
+ expect(continued).toEqual([" │ Checked the filings."]);
});
it("nests subagent tools under the orange rule", () => {
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index 405d86c3f..73339fccd 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -2,20 +2,22 @@
* The transcript block model and its renderer.
*
* A {@link Block} is one logical unit of the conversation — a user message, a
- * streamed assistant reply, a reasoning trace, a tool call, a nested subagent
- * step, a log line, and so on. {@link renderBlockLines} turns a block into the
+ * streamed assistant reply, a reasoning trace, a tool call, a task starting
+ * or ending, a log line, and so on. {@link renderBlockLines} turns a block into the
* exact terminal rows it occupies: a colored gutter glyph, brand-aligned
- * indentation, nesting rules for subagents, and word-wrapped content — with no
+ * indentation, nesting rules for an agent's own rows, and word-wrapped content — with no
* boxes anywhere. Every returned row is already styled and fits within the
* given width, so the live region can place rows verbatim.
*/
import { renderMarkdown } from "./markdown.js";
import type { ToolDetailLine } from "./line-diff.js";
+import type { TaskKind } from "./task-activity.js";
import type { Theme } from "./theme.js";
import type { ToolGroupPresentation } from "./tool-presentation.js";
import { isPromptControlCommand } from "./prompt-commands.js";
import { renderTool } from "./tool-rows.js";
+import { truncate } from "./tool-format.js";
import { elisionText, TOOL_COLUMN_LEAD } from "./rail.js";
import {
clipVisible,
@@ -38,10 +40,9 @@ export type BlockKind =
| "flow"
| "command"
| "question"
- | "subagent"
+ | "task"
| "subagent-step"
| "subagent-tool"
- | "subagent-close"
| "connection-auth"
| "sandbox"
| "log"
@@ -57,12 +58,12 @@ export interface Block {
kind: BlockKind;
/** Stable id for in-place updates while the block is live. */
id?: string;
- /** Nesting depth: 0 = top level, 1 = inside a subagent, etc. */
+ /** Nesting depth: 0 = top level, 1 = an agent's own row, etc. */
depth?: number;
/** Whether the block is still streaming / mutating (drives the activity pulse). */
live?: boolean;
- /** Primary label — tool name, subagent name, log source, error title. */
+ /** Primary label — tool name, task name, log source, error title. */
title?: string;
/** Past-tense tool label swapped in once the call settles successfully. */
doneTitle?: string;
@@ -84,7 +85,11 @@ export interface Block {
/** Structured remediation shown between an error's body and its detail. */
hint?: string;
- /** Tool, connection, or completed command lifecycle status. */
+ /**
+ * Tool, connection, or completed command lifecycle status. A task line
+ * without one marks the task starting; `done`, `error`, and `denied`
+ * (stopped) mark it ending.
+ */
status?: ToolStatus;
/** When true, treat `body` as pre-styled and only wrap + indent it. */
preformatted?: boolean;
@@ -105,8 +110,12 @@ export interface Block {
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. */
+ /** The agent call an agent's own row belongs to. */
subagentCallId?: string;
+ /** The agent an agent's own row belongs to, named above its first row. */
+ agentName?: string;
+ /** Task lines only: whether an agent or a tool does the work. */
+ taskKind?: TaskKind;
/**
* Monotonic activity stamp, bumped on every push and in-place update.
* Recency windows key on it so a parallel-announced call that just
@@ -125,17 +134,8 @@ export interface Block {
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.
- */
+ /** Earlier captured writes merged into this log section; renders as `… +N more`. */
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. */
@@ -160,7 +160,7 @@ export interface RenderBlockContext {
* 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 };
+ previous?: { kind: BlockKind; title?: string; subagentCallId?: string };
}
/**
@@ -176,20 +176,23 @@ export function renderBlockLines(
const depth = block.depth ?? 0;
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}`);
+ const rows = renderBody(block, avail, theme, context).map((row) => `${prefix}${row}`);
+ // An agent's own rows interleave with everything else in the order they
+ // finish, so each run of them opens with the agent's name.
+ if (
+ block.agentName !== undefined &&
+ context.previous?.subagentCallId !== block.subagentCallId &&
+ rows.length > 0
+ ) {
+ const name = `${theme.colors.orange(theme.glyph.subagent)} ${theme.colors.dim(block.agentName)}`;
+ return [clipVisible(`${TOOL_COLUMN_LEAD}${name}`, width), ...rows];
}
- return rows.map((row) => `${prefix}${row}`);
+ return rows;
}
/**
- * 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.
+ * The gutter prefix for nested rows: the two-cell tool-column indent, then a
+ * dim vertical rule per nesting level beneath the agent's name.
*/
function nestingPrefix(depth: number, theme: Theme): string {
if (depth <= 0) return "";
@@ -197,24 +200,12 @@ function nestingPrefix(depth: number, theme: Theme): string {
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: 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);
@@ -245,17 +236,8 @@ function renderBody(
return renderSandbox(block, width, theme, context);
case "log":
return renderLog(block, width, theme);
- case "subagent":
- return renderSubagentHeader(block, width, theme, context);
- 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 "task":
+ return renderTask(block, width, theme);
case "turn-stats":
return renderTurnStats(block, width, theme);
case "session-boundary":
@@ -280,16 +262,6 @@ function renderProse(
): string[] {
const rows: string[] = [];
const isSubagent = block.kind === "subagent-step";
- // 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)))];
- }
// The brand anchors every top-level response; Markdown styles the content
// following it, rather than replacing the response gutter.
const markdown = context.renderMarkdown ?? true;
@@ -571,43 +543,38 @@ function renderTurnStats(block: Block, width: number, theme: Theme): string[] {
return [theme.colors.dim(truncatePlain(line, Math.max(1, width)))];
}
-function renderSubagentHeader(
+/**
+ * A task's line: `※ researcher Find Q3 revenue numbers` as it starts, and
+ * `✓ researcher finished in 1m 12s · Read 10 files` (or failed, or stopped)
+ * as it ends. Each is written once; what the task does in between lives in
+ * the task panel above the prompt.
+ */
+function renderTask(block: Block, width: number, theme: Theme): string[] {
+ const c = theme.colors;
+ const { mark, detail, color } = taskLineStyle(block, theme);
+ const head = `${TOOL_COLUMN_LEAD}${mark} ${c.bold(truncate(block.title ?? "task", width - 4))}`;
+ const budget = width - visibleLength(head) - 2;
+ if (detail.length === 0 || budget < 6) return [clipVisible(head, Math.max(1, width))];
+ return [clipVisible(`${head} ${color(truncate(detail, budget))}`, Math.max(1, width))];
+}
+
+function taskLineStyle(
block: Block,
- width: number,
theme: Theme,
- context: RenderBlockContext,
-): string[] {
- // `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 settles its mark: an in-progress section pulses the `※`
- // on the shared activity beat — by intensity (orange ↔ dim), so the
- // glyph keeps anchoring the section — and a done one holds 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)
- : context.activityPulse.trim().length > 0
- ? theme.colors.orange(theme.glyph.subagent)
- : theme.colors.dim(theme.glyph.subagent);
- let header = `${lead}${mark} subagent(${name}${ordinal})`;
- if (!isOrdinal && block.subtitle !== undefined && block.subtitle.length > 0) {
- header += ` ${theme.colors.dim(block.subtitle)}`;
+): { mark: string; detail: string; color: (text: string) => string } {
+ const c = theme.colors;
+ switch (block.status) {
+ case "done":
+ return { mark: c.green(theme.glyph.success), detail: block.body ?? "", color: c.dim };
+ case "error":
+ return { mark: c.red(theme.glyph.error), detail: block.body ?? "failed", color: c.red };
+ case "denied":
+ return { mark: c.dim(theme.glyph.square), detail: block.body ?? "stopped", color: c.dim };
+ default: {
+ const accent = block.taskKind === "agent" ? c.orange : c.gray;
+ return { mark: accent(theme.glyph.subagent), detail: block.subtitle ?? "", color: c.gray };
+ }
}
- 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/rail.ts b/packages/eve/src/cli/dev/tui/rail.ts
index d2f7059e2..8bdf889ed 100644
--- a/packages/eve/src/cli/dev/tui/rail.ts
+++ b/packages/eve/src/cli/dev/tui/rail.ts
@@ -1,6 +1,6 @@
/**
* The shared atoms of the transcript's rail grammar. Persistent sections
- * (tool rows, subagent sections) all hang their marks at the
+ * (tool rows, task lines) 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.
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 2e36c2525..f2741d0be 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -374,10 +374,10 @@ describe("registryHandoffAddress", () => {
suspendPromptForInput: () => promptSuspended.resolve(),
subagents: {
begin: vi.fn(),
+ end: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
- complete: vi.fn(),
markChildToolCallId: vi.fn(),
},
});
@@ -3578,7 +3578,7 @@ describe("EveTUIRunner renderer teardown", () => {
expect(requestStop).toHaveBeenCalledOnce();
});
- it("finishes the section on the child's own turn boundary, before task.settled", async () => {
+ it("follows the child to its own turn boundary, before task.settled", async () => {
const client = stubClient();
vi.stubGlobal(
"fetch",
@@ -3608,14 +3608,14 @@ describe("EveTUIRunner renderer teardown", () => {
),
);
- const completeSubagent = vi.fn();
+ const upsertStep = 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.
+ // Hold the second prompt open until the child's final message lands
+ // — exiting the run loop aborts the child pump.
readPrompt: vi
.fn()
.mockResolvedValueOnce("delegate")
@@ -3628,14 +3628,14 @@ describe("EveTUIRunner renderer teardown", () => {
}),
subagents: {
begin: vi.fn(),
- upsertStep: vi.fn(),
+ end: vi.fn(),
+ upsertStep: (update) => {
+ upsertStep(update);
+ if (update.finalized) completed.resolve();
+ },
upsertTool: vi.fn(),
removeTool: vi.fn(),
markChildToolCallId: vi.fn(),
- complete: (update: { authoritative: boolean; callId: string }) => {
- completeSubagent(update);
- completed.resolve();
- },
},
}),
session: sessionYielding([
@@ -3661,7 +3661,7 @@ describe("EveTUIRunner renderer teardown", () => {
},
},
// The parent stream never reports task.settled — the child's own
- // boundary must finish the section.
+ // stream still delivers its final message.
{ type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },
{
type: "session.waiting",
@@ -3673,7 +3673,9 @@ describe("EveTUIRunner renderer teardown", () => {
await runner.run();
await completed.promise;
- expect(completeSubagent).toHaveBeenCalledWith({ authoritative: true, callId: "call-child" });
+ expect(upsertStep).toHaveBeenCalledWith(
+ expect.objectContaining({ callId: "call-child", message: "final answer", finalized: true }),
+ );
});
it("aborts child-session streams when Ctrl-C exits the runner", async () => {
@@ -4744,29 +4746,30 @@ describe("EveTUIRunner session id reporting", () => {
});
describe("EveTUIRunner cancelled-turn subagent settling", () => {
- it("settles subagent sections when the turn is explicitly cancelled", async () => {
+ it("stops following only the cancelled turn's agents", async () => {
// A child stream that never ends on its own — it only stops when the
// pump aborts it (the scoped cancellation path under test).
const client = stubClient();
+ const childSignals = new Map<string, AbortSignal | undefined>();
vi.stubGlobal(
"fetch",
- vi.fn<typeof fetch>(
- async (_input, init) =>
- new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- init?.signal?.addEventListener(
- "abort",
- () => controller.error(new DOMException("Aborted", "AbortError")),
- { once: true },
- );
- },
- }),
- {
- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },
+ vi.fn<typeof fetch>(async (input, init) => {
+ childSignals.set(new URL(String(input)).pathname, init?.signal ?? undefined);
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ init?.signal?.addEventListener(
+ "abort",
+ () => controller.error(new DOMException("Aborted", "AbortError")),
+ { once: true },
+ );
},
- ),
- ),
+ }),
+ {
+ headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },
+ },
+ );
+ }),
);
const session = sessionYielding([
@@ -4817,15 +4820,24 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {
]);
const view = {
begin: vi.fn(),
+ end: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
- complete: vi.fn(),
markChildToolCallId: vi.fn(),
};
const prompts: Array<string | undefined> = ["hello", undefined];
+ let abortedAtNextPrompt: Record<string, boolean | undefined> = {};
const renderer = fakeRenderer({
- readPrompt: vi.fn(async () => prompts.shift()),
+ readPrompt: vi.fn(async () => {
+ if (prompts.length === 1) {
+ await vi.waitFor(() => expect(childSignals.size).toBe(2));
+ abortedAtNextPrompt = Object.fromEntries(
+ [...childSignals].map(([path, signal]) => [path, signal?.aborted]),
+ );
+ }
+ return prompts.shift();
+ }),
renderStream: vi.fn(async (result) => {
for await (const event of result.events as AsyncIterable<unknown>) {
void event;
@@ -4837,12 +4849,12 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {
const runner = new EveTUIRunner({ session, client, renderer, name: "Weather Agent" });
await runner.run();
- expect(view.begin).toHaveBeenCalledWith({ callId: "call-a", name: "researcher" });
- expect(view.begin).toHaveBeenCalledWith({ callId: "call-1", name: "researcher" });
- // A cancelled call's section closes with the cancelled turn, not a
- // later `task.settled`.
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });
- expect(view.complete).not.toHaveBeenCalledWith({ authoritative: true, callId: "call-a" });
+ // A cancelled turn stops following its own agents without waiting for a
+ // later `task.settled`; another turn's agent keeps streaming.
+ expect(abortedAtNextPrompt).toEqual({
+ "/eve/v1/session/child-1/stream": true,
+ "/eve/v1/session/child-a/stream": false,
+ });
});
});
@@ -4937,3 +4949,117 @@ it("keeps the result of an explicit login command after onboarding", async () =>
summary: undefined,
});
});
+
+describe("EveTUIRunner task activity", () => {
+ it("shows people their tasks and keeps the model's task bookkeeping out of view", async () => {
+ const turn = { sequence: 1, stepIndex: 0, turnId: "turn-1" };
+ const inputDelta = (callId: string, toolName: string) => ({
+ type: "action.input.appended",
+ data: { ...turn, callId, inputTextDelta: "{}", toolName },
+ });
+ const toolResult = (
+ callId: string,
+ toolName: string,
+ output: unknown,
+ status = "completed",
+ ) => ({
+ type: "action.result",
+ data: { ...turn, result: { callId, kind: "tool-result", output, toolName }, status },
+ });
+ const session = sessionYielding([
+ { type: "turn.started", data: { sequence: 0, turnId: "turn-1" } },
+ inputDelta("deploy-call", "deploy"),
+ inputDelta("deploy-call", "deploy"),
+ inputDelta("wait-call", "task_wait"),
+ {
+ type: "actions.requested",
+ data: {
+ ...turn,
+ actions: [
+ {
+ callId: "deploy-call",
+ input: { env: "preview" },
+ kind: "tool-call",
+ toolName: "deploy",
+ },
+ { callId: "retry-call", input: {}, kind: "tool-call", toolName: "report" },
+ { callId: "lookup-call", input: {}, kind: "tool-call", toolName: "lookup" },
+ { callId: "wait-call", input: {}, kind: "tool-call", toolName: "task_wait" },
+ {
+ callId: "cancel-call",
+ input: { taskId: "t0" },
+ kind: "tool-call",
+ toolName: "task_cancel",
+ },
+ ],
+ presentation: { "deploy-call": { label: "Deploy to preview" } },
+ },
+ },
+ {
+ type: "task.started",
+ data: {
+ callId: "deploy-call",
+ kind: "tool",
+ name: "deploy",
+ taskId: "t1",
+ turnId: "turn-1",
+ },
+ },
+ toolResult("deploy-call", "deploy", "receipt written for the model"),
+ toolResult("retry-call", "report", { code: "TOO_MANY_TASKS", message: "wait" }, "failed"),
+ // An authored tool's own result can carry the same code; only a refusal fails.
+ toolResult("lookup-call", "lookup", { code: "UNKNOWN_TASK", ticket: "T-1" }),
+ toolResult("cancel-call", "task_cancel", "t0 had no work to stop."),
+ {
+ type: "task.settled",
+ data: {
+ callId: "deploy-call",
+ output: { url: "https://preview.example" },
+ status: "completed",
+ taskId: "t1",
+ turnId: "turn-1",
+ },
+ },
+ toolResult("wait-call", "task_wait", "t1 completed; its result follows."),
+ { type: "session.waiting", data: { continuationToken: "c", wait: "next-user-message" } },
+ ]);
+ const seen: AgentTUIStreamEvent[] = [];
+ const prompts: Array<string | undefined> = ["deploy it", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {
+ seen.push(event);
+ }
+ }),
+ });
+
+ await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();
+
+ expect(seen.filter((event) => event.type !== "turn-start" && event.type !== "finish")).toEqual([
+ { type: "tool-call-preparing", toolCallId: "deploy-call", toolName: "deploy" },
+ {
+ type: "tool-call",
+ toolCallId: "deploy-call",
+ toolName: "deploy",
+ input: { env: "preview" },
+ label: "Deploy to preview",
+ },
+ { type: "tool-call", toolCallId: "retry-call", toolName: "report", input: {} },
+ { type: "tool-call", toolCallId: "lookup-call", toolName: "lookup", input: {} },
+ { type: "task-started", toolCallId: "deploy-call", kind: "tool", toolName: "deploy" },
+ { type: "tool-withdrawn", toolCallId: "retry-call", reason: expect.any(String) },
+ {
+ type: "tool-result",
+ toolCallId: "lookup-call",
+ output: { code: "UNKNOWN_TASK", ticket: "T-1" },
+ },
+ {
+ type: "task-settled",
+ toolCallId: "deploy-call",
+ status: "completed",
+ output: { url: "https://preview.example" },
+ },
+ ]);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 3e906c3eb..4f02469ea 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -27,6 +27,7 @@ import type { OnboardingScreenEvent } from "./setup-commands.js";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import { createEventDeduper } from "#protocol/event-dedupe.js";
import { isCurrentTurnBoundaryEvent } from "#protocol/message.js";
+import { isTaskControlTool, isTaskRetryRefusal } from "#protocol/task-tools.js";
import {
createDevelopmentRuntimeArtifactRefresher,
type DevelopmentRuntimeArtifactRefresher,
@@ -176,11 +177,35 @@ export type AgentTUIStreamEvent =
| { 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-call";
+ toolCallId: string;
+ toolName: string;
+ input: unknown;
+ /** The tool's own `label.start` copy, when it defines one. */
+ label?: string;
+ }
| { type: "tool-approval-request"; approvalId: string; toolCallId: string }
- | { type: "tool-result"; toolCallId: string; output: unknown }
+ | {
+ type: "tool-result";
+ toolCallId: string;
+ output: unknown;
+ /** The tool's own `label.complete` copy, when it defines one. */
+ label?: string;
+ }
| { type: "tool-error"; toolCallId: string; errorText: string }
| { type: "tool-rejected"; toolCallId: string; reason: string }
+ /** A call the session refused for the model to retry; it leaves no trace in the transcript. */
+ | { type: "tool-withdrawn"; toolCallId: string; reason: string }
+ /** A call became a task that keeps working while the turn goes on. */
+ | { type: "task-started"; toolCallId: string; kind: "agent" | "tool"; toolName: string }
+ | {
+ type: "task-settled";
+ toolCallId: string;
+ status: "completed" | "failed" | "cancelled";
+ output?: unknown;
+ errorText?: string;
+ }
| { type: "error"; errorText: string; hint?: string; detail?: string }
| { type: "turn-cancelled" }
| { type: "finish"; usage?: AgentTUIStreamUsage };
@@ -208,7 +233,6 @@ export type AgentTUISessionOptions = {
continueSession?: boolean;
tools?: TerminalPartDisplayMode;
reasoning?: TerminalPartDisplayMode;
- subagents?: TerminalPartDisplayMode;
connectionAuth?: TerminalPartDisplayMode;
assistantResponseStats?: AssistantResponseStatsMode;
contextSize?: number;
@@ -525,7 +549,6 @@ export class EveTUIRunner {
readonly #name: string;
readonly #tools: TerminalPartDisplayMode;
readonly #reasoning: TerminalPartDisplayMode;
- readonly #subagents: TerminalPartDisplayMode;
readonly #connectionAuth: TerminalPartDisplayMode;
readonly #assistantResponseStats: AssistantResponseStatsMode;
readonly #contextSize?: number;
@@ -639,7 +662,6 @@ export class EveTUIRunner {
this.#withExclusiveTerminal = options.withExclusiveTerminal;
this.#tools = options.tools ?? "full";
this.#reasoning = options.reasoning ?? "full";
- this.#subagents = options.subagents ?? "full";
this.#connectionAuth = options.connectionAuth ?? "full";
this.#assistantResponseStats = options.assistantResponseStats ?? defaultAssistantResponseStats;
this.#contextSize = options.contextSize;
@@ -1073,7 +1095,6 @@ export class EveTUIRunner {
continueSession: Boolean(this.#renderer.readPrompt),
tools: this.#tools,
reasoning: this.#reasoning,
- subagents: this.#subagents,
connectionAuth: this.#connectionAuth,
assistantResponseStats: this.#assistantResponseStats,
contextSize: this.#contextSize,
@@ -1626,7 +1647,6 @@ export class EveTUIRunner {
this.#subagentPump.taskStarted(event, sourceSession?.state.sessionId),
onAgentStarted: (event) =>
this.#subagentPump.agentStarted(event, sourceSession?.state.sessionId),
- onTaskSettled: (callId) => this.#subagentPump.settle(callId),
onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),
onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),
onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),
@@ -2106,7 +2126,6 @@ type EveStreamTranslatorInput = {
turnState: AgentTUITurnState;
onTaskStarted?: (event: TaskStartedStreamEvent) => void;
onAgentStarted?: (event: AgentStartedStreamEvent) => void;
- onTaskSettled?: (callId: string) => void;
onTurnCancelled?: (turnId: string) => void;
onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;
onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;
@@ -2153,7 +2172,6 @@ async function* eveEventsToTUIStream(
turnState,
onTaskStarted,
onAgentStarted,
- onTaskSettled,
onTurnCancelled,
onConnectionAuthRequired,
onConnectionAuthCompleted,
@@ -2173,6 +2191,10 @@ async function* eveEventsToTUIStream(
// completed is the discriminator.
let stepEpoch = 0;
const knownToolCalls = new Set<string>();
+ const preparingToolCalls = new Set<string>();
+ // A task's `action.result` is only its start receipt, written for the
+ // model; the call settles with `task.settled`.
+ const taskCallIds = new Set<string>();
const seenInputRequestIds = new Set<string>();
// The harness reports one underlying failure as a cascade (`step.failed` →
// `turn.failed` → `session.failed`) with an identical payload on each
@@ -2347,28 +2369,45 @@ async function* eveEventsToTUIStream(
break;
}
+ case "action.input.appended": {
+ const { callId, toolName } = event.data;
+ if (knownToolCalls.has(callId) || preparingToolCalls.has(callId)) break;
+ if (isTaskControlTool(toolName)) break;
+ preparingToolCalls.add(callId);
+ yield { type: "tool-call-preparing", toolCallId: callId, toolName };
+ break;
+ }
+
case "actions.requested": {
const data = (event as ActionsRequestedStreamEvent).data;
- const actions = data.actions.filter((action) => action.kind === "tool-call");
+ const actions = data.actions.flatMap((action) =>
+ action.kind === "tool-call" && !isTaskControlTool(action.toolName) ? [action] : [],
+ );
if (actions.length === 0) break;
for (const action of actions) {
toolNames.set(action.callId, action.toolName);
if (knownToolCalls.has(action.callId)) continue;
knownToolCalls.add(action.callId);
- yield {
+ const toolCall: Extract<AgentTUIStreamEvent, { type: "tool-call" }> = {
type: "tool-call",
toolCallId: action.callId,
toolName: action.toolName,
input: action.input,
};
+ const label = data.presentation?.[action.callId]?.label;
+ if (label !== undefined) toolCall.label = label;
+ yield toolCall;
}
break;
}
case "input.requested": {
const data = (event as InputRequestedStreamEvent).data;
- const requests = data.requests.filter((request) => request.action.kind === "tool-call");
+ const requests = data.requests.filter(
+ (request) =>
+ request.action.kind === "tool-call" && !isTaskControlTool(request.action.toolName),
+ );
if (requests.length === 0) break;
for (const request of requests) {
@@ -2438,20 +2477,28 @@ async function* eveEventsToTUIStream(
break;
}
const callId = resultEvent.data.result.callId;
- if (!knownToolCalls.has(callId)) {
- // Results for calls this turn never announced (e.g. subagent
- // dispatches, which surface through the subagent section instead)
- // have no tool block to attach to.
+ // Results for calls this turn never announced (task control calls,
+ // or a call first announced to another stream) have no tool block.
+ if (!knownToolCalls.has(callId) || taskCallIds.has(callId)) break;
+ if (isTaskRetryRefusal(resultEvent)) {
+ yield {
+ type: "tool-withdrawn",
+ toolCallId: callId,
+ reason: formatActionResultError(resultEvent),
+ };
break;
}
switch (resultEvent.data.status) {
case "completed": {
const output = resultEvent.data.result.output;
- yield {
+ const toolResult: Extract<AgentTUIStreamEvent, { type: "tool-result" }> = {
type: "tool-result",
toolCallId: callId,
output,
};
+ const label = resultEvent.data.presentation?.[callId]?.label;
+ if (label !== undefined) toolResult.label = label;
+ yield toolResult;
const address = registryHandoffAddress(undefined, toolNames.get(callId), output);
if (address !== undefined) await onRegistryHandoff?.(address);
break;
@@ -2546,16 +2593,32 @@ async function* eveEventsToTUIStream(
// and re-entry from a later translator live in the pump. The agent's
// content is observed through its session's stream.
case "task.started":
+ taskCallIds.add(event.data.callId);
onTaskStarted?.(event);
+ yield {
+ type: "task-started",
+ toolCallId: event.data.callId,
+ kind: event.data.kind,
+ toolName: event.data.name,
+ };
break;
case "agent.started":
onAgentStarted?.(event);
break;
- case "task.settled":
- onTaskSettled?.(event.data.callId);
+ case "task.settled": {
+ const { callId, error, output, status } = event.data;
+ const settled: Extract<AgentTUIStreamEvent, { type: "task-settled" }> = {
+ type: "task-settled",
+ toolCallId: callId,
+ status,
+ };
+ if (output !== undefined) settled.output = output;
+ if (error !== undefined) settled.errorText = error.message;
+ yield settled;
break;
+ }
case "authorization.required":
onConnectionAuthRequired?.(event as AuthorizationRequiredStreamEvent);
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
index 31a5d57af..0c9dcc4cd 100644
--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
@@ -19,10 +19,10 @@ afterEach(() => {
function fakeView(): SubagentView {
return {
begin: vi.fn(),
+ end: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
- complete: vi.fn(),
markChildToolCallId: vi.fn(),
};
}
@@ -222,7 +222,7 @@ describe("SubagentPump.settleCancelledTurn", () => {
if (child === undefined) throw new Error(`Unexpected child path: ${path}`);
return child.response(signal);
});
- const { pump, view } = createPump();
+ const { pump } = createPump();
startAgentTask(pump, "child-a", { turnId: "turn-a" });
startAgentTask(pump, "child-b", { turnId: "turn-b" });
@@ -230,17 +230,12 @@ describe("SubagentPump.settleCancelledTurn", () => {
pump.settleCancelledTurn("turn-b");
- expect(view.complete).toHaveBeenCalledTimes(1);
- expect(view.complete).toHaveBeenCalledWith({
- authoritative: true,
- callId: "child-b",
- });
expect(childB.aborted).toBe(true);
expect(childA.aborted).toBe(false);
pump.abortAll();
});
- it("closes live sections and stops stale child output after cancellation", async () => {
+ it("finalizes the live step and stops stale child output after cancellation", async () => {
const child = pushableChildStream();
const requests = serveChildStreams(({ signal }) => child.response(signal));
const { pump, view } = createPump();
@@ -254,9 +249,8 @@ describe("SubagentPump.settleCancelledTurn", () => {
),
);
- // The parent turn is cancelled: sections settle and the stream stops.
+ // The parent turn is cancelled: the live step finalizes and the stream stops.
pump.settleCancelledTurn("turn-1");
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });
expect(view.upsertStep).toHaveBeenCalledWith(
expect.objectContaining({ callId: "call-1", finalized: true }),
);
@@ -266,37 +260,101 @@ describe("SubagentPump.settleCancelledTurn", () => {
child.push(reasoningEvent("stale output", 1));
await new Promise((resolve) => setTimeout(resolve, 10));
expect(vi.mocked(view.upsertStep).mock.calls.length).toBe(updatesAfterSettle);
-
- // The call's late `task.settled` settles as a no-op.
- const completions = vi.mocked(view.complete).mock.calls.length;
- pump.settle("call-1");
- expect(vi.mocked(view.complete).mock.calls.length).toBe(completions);
});
});
-describe("SubagentPump completion", () => {
- it("reopens after parent completion and upgrades at the child boundary", async () => {
- const child = pushableChildStream();
- const requests = serveChildStreams(({ signal }) => child.response(signal));
+describe("SubagentPump task bookkeeping", () => {
+ it("keeps the child's task bookkeeping out of its activity", async () => {
+ const action = (callId: string, toolName: string) => ({
+ callId,
+ input: toolName === "task_wait" ? {} : { message: "Check the filings" },
+ kind: "tool-call" as const,
+ toolName,
+ });
+ const result = (callId: string, toolName: string, output: unknown, status = "completed") => ({
+ type: "action.result",
+ data: {
+ result: { callId, kind: "tool-result", output, toolName },
+ sequence: 2,
+ status,
+ stepIndex: 0,
+ turnId: "child-turn",
+ },
+ });
+ serveChildStreams(
+ durableChild(
+ [
+ {
+ type: "actions.requested",
+ data: {
+ actions: [
+ action("analyst-call", "analyst"),
+ action("deploy-call", "deploy"),
+ action("wait-call", "task_wait"),
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "child-turn",
+ },
+ },
+ {
+ type: "task.started",
+ data: {
+ callId: "analyst-call",
+ kind: "agent",
+ name: "analyst",
+ taskId: "t1",
+ turnId: "child-turn",
+ },
+ },
+ result("analyst-call", "analyst", "model-facing receipt"),
+ result("deploy-call", "deploy", { code: "TOO_MANY_TASKS", message: "wait" }, "failed"),
+ result("wait-call", "task_wait", "t1 completed; its result follows."),
+ {
+ type: "task.settled",
+ data: {
+ callId: "analyst-call",
+ output: "Revenue grew 12%",
+ status: "completed",
+ taskId: "t1",
+ turnId: "child-turn",
+ },
+ },
+ { type: "session.waiting", data: { continuationToken: "c", wait: "next-user-message" } },
+ ].map((event, index) => stampTestEvent(event as UnstampedMessageStreamEvent, index)),
+ ),
+ );
const { pump, view } = createPump();
startAgentTask(pump, "call-1");
- pump.settle("call-1");
- expect(view.complete).toHaveBeenCalledWith({ authoritative: false, callId: "call-1" });
- startAgentTask(pump, "call-1");
- expect(view.begin).toHaveBeenCalledOnce();
-
- await vi.waitFor(() => expect(requests).toHaveLength(1));
- child.push(reasoningEvent("delayed output", 0));
- child.push(boundaryEvent(1));
+ await vi.waitFor(() => expect(view.removeTool).toHaveBeenCalledOnce());
await vi.waitFor(() =>
- expect(view.complete).toHaveBeenLastCalledWith({ authoritative: true, callId: "call-1" }),
+ expect(view.upsertTool).toHaveBeenLastCalledWith(
+ expect.objectContaining({ childCallId: "analyst-call", status: "done" }),
+ ),
);
- expect(view.begin).toHaveBeenCalledTimes(2);
- expect(view.upsertStep).toHaveBeenCalledWith(
- expect.objectContaining({ callId: "call-1", reasoning: "delayed output" }),
- );
+ const updates = vi.mocked(view.upsertTool).mock.calls.map(([update]) => update);
+ expect(updates.some((update) => update.toolName === "task_wait")).toBe(false);
+ // The agent call reads as a delegation and ends with its task, not its receipt.
+ expect(
+ updates
+ .filter((update) => update.childCallId === "analyst-call")
+ .map(({ status, agentTask, output }) => ({ status, agentTask, output })),
+ ).toEqual([
+ { status: "executing", agentTask: undefined, output: undefined },
+ { status: "executing", agentTask: true, output: undefined },
+ { status: "done", agentTask: true, output: "Revenue grew 12%" },
+ ]);
+ // A call refused for the model to retry leaves the activity, with why.
+ expect(view.removeTool).toHaveBeenCalledWith({
+ callId: "call-1",
+ childCallId: "deploy-call",
+ reason: "failed",
+ });
+ // The task's end waits for the child's own boundary, which it reached.
+ expect(view.begin).toHaveBeenCalledWith({ callId: "call-1" });
+ await vi.waitFor(() => expect(view.end).toHaveBeenCalledWith({ callId: "call-1" }));
});
});
@@ -323,13 +381,10 @@ describe("SubagentPump child stream transport", () => {
tracingDone = response.clone().text().catch(tracingError);
return response;
});
- const { pump, view } = createPump();
+ const { pump } = createPump();
try {
startAgentTask(pump, "call-1");
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
await vi.waitFor(() => expect(signal?.aborted).toBe(true));
await tracingDone;
@@ -388,14 +443,12 @@ describe("SubagentPump child stream transport", () => {
]),
);
const onToolCompleted = vi.fn(async () => {});
- const { pump, view } = createPump({ onToolCompleted });
+ const { pump } = createPump({ onToolCompleted });
const task = startAgentTask(pump, "call-1", {
name: "self-modification__agent",
sessionId: "conversation-child",
});
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
+ await vi.waitFor(() => expect(requests[0]?.signal?.aborted).toBe(true));
callAgentTask(pump, task, "call-2", "turn-2");
await vi.waitFor(() => expect(onToolCompleted).toHaveBeenCalledOnce());
@@ -416,7 +469,6 @@ describe("SubagentPump child stream transport", () => {
const { pump, view } = createPump();
const task = startAgentTask(pump, "call-1", { sessionId: "conversation-child" });
await vi.waitFor(() => expect(requests).toHaveLength(1));
- pump.settle("call-1");
callAgentTask(pump, task, "call-2", "turn-2");
await new Promise((resolve) => setTimeout(resolve, 10));
@@ -432,7 +484,7 @@ describe("SubagentPump child stream transport", () => {
});
it("leaves connection authorization events to the parent runner", async () => {
- serveChildStreams(
+ const authRequests = serveChildStreams(
durableChild([
stampTestEvent(
{
@@ -466,9 +518,7 @@ describe("SubagentPump child stream transport", () => {
const { pump, view } = createPump();
startAgentTask(pump, "call-1");
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
+ await vi.waitFor(() => expect(authRequests[0]?.signal?.aborted).toBe(true));
expect(view.upsertStep).not.toHaveBeenCalled();
expect(view.upsertTool).not.toHaveBeenCalled();
@@ -488,9 +538,7 @@ describe("SubagentPump child stream transport", () => {
const { pump, view } = createPump();
startAgentTask(pump, "call-1");
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
+ await vi.waitFor(() => expect(requests[1]?.signal?.aborted).toBe(true));
expect(requests.map(({ path, startIndex }) => ({ path, startIndex }))).toEqual([
{ path: "/eve/v1/children/call-1/stream", startIndex: 0 },
@@ -506,13 +554,13 @@ describe("SubagentPump child stream transport", () => {
const requests = serveChildStreams((request) =>
responseOf(requests.length > 8 ? [boundaryEvent(request.startIndex)] : []),
);
- const { pump, view } = createPump();
+ const { pump } = createPump();
startAgentTask(pump, "call-1");
await vi.advanceTimersByTimeAsync(60_000);
expect(requests).toHaveLength(9);
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });
+ expect(requests.at(-1)?.signal?.aborted).toBe(true);
});
it("stops following when the child stream is refused", async () => {
@@ -524,22 +572,19 @@ describe("SubagentPump child stream transport", () => {
await new Promise((resolve) => setTimeout(resolve, 10));
expect(requests).toHaveLength(1);
- expect(view.complete).not.toHaveBeenCalled();
- pump.settle("call-1");
- expect(view.complete).toHaveBeenCalledWith({ authoritative: false, callId: "call-1" });
+ // Nothing more will come, so the task's end must not wait for it.
+ expect(view.end).toHaveBeenCalledWith({ callId: "call-1" });
});
it("uses the parent-authored child path and never the remote URL", async () => {
const requests = serveChildStreams(durableChild([boundaryEvent(0)]));
- const { pump, view } = createPump({ host: "https://parent.example" });
+ const { pump } = createPump({ host: "https://parent.example" });
const streamPath = "/eve/v1/session/parent/subagents/remote-call/child/stream";
startAgentTask(pump, "remote-call", {
remote: { url: "https://remote.example/private" },
streamPath,
});
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "remote-call" }),
- );
+ await vi.waitFor(() => expect(requests[0]?.signal?.aborted).toBe(true));
expect(requests[0]!.url.origin).toBe("https://parent.example");
expect(requests[0]!.path).toBe(streamPath);
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.ts
index 6e89020c7..07e002833 100644
--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts
@@ -1,19 +1,21 @@
/**
* The subagent child-stream subsystem: for every call to an agent task on
* the parent stream, a parallel pump over the agent's 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.
+ * events into the renderer's view of what that agent is doing. Extracted
+ * from the runner — the subsystem touches nothing but its own run state, the
+ * client, and the {@link SubagentView} seam.
*/
import type { Client, StreamReconnectPolicy } from "#client/index.js";
import {
isCurrentTurnBoundaryEvent,
+ type ActionPresentationByCallId,
type ActionResultStreamEvent,
type AgentStartedStreamEvent,
type MessageStreamEvent,
type TaskStartedStreamEvent,
} from "#protocol/message.js";
+import { isTaskControlTool, isTaskRetryRefusal } from "#protocol/task-tools.js";
/**
* Pumps end on the child boundary or abort, never on a retry budget: a child
@@ -26,22 +28,28 @@ const childStreamReconnectPolicy = {
} as const satisfies StreamReconnectPolicy;
/**
- * 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.
+ * The renderer's view of each agent task's own activity. One cohesive
+ * capability: a renderer that implements it shows what every working agent
+ * is doing, and a renderer without it simply shows none. Individually
+ * optional methods would let a renderer implement a type-legal subset that
+ * ghosts placeholders or duplicates parent tool rows. The task's start and
+ * end reach the renderer on the parent stream, not through this view.
*/
export interface SubagentView {
- /** Opens a call's section the moment its dispatch is announced. */
- begin(update: { callId: string; name: string }): void;
+ /**
+ * The pump follows the agent a call reaches. The agent's last events can
+ * trail the parent's `task.settled`, so the task's end waits for {@link end}.
+ */
+ begin(update: { callId: string }): void;
+ /** The followed agent's own stream ended, or the pump stopped following it. */
+ end(update: { callId: 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: { authoritative: boolean; callId: string }): void;
+ /**
+ * Drops a child tool call that never materialized, or one the session
+ * refused for the model to retry (`reason` says why).
+ */
+ removeTool(update: { callId: string; childCallId: string; reason?: string }): void;
/** Suppresses the parent-level tool row for a child-owned call id. */
markChildToolCallId(callId: string): void;
}
@@ -66,6 +74,9 @@ type SubagentToolState = {
status: SubagentToolStatus;
output?: unknown;
errorText?: string;
+ label?: string;
+ /** The child's call started an agent task of its own. */
+ agentTask?: boolean;
};
export type SubagentRun = {
@@ -73,8 +84,8 @@ export type SubagentRun = {
childSessionId: string;
/** Parent turn that originated this dispatch; cancellation is scoped to it. */
parentTurnId: string;
- /** Parent completion is provisional; only a child boundary is authoritative. */
- status: "open" | "provisional" | "authoritative";
+ /** Only the child's own boundary ends the run: its last events can trail the parent's. */
+ done: boolean;
/** The parent session, whose client follows the child stream. */
parentSessionId: string;
/** The agent task's session, whose stream this run follows. */
@@ -96,6 +107,8 @@ export type SubagentRun = {
/** Monotonic counter for new section keys. */
nextSectionKey: number;
tools: Map<string, SubagentToolState>;
+ /** Child calls that started tasks: their `action.result` is only a receipt. */
+ taskCallIds: Set<string>;
};
export type SubagentStepUpdate = {
@@ -116,6 +129,10 @@ export type SubagentToolUpdate = {
status: SubagentToolStatus;
output?: unknown;
errorText?: string;
+ /** The tool's own label copy, when it defines one. */
+ label?: string;
+ /** The call started an agent task, so it reads as a delegation. */
+ agentTask?: boolean;
};
export interface SubagentPumpOptions {
@@ -154,7 +171,7 @@ export class SubagentPump {
this.#onToolCompleted = options.onToolCompleted;
}
- /** A call started or reached a task. A call to an agent task opens a section at once. */
+ /** A call started or reached a task. A call to an agent task starts following it at once. */
taskStarted(event: TaskStartedStreamEvent, parentSessionId: string | undefined): void {
const { callId, kind, taskId, turnId } = event.data;
if (kind !== "agent") return;
@@ -170,7 +187,7 @@ export class SubagentPump {
/**
* A run opened a session. The session an agent task opens is its agent's;
- * sessions other tools open have no section.
+ * sessions other tools open are not followed.
*/
agentStarted(started: AgentStartedStreamEvent, parentSessionId: string | undefined): void {
const { callId, taskId, turnId } = started.data;
@@ -182,12 +199,10 @@ export class SubagentPump {
}
/**
- * The moment a call is known to reach an agent, its section header
- * replaces the parent-level tool row (or its still-preparing
- * placeholder). Without this the placeholder is swept at the step boundary
- * and nothing shows until the child's first content arrives. A later
- * parent-stream translator may replay the call; re-entry only refreshes
- * the name.
+ * The moment a call is known to reach an agent, the pump follows the
+ * agent's session and claims the call id, so no parent-level tool row
+ * duplicates it. A later parent-stream translator may replay the call;
+ * re-entry only refreshes the name.
*/
#begin(input: {
readonly callId: string;
@@ -203,32 +218,23 @@ export class SubagentPump {
childSessionId: started.data.sessionId,
parentSessionId: input.parentSessionId,
parentTurnId: input.parentTurnId,
- status: "open",
+ done: false,
started,
steps: new Map(),
currentSectionKey: null,
nextSectionKey: 0,
tools: new Map(),
+ taskCallIds: new Set(),
});
} else {
existing.name = started.data.name;
}
this.#view?.markChildToolCallId(callId);
- if (existing !== undefined && existing.status !== "open") return;
- this.#view?.begin({ callId, name: started.data.name });
if (existing !== undefined) return;
+ this.#view?.begin({ callId });
this.#activateOrQueue(callId);
}
- /**
- * Parent completion is provisional because the child's final events can be
- * in flight on an independent connection. The pump remains open until the
- * child boundary supplies authoritative completion.
- */
- settle(callId: string): void {
- this.#finalizeRun(callId, false);
- }
-
abortAll(): void {
for (const controller of this.#pumps.values()) {
controller.abort();
@@ -245,7 +251,7 @@ export class SubagentPump {
settleCancelledTurn(turnId: string): void {
for (const [callId, run] of this.#runs) {
if (run.parentTurnId !== turnId) continue;
- this.#finalizeRun(callId, true);
+ this.#finalizeRun(callId);
this.#pumps.get(callId)?.abort();
this.#pumps.delete(callId);
}
@@ -263,7 +269,7 @@ export class SubagentPump {
*/
#activateOrQueue(callId: string): void {
const run = this.#runs.get(callId);
- if (run === undefined || run.status === "authoritative") return;
+ if (run === undefined || run.done) return;
const activeCallId = this.#activeChildCalls.get(run.childSessionId);
if (activeCallId === undefined) {
this.#activeChildCalls.set(run.childSessionId, callId);
@@ -281,7 +287,7 @@ export class SubagentPump {
const client = this.#client;
if (!client) return;
const run = this.#runs.get(callId);
- if (run === undefined || run.status === "authoritative") return;
+ if (run === undefined || run.done) return;
const controller = new AbortController();
this.#pumps.set(callId, controller);
@@ -305,12 +311,13 @@ export class SubagentPump {
// `session.waiting`. Keep following so the approved tool result
// can still update the nested view.
if (event.type === "session.waiting" && hasPendingChildApproval(run)) continue;
- this.#finalizeRun(callId, true);
+ this.#finalizeRun(callId);
return;
}
} catch {
- // Only a non-retryable failure ends the follower early; the call's
- // `task.settled` still settles the section.
+ // Only a non-retryable failure ends the follower early; nothing more
+ // will come, so the task's end need not wait for it.
+ if (!controller.signal.aborted) this.#view?.end({ callId });
} finally {
controller.abort();
if (this.#pumps.get(callId) === controller) this.#pumps.delete(callId);
@@ -326,6 +333,7 @@ export class SubagentPump {
toolName: string;
input: unknown;
status: SubagentToolState["status"];
+ label?: string;
},
): void {
const existing = run.tools.get(request.childCallId);
@@ -334,6 +342,7 @@ export class SubagentPump {
input: request.input,
status: request.status,
};
+ if (request.label !== undefined) tool.label = request.label;
if (existing) {
const terminal =
existing.status === "done" ||
@@ -365,28 +374,35 @@ export class SubagentPump {
run.tools.set(request.childCallId, tool);
}
this.#view?.markChildToolCallId(request.childCallId);
- this.#view?.upsertTool({
+ this.#emitTool(callId, run, request.childCallId, tool);
+ }
+
+ #emitTool(callId: string, run: SubagentRun, childCallId: string, tool: SubagentToolState): void {
+ const update: SubagentToolUpdate = {
callId,
subagentName: run.name,
- childCallId: request.childCallId,
+ childCallId,
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;
+ if (tool.label !== undefined) update.label = tool.label;
+ if (tool.agentTask === true) update.agentTask = true;
+ this.#view?.upsertTool(update);
}
/**
- * 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 call's
- * `task.settled` can both land here.
+ * Ends a run on the child's own boundary: re-emits a finalized snapshot
+ * for any still-streaming step, sweeps preparing ghosts, and releases the
+ * child session to the next queued call. `done` is the idempotency
+ * authority.
*/
- #finalizeRun(callId: string, authoritative: boolean): void {
+ #finalizeRun(callId: string): void {
const run = this.#runs.get(callId);
- if (!run || run.status === "authoritative") return;
- if (!authoritative && run.status === "provisional") return;
- run.status = authoritative ? "authoritative" : "provisional";
+ if (!run || run.done) return;
+ run.done = true;
for (const [sectionKey, step] of run.steps) {
if (!step.finalized) {
step.finalized = true;
@@ -402,8 +418,8 @@ export class SubagentPump {
}
run.currentSectionKey = null;
this.#sweepPreparingTools(callId, run);
- this.#view?.complete({ authoritative, callId });
- if (authoritative) this.#releaseChildSession(callId, run.childSessionId);
+ this.#view?.end({ callId });
+ this.#releaseChildSession(callId, run.childSessionId);
}
#releaseChildSession(callId: string, childSessionId: string): void {
@@ -419,7 +435,7 @@ export class SubagentPump {
while (remaining.length > 0) {
const nextCallId = remaining.shift()!;
const nextRun = this.#runs.get(nextCallId);
- if (nextRun === undefined || nextRun.status === "authoritative") continue;
+ if (nextRun === undefined || nextRun.done) continue;
if (remaining.length === 0) this.#queuedChildCalls.delete(childSessionId);
else this.#queuedChildCalls.set(childSessionId, remaining);
this.#activeChildCalls.set(childSessionId, nextCallId);
@@ -446,12 +462,6 @@ export class SubagentPump {
#applyChildEvent(callId: string, event: MessageStreamEvent): Promise<void> | undefined {
const run = this.#runs.get(callId);
if (!run) return;
- // Parent completion is provisional. Any delayed child event reopens the
- // mutable cohort until the child stream supplies its own boundary.
- if (run.status === "provisional") {
- run.status = "open";
- this.#view?.begin({ callId, name: run.name });
- }
const view = this.#view;
const emit = (key: number, step: SubagentChildStep) => {
@@ -513,18 +523,30 @@ export class SubagentPump {
// as a placeholder ghost in the section.
this.#sweepPreparingTools(callId, run);
break;
+ case "action.input.appended": {
+ const { callId: childCallId, toolName } = event.data;
+ if (run.tools.has(childCallId) || isTaskControlTool(toolName)) break;
+ this.#registerChildTool(callId, run, {
+ childCallId,
+ toolName,
+ input: undefined,
+ status: "preparing",
+ });
+ 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;
+ if (action.kind !== "tool-call" || isTaskControlTool(action.toolName)) continue;
this.#registerChildTool(callId, run, {
childCallId: action.callId,
toolName: action.toolName,
input: action.input,
status: "executing",
+ ...labelOf(event.data.presentation, action.callId),
});
}
break;
@@ -538,6 +560,7 @@ export class SubagentPump {
finalizeCurrent();
for (const request of event.data.requests) {
if (request.action.kind !== "tool-call") continue;
+ if (isTaskControlTool(request.action.toolName)) continue;
this.#registerChildTool(callId, run, {
childCallId: request.action.callId,
toolName: request.action.toolName,
@@ -550,8 +573,20 @@ export class SubagentPump {
case "action.result": {
const result = event.data.result;
if (result.kind !== "tool-result") break;
+ if (run.taskCallIds.has(result.callId)) break;
const tool = run.tools.get(result.callId);
if (!tool) break;
+ if (isTaskRetryRefusal(event)) {
+ run.tools.delete(result.callId);
+ view?.removeTool({
+ callId,
+ childCallId: result.callId,
+ reason: this.#formatActionResultError(event),
+ });
+ break;
+ }
+ const label = labelOf(event.data.presentation, result.callId).label;
+ if (label !== undefined) tool.label = label;
switch (event.data.status) {
case "completed":
tool.status = "done";
@@ -566,22 +601,42 @@ export class SubagentPump {
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);
+ this.#emitTool(callId, run, result.callId, tool);
if (event.data.status === "completed") {
return this.#onToolCompleted?.(run.name, tool.toolName, result.output);
}
break;
}
+ case "task.started": {
+ // The child's call started a task of its own: its result arrives
+ // with `task.settled`, and an agent task reads as a delegation.
+ run.taskCallIds.add(event.data.callId);
+ const tool = run.tools.get(event.data.callId);
+ if (tool === undefined || event.data.kind !== "agent") break;
+ tool.agentTask = true;
+ this.#emitTool(callId, run, event.data.callId, tool);
+ break;
+ }
+ case "task.settled": {
+ const tool = run.tools.get(event.data.callId);
+ if (tool === undefined) break;
+ switch (event.data.status) {
+ case "completed":
+ tool.status = "done";
+ if (event.data.output !== undefined) tool.output = event.data.output;
+ break;
+ case "failed":
+ tool.status = "failed";
+ tool.errorText = event.data.error?.message ?? "Failed.";
+ break;
+ case "cancelled":
+ tool.status = "rejected";
+ tool.errorText = "Stopped.";
+ break;
+ }
+ this.#emitTool(callId, run, event.data.callId, tool);
+ break;
+ }
default:
// Other events (session.*, turn.*, step.started, etc.) carry no
// visible text — ignore.
@@ -590,6 +645,14 @@ export class SubagentPump {
}
}
+function labelOf(
+ presentation: ActionPresentationByCallId | undefined,
+ callId: string,
+): { label?: string } {
+ const label = presentation?.[callId]?.label;
+ return label === undefined ? {} : { label };
+}
+
function hasPendingChildApproval(run: SubagentRun): boolean {
return [...run.tools.values()].some((tool) => tool.status === "approval-requested");
}
diff --git a/packages/eve/src/cli/dev/tui/subagent-section.test.ts b/packages/eve/src/cli/dev/tui/subagent-section.test.ts
deleted file mode 100644
index 2190d5ffb..000000000
--- a/packages/eve/src/cli/dev/tui/subagent-section.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-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: "Run pnpm lint", subtitle: "", toolName: "bash" }),
- {
- 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/task-activity.ts b/packages/eve/src/cli/dev/tui/task-activity.ts
new file mode 100644
index 000000000..743d04c04
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/task-activity.ts
@@ -0,0 +1,159 @@
+/**
+ * The tasks a turn has working: agents and tools that keep running while the
+ * turn goes on. The transcript only ever grows at its end, so a task writes
+ * one line when it starts and one when it ends; what it is doing in between
+ * lives here and renders in the fixed task panel above the prompt, the one
+ * region that redraws in place.
+ */
+
+import type { Block } from "./blocks.js";
+import type { Theme } from "./theme.js";
+import { formatTurnDuration } from "./stream-format.js";
+import { TOOL_COLUMN_LEAD } from "./rail.js";
+import { truncate } from "./tool-format.js";
+import { clipVisible, visibleLength } from "#cli/ui/terminal-text.js";
+
+export type TaskKind = "agent" | "tool";
+
+export interface TaskEntry {
+ readonly callId: string;
+ readonly kind: TaskKind;
+ /** Display name, unique among working tasks. */
+ readonly name: string;
+ readonly toolName: string;
+ readonly input: unknown;
+ readonly label: string | undefined;
+ readonly startedAtMs: number;
+ /** An agent's latest words or thinking, one line. */
+ step?: string;
+ /** Settled, waiting only for the agent's own last events. */
+ finishing?: boolean;
+ /** An agent's own tool calls, newest last, for its activity and summary. */
+ readonly childTools: Map<string, Block>;
+}
+
+/** The panel shows this many tasks; the rest collapse into one counted row. */
+const maxPanelRows = 4;
+
+export class TaskActivity {
+ readonly #entries = new Map<string, TaskEntry>();
+
+ start(input: {
+ readonly callId: string;
+ readonly kind: TaskKind;
+ readonly baseName: string;
+ readonly toolName: string;
+ readonly input: unknown;
+ readonly label: string | undefined;
+ readonly nowMs: number;
+ }): TaskEntry {
+ const entry: TaskEntry = {
+ callId: input.callId,
+ kind: input.kind,
+ name: this.#uniqueName(input.baseName),
+ toolName: input.toolName,
+ input: input.input,
+ label: input.label,
+ startedAtMs: input.nowMs,
+ childTools: new Map(),
+ };
+ this.#entries.set(input.callId, entry);
+ return entry;
+ }
+
+ get(callId: string): TaskEntry | undefined {
+ return this.#entries.get(callId);
+ }
+
+ /** Removes and returns a task that ended. */
+ finish(callId: string): TaskEntry | undefined {
+ const entry = this.#entries.get(callId);
+ this.#entries.delete(callId);
+ return entry;
+ }
+
+ working(): readonly TaskEntry[] {
+ return [...this.#entries.values()];
+ }
+
+ clear(): void {
+ this.#entries.clear();
+ }
+
+ /** Parallel calls to one agent read `researcher`, `researcher #2`, …; a name is never renamed. */
+ #uniqueName(baseName: string): string {
+ const taken = new Set([...this.#entries.values()].map((entry) => entry.name));
+ if (!taken.has(baseName)) return baseName;
+ for (let ordinal = 2; ; ordinal += 1) {
+ const candidate = `${baseName} #${String(ordinal)}`;
+ if (!taken.has(candidate)) return candidate;
+ }
+ }
+}
+
+/** Joins the working tasks' names for the turn bar: `Waiting for researcher and reviewer`. */
+export function waitingLabel(entries: readonly TaskEntry[]): string {
+ const names = entries.map((entry) => entry.name);
+ if (names.length === 1) return `Waiting for ${names[0]!}`;
+ if (names.length === 2) return `Waiting for ${names[0]!} and ${names[1]!}`;
+ return `Waiting for ${String(names.length)} tasks`;
+}
+
+/** What a working task is doing right now, in one short line. */
+function currentActivity(entry: TaskEntry): { text: string; attention: boolean } {
+ if (entry.finishing === true) return { text: "Finishing", attention: false };
+ const tools = [...entry.childTools.values()];
+ const awaiting = tools.findLast((tool) => tool.status === "approval");
+ if (awaiting !== undefined) {
+ return { text: `Needs your approval: ${awaiting.title ?? "tool"}`, attention: true };
+ }
+ const running = tools.findLast((tool) => tool.status === "running");
+ if (running !== undefined) return { text: running.title ?? "Working", attention: false };
+ if (entry.step !== undefined) return { text: entry.step, attention: false };
+ return { text: entry.kind === "agent" ? "Starting" : "Working", attention: false };
+}
+
+/**
+ * One row per working task — mark, name, current activity, elapsed time —
+ * capped so a wide fan-out cannot push the prompt off screen.
+ */
+export function renderTaskPanelRows(
+ entries: readonly TaskEntry[],
+ options: {
+ readonly width: number;
+ readonly theme: Theme;
+ readonly nowMs: number;
+ readonly pulse: string;
+ },
+): string[] {
+ const { width, theme, nowMs } = options;
+ const c = theme.colors;
+ const shown = entries.length > maxPanelRows ? entries.slice(0, maxPanelRows - 1) : entries;
+ const nameWidth = Math.min(24, Math.max(...shown.map((entry) => visibleLength(entry.name)), 0));
+ const rows = shown.map((entry) => {
+ const mark =
+ options.pulse.trim().length > 0
+ ? c.orange(theme.glyph.subagent)
+ : c.dim(theme.glyph.subagent);
+ const name = truncate(entry.name, nameWidth);
+ const padded = name + " ".repeat(Math.max(0, nameWidth - visibleLength(name)));
+ const elapsed = formatTurnDuration(nowMs - entry.startedAtMs);
+ const lead = `${TOOL_COLUMN_LEAD}${mark} ${padded} `;
+ const budget = width - visibleLength(lead) - elapsed.length - 2;
+ const activity = currentActivity(entry);
+ const text = budget >= 4 ? truncate(activity.text, budget) : "";
+ const color = activity.attention ? c.yellow : c.dim;
+ const gap = Math.max(1, width - visibleLength(lead) - visibleLength(text) - elapsed.length);
+ return clipVisible(`${lead}${color(text)}${" ".repeat(gap)}${c.dim(elapsed)}`, width);
+ });
+ const hidden = entries.length - shown.length;
+ if (hidden > 0) {
+ rows.push(
+ clipVisible(
+ `${TOOL_COLUMN_LEAD}${c.dim(`${theme.glyph.ellipsis} ${String(hidden)} more working`)}`,
+ width,
+ ),
+ );
+ }
+ return rows;
+}
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 03b61b4f8..ba6397d65 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -14,6 +14,7 @@ import {
import type { AgentTUIStreamEvent, AgentTUIStreamResult, SubagentToolUpdate } from "./runner.js";
import { PROMPT_COMMANDS, promptCommandsFor } from "./prompt-commands.js";
import { TerminalRenderer } from "./terminal-renderer.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
import { MockScreen, MockUserInput } from "./test/mock-terminal.js";
function streamOf(events: AgentTUIStreamEvent[]): AgentTUIStreamResult {
@@ -570,33 +571,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
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;
@@ -993,7 +967,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
it("settles an authorization block when its callback arrives in a later stream pass", async () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "research", name: "researcher" });
renderer.upsertConnectionAuth({
name: "linear",
description: "Authorization required for linear",
@@ -1088,6 +1061,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
{ type: "tool-result", toolCallId: "c1", output: { text: `done ${c1Osc}` } },
{ type: "assistant-delta", id: "t1", delta: `safe assistant ${osc}` },
{ type: "assistant-complete", id: "t1" },
+ { type: "task-started", toolCallId: "s1", kind: "agent", toolName: `researcher${osc}` },
{ type: "error", errorText: `session failed ${dcs}`, detail: `detail ${osc}` },
{ type: "finish" },
]),
@@ -1128,239 +1102,343 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("nests subagent steps and tools under a subagent header", async () => {
- const { screen, renderer } = makeRenderer();
- // The runner makes the renderer interactive via the startup header before
- // any subagent activity arrives.
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.upsertSubagentStep({
- callId: "s1",
- subagentName: "researcher",
- sectionKey: 0,
- reasoning: "comparing cities",
- message: "Looking into NYC.",
- finalized: true,
- });
- renderer.upsertSubagentTool({
- callId: "s1",
- subagentName: "researcher",
- childCallId: "cc1",
- toolName: "get_weather",
- input: { city: "NYC" },
- status: "done",
- output: { tempF: 61 },
- });
-
- const snapshot = screen.snapshot();
- 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(
- {
+ describe("tasks", () => {
+ function taskStream() {
+ let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const result: AgentTUIStreamResult = {
events: new ReadableStream<AgentTUIStreamEvent>({
- start(controller) {
- streamController = controller;
+ start(next) {
+ controller = next;
},
}),
+ };
+ return {
+ result,
+ push: (...events: AgentTUIStreamEvent[]) => {
+ for (const event of events) controller?.enqueue(event);
+ },
+ close: () => controller?.close(),
+ };
+ }
+
+ const delegate: AgentTUIStreamEvent[] = [
+ { type: "step-start" },
+ {
+ type: "tool-call",
+ toolCallId: "call-r",
+ toolName: "researcher",
+ input: { message: "Find the Q3 revenue numbers\nand cite sources" },
},
- { continueSession: true },
- );
+ { type: "task-started", toolCallId: "call-r", kind: "agent", toolName: "researcher" },
+ { type: "assistant-delta", id: "t1", delta: "I asked the researcher to dig in." },
+ { type: "assistant-complete", id: "t1" },
+ { type: "step-finish" },
+ ];
- // The model commits to the `agent` tool; its input streams.
- streamController?.enqueue({
- type: "tool-call-preparing",
- toolCallId: "sub1",
- toolName: "agent",
+ const childTool = (status: SubagentToolUpdate["status"], input?: unknown) => {
+ const update: SubagentToolUpdate = {
+ callId: "call-r",
+ subagentName: "researcher",
+ childCallId: "fetch-1",
+ toolName: "web_fetch",
+ input,
+ status,
+ };
+ if (status === "done") update.output = "<html>";
+ return update;
+ };
+
+ it("writes the transcript once while the panel shows what each task is doing", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const stream = taskStream();
+ const rendering = renderer.renderStream(stream.result, { continueSession: true });
+
+ stream.push(...delegate);
+ await screen.waitForText("Waiting for researcher");
+ // The call row became the start line in place; the model-facing
+ // delegation row is gone.
+ expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");
+ expect(screen.snapshot()).not.toContain("Delegate");
+ const writtenBeforeActivity = screen.rawOutput().length;
+
+ renderer.upsertSubagentTool(childTool("preparing"));
+ expect(screen.snapshot()).toMatch(/※ researcher\s+Fetch …/u);
+ renderer.upsertSubagentTool(childTool("executing", { url: "https://ir.example" }));
+ expect(screen.snapshot()).toMatch(/※ researcher\s+Fetch https:\/\/ir\.example/u);
+ renderer.upsertSubagentTool(childTool("done", { url: "https://ir.example" }));
+
+ stream.push({ type: "task-settled", toolCallId: "call-r", status: "completed" });
+ await screen.waitForText("✓ researcher");
+ stream.close();
+ await rendering;
+ renderer.shutdown();
+
+ // The start line and the reply were already in scrollback: live rows
+ // repaint on every update, but nothing the agent did rewrote them.
+ const writtenSince = stripAnsi(screen.rawOutput().slice(writtenBeforeActivity));
+ expect(writtenSince).not.toContain("Find the Q3 revenue numbers");
+ expect(writtenSince).not.toContain("I asked the researcher to dig in.");
+ expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s · Fetched 1 URL/u);
});
- await screen.waitForText("Delegate");
- // The agent's section supersedes the tool-call placeholder once agent.started arrives.
- renderer.markChildToolCallId("sub1");
- renderer.beginSubagent({ callId: "sub1", name: "agent" });
- await screen.waitForText("※ subagent(self)");
+ it("waits for an agent's own last events before writing its end line", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const stream = taskStream();
+ const rendering = renderer.renderStream(stream.result, { continueSession: true });
+ stream.push(...delegate);
+ await screen.waitForText("Waiting for researcher");
+ renderer.subagents.begin({ callId: "call-r" });
+
+ stream.push({ type: "task-settled", toolCallId: "call-r", status: "completed" });
+ await screen.waitForText("Finishing");
+ expect(screen.snapshot()).not.toContain("✓ researcher");
+
+ // The agent's last call reaches the TUI after its parent settled the task.
+ renderer.upsertSubagentTool(childTool("done", { url: "https://ir.example" }));
+ renderer.subagents.end({ callId: "call-r" });
+ expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s · Fetched 1 URL/u);
+
+ stream.close();
+ await rendering;
+ renderer.shutdown();
+ });
- const snapshot = screen.snapshot();
- expect(snapshot).toContain("※ subagent(self)");
- expect(snapshot).not.toContain("Delegate");
+ it("writes a waiting end line once the turn's stream ends", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ renderer.subagents.begin({ callId: "call-r" });
+ await renderer.renderStream(
+ streamOf([
+ ...delegate,
+ { type: "task-settled", toolCallId: "call-r", status: "completed" },
+ { type: "finish" },
+ ]),
+ { continueSession: true },
+ );
+ renderer.shutdown();
- streamController?.close();
- await rendering;
- renderer.shutdown();
+ expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s/u);
+ expect(screen.snapshot()).not.toContain("Finishing");
+ });
- // The step-boundary ghost sweep must not take the section with it.
- expect(screen.snapshot()).toContain("※ subagent(self)");
- });
+ it("closes working tasks before a session restart", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {
+ continueSession: true,
+ });
+ renderer.renderSessionBoundary();
+ renderer.shutdown();
- it("windows subagent children by latest activity, not announce order", () => {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const snapshot = screen.snapshot();
+ const stopped = snapshot.indexOf("▪ researcher stopped");
+ expect(stopped).toBeGreaterThan(-1);
+ expect(stopped).toBeLessThan(snapshot.indexOf("Session restarted"));
+ });
- // 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");
+ it("names an agent task's request even when tool rows are hidden", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const renderer = new TerminalRenderer({
+ input: new MockUserInput(),
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ tools: "hidden",
+ });
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {
+ continueSession: true,
+ });
+ renderer.shutdown();
- 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();
- });
+ expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");
+ });
- 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,
+ it("logs why an agent's own call was refused for its model to retry", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const stub = stubDiagnostics();
+ const renderer = new TerminalRenderer({
+ input: new MockUserInput(),
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+ await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {
+ continueSession: true,
+ });
+ renderer.upsertSubagentTool(childTool("executing", { url: "https://ir.example" }));
+ renderer.removeSubagentTool({
+ callId: "call-r",
+ childCallId: "fetch-1",
+ reason: "8 tasks are already working",
+ });
+ renderer.shutdown();
+
+ expect(stub.append).toHaveBeenCalledWith({
+ source: "tool",
+ summary: "web_fetch was refused for the model to retry",
+ detail: "8 tasks are already working",
+ });
});
- renderer.upsertSubagentTool({
- callId: "s1",
- subagentName: "echo-marker",
- childCallId: "cc1",
- toolName: "web_fetch",
- input: { url: "https://one.example" },
- status: "done",
- output: { ok: true },
+
+ it("ends a stopped or failed task with what happened, not Done", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ await renderer.renderStream(
+ streamOf([
+ ...delegate,
+ { type: "task-started", toolCallId: "call-d", kind: "tool", toolName: "deploy" },
+ { type: "task-settled", toolCallId: "call-r", status: "cancelled" },
+ {
+ type: "task-settled",
+ toolCallId: "call-d",
+ status: "failed",
+ errorText: "Preview build failed\nstack…",
+ },
+ { type: "finish" },
+ ]),
+ { continueSession: true },
+ );
+ renderer.shutdown();
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("▪ researcher stopped");
+ expect(snapshot).toContain("⨯ deploy failed · Preview build failed");
+ expect(snapshot).not.toContain("stack…");
});
- // 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");
+ it("reads a cancelled turn's unfinished tasks as stopped", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ await renderer.renderStream(
+ streamOf([...delegate, { type: "turn-cancelled" }, { type: "finish" }]),
+ { continueSession: true },
+ );
+ renderer.shutdown();
- renderer.completeSubagent({ authoritative: true, 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();
- });
+ expect(screen.snapshot()).toContain("▪ researcher stopped");
+ expect(screen.snapshot()).not.toContain("Waiting for researcher");
+ });
- it("keeps parent completion provisional until delayed child output reaches its boundary", async () => {
- const { screen, input, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "s1", name: "researcher" });
- renderer.upsertSubagentStep({
- callId: "s1",
- subagentName: "researcher",
- sectionKey: 0,
- reasoning: "",
- message: "parent-visible output",
- finalized: true,
+ it("tells parallel calls to one agent apart without renaming the first", async () => {
+ const { screen, renderer } = makeRenderer();
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const stream = taskStream();
+ const rendering = renderer.renderStream(stream.result, { continueSession: true });
+ stream.push(...delegate, {
+ type: "task-started",
+ toolCallId: "call-r2",
+ kind: "agent",
+ toolName: "researcher",
+ });
+ await screen.waitForText("Waiting for researcher and researcher #2");
+ stream.close();
+ await rendering;
+ renderer.shutdown();
+
+ expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");
+ expect(screen.snapshot()).toContain("※ researcher #2");
});
- renderer.completeSubagent({ authoritative: false, callId: "s1" });
- await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });
- renderer.beginSubagent({ callId: "s1", name: "researcher" });
- renderer.upsertSubagentStep({
- callId: "s1",
- subagentName: "researcher",
- sectionKey: 1,
- reasoning: "",
- message: "delayed child output",
- finalized: true,
+ it("writes an agent's finished messages under --subagents full", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const renderer = new TerminalRenderer({
+ input: new MockUserInput(),
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ subagents: "full",
+ });
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const stream = taskStream();
+ const rendering = renderer.renderStream(stream.result, { continueSession: true });
+ stream.push(...delegate);
+ await screen.waitForText("Waiting for researcher");
+
+ const step = {
+ callId: "call-r",
+ subagentName: "researcher",
+ sectionKey: 0,
+ reasoning: "",
+ message: "Revenue grew 12% year over year.",
+ };
+ renderer.upsertSubagentStep({ ...step, finalized: false });
+ renderer.upsertSubagentStep({ ...step, finalized: true });
+ renderer.upsertSubagentStep({ ...step, finalized: true });
+ stream.close();
+ await rendering;
+ renderer.shutdown();
+
+ expect(screen.snapshot()).toContain("※ researcher\n │ Revenue grew 12% year over year.");
+ expect(countOccurrences(stripAnsi(screen.rawOutput()), "│ Revenue grew 12%")).toBe(1);
});
- expect(screen.snapshot()).toContain("delayed child output");
- expect(screen.snapshot()).not.toContain("└ Done");
+ it("shows neither lines nor panel rows for agents under --subagents hidden", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const renderer = new TerminalRenderer({
+ input: new MockUserInput(),
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ subagents: "hidden",
+ });
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {
+ continueSession: true,
+ });
+ renderer.shutdown();
- renderer.completeSubagent({ authoritative: true, callId: "s1" });
- const outputAfterCommit = screen.rawOutput().length;
- const prompt = renderer.readPrompt();
- input.type("next");
- expect(screen.rawOutput().slice(outputAfterCommit)).not.toContain("subagent(researcher)");
- input.enter();
- await prompt;
- renderer.shutdown();
- });
+ expect(screen.snapshot()).not.toContain("※");
+ expect(screen.snapshot()).not.toContain("Find the Q3");
+ });
- 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();
+ it("leaves no trace of a call refused for the model to retry", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ { type: "tool-call", toolCallId: "c1", toolName: "deploy", input: { env: "preview" } },
+ { type: "tool-withdrawn", toolCallId: "c1", reason: "8 tasks are already working" },
+ { type: "assistant-delta", id: "t1", delta: "Queued the deploy." },
+ { type: "assistant-complete", id: "t1" },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "deploy", 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");
- });
+ expect(screen.snapshot()).not.toContain("deploy ");
+ expect(screen.snapshot()).not.toContain("already working");
+ });
- 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();
+ it("titles a tool by its own label instead of its raw arguments", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "deploy",
+ input: { project: "storefront", environment: "production" },
+ label: "Deploy storefront to production",
+ },
+ {
+ type: "tool-result",
+ toolCallId: "c1",
+ output: { url: "https://storefront.example" },
+ label: "Deployed storefront",
+ },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "ship it", 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");
+ expect(screen.snapshot()).toContain("Deployed storefront");
+ expect(screen.snapshot()).not.toContain("environment=");
+ });
});
it("commits the one-line session boundary", () => {
@@ -4437,7 +4515,6 @@ describe("TerminalRenderer setup flow session", () => {
try {
const { screen, renderer } = makeRenderer();
renderer.setupFlow.begin("Add integration");
- renderer.beginSubagent({ callId: "research", name: "researcher" });
let release!: () => void;
const inherited = renderer.setupFlow.withInheritedStdio(
() => new Promise<void>((resolve) => (release = resolve)),
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index b8aba7299..d979e6f8e 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -83,6 +83,7 @@ import {
import type {
AssistantResponseStatsMode,
LogDisplayMode,
+ SubagentDisplayMode,
TerminalPartDisplayMode,
} from "./types.js";
import type { AgentInfoResult } from "#client/index.js";
@@ -141,6 +142,7 @@ import {
import type { VercelStatusSnapshot } from "./vercel-status.js";
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
import {
+ agentDisplayName,
isPanelRoutedTool,
presentPreparingTool,
presentTool,
@@ -149,7 +151,13 @@ import {
type ToolPresentationContext,
} from "./tool-presentation.js";
import { FileContentCache } from "./file-content-cache.js";
-import { groupToolBlocksForDisplay } from "./tool-block-groups.js";
+import { groupToolBlocksForDisplay, summarizeChildTools } from "./tool-block-groups.js";
+import {
+ renderTaskPanelRows,
+ TaskActivity,
+ waitingLabel,
+ type TaskEntry,
+} from "./task-activity.js";
import { renderQuestionChoices, renderQuestionPanel } from "./question-panel.js";
import { TurnClock } from "./turn-clock.js";
import { MessageQueue, renderMessageQueueRows } from "./message-queue.js";
@@ -280,7 +288,7 @@ type TerminalRendererOptions = {
output?: TerminalOutput;
tools?: TerminalPartDisplayMode;
reasoning?: TerminalPartDisplayMode;
- subagents?: TerminalPartDisplayMode;
+ subagents?: SubagentDisplayMode;
connectionAuth?: TerminalPartDisplayMode;
assistantResponseStats?: AssistantResponseStatsMode;
contextSize?: number;
@@ -318,20 +326,37 @@ type RenderTurnState = {
reasoning: Map<string, string>;
tools: Map<string, NativeToolState>;
modelActivity: "Thinking" | "Generating";
+ /** True between a model step's start and finish. */
+ inStep: boolean;
runningTools: Set<string>;
cancelled: boolean;
restoreCancelledPrompt: boolean;
};
-function turnActivityLabel(state: RenderTurnState | undefined): string {
+/**
+ * Between model steps with tasks working, the turn is waiting on them — the
+ * model called `task_wait` or ended its reply — so the bar names the tasks.
+ */
+function turnActivityLabel(
+ state: RenderTurnState | undefined,
+ tasks: readonly TaskEntry[],
+): string {
if (state === undefined) return "Thinking";
- return state.runningTools.size > 0 ? "Running" : state.modelActivity;
+ if (state.runningTools.size > 0) return "Running";
+ if (!state.inStep && tasks.length > 0) return waitingLabel(tasks);
+ return state.modelActivity;
}
function updateTurnActivity(state: RenderTurnState, event: AgentTUIStreamEvent): void {
switch (event.type) {
- case "turn-start":
case "step-start":
+ state.inStep = true;
+ state.modelActivity = "Thinking";
+ break;
+ case "step-finish":
+ state.inStep = false;
+ break;
+ case "turn-start":
case "reasoning-delta":
state.modelActivity = "Thinking";
break;
@@ -349,6 +374,9 @@ function updateTurnActivity(state: RenderTurnState, event: AgentTUIStreamEvent):
case "tool-result":
case "tool-error":
case "tool-rejected":
+ case "tool-withdrawn":
+ // A task keeps working past its call; the task panel tracks it instead.
+ case "task-started":
state.runningTools.delete(event.toolCallId);
break;
}
@@ -363,6 +391,8 @@ type NativeToolState = {
preparing?: boolean;
output?: unknown;
errorText?: string;
+ label?: string | undefined;
+ completeLabel?: string | undefined;
};
const caretBlinkMs = 500;
@@ -404,7 +434,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #renderMarkdown: boolean;
readonly #tools: TerminalPartDisplayMode;
readonly #reasoning: TerminalPartDisplayMode;
- readonly #subagents: TerminalPartDisplayMode;
+ readonly #subagents: SubagentDisplayMode;
readonly #connectionAuth: TerminalPartDisplayMode;
readonly #assistantResponseStats: AssistantResponseStatsMode;
readonly #captureForeignOutput: boolean;
@@ -433,13 +463,22 @@ export class TerminalRenderer implements AgentTUIRenderer {
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[]>();
- /** Parent-completed sections retained as mutable until the child boundary. */
- readonly #provisionalSubagentCallIds = new Set<string>();
+ /** Working tasks, shown in the task panel between their start and end lines. */
+ readonly #tasks = new TaskActivity();
+ /** An agent's own rows already written under `--subagents full`. */
+ readonly #writtenAgentRows = new Set<string>();
+ /** Calls whose start line is written; a replayed start must not write another. */
+ readonly #startedTaskCallIds = new Set<string>();
+ /** Agent calls whose own stream the pump follows, and those whose stream ended. */
+ readonly #followedAgentCallIds = new Set<string>();
+ readonly #endedAgentCallIds = new Set<string>();
+ /** Settled agent tasks whose end line waits for the agent's own end. */
+ readonly #pendingTaskEnds = new Map<
+ string,
+ { event: TaskSettledEvent; endedAtMs: number; timer: ReturnType<typeof setTimeout> }
+ >();
/** Session-local file contents, so write blocks can render real diffs. */
readonly #fileContents = new FileContentCache();
- readonly #subagentHeaders = new Set<string>();
#agentHeader?: AgentHeaderOptions;
#initialPromptPlaceholder = "Send a message…";
#startupPhase?: "starting" | "connecting" | "updating";
@@ -676,7 +715,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#renderMarkdown = options?.renderMarkdown ?? detectMarkdownRendering();
this.#tools = options?.tools ?? "auto-collapsed";
this.#reasoning = options?.reasoning ?? "auto-collapsed";
- this.#subagents = options?.subagents ?? "auto-collapsed";
+ this.#subagents = options?.subagents ?? "collapsed";
this.#connectionAuth = options?.connectionAuth ?? "full";
this.#assistantResponseStats = options?.assistantResponseStats ?? defaultAssistantResponseStats;
this.#contextSize = options?.contextSize;
@@ -868,7 +907,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
async readPrompt(options?: AgentTUISessionOptions): Promise<string> {
this.#start(options);
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
this.#commitTurnStats();
this.#inputActive = true;
this.#promptPlaceholderActive = true;
@@ -1162,6 +1201,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
reasoning: new Map(),
tools: new Map(),
modelActivity: "Thinking",
+ inStep: false,
runningTools: new Set(),
cancelled: false,
restoreCancelledPrompt: true,
@@ -1210,7 +1250,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (this.#turnIndicator.kind === "waiting") {
this.#turnIndicator = { kind: "idle" };
}
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
this.#status = completedTurnStatus({
interrupted: this.#interrupted,
cancelled: this.#turnCancelled,
@@ -1222,9 +1262,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
// An interrupted or cancelled 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 || turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);
+ this.#flushTaskEnds();
+ if (this.#interrupted || turnState.cancelled) {
+ this.#settleCurrentTurnToolBlocks(turnState);
+ this.#stopWorkingTasks();
+ }
this.#finalizeAllBlocks();
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
this.#diagnostics?.reportStats();
this.#paint();
@@ -1253,6 +1297,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
reasoning: new Map(),
tools: new Map(),
modelActivity: "Thinking",
+ inStep: false,
runningTools: new Set(),
cancelled: false,
restoreCancelledPrompt: false,
@@ -1274,9 +1319,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
} finally {
this.#sweepPreparingToolBlocks(turnState);
- if (turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);
+ this.#flushTaskEnds();
+ if (turnState.cancelled) {
+ this.#settleCurrentTurnToolBlocks(turnState);
+ this.#stopWorkingTasks();
+ }
this.#finalizeAllBlocks();
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
this.#diagnostics?.reportStats();
this.#paint();
}
@@ -1661,6 +1710,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
});
}
+ /**
+ * An agent's words or thinking. The task panel shows the latest line;
+ * `--subagents full` also writes each finished message, in order.
+ */
upsertSubagentStep(update: SubagentStepUpdate): void {
this.#diagnostics?.recordSubagentDispatch(update.callId);
if (this.#subagents === "hidden") return;
@@ -1668,32 +1721,39 @@ export class TerminalRenderer implements AgentTUIRenderer {
const messageText = stripTerminalControls(update.message ?? "").trim();
if (reasoningText.length === 0 && messageText.length === 0) return;
- this.#ensureSubagentHeader(update.callId, update.subagentName);
- if (this.#subagents === "collapsed") {
- this.#paint();
- return;
+ const entry = this.#tasks.get(update.callId);
+ if (entry !== undefined) {
+ entry.step = firstLine(messageText) ?? "Thinking";
+ }
+ if (this.#subagents === "full" && update.finalized) {
+ const id = subagentStepRowId(update.callId, update.sectionKey);
+ if (!this.#writtenAgentRows.has(id)) {
+ this.#writtenAgentRows.add(id);
+ const block: Block = {
+ kind: "subagent-step",
+ subagentCallId: update.callId,
+ agentName: entry?.name ?? agentDisplayName(stripTerminalControls(update.subagentName)),
+ depth: 1,
+ body: messageText,
+ live: false,
+ };
+ if (reasoningText.length > 0) block.reasoning = reasoningText;
+ this.#pushBlock(block);
+ }
}
-
- this.#upsertSubagentBlock({
- 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();
}
+ /**
+ * An agent's own tool call. The task panel shows what is running and counts
+ * finished calls for the task's end line; `--subagents full` also writes each
+ * finished call, in order.
+ */
upsertSubagentTool(update: SubagentToolUpdate): void {
this.#diagnostics?.recordSubagentDispatch(update.callId);
if (update.status === "failed" && update.errorText !== undefined) {
- // Captured before the display guards: hidden or collapsed subagent
- // views must not keep tool failures out of the diagnostic log.
+ // Captured before the display guards: a hidden agent view must not
+ // keep tool failures out of the diagnostic log.
this.#diagnostics?.append({
source: "tool",
summary: `${update.toolName} failed (subagent ${update.subagentName})`,
@@ -1701,38 +1761,32 @@ export class TerminalRenderer implements AgentTUIRenderer {
});
}
if (this.#subagents === "hidden") return;
- this.#ensureSubagentHeader(update.callId, update.subagentName);
- if (this.#subagents === "collapsed") {
- this.#paint();
- return;
- }
const status = subagentToolStatus(update.status);
// Subagents reuse the session's sandbox, so their reads and writes feed
// the same file-content cache and their write blocks diff the same way.
+ const context = this.#toolPresentationContext({
+ input: update.input,
+ output: update.output,
+ toolCallId: update.childCallId,
+ toolName: update.toolName,
+ label: update.label,
+ agentTask: update.agentTask,
+ });
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,
- }),
- );
+ ? presentPreparingTool(update.toolName, context)
+ : presentTool(update.toolName, update.input, context);
+ const entry = this.#tasks.get(update.callId);
const block: Block = {
- id: subagentToolSectionId(update.callId, update.childCallId),
kind: "subagent-tool",
subagentCallId: update.callId,
+ agentName: entry?.name ?? agentDisplayName(stripTerminalControls(update.subagentName)),
depth: 1,
title: stripTerminalControls(presentation.title),
subtitle: stripTerminalControls(presentation.subtitle),
status,
- live: status === "running" || status === "approval",
- expanded: this.#subagents === "full",
+ live: false,
toolName: update.toolName,
toolGroup: presentation.group,
toolInput: update.input,
@@ -1750,27 +1804,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
} else if (update.errorText !== undefined) {
block.result = stripTerminalControls(update.errorText);
}
- this.#upsertSubagentBlock(block);
- this.#syncSubagentChildLiveness(update.callId);
- this.#paint();
- }
+ entry?.childTools.set(update.childCallId, block);
- /**
- * 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) })),
- );
+ const settled = status === "done" || status === "error" || status === "denied";
+ const id = subagentToolRowId(update.callId, update.childCallId);
+ if (this.#subagents === "full" && settled && !this.#writtenAgentRows.has(id)) {
+ this.#writtenAgentRows.add(id);
+ this.#pushBlock(block);
+ }
+ this.#paint();
}
- removeSubagentTool(update: { callId: string; childCallId: string }): void {
- this.#removeBlock(subagentToolSectionId(update.callId, update.childCallId));
+ removeSubagentTool(update: { callId: string; childCallId: string; reason?: string }): void {
+ const childTools = this.#tasks.get(update.callId)?.childTools;
+ if (update.reason !== undefined) {
+ // The same record a refused top-level call leaves; see `tool-withdrawn`.
+ const toolName = childTools?.get(update.childCallId)?.toolName ?? update.childCallId;
+ this.#diagnostics?.append({
+ source: "tool",
+ summary: `${toolName} was refused for the model to retry`,
+ detail: update.reason,
+ });
+ }
+ childTools?.delete(update.childCallId);
this.#paint();
}
@@ -1779,57 +1835,19 @@ export class TerminalRenderer implements AgentTUIRenderer {
* public methods below are its implementation and the unit tests' seam.
*/
readonly subagents: SubagentView = {
- begin: (update) => this.beginSubagent(update),
+ begin: ({ callId }) => {
+ this.#followedAgentCallIds.add(callId);
+ },
+ end: ({ callId }) => {
+ this.#endedAgentCallIds.add(callId);
+ this.#flushTaskEnd(callId);
+ },
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 !== undefined) {
- if (header.status === "done") delete header.status;
- header.live = true;
- }
- this.#provisionalSubagentCallIds.delete(update.callId);
- 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: { authoritative: boolean; callId: string }): void {
- const header = this.#blockById.get(subagentHeaderId(update.callId));
- if (header === undefined) return;
- header.status = "done";
- if (update.authoritative) {
- this.#provisionalSubagentCallIds.delete(update.callId);
- for (const block of this.#blocks) {
- if (block.subagentCallId === update.callId) block.live = false;
- }
- } else {
- this.#provisionalSubagentCallIds.add(update.callId);
- for (const block of this.#blocks) {
- if (block.subagentCallId === update.callId) block.live = true;
- }
- }
- this.#syncProvisionalSubagentTicker();
- this.#paint();
- }
-
markChildToolCallId(callId: string): void {
this.#childToolCallIds.add(callId);
const staleId = this.#parentToolBlockIds.get(callId);
@@ -1930,6 +1948,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
// The dying turn's stats coda closes before the boundary — it belongs
// to the session that ended, not the fresh one.
this.#commitTurnStats();
+ // Tasks die with the session; close their lines before the boundary.
+ this.#stopWorkingTasks();
this.#clearConversationState();
const c = this.#theme.colors;
@@ -1953,14 +1973,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#modelTurnId = undefined;
this.#childToolCallIds.clear();
this.#parentToolBlockIds.clear();
- this.#subagentHeaders.clear();
- this.#provisionalSubagentCallIds.clear();
- this.#subagentCallsByName.clear();
+ for (const pending of this.#pendingTaskEnds.values()) clearTimeout(pending.timer);
+ this.#pendingTaskEnds.clear();
+ this.#tasks.clear();
+ this.#writtenAgentRows.clear();
+ this.#startedTaskCallIds.clear();
+ this.#followedAgentCallIds.clear();
+ this.#endedAgentCallIds.clear();
this.#messageQueue.reset();
this.#nextSubmittedPromptOrigin = undefined;
this.#fileContents.clear();
this.#turnClock.reset();
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
}
/**
@@ -3133,7 +3157,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#startTicker();
this.#armFlowIdleTrap();
} else {
- this.#syncProvisionalSubagentTicker();
+ this.#syncTaskTicker();
}
this.#live.reset();
this.#paint();
@@ -3605,7 +3629,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
#stopTicker() {
- if (this.#hasLiveProvisionalSubagents()) return;
+ if (this.#tasks.working().length > 0) return;
this.#clearTicker();
}
@@ -3616,18 +3640,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
- #hasLiveProvisionalSubagents(): boolean {
- return this.#blocks.some(
- (block) =>
- block.live &&
- block.subagentCallId !== undefined &&
- this.#provisionalSubagentCallIds.has(block.subagentCallId),
- );
- }
-
- /** Keeps mutable subagent sections visibly active after their parent turn settles. */
- #syncProvisionalSubagentTicker(): void {
- if (this.#hasLiveProvisionalSubagents()) {
+ /** Keeps the task panel's elapsed times ticking while any task works, even between streams. */
+ #syncTaskTicker(): void {
+ if (this.#tasks.working().length > 0) {
this.#startTicker();
} else if (!this.#streamDraftActive && this.#turnIndicator.kind === "idle") {
this.#clearTicker();
@@ -3735,35 +3750,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
- #ensureSubagentHeader(callId: string, name: string) {
- if (this.#subagentHeaders.has(callId)) return;
- this.#subagentHeaders.add(callId);
-
- // 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",
- 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) {
if (block.id && this.#committedIds.has(block.id)) {
return;
@@ -3779,35 +3765,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#pushBlock(block);
}
- /**
- * Inserts a new child beside the rest of its call's cohort instead of at
- * the transcript's live edge. A child's final events can arrive after later
- * parent blocks; arrival order must not split its section.
- */
- #upsertSubagentBlock(block: Block) {
- if (block.id && this.#committedIds.has(block.id)) return;
- const existing = block.id ? this.#blockById.get(block.id) : undefined;
- if (existing !== undefined) {
- Object.assign(existing, block);
- existing.updateSeq = ++this.#updateSequence;
- return;
- }
-
- const callId = block.subagentCallId;
- if (callId === undefined) {
- this.#pushBlock(block);
- return;
- }
- if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();
- block.updateSeq = ++this.#updateSequence;
- let anchor = -1;
- for (let index = 0; index < this.#blocks.length; index += 1) {
- if (this.#blocks[index]?.subagentCallId === callId) anchor = index;
- }
- this.#blocks.splice(anchor < 0 ? this.#blocks.length : anchor + 1, 0, block);
- if (block.id !== undefined) this.#blockById.set(block.id, block);
- }
-
#removeBlock(id: string) {
this.#blocks = this.#blocks.filter((candidate) => candidate.id !== id);
this.#blockById.delete(id);
@@ -3819,8 +3776,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
// stay live past this stream boundary so their later terminal update can
// replace the same transcript block.
if (
- (block.subagentCallId !== undefined &&
- this.#provisionalSubagentCallIds.has(block.subagentCallId)) ||
block.status === "approval" ||
block.status === "running" ||
(block.kind === "connection-auth" && block.live) ||
@@ -3838,7 +3793,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
displayModes: DisplayModes,
turnState: RenderTurnState,
): void {
- const previousActivity = turnActivityLabel(turnState);
+ const previousActivity = turnActivityLabel(turnState, this.#tasks.working());
updateTurnActivity(turnState, event);
switch (event.type) {
case "turn-start":
@@ -3932,13 +3887,24 @@ export class TerminalRenderer implements AgentTUIRenderer {
case "tool-call":
this.#diagnostics?.recordToolCall(event.toolName);
- if (displayModes.tools === "hidden") break;
+ if (displayModes.tools === "hidden") {
+ // No row, but a call that becomes a task still names its request.
+ turnState.tools.set(event.toolCallId, {
+ input: event.input,
+ label: event.label,
+ status: "running",
+ toolCallId: event.toolCallId,
+ toolName: event.toolName,
+ });
+ break;
+ }
this.#upsertNativeTool(
{
input: event.input,
status: "running",
toolCallId: event.toolCallId,
toolName: event.toolName,
+ label: event.label,
},
displayModes,
turnState,
@@ -3958,7 +3924,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
const existing = this.#resolveNativeToolState(event.toolCallId, turnState);
if (existing === undefined) break;
this.#upsertNativeTool(
- { ...existing, output: event.output, status: "done" },
+ {
+ ...existing,
+ output: event.output,
+ status: "done",
+ completeLabel: event.label,
+ },
displayModes,
turnState,
);
@@ -3995,6 +3966,31 @@ export class TerminalRenderer implements AgentTUIRenderer {
break;
}
+ case "tool-withdrawn": {
+ // The model reads why and retries; the person only sees the retry.
+ const withdrawn = turnState.tools.get(event.toolCallId);
+ this.#diagnostics?.append({
+ source: "tool",
+ summary: `${withdrawn?.toolName ?? event.toolCallId} was refused for the model to retry`,
+ detail: event.reason,
+ });
+ turnState.tools.delete(event.toolCallId);
+ this.#removeBlock(
+ this.#parentToolBlockIds.get(event.toolCallId) ?? toolSectionId(event.toolCallId),
+ );
+ this.#parentToolBlockIds.delete(event.toolCallId);
+ this.#paint();
+ break;
+ }
+
+ case "task-started":
+ this.#startTask(event, displayModes, turnState);
+ break;
+
+ case "task-settled":
+ this.#endTask(event);
+ break;
+
case "error":
this.#addErrorBlock("Error", event.errorText, { detail: event.detail, hint: event.hint });
break;
@@ -4028,7 +4024,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
break;
}
// Activity is independent of transcript visibility and idle streams.
- if (turnState === this.#activeTurnState && turnActivityLabel(turnState) !== previousActivity) {
+ if (
+ turnState === this.#activeTurnState &&
+ turnActivityLabel(turnState, this.#tasks.working()) !== previousActivity
+ ) {
this.#paint();
}
}
@@ -4073,6 +4072,197 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
+ /**
+ * A call became a task: its row turns into the task's start line, in
+ * place, and the task joins the panel above the prompt. The line is
+ * written once and never changes, so nothing in the transcript moves while
+ * the task works.
+ */
+ #startTask(
+ event: Extract<AgentTUIStreamEvent, { type: "task-started" }>,
+ displayModes: DisplayModes,
+ turnState: RenderTurnState,
+ ): void {
+ const { kind, toolCallId, toolName } = event;
+ const rowId = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);
+ const tool = turnState.tools.get(toolCallId);
+ turnState.tools.delete(toolCallId);
+ this.#parentToolBlockIds.delete(toolCallId);
+ const visible =
+ kind === "agent" ? this.#subagents !== "hidden" : displayModes.tools !== "hidden";
+ if (!visible || this.#startedTaskCallIds.has(toolCallId)) {
+ this.#removeBlock(rowId);
+ this.#syncNativeToolBlockLiveness(turnState);
+ this.#paint();
+ return;
+ }
+ this.#startedTaskCallIds.add(toolCallId);
+
+ const input = tool?.input;
+ const label = tool?.label;
+ let baseName = agentDisplayName(stripTerminalControls(toolName));
+ let summary = agentTaskSummary(input);
+ if (kind === "tool") {
+ const presentation = presentTool(
+ toolName,
+ input,
+ this.#toolPresentationContext({ input, toolCallId, toolName, label }),
+ );
+ baseName = stripTerminalControls(presentation.title);
+ summary = stripTerminalControls(presentation.subtitle);
+ }
+ const entry = this.#tasks.start({
+ callId: toolCallId,
+ kind,
+ baseName,
+ toolName,
+ input,
+ label,
+ nowMs: Date.now(),
+ });
+ this.#replaceBlock(rowId, {
+ id: taskLineId(toolCallId, "start"),
+ kind: "task",
+ taskKind: kind,
+ title: entry.name,
+ subtitle: summary,
+ live: false,
+ });
+ this.#syncNativeToolBlockLiveness(turnState);
+ this.#syncTaskTicker();
+ this.#paint();
+ }
+
+ /**
+ * A task settled. An agent's own last events can trail its parent's
+ * `task.settled` on a separate stream, so while the pump follows that
+ * agent, its end line waits for the agent's own end — or, if that never
+ * comes, for a short grace period or the end of the turn's stream — and
+ * counts all of its work.
+ */
+ #endTask(event: TaskSettledEvent): void {
+ const { toolCallId } = event;
+ const entry = this.#tasks.get(toolCallId);
+ if (entry === undefined || this.#pendingTaskEnds.has(toolCallId)) return;
+ const endedAtMs = Date.now();
+ const awaitsAgent =
+ entry.kind === "agent" &&
+ this.#followedAgentCallIds.has(toolCallId) &&
+ !this.#endedAgentCallIds.has(toolCallId);
+ if (!awaitsAgent) {
+ this.#writeTaskEnd(event, endedAtMs);
+ return;
+ }
+ entry.finishing = true;
+ const timer = setTimeout(() => this.#flushTaskEnd(toolCallId), TASK_END_GRACE_MS);
+ timer.unref?.();
+ this.#pendingTaskEnds.set(toolCallId, { event, endedAtMs, timer });
+ this.#paint();
+ }
+
+ #flushTaskEnd(callId: string): void {
+ const pending = this.#pendingTaskEnds.get(callId);
+ if (pending === undefined) return;
+ clearTimeout(pending.timer);
+ this.#pendingTaskEnds.delete(callId);
+ this.#writeTaskEnd(pending.event, pending.endedAtMs);
+ }
+
+ #flushTaskEnds(): void {
+ for (const callId of this.#pendingTaskEnds.keys()) this.#flushTaskEnd(callId);
+ }
+
+ /** A task ended: it leaves the panel and writes its end line once. */
+ #writeTaskEnd(event: TaskSettledEvent, endedAtMs: number): void {
+ const entry = this.#tasks.finish(event.toolCallId);
+ if (entry === undefined) return;
+ const dot = ` ${this.#theme.glyph.dot} `;
+ const elapsed = `finished in ${formatTurnDuration(endedAtMs - entry.startedAtMs)}`;
+ const line: Block = {
+ id: taskLineId(event.toolCallId, "end"),
+ kind: "task",
+ taskKind: entry.kind,
+ title: entry.name,
+ live: false,
+ };
+ switch (event.status) {
+ case "completed": {
+ const outcome =
+ entry.kind === "agent"
+ ? summarizeChildTools([...entry.childTools.values()])
+ : presentTool(
+ entry.toolName,
+ entry.input,
+ this.#toolPresentationContext({
+ input: entry.input,
+ toolCallId: event.toolCallId,
+ toolName: entry.toolName,
+ label: entry.label,
+ }),
+ ).summarizeResult(event.output);
+ line.status = "done";
+ line.body =
+ outcome === undefined || outcome.length === 0 ? elapsed : `${elapsed}${dot}${outcome}`;
+ break;
+ }
+ case "failed": {
+ const reason = firstLine(stripTerminalControls(event.errorText ?? ""));
+ line.status = "error";
+ line.body = reason === undefined ? "failed" : `failed${dot}${reason}`;
+ break;
+ }
+ case "cancelled":
+ line.status = "denied";
+ line.body = "stopped";
+ break;
+ }
+ this.#pushBlock(line);
+ this.#syncTaskTicker();
+ this.#paint();
+ }
+
+ /**
+ * A cancelled, dropped, or failed session gets no end for its unsettled
+ * tasks; they read as stopped. Settled ones keep their real outcome.
+ */
+ #stopWorkingTasks(): void {
+ this.#flushTaskEnds();
+ const endedAtMs = Date.now();
+ for (const entry of this.#tasks.working()) {
+ this.#writeTaskEnd(
+ { type: "task-settled", toolCallId: entry.callId, status: "cancelled" },
+ endedAtMs,
+ );
+ }
+ }
+
+ /** Swaps a live row for its successor at the same position, so nothing below it moves. */
+ #replaceBlock(id: string, block: Block): void {
+ const index = this.#blocks.findIndex((candidate) => candidate.id === id);
+ if (index === -1) {
+ this.#pushBlock(block);
+ return;
+ }
+ this.#blockById.delete(id);
+ block.updateSeq = ++this.#updateSequence;
+ this.#blocks[index] = block;
+ if (block.id !== undefined) this.#blockById.set(block.id, block);
+ }
+
+ #taskPanelRows(width: number): string[] {
+ const working = this.#tasks.working();
+ if (working.length === 0) return [];
+ return renderTaskPanelRows(working, {
+ width,
+ theme: this.#theme,
+ nowMs: Date.now(),
+ pulse: this.#progressPulseGlyph(
+ this.#activityPulseStartedAtMs,
+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
+ ),
+ });
+ }
+
/**
* 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
@@ -4083,15 +4273,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly output?: unknown;
readonly toolCallId: string;
readonly toolName: string;
+ readonly label?: string | undefined;
+ readonly completeLabel?: string | undefined;
+ /** The call started an agent task of its own. */
+ readonly agentTask?: boolean | undefined;
}): 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 context: {
+ previousContent?: string;
+ existed?: boolean;
+ isSubagent?: boolean;
+ label?: string;
+ completeLabel?: string;
+ } = {};
+ if (tool.agentTask === true || this.#isSubagentToolName(tool.toolName)) {
+ context.isSubagent = true;
+ }
+ if (tool.label !== undefined) context.label = tool.label;
+ if (tool.completeLabel !== undefined) context.completeLabel = tool.completeLabel;
const write = readWriteFileInput(tool.toolName, tool.input);
if (write === undefined) {
- return context.isSubagent === true ? context : undefined;
+ return Object.keys(context).length > 0 ? context : undefined;
}
const previous = this.#fileContents.observeWrite({
path: write.path,
@@ -4542,6 +4746,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
rows.push(...renderAttentionRows(this.#setupAttention, width, this.#theme), "");
}
+ // The task panel is the one region that redraws in place while tasks
+ // work, so it sits in the footer rather than the transcript.
+ const taskRows = this.#taskPanelRows(width);
+ if (taskRows.length > 0) {
+ rows.push(...taskRows);
+ if (this.#inputActive) rows.push("");
+ }
+
// The message-queue panel takes the slot directly above the input
// because it holds the user's own undelivered words and carries the
// steering/cancel affordance.
@@ -4663,7 +4875,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const marker = elapsedMs % 1000 < 500 ? (this.#theme.unicode ? "•" : "*") : " ";
const elapsed =
elapsedMs < 1000 ? "0s" : formatTurnDuration(Math.floor(elapsedMs / 1000) * 1000);
- const label = `${turnActivityLabel(this.#activeTurnState)} (${elapsed})`;
+ const label = `${turnActivityLabel(this.#activeTurnState, this.#tasks.working())} (${elapsed})`;
const { inputTokens, outputTokens } = this.#turnClock.usage;
const tokens =
inputTokens > 0 || outputTokens > 0
@@ -5264,11 +5476,12 @@ function promptInputRows({
}
/** Kind + title of the previously rendered block, for gap / run decisions. */
-type PreviousBlock = { kind: BlockKind; title?: string };
+type PreviousBlock = { kind: BlockKind; title?: string; subagentCallId?: string };
function previousBlockOf(block: Block): PreviousBlock {
const previous: PreviousBlock = { kind: block.kind };
if (block.title !== undefined) previous.title = block.title;
+ if (block.subagentCallId !== undefined) previous.subagentCallId = block.subagentCallId;
return previous;
}
@@ -5289,7 +5502,7 @@ function isActiveToolStatus(status: ToolStatus | undefined): boolean {
* 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.
+ * Used by the top-level tool cohort.
*/
function applyCohortLiveness(entries: ReadonlyArray<{ block: Block; active: boolean }>): void {
const cohortActive = entries.some((entry) => entry.active);
@@ -5302,7 +5515,7 @@ function leadsWithGap(block: Block, previous: PreviousBlock | undefined): boolea
// 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" &&
+ (block.kind === "tool" || block.kind === "task") &&
(previous?.kind === "user" || previous?.kind === "assistant" || previous?.kind === "question")
) {
return true;
@@ -5316,7 +5529,6 @@ function leadsWithGap(block: Block, previous: PreviousBlock | undefined): boolea
case "user":
case "assistant":
case "reasoning":
- case "subagent":
case "error":
case "notice":
case "question":
@@ -5474,18 +5686,35 @@ function questionSectionId(requestId: string): string {
return `question:${requestId}`;
}
-function subagentHeaderId(callId: string): string {
- return `subagent:${callId}:header`;
+type TaskSettledEvent = Extract<AgentTUIStreamEvent, { type: "task-settled" }>;
+
+/** How long a settled agent task waits for its own stream's end before writing its end line. */
+const TASK_END_GRACE_MS = 2_000;
+
+function taskLineId(callId: string, edge: "start" | "end"): string {
+ return `task:${callId}:${edge}`;
}
-function subagentStepSectionId(callId: string, sectionKey: number): string {
+function subagentStepRowId(callId: string, sectionKey: number): string {
return `subagent:${callId}:step:${sectionKey}`;
}
-function subagentToolSectionId(callId: string, childCallId: string): string {
+function subagentToolRowId(callId: string, childCallId: string): string {
return `subagent:${callId}:tool:${childCallId}`;
}
+/** The first line of an agent call's message: what the agent was asked to do. */
+function agentTaskSummary(input: unknown): string {
+ if (input === null || typeof input !== "object") return "";
+ const message: unknown = Reflect.get(input, "message");
+ return typeof message === "string" ? (firstLine(stripTerminalControls(message)) ?? "") : "";
+}
+
+function firstLine(text: string): string | undefined {
+ const line = text.split(/\r?\n/u).find((candidate) => candidate.trim().length > 0);
+ return line?.trim();
+}
+
function connectionAuthSectionId(connectionName: string): string {
return `connection-auth:${connectionName}`;
}
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
index ce12404d0..fc0c8722a 100644
--- a/packages/eve/src/cli/dev/tui/tool-block-groups.test.ts
+++ b/packages/eve/src/cli/dev/tui/tool-block-groups.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { Block } from "./blocks.js";
-import { groupToolBlocksForDisplay, maxVisibleSubagentRunChildren } from "./tool-block-groups.js";
+import { groupToolBlocksForDisplay, summarizeChildTools } from "./tool-block-groups.js";
function fetchBlock(
id: string,
@@ -28,27 +28,6 @@ function fetchBlock(
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");
@@ -145,329 +124,16 @@ describe("groupToolBlocksForDisplay", () => {
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 => ({
+ it("keeps two agents' settled rows apart even when their calls match", () => {
+ const read = (callId: string): Block => ({
+ ...fetchBlock(`read:${callId}`, "https://one.example", "done"),
kind: "subagent-tool",
- id,
- subagentCallId: "ca",
+ subagentCallId: callId,
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 }]);
+ const groups = groupToolBlocksForDisplay([read("c1"), read("c2")]);
+ expect(groups.map((group) => group.members.length)).toEqual([1, 1]);
});
it("coalesces a contiguous run of same-source log writes into one section", () => {
@@ -582,3 +248,40 @@ describe("groupToolBlocksForDisplay", () => {
]);
});
});
+
+describe("summarizeChildTools", () => {
+ const child = (
+ toolName: string,
+ status: "done" | "error" | "running",
+ copy?: [string, string, string],
+ ): Block => {
+ const block: Block = { kind: "subagent-tool", depth: 1, status, toolName, title: toolName };
+ if (copy !== undefined) {
+ block.toolGroup = {
+ verb: copy[0],
+ pastVerb: copy[0],
+ singularNoun: copy[1],
+ pluralNoun: copy[2],
+ item: "x",
+ };
+ }
+ return block;
+ };
+
+ it("counts an agent's settled work by kind, most frequent first, and never hides failures", () => {
+ const read = child("read_file", "done", ["Read", "file", "files"]);
+ const summary = summarizeChildTools([
+ child("bash", "done", ["Ran", "command", "commands"]),
+ read,
+ read,
+ child("write_file", "done"),
+ child("web_fetch", "error", ["Fetched", "URL", "URLs"]),
+ child("grep", "running", ["Grepped", "pattern", "patterns"]),
+ ]);
+ expect(summary).toBe("Read 2 files, Ran 1 command, Wrote 1 file, 1 failed");
+ });
+
+ it("has nothing to say for an agent that ran no tools", () => {
+ expect(summarizeChildTools([])).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/tool-block-groups.ts b/packages/eve/src/cli/dev/tui/tool-block-groups.ts
index aa91532b3..cb8fdee27 100644
--- a/packages/eve/src/cli/dev/tui/tool-block-groups.ts
+++ b/packages/eve/src/cli/dev/tui/tool-block-groups.ts
@@ -11,11 +11,8 @@ interface ToolBlockDisplayGroup {
*
* 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
+ * failed aggregate instead of fragmenting on every status flip. 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
@@ -89,45 +86,6 @@ function groupBlocks(
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;
@@ -172,6 +130,7 @@ function sameRun(first: Block, candidate: Block): boolean {
candidate.kind === first.kind &&
candidate.depth === first.depth &&
candidate.live === first.live &&
+ candidate.subagentCallId === first.subagentCallId &&
// Copy derives from the tool name, so name equality implies equal copy.
candidate.toolName === first.toolName
);
@@ -200,13 +159,6 @@ function partitionRunByStatus(run: readonly Block[]): ToolBlockDisplayGroup[] {
}));
}
-/**
- * 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.
@@ -258,149 +210,6 @@ function coalesceLogBucket(members: readonly Block[]): ToolBlockDisplayGroup {
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!;
@@ -446,20 +255,6 @@ function collapseSettledToolBlocks(members: readonly Block[]): DisplayBlock {
};
}
-/**
- * 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;
@@ -498,11 +293,11 @@ function condensedRunTitle(run: readonly Block[]): string {
}
/**
- * 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.
+ * What an agent did, for the line its task ends on: counted settled work plus
+ * a failure count, so an error folds into the summary without vanishing from
+ * it. `undefined` when the agent ran no tools.
*/
-function condensedChildSummary(children: readonly Block[]): string | undefined {
+export function summarizeChildTools(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");
@@ -513,24 +308,6 @@ function condensedChildSummary(children: readonly Block[]): string | undefined {
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) {
@@ -543,7 +320,7 @@ function condensedKindCopy(block: Block): CondensedKindCopy {
if (toolBaseName(block.toolName ?? "") === "write_file") {
return { pastVerb: "Wrote", singularNoun: "file", pluralNoun: "files" };
}
- return { pastVerb: "Made", singularNoun: "tool call", pluralNoun: "tool calls" };
+ return { pastVerb: "Used", singularNoun: "tool", pluralNoun: "tools" };
}
/** A block's activity stamp; unstamped (test-built) blocks all tie at 0. */
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
index 90c97cebc..38b73604a 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
@@ -11,10 +11,10 @@ describe("presentPreparingTool", () => {
expect(presentPreparingTool("final_output").title).toBe("Return final output");
});
- it("keeps unknown tools on their name with a quiet hint", () => {
+ it("leads unknown tools with their name", () => {
const presentation = presentPreparingTool("linear__list_issues");
- expect(presentation.title).toBe("linear__list_issues");
- expect(presentation.subtitle).toBe("preparing…");
+ expect(presentation.title).toBe("linear__list_issues …");
+ expect(presentation.subtitle).toBe("");
});
});
@@ -189,11 +189,18 @@ describe("presentTool", () => {
expect(presentation.group).toBeUndefined();
expect(presentation.doneTitle).toBeUndefined();
expect(presentPreparingTool("task_update")).toMatchObject({
- title: "task_update",
- subtitle: "preparing…",
+ title: "task_update …",
+ subtitle: "",
});
});
+ it("keeps eve's own copy for builtin tools over their provided labels", () => {
+ // Provided tools define labels too; eve's copy keeps them groupable.
+ const presentation = presentTool("bash", { command: "ls" }, { label: "bash ls" });
+ expect(presentation.title).toBe("Run ls");
+ expect(presentation.group?.verb).toBe("Run");
+ });
+
it("presents a named subagent dispatch as a delegation", () => {
const parsed = presentTool(
"stock-price",
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.ts
index 553de6f0f..06147872f 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts
@@ -30,6 +30,10 @@ export interface ToolPresentationContext {
* `Delegate stock-price` — instead of a generic tool call.
*/
readonly isSubagent?: boolean;
+ /** The tool's own `label.start` copy, used when eve has no copy of its own for the tool. */
+ readonly label?: string;
+ /** The tool's own `label.complete` copy, shown once the call succeeds. */
+ readonly completeLabel?: string;
}
/** Copy needed to aggregate equivalent calls without merging their state. */
@@ -215,11 +219,12 @@ export function presentTool(
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.
+ // message rides as the quiet subtitle. The row is transient — the
+ // task's start line replaces it once the call becomes a task.
+ const name = agentDisplayName(toolName);
return {
- title: `${DELEGATE_VERB} ${baseName}`,
- doneTitle: `Delegated ${baseName}`,
+ title: `${DELEGATE_VERB} ${name}`,
+ doneTitle: `Delegated ${name}`,
subtitle: salientArg(input, "message") ?? "",
summarizeResult: () => undefined,
};
@@ -252,6 +257,18 @@ export function presentTool(
}
}
+ if (context?.label !== undefined) {
+ // Authored activity copy replaces the raw name and argument dump.
+ const presentation = {
+ title: context.label,
+ subtitle: "",
+ summarizeResult: summarizeToolResult,
+ };
+ return context.completeLabel === undefined
+ ? presentation
+ : { ...presentation, doneTitle: context.completeLabel };
+ }
+
return {
title: toolName,
subtitle: summarizeToolArgs(input),
@@ -259,11 +276,20 @@ export function presentTool(
};
}
+/**
+ * The name an agent task goes by. The generic self-delegation tool is
+ * literally named `agent`, which reads as `subagent` to a person.
+ */
+export function agentDisplayName(toolName: string): string {
+ const baseName = toolBaseName(toolName);
+ return baseName === "agent" ? "subagent" : baseName;
+}
+
/**
* 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.
+ * (`action.input.appended`). Known tools lead with their activity verb so the
+ * row already reads as intent (`Fetch …`); unknown tools lead with their name.
+ * The full presentation replaces this once the input arrives.
*/
export function presentPreparingTool(
toolName: string,
@@ -277,15 +303,15 @@ export function presentPreparingTool(
// A named subagent's tool carries the delegation target in its name —
// showable before the message finishes streaming.
return {
- title: `${DELEGATE_VERB} ${baseName} …`,
+ title: `${DELEGATE_VERB} ${agentDisplayName(toolName)} …`,
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…" : "",
+ title: `${verb ?? toolName} …`,
+ subtitle: "",
summarizeResult: () => undefined,
};
}
diff --git a/packages/eve/src/cli/dev/tui/types.ts b/packages/eve/src/cli/dev/tui/types.ts
index 509774b33..73dab705f 100644
--- a/packages/eve/src/cli/dev/tui/types.ts
+++ b/packages/eve/src/cli/dev/tui/types.ts
@@ -7,6 +7,14 @@ export type { LogDisplayMode };
*/
export type TerminalPartDisplayMode = "full" | "collapsed" | "auto-collapsed" | "hidden";
+/**
+ * Controls how subagent tasks render. `collapsed` writes a line when a
+ * subagent task starts and when it ends, and shows its current activity in
+ * the task panel above the prompt; `full` also writes each finished child
+ * message and tool call; `hidden` shows neither lines nor panel rows.
+ */
+export type SubagentDisplayMode = "full" | "collapsed" | "hidden";
+
/**
* Controls which usage statistic is shown for assistant responses.
*/
@@ -32,12 +40,11 @@ export type TuiDisplayOptions = {
reasoning?: TerminalPartDisplayMode;
/**
- * How subagent sections should render. `full` shows every nested child
- * event line and the subagent's output; `auto-collapsed` collapses the
- * section once the subagent reaches `done`; `collapsed` always shows
- * only the header; `hidden` skips the section entirely.
+ * How subagent tasks render.
+ *
+ * @default "collapsed"
*/
- subagents?: TerminalPartDisplayMode;
+ subagents?: SubagentDisplayMode;
/**
* How MCP connection authorization sections should render. `full`
diff --git a/packages/eve/src/cli/dev/ui-options.ts b/packages/eve/src/cli/dev/ui-options.ts
index 880aa9797..6ea927a75 100644
--- a/packages/eve/src/cli/dev/ui-options.ts
+++ b/packages/eve/src/cli/dev/ui-options.ts
@@ -1,6 +1,7 @@
import type {
AssistantResponseStatsMode,
LogDisplayMode,
+ SubagentDisplayMode,
TerminalPartDisplayMode,
TuiDisplayOptions,
} from "#cli/dev/tui/types.js";
@@ -12,7 +13,7 @@ interface DevelopmentTuiOptions {
readonly contextSize?: number;
readonly logs?: LogDisplayMode;
readonly reasoning?: TerminalPartDisplayMode;
- readonly subagents?: TerminalPartDisplayMode;
+ readonly subagents?: SubagentDisplayMode;
readonly tools?: TerminalPartDisplayMode;
readonly ui?: boolean;
}
diff --git a/packages/eve/src/cli/option-parsers.test.ts b/packages/eve/src/cli/option-parsers.test.ts
new file mode 100644
index 000000000..8a710d874
--- /dev/null
+++ b/packages/eve/src/cli/option-parsers.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { parseSubagentDisplayMode } from "#cli/option-parsers.js";
+
+describe("parseSubagentDisplayMode", () => {
+ it("accepts the subagent modes and names them when rejecting another", () => {
+ expect(["full", "collapsed", "hidden"].map(parseSubagentDisplayMode)).toEqual([
+ "full",
+ "collapsed",
+ "hidden",
+ ]);
+ // `auto-collapsed` was removed: it never differed from `collapsed`.
+ expect(() => parseSubagentDisplayMode("auto-collapsed")).toThrow(
+ 'Expected one of full, collapsed, hidden, received "auto-collapsed".',
+ );
+ });
+});
diff --git a/packages/eve/src/cli/option-parsers.ts b/packages/eve/src/cli/option-parsers.ts
index a474dfcb9..703fe93d2 100644
--- a/packages/eve/src/cli/option-parsers.ts
+++ b/packages/eve/src/cli/option-parsers.ts
@@ -5,6 +5,7 @@ import type { AgentReasoningDefinition } from "#shared/agent-definition.js";
import type {
AssistantResponseStatsMode,
LogDisplayMode,
+ SubagentDisplayMode,
TerminalPartDisplayMode,
} from "#cli/dev/tui/types.js";
@@ -36,6 +37,19 @@ export function parseDisplayMode(value: string): TerminalPartDisplayMode {
return value as TerminalPartDisplayMode;
}
+const SUBAGENT_DISPLAY_MODES = new Set(["full", "collapsed", "hidden"]);
+
+/** Parses a subagent task display mode. */
+export function parseSubagentDisplayMode(value: string): SubagentDisplayMode {
+ if (!SUBAGENT_DISPLAY_MODES.has(value)) {
+ throw new InvalidArgumentError(
+ `Expected one of ${[...SUBAGENT_DISPLAY_MODES].join(", ")}, received "${value}".`,
+ );
+ }
+
+ return value as SubagentDisplayMode;
+}
+
/** Parses an assistant response statistics mode. */
export function parseStatsMode(value: string): AssistantResponseStatsMode {
if (!STATS_MODES.has(value)) {
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index 45eac96f0..f0f507c4a 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -1247,7 +1247,7 @@ describe("resolveTuiDisplayOptions", () => {
resolveTuiDisplayOptions({
tools: "hidden",
reasoning: "collapsed",
- subagents: "auto-collapsed",
+ subagents: "collapsed",
connectionAuth: "full",
assistantResponseStats: "tokens",
contextSize: 200_000,
@@ -1256,7 +1256,7 @@ describe("resolveTuiDisplayOptions", () => {
).toEqual({
tools: "hidden",
reasoning: "collapsed",
- subagents: "auto-collapsed",
+ subagents: "collapsed",
connectionAuth: "full",
assistantResponseStats: "tokens",
contextSize: 200_000,
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index b63895312..c0648f025 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -6,7 +6,7 @@ import {
loadModuleBackedDefinition,
type ModuleBackedDefinitionLoadOptions,
} from "#compiler/normalize-helpers.js";
-import { TASK_TOOL_NAMES } from "#execution/tasks/calls.js";
+import { TASK_TOOL_NAMES } from "#protocol/task-tools.js";
/**
* Compiled tool entry produced from one authored `tools/*.ts` file.
diff --git a/packages/eve/src/execution/activity-events.test.ts b/packages/eve/src/execution/activity-events.test.ts
index 2bb9ca1b5..133be1a83 100644
--- a/packages/eve/src/execution/activity-events.test.ts
+++ b/packages/eve/src/execution/activity-events.test.ts
@@ -63,6 +63,51 @@ describe("projectActivityEvents", () => {
]);
});
+ it("projects no activity for the model's own task calls", () => {
+ const at = "2026-01-01T00:00:00Z";
+ const turn = { sequence: 0, stepIndex: 0, turnId: "turn" };
+ expect(
+ [
+ projectActivityEvents({
+ at,
+ event: {
+ data: {
+ ...turn,
+ actions: [
+ { callId: "wait-1", input: {}, kind: "tool-call", toolName: "task_wait" },
+ {
+ callId: "cancel-1",
+ input: { taskId: "t1" },
+ kind: "tool-call",
+ toolName: "task_cancel",
+ },
+ ],
+ },
+ type: "actions.requested",
+ },
+ lineage,
+ }),
+ projectActivityEvents({
+ at,
+ event: {
+ data: {
+ ...turn,
+ result: {
+ callId: "wait-1",
+ kind: "tool-result",
+ output: "done",
+ toolName: "task_wait",
+ },
+ status: "completed",
+ },
+ type: "action.result",
+ },
+ lineage,
+ }),
+ ].flat(),
+ ).toEqual([]);
+ });
+
it("normalizes and bounds authorization blocker labels", () => {
const [event] = projectActivityEvents({
at: "2026-01-01T00:00:00Z",
diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.ts
index eb72a162e..1c4bb7d1d 100644
--- a/packages/eve/src/execution/activity-events.ts
+++ b/packages/eve/src/execution/activity-events.ts
@@ -6,6 +6,7 @@ import type {
ActivityWorkIdentityV1,
} from "#protocol/activity.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import { isTaskControlTool } from "#protocol/task-tools.js";
export function projectActivityEvents(input: {
readonly at: string;
@@ -19,6 +20,7 @@ export function projectActivityEvents(input: {
if (event.type === "actions.requested") {
return event.data.actions.flatMap((action) => {
if (action.kind === "subagent-call" || action.kind === "remote-agent-call") return [];
+ if (action.kind === "tool-call" && isTaskControlTool(action.toolName)) return [];
const kind = action.kind === "load-skill" ? ("skill" as const) : ("tool" as const);
const rawName = action.kind === "load-skill" ? "load_skill" : action.toolName;
const name = normalizePresentationText(rawName) || (kind === "skill" ? "Skill" : "Tool");
@@ -91,6 +93,7 @@ export function projectActivityEvents(input: {
},
];
}
+ if (result.kind === "tool-result" && isTaskControlTool(result.toolName)) return [];
const id = actionId(lineage.id, result.callId);
const label = activityLabel(event.data.presentation?.[result.callId]?.label);
const labelUpdates =
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index e33fd200e..4c8848d41 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -16,7 +16,8 @@ import {
type SteeringTurn,
} from "#execution/session/input-queue.js";
import { AuthKey } from "#context/keys.js";
-import { TASK_WAIT_TOOL_NAME, taskToolResult, type TaskToolCall } from "#execution/tasks/calls.js";
+import { taskToolResult, type TaskToolCall } from "#execution/tasks/calls.js";
+import { TASK_WAIT_TOOL_NAME } from "#protocol/task-tools.js";
import { principalOf } from "#execution/session/principal.js";
import { renderTaskWaitResult } from "#execution/tasks/render.js";
import {
diff --git a/packages/eve/src/execution/tasks/calls.ts b/packages/eve/src/execution/tasks/calls.ts
index a6d5054ce..222a0e28f 100644
--- a/packages/eve/src/execution/tasks/calls.ts
+++ b/packages/eve/src/execution/tasks/calls.ts
@@ -2,6 +2,7 @@ import type { ModelMessage } from "ai";
import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
import type { JsonValue } from "#shared/json.js";
+import { TASK_CANCEL_TOOL_NAME, TASK_WAIT_TOOL_NAME } from "#protocol/task-tools.js";
/**
* Calls to the task tools. They defer out of the model step like
@@ -11,12 +12,6 @@ export type TaskToolCall =
| { readonly callId: string; readonly kind: "task_wait"; readonly timeoutMs?: number }
| { readonly callId: string; readonly kind: "task_cancel"; readonly taskId: string };
-export const TASK_WAIT_TOOL_NAME = "task_wait";
-export const TASK_CANCEL_TOOL_NAME = "task_cancel";
-
-/** The task tools' names; authored tools cannot use them. */
-export const TASK_TOOL_NAMES: readonly string[] = [TASK_WAIT_TOOL_NAME, TASK_CANCEL_TOOL_NAME];
-
/**
* The task tool calls a parked step's response still waits on. The response
* is the one record of these calls: a call without a result is pending, and
diff --git a/packages/eve/src/execution/tasks/model-step.ts b/packages/eve/src/execution/tasks/model-step.ts
index e5b869399..8b620ab79 100644
--- a/packages/eve/src/execution/tasks/model-step.ts
+++ b/packages/eve/src/execution/tasks/model-step.ts
@@ -1,6 +1,6 @@
import type { ModelMessage, SystemModelMessage } from "ai";
-import { TASK_CANCEL_TOOL_NAME, TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";
+import { TASK_CANCEL_TOOL_NAME, TASK_WAIT_TOOL_NAME } from "#protocol/task-tools.js";
import {
FINAL_REPLY_TASK_SYSTEM_BLOCK,
renderModelOutputText,
diff --git a/packages/eve/src/execution/tasks/session.ts b/packages/eve/src/execution/tasks/session.ts
index 43a448fd0..74e9d2baf 100644
--- a/packages/eve/src/execution/tasks/session.ts
+++ b/packages/eve/src/execution/tasks/session.ts
@@ -1,9 +1,5 @@
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
-import {
- TASK_CANCEL_TOOL_NAME,
- taskToolResult,
- type TaskToolCall,
-} from "#execution/tasks/calls.js";
+import { taskToolResult, type TaskToolCall } from "#execution/tasks/calls.js";
import { renderTaskCancelResult, renderUnknownCancelTaskError } from "#execution/tasks/render.js";
import { cancelTasksStep, type TaskRunMessage } from "#execution/tasks/steps.js";
import {
@@ -13,6 +9,7 @@ import {
type TaskTable,
} from "#execution/tasks/table.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
+import { TASK_CANCEL_TOOL_NAME, UNKNOWN_TASK_CODE } from "#protocol/task-tools.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
// What the session's workflow body does with tasks between steps: records
@@ -47,7 +44,7 @@ export async function answerTaskCancel(
const result = taskCancelResult(sessionTaskTable(cursor), call.taskId);
if (result === undefined) {
const error = {
- code: "UNKNOWN_TASK",
+ code: UNKNOWN_TASK_CODE,
message: renderUnknownCancelTaskError(call.taskId),
};
return { ...taskToolResult(call.callId, TASK_CANCEL_TOOL_NAME, error), isError: true };
diff --git a/packages/eve/src/execution/tasks/start.ts b/packages/eve/src/execution/tasks/start.ts
index 626cdc95a..ee7cdc3c2 100644
--- a/packages/eve/src/execution/tasks/start.ts
+++ b/packages/eve/src/execution/tasks/start.ts
@@ -28,6 +28,7 @@ import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers
import { createLogger, logError } from "#internal/logging.js";
import type { HarnessSession } from "#harness/types.js";
import { createTaskStartedEvent, type TaskStartedStreamEvent } from "#protocol/message.js";
+import { TOO_MANY_TASKS_CODE, UNKNOWN_TASK_CODE } from "#protocol/task-tools.js";
import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";
const log = createLogger("execution.tasks");
@@ -136,7 +137,7 @@ function tooManyTasks(
callId: input.task.callId,
isError: true,
output: {
- code: "TOO_MANY_TASKS",
+ code: TOO_MANY_TASKS_CODE,
message: renderTooManyTasksError(MAX_WORKING_TASKS, runningIds),
},
toolName: input.task.toolName,
@@ -148,7 +149,7 @@ function unknownTaskResult(input: TaskDispatchInput): RuntimeToolResultActionRes
callId: input.task.callId,
isError: true,
output: {
- code: "UNKNOWN_TASK",
+ code: UNKNOWN_TASK_CODE,
message: renderUnknownTaskError(input.taskId, input.task.toolName),
},
toolName: input.task.toolName,
diff --git a/packages/eve/src/protocol/task-tools.ts b/packages/eve/src/protocol/task-tools.ts
new file mode 100644
index 000000000..bd91f8c77
--- /dev/null
+++ b/packages/eve/src/protocol/task-tools.ts
@@ -0,0 +1,37 @@
+import type { ActionResultStreamEvent } from "#protocol/message.js";
+
+export const TASK_WAIT_TOOL_NAME = "task_wait";
+export const TASK_CANCEL_TOOL_NAME = "task_cancel";
+
+/** The task tools' names; authored tools cannot use them. */
+export const TASK_TOOL_NAMES: readonly string[] = [TASK_WAIT_TOOL_NAME, TASK_CANCEL_TOOL_NAME];
+
+/**
+ * Whether a tool call is the model managing its own tasks. The stream keeps
+ * these calls so evals and traces can see them, but activity surfaces hide
+ * them: people see the tasks, not the model waiting on or stopping them. The
+ * names are reserved, so no authored tool matches.
+ */
+export function isTaskControlTool(toolName: string): boolean {
+ return TASK_TOOL_NAMES.includes(toolName);
+}
+
+export const TOO_MANY_TASKS_CODE = "TOO_MANY_TASKS";
+export const UNKNOWN_TASK_CODE = "UNKNOWN_TASK";
+
+/** A task call the session refused for the model to retry: too many tasks, or an unknown id. */
+const TASK_RETRY_ERROR_CODES: readonly string[] = [TOO_MANY_TASKS_CODE, UNKNOWN_TASK_CODE];
+
+/**
+ * Whether a tool result is the session refusing a task call for the model
+ * to retry. Its message tells the model how to recover, so activity surfaces
+ * keep it out of view. Only a failed result counts: an authored tool can
+ * return the same `code` as ordinary output.
+ */
+export function isTaskRetryRefusal(event: ActionResultStreamEvent): boolean {
+ if (event.data.status !== "failed" || event.data.result.kind !== "tool-result") return false;
+ const output = event.data.result.output;
+ if (typeof output !== "object" || output === null) return false;
+ const code: unknown = Reflect.get(output, "code");
+ return typeof code === "string" && TASK_RETRY_ERROR_CODES.includes(code);
+}
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index 663ea74b9..735983578 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -2,6 +2,7 @@ import type { SessionAuthContext } from "#channel/types.js";
import { createLogger, extractErrorId, formatErrorHint, logError } from "#internal/logging.js";
import { describeActionRequests } from "#public/channels/slack/action-status.js";
+import { isTaskControlTool } from "#protocol/task-tools.js";
import { buildSlackAuthContext, slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";
import {
buildAuthCompletedText,
@@ -473,7 +474,11 @@ export const defaultEvents: SlackChannelInternalEvents = {
await channel.thread.startTyping(truncateTypingStatus(buffered));
return;
}
- await channel.thread.startTyping(truncateTypingStatus(describeActionRequests(event.actions)));
+ const actions = event.actions.filter(
+ (action) => action.kind !== "tool-call" || !isTaskControlTool(action.toolName),
+ );
+ if (actions.length === 0) return;
+ await channel.thread.startTyping(truncateTypingStatus(describeActionRequests(actions)));
},
async "message.completed"(event, channel, _ctx) {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 9f65b94c0..4f6607c0f 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -768,6 +768,35 @@ describe("slackChannel() default event handlers", () => {
expect(ctx.state.pendingToolCallMessage).toBeNull();
});
+ it("keeps the model's own task calls out of the typing status", async () => {
+ const adapter = withState(
+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
+ THREAD_STATE,
+ );
+ const ctx = buildAdapterContext(adapter, stubAccessor());
+ const requested = (toolNames: readonly string[]) =>
+ makeEvent("actions.requested", {
+ actions: toolNames.map((toolName, index) => ({
+ callId: `call_${String(index)}`,
+ input: {},
+ kind: "tool-call" as const,
+ toolName,
+ })),
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ });
+
+ await callEvent(adapter, requested(["task_wait"]), ctx);
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ await callEvent(adapter, requested(["task_cancel", "search"]), ctx);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(parseSlackRequestBody(fetchMock.mock.calls[0]![1] as RequestInit)).toMatchObject({
+ status: "search",
+ });
+ });
+
it("message.completed clears typing without posting for empty delivery", async () => {
const adapter = withState(
getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
diff --git a/packages/eve/src/tools/provided/task-cancel.ts b/packages/eve/src/tools/provided/task-cancel.ts
index b8e5815d5..29cfaff38 100644
--- a/packages/eve/src/tools/provided/task-cancel.ts
+++ b/packages/eve/src/tools/provided/task-cancel.ts
@@ -1,4 +1,4 @@
-import { TASK_CANCEL_TOOL_NAME } from "#execution/tasks/calls.js";
+import { TASK_CANCEL_TOOL_NAME } from "#protocol/task-tools.js";
import {
TASK_CANCEL_DESCRIPTION,
TASK_CANCEL_TASK_ID_DESCRIPTION,
diff --git a/packages/eve/src/tools/provided/task-wait.ts b/packages/eve/src/tools/provided/task-wait.ts
index e7f8f5527..5aa2ab12c 100644
--- a/packages/eve/src/tools/provided/task-wait.ts
+++ b/packages/eve/src/tools/provided/task-wait.ts
@@ -1,4 +1,4 @@
-import { TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";
+import { TASK_WAIT_TOOL_NAME } from "#protocol/task-tools.js";
import { TASK_WAIT_DESCRIPTION, TASK_WAIT_TIMEOUT_DESCRIPTION } from "#execution/tasks/render.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { defineJsonSchema } from "#tools/schema.js";
diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.ts
index abc140469..b119abb85 100644
--- a/packages/eve/test/tui-client/tui-subagents-weather.ts
+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts
@@ -17,18 +17,15 @@ import { theme } from "./lib/theme.ts";
* landing under `stepIndex: 0` and collapsing into one box.
*
* Pass conditions:
- * 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).
+ * 1. A `※ stock-price` start line exists.
+ * 2. The task panel asks for approval of the child's `get_stock_price`
+ * call, and the approval prompt accepts it.
* 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 —
- * or the section already settled to its `└ Done` footnote (a
- * completed subagent collapses, so nested rows are transient).
+ * 4. The task ends on a `✓ stock-price` line.
* 5. The parent's final assistant reply (a top-level `▲` section)
- * also contains the price.
+ * contains the price.
*/
const TICKER = "GOOG";
@@ -72,17 +69,17 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
);
input.enter();
- // The subagent region header should appear once the parent delegates.
- await waitForCondition(() => screen.snapshot().includes("※ subagent(stock-price"), {
+ // The task's start line appears once the parent delegates.
+ await waitForCondition(() => screen.snapshot().includes("※ stock-price"), {
timeoutMs: 120_000,
- label: "subagent region header",
+ label: "task start line",
onTimeout: () => screen.snapshot(),
});
- console.log(theme.muted("[tui-weather] subagent region header appeared"));
+ console.log(theme.muted("[tui-weather] task start line appeared"));
- // Approve the get_stock_price tool when prompted. The TUI parks on a
- // y/n approval prompt, match the question smoke's handshake delay
- // so the server's resume hook is registered before we reply.
+ // The task panel names the approval the child waits on, and the TUI
+ // parks on a y/n prompt. Match the question smoke's handshake delay so
+ // the server's resume hook is registered before we reply.
await waitForCondition(
() =>
screen.snapshot().includes("Approve get_stock_price?") ||
@@ -97,60 +94,15 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
input.emit("data", Buffer.from("y"));
console.log(theme.muted("[tui-weather] approved get_stock_price"));
- // Price should appear in the body once the child unblocks.
- await waitForCondition(() => screen.snapshot().includes(PRICE), {
+ await waitForCondition(() => screen.snapshot().includes("✓ stock-price"), {
timeoutMs: 120_000,
- label: `price ${PRICE} renders in the body`,
+ label: "task end line",
onTimeout: () => screen.snapshot(),
});
- console.log(theme.muted(`[tui-weather] price ${PRICE} landed in body`));
-
- // 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 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(
- // 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 (or the section settled)`,
- onTimeout: () => screen.snapshot(),
- },
- );
- console.log(theme.muted("[tui-weather] subagent region carried the price or settled to Done"));
+ console.log(theme.muted("[tui-weather] task end line appeared"));
// Wait for the parent's follow-up assistant section (top-level `▲`
- // prose, not nested under the rule gutter) to echo the price.
+ // prose) to echo the price.
await waitForCondition(() => assistantSectionContains(screen.snapshot(), PRICE), {
timeoutMs: 120_000,
label: "parent assistant reply with price",
@@ -161,13 +113,13 @@ run(WEATHER_SMOKE_TARGET, async (target) => {
// No parent-level tool row for the child's call should remain: a tool
// 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
+ // (e.g. ` ▪ get_stock_price`). The child's own calls surface only in the
+ // task panel and its end line. Assistant prose lines start with `▲ `, so
// they cannot false-positive here.
- const parentToolRowRegex = /^ {0,2}[^\s│▲] get_stock_price/mu;
+ 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}`,
+ `Final screen still contains a parent-level tool row for the child's get_stock_price call. The child's calls belong to its task, not the parent transcript.\n\n${finalSnapshot}`,
);
}
console.log(theme.muted("[tui-weather] no stale parent-level get_stock_price tool row"));
diff --git a/packages/eve/test/tui-client/tui-subagents.ts b/packages/eve/test/tui-client/tui-subagents.ts
index 38c0b0e01..ed0e3e4e5 100644
--- a/packages/eve/test/tui-client/tui-subagents.ts
+++ b/packages/eve/test/tui-client/tui-subagents.ts
@@ -5,23 +5,23 @@ import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";
// Note: the apps/fixtures/agent-tui-client's echo-marker subagent is the source of every child
// stream event the TUI observes here. The smoke validates the full pipeline:
-// parent task.started + agent.started → child session subscription → nested `│` region
-// populated from the child's message.completed → parent task.settled.
+// parent task.started → start line → agent.started → child session subscription → task
+// panel activity → parent task.settled → end line.
import { run } from "./lib/run.ts";
import { theme } from "./lib/theme.ts";
/**
- * End-to-end proof that the TUI surfaces an agent task's child stream as a
- * persistent body section. This smoke test drives the subagent section path
- * against the `echo-marker` fixture:
+ * End-to-end proof that the TUI surfaces an agent task as a start line, a
+ * task-panel row while it works, and an end line. This smoke test drives
+ * the task path against the `echo-marker` fixture:
*
* 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 `※ 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
+ * 4. Wait for the `※ echo-marker` start line to appear.
+ * 5. Wait for the `✓ echo-marker` end line once the task settles.
+ * 6. Verify the parent assistant message contains the token. The
* rendering side-channel must not have broken the harness path.
*/
@@ -53,22 +53,16 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
);
input.enter();
- await screen.waitForText("※ subagent(echo-marker", 90_000);
- console.log(theme.muted("[tui-subagents] subagent region header appeared"));
+ await screen.waitForText("※ echo-marker", 90_000);
+ console.log(theme.muted("[tui-subagents] task start line appeared"));
- await waitForCondition(() => screen.snapshot().includes(SUBAGENT_TOKEN), {
- timeoutMs: 90_000,
- label: "subagent message text landed in body",
- });
- console.log(theme.muted("[tui-subagents] subagent message text landed in body"));
-
- // 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 screen.waitForText("✓ echo-marker", 90_000);
+ console.log(theme.muted("[tui-subagents] task end line appeared"));
+
+ // The verbatim echo must land in a top-level `▲`-prefixed assistant
+ // section: the parent read the child's result. 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: 120_000,
label: "parent assistant section containing the token",
@@ -77,6 +71,12 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
console.log(theme.muted("[tui-subagents] parent assistant reply rendered with token"));
const finalSnapshot = screen.snapshot();
+ // The model's own task bookkeeping never reaches the transcript.
+ for (const internal of ["task_wait", "task_cancel", "<task_result"]) {
+ if (finalSnapshot.includes(internal)) {
+ throw new Error(`Final screen shows internal task text "${internal}":\n${finalSnapshot}`);
+ }
+ }
if (finalSnapshot.includes("Error")) {
throw new Error(`Final screen contains an Error section:\n${finalSnapshot}`);
}