Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

show a live subagent tree above the loader (#254)

ktb6b2df162b15
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index fa422c80c9..fca24ca58b 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -217,6 +217,12 @@ export interface RlmChildAgentSnapshot {
status: RlmChildAgentStatus;
durationMs?: number;
answerPreview?: string;
+ /** Number of tool executions the subagent has started so far. */
+ toolUseCount?: number;
+ /** Context size (tokens) of the subagent's latest turn. */
+ tokenCount?: number;
+ /** Latest recap of what the subagent is doing, from the summarizer. */
+ recap?: string;
sessionDir: string;
transcript: readonly RlmChildAgentTranscriptLine[];
structuredTranscript?: readonly RlmChildAgentStructuredTranscriptEntry[];
@@ -247,6 +253,7 @@ export type AgentSessionEvent =
| { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
| { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
| { type: "rlm_child_update"; child: RlmChildAgentSnapshot }
+ | { type: "recap_update"; recap: string | undefined }
| { type: "goal_update"; goal: GoalState }
| { type: "bash_start"; command: string; excludeFromContext: boolean }
| { type: "bash_output"; chunk: string }
@@ -732,6 +739,8 @@ export class AgentSession {
private _rlmParentNodeId?: string;
private _subagentRuntimeHost?: SubagentRuntimeHost;
private _activeRlmChildRuns = new Map<string, RlmChildRun>();
+ /** Latest recap for this session, written by the daemon summarizer; read by a parent to label its child snapshots. */
+ private _currentRecap?: string;
// Model registry for API key resolution
private _modelRegistry: ModelRegistry;
@@ -3824,6 +3833,24 @@ export class AgentSession {
return usage;
}
+ /** Context size (tokens) of this session's latest assistant turn, for live subagent display. */
+ _contextTokensForCurrentMessages(): number | undefined {
+ const last = this._findLastAssistantMessage();
+ return last ? calculateContextTokens(last.usage) : undefined;
+ }
+
+ setCurrentRecap(recap: string | undefined): void {
+ if (this._currentRecap === recap) {
+ return;
+ }
+ this._currentRecap = recap;
+ this._emit({ type: "recap_update", recap });
+ }
+
+ getCurrentRecap(): string | undefined {
+ return this._currentRecap;
+ }
+
private _assistantUsageForCurrentMessages(): Usage {
const usage = emptyUsage();
for (const message of this.agent.state.messages) {
@@ -4025,6 +4052,7 @@ export class AgentSession {
const label = rlmChildLabel(prompt);
let answerPreview: string | undefined;
let durationMs: number | undefined;
+ let toolUseCount = 0;
const run: RlmChildRun = {
id: childNodeId,
prompt,
@@ -4048,6 +4076,9 @@ export class AgentSession {
status: run.status,
durationMs,
answerPreview,
+ toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,
+ tokenCount: run.session?._contextTokensForCurrentMessages(),
+ recap: run.session?.getCurrentRecap(),
sessionDir: childSessionDir,
transcript: [...transcript],
structuredTranscript: [...structuredTranscript],
@@ -4157,6 +4188,11 @@ export class AgentSession {
this._emit(event);
return;
}
+ if (event.type === "recap_update") {
+ // The summarizer set the child's recap; refresh its snapshot so the parent UI shows it.
+ emitChildUpdate();
+ return;
+ }
switch (event.type) {
case "message_start": {
if (event.message.role === "user") {
@@ -4181,6 +4217,7 @@ export class AgentSession {
case "tool_execution_start": {
const args = formatRlmToolArgs(event.args);
const text = args ? `${event.toolName} running ${args}` : `${event.toolName} running`;
+ toolUseCount += 1;
// Tool break: next assistant text starts a new entry after this tool row.
currentAssistantIndex = undefined;
lastToolTranscriptIndex = transcript.length;
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 5c10f7cd73..f9f2aece8b 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -474,6 +474,12 @@ export interface AgentConnectionRlmChildAgentSnapshot {
status: AgentConnectionRlmChildAgentStatus;
durationMs?: number;
answerPreview?: string;
+ /** Number of tool executions the subagent has started so far. */
+ toolUseCount?: number;
+ /** Context size (tokens) of the subagent's latest turn. */
+ tokenCount?: number;
+ /** Latest recap of what the subagent is doing. */
+ recap?: string;
sessionDir: string;
transcript: readonly AgentConnectionRlmChildAgentTranscriptLine[];
structuredTranscript?: readonly AgentConnectionRlmChildAgentStructuredTranscriptEntry[];
@@ -503,6 +509,7 @@ export type AgentConnectionSessionEvent =
| { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
| { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
| { type: "rlm_child_update"; child: AgentConnectionRlmChildAgentSnapshot }
+ | { type: "recap_update"; recap: string | undefined }
| { type: "goal_update"; goal: GoalState }
| { type: "bash_start"; command: string; excludeFromContext: boolean }
| { type: "bash_output"; chunk: string }
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index a38860114c..0461285d2a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -181,12 +181,18 @@ export class AgentDaemon {
private readonly cronScheduler: AgentCronScheduler;
private readonly summarizer = new DaemonSessionSummarizer(
() => [...this.sessions.values()],
- (state) =>
+ (state) => {
+ // Subagents share their recap with the parent so it shows in the parent's
+ // subagent tree; their own session channel usually has no attached client.
+ if (state.runtime.metadata.kind === "subagent") {
+ state.runtime.session.setCurrentRecap(state.summaryState?.summary);
+ }
this.broadcastToSession(state, {
type: "session_status",
activeSessionId: state.activeSessionId,
recap: state.summaryState?.summary,
- }),
+ });
+ },
);
constructor(
diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
index fa8f8c67fc..5ce108203b 100644
--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
@@ -69,6 +69,9 @@ export interface ChildAgentInspectorNode {
status: ChildAgentStatus;
durationMs?: number;
answerPreview?: string;
+ toolUseCount?: number;
+ tokenCount?: number;
+ recap?: string;
sessionDir: string;
transcript: readonly ChildAgentTranscriptLine[];
structuredTranscript?: readonly ChildAgentStructuredTranscriptEntry[];
diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.ts
index ec593a7a8e..bc2e248257 100644
--- a/packages/coding-agent/src/modes/interactive/components/index.ts
+++ b/packages/coding-agent/src/modes/interactive/components/index.ts
@@ -44,6 +44,7 @@ export {
type SubAgentTreeNode,
type SubAgentTreeOptions,
} from "./sub-agent-tree.js";
+export { SubagentTreeView } from "./subagent-tree-view.js";
export { ThemeSelectorComponent } from "./theme-selector.js";
export { ThinkingSelectorComponent } from "./thinking-selector.js";
export { ToolExecutionComponent, type ToolExecutionOptions } from "./tool-execution.js";
diff --git a/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts b/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
new file mode 100644
index 0000000000..6b5f1565a8
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
@@ -0,0 +1,162 @@
+import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
+import { formatTokenCount } from "../agent-activity.js";
+import { theme } from "../theme/theme.js";
+import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
+import type { ChildAgentInspectorNode, ChildAgentStructuredTranscriptEntry } from "./child-agent-inspector.js";
+
+/** Left padding so the tree aligns with the loader message / tool-call text. */
+const PAD = " ";
+/** How many subagents to show before collapsing the rest into a "+N more" line. */
+const MAX_VISIBLE = 5;
+/** Keep each node's label to the first few words so the row stays scannable. */
+const LABEL_MAX_WORDS = 4;
+const LABEL_MAX_CHARS = 32;
+
+/**
+ * Live, render-only tree of the current turn's in-flight subagents, shown above the
+ * working loader and in addition to the inline list below the prompt bar. Each node is
+ * two lines — label + tool-use/token counts, then its current recap — with an animated
+ * working icon. Subagents drop out of the tree as soon as they finish.
+ */
+export class SubagentTreeView implements Component {
+ private nodes: readonly ChildAgentInspectorNode[] = [];
+
+ setNodes(nodes: readonly ChildAgentInspectorNode[]): void {
+ // Flatten the whole inspector tree — nested subagents live under `children` —
+ // and keep only the in-flight ones; finished subagents disappear.
+ const flat: ChildAgentInspectorNode[] = [];
+ const walk = (list: readonly ChildAgentInspectorNode[]): void => {
+ for (const node of list) {
+ if (node.status === "running" || node.status === "queued") {
+ flat.push(node);
+ }
+ if (node.children) {
+ walk(node.children);
+ }
+ }
+ };
+ walk(nodes);
+ this.nodes = flat;
+ }
+
+ hasNodes(): boolean {
+ return this.nodes.length > 0;
+ }
+
+ invalidate(): void {
+ // Rendering is derived from the nodes set above.
+ }
+
+ render(width: number): string[] {
+ if (this.nodes.length === 0) {
+ return [];
+ }
+ const safeWidth = Math.max(1, width);
+ const visible = this.nodes.slice(0, MAX_VISIBLE);
+ const hidden = this.nodes.length - visible.length;
+ const icon = theme.fg("accent", workingIconFrame(getWorkingPulseFrame()));
+
+ // Leading blank line so the tree doesn't hug the tool call/output above it.
+ const lines: string[] = [""];
+ lines.push(truncateToWidth(`${PAD}${this.header()}`, safeWidth));
+ for (const [index, node] of visible.entries()) {
+ const isLast = index === visible.length - 1 && hidden === 0;
+ this.renderNode(lines, node, isLast, icon, safeWidth);
+ }
+ if (hidden > 0) {
+ lines.push(truncateToWidth(`${PAD} ${theme.fg("muted", `+${hidden} more`)}`, safeWidth));
+ }
+ return lines;
+ }
+
+ private header(): string {
+ const count = this.nodes.length;
+ const noun = count === 1 ? "agent" : "agents";
+ return theme.fg("text", `Running ${count} ${noun}…`);
+ }
+
+ private renderNode(
+ lines: string[],
+ node: ChildAgentInspectorNode,
+ isLast: boolean,
+ icon: string,
+ width: number,
+ ): void {
+ const edge = theme.fg("text", `${isLast ? "└" : "├"} `);
+ lines.push(truncateToWidth(`${PAD}${edge}${icon} ${this.nodeSummary(node)}`, width));
+
+ // Always a second line: the recap once we have it, else a live activity label
+ // (mirroring the main agent's "Writing code" / "Executing" status) so the row
+ // is never blank while we wait for the recap.
+ const childEdge = theme.fg("text", isLast ? " " : "│ ");
+ const connector = theme.fg("dim", "└ ");
+ const prefix = `${PAD}${childEdge}${connector}`;
+ const detail = node.recap?.trim() || nodeActivityLabel(node);
+ const text = truncateToWidth(detail, Math.max(1, width - visibleWidth(prefix)));
+ lines.push(`${prefix}${theme.fg("dim", text)}`);
+ }
+
+ private nodeSummary(node: ChildAgentInspectorNode): string {
+ const parts = [theme.fg("text", compactLabel(node.label))];
+ const meta: string[] = [];
+ if (node.toolUseCount && node.toolUseCount > 0) {
+ meta.push(`${node.toolUseCount} ${node.toolUseCount === 1 ? "tool use" : "tool uses"}`);
+ }
+ if (node.tokenCount && node.tokenCount > 0) {
+ meta.push(`${formatTokenCount(node.tokenCount)} tokens`);
+ }
+ if (meta.length > 0) {
+ parts.push(theme.fg("muted", `· ${meta.join(" · ")}`));
+ }
+ return parts.join(" ");
+ }
+}
+
+/**
+ * A main-agent-style activity label ("Waiting" / "Writing" / "Executing") derived from
+ * the subagent's latest transcript entry, shown until its recap lands.
+ */
+function nodeActivityLabel(node: ChildAgentInspectorNode): string {
+ if (node.status === "queued") {
+ return "Waiting";
+ }
+ const last = lastMeaningfulEntry(node.structuredTranscript);
+ if (!last) {
+ return "Waiting";
+ }
+ if (last.type === "tool") {
+ // Still running its tool vs. finished and about to think again.
+ return last.isPartial ? `Executing ${last.toolName}` : "Waiting";
+ }
+ if (last.type === "message" && last.role === "assistant") {
+ return "Writing";
+ }
+ return "Waiting";
+}
+
+function lastMeaningfulEntry(
+ transcript: readonly ChildAgentStructuredTranscriptEntry[] | undefined,
+): ChildAgentStructuredTranscriptEntry | undefined {
+ if (!transcript) {
+ return undefined;
+ }
+ for (let i = transcript.length - 1; i >= 0; i--) {
+ const entry = transcript[i];
+ if (entry && entry.type !== "system") {
+ return entry;
+ }
+ }
+ return undefined;
+}
+
+/** First few words of the prompt, clipped to a sensible width with an ellipsis. */
+function compactLabel(label: string): string {
+ const words = label.trim().split(/\s+/);
+ let compact = words.slice(0, LABEL_MAX_WORDS).join(" ");
+ const clipped = words.length > LABEL_MAX_WORDS;
+ if (compact.length > LABEL_MAX_CHARS) {
+ compact = compact.slice(0, LABEL_MAX_CHARS).trimEnd();
+ return `${compact}…`;
+ }
+ return clipped ? `${compact}…` : compact;
+}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index cb9f9d8071..4e75704187 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -157,6 +157,7 @@ import { ScopedModelsSelectorComponent } from "./components/scoped-models-select
import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
+import { SubagentTreeView } from "./components/subagent-tree-view.js";
import { ToolExecutionComponent, type ToolExecutionDefinition } from "./components/tool-execution.js";
import { TreeSelectorComponent } from "./components/tree-selector.js";
import { UserMessageComponent } from "./components/user-message.js";
@@ -552,6 +553,9 @@ export class InteractiveMode {
// RLM child-agent tray: inline list below the editor, full-screen detail on open.
private childAgentSummary: ChildAgentSummaryComponent;
+ // Live tree of the current turn's subagents, drawn above the working loader.
+ // Shown in addition to the inline list below the prompt bar.
+ private subagentTree = new SubagentTreeView();
private childAgentDetail: ChildAgentDetailComponent;
private childAgentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();
private childAgentNodes: ChildAgentInspectorNode[] = [];
@@ -2407,22 +2411,16 @@ export class InteractiveMode {
? undefined
: this.formatWorkingElapsed(Date.now() - this.workingStartedAt);
const status = this.activityTracker.getStatus();
- const runningSubagents = this.countRunningChildAgents();
- // Subagents-only (turn ended, subagents still running): just the count, no
- // elapsed timer (it resets on view return) and no stale extension message.
+ // The subagent count/recaps live in the tree above the loader, so the loader
+ // message itself no longer repeats "N subagents running".
if (!this.isAgentStreaming()) {
- return runningSubagents > 0
- ? `${runningSubagents} ${runningSubagents === 1 ? "subagent" : "subagents"} running`
- : "";
+ return "";
}
if (this.workingMessage !== undefined) {
// Extensions and tool bootstrap own the message; keep the plain "<message> <elapsed>" form.
return elapsed === undefined ? this.workingMessage : `${this.workingMessage} ${elapsed}`;
}
const parts: string[] = [AGENT_ACTIVITY_LABELS[status.activity]];
- if (runningSubagents > 0) {
- parts.push(`${runningSubagents} ${runningSubagents === 1 ? "subagent" : "subagents"} running`);
- }
if (elapsed !== undefined) {
parts.push(elapsed);
}
@@ -4372,6 +4370,7 @@ export class InteractiveMode {
}
this.childAgentNodes = this.buildChildAgentInspectorNodes();
this.childAgentSummary.setNodes(this.childAgentNodes);
+ this.subagentTree.setNodes(this.childAgentNodes);
this.updateWorkingPulse();
this.syncWorkingLoader();
this.updateWorkingLoaderMessage();
@@ -4399,6 +4398,8 @@ export class InteractiveMode {
this.mainViewContainer.clear();
this.mainViewContainer.addChild(this.chatContainer);
this.mainViewContainer.addChild(this.pendingMessagesContainer);
+ // Subagent tree sits directly above the loader, mirroring Claude's layout.
+ this.mainViewContainer.addChild(this.subagentTree);
this.mainViewContainer.addChild(this.statusContainer);
}
@@ -4406,6 +4407,7 @@ export class InteractiveMode {
this.childAgentSnapshots.clear();
this.childAgentNodes = [];
this.childAgentSummary.setNodes([]);
+ this.subagentTree.setNodes([]);
this.childAgentSummary.setHidden(false);
this.childAgentDetail.setNode(undefined);
this.childAgentDetailNodeId = undefined;
@@ -4608,6 +4610,9 @@ export class InteractiveMode {
status: child.status,
durationMs: child.durationMs,
answerPreview: child.answerPreview,
+ toolUseCount: child.toolUseCount,
+ tokenCount: child.tokenCount,
+ recap: child.recap,
sessionDir: child.sessionDir,
transcript: child.transcript.map(
(line): ChildAgentTranscriptLine => ({
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index aa31f52e7c..36a0d161e5 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -253,6 +253,8 @@ describe("AgentSession rlm recursion", () => {
status: string;
label: string;
answerPreview?: string;
+ tokenCount?: number;
+ toolUseCount?: number;
transcript: readonly { role: string; text: string }[];
structuredTranscript?: readonly { type: string; role: string; text: string }[];
}> = [];
@@ -276,6 +278,9 @@ describe("AgentSession rlm recursion", () => {
expect(childUpdates[0]?.label).toBe("summarize shard 1");
const doneUpdate = [...childUpdates].reverse().find((update) => update.status === "done");
expect(doneUpdate?.answerPreview).toBe("child answer: summarize shard 1");
+ // Context tokens from the child's own assistant usage (input 7 + output 3); no tools ran.
+ expect(doneUpdate?.tokenCount).toBe(10);
+ expect(doneUpdate?.toolUseCount).toBeUndefined();
expect(doneUpdate?.transcript).toContainEqual({ role: "user", text: "summarize shard 1" });
expect(doneUpdate?.transcript).toContainEqual({ role: "assistant", text: "child answer: summarize shard 1" });
expect(doneUpdate?.structuredTranscript).toEqual(
@@ -286,6 +291,47 @@ describe("AgentSession rlm recursion", () => {
);
});
+ it("surfaces a child's recap on its snapshot once the summarizer sets it", async () => {
+ let releaseChild: () => void = () => {};
+ const release = new Promise<void>((resolve) => {
+ releaseChild = resolve;
+ });
+ let childStarted = false;
+ const root = createSession({
+ streamFn: (_model, context) => {
+ const text = userText(context);
+ const stream = createAssistantMessageEventStream();
+ childStarted = true;
+ void release.then(() => {
+ stream.push({ type: "done", reason: "stop", message: assistantMessage(`child answer: ${text}`) });
+ });
+ return stream;
+ },
+ });
+
+ const recaps: Array<string | undefined> = [];
+ root.subscribe((event) => {
+ if (event.type === "rlm_child_update") {
+ recaps.push(event.child.recap);
+ }
+ });
+
+ const runPromise = root.runRlmChild("slow shard");
+ await waitFor(() => childStarted);
+ const rootRun = [...(root as unknown as InspectableRlmSession)._activeRlmChildRuns.values()][0];
+ if (!rootRun?.session) {
+ throw new Error("Missing child session on root run");
+ }
+
+ // What the daemon summarizer does for subagents: stash the recap on the session,
+ // which emits recap_update and re-emits the parent's enriched child snapshot.
+ rootRun.session.setCurrentRecap("Summarizing the slow shard");
+ await waitFor(() => recaps.includes("Summarizing the slow shard"));
+
+ releaseChild();
+ await runPromise;
+ });
+
it("surfaces missing ripgrep as one child-agent error before model work starts", async () => {
toolsManagerMock.ensureTool.mockResolvedValueOnce(undefined);
const streamFn = vi.fn((_model, context: Context) => streamAnswer(`child answer: ${userText(context)}`));
diff --git a/packages/coding-agent/test/subagent-tree-view.test.ts b/packages/coding-agent/test/subagent-tree-view.test.ts
new file mode 100644
index 0000000000..40d3bbbbce
--- /dev/null
+++ b/packages/coding-agent/test/subagent-tree-view.test.ts
@@ -0,0 +1,228 @@
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, test } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import type { ChildAgentInspectorNode } from "../src/modes/interactive/components/child-agent-inspector.js";
+import { SubagentTreeView } from "../src/modes/interactive/components/subagent-tree-view.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+function node(overrides: Partial<ChildAgentInspectorNode> & { id: string }): ChildAgentInspectorNode {
+ return {
+ label: overrides.id,
+ status: "running",
+ sessionDir: `/tmp/${overrides.id}`,
+ transcript: [],
+ ...overrides,
+ };
+}
+
+function renderText(view: SubagentTreeView, width = 100): string {
+ return stripAnsi(view.render(width).join("\n"));
+}
+
+describe("SubagentTreeView", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ test("renders nothing when there are no live subagents", () => {
+ const view = new SubagentTreeView();
+ expect(view.render(100)).toEqual([]);
+ expect(view.hasNodes()).toBe(false);
+ });
+
+ test("only in-flight subagents show; finished ones disappear", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([
+ node({ id: "a", status: "running" }),
+ node({ id: "b", status: "queued" }),
+ node({ id: "done", status: "done" }),
+ node({ id: "err", status: "error" }),
+ ]);
+ expect(view.hasNodes()).toBe(true);
+ const text = renderText(view);
+ // running + queued counted; done/error dropped entirely.
+ expect(text).toContain("Running 2 agents…");
+ expect(text).not.toContain("done");
+ expect(text).not.toContain("err");
+ });
+
+ test("includes in-flight nested subagents from the children tree", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([
+ node({
+ id: "parent",
+ label: "parent",
+ status: "running",
+ children: [
+ node({ id: "child-run", label: "nested running", status: "running" }),
+ node({ id: "child-done", label: "nested done", status: "done" }),
+ ],
+ }),
+ ]);
+ const text = renderText(view);
+ // parent + nested running counted; nested done dropped.
+ expect(text).toContain("Running 2 agents…");
+ expect(text).toContain("nested running");
+ expect(text).not.toContain("nested done");
+ });
+
+ test("shows a running nested subagent even when its parent has finished", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([
+ node({
+ id: "parent",
+ label: "parent",
+ status: "done",
+ children: [node({ id: "child-run", label: "nested running", status: "running" })],
+ }),
+ ]);
+ const text = renderText(view);
+ expect(text).toContain("Running 1 agent…");
+ expect(text).toContain("nested running");
+ expect(text).not.toContain("parent");
+ });
+
+ test("disappears once every subagent is done", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "a", status: "done" }), node({ id: "b", status: "cancelled" })]);
+ expect(view.render(100)).toEqual([]);
+ });
+
+ test("header pluralizes on the live count", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "a" })]);
+ expect(renderText(view)).toContain("Running 1 agent…");
+ view.setNodes([node({ id: "a" }), node({ id: "b" })]);
+ expect(renderText(view)).toContain("Running 2 agents…");
+ });
+
+ test("opens with a blank line and a single-space left pad", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "x", label: "scout", recap: "looking" })]);
+ const lines = view.render(100).map((line) => stripAnsi(line));
+ expect(lines[0]).toBe(""); // spacing above so it doesn't hug the tool call
+ expect(lines[1]).toBe(" Running 1 agent…"); // one-space left padding
+ expect(lines.slice(2).every((line) => line.startsWith(" "))).toBe(true);
+ });
+
+ test("every node is two lines: summary then recap", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([
+ node({
+ id: "x",
+ label: "Angle A scan",
+ toolUseCount: 22,
+ tokenCount: 41000,
+ recap: "Searching for 6 patterns",
+ }),
+ ]);
+ const text = renderText(view);
+ expect(text).toContain("Angle A scan · 22 tool uses · 41k tokens");
+ expect(text).toContain("Searching for 6 patterns");
+ });
+
+ test("falls back to a live activity label until the recap lands", () => {
+ const view = new SubagentTreeView();
+ // No transcript yet -> Waiting.
+ view.setNodes([node({ id: "x", label: "scout" })]);
+ // header + blank + 2 node lines = 4
+ expect(view.render(100)).toHaveLength(4);
+ expect(renderText(view)).toContain("Waiting");
+
+ // A tool still running -> Executing <tool>.
+ view.setNodes([
+ node({
+ id: "x",
+ label: "scout",
+ structuredTranscript: [
+ {
+ type: "tool",
+ role: "tool",
+ text: "",
+ toolCallId: "1",
+ toolName: "Bash",
+ args: {},
+ isPartial: true,
+ executionStarted: true,
+ argsComplete: true,
+ },
+ ],
+ }),
+ ]);
+ expect(renderText(view)).toContain("Executing Bash");
+
+ // Assistant text streaming -> Writing.
+ view.setNodes([
+ node({
+ id: "x",
+ label: "scout",
+ structuredTranscript: [
+ { type: "message", role: "assistant", text: "thinking out loud", message: {} as never },
+ ],
+ }),
+ ]);
+ expect(renderText(view)).toContain("Writing");
+
+ // Queued -> Waiting regardless of transcript.
+ view.setNodes([node({ id: "x", label: "scout", status: "queued" })]);
+ expect(renderText(view)).toContain("Waiting");
+ });
+
+ test("the recap wins over the activity label once present", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([
+ node({
+ id: "x",
+ label: "scout",
+ recap: "Searching for 6 patterns",
+ structuredTranscript: [
+ {
+ type: "tool",
+ role: "tool",
+ text: "",
+ toolCallId: "1",
+ toolName: "Bash",
+ args: {},
+ isPartial: true,
+ executionStarted: true,
+ argsComplete: true,
+ },
+ ],
+ }),
+ ]);
+ const text = renderText(view);
+ expect(text).toContain("Searching for 6 patterns");
+ expect(text).not.toContain("Executing");
+ });
+
+ test("animates the working icon — frames differ as the pulse advances", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "x", label: "scout" })]);
+ // The icon is read from the process-wide pulse frame at render time; the
+ // summary line carries one of the working icon glyphs.
+ const summaryLine = stripAnsi(view.render(100)[2] ?? "");
+ expect(summaryLine).toMatch(/[◇◈◆]/);
+ });
+
+ test("never leaks the transcript onto the recap line", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "x", label: "scout", transcript: [{ role: "tool", text: "Bash: rm -rf secret" }] })]);
+ expect(renderText(view)).not.toContain("Bash: rm -rf secret");
+ });
+
+ test("caps the label to a few words", () => {
+ const view = new SubagentTreeView();
+ view.setNodes([node({ id: "x", label: "find every place the parser touches the old config schema" })]);
+ const text = renderText(view);
+ expect(text).toContain("find every place the…");
+ expect(text).not.toContain("schema");
+ });
+
+ test("caps at five nodes with a +N more line", () => {
+ const view = new SubagentTreeView();
+ view.setNodes(Array.from({ length: 7 }, (_, i) => node({ id: `run-${i}`, label: `run-${i}` })));
+ expect(renderText(view)).toContain("+2 more"); // 7 live, 5 shown
+ });
+});