A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): delete child-agent inspector; one subagent summary line (#587)
Sebastian Müller396fefa500b0
diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.tsindex 7d6c2433e4..d28c37976b 100644--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts@@ -15,6 +15,8 @@ export interface DaemonSocketClient {catchupPurposes?: Map<string, "replacement" | "resync">;/** The single catch-up drain currently serving this client. */catchupPromise?: Promise<void>;+ /** Delayed retry after transient catch-up snapshot preparation failure. */+ catchupRetryTimer?: NodeJS.Timeout;backpressured?: boolean;authenticated?: boolean;transport?: "jsonl" | "private-framed";diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex d2f54c385d..9493175ad3 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -67,7 +67,7 @@ import {normalizeObserveLimit,normalizeObserveMaxChars,} from "../../core/agent-observe.js";-import type { AgentSession, PromptOptions } from "../../core/agent-session.js";+import { type AgentSession, type PromptOptions, rlmChildLabel } from "../../core/agent-session.js";import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";import {AgentSessionRuntime,@@ -115,7 +115,7 @@ import {createAgentConnectionState,} from "../agent-connection/snapshot.js";import { createAgentConnectionToolDefinition } from "../agent-connection/tool-definition.js";-import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";+import type { AgentConnectionHeartbeat, AgentConnectionRlmChildAgentSnapshot } from "../agent-connection/types.js";import { waitForHeadlessCompletion } from "../headless-completion.js";import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";import { encodePrivateFrame, PrivateFrameDecoder } from "../session-worker/private-framing.js";@@ -313,6 +313,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([]);const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SUPPORTED_CLIENT_CAPABILITIES);+const CLIENT_CATCHUP_RETRY_MS = 250;const UPDATE_RESTART_ABORT_BASH_TIMEOUT_MS = 5000;const SUPERVISOR_FENCE_POLL_MS = 250;const UPDATE_RESTART_MARKER =@@ -1051,6 +1052,40 @@ export class AgentDaemon {);}+ /** Add saved-only descendants discovered by the shared passive-registry walk. */+ private async buildRlmChildSnapshotsWithPassiveRlmSubagents(+ rootState: ActiveSessionState,+ ): Promise<AgentConnectionRlmChildAgentSnapshot[]> {+ const snapshots = buildRlmChildSnapshots(rootState.activeSessionId, [...this.sessions.values()]);+ const residentParentIds = new Set([+ rootState.activeSessionId,+ ...snapshots.flatMap((snapshot) => (snapshot.activeSessionId ? [snapshot.activeSessionId] : [])),+ ]);+ const seenChildIds = new Set(snapshots.map((snapshot) => snapshot.id));+ for (const passive of await this.listPassiveRlmSubagents()) {+ if (+ !passive.rootParentState ||+ !residentParentIds.has(passive.rootParentState.activeSessionId) ||+ seenChildIds.has(passive.entry.childId)+ ) {+ continue;+ }+ const parentEntry = passive.chain.at(-2);+ const parentId = parentEntry?.childId ?? passive.rootParentState.runtime.metadata.rlmChildId;+ snapshots.push({+ id: passive.entry.childId,+ ...(parentId ? { parentId } : {}),+ sessionName: passive.info.name ?? passive.entry.sessionName,+ model: passive.entry.model ? `${passive.entry.model.provider}/${passive.entry.model.modelId}` : undefined,+ label: rlmChildLabel(passive.entry.prompt ?? ""),+ status: "done",+ sessionDir: passive.entry.sessionDir,+ });+ seenChildIds.add(passive.entry.childId);+ }+ return snapshots;+ }+private async buildSessionListWithPassiveRlmSubagents(activeSessions: ActiveSessionState[],savedSessions: SessionInfo[],@@ -2614,6 +2649,7 @@ export class AgentDaemon {cleanedUp = true;socket.off("close", cleanup);socket.off("error", cleanup);+ this.clearClientCatchupRetry(client);this.detachClient(client);client.detachInput();this.clients.delete(client);@@ -3122,7 +3158,7 @@ export class AgentDaemon {client.attachedActiveSessionIds.add(state.activeSessionId);let result: DaemonAttachResult;try {- result = this.createAttachResult(client, state, command);+ result = await this.createAttachResult(client, state, command);} catch (error) {state.clients.delete(client);client.attachedActiveSessionIds.delete(state.activeSessionId);@@ -4023,12 +4059,12 @@ export class AgentDaemon {}}- private createAttachResult(+ private async createAttachResult(client: DaemonSocketClient,state: ActiveSessionState,command: Extract<DaemonCommand, { type: "attach" }>,- ): DaemonAttachResult {- const snapshot = this.createSessionSnapshot(state);+ ): Promise<DaemonAttachResult> {+ const snapshot = await this.createSessionSnapshot(state);const replay =command.resumeCursor?.activeSessionId && command.resumeCursor.activeSessionId !== state.activeSessionId? {@@ -4061,7 +4097,7 @@ export class AgentDaemon {};}- private createSessionSnapshot(state: ActiveSessionState): DaemonSessionSnapshot {+ private async createSessionSnapshot(state: ActiveSessionState): Promise<DaemonSessionSnapshot> {const metadata = state.runtime.metadata;const parent =metadata.parentActiveSessionId || metadata.parentSessionId || metadata.rlmParentNodeId || metadata.rlmChildId@@ -4072,7 +4108,7 @@ export class AgentDaemon {...(metadata.rlmChildId ? { childId: metadata.rlmChildId } : {}),}: undefined;- const children = buildRlmChildSnapshots(state.activeSessionId, [...this.sessions.values()]);+ const children = await this.buildRlmChildSnapshotsWithPassiveRlmSubagents(state);const connectionState = this.createConnectionState(state);return {activeSessionId: state.activeSessionId,@@ -5113,6 +5149,9 @@ export class AgentDaemon {} catch (error) {disposeError = error;}+ for (const client of state.clients) {+ abortClientSnapshotStreaming(client, state.activeSessionId);+ }this.broadcastToSession(state, { type: "session_closed", activeSessionId: state.activeSessionId, reason });for (const client of state.clients) {client.attachedActiveSessionIds.delete(state.activeSessionId);@@ -5207,66 +5246,7 @@ export class AgentDaemon {client.transport === "private-framed" &&daemonClientCapabilitiesForSession(client, state.activeSessionId).has("chunked_snapshot")) {- try {- const result = this.createAttachResult(client, state, {- type: "attach",- activeSessionId: state.activeSessionId,- });- const snapshotId = `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;- this.write(client, {- ...sequencedMessage,- messages: [],- snapshotFollows: true,- });- const snapshotSignal = markClientSnapshotStreaming(client, state.activeSessionId);- let transcript: SnapshotTranscriptChunkSource;- try {- transcript = createSnapshotTranscriptChunks({- activeSessionId: state.activeSessionId,- snapshotId,- messages: result.snapshot.messages,- targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,- signal: snapshotSignal,- });- } catch (error) {- finishClientSnapshotStreaming(client, state.activeSessionId);- throw error;- }- void this.streamWorkerSnapshot(- client,- {- ...result,- messages: result.messages ? [] : undefined,- snapshot: { ...result.snapshot, messages: [] },- snapshotStream: {- id: snapshotId,- messageCount: result.snapshot.messages.length,- targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,- },- },- transcript,- "replacement",- snapshotSignal,- true,- ).catch((error) => {- this.log(`could not stream replacement snapshot: ${String(error)}`);- this.queueClientCatchup(client, state.activeSessionId, "replacement");- if (!client.snapshotStreaming) {- void this.catchUpBackpressuredClient(client).catch((catchupError) =>- this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),- );- }- });- } catch (error) {- this.log(`could not prepare replacement snapshot: ${String(error)}`);- // Continue below with the complete replacement event.- if (client.transport === "private-framed") {- this.write(client, sequencedMessage);- } else {- serialized ??= serializeJsonLine(sequencedMessage);- this.writeSerialized(client, serialized, sequencedMessage);- }- }+ this.beginReplacementSnapshot(client, state, sequencedMessage);continue;}if (client.transport === "private-framed") {@@ -5278,6 +5258,83 @@ export class AgentDaemon {}}+ private beginReplacementSnapshot(+ client: DaemonSocketClient,+ state: ActiveSessionState,+ message: Extract<DaemonOutbound, { type: "session_replaced" }>,+ ): void {+ const snapshotId = `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;+ // Mark before the registry read so later events queue behind this snapshot.+ const snapshotSignal = markClientSnapshotStreaming(client, state.activeSessionId);+ void this.prepareReplacementSnapshot(client, state, message, snapshotId, snapshotSignal).catch((error) => {+ finishClientSnapshotStreaming(client, state.activeSessionId);+ this.log(`could not prepare replacement snapshot: ${String(error)}`);+ if (!client.socket.destroyed && this.sessions.get(state.activeSessionId) === state) {+ this.write(client, message);+ }+ if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {+ void this.catchUpBackpressuredClient(client).catch((catchupError) =>+ this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),+ );+ }+ });+ }++ private async prepareReplacementSnapshot(+ client: DaemonSocketClient,+ state: ActiveSessionState,+ message: Extract<DaemonOutbound, { type: "session_replaced" }>,+ snapshotId: string,+ snapshotSignal: AbortSignal,+ ): Promise<void> {+ const result = await this.createAttachResult(client, state, {+ type: "attach",+ activeSessionId: state.activeSessionId,+ });+ if (this.sessions.get(state.activeSessionId) !== state) {+ finishClientSnapshotStreaming(client, state.activeSessionId);+ if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {+ void this.catchUpBackpressuredClient(client).catch((catchupError) =>+ this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),+ );+ }+ return;+ }+ const transcript = createSnapshotTranscriptChunks({+ activeSessionId: state.activeSessionId,+ snapshotId,+ messages: result.snapshot.messages,+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,+ signal: snapshotSignal,+ });+ this.write(client, { ...message, messages: [], snapshotFollows: true });+ void this.streamWorkerSnapshot(+ client,+ {+ ...result,+ messages: result.messages ? [] : undefined,+ snapshot: { ...result.snapshot, messages: [] },+ snapshotStream: {+ id: snapshotId,+ messageCount: result.snapshot.messages.length,+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,+ },+ },+ transcript,+ "replacement",+ snapshotSignal,+ true,+ ).catch((error) => {+ this.log(`could not stream replacement snapshot: ${String(error)}`);+ this.queueClientCatchup(client, state.activeSessionId, "replacement");+ if (!client.snapshotStreaming) {+ void this.catchUpBackpressuredClient(client).catch((catchupError) =>+ this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),+ );+ }+ });+ }+private broadcastGlobal(message: DaemonOutbound): void {for (const client of this.clients) {this.write(client, message);@@ -5311,6 +5368,7 @@ export class AgentDaemon {if (client.snapshotStreaming || client.backpressured) {return Promise.resolve();}+ this.clearClientCatchupRetry(client);const catchup = this.drainBackpressuredClientCatchupQueue(client).finally(() => {if (client.catchupPromise === catchup) {client.catchupPromise = undefined;@@ -5320,6 +5378,33 @@ export class AgentDaemon {return catchup;}+ private clearClientCatchupRetry(client: DaemonSocketClient): void {+ if (!client.catchupRetryTimer) {+ return;+ }+ clearTimeout(client.catchupRetryTimer);+ client.catchupRetryTimer = undefined;+ }++ private scheduleClientCatchupRetry(client: DaemonSocketClient): void {+ if (client.socket.destroyed || client.catchupRetryTimer) {+ return;+ }+ client.catchupRetryTimer = setTimeout(() => {+ client.catchupRetryTimer = undefined;+ if (client.socket.destroyed || !client.catchupActiveSessionIds?.size) {+ return;+ }+ if (client.snapshotStreaming || client.backpressured) {+ this.scheduleClientCatchupRetry(client);+ return;+ }+ void this.catchUpBackpressuredClient(client).catch((error) =>+ this.log(`could not retry catch-up for client ${client.id}: ${String(error)}`),+ );+ }, CLIENT_CATCHUP_RETRY_MS);+ }+private async drainBackpressuredClientCatchupQueue(client: DaemonSocketClient): Promise<void> {while (!client.socket.destroyed &&@@ -5327,13 +5412,15 @@ export class AgentDaemon {!client.backpressured &&client.catchupActiveSessionIds?.size) {- await this.drainBackpressuredClientCatchups(client);+ if ((await this.drainBackpressuredClientCatchups(client)) === "retry-later") {+ return;+ }}}- private async drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<void> {+ private async drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<"drained" | "retry-later"> {if (client.socket.destroyed) {- return;+ return "drained";}const pending = [...(client.catchupActiveSessionIds ?? [])].map((activeSessionId) => ({activeSessionId,@@ -5347,81 +5434,96 @@ export class AgentDaemon {if (!state || !state.clients.has(client)) {continue;}- const result = this.createAttachResult(client, state, {- type: "attach",- activeSessionId,- });- if (- client.transport === "private-framed" &&- daemonClientCapabilitiesForSession(client, activeSessionId).has("chunked_snapshot")- ) {- if (purpose === "replacement") {- this.write(client, {- type: "session_replaced",- activeSessionId,- state: result.snapshot.state,- messages: [],- snapshotFollows: true,- meta: createDaemonEventMeta(- activeSessionId,- state.lastEventSequence,- undefined,- state.eventGeneration,- ),- });- }- const snapshotId = `${activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;- const snapshotSignal = markClientSnapshotStreaming(client, activeSessionId);- let transcript: SnapshotTranscriptChunkSource;- try {- transcript = createSnapshotTranscriptChunks({- activeSessionId,- snapshotId,- messages: result.snapshot.messages,- targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,- signal: snapshotSignal,- });- } catch (error) {- finishClientSnapshotStreaming(client, activeSessionId);- throw error;- }- await this.streamWorkerSnapshot(- client,- {- ...result,- messages: result.messages ? [] : undefined,- snapshot: { ...result.snapshot, messages: [] },- snapshotStream: {- id: snapshotId,- messageCount: result.snapshot.messages.length,- targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,- },- },- transcript,- purpose === "replacement" ? "replacement" : "catchup",- snapshotSignal,- true,- );- continue;- }- const meta = createDaemonEventMeta(activeSessionId, state.lastEventSequence, undefined, state.eventGeneration);- const catchup: DaemonOutbound =- purpose === "replacement"- ? {+ try {+ const result = await this.createAttachResult(client, state, {+ type: "attach",+ activeSessionId,+ });+ if (+ client.transport === "private-framed" &&+ daemonClientCapabilitiesForSession(client, activeSessionId).has("chunked_snapshot")+ ) {+ if (purpose === "replacement") {+ this.write(client, {type: "session_replaced",activeSessionId,state: result.snapshot.state,+ messages: [],+ snapshotFollows: true,+ meta: createDaemonEventMeta(+ activeSessionId,+ state.lastEventSequence,+ undefined,+ state.eventGeneration,+ ),+ });+ }+ const snapshotId = `${activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;+ const snapshotSignal = markClientSnapshotStreaming(client, activeSessionId);+ let transcript: SnapshotTranscriptChunkSource;+ try {+ transcript = createSnapshotTranscriptChunks({+ activeSessionId,+ snapshotId,messages: result.snapshot.messages,- meta,- }- : { type: "session_resynced", activeSessionId, snapshot: result.snapshot, meta };- if (!this.write(client, catchup)) {- for (const remaining of pending.slice(index + 1)) {+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,+ signal: snapshotSignal,+ });+ } catch (error) {+ finishClientSnapshotStreaming(client, activeSessionId);+ throw error;+ }+ await this.streamWorkerSnapshot(+ client,+ {+ ...result,+ messages: result.messages ? [] : undefined,+ snapshot: { ...result.snapshot, messages: [] },+ snapshotStream: {+ id: snapshotId,+ messageCount: result.snapshot.messages.length,+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,+ },+ },+ transcript,+ purpose === "replacement" ? "replacement" : "catchup",+ snapshotSignal,+ true,+ );+ continue;+ }+ const meta = createDaemonEventMeta(+ activeSessionId,+ state.lastEventSequence,+ undefined,+ state.eventGeneration,+ );+ const catchup: DaemonOutbound =+ purpose === "replacement"+ ? {+ type: "session_replaced",+ activeSessionId,+ state: result.snapshot.state,+ messages: result.snapshot.messages,+ meta,+ }+ : { type: "session_resynced", activeSessionId, snapshot: result.snapshot, meta };+ if (!this.write(client, catchup)) {+ for (const remaining of pending.slice(index + 1)) {+ this.queueClientCatchup(client, remaining.activeSessionId, remaining.purpose);+ }+ return "retry-later";+ }+ } catch (error) {+ for (const remaining of pending.slice(index)) {this.queueClientCatchup(client, remaining.activeSessionId, remaining.purpose);}- return;+ this.log(`could not catch up client ${client.id} for ${activeSessionId}: ${String(error)}`);+ this.scheduleClientCatchupRetry(client);+ return "retry-later";}}+ return "drained";}private queueClientCatchup(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.tsdeleted file mode 100644index 33bca0e87b..0000000000--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts+++ /dev/null@@ -1,873 +0,0 @@-import { getModels, type KnownProvider } from "@earendil-works/pi-ai";-import {- type Component,- type Focusable,- getKeybindings,- type Keybinding,- Loader,- type TUI,- truncateToWidth,- visibleWidth,-} from "@earendil-works/pi-tui";-import { AGENT_ACTIVITY_LABELS, formatTokenCount } from "../agent-activity.js";-import { theme } from "../theme/theme.js";-import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";-import { keyText } from "./keybinding-hints.js";--export type ChildAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";--export interface ChildAgentActivity {- kind: "waiting" | "writing" | "executing";- toolName?: string;-}--export interface ChildAgentInspectorNode {- id: string;- /** The child's own daemon active-session id, for attaching directly to its stream. */- activeSessionId?: string;- /** Stable daemon-visible session name for addressing/displaying the child. */- sessionName?: string;- /** Exact provider/model selector used by the child. */- model?: string;- label: string;- status: ChildAgentStatus;- durationMs?: number;- answerPreview?: string;- toolUseCount?: number;- tokenCount?: number;- recap?: string;- sessionDir: string;- activity?: ChildAgentActivity;- hasActiveHeartbeat?: boolean;- error?: string;- children?: readonly ChildAgentInspectorNode[];-}--export interface ChildAgentDetailOptions {- ui?: TUI;-}--interface FlatChildAgentNode {- node: ChildAgentInspectorNode;-}--interface DetailSections {- headerLines: string[];- bodyLines: string[];-}--interface ExpandableComponent extends Component {- setExpanded(expanded: boolean): void;-}--function isExpandableComponent(component: Component): component is ExpandableComponent {- return "setExpanded" in component && typeof (component as { setExpanded?: unknown }).setExpanded === "function";-}--// Active before finished, so completed agents settle to the bottom.-function childAgentSortRank(node: ChildAgentInspectorNode): number {- return node.status === "running" || node.status === "queued" || node.hasActiveHeartbeat ? 0 : 1;-}--function flattenChildAgentNodes(nodes: readonly ChildAgentInspectorNode[]): FlatChildAgentNode[] {- const result: FlatChildAgentNode[] = [];- const walk = (items: readonly ChildAgentInspectorNode[]): void => {- const ordered = [...items].sort((a, b) => childAgentSortRank(a) - childAgentSortRank(b));- for (const node of ordered) {- result.push({ node });- walk(node.children ?? []);- }- };- walk(nodes);- return result;-}--interface KeyActionOptions {- primaryOnly?: boolean;-}--function keyAction(keybinding: Keybinding, description: string, options: KeyActionOptions = {}): string | undefined {- const keys = keyText(keybinding, options).trim();- return keys ? `${theme.fg("dim", keys)}${theme.fg("muted", ` ${description}`)}` : undefined;-}--function combinedKeyAction(keybindings: readonly Keybinding[], description: string): string | undefined {- const keys = keybindings- .map((keybinding) => keyText(keybinding).trim())- .filter((key) => key.length > 0)- .join("/");- return keys ? `${theme.fg("dim", keys)}${theme.fg("muted", ` ${description}`)}` : undefined;-}--function joinHints(hints: ReadonlyArray<string | undefined>): string {- return hints.filter((hint) => hint !== undefined).join(theme.fg("dim", " · "));-}--function hintLine(hints: ReadonlyArray<string | undefined>, width: number): string {- return truncateToWidth(joinHints(hints), width, "");-}--// Matches the agents view delete confirmation window.-const KILL_CONFIRM_DURATION_MS = 2000;--// Left indent for the detail panel's own lines, aligned with the conversation body.-const CONTENT_INDENT = 2;--function isKillableChildAgentStatus(status: ChildAgentStatus): boolean {- return status === "running" || status === "queued";-}--/** A main-agent-style activity label ("Waiting" / "Writing" / "Executing"), shown until the recap lands. */-export function nodeActivityLabel(node: ChildAgentInspectorNode): string {- if (node.status === "queued") {- return "Waiting";- }- switch (node.activity?.kind) {- case "executing":- return node.activity.toolName ? `Executing ${node.activity.toolName}` : "Executing";- case "writing":- return "Writing";- default:- return "Waiting";- }-}--// Subagent list entries mirror the agents view row format: icon, title, right-aligned time.-function childAgentStatusIcon(node: ChildAgentInspectorNode): string {- if (node.hasActiveHeartbeat) {- return "♥";- }- switch (node.status) {- case "queued":- return "◇";- case "running":- return "◆";- case "done":- return "✓";- case "error":- case "cancelled":- return "✗";- default: {- const _exhaustive: never = node.status;- return _exhaustive;- }- }-}--function formatChildAgentStatusIcon(node: ChildAgentInspectorNode, icon: string): string {- if (node.hasActiveHeartbeat) {- return theme.fg("error", icon);- }- switch (node.status) {- case "queued":- return theme.fg("dim", icon);- case "running":- return theme.bold(icon);- case "done":- return theme.fg("success", icon);- case "error":- return theme.fg("error", icon);- case "cancelled":- return theme.fg("warning", icon);- default: {- const _exhaustive: never = node.status;- return _exhaustive;- }- }-}--function formatChildAgentDuration(durationMs: number | undefined): string {- if (durationMs === undefined) {- return "";- }- const seconds = Math.max(0, Math.floor(durationMs / 1000));- if (seconds < 60) {- return `${seconds}s`;- }- const minutes = Math.floor(seconds / 60);- if (minutes < 60) {- return `${minutes}m`;- }- return `${Math.floor(minutes / 60)}h`;-}--function childAgentRecap(node: ChildAgentInspectorNode): string {- const recap = node.recap?.replace(/\s+/g, " ").trim();- return recap || (node.hasActiveHeartbeat ? "Heartbeat active" : nodeActivityLabel(node));-}--function padTableCell(value: string, width: number, ellipsis = ""): string {- const truncated = truncateToWidth(value, width, ellipsis);- return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));-}--function childAgentModelLabel(selector: string | undefined): string {- if (!selector) {- return "";- }- const separatorIndex = selector.indexOf("/");- if (separatorIndex === -1) {- return selector;- }- const provider = selector.slice(0, separatorIndex);- const modelId = selector.slice(separatorIndex + 1);- return getModels(provider as KnownProvider).find((model) => model.id === modelId)?.name ?? modelId;-}--function truncateModelLabel(value: string, width: number): string {- if (visibleWidth(value) <= width) {- return value;- }- if (width <= 1) {- return truncateToWidth(value, width, "");- }- const prefixWidth = Math.max(1, Math.floor((width - 1) * 0.35));- const suffixWidth = width - prefixWidth - 1;- let suffix = "";- for (const character of [...value].reverse()) {- if (visibleWidth(character + suffix) > suffixWidth) {- break;- }- suffix = character + suffix;- }- return `${truncateToWidth(value, prefixWidth, "")}…${suffix}`;-}--// Rows shown at once in the inline list below the prompt; extras scroll.-const SUMMARY_VISIBLE_ROWS = 5;-const SUMMARY_LIST_INDENT = 0;-const SHARED_PREFIX_MIN = 12;-const SUMMARY_COLUMN_GAP = 2;-const SUMMARY_PROMPT_MAX_WIDTH = 24;-const SUMMARY_RECAP_MIN_WIDTH = 12;-const SUMMARY_MODEL_WIDTH = 20;-const SUMMARY_TOKENS_WIDTH = 8;-const SUMMARY_DURATION_WIDTH = 4;-const SUMMARY_TOKEN_TIME_GAP = 2;-const SUMMARY_METRICS_WIDTH =- SUMMARY_MODEL_WIDTH + 1 + SUMMARY_TOKENS_WIDTH + SUMMARY_TOKEN_TIME_GAP + SUMMARY_DURATION_WIDTH;-// Opening chars of the prompt kept for context before eliding a shared prefix.-const PROMPT_LEADING_CONTEXT = 6;-// Words of context kept on each side of the divergence.-const PROMPT_DIFF_CONTEXT_WORDS = 1;--export class ChildAgentSummaryComponent implements Component, Focusable {- focused = false;- private readonly paddingX = 1;- private nodes: readonly ChildAgentInspectorNode[] = [];- private hidden = false;- private selectedId: string | undefined;-- onOpen?: () => void;- onCancel?: () => void;- onExit?: () => void;- onOpenDetail?: (nodeId: string) => void;- // Chat actions that should still work while the list holds focus.- onChatAction?: (data: string) => void;-- constructor(- private readonly getLocationLabel: () => string | undefined = () => undefined,- private readonly getContextLabel: () => string | undefined = () => undefined,- private readonly getOverrideLabel: () => string | undefined = () => undefined,- ) {}-- setNodes(nodes: readonly ChildAgentInspectorNode[]): void {- this.nodes = nodes;- const flat = flattenChildAgentNodes(this.nodes);- if (flat.length === 0) {- this.selectedId = undefined;- return;- }- if (!this.focused || !this.selectedId || !flat.some((entry) => entry.node.id === this.selectedId)) {- this.selectedId =- flat.find(- (entry) =>- entry.node.status === "running" || entry.node.status === "queued" || entry.node.hasActiveHeartbeat,- )?.node.id ?? flat[0]?.node.id;- }- }-- setHidden(hidden: boolean): void {- this.hidden = hidden;- }-- selectNode(nodeId: string): void {- if (flattenChildAgentNodes(this.nodes).some((entry) => entry.node.id === nodeId)) {- this.selectedId = nodeId;- }- }-- hasNodes(): boolean {- return flattenChildAgentNodes(this.nodes).length > 0;- }-- invalidate(): void {- // Render output is derived from node state.- }-- render(width: number): string[] {- if (this.hidden) {- return [];- }-- const safeWidth = Math.max(1, width);- const flat = flattenChildAgentNodes(this.nodes);- const lines = [...this.renderInfoLine(safeWidth)];- lines.push(...this.renderSubagentList(flat, safeWidth));- return lines;- }-- handleInput(data: string): void {- const kb = getKeybindings();- const flat = flattenChildAgentNodes(this.nodes);- const open = () => (this.selectedId ? this.onOpenDetail?.(this.selectedId) : this.onOpen?.());- if (kb.matches(data, "tui.select.confirm") || kb.matches(data, "app.agents.open")) {- open();- return;- }- if (kb.matches(data, "app.agents.back")) {- this.onExit?.();- return;- }- if (kb.matches(data, "tui.select.down")) {- this.moveSelection(1, flat);- return;- }- if (kb.matches(data, "tui.select.up")) {- if (this.isAtFirstRow(flat)) {- this.onCancel?.();- } else {- this.moveSelection(-1, flat);- }- return;- }- if (kb.matches(data, "tui.select.cancel")) {- this.onCancel?.();- return;- }- // Keys the list doesn't own fall through to chat actions (expand tools, etc.).- this.onChatAction?.(data);- }-- private isAtFirstRow(flat: readonly FlatChildAgentNode[]): boolean {- return flat.length === 0 || flat[0]?.node.id === this.selectedId;- }-- private moveSelection(delta: number, flat: readonly FlatChildAgentNode[]): void {- if (flat.length === 0) {- return;- }- const current = Math.max(- 0,- flat.findIndex((entry) => entry.node.id === this.selectedId),- );- const next = Math.max(0, Math.min(flat.length - 1, current + delta));- this.selectedId = flat[next]?.node.id;- }-- private renderInfoLine(width: number): string[] {- const overrideLabel = this.getOverrideLabel()?.trim();- const locationLabel = this.getLocationLabel()?.trim();- const contextLabel = this.getContextLabel()?.trim();- const override = overrideLabel ? theme.fg("muted", overrideLabel) : "";- const location = !override && locationLabel ? theme.fg("muted", locationLabel) : "";- const context = contextLabel ? theme.fg("muted", contextLabel) : "";- const leftSegments = [override, location].filter((segment) => segment.length > 0);- if (leftSegments.length === 0 && !context) {- return [];- }-- const rawLeft = leftSegments.join(theme.fg("dim", " "));- const paddedLine = context- ? this.renderSplitLine(rawLeft, context, width)- : this.renderCompactLine(rawLeft, width);- return [paddedLine];- }-- private renderSubagentList(flat: readonly FlatChildAgentNode[], width: number): string[] {- if (flat.length === 0) {- return [];- }- const contentWidth = Math.max(1, width - this.paddingX * 2);- const selectedIndex = Math.max(- 0,- flat.findIndex((entry) => entry.node.id === this.selectedId),- );- const start = this.focused- ? Math.max(0, Math.min(selectedIndex - (SUMMARY_VISIBLE_ROWS - 1), flat.length - SUMMARY_VISIBLE_ROWS))- : 0;- const clampedStart = Math.max(0, start);- const window = flat.slice(clampedStart, clampedStart + SUMMARY_VISIBLE_ROWS);-- const agentWidth = `S${flat.length}`.length;- const fixedWidth = SUMMARY_LIST_INDENT + 2 + agentWidth + SUMMARY_COLUMN_GAP * 3 + SUMMARY_METRICS_WIDTH;- const flexibleWidth = Math.max(0, contentWidth - fixedWidth);- const recapMinimum = Math.min(SUMMARY_RECAP_MIN_WIDTH, Math.floor(flexibleWidth / 2));- const promptTarget = Math.min(SUMMARY_PROMPT_MAX_WIDTH, Math.max(10, Math.floor(flexibleWidth * 0.34)));- const promptWidth = Math.max(0, Math.min(promptTarget, flexibleWidth - recapMinimum));- const recapWidth = Math.max(0, flexibleWidth - promptWidth);- const promptPrefix = this.sharedPromptPrefix(window);- const promptSuffix = this.sharedPromptSuffix(window, promptPrefix);-- const lines: string[] = [];- for (const entry of window) {- const selected = this.focused && entry.node.id === this.selectedId;- const number = flat.indexOf(entry) + 1;- lines.push(- this.panelLine(- this.renderListEntry(entry, number, agentWidth, promptPrefix, promptSuffix, promptWidth, recapWidth),- width,- selected,- ),- );- }- const scrollHint = this.scrollHint(flat.length, clampedStart, contentWidth);- if (scrollHint) {- lines.push(this.panelLine(scrollHint, width, false));- }- return lines;- }-- // Only elide when the prefix is long enough and leaves a distinguishing tail.- private sharedPromptPrefix(flat: readonly FlatChildAgentNode[]): string {- if (flat.length < 2) {- return "";- }- const labels = flat.map((entry) => this.entryLabel(entry));- let prefix = labels[0] ?? "";- for (const label of labels) {- let i = 0;- while (i < prefix.length && i < label.length && prefix[i] === label[i]) {- i++;- }- prefix = prefix.slice(0, i);- if (!prefix) {- break;- }- }- const minTail = labels.some((label) => label.length <= prefix.length);- return prefix.length >= SHARED_PREFIX_MIN && !minTail ? prefix : "";- }-- // Common trailing run after the divergence, so the diff window can also drop a- // shared tail. Only used when it leaves room past the prefix for a real diff.- private sharedPromptSuffix(flat: readonly FlatChildAgentNode[], prefix: string): string {- if (flat.length < 2 || !prefix) {- return "";- }- const labels = flat.map((entry) => this.entryLabel(entry));- let suffix = labels[0] ?? "";- for (const label of labels) {- let i = 0;- while (- i < suffix.length &&- i < label.length &&- suffix[suffix.length - 1 - i] === label[label.length - 1 - i]- ) {- i++;- }- suffix = suffix.slice(suffix.length - i);- }- // Keep the suffix clear of the prefix on every label so the diff survives.- const safe = labels.every((label) => prefix.length + suffix.length < label.length);- return safe && suffix.length >= SHARED_PREFIX_MIN ? suffix : "";- }-- private renderListEntry(- entry: FlatChildAgentNode,- number: number,- agentWidth: number,- sharedPrefix: string,- sharedSuffix: string,- promptWidth: number,- recapWidth: number,- ): string {- const indent = " ".repeat(SUMMARY_LIST_INDENT);- // Running rows pulse the shared working glyph; other states stay static.- const rawIcon = entry.node.hasActiveHeartbeat- ? childAgentStatusIcon(entry.node)- : entry.node.status === "running"- ? workingIconFrame(getWorkingPulseFrame())- : childAgentStatusIcon(entry.node);- const icon = formatChildAgentStatusIcon(entry.node, rawIcon);- const agentLabel = `S${number}`;- const agentCell = theme.fg("muted", padTableCell(agentLabel, agentWidth));- const promptCell = this.elidePrompt(this.entryLabel(entry), sharedPrefix, sharedSuffix, promptWidth);- const recapCell = theme.fg("muted", padTableCell(childAgentRecap(entry.node), recapWidth, "…"));- const model = childAgentModelLabel(entry.node.model);- const tokens = entry.node.tokenCount === undefined ? "" : `${formatTokenCount(entry.node.tokenCount)} tok`;- const duration = formatChildAgentDuration(entry.node.durationMs);- const modelCell = padTableCell(truncateModelLabel(model, SUMMARY_MODEL_WIDTH), SUMMARY_MODEL_WIDTH);- const tokensCell = padTableCell(tokens, SUMMARY_TOKENS_WIDTH, "…");- const durationCell = padTableCell(duration, SUMMARY_DURATION_WIDTH, "…");- const metrics = `${modelCell} ${tokensCell}${" ".repeat(SUMMARY_TOKEN_TIME_GAP)}${durationCell}`;- const gap = " ".repeat(SUMMARY_COLUMN_GAP);- return `${indent}${icon} ${agentCell}${gap}${promptCell}${gap}${recapCell}${gap}${theme.fg("muted", metrics)}`;- }-- private entryLabel(entry: FlatChildAgentNode): string {- return entry.node.sessionName?.trim() || entry.node.label;- }-- private elidePrompt(label: string, sharedPrefix: string, sharedSuffix: string, width: number): string {- const text = this.elideAroundDiff(label, sharedPrefix, sharedSuffix);- const safeWidth = Math.max(0, width);- const truncated =- visibleWidth(text) > safeWidth ? `${truncateToWidth(text, Math.max(0, safeWidth - 1), "").trimEnd()}…` : text;- return theme.fg("dim", padTableCell(truncated, safeWidth));- }-- // Window the prompt around its divergence: "<leading context>…<~2 words before- // the diff><diff><~2 words after the diff>…", dropping the shared head and tail.- private elideAroundDiff(label: string, sharedPrefix: string, sharedSuffix: string): string {- // Nothing useful to elide if the whole shared run fits in the leading window.- if (!sharedPrefix || !label.startsWith(sharedPrefix) || sharedPrefix.length <= PROMPT_LEADING_CONTEXT) {- return label;- }- // Snap the leading window to a word boundary so it doesn't cut mid-word.- const leadSpace = label.lastIndexOf(" ", PROMPT_LEADING_CONTEXT);- const lead = label.slice(0, leadSpace > 0 ? leadSpace : PROMPT_LEADING_CONTEXT).trimEnd();-- // Back the window start up a couple words before the divergence.- let start = sharedPrefix.length;- for (let words = 0; words < PROMPT_DIFF_CONTEXT_WORDS && start > 0; words++) {- const prevSpace = label.lastIndexOf(" ", start - 2);- if (prevSpace <= lead.length) {- break;- }- start = prevSpace + 1;- }-- // Advance the window end a couple words past where the labels re-converge.- let end = label.length;- if (sharedSuffix && label.endsWith(sharedSuffix)) {- end = label.length - sharedSuffix.length;- for (let words = 0; words < PROMPT_DIFF_CONTEXT_WORDS && end < label.length; words++) {- const nextSpace = label.indexOf(" ", end + 1);- if (nextSpace < 0) {- end = label.length;- break;- }- end = nextSpace;- }- }-- const middle = label.slice(start, end).trimEnd();- const tail = end < label.length ? "…" : "";- return `${lead}…${middle}${tail}`;- }-- private scrollHint(total: number, start: number, width: number): string | undefined {- if (total <= SUMMARY_VISIBLE_ROWS) {- return undefined;- }- const above = start;- const below = total - (start + SUMMARY_VISIBLE_ROWS);- const segments: string[] = [];- if (above > 0) {- segments.push(theme.fg("dim", `▴ ${above} above`));- }- if (below > 0) {- segments.push(theme.fg("dim", `▾ ${below} below`));- }- const hint = this.focused- ? joinHints([- combinedKeyAction(["tui.select.up", "tui.select.down"], "scroll"),- keyAction("tui.select.confirm", "open"),- ])- : "";- const left = segments.join(theme.fg("dim", " · "));- const body = hint ? `${left}${theme.fg("dim", " ")}${hint}` : left;- return this.truncate(`${" ".repeat(SUMMARY_LIST_INDENT)}${body}`, width);- }-- private panelLine(line: string, width: number, selected: boolean): string {- const contentWidth = Math.max(1, width - this.paddingX * 2);- const truncated = this.truncate(line, contentWidth);- const paddedContent = truncated + " ".repeat(Math.max(0, contentWidth - visibleWidth(truncated)));- const padded = `${" ".repeat(this.paddingX)}${paddedContent}${" ".repeat(this.paddingX)}`;- return selected ? theme.getSelectionBackgroundColor()(padded) : padded;- }-- private truncate(line: string, width: number): string {- return truncateToWidth(line, width, "");- }-- private renderCompactLine(line: string, width: number): string {- const panelWidth = Math.min(width, visibleWidth(line) + this.paddingX * 2);- const contentWidth = Math.max(1, panelWidth - this.paddingX * 2);- const truncated = this.truncate(line, contentWidth);- return `${" ".repeat(this.paddingX)}${truncated}${" ".repeat(Math.max(0, panelWidth - this.paddingX - visibleWidth(truncated)))}`;- }-- private renderSplitLine(left: string, right: string, width: number): string {- const contentWidth = Math.max(1, width - this.paddingX);- const gapWidth = left ? 2 : 0;- const leftWidth = visibleWidth(left);- const rightWidthLimit =- left && contentWidth > gapWidth && leftWidth + gapWidth + visibleWidth(right) > contentWidth- ? contentWidth - gapWidth - Math.min(leftWidth, Math.max(1, Math.floor((contentWidth - gapWidth) / 3)))- : contentWidth;- const renderedRight = this.truncate(right, Math.max(0, rightWidthLimit));- const rightWidth = visibleWidth(renderedRight);- const renderedLeftWidth = Math.max(0, contentWidth - rightWidth - gapWidth);- const renderedLeft = renderedLeftWidth > 0 ? this.truncate(left, renderedLeftWidth) : "";- const gap = Math.max(0, contentWidth - visibleWidth(renderedLeft) - rightWidth);- return `${" ".repeat(this.paddingX)}${renderedLeft}${" ".repeat(gap)}${renderedRight}`;- }-}--export class ChildAgentDetailComponent implements Component, Focusable {- focused = false;- private node: ChildAgentInspectorNode | undefined;- private bodyComponents: Component[] = [];- private toolsExpanded = false;- private readonly fallbackTui = { requestRender: () => {} } as TUI;- private killConfirmExpiresAt = 0;- private killConfirmTimer: ReturnType<typeof setTimeout> | undefined;- private backHintLabel = "back to chat";- private statusLoader: Loader | undefined;- private lastStatusMessage: string | undefined;-- onCancel?: () => void;- onToggleToolsExpanded?: () => void;- onKill?: (nodeId: string) => void;-- constructor(- _getViewportHeight: () => number = () => 0,- private readonly options: ChildAgentDetailOptions = {},- ) {}-- setNode(node: ChildAgentInspectorNode | undefined): void {- if (node?.id !== this.node?.id) {- this.clearKillConfirmation({ render: false });- }- this.node = node;- // Stop the spinner's interval once the subagent is no longer running, not just- // when the panel closes, so it doesn't keep requesting redraws after completion.- if (!node || (node.status !== "running" && node.status !== "queued")) {- this.statusLoader?.stop();- this.statusLoader = undefined;- this.lastStatusMessage = undefined;- }- }-- setBodyComponents(components: Component[]): void {- this.bodyComponents = components;- this.requestRender();- }-- setBackHintLabel(label: string): void {- this.backHintLabel = label;- }-- setToolsExpanded(expanded: boolean): void {- this.toolsExpanded = expanded;- for (const component of this.bodyComponents) {- if (isExpandableComponent(component)) {- component.setExpanded(expanded);- }- }- }-- invalidate(): void {- for (const component of this.bodyComponents) {- component.invalidate?.();- }- }-- render(width: number): string[] {- const safeWidth = Math.max(1, width);- const sections = this.renderDetail(safeWidth);- return [- ...sections.headerLines,- ...sections.bodyLines,- ...this.statusAndRecapLines(safeWidth),- this.panelLine(theme.fg("borderMuted", "─".repeat(safeWidth)), safeWidth),- this.panelLine(this.detailHintLine(safeWidth), safeWidth),- ];- }-- /** Subagent's own working status + recap, sitting just above the bottom divider. */- private statusAndRecapLines(width: number): string[] {- const node = this.node;- if (!node) {- return [];- }- const lines: string[] = [];- if (node.status === "running" || node.status === "queued") {- // Reuse the main agent's loader so the spinner and labels are identical.- // The loader self-pads one space; add one more to align with the body.- const loader = this.ensureStatusLoader();- // setMessage triggers a render; only call it when the label actually changes,- // or render()->setMessage->requestRender->render becomes a self-sustaining loop.- const message = this.panelStatusLabel(node);- if (message !== this.lastStatusMessage) {- this.lastStatusMessage = message;- loader.setMessage(message);- }- lines.push(...loader.render(width).map((line) => this.indent(line, width, 1)));- }- const recap = node.recap?.trim();- if (recap) {- lines.push("");- lines.push(this.indent(this.truncate(theme.fg("dim", `Recap: ${recap}`), width - CONTENT_INDENT), width));- }- lines.push("");- return lines;- }-- private ensureStatusLoader(): Loader {- if (!this.statusLoader) {- this.statusLoader = new Loader(- this.options.ui ?? this.fallbackTui,- (spinner) => theme.fg("accent", spinner),- (text) => theme.fg("muted", text),- "",- );- }- return this.statusLoader;- }-- private panelStatusLabel(node: ChildAgentInspectorNode): string {- if (node.status === "queued") {- return AGENT_ACTIVITY_LABELS.waiting;- }- switch (node.activity?.kind) {- case "executing":- return AGENT_ACTIVITY_LABELS.executing;- case "writing":- return AGENT_ACTIVITY_LABELS.writing;- default:- return AGENT_ACTIVITY_LABELS.waiting;- }- }-- private indent(line: string, width: number, spaces = CONTENT_INDENT): string {- if (line === "") {- return line;- }- return this.truncate(`${" ".repeat(spaces)}${line}`, width);- }-- handleInput(data: string): void {- const kb = getKeybindings();- // Any input other than the kill key disarms the pending confirmation,- // matching the agents view delete flow.- if (!kb.matches(data, "app.agents.delete")) {- this.clearKillConfirmation({ render: false });- }- if (kb.matches(data, "app.tools.expand")) {- this.onToggleToolsExpanded?.();- return;- }- if (kb.matches(data, "app.agents.delete")) {- this.handleKillKey();- return;- }- if (kb.matches(data, "app.agents.back")) {- this.onCancel?.();- }- }-- private handleKillKey(): void {- const node = this.node;- if (!node || !isKillableChildAgentStatus(node.status)) {- this.clearKillConfirmation({ render: false });- return;- }- if (this.isKillConfirmationVisible()) {- this.clearKillConfirmation({ render: false });- this.onKill?.(node.id);- return;- }- this.showKillConfirmation();- }-- private showKillConfirmation(): void {- if (this.killConfirmTimer) {- clearTimeout(this.killConfirmTimer);- }- this.killConfirmExpiresAt = Date.now() + KILL_CONFIRM_DURATION_MS;- this.killConfirmTimer = setTimeout(() => {- this.killConfirmTimer = undefined;- this.killConfirmExpiresAt = 0;- this.requestRender();- }, KILL_CONFIRM_DURATION_MS);- this.killConfirmTimer.unref?.();- this.requestRender();- }-- private clearKillConfirmation(options: { render?: boolean } = {}): void {- if (!this.killConfirmTimer && this.killConfirmExpiresAt === 0) {- return;- }- if (this.killConfirmTimer) {- clearTimeout(this.killConfirmTimer);- this.killConfirmTimer = undefined;- }- this.killConfirmExpiresAt = 0;- if (options.render !== false) {- this.requestRender();- }- }-- private isKillConfirmationVisible(): boolean {- return this.killConfirmExpiresAt > Date.now();- }-- private requestRender(): void {- (this.options.ui ?? this.fallbackTui).requestRender();- }-- private renderDetail(width: number): DetailSections {- const selected = this.node;- if (!selected) {- return {- headerLines: [this.panelLine(this.headerLine(theme.fg("muted", "agent unavailable"), width), width)],- bodyLines: [],- };- }-- const headerLines = [this.indent(this.truncate(theme.fg("text", selected.label), width - CONTENT_INDENT), width)];- headerLines.push(this.panelLine(theme.fg("borderMuted", "─".repeat(width)), width));-- const bodyLines: string[] = [];- for (const component of this.bodyComponents) {- bodyLines.push(...component.render(width));- }- return { headerLines, bodyLines };- }-- private headerLine(text: string, width: number): string {- const plainWidth = visibleWidth(text);- const rule = "─".repeat(Math.max(1, width - plainWidth - 1));- return this.truncate(`${text} ${theme.fg("borderMuted", rule)}`, width);- }-- private detailHintLine(width: number): string {- const backAction = keyAction("app.agents.back", this.backHintLabel, { primaryOnly: true });- const expandAction = keyAction("app.tools.expand", this.toolsExpanded ? "to collapse" : "to expand");- const killable = this.node !== undefined && isKillableChildAgentStatus(this.node.status);- const stopAction = !killable- ? undefined- : this.isKillConfirmationVisible()- ? theme.fg("error", `${keyText("app.agents.delete", { primaryOnly: true }).trim()} again to stop`)- : keyAction("app.agents.delete", "stop", { primaryOnly: true });- const actions = [backAction, expandAction, stopAction];- const separatorWidth = visibleWidth(joinHints(["", ""]));- const modelWidth = Math.max(0, width - visibleWidth(joinHints(actions)) - separatorWidth);- const modelLabel = childAgentModelLabel(this.node?.model);- const model =- modelLabel && modelWidth >= 4 ? theme.fg("muted", truncateToWidth(modelLabel, modelWidth, "…")) : undefined;- return hintLine([backAction, model, expandAction, stopAction], width);- }-- private panelLine(line: string, width: number): string {- return this.truncate(line, width);- }-- private truncate(line: string, width: number): string {- return truncateToWidth(line, width, "");- }-}diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.tsindex 3195b7edba..ca7468ffc0 100644--- a/packages/coding-agent/src/modes/interactive/components/index.ts+++ b/packages/coding-agent/src/modes/interactive/components/index.ts@@ -6,12 +6,6 @@ export { AssistantMessageComponent } from "./assistant-message.js";export { BashExecutionComponent } from "./bash-execution.js";export { BorderedLoader } from "./bordered-loader.js";export { BranchSummaryMessageComponent } from "./branch-summary-message.js";-export {- ChildAgentDetailComponent,- type ChildAgentInspectorNode,- type ChildAgentStatus,- ChildAgentSummaryComponent,-} from "./child-agent-inspector.js";export {CompactionOutcomeMessageComponent,MalformedCompactionOutcomeMessageComponent,@@ -46,6 +40,7 @@ export { type ModelsCallbacks, type ModelsConfig, ScopedModelsSelectorComponentexport { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from "./settings-selector.js";export { ShowImagesSelectorComponent } from "./show-images-selector.js";export { SkillInvocationMessageComponent } from "./skill-invocation-message.js";+export { SubagentSummaryLine } from "./subagent-summary-line.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-summary-line.ts b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.tsnew file mode 100644index 0000000000..0ae22af740--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts@@ -0,0 +1,116 @@+import { type Component, type Focusable, getKeybindings, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";+import type { AgentConnectionRlmChildAgentSnapshot } from "../../agent-connection/index.js";+import { theme } from "../theme/theme.js";+import { keyText } from "./keybinding-hints.js";++export interface SubagentSummaryCounts {+ total: number;+ running: number;+ idle: number;+ inactive: number;+}++export function countDirectSubagentStatuses(+ children: Iterable<AgentConnectionRlmChildAgentSnapshot>,+ parentId: string | undefined,+ activeHeartbeatSessionIds: ReadonlySet<string>,+): SubagentSummaryCounts {+ let total = 0;+ let running = 0;+ let idle = 0;+ for (const child of children) {+ if (child.parentId !== parentId || child.status === "cancelled") continue;+ total += 1;+ const isRunning =+ child.status === "running" ||+ child.status === "queued" ||+ child.activity !== undefined ||+ (child.activeSessionId !== undefined && activeHeartbeatSessionIds.has(child.activeSessionId));+ if (isRunning) {+ running += 1;+ } else if ((child.status === "done" || child.status === "error") && child.activeSessionId !== undefined) {+ idle += 1;+ }+ }+ return { total, running, idle, inactive: total - running - idle };+}++/** One-line entry into the current session's scoped agents view. */+export class SubagentSummaryLine implements Component, Focusable {+ focused = false;+ private counts: SubagentSummaryCounts = { total: 0, running: 0, idle: 0, inactive: 0 };+ private openable = false;++ onOpen?: () => void;+ onCancel?: () => void;+ onChatAction?: (data: string) => void;++ constructor(+ private readonly getLocationLabel: () => string | undefined = () => undefined,+ private readonly getContextLabel: () => string | undefined = () => undefined,+ private readonly getOverrideLabel: () => string | undefined = () => undefined,+ ) {}++ setSubagentCounts(counts: SubagentSummaryCounts): void {+ this.counts = counts;+ }++ setOpenable(openable: boolean): void {+ this.openable = openable;+ }++ isSelectable(): boolean {+ return this.counts.total > 0 && this.openable;+ }++ handleInput(data: string): void {+ const keybindings = getKeybindings();+ if (keybindings.matches(data, "tui.select.confirm") || keybindings.matches(data, "app.agents.open")) {+ if (this.isSelectable()) this.onOpen?.();+ return;+ }+ if (+ keybindings.matches(data, "tui.select.up") ||+ keybindings.matches(data, "tui.select.cancel") ||+ keybindings.matches(data, "app.agents.back")+ ) {+ this.onCancel?.();+ return;+ }+ this.onChatAction?.(data);+ }++ render(width: number): string[] {+ const lines = this.renderInfoLine(width);+ if (this.counts.total === 0) return lines;+ const summary = `${this.counts.total} subagent${this.counts.total === 1 ? "" : "s"}: ${this.counts.running} running · ${this.counts.idle} idle · ${this.counts.inactive} inactive`;+ const openHint = this.openable+ ? ` ${keyText("tui.select.confirm")} or ${keyText("app.agents.open")} to open`+ : "";+ const text = `${this.focused ? "▸" : " "} ${summary}${openHint}`;+ const line = truncateToWidth(text, width, "…");+ lines.push(this.focused ? theme.bg("selectedBg", line.padEnd(width)) : theme.fg("dim", line));+ return lines;+ }++ private renderInfoLine(width: number): string[] {+ const overrideLabel = this.getOverrideLabel()?.trim();+ const locationLabel = this.getLocationLabel()?.trim();+ const contextLabel = this.getContextLabel()?.trim();+ const left = overrideLabel || locationLabel || "";+ if (!left && !contextLabel) return [];+ const safeWidth = Math.max(1, width);+ const right = contextLabel ?? "";+ const gap = left && right ? 2 : 0;+ const rightWidth = Math.min(visibleWidth(right), Math.max(0, safeWidth - gap));+ const leftWidth = Math.max(0, safeWidth - rightWidth - gap);+ const renderedLeft = truncateToWidth(left, leftWidth, "…");+ const renderedRight = truncateToWidth(right, rightWidth, "…");+ const padding = Math.max(0, safeWidth - visibleWidth(renderedLeft) - visibleWidth(renderedRight));+ return [theme.fg("muted", `${renderedLeft}${" ".repeat(padding)}${renderedRight}`)];+ }++ invalidate(): void {+ // Render output is derived from counts and focus state.+ }+}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex bd0b173425..4f6fadc54b 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -149,7 +149,6 @@ import type {AgentConnectionSessionContext,AgentConnectionSessionEvent,AgentConnectionSessionTreeNode,- AgentConnectionSessionWatcher,AgentConnectionSideQuestionEvent,AgentConnectionSlashCommand,AgentConnectionSnapshot,@@ -174,11 +173,6 @@ import { BashExecutionComponent } from "./components/bash-execution.js";import { BorderedLoader } from "./components/bordered-loader.js";import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";import { type FullPaneOverlayOptions, showFullPaneOverlay } from "./components/centered-overlay.js";-import {- ChildAgentDetailComponent,- type ChildAgentInspectorNode,- ChildAgentSummaryComponent,-} from "./components/child-agent-inspector.js";import {CompactionOutcomeMessageComponent,MalformedCompactionOutcomeMessageComponent,@@ -186,7 +180,6 @@ import {import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";import { ConfigurationMenuComponent, type ConfigurationMenuTab } from "./components/configuration-menu.js";import { formatContextTree } from "./components/context-tree-format.js";-import { buildConversationComponents } from "./components/conversation-components.js";import { CountdownTimer } from "./components/countdown-timer.js";import { CustomEditor } from "./components/custom-editor.js";import { CustomMessageComponent } from "./components/custom-message.js";@@ -214,6 +207,7 @@ import {styleSlashCommandText,} from "./components/slash-command-message.js";import { SlashCommandResultMessageComponent } from "./components/slash-command-result-message.js";+import { countDirectSubagentStatuses, SubagentSummaryLine } from "./components/subagent-summary-line.js";import { ThinkingSelectorComponent } from "./components/thinking-selector.js";import {selectLatestToolExpandHint,@@ -342,7 +336,7 @@ export function formatSplashCwd(cwd: string): string {return normalized;}-export function mergeChildAgentSnapshots(+function mergeSubagentSnapshot(previous: AgentConnectionRlmChildAgentSnapshot,incoming: AgentConnectionRlmChildAgentSnapshot,): AgentConnectionRlmChildAgentSnapshot {@@ -351,44 +345,13 @@ export function mergeChildAgentSnapshots(...previous,...incoming,parentId: incoming.parentId ?? previous.parentId,- activeSessionId: incoming.activeSessionId ?? previous.activeSessionId,- sessionName: incoming.sessionName ?? previous.sessionName,- model: incoming.model ?? previous.model,- durationMs: incoming.durationMs ?? previous.durationMs,- answerPreview: incoming.answerPreview ?? previous.answerPreview,- toolUseCount:- incoming.toolUseCount === undefined- ? previous.toolUseCount- : Math.max(previous.toolUseCount ?? 0, incoming.toolUseCount),- tokenCount: incoming.tokenCount ?? previous.tokenCount,- recap: incoming.recap ?? previous.recap,+ // Active updates may omit a previously known daemon session id, but a+ // terminal update without one means the child is no longer resident.+ activeSessionId: active ? (incoming.activeSessionId ?? previous.activeSessionId) : incoming.activeSessionId,activity: active ? (incoming.activity ?? previous.activity) : undefined,- error: incoming.status === "error" ? (incoming.error ?? previous.error) : undefined,};}-function childAgentSummaryChanged(- previous: AgentConnectionRlmChildAgentSnapshot,- next: AgentConnectionRlmChildAgentSnapshot,-): boolean {- const previousTokens = previous.tokenCount === undefined ? undefined : formatTokenCount(previous.tokenCount);- const nextTokens = next.tokenCount === undefined ? undefined : formatTokenCount(next.tokenCount);- return (- previous.parentId !== next.parentId ||- previous.activeSessionId !== next.activeSessionId ||- previous.sessionName !== next.sessionName ||- previous.model !== next.model ||- previous.label !== next.label ||- previous.status !== next.status ||- previous.durationMs !== next.durationMs ||- previous.toolUseCount !== next.toolUseCount ||- previousTokens !== nextTokens ||- previous.recap !== next.recap ||- previous.activity?.kind !== next.activity?.kind ||- previous.activity?.toolName !== next.activity?.toolName- );-}-export function truncatePathMiddle(value: string, width: number): string {if (visibleWidth(value) <= width) {return value;@@ -963,21 +926,10 @@ export class InteractiveMode {private toolDefinitionCache = new Map<string, ToolExecutionDefinition | undefined>();private agentRunFileChanges = new Map<string, FileChangeSummary>();- // RLM child-agent tray: inline list below the editor, full-screen detail on open.- private childAgentSummary: ChildAgentSummaryComponent;- private childAgentDetail: ChildAgentDetailComponent;- private childAgentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();- private childAgentNodes: ChildAgentInspectorNode[] = [];- private childAgentDetailNodeId: string | undefined;- private childAgentPanelMode: "detail" | undefined;- private childAgentWatcher: AgentConnectionSessionWatcher | undefined;- private childAgentWatcherToken = 0;- private childAgentWatcherMessages: AgentMessage[] = [];- private childAgentRefreshSeq = 0;- private childAgentBodyBuildSeq = 0;- // The session key the current watcher attached with, so a later snapshot that- // gains the real activeSessionId can retry the attach.- private childAgentWatchedKey: string | undefined;+ // One summary line below the editor, backed by the existing child-status stream.+ private subagentSummaryLine: SubagentSummaryLine;+ private subagentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();+ private rlmNodeId: string | undefined;// Tool output expansion stateprivate toolOutputExpanded = false;@@ -1110,14 +1062,6 @@ export class InteractiveMode {this.queuedMessagesContainer = new Container();this.sideQuestionContainer = new Container();this.featureHintContainer = new Container();- this.childAgentDetail = new ChildAgentDetailComponent(() => this.getChildAgentPanelRows(), {- ui: this.ui,- });- this.childAgentDetail.onCancel = () => {- this.closeChildAgentPanel({ selectNodeId: this.childAgentDetailNodeId });- };- this.childAgentDetail.onToggleToolsExpanded = () => this.toggleToolOutputExpansion();- this.childAgentDetail.onKill = (nodeId) => void this.killChildAgent(nodeId);this.widgetContainerAbove = new Container();this.widgetContainerBelow = new Container();this.recapContainer = new Container();@@ -1137,20 +1081,21 @@ export class InteractiveMode {this.mainViewContainer = new Container();this.promptDock = new Container();this.footerSlot = new Container();- this.restoreMainAgentView();+ this.mainViewContainer.addChild(this.chatContainer);+ this.mainViewContainer.addChild(this.shortcutGuideContainer);+ this.mainViewContainer.addChild(this.pendingMessagesContainer);+ this.mainViewContainer.addChild(this.statusContainer);this.editorContainer = new Container();this.editorContainer.addChild(this.editor as Component);- this.childAgentSummary = new ChildAgentSummaryComponent(+ this.subagentSummaryLine = new SubagentSummaryLine(() => this.getTrayLocationLabel(),() => this.getTrayContextLabel(),() => this.getTrayOverrideLabel(),);- this.childAgentSummary.onOpenDetail = () => void this.openScopedAgentsView();- // Fallback for Enter when the list emptied out while focused.- this.childAgentSummary.onOpen = () => void this.openScopedAgentsView();- this.childAgentSummary.onCancel = () => this.focusEditor();- this.childAgentSummary.onExit = () => this.handleSubagentSummaryExit();- this.childAgentSummary.onChatAction = (data) => this.handleSubagentSummaryChatAction(data);+ this.subagentSummaryLine.setOpenable(this.options.returnToAgentsView === true);+ this.subagentSummaryLine.onOpen = () => void this.openScopedAgentsView();+ this.subagentSummaryLine.onCancel = () => this.focusEditor();+ this.subagentSummaryLine.onChatAction = (data) => this.handleSubagentSummaryChatAction(data);this.footerDataProvider = new FooterDataProvider(this.uiServices.getInitialCwd());this.footer = new FooterComponent(this.footerDataProvider);this.footer.setAutoCompactEnabled(this.settingsManager.getCompactionEnabled());@@ -1429,7 +1374,7 @@ export class InteractiveMode {verboseInstructions,{topPadding: true,- getHideStartHint: () => this.childAgentPanelMode !== undefined || !this.isNewChat(),+ getHideStartHint: () => !this.isNewChat(),getStartHint: () => this.startHint,},);@@ -1449,7 +1394,7 @@ export class InteractiveMode {this.mainContainer.addChild(container);}this.mainContainer.addChild(this.editorContainer);- this.mainContainer.addChild(this.childAgentSummary);+ this.mainContainer.addChild(this.subagentSummaryLine);this.mainContainer.addChild(this.widgetContainerBelow);this.footerSlot.addChild(this.footer);this.mainContainer.addChild(this.footerSlot);@@ -2582,7 +2527,7 @@ export class InteractiveMode {const heartbeats = scopeHeartbeatsToSession(this.heartbeatCatalog,this.connectionState,- this.childAgentSnapshots.values(),+ this.subagentSnapshots.values(),);if (heartbeats.length === this.heartbeats.length &&@@ -2593,7 +2538,8 @@ export class InteractiveMode {this.heartbeats = heartbeats;this.heartbeatManager?.setHeartbeats(heartbeats);this.scheduleHeartbeatManagerRefresh();- this.refreshChildAgentInspector();+ this.updateSubagentSummaryLine();+ this.ui.requestRender();}private applyConnectionStateSnapshot(state: AgentConnectionState): void {@@ -2867,7 +2813,7 @@ export class InteractiveMode {this.renderRecap();this.ipythonToolComponents.clear();this.lateIpythonSentAgentMessages.clear();- this.resetChildAgentInspector();+ this.resetSubagentSummary();this.setGoalAnnouncementBaseline(this.getGoalState());this.syncGoalTray(this.getGoalState());}@@ -2906,7 +2852,8 @@ export class InteractiveMode {this.applyConnectionStateSnapshot(snapshot.state);this.streamingComponent = undefined;this.streamingMessage = undefined;- this.replaceChildAgentInspector(snapshot.children);+ this.rlmNodeId = snapshot.parent?.childId;+ this.replaceSubagentSummary(snapshot.children);await this.renderSessionContext(this.getSessionContextFromConnectionSnapshot(snapshot), {clearChat: true,updateFooter: true,@@ -3303,9 +3250,6 @@ export class InteractiveMode {}private shouldSuppressFeatureHint(): boolean {- if (this.childAgentPanelMode) {- return true;- }const { steering, followUp } = this.getAllQueuedMessages();return steering.length > 0 || followUp.length > 0;}@@ -3336,7 +3280,7 @@ export class InteractiveMode {}private updateWorkingPulse(): void {- const active = this.isAgentStreaming() || this.countRunningChildAgents() > 0;+ const active = this.isAgentStreaming() || this.countRunningSubagents() > 0;if (!active) {this.stopWorkingPulse();return;@@ -3360,9 +3304,9 @@ export class InteractiveMode {}}- private countRunningChildAgents(): number {+ private countRunningSubagents(): number {let count = 0;- for (const child of this.childAgentSnapshots.values()) {+ for (const child of this.subagentSnapshots.values()) {if (child.status === "running") {count += 1;}@@ -3571,8 +3515,8 @@ export class InteractiveMode {private renderRecap(): void {if (!this.recapContainer) return;this.recapContainer.clear();- const recap = this.childAgentPanelMode ? undefined : this.sessionRecap?.trim();- const showChanges = !this.childAgentPanelMode && !this.isAgentStreaming() && this.agentRunFileChanges.size > 0;+ const recap = this.sessionRecap?.trim();+ const showChanges = !this.isAgentStreaming() && this.agentRunFileChanges.size > 0;if (showChanges) {this.recapContainer.addChild(new TruncatedText(formatTotalChangeSummary([...this.agentRunFileChanges.values()]), 1, 0),@@ -3936,18 +3880,6 @@ export class InteractiveMode {*/private setCustomEditorComponent(factory: EditorFactory | undefined): void {this.editorComponentFactory = factory;- if (this.childAgentPanelMode) {- this.restoreMainAgentView();- // Re-render queued previews cleared on panel entry; the queue may still hold messages.- this.updatePendingMessagesDisplay();- this.childAgentDetailNodeId = undefined;- this.childAgentDetail.setBackHintLabel("back to chat");- this.childAgentDetail.setNode(undefined);- this.childAgentPanelMode = undefined;- this.resumeFeatureHintPresentation();- }- this.childAgentSummary.setHidden(false);-// Snapshot the current editor before replacing it. Paste markers are only// meaningful while their originating editor still owns the paste snapshot.const currentEditor = this.editor;@@ -4180,7 +4112,7 @@ export class InteractiveMode {this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());- this.defaultEditor.onAction("app.subagents.focus", () => this.focusChildAgentSummary());+ this.defaultEditor.onAction("app.subagents.focus", () => this.focusSubagentSummary());this.defaultEditor.onAction("app.heartbeats.open", () => {void this.showHeartbeatManager();});@@ -4201,7 +4133,7 @@ export class InteractiveMode {void this.requestAgentsView();});this.defaultEditor.onAgentsBack = () => this.handleAgentsBack();- this.defaultEditor.onMoveBelowPrompt = () => this.focusChildAgentSummary();+ this.defaultEditor.onMoveBelowPrompt = () => this.focusSubagentSummary();this.defaultEditor.onChange = (text: string) => {if (text.length > 0) {@@ -5368,13 +5300,13 @@ export class InteractiveMode {case "thinking_level_changed":this.footer.invalidate();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.updateEditorBorderColor();break;case "service_tier_changed":this.footer.invalidate();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();break;case "bash_start": {@@ -5699,7 +5631,7 @@ export class InteractiveMode {}case "rlm_child_update":- this.updateChildAgentInspector(event.child);+ this.updateSubagentSummary(event.child);break;case "goal_update":@@ -5753,7 +5685,7 @@ export class InteractiveMode {}private syncGoalTray(goal: GoalState): void {- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.updateGoalTrayTimer(goal);}@@ -5761,7 +5693,7 @@ export class InteractiveMode {if (goal.status === "active") {if (!this.goalTrayTimer) {this.goalTrayTimer = setInterval(() => {- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.ui.requestRender();}, 1000);this.goalTrayTimer.unref?.();@@ -5871,120 +5803,87 @@ export class InteractiveMode {return `: ${truncateToWidth(detail, availableWidth)}`;}- private seedChildAgentInspector(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {- if (!children?.length) {- return;- }+ private seedSubagentSummary(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {let changed = false;- for (const child of children) {- // Live rlm_child_update events are richer than the snapshot; never- // clobber state that already arrived from the event stream.- if (!this.childAgentSnapshots.has(child.id) && child.status !== "cancelled") {- this.childAgentSnapshots.set(child.id, child);+ for (const child of children ?? []) {+ // Live updates can arrive before the initial snapshot; do not replace them+ // with the snapshot's older state.+ if (!this.subagentSnapshots.has(child.id) && child.status !== "cancelled") {+ this.subagentSnapshots.set(child.id, child);changed = true;}}- if (changed) {- this.refreshChildAgentInspector();- }+ if (changed) this.refreshSubagentSummary();}- private replaceChildAgentInspector(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {+ private replaceSubagentSummary(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {const next = new Map<string, AgentConnectionRlmChildAgentSnapshot>();for (const child of children ?? []) {- if (child.status === "cancelled") {- continue;- }- const previous = this.childAgentSnapshots.get(child.id);- next.set(child.id, previous ? mergeChildAgentSnapshots(previous, child) : child);+ if (child.status === "cancelled") continue;+ const previous = this.subagentSnapshots.get(child.id);+ next.set(child.id, previous ? mergeSubagentSnapshot(previous, child) : child);}- this.childAgentSnapshots = next;- this.refreshChildAgentInspector();+ this.subagentSnapshots = next;+ this.refreshSubagentSummary();}- private updateChildAgentInspector(child: AgentConnectionRlmChildAgentSnapshot): void {- // Cancellation is also the lifecycle tombstone for deleted subagents.+ private updateSubagentSummary(child: AgentConnectionRlmChildAgentSnapshot): void {if (child.status === "cancelled") {- this.removeChildAgentSnapshot(child.id);- this.refreshChildAgentInspector();- return;- }- const previous = this.childAgentSnapshots.get(child.id);- const next = previous ? mergeChildAgentSnapshots(previous, child) : child;- this.childAgentSnapshots.set(child.id, next);- if (!previous || childAgentSummaryChanged(previous, next) || this.childAgentDetailNodeId === child.id) {- this.refreshChildAgentInspector();+ this.removeSubagentSnapshot(child.id);+ } else {+ const previous = this.subagentSnapshots.get(child.id);+ this.subagentSnapshots.set(child.id, previous ? mergeSubagentSnapshot(previous, child) : child);}+ this.refreshSubagentSummary();}- private refreshChildAgentInspector(): void {- this.childAgentNodes = this.buildChildAgentInspectorNodes();- this.childAgentSummary.setNodes(this.childAgentNodes);+ private refreshSubagentSummary(): void {this.updateScopedHeartbeats();+ this.updateSubagentSummaryLine();this.updateWorkingPulse();this.syncWorkingLoader();this.updateWorkingLoaderMessage();- if (this.childAgentDetailNodeId) {- const detailNode = this.findChildAgentInspectorNode(this.childAgentDetailNodeId);- if (!detailNode && this.childAgentPanelMode === "detail") {- this.closeChildAgentPanel();- return;- }- this.childAgentDetail.setNode(detailNode);- this.maybeRetryChildAgentWatch(detailNode);- }this.ui.requestRender();}- private removeChildAgentSnapshot(id: string): void {- this.childAgentSnapshots.delete(id);- for (const child of [...this.childAgentSnapshots.values()]) {- if (child.parentId === id) {- this.removeChildAgentSnapshot(child.id);- }- }+ private updateSubagentSummaryLine(): void {+ const activeHeartbeatSessionIds = new Set(+ this.heartbeatCatalog+ .filter((heartbeat) => heartbeat.job.status === "active")+ .map((heartbeat) => heartbeat.job.activeSessionId),+ );+ this.subagentSummaryLine.setSubagentCounts(+ countDirectSubagentStatuses(this.subagentSnapshots.values(), this.rlmNodeId, activeHeartbeatSessionIds),+ );+ if (!this.subagentSummaryLine.isSelectable() && this.subagentSummaryLine.focused) this.focusEditor();}- private restoreMainAgentView(): void {- this.mainViewContainer.clear();- this.mainViewContainer.addChild(this.chatContainer);- this.mainViewContainer.addChild(this.shortcutGuideContainer);- this.mainViewContainer.addChild(this.pendingMessagesContainer);- this.mainViewContainer.addChild(this.statusContainer);+ private removeSubagentSnapshot(id: string): void {+ this.subagentSnapshots.delete(id);+ for (const child of [...this.subagentSnapshots.values()]) {+ if (child.parentId === id) this.removeSubagentSnapshot(child.id);+ }}- private resetChildAgentInspector(): void {- this.childAgentSnapshots.clear();- this.childAgentNodes = [];- this.childAgentSummary.setNodes([]);+ private resetSubagentSummary(): void {+ this.subagentSnapshots.clear();+ this.rlmNodeId = undefined;+ this.updateSubagentSummaryLine();this.updateScopedHeartbeats();- this.childAgentSummary.setHidden(false);- this.childAgentDetail.setNode(undefined);- this.childAgentDetailNodeId = undefined;- if (this.childAgentPanelMode) {- this.closeChildAgentPanel();- }// Clearing snapshots can drop the last running subagent; reconcile the// pulse and loader so neither lingers when nothing is in flight.this.updateWorkingPulse();this.syncWorkingLoader();}- private getChildAgentPanelRows(): number {- const rows = this.ui.terminal.rows;- return Math.max(4, Math.min(12, Math.floor(rows * 0.4)));- }-private focusEditor(): void {this.ui.setFocus(this.editor);this.ui.requestRender();}- private focusChildAgentSummary(): boolean {- if (!this.childAgentSummary.hasNodes() || this.childAgentPanelMode || this.getTrayOverrideLabel()) {- return false;- }- this.ui.setFocus(this.childAgentSummary);+ private focusSubagentSummary(): boolean {+ if (!this.subagentSummaryLine.isSelectable() || this.getTrayOverrideLabel()) return false;+ this.ui.setFocus(this.subagentSummaryLine);this.ui.requestRender();return true;}@@ -6003,18 +5902,6 @@ export class InteractiveMode {await this.returnToAgentsView("scoped_agents_view");}- // Left from the focused subagent list: exit to manage sessions if available,- // otherwise just drop focus back to the editor.- private handleSubagentSummaryExit(): void {- if (this.options.returnToAgentsView && !this.editor.getText().trim()) {- void this.returnToAgentsView();- return;- }- this.focusEditor();- }-- // Chat actions stay live while the subagent list holds focus; the editor's- // own handlers are bypassed because input routes only to the focused list.private handleSubagentSummaryChatAction(data: string): void {if (this.keybindings.matches(data, "app.tools.expand")) {this.toggleToolOutputExpansion();@@ -6042,7 +5929,7 @@ export class InteractiveMode {private getTrayLocationLabel(): string | undefined {const modelLabel = this.getModelTrayLabel();- const hasChildren = this.options.sessionHasChildren === true || (this.childAgentSnapshots?.size ?? 0) > 0;+ const hasChildren = this.options.sessionHasChildren === true || (this.subagentSnapshots?.size ?? 0) > 0;const depthLabel = formatAgentDepthLabel(this.options.sessionDepth, hasChildren);const shortcutsHint = this.getShortcutsTrayHint();const agentsHint = this.getAgentsViewTrayHint();@@ -6068,7 +5955,7 @@ export class InteractiveMode {}this.sessionHasMessages = hasMessages;this.builtInHeader?.invalidate();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();}private getModelTrayLabel(): string {@@ -6153,214 +6040,6 @@ export class InteractiveMode {return `${hours}h ${remainingMinutes.toString().padStart(2, "0")}m`;}- private async killChildAgent(nodeId: string): Promise<void> {- try {- const cancelled = await this.agentConnection.cancelRlmChild(nodeId);- if (!cancelled) {- this.showError("Subagent already finished");- }- } catch (error) {- this.showError(`Failed to stop subagent: ${error instanceof Error ? error.message : String(error)}`);- }- this.ui.requestRender();- }-- private async startChildAgentWatch(node: ChildAgentInspectorNode): Promise<void> {- this.stopChildAgentWatch();- const key = node.activeSessionId ?? node.id;- const token = ++this.childAgentWatcherToken;- this.childAgentWatchedKey = key;- const watcher = await this.agentConnection.watchSession(key).catch(() => undefined);- // The panel may have closed (or another node opened) while attaching.- if (token !== this.childAgentWatcherToken) {- await watcher?.close().catch(() => undefined);- return;- }- if (!watcher) {- // A still-running child may not have registered yet (in-process snapshots never- // carry activeSessionId, so the key won't change). Clear the watched key so the- // next rlm_child_update retries the attach until a watcher is obtained.- if (node.status === "running" || node.status === "queued") {- this.childAgentWatchedKey = undefined;- return;- }- const fallback = node.error?.trim()- ? theme.fg("error", ` ${node.error.trim()}`)- : theme.fg("muted", " conversation unavailable");- this.childAgentDetail.setBodyComponents([new Text(fallback, 1, 0)]);- return;- }- this.childAgentWatcher = watcher;- watcher.subscribe((event) => {- if (token !== this.childAgentWatcherToken) {- return;- }- // Replacement and resync snapshots both carry authoritative messages.- if (event.type === "session_event" || event.type === "session_replaced" || event.type === "session_resynced") {- void this.refreshChildAgentWatch(token, watcher);- }- });- await this.refreshChildAgentWatch(token, watcher);- }-- // (Re)attach when the key differs from what we last attached with — including the- // undefined left by a failed attach on a not-yet-registered child. Once a watcher is- // held the key matches, so this won't re-attach (or cancel an in-flight attach) per update.- private maybeRetryChildAgentWatch(node: ChildAgentInspectorNode | undefined): void {- if (!node || this.childAgentPanelMode !== "detail") {- return;- }- const key = node.activeSessionId ?? node.id;- if (key !== this.childAgentWatchedKey) {- void this.startChildAgentWatch(node);- }- }-- private async refreshChildAgentWatch(token: number, watcher: AgentConnectionSessionWatcher): Promise<void> {- const seq = ++this.childAgentRefreshSeq;- const messages = await watcher.getMessages().catch(() => undefined);- // Drop a fetch that a newer refresh (or a different watch) has already superseded.- if (!messages || token !== this.childAgentWatcherToken || seq !== this.childAgentRefreshSeq) {- return;- }- this.childAgentWatcherMessages = messages;- await this.rebuildChildAgentBody(token);- }-- private async rebuildChildAgentBody(token: number): Promise<void> {- const watcher = this.childAgentWatcher;- if (!watcher || token !== this.childAgentWatcherToken) {- return;- }- const buildSeq = ++this.childAgentBodyBuildSeq;- const messages = this.childAgentWatcherMessages;- const toolNames = new Set<string>();- for (const message of messages) {- if (message.role === "assistant") {- for (const content of message.content) {- if (content.type === "toolCall") {- toolNames.add(content.name);- }- }- }- }- const definitions = new Map<string, ToolExecutionDefinition | undefined>();- const childCommandsPromise = watcher.getCommands().catch(() => []);- await Promise.all(- [...toolNames].map(async (name) => {- definitions.set(name, (await watcher.getToolDefinition(name).catch(() => undefined)) ?? undefined);- }),- );- const childCommands = await childCommandsPromise;- const childCommandNames = new Set(childCommands.map((command) => command.name));- if (token !== this.childAgentWatcherToken || buildSeq !== this.childAgentBodyBuildSeq) {- return;- }- this.childAgentDetail.setBodyComponents(- buildConversationComponents(messages, {- ui: this.ui,- cwd: this.getCurrentCwd(),- toolOptions: {- showImages: this.settingsManager.getShowImages(),- },- getToolDefinition: (name) => definitions.get(name),- markdownTheme: this.getMarkdownThemeWithSettings(),- hideThinkingBlock: this.hideThinkingBlock,- hiddenThinkingLabel: this.hiddenThinkingLabel,- toolsExpanded: this.toolOutputExpanded,- isRecognizedSlashCommand: (name) => isBuiltinSlashCommandName(name) || childCommandNames.has(name),- }),- );- }-- private stopChildAgentWatch(): void {- this.childAgentWatcherToken++;- this.childAgentWatcherMessages = [];- this.childAgentWatchedKey = undefined;- const watcher = this.childAgentWatcher;- this.childAgentWatcher = undefined;- void watcher?.close().catch(() => undefined);- }-- private closeChildAgentPanel(options: { selectNodeId?: string } = {}): void {- this.stopChildAgentWatch();- this.childAgentPanelMode = undefined;- this.childAgentDetailNodeId = undefined;- this.childAgentDetail.setBackHintLabel("back to chat");- this.childAgentDetail.setNode(undefined);- this.childAgentDetail.setBodyComponents([]);- this.childAgentSummary.setHidden(false);- this.restoreMainAgentView();- this.resumeFeatureHintPresentation();- // Restore the parent recap that was suppressed while the panel was open.- this.renderRecap();- // Re-render queued previews cleared on panel entry; the queue may still hold messages.- this.updatePendingMessagesDisplay();- this.editorContainer.clear();- this.editorContainer.addChild(this.editor);- // Returning from a subagent's detail keeps that subagent selected in the- // inline list; other closes drop back to the editor.- if (options.selectNodeId && this.childAgentSummary.hasNodes()) {- this.childAgentSummary.selectNode(options.selectNodeId);- this.ui.setFocus(this.childAgentSummary);- } else {- this.ui.setFocus(this.editor);- }- this.ui.requestRender();- }-- private buildChildAgentInspectorNodes(): ChildAgentInspectorNode[] {- const activeHeartbeatSessionIds = new Set(- this.heartbeats- .filter((heartbeat) => heartbeat.job.status === "active")- .map((heartbeat) => heartbeat.job.activeSessionId),- );- const childrenByParent = new Map<string | undefined, AgentConnectionRlmChildAgentSnapshot[]>();- for (const child of this.childAgentSnapshots.values()) {- const siblings = childrenByParent.get(child.parentId) ?? [];- siblings.push(child);- childrenByParent.set(child.parentId, siblings);- }-- const build = (child: AgentConnectionRlmChildAgentSnapshot): ChildAgentInspectorNode => ({- id: child.id,- activeSessionId: child.activeSessionId,- sessionName: child.sessionName,- model: child.model,- label: child.label,- status: child.status,- durationMs: child.durationMs,- answerPreview: child.answerPreview,- toolUseCount: child.toolUseCount,- tokenCount: child.tokenCount,- recap: child.recap,- sessionDir: child.sessionDir,- activity: child.activity,- hasActiveHeartbeat:- child.activeSessionId !== undefined && activeHeartbeatSessionIds.has(child.activeSessionId),- error: child.error,- children: childrenByParent.get(child.id)?.map(build),- });-- return (childrenByParent.get(undefined) ?? []).map(build);- }-- private findChildAgentInspectorNode(nodeId: string): ChildAgentInspectorNode | undefined {- const visit = (nodes: readonly ChildAgentInspectorNode[]): ChildAgentInspectorNode | undefined => {- for (const node of nodes) {- if (node.id === nodeId) {- return node;- }- const child = visit(node.children ?? []);- if (child) {- return child;- }- }- return undefined;- };- return visit(this.childAgentNodes);- }-/** Extract text content from a user message */private getUserMessageText(message: Message): string {if (message.role !== "user") return "";@@ -6783,7 +6462,8 @@ export class InteractiveMode {const context = this.getSessionContextFromConnectionSnapshot(snapshot);const state = snapshot.state;const streamingMessage = snapshot.streamingMessage;- this.seedChildAgentInspector(snapshot.children);+ this.rlmNodeId = snapshot.parent?.childId;+ this.seedSubagentSummary(snapshot.children);this.setSessionHasMessages(context.messages.length > 0);this.applyConnectionStateSnapshot(state);await this.renderSessionContext(context, {@@ -6944,12 +6624,12 @@ export class InteractiveMode {this.ctrlCExitHintTimer = undefined;if (!this.isCtrlCExitHintVisible()) {this.ctrlCExitHintExpiresAt = 0;- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.ui.requestRender();}}, InteractiveMode.EXIT_HINT_DURATION_MS);this.ctrlCExitHintTimer.unref?.();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.ui.requestRender();}@@ -6963,7 +6643,7 @@ export class InteractiveMode {}this.ctrlCExitHintExpiresAt = 0;if (options.render !== false) {- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.ui.requestRender();}}@@ -7215,7 +6895,7 @@ export class InteractiveMode {}private getPromptDockComponents(): Component[] {- return [this.editorContainer, this.childAgentSummary, this.footerSlot];+ return [this.editorContainer, this.subagentSummaryLine, this.footerSlot];}/** Enter or leave fullscreen rendering without touching the persisted setting. */@@ -7270,7 +6950,6 @@ export class InteractiveMode {child.setExpanded(expanded);}}- this.childAgentDetail.setToolsExpanded(expanded);// Expanding/collapsing changes blocks above the viewport, which would// otherwise force a full redraw that scrolls to the top and replays the// whole transcript. Keep the user anchored at their current position.@@ -7297,11 +6976,6 @@ export class InteractiveMode {this.chatContainer.addChild(this.streamingComponent);}- // The open subagent body bakes in thinking visibility at build time.- if (this.childAgentWatcher) {- await this.rebuildChildAgentBody(this.childAgentWatcherToken);- }-this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);})().catch((error) => {this.showError(error instanceof Error ? error.message : String(error));@@ -7736,7 +7410,7 @@ export class InteractiveMode {availableThinkingLevels: state.availableThinkingLevels,});this.footer.invalidate();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.updateEditorBorderColor();// Rebuild so the /effort argument hint reflects the new model's levels.this.setupAutocompleteProvider();@@ -7992,7 +7666,7 @@ export class InteractiveMode {}this.patchConnectionState({ serviceTier: state.serviceTier });this.footer.invalidate();- this.childAgentSummary.invalidate();+ this.subagentSummaryLine.invalidate();this.showStatus(`Fast mode: ${state.serviceTier === "priority" ? "on" : "off"}`);}).catch((error) => {@@ -9819,7 +9493,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor| \`${selectModel}\` | Open model selector || \`${expandTools}\` | Toggle tool output expansion || \`${toggleThinking}\` | Toggle thinking block visibility |-| \`${focusSubagents}\` | Open subagent inspector |+| \`${focusSubagents}\` | Focus the subagent summary / open the scoped agents view || \`${manageHeartbeats}\` | Manage heartbeats || \`${externalEditor}\` | Edit message in external editor || \`${promptStash}\` | Stash or restore draft prompt |diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.tsdeleted file mode 100644index 3995493a89..0000000000--- a/packages/coding-agent/test/child-agent-summary-list.test.ts+++ /dev/null@@ -1,330 +0,0 @@-import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";-import { beforeAll, describe, expect, it } from "vitest";-import { KeybindingsManager } from "../src/core/keybindings.js";-import {- ChildAgentDetailComponent,- type ChildAgentInspectorNode,- ChildAgentSummaryComponent,-} from "../src/modes/interactive/components/child-agent-inspector.js";-import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";-import { setWorkingPulseFrame, workingIconFrame } from "../src/modes/interactive/theme/working-icon.js";--function stripAnsi(text: string): string {- return text.replace(/\x1b\[[0-9;]*m/g, "");-}--function node(id: string, status: ChildAgentInspectorNode["status"] = "running"): ChildAgentInspectorNode {- return { id, label: id, status, sessionDir: `/tmp/${id}` };-}--describe("ChildAgentSummaryComponent inline list", () => {- beforeAll(() => {- initTheme("dark");- setKeybindings(new KeybindingsManager());- });-- it("renders one row per subagent when within the cap", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([node("alpha"), node("beta")]);- const out = stripAnsi(summary.render(80).join("\n"));- expect(out).toContain("alpha");- expect(out).toContain("beta");- expect(out).not.toMatch(/more (above|below)/);- });-- it("caps the list at five rows and shows a scroll indicator", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f"), node("g")]);- const lines = summary.render(80).map(stripAnsi);- // Row lines carry a status glyph; the scroll-hint line does not.- const rowLines = lines.filter((line) => /[◇◈◆✓✗]/.test(line));- expect(rowLines.length).toBe(5);- expect(lines.join("\n")).toContain("2 below");- });-- it("keeps the active agents visible when a previously selected agent finishes", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f")]);- summary.selectNode("a");- summary.setNodes([node("a", "done"), node("b"), node("c"), node("d"), node("e"), node("f")]);- const out = summary.render(80).map(stripAnsi).join("\n");- expect(out).toContain("b");- expect(out).toContain("f");- expect(out).not.toContain(" a ");- });-- it("shows the model and token usage without a tool column", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("a"), model: "openai/gpt-5.4", toolUseCount: 3, tokenCount: 41_000 }]);- const out = stripAnsi(summary.render(80).join("\n"));- expect(out).toContain("GPT-5.4");- expect(out).not.toContain("openai/gpt-5.4");- expect(out).toContain("41k tok");- expect(out).not.toContain("tools");- });-- it("preserves nested model ids when the label is truncated", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("a"), model: "prime-inference/internal/glm-5.2-fast" }]);- const out = stripAnsi(summary.render(80).join("\n"));- expect(out).toContain("intern…/glm-5.2-fast");- expect(out).not.toContain("prime-inference");- });-- it("shows recaps in a fixed column and falls back to activity", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([- { ...node("short"), recap: "Inspecting the scheduler queue" },- { ...node("a much longer starting prompt"), activity: { kind: "executing", toolName: "ipython" } },- ]);- const lines = summary.render(100).map(stripAnsi);- expect(lines.join("\n")).toContain("Inspecting the scheduler queue");- expect(lines.join("\n")).toContain("Executing ipython");- expect(lines[0]?.indexOf("Inspecting")).toBe(lines[1]?.indexOf("Executing"));- expect(lines.join("\n")).not.toContain("│");- });-- it("scrolls the window and updates the indicator as selection moves down", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f"), node("g")]);- // Drive selection past the initial window via the down key.- for (let i = 0; i < 6; i++) {- summary.handleInput("\x1b[B");- }- const out = summary.render(80).map(stripAnsi).join("\n");- expect(out).toContain("g");- expect(out).toContain("above");- });-- it("animates the running row glyph across pulse frames", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([node("a", "running")]);- setWorkingPulseFrame(0);- const frame0 = stripAnsi(summary.render(80).join("\n"));- setWorkingPulseFrame(1);- const frame1 = stripAnsi(summary.render(80).join("\n"));- expect(frame0).toContain(workingIconFrame(0));- expect(frame1).toContain(workingIconFrame(1));- expect(frame0).not.toBe(frame1);- });-- it("shows heartbeating completed subagents as active with heartbeat icons", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("done", "done") }, { ...node("heartbeat", "done"), hasActiveHeartbeat: true }]);- const lines = summary.render(80).map(stripAnsi);-- expect(lines[0]).toContain("♥");- expect(lines[0]).toContain("heartbeat");- expect(lines[0]).toContain("Heartbeat active");- expect(lines[1]).toContain("✓");- });-- it("can reselect a node by id when returning from its detail view", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a"), node("b"), node("c")]);- summary.selectNode("c");- let opened: string | undefined;- summary.onOpenDetail = (id) => {- opened = id;- };- summary.handleInput("\r");- expect(opened).toBe("c");- });-- it("uses compact fixed-width S-number labels", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([node("first task"), node("second task")]);- const out = stripAnsi(summary.render(80).join("\n"));- expect(out).toContain("S1");- expect(out).toContain("S2");- expect(out).not.toContain("Subagent");- expect(out).not.toContain("↳");- });-- it("aligns the row icon and label with the agents-view tray hint", () => {- const summary = new ChildAgentSummaryComponent(() => "← agents view");- summary.setNodes([node("task", "done")]);- const [infoLine = "", row = ""] = summary.render(80).map(stripAnsi);- expect(row.indexOf("✓")).toBe(infoLine.indexOf("←"));- expect(row.indexOf("S1")).toBe(infoLine.indexOf("agents"));- });-- it("keeps truncation ellipses in the prompt color", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("a"), label: "A starting prompt that is much too long for its fixed column" }]);- const out = summary.render(80).join("\n");- const ellipsisIndex = out.indexOf("…");- const beforeEllipsis = out.slice(0, ellipsisIndex);- const dimStart = theme.fg("dim", "").replace("\x1b[39m", "");- expect(ellipsisIndex).toBeGreaterThan(0);- expect(beforeEllipsis.lastIndexOf(dimStart)).toBeGreaterThan(beforeEllipsis.lastIndexOf("\x1b[39m"));- expect(out[ellipsisIndex - 1]).not.toBe(" ");- });-- it("prefers stable session names over spawn prompts in the summary row", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([- {- ...node("a"),- sessionName: "anticheat-review",- label: "You are doing a manual trajectory review for anti-cheat evidence",- recap: "Extracting and analyzing test results",- },- ]);- const out = stripAnsi(summary.render(120).join("\n"));- expect(out).toContain("anticheat-review");- expect(out).not.toContain("manual trajectory");- expect(out).toContain("Extracting and analyzing test results");- });-- it("keeps the selected background active across the entire row", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([- {- ...node("a"),- label: "A starting prompt that is much too long for its fixed column",- recap: "A recap that is also much too long for its fixed column and must be truncated",- toolUseCount: 3,- tokenCount: 41_000,- durationMs: 5_000,- },- ]);- const [line] = summary.render(80);- const backgroundStart = theme.bg("selectedBg", "").replace("\x1b[49m", "");- expect(line?.startsWith(backgroundStart)).toBe(true);- expect(line?.endsWith("\x1b[49m")).toBe(true);- expect(line).not.toContain("\x1b[0m");- });-- it("adds extra space between token count and duration", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("a"), tokenCount: 41_000, durationMs: 5_000 }]);- const out = stripAnsi(summary.render(80).join("\n"));- expect(out).toMatch(/41k tok\s{3}5s/);- });-- it("shows the model to the right of the back action in detail view", () => {- const detail = new ChildAgentDetailComponent();- detail.setNode({ ...node("a"), model: "anthropic/claude-opus-4-7" });- const hint = stripAnsi(detail.render(100).at(-1) ?? "");- expect(hint).toContain("back to chat");- expect(hint).toContain("Claude Opus 4.7");- expect(hint).not.toContain("anthropic/claude-opus-4-7");- expect(hint.indexOf("Claude Opus 4.7")).toBeGreaterThan(hint.indexOf("back to chat"));- });-- it("truncates long models before hiding detail actions", () => {- const detail = new ChildAgentDetailComponent();- detail.setNode({- ...node("a"),- model: "provider-with-a-long-name/model-with-an-even-longer-name",- });- const hint = stripAnsi(detail.render(60).at(-1) ?? "");- expect(hint).toContain("back to chat");- expect(hint).toContain("model-wit…");- expect(hint).not.toContain("provider-with-a-long-name");- expect(hint).toContain("to expand");- expect(hint).toContain("stop");- });-- it("keeps the starting prompt compact so the recap gets more room", () => {- const summary = new ChildAgentSummaryComponent();- const prompt = "Investigate every scheduler dispatch path and identify all possible starvation conditions";- summary.setNodes([{ ...node("a"), label: prompt, recap: "Found an unfair queue rotation" }]);- const out = stripAnsi(summary.render(100).join("\n"));- expect(out).not.toContain(prompt);- expect(out).toContain("Investigate every");- expect(out).toContain("Found an unfair queue rotation");- });-- it("never exceeds the row width with wide (CJK) characters", () => {- const wide = "実行するタスクは非常に長い説明を含んでいてこれは折り返しのテストです".repeat(3);- const summary = new ChildAgentSummaryComponent();- summary.setNodes([{ ...node("a"), label: wide, recap: wide, toolUseCount: 12, tokenCount: 912_000 }]);- for (const width of [40, 60, 80]) {- for (const line of summary.render(width)) {- expect(visibleWidth(line)).toBeLessThanOrEqual(width);- }- }- });-- it("elides a shared prompt prefix so rows surface where they differ", () => {- const summary = new ChildAgentSummaryComponent();- summary.setNodes([- { ...node("a"), label: "Refactor the authentication module for tokens" },- { ...node("b"), label: "Refactor the authentication module for refresh" },- ]);- const out = stripAnsi(summary.render(120).join("\n"));- // The shared prefix is replaced by an ellipsis; the differing tail survives.- expect(out).toContain("…");- expect(out).not.toContain("Refactor the authentication module for tokens");- });-- it("surfaces the divergence even when the shared prefix is very long", () => {- const prefix = "You are a sleeper subagent in a parallel batch. Please sleep for exactly ";- const summary = new ChildAgentSummaryComponent();- summary.setNodes([- { ...node("a"), label: `${prefix}30 seconds then report done` },- { ...node("b"), label: `${prefix}120 seconds then report done` },- ]);- const out = stripAnsi(summary.render(130).join("\n"));- expect(out).toContain("exactly 30");- expect(out).toContain("exactly 120");- });-- it("windows tightly around the diff when prompts share a head and tail", () => {- const head =- "Hello there. You are a subagent and we give subagents different tasks. Your task is to sleep since you are subagent ";- const tail = " and therefore you were assigned to sleep ten minutes total today";- const summary = new ChildAgentSummaryComponent();- summary.setNodes([- { ...node("a"), label: `${head}#1${tail}` },- { ...node("b"), label: `${head}#2${tail}` },- ]);- const out = stripAnsi(summary.render(120).join("\n"));- expect(out).toContain("#1");- expect(out).toContain("#2");- // The shared tail is dropped behind a trailing ellipsis, not shown in full.- expect(out).not.toContain("assigned to sleep ten minutes total today");- });-- it("forwards unhandled keys to the chat action callback", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a")]);- let forwarded: string | undefined;- summary.onChatAction = (data) => {- forwarded = data;- };- // Ctrl+O isn't a list key, so it should bubble to the chat action handler.- summary.handleInput("\x0f");- expect(forwarded).toBe("\x0f");- });-- it("opens the selected subagent's detail on confirm", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a"), node("b")]);- let opened: string | undefined;- summary.onOpenDetail = (id) => {- opened = id;- };- summary.handleInput("\r");- expect(opened).toBe("a");- });-- it("falls back to onOpen when confirm is pressed with no selection", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([]); // list emptied while focused: no selection- let fellBack = false;- summary.onOpen = () => {- fellBack = true;- };- summary.handleInput("\r");- expect(fellBack).toBe(true);- });-});diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 4b9435becc..85f8f77175 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -33,6 +33,7 @@ import {createDaemonCommandEnvelope,type DaemonAttachResult,type DaemonCommand,+ type DaemonOutbound,} from "../src/modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";@@ -3086,6 +3087,119 @@ describe("daemon mode helpers", () => {expect(client.catchupActiveSessionIds).toEqual(new Set());});+ it("automatically retries every pending catch-up after snapshot creation rejects", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const firstState = makeState("first");+ const secondState = makeState("second");+ firstState.eventGeneration = "generation-1";+ secondState.eventGeneration = "generation-2";+ const write = vi.fn((_data: unknown) => true);+ const client = makeClient("client-1", firstState.activeSessionId);+ client.socket = { destroyed: false, write } as unknown as Socket;+ firstState.clients.add(client);+ secondState.clients.add(client);+ const createAttachResult = vi.fn(async (_client: DaemonSocketClient, state: ActiveSessionState) => {+ if (createAttachResult.mock.calls.length === 1) {+ throw new Error("snapshot creation failed");+ }+ return {+ activeSessionId: state.activeSessionId,+ snapshot: {+ activeSessionId: state.activeSessionId,+ state: { activeSessionId: state.activeSessionId },+ messages: [],+ lastEventSequence: state.lastEventSequence,+ },+ lastEventSequence: state.lastEventSequence,+ } as unknown as DaemonAttachResult;+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: typeof createAttachResult;+ queueClientCatchup(+ client: DaemonSocketClient,+ activeSessionId: string,+ purpose?: "replacement" | "resync",+ ): void;+ catchUpBackpressuredClient(client: DaemonSocketClient): Promise<void>;+ };+ internals.sessions.set(firstState.activeSessionId, firstState);+ internals.sessions.set(secondState.activeSessionId, secondState);+ internals.createAttachResult = createAttachResult;+ internals.queueClientCatchup(client, firstState.activeSessionId, "replacement");+ internals.queueClientCatchup(client, secondState.activeSessionId, "resync");++ await internals.catchUpBackpressuredClient(client);++ expect(client.catchupActiveSessionIds).toEqual(+ new Set([firstState.activeSessionId, secondState.activeSessionId]),+ );+ expect(client.catchupPurposes).toEqual(+ new Map([+ [firstState.activeSessionId, "replacement"],+ [secondState.activeSessionId, "resync"],+ ]),+ );+ expect(createAttachResult).toHaveBeenCalledOnce();++ await vi.waitFor(() => expect(createAttachResult).toHaveBeenCalledTimes(3));++ expect(client.catchupActiveSessionIds).toEqual(new Set());+ expect(client.catchupPurposes).toEqual(new Map());+ const messages = write.mock.calls.map(([data]) => JSON.parse(String(data)) as { type: string });+ expect(messages.map((message) => message.type)).toEqual(["session_replaced", "session_resynced"]);+ });++ it("clears a scheduled catch-up retry when the client disconnects", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = makeState("active");+ state.extensionUiRequests = new Map();+ const socketState = { destroyed: false };+ const socket = Object.assign(new EventEmitter(), {+ get destroyed() {+ return socketState.destroyed;+ },+ write: vi.fn((_data: unknown) => true),+ }) as unknown as Socket;+ const createAttachResult = vi.fn(async () => {+ throw new Error("snapshot creation failed");+ });+ const internals = daemon as unknown as {+ clients: Set<DaemonSocketClient>;+ sessions: Map<string, ActiveSessionState>;+ handleConnection(socket: Socket): void;+ createAttachResult: typeof createAttachResult;+ queueClientCatchup(client: DaemonSocketClient, activeSessionId: string): void;+ catchUpBackpressuredClient(client: DaemonSocketClient): Promise<void>;+ };+ internals.handleConnection(socket);+ const client = [...internals.clients][0]!;+ client.attachedActiveSessionIds.add(state.activeSessionId);+ state.clients.add(client);+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = createAttachResult;+ internals.queueClientCatchup(client, state.activeSessionId);++ await internals.catchUpBackpressuredClient(client);++ expect(client.catchupRetryTimer).toBeDefined();+ socketState.destroyed = true;+ socket.emit("close");+ expect(client.catchupRetryTimer).toBeUndefined();+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(createAttachResult).toHaveBeenCalledOnce();+ });+it("marks a chunked attach as snapshotting before deferred streaming", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-order-"));try {@@ -3146,7 +3260,7 @@ describe("daemon mode helpers", () => {expect(client.snapshotActiveSessionIds).not.toContain("active");});- it("falls back to a full replacement when snapshot cache creation fails", () => {+ it("falls back to a full replacement when snapshot cache creation fails", async () => {const root = mkdtempSync(join(tmpdir(), "prime-agent-daemon-replacement-fallback-"));try {const invalidAgentDir = join(root, "not-a-directory");@@ -3175,10 +3289,12 @@ describe("daemon mode helpers", () => {lastEventSequence: 0,} as unknown as DaemonAttachResult;const internals = daemon as unknown as {- createAttachResult: () => DaemonAttachResult;+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: () => Promise<DaemonAttachResult>;broadcastToSession(state: ActiveSessionState, message: unknown): void;};- internals.createAttachResult = () => result;+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = async () => result;internals.broadcastToSession(state, {type: "session_replaced",@@ -3187,16 +3303,156 @@ describe("daemon mode helpers", () => {messages: [],});- expect(write).toHaveBeenCalledTimes(2);- const replacementFrame = String(write.mock.calls[0]?.[0]);- expect(replacementFrame).toContain('"type":"session_replaced"');- expect(replacementFrame).toContain('"snapshotFollows":true');- expect(String(write.mock.calls[1]?.[0])).toContain('"type":"session_snapshot_begin"');+ await vi.waitFor(() => expect(write).toHaveBeenCalled());+ const frames = write.mock.calls.map((call) => String(call[0])).join("\n");+ expect(frames).toContain('"type":"session_replaced"');+ expect(frames).toContain('"snapshotFollows":true');+ expect(frames).toContain('"type":"session_snapshot_begin"');} finally {rmSync(root, { recursive: true, force: true });}});+ it.each(["resolved", "rejected"] as const)(+ "does not send a replacement snapshot after the session closes while preparation is %s",+ async (outcome) => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = makeState("active");+ state.eventGeneration = "generation-1";+ state.extensionUiRequests = new Map();+ state.unsubscribe = vi.fn();+ state.runtime = {+ ...state.runtime,+ dispose: vi.fn(async () => {}),+ session: {+ sessionId: "session-active",+ sessionFile: undefined,+ isBashRunning: false,+ abort: vi.fn(async () => {}),+ sessionManager: { appendSessionState: vi.fn() },+ },+ } as unknown as ActiveSessionState["runtime"];+ const write = vi.fn((_data: unknown) => true);+ const client = makeClient("client-1", state.activeSessionId);+ client.socket = { destroyed: false, write } as unknown as Socket;+ client.transport = "private-framed";+ setDaemonClientSessionCapabilities(client, state.activeSessionId, new Set(["chunked_snapshot"]));+ state.clients.add(client);+ let resolveAttach: (result: DaemonAttachResult) => void = () => {};+ let rejectAttach: (error: Error) => void = () => {};+ const pendingAttach = new Promise<DaemonAttachResult>((resolve, reject) => {+ resolveAttach = resolve;+ rejectAttach = reject;+ });+ const streamWorkerSnapshot = vi.fn(async () => {});+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ streamWorkerSnapshot: typeof streamWorkerSnapshot;+ closeSession(state: ActiveSessionState, reason: "killed"): Promise<void>;+ closeChildSessions: ReturnType<typeof vi.fn>;+ isEmptyDraftContent: ReturnType<typeof vi.fn>;+ abortBashForClose: ReturnType<typeof vi.fn>;+ recordWorkerRecoveryState: ReturnType<typeof vi.fn>;+ cancelScheduledJobsForSession: ReturnType<typeof vi.fn>;+ broadcastToSession(state: ActiveSessionState, message: unknown): void;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = vi.fn(() => pendingAttach);+ internals.streamWorkerSnapshot = streamWorkerSnapshot;+ internals.closeChildSessions = vi.fn(async () => undefined);+ internals.isEmptyDraftContent = vi.fn(() => true);+ internals.abortBashForClose = vi.fn(async () => {});+ internals.recordWorkerRecoveryState = vi.fn();+ internals.cancelScheduledJobsForSession = vi.fn();++ internals.broadcastToSession(state, {+ type: "session_replaced",+ activeSessionId: state.activeSessionId,+ state: {},+ messages: [],+ });+ const snapshotSignal = client.snapshotTransferAbortControllers?.get(state.activeSessionId)?.signal;+ expect(snapshotSignal?.aborted).toBe(false);++ await internals.closeSession(state, "killed");+ expect(snapshotSignal?.aborted).toBe(true);++ if (outcome === "resolved") {+ resolveAttach({+ activeSessionId: state.activeSessionId,+ snapshot: { summary: {}, state: {}, messages: [] },+ lastEventSequence: 0,+ } as unknown as DaemonAttachResult);+ } else {+ rejectAttach(new Error("snapshot preparation failed after close"));+ }+ await vi.waitFor(() => expect(client.snapshotStreaming).toBe(false));++ const frames = write.mock.calls.map((call) => String(call[0])).join("\n");+ expect(frames).toContain('"type":"session_closed"');+ expect(frames).not.toContain('"type":"session_replaced"');+ expect(frames).not.toContain('"type":"session_snapshot_begin"');+ expect(streamWorkerSnapshot).not.toHaveBeenCalled();+ },+ );++ it("drains queued catch-up after replacement snapshot preparation outlives its session", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = makeState("closing");+ state.eventGeneration = "generation-1";+ const otherState = makeState("queued");+ const client = makeClient("client-1", state.activeSessionId);+ client.transport = "private-framed";+ setDaemonClientSessionCapabilities(client, state.activeSessionId, new Set(["chunked_snapshot"]));+ state.clients.add(client);+ let resolveAttach: (result: DaemonAttachResult) => void = () => {};+ const pendingAttach = new Promise<DaemonAttachResult>((resolve) => {+ resolveAttach = resolve;+ });+ const catchUpBackpressuredClient = vi.fn(async (target: DaemonSocketClient) => {+ target.catchupActiveSessionIds?.clear();+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ catchUpBackpressuredClient: typeof catchUpBackpressuredClient;+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.sessions.set(otherState.activeSessionId, otherState);+ internals.createAttachResult = vi.fn(() => pendingAttach);+ internals.catchUpBackpressuredClient = catchUpBackpressuredClient;++ internals.broadcastToSession(state, {+ type: "session_replaced",+ activeSessionId: state.activeSessionId,+ state: {},+ messages: [],+ } as unknown as DaemonOutbound);+ client.catchupActiveSessionIds = new Set([otherState.activeSessionId]);+ internals.sessions.delete(state.activeSessionId);+ resolveAttach({+ activeSessionId: state.activeSessionId,+ snapshot: { summary: {}, state: {}, messages: [] },+ lastEventSequence: 0,+ } as unknown as DaemonAttachResult);++ await vi.waitFor(() => expect(catchUpBackpressuredClient).toHaveBeenCalledWith(client));+ expect(client.snapshotStreaming).toBe(false);+ expect(client.catchupActiveSessionIds).toEqual(new Set());+ });+it.each([["explicit session file", (sessionPath: string) => ({ type: "create" as const, sessionPath })],["continue recent", (_sessionPath: string) => ({ type: "create" as const, continueRecent: true })],@@ -3612,6 +3868,9 @@ describe("daemon mode helpers", () => {createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController;+ buildRlmChildSnapshotsWithPassiveRlmSubagents(+ state: ActiveSessionState,+ ): Promise<NonNullable<DaemonAttachResult["snapshot"]["children"]>>;handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;};@@ -3622,6 +3881,21 @@ describe("daemon mode helpers", () => {expect(fixture.createRuntime).toHaveBeenCalledOnce();expect([...internals.sessions.values()]).toEqual([parentState]);+ const children = await internals.buildRlmChildSnapshotsWithPassiveRlmSubagents(parentState);+ expect(children).toEqual([+ expect.objectContaining({+ id: fixture.childId,+ status: "done",+ }),+ expect.objectContaining({+ id: fixture.grandchildId,+ parentId: fixture.childId,+ status: "done",+ }),+ ]);+ expect(children.every((child) => child.activeSessionId === undefined)).toBe(true);+ // Snapshotting must reuse the passive registry walk without hydrating children.+ expect(fixture.createRuntime).toHaveBeenCalledOnce();expect((await internals.createAgentMessageController(() => parentState).listAgents()).agents).toContainEqual(expect.objectContaining({activeSessionId: expect.any(String),diff --git a/packages/coding-agent/test/interactive-heartbeat-management.test.ts b/packages/coding-agent/test/interactive-heartbeat-management.test.tsindex 17e649f2aa..c7923fd8db 100644--- a/packages/coding-agent/test/interactive-heartbeat-management.test.ts+++ b/packages/coding-agent/test/interactive-heartbeat-management.test.ts@@ -27,18 +27,18 @@ interface HeartbeatScopeHarness {heartbeatCatalog: AgentConnectionHeartbeat[];heartbeats: AgentConnectionHeartbeat[];connectionState: { activeSessionId: string; sessionId: string };- childAgentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;+ subagentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;heartbeatManager: { setHeartbeats(heartbeats: AgentConnectionHeartbeat[]): void } | undefined;+ ui: { requestRender(): void };scheduleHeartbeatManagerRefresh(): void;- refreshChildAgentInspector(): void;+ updateSubagentSummaryLine(): void;applyHeartbeatCatalog(heartbeats: AgentConnectionHeartbeat[]): void;}interface ChildIdentityUpdateHarness {- childAgentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;- childAgentDetailNodeId: string | undefined;- refreshChildAgentInspector(): void;- updateChildAgentInspector(child: AgentConnectionRlmChildAgentSnapshot): void;+ subagentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;+ refreshSubagentSummary(): void;+ updateSubagentSummary(child: AgentConnectionRlmChildAgentSnapshot): void;}interface HeartbeatRefreshHarness {@@ -49,12 +49,6 @@ interface HeartbeatRefreshHarness {scheduleHeartbeatManagerRefresh(): void;}-interface HeartbeatChildHarness {- heartbeats: AgentConnectionHeartbeat[];- childAgentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;- buildChildAgentInspectorNodes(): Array<{ id: string; hasActiveHeartbeat?: boolean }>;-}-function heartbeat(overrides: Partial<AgentCronJob> = {}): AgentCronJob {return {id: "heartbeat-1",@@ -75,34 +69,6 @@ function heartbeat(overrides: Partial<AgentCronJob> = {}): AgentCronJob {}describe("interactive heartbeat management", () => {- it("maps only active heartbeat jobs onto below-prompt subagent rows", () => {- const harness = Object.create(InteractiveMode.prototype) as HeartbeatChildHarness;- harness.heartbeats = [- { job: { ...heartbeat(), activeSessionId: "active-child" } },- { job: { ...heartbeat(), id: "paused", activeSessionId: "paused-child", status: "paused" } },- ];- harness.childAgentSnapshots = new Map(- [- ["active", "active-child"],- ["paused", "paused-child"],- ].map(([id, activeSessionId]) => [- id,- {- id,- activeSessionId,- label: id,- status: "done",- sessionDir: `/tmp/${id}`,- } satisfies AgentConnectionRlmChildAgentSnapshot,- ]),- );-- expect(harness.buildChildAgentInspectorNodes()).toEqual([- expect.objectContaining({ id: "active", hasActiveHeartbeat: true }),- expect.objectContaining({ id: "paused", hasActiveHeartbeat: false }),- ]);- });-it("clears local user-heartbeat state after stopping from the manager", async () => {const current = heartbeat();const stopped = { ...current, status: "cancelled" as const, nextRunAt: undefined };@@ -159,7 +125,7 @@ describe("interactive heartbeat management", () => {harness.heartbeatCatalog = [];harness.heartbeats = [];harness.connectionState = { activeSessionId: "active-1", sessionId: "session-1" };- harness.childAgentSnapshots = new Map([+ harness.subagentSnapshots = new Map([["child-1",{@@ -172,15 +138,16 @@ describe("interactive heartbeat management", () => {],]);harness.heartbeatManager = { setHeartbeats: vi.fn() };+ harness.ui = { requestRender: vi.fn() };harness.scheduleHeartbeatManagerRefresh = vi.fn();- harness.refreshChildAgentInspector = vi.fn();+ harness.updateSubagentSummaryLine = vi.fn();harness.applyHeartbeatCatalog([own, child, unrelated]);expect(harness.heartbeatCatalog).toEqual([own, child, unrelated]);expect(harness.heartbeats).toEqual([own, child]);expect(harness.heartbeatManager.setHeartbeats).toHaveBeenCalledWith([own, child]);- expect(harness.refreshChildAgentInspector).toHaveBeenCalledOnce();+ expect(harness.updateSubagentSummaryLine).toHaveBeenCalledOnce();});it("refreshes heartbeat scope when a known subagent gains its active session id", () => {@@ -191,14 +158,13 @@ describe("interactive heartbeat management", () => {sessionDir: "/tmp/child-1",};const harness = Object.create(InteractiveMode.prototype) as ChildIdentityUpdateHarness;- harness.childAgentSnapshots = new Map([[existing.id, existing]]);- harness.childAgentDetailNodeId = undefined;- harness.refreshChildAgentInspector = vi.fn();+ harness.subagentSnapshots = new Map([[existing.id, existing]]);+ harness.refreshSubagentSummary = vi.fn();- harness.updateChildAgentInspector({ ...existing, activeSessionId: "active-2" });+ harness.updateSubagentSummary({ ...existing, activeSessionId: "active-2" });- expect(harness.childAgentSnapshots.get(existing.id)?.activeSessionId).toBe("active-2");- expect(harness.refreshChildAgentInspector).toHaveBeenCalledOnce();+ expect(harness.subagentSnapshots.get(existing.id)?.activeSessionId).toBe("active-2");+ expect(harness.refreshSubagentSummary).toHaveBeenCalledOnce();});it("refreshes an open manager after the next scheduled run", async () => {diff --git a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts b/packages/coding-agent/test/interactive-mode-ctrl-c.test.tsindex 35d21ccafe..eaf202397c 100644--- a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts+++ b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts@@ -36,7 +36,7 @@ type FakeInteractiveMode = {abortBranchSummary: Mock;abortBash: Mock;};- childAgentSummary: { invalidate: Mock };+ subagentSummaryLine: { invalidate: Mock };ui: { requestRender: Mock; onDebug?: () => void };restoreQueuedMessagesToEditor: Mock;updatePendingMessagesDisplay: Mock;@@ -106,7 +106,7 @@ function createInteractiveFake(options: {abortBranchSummary: vi.fn(),abortBash: vi.fn(),},- childAgentSummary: { invalidate: vi.fn() },+ subagentSummaryLine: { invalidate: vi.fn() },ui: { requestRender: vi.fn() },restoreQueuedMessagesToEditor: vi.fn().mockResolvedValue(0),updatePendingMessagesDisplay: vi.fn(),@@ -207,7 +207,7 @@ describe("InteractiveMode interrupt shortcuts", () => {await vi.advanceTimersByTimeAsync(2000);expect(Reflect.get(InteractiveMode.prototype, "getTrayOverrideLabel").call(mode)).toBeUndefined();- expect(mode.childAgentSummary.invalidate).toHaveBeenCalled();+ expect(mode.subagentSummaryLine.invalidate).toHaveBeenCalled();expect(mode.ui.requestRender).toHaveBeenCalled();});diff --git a/packages/coding-agent/test/interactive-mode-effort-command.test.ts b/packages/coding-agent/test/interactive-mode-effort-command.test.tsindex 05558a4649..12a7e5a2c2 100644--- a/packages/coding-agent/test/interactive-mode-effort-command.test.ts+++ b/packages/coding-agent/test/interactive-mode-effort-command.test.ts@@ -42,7 +42,7 @@ type FastCommandContext = {getState: () => Promise<{ sessionId: string; serviceTier: ServiceTier }>;};footer: { invalidate: () => void };- childAgentSummary: { invalidate: () => void };+ subagentSummaryLine: { invalidate: () => void };showStatus: (message: string) => void;showError: (message: string) => void;patchConnectionState: (patch: Record<string, unknown>) => void;@@ -79,7 +79,7 @@ function makeFastContext(model: Model<Api> = testModel("openai-codex", "gpt-5.5"fastModeToggleQueue: Promise.resolve(),agentConnection: undefined as never,footer: { invalidate: vi.fn() },- childAgentSummary: { invalidate: vi.fn() },+ subagentSummaryLine: { invalidate: vi.fn() },showStatus: vi.fn(),showError: vi.fn(),patchConnectionState: vi.fn((patch: Record<string, unknown>) => {@@ -244,7 +244,7 @@ describe("InteractiveMode /effort", () => {settingsManager: { setDefaultModelAndProvider: (provider: string, id: string) => void };patchConnectionState: (patch: Record<string, unknown>) => void;footer: { invalidate: () => void };- childAgentSummary: { invalidate: () => void };+ subagentSummaryLine: { invalidate: () => void };updateEditorBorderColor: () => void;setupAutocompleteProvider: () => void;};@@ -272,7 +272,7 @@ describe("InteractiveMode /effort", () => {settingsManager: { setDefaultModelAndProvider: vi.fn() },patchConnectionState,footer: { invalidate: vi.fn() },- childAgentSummary: { invalidate: vi.fn() },+ subagentSummaryLine: { invalidate: vi.fn() },updateEditorBorderColor: vi.fn(),setupAutocompleteProvider,};@@ -299,7 +299,7 @@ describe("InteractiveMode /effort", () => {expect(context.agentConnection.setServiceTier).toHaveBeenCalledWith("priority");expect(context.patchConnectionState).toHaveBeenCalledWith({ serviceTier: "priority" });expect(context.footer.invalidate).toHaveBeenCalledWith();- expect(context.childAgentSummary.invalidate).toHaveBeenCalledWith();+ expect(context.subagentSummaryLine.invalidate).toHaveBeenCalledWith();});it("disables Fast mode when it is already enabled", async () => {diff --git a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts b/packages/coding-agent/test/interactive-mode-feature-hints.test.tsindex ec65ce4fd9..d37628873f 100644--- a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts+++ b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts@@ -43,7 +43,6 @@ function createMode() {featureHintAnimationTimer: undefined,featureHintComponent: undefined,featureHintRunPending: false,- childAgentPanelMode: undefined,connectionQueue: { steering: [], followUp: [] },compactionQueuedMessages: [],options: { returnToAgentsView: true },@@ -173,47 +172,6 @@ describe("InteractiveMode feature hints", () => {expect(requestRender).not.toHaveBeenCalled();});- it("suspends hints in subagent detail and resumes them in the parent view", () => {- const { mode, featureHintContainer, featureHintDeck } = createMode();- Reflect.set(mode, "childAgentPanelMode", "detail");-- callPrivate(mode, "startFeatureHintPresentation");- vi.advanceTimersByTime(5_000);- expect(featureHintContainer.children).toHaveLength(0);- expect(featureHintDeck.next).not.toHaveBeenCalled();-- Reflect.set(mode, "childAgentPanelMode", undefined);- callPrivate(mode, "resumeFeatureHintPresentation");- vi.advanceTimersByTime(5_000);- expect(featureHintContainer.children).toHaveLength(1);- expect(featureHintDeck.next).toHaveBeenCalledOnce();- });-- it("resumes hints when an editor switch closes subagent detail", () => {- const resumeFeatureHintPresentation = vi.fn();- const defaultEditor = { setText: vi.fn() };- const mode = {- childAgentPanelMode: "detail",- childAgentDetailNodeId: "subagent-1",- childAgentDetail: { setBackHintLabel: vi.fn(), setNode: vi.fn() },- childAgentSummary: { setHidden: vi.fn() },- editor: { getText: () => "draft" },- defaultEditor,- editorContainer: { clear: vi.fn(), addChild: vi.fn() },- ui: { setFocus: vi.fn(), requestRender: vi.fn() },- restoreMainAgentView: vi.fn(),- updatePendingMessagesDisplay: vi.fn(),- resumeFeatureHintPresentation,- };- Object.setPrototypeOf(mode, InteractiveMode.prototype);-- Reflect.get(InteractiveMode.prototype, "setCustomEditorComponent").call(mode, undefined);-- expect(Reflect.get(mode, "childAgentPanelMode")).toBeUndefined();- expect(defaultEditor.setText).toHaveBeenCalledWith("draft");- expect(resumeFeatureHintPresentation).toHaveBeenCalledOnce();- });-it("retains the hint and remaining delay when the loader is recreated", () => {const { mode, statusContainer, featureHintContainer, featureHintDeck } = createMode();diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.tsindex cfa875a352..b77c85ee6e 100644--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts@@ -73,7 +73,7 @@ type ResetHarness = PromptStashLiveMarkerHarness & {ipythonToolComponents: Map<string, unknown>;lateIpythonSentAgentMessages: Map<string, unknown>;resetPendingToolState: Mock;- resetChildAgentInspector: Mock;+ resetSubagentSummary: Mock;setGoalAnnouncementBaseline: Mock;getGoalState: Mock<() => unknown>;syncGoalTray: Mock;@@ -555,7 +555,7 @@ describe("InteractiveMode prompt stash", () => {ipythonToolComponents: new Map(),lateIpythonSentAgentMessages: new Map(),resetPendingToolState: vi.fn(),- resetChildAgentInspector: vi.fn(),+ resetSubagentSummary: vi.fn(),setGoalAnnouncementBaseline: vi.fn(),getGoalState: vi.fn(() => undefined),syncGoalTray: vi.fn(),@@ -590,7 +590,7 @@ describe("InteractiveMode prompt stash", () => {ipythonToolComponents: new Map(),lateIpythonSentAgentMessages: new Map(),resetPendingToolState: vi.fn(),- resetChildAgentInspector: vi.fn(),+ resetSubagentSummary: vi.fn(),setGoalAnnouncementBaseline: vi.fn(),getGoalState: vi.fn(() => undefined),syncGoalTray: vi.fn(),diff --git a/packages/coding-agent/test/interactive-mode-startup.test.ts b/packages/coding-agent/test/interactive-mode-startup.test.tsindex 9ddfdcf891..c7ea2bc7ac 100644--- a/packages/coding-agent/test/interactive-mode-startup.test.ts+++ b/packages/coding-agent/test/interactive-mode-startup.test.ts@@ -21,7 +21,6 @@ describe("InteractiveMode startup hints", () => {function createMode(sessionHasMessages = false, returnToAgentsView = false, getEditorText = () => "") {const mode = {- childAgentPanelMode: undefined,sessionHasMessages,options: { returnToAgentsView },editor: { getText: getEditorText },diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 1a0500844a..f57e9fbe7f 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -33,7 +33,6 @@ import type {AgentConnectionModelCatalog,AgentConnectionResourceDiagnostic,AgentConnectionResourceSnapshot,- AgentConnectionRlmChildAgentSnapshot,AgentConnectionSessionContext,AgentConnectionSessionEvent,AgentConnectionSnapshot,@@ -47,12 +46,7 @@ import { BashExecutionComponent } from "../src/modes/interactive/components/bashimport type { ConfigurationMenuComponent } from "../src/modes/interactive/components/configuration-menu.js";import type { AuthSelectorProvider } from "../src/modes/interactive/components/oauth-selector.js";import type { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";-import {- formatSplashCwd,- InteractiveMode,- mergeChildAgentSnapshots,- truncatePathMiddle,-} from "../src/modes/interactive/interactive-mode.js";+import { formatSplashCwd, InteractiveMode, truncatePathMiddle } from "../src/modes/interactive/interactive-mode.js";import { ClientPromptStashStore, type PromptStashState } from "../src/modes/interactive/prompt-stash-state.js";import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";@@ -121,56 +115,6 @@ function createConnectionState(overrides: Partial<AgentConnectionState> = {}): A};}-describe("mergeChildAgentSnapshots", () => {- const rich: AgentConnectionRlmChildAgentSnapshot = {- id: "child-1",- activeSessionId: "active-child-1",- model: "openai/gpt-5.4",- label: "Inspect the scheduler",- status: "running",- durationMs: 5_000,- answerPreview: "Reading the queue",- toolUseCount: 4,- tokenCount: 41_000,- recap: "Tracing dispatch",- sessionDir: "/tmp/child-1",- activity: { kind: "executing", toolName: "ipython" },- };-- test("preserves rich live fields when a daemon resync is sparse", () => {- const merged = mergeChildAgentSnapshots(rich, {- id: "child-1",- label: "Inspect the scheduler",- status: "running",- sessionDir: "/tmp/child-1",- });-- expect(merged).toMatchObject({- activeSessionId: "active-child-1",- model: "openai/gpt-5.4",- durationMs: 5_000,- answerPreview: "Reading the queue",- toolUseCount: 4,- tokenCount: 41_000,- recap: "Tracing dispatch",- activity: { kind: "executing", toolName: "ipython" },- });- });-- test("clears transient activity when the child finishes", () => {- const merged = mergeChildAgentSnapshots(rich, {- id: "child-1",- label: "Inspect the scheduler",- status: "done",- sessionDir: "/tmp/child-1",- });-- expect(merged.activity).toBeUndefined();- expect(merged.toolUseCount).toBe(4);- expect(merged.tokenCount).toBe(41_000);- });-});-describe("InteractiveMode update notifications", () => {beforeAll(() => {initTheme("dark");@@ -835,8 +779,6 @@ describe("InteractiveMode submit handling", () => {});Object.assign(fakeThis, {editorContainer: new Container(),- childAgentPanelMode: undefined,- childAgentSummary: { setHidden: vi.fn() },ui: { setFocus: vi.fn(), requestRender: vi.fn() },keybindings: {},autocompleteProvider: undefined,@@ -1203,7 +1145,7 @@ describe("InteractiveMode pending bash components", () => {ipythonToolComponents: new Map(),lateIpythonSentAgentMessages: new Map(),resetPendingToolState: vi.fn(),- resetChildAgentInspector: vi.fn(),+ resetSubagentSummary: vi.fn(),setGoalAnnouncementBaseline: vi.fn(),syncGoalTray: vi.fn(),getGoalState: () => emptyGoalState(),@@ -1308,7 +1250,7 @@ describe("InteractiveMode connection events", () => {thinkingLevel: "medium",model: null,})),- seedChildAgentInspector: vi.fn(),+ seedSubagentSummary: vi.fn(),setSessionHasMessages: vi.fn(),applyConnectionStateSnapshot: vi.fn(),renderSessionContext: renderSessionContextMock,@@ -1510,7 +1452,7 @@ describe("InteractiveMode connection events", () => {streamingComponent: {},streamingMessage: {},applyConnectionStateSnapshot: vi.fn(),- replaceChildAgentInspector: vi.fn(),+ replaceSubagentSummary: vi.fn(),getSessionContextFromConnectionSnapshot: vi.fn(() => ({messages: [],thinkingLevel: "medium",@@ -1559,7 +1501,7 @@ describe("InteractiveMode connection events", () => {isAgentCompacting: () => true,isBashRunning: () => true,applyConnectionStateSnapshot: vi.fn(),- replaceChildAgentInspector: vi.fn(),+ replaceSubagentSummary: vi.fn(),getSessionContextFromConnectionSnapshot: vi.fn(() => ({messages: [],thinkingLevel: "medium",@@ -1657,48 +1599,6 @@ describe("InteractiveMode connection events", () => {expect(fakeThis.handleEvent).not.toHaveBeenCalled();expect(fakeThis.renderInitialMessages).toHaveBeenCalledOnce();});-- test("drops child body builds superseded by any newer caller", async () => {- const oldCommands = createDeferred<[]>();- const watcher = {- getCommands: vi.fn().mockReturnValueOnce(oldCommands.promise).mockResolvedValueOnce([]),- getToolDefinition: vi.fn(async () => undefined),- };- const setBodyComponents = vi.fn();- const fakeThis = {- childAgentWatcher: watcher,- childAgentWatcherToken: 1,- childAgentWatcherMessages: [userMessage("old", 1)],- childAgentBodyBuildSeq: 0,- childAgentDetail: { setBodyComponents },- ui: {},- getCurrentCwd: () => process.cwd(),- settingsManager: { getShowImages: () => true },- getMarkdownThemeWithSettings: () => ({}),- hideThinkingBlock: false,- hiddenThinkingLabel: "",- toolOutputExpanded: false,- };- Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);- const rebuildChildAgentBody = (- InteractiveMode.prototype as unknown as {- rebuildChildAgentBody(this: typeof fakeThis, token: number): Promise<void>;- }- ).rebuildChildAgentBody;-- const staleBuild = rebuildChildAgentBody.call(fakeThis, 1);- fakeThis.childAgentWatcherMessages = [userMessage("new", 2)];- await rebuildChildAgentBody.call(fakeThis, 1);- oldCommands.resolve([]);- await staleBuild;-- expect(setBodyComponents).toHaveBeenCalledOnce();- const rendered = setBodyComponents.mock.calls[0]![0].flatMap((component: Component) => component.render(40)).join(- "\n",- );- expect(rendered).toContain("new");- expect(rendered).not.toContain("old");- });});describe("InteractiveMode connection extension UI", () => {@@ -2085,7 +1985,7 @@ describe("InteractiveMode model selection persistence", () => {settingsManager: { setDefaultModelAndProvider(provider: string, modelId: string): void };};footer: { invalidate(): void };- childAgentSummary: { invalidate(): void };+ subagentSummaryLine: { invalidate(): void };patchConnectionState(patch: Partial<AgentConnectionState>): void;updateEditorBorderColor(): void;showStatus(message: string): void;@@ -2310,7 +2210,7 @@ describe("InteractiveMode model selection persistence", () => {},};fakeThis.footer = { invalidate: vi.fn() };- fakeThis.childAgentSummary = { invalidate: vi.fn() };+ fakeThis.subagentSummaryLine = { invalidate: vi.fn() };fakeThis.patchConnectionState = vi.fn();fakeThis.updateEditorBorderColor = vi.fn();fakeThis.setupAutocompleteProvider = vi.fn();@@ -2344,7 +2244,7 @@ describe("InteractiveMode model selection persistence", () => {},};fakeThis.footer = { invalidate: vi.fn() };- fakeThis.childAgentSummary = { invalidate: vi.fn() };+ fakeThis.subagentSummaryLine = { invalidate: vi.fn() };fakeThis.patchConnectionState = vi.fn();fakeThis.updateEditorBorderColor = vi.fn();@@ -2371,7 +2271,7 @@ describe("InteractiveMode model selection persistence", () => {},};fakeThis.footer = { invalidate: vi.fn() };- fakeThis.childAgentSummary = { invalidate: vi.fn() };+ fakeThis.subagentSummaryLine = { invalidate: vi.fn() };fakeThis.patchConnectionState = vi.fn();fakeThis.updateEditorBorderColor = vi.fn();fakeThis.showStatus = vi.fn();@@ -4291,16 +4191,14 @@ describe("truncatePathMiddle", () => {});describe("InteractiveMode.setToolsExpanded", () => {- test("applies expansion state to the active header, chat entries, and child agent detail", () => {+ test("applies expansion state to the active header and chat entries", () => {const header = { setExpanded: vi.fn() };const chatChild = { setExpanded: vi.fn() };- const childAgentDetail = { setToolsExpanded: vi.fn() };const fakeThis: any = {toolOutputExpanded: false,customHeader: undefined,builtInHeader: header,chatContainer: { children: [chatChild] },- childAgentDetail,ui: {requestRender: vi.fn(),requestRenderPreservingViewport: vi.fn(),@@ -4313,7 +4211,6 @@ describe("InteractiveMode.setToolsExpanded", () => {expect(fakeThis.toolOutputExpanded).toBe(true);expect(header.setExpanded).toHaveBeenCalledWith(true);expect(chatChild.setExpanded).toHaveBeenCalledWith(true);- expect(childAgentDetail.setToolsExpanded).toHaveBeenCalledWith(true);// Expansion keeps the user anchored, so it uses the viewport-preserving path.expect(fakeThis.ui.requestRenderPreservingViewport).toHaveBeenCalledTimes(1);});diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.tsindex a80be2eafb..1419aef040 100644--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts@@ -35,7 +35,6 @@ type HandleEventThis = {chatContainer: Container;recapContainer: Container;sessionRecap: string | undefined;- childAgentPanelMode: undefined;hideThinkingBlock: boolean;hiddenThinkingLabel: string;streamingComponent: AssistantMessageComponent | undefined;@@ -85,7 +84,6 @@ function createFakeInteractiveModeThis(): HandleEventThis {chatContainer: new Container(),recapContainer: new Container(),sessionRecap: "Updated files",- childAgentPanelMode: undefined,hideThinkingBlock: false,hiddenThinkingLabel: "Thinking...",streamingComponent: undefined,diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.tsindex f181d84578..2fb63ea4c4 100644--- a/packages/coding-agent/test/marquee-components.test.ts+++ b/packages/coding-agent/test/marquee-components.test.ts@@ -1,16 +1,10 @@-import type { AssistantMessage, Usage, UserMessage } from "@earendil-works/pi-ai";+import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";import { type Component, setKeybindings, TUI, visibleWidth } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { beforeAll, describe, expect, test } from "vitest";import { VirtualTerminal } from "../../tui/test/virtual-terminal.js";import { KeybindingsManager } from "../src/core/keybindings.js";import { AssistantMessageComponent } from "../src/modes/interactive/components/assistant-message.js";-import {- ChildAgentDetailComponent,- type ChildAgentInspectorNode,- ChildAgentSummaryComponent,-} from "../src/modes/interactive/components/child-agent-inspector.js";-import { buildConversationComponents } from "../src/modes/interactive/components/conversation-components.js";import { IPythonCellComponent, type IPythonCellState } from "../src/modes/interactive/components/ipython-cell.js";import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";import { initTheme } from "../src/modes/interactive/theme/theme.js";@@ -48,14 +42,6 @@ const EMPTY_USAGE: Usage = {},};-function createUserMessage(text: string): UserMessage {- return {- role: "user",- content: [{ type: "text", text }],- timestamp: Date.now(),- };-}-function createAssistantMessage(text: string, thinking?: string): AssistantMessage {return {role: "assistant",@@ -69,16 +55,6 @@ function createAssistantMessage(text: string, thinking?: string): AssistantMessa};}-function bodyOptions(toolsExpanded = false) {- return {- ui: { requestRender() {} } as unknown as TUI,- cwd: "/tmp",- toolOptions: {},- getToolDefinition: () => undefined,- toolsExpanded,- };-}-async function renderInVirtualTerminal(component: Component, width = 100, height = 30): Promise<string> {const terminal = new VirtualTerminal(width, height);const tui = new TUI(terminal);@@ -428,177 +404,6 @@ describe("marquee TUI components", () => {expect(short).not.toContain("Ctrl+O to expand");});- test("renders child agent summary inline list and detail view", () => {- const summary = new ChildAgentSummaryComponent(- () => "agents-sidebar",- () => "37% context left",- );- const node: ChildAgentInspectorNode = {- id: "sub-a",- label: "inspect training logs",- model: "openai/gpt-5.4",- status: "running",- sessionDir: "/tmp/session/sub-a",- children: [- {- id: "sub-b",- label: "check shard 2",- model: "anthropic/claude-sonnet-4-5",- status: "done",- sessionDir: "/tmp/session/sub-b",- },- ],- };- summary.setNodes([node]);-- // The info line carries location/context; the list renders the subagents- // below a separator, with the time pinned at the right edge.- const summaryLines = summary.render(90).map(stripAnsi);- const summaryText = summaryLines.join("\n");- expect(summaryText).toContain("agents-sidebar");- expect(summaryText).toContain("37% context left");- expect(summaryText).toContain("S1");- expect(summaryText).toContain("inspect train…");- expect(summaryText).toContain("GPT-5.4");- expect(summaryText).not.toContain("openai/gpt-5.4");- const infoRow = summary.render(90)[0] ?? "";- expect(visibleWidth(infoRow)).toBe(90);-- summary.focused = true;- let openedNodeId: string | undefined;- summary.onOpenDetail = (nodeId) => {- openedNodeId = nodeId;- };- // Right opens the selected subagent, like Enter.- summary.handleInput("\x1b[C");- expect(openedNodeId).toBe("sub-a");-- const detailComponent = new ChildAgentDetailComponent(() => 20);- detailComponent.setNode(node);- detailComponent.setBodyComponents(- buildConversationComponents(- [- createUserMessage("inspect training logs"),- createAssistantMessage("reading shard metrics", "checking loss curve"),- ],- bodyOptions(),- ),- );- const detailLines = detailComponent.render(42);- const detail = stripAnsi(detailLines.join("\n"));- expect(detail).toContain("inspect training logs");- expect(detail).toContain("reading shard metrics");- expect(detail).toContain("← back to chat");- expect(stripAnsi(detailComponent.render(80).at(-1) ?? "")).toContain("GPT-5.4");- expect(stripAnsi(detailComponent.render(80).at(-1) ?? "")).not.toContain("openai/gpt-5.4");- expect(detail).not.toContain("user: inspect training logs");- expect(detail).not.toContain("assistant: reading shard metrics");- });-- test("renders child agent assistant errors in the detail view", () => {- const detailComponent = new ChildAgentDetailComponent(() => 20);- detailComponent.setToolsExpanded(true);- const assistantError: AssistantMessage = {- ...createAssistantMessage(""),- content: [],- stopReason: "error",- errorMessage: [- "Provider request failed",- "Traceback (most recent call last):",- ' File "/tmp/internal.py", line 12, in run',- "RuntimeError: backend crashed",- ].join("\n"),- };- detailComponent.setNode({- id: "sub-assistant-error",- label: "inspect failure",- status: "error",- sessionDir: "/tmp/session/sub-assistant-error",- });- detailComponent.setBodyComponents(buildConversationComponents([assistantError], bodyOptions(true)));-- const expanded = stripAnsi(detailComponent.render(100).join("\n"));- expect(expanded).toContain("/tmp/internal.py");- });-- test("routes child agent detail tool expansion through app keybindings", () => {- setKeybindings(new KeybindingsManager({ "app.tools.expand": "ctrl+x" }));- try {- const detailComponent = new ChildAgentDetailComponent(() => 20);- let toggleCount = 0;- detailComponent.onToggleToolsExpanded = () => {- toggleCount += 1;- };- detailComponent.setNode({- id: "sub-a",- label: "inspect training logs",- status: "running",- sessionDir: "/tmp/session/sub-a",- });-- const before = stripAnsi(detailComponent.render(80).join("\n"));- expect(before).toContain("Ctrl+X to expand");- detailComponent.handleInput("\x18");-- expect(toggleCount).toBe(1);- detailComponent.setToolsExpanded(true);- const after = stripAnsi(detailComponent.render(80).join("\n"));- expect(after).toContain("Ctrl+X to collapse");- } finally {- setKeybindings(new KeybindingsManager());- }- });-- test("keeps child agent summary visible when the right tray label is long", () => {- const summary = new ChildAgentSummaryComponent(- () => undefined,- () => "Pursuing goal (1m 05s) · 25% context left",- );- summary.setNodes([- {- id: "sub-a",- label: "inspect training logs",- status: "running",- sessionDir: "/tmp/session/sub-a",- },- ]);-- const lines = summary.render(32);- const infoRow = lines[0] ?? "";-- expect(visibleWidth(infoRow)).toBe(32);- expect(stripAnsi(infoRow)).toContain("Pursuing goal");- // The subagent itself renders as a list row below the info line.- expect(stripAnsi(lines.join("\n"))).toContain("S1");- });-- test("renders full child agent detail without internal scroll controls", () => {- const detailComponent = new ChildAgentDetailComponent(() => 6);- detailComponent.setNode({- id: "sub-scroll",- label: "inspect long output",- status: "done",- sessionDir: "/tmp/session/sub-scroll",- });- detailComponent.setBodyComponents(- buildConversationComponents(- Array.from({ length: 12 }, (_, index) =>- createAssistantMessage(`conversation row ${String(index + 1).padStart(2, "0")}`),- ),- bodyOptions(),- ),- );-- const firstLines = detailComponent.render(48);- const first = stripAnsi(firstLines.join("\n"));- expect(first).toContain("conversation row 01");- expect(first).toContain("conversation row 12");- expect(first).toContain("← back to chat");- expect(first).not.toContain("↑");- expect(first).not.toContain("↓");- expect(firstLines.length).toBeGreaterThan(6);- });-test("routes built-in ipython tool rows through the cell renderer", () => {const component = new ToolExecutionComponent("ipython",diff --git a/packages/coding-agent/test/subagent-summary-line.test.ts b/packages/coding-agent/test/subagent-summary-line.test.tsnew file mode 100644index 0000000000..504879a3f4--- /dev/null+++ b/packages/coding-agent/test/subagent-summary-line.test.ts@@ -0,0 +1,162 @@+import { setKeybindings } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { KeybindingsManager } from "../src/core/keybindings.js";+import type { AgentConnectionRlmChildAgentSnapshot } from "../src/modes/agent-connection/types.js";+import {+ countDirectSubagentStatuses,+ SubagentSummaryLine,+} from "../src/modes/interactive/components/subagent-summary-line.js";+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++function child(+ id: string,+ status: AgentConnectionRlmChildAgentSnapshot["status"],+ overrides: Partial<AgentConnectionRlmChildAgentSnapshot> = {},+): AgentConnectionRlmChildAgentSnapshot {+ return { id, label: id, status, sessionDir: `/tmp/${id}`, ...overrides };+}++describe("SubagentSummaryLine", () => {+ beforeAll(() => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());+ });++ it("renders no subagent line without children and uses singular and plural labels", () => {+ const line = new SubagentSummaryLine();+ expect(line.render(120)).toEqual([]);++ line.setSubagentCounts({ total: 1, running: 1, idle: 0, inactive: 0 });+ let rendered = line.render(120).map(stripAnsi);+ expect(rendered).toHaveLength(1);+ expect(rendered[0]).toContain("1 subagent: 1 running · 0 idle · 0 inactive");++ line.setSubagentCounts({ total: 2, running: 1, idle: 1, inactive: 0 });+ rendered = line.render(120).map(stripAnsi);+ expect(rendered[0]).toContain("2 subagents: 1 running · 1 idle · 0 inactive");+ });++ it("counts only direct children using running, idle, and inactive status projections", () => {+ const children = [+ child("running", "running"),+ child("queued", "queued"),+ child("active", "done", { activity: { kind: "writing" } }),+ child("heartbeat", "done", { activeSessionId: "heartbeat-session" }),+ child("idle-done", "done", { activeSessionId: "idle-done-session" }),+ child("idle-error", "error", { activeSessionId: "idle-error-session" }),+ child("inactive-done", "done"),+ child("inactive-error", "error"),+ child("cancelled", "cancelled"),+ child("grandchild", "running", { parentId: "running" }),+ ];++ expect(countDirectSubagentStatuses(children, undefined, new Set(["heartbeat-session"]))).toEqual({+ total: 8,+ running: 4,+ idle: 2,+ inactive: 2,+ });+ });++ it("opens on Enter or Right only when the daemon-backed line is selectable", () => {+ const line = new SubagentSummaryLine();+ const onOpen = vi.fn();+ line.onOpen = onOpen;+ line.setSubagentCounts({ total: 2, running: 0, idle: 2, inactive: 0 });+ line.setOpenable(true);++ line.handleInput("\r");+ line.handleInput("\x1b[C");++ expect(onOpen).toHaveBeenCalledTimes(2);+ });++ it("stays visible but non-selectable for an in-process connection", () => {+ const line = new SubagentSummaryLine();+ const onOpen = vi.fn();+ line.onOpen = onOpen;+ line.setSubagentCounts({ total: 1, running: 0, idle: 0, inactive: 1 });+ line.setOpenable(false);++ expect(stripAnsi(line.render(100).join("\n"))).toContain("1 subagent: 0 running · 0 idle · 1 inactive");+ expect(line.isSelectable()).toBe(false);+ line.handleInput("\r");+ expect(onOpen).not.toHaveBeenCalled();+ });++ it("updates the rendered counts from consecutive child-status events", () => {+ const line = new SubagentSummaryLine();+ line.setOpenable(true);+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;+ Object.assign(mode, {+ subagentSnapshots: new Map<string, AgentConnectionRlmChildAgentSnapshot>(),+ rlmNodeId: undefined,+ heartbeatCatalog: [],+ subagentSummaryLine: line,+ updateScopedHeartbeats: vi.fn(),+ updateWorkingPulse: vi.fn(),+ syncWorkingLoader: vi.fn(),+ updateWorkingLoaderMessage: vi.fn(),+ ui: { requestRender: vi.fn() },+ });+ const update = Reflect.get(InteractiveMode.prototype, "updateSubagentSummary") as (+ this: typeof mode,+ value: AgentConnectionRlmChildAgentSnapshot,+ ) => void;++ update.call(mode, child("worker", "running"));+ expect(stripAnsi(line.render(100).join("\n"))).toContain("1 running · 0 idle · 0 inactive");++ update.call(mode, child("worker", "done", { activeSessionId: "active-worker" }));+ expect(stripAnsi(line.render(100).join("\n"))).toContain("0 running · 1 idle · 0 inactive");+ });++ it("clears a resident session id when a terminal update reports an evicted child", () => {+ const line = new SubagentSummaryLine();+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;+ Object.assign(mode, {+ subagentSnapshots: new Map<string, AgentConnectionRlmChildAgentSnapshot>(),+ rlmNodeId: undefined,+ heartbeatCatalog: [],+ subagentSummaryLine: line,+ updateScopedHeartbeats: vi.fn(),+ updateWorkingPulse: vi.fn(),+ syncWorkingLoader: vi.fn(),+ updateWorkingLoaderMessage: vi.fn(),+ ui: { requestRender: vi.fn() },+ });+ const update = Reflect.get(InteractiveMode.prototype, "updateSubagentSummary") as (+ this: typeof mode,+ value: AgentConnectionRlmChildAgentSnapshot,+ ) => void;++ update.call(mode, child("worker", "running", { activeSessionId: "resident-worker" }));+ // Active partial updates retain the last known resident id.+ update.call(mode, child("worker", "running"));+ update.call(mode, child("worker", "done"));++ expect(stripAnsi(line.render(100).join("\n"))).toContain("0 running · 0 idle · 1 inactive");+ });++ it("turns a selection into the scoped agents-view run result", async () => {+ const returnToAgentsView = vi.fn(async () => undefined);+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;+ Object.assign(mode, {+ editor: { getText: () => "" },+ options: { returnToAgentsView: true },+ returnToAgentsView,+ });+ const open = Reflect.get(InteractiveMode.prototype, "openScopedAgentsView") as (+ this: typeof mode,+ ) => Promise<void>;+ const line = new SubagentSummaryLine();+ line.setSubagentCounts({ total: 1, running: 1, idle: 0, inactive: 0 });+ line.setOpenable(true);+ line.onOpen = () => void open.call(mode);++ line.handleInput("\r");+ await vi.waitFor(() => expect(returnToAgentsView).toHaveBeenCalledWith("scoped_agents_view"));+ });+});diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.tsindex ea7be4c5dc..1679c2addf 100644--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts@@ -871,7 +871,7 @@ describe("ENG-4509 side questions", () => {isAgentCompacting: () => false,isBashRunning: () => true,applyConnectionStateSnapshot: vi.fn(),- replaceChildAgentInspector: vi.fn(),+ replaceSubagentSummary: vi.fn(),getSessionContextFromConnectionSnapshot: vi.fn(() => ({messages: [],thinkingLevel: "medium",diff --git a/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts b/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.tsindex 65f554aac8..49253a889f 100644--- a/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts+++ b/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts@@ -6,7 +6,6 @@ import { initTheme } from "../../../src/modes/interactive/theme/theme.js";type RecapRenderMode = {recapContainer: Container;- childAgentPanelMode?: "detail";sessionRecap?: string;agentRunFileChanges: Map<string, never>;isAgentStreaming: () => boolean;@@ -126,11 +125,4 @@ describe("ENG-4533 recap layout", () => {expect(visibleWidth(lines[0] ?? "")).toBe(24);expect(stripAnsi(lines[0] ?? "")).toContain("Recap:");});-- it("suppresses the parent recap area in child-agent detail", () => {- const mode = createRenderMode("Reviewing the parent session");- mode.childAgentPanelMode = "detail";-- expect(render(mode)).toEqual([]);- });});diff --git a/packages/coding-agent/test/suite/regressions/4741-hint-placement.test.ts b/packages/coding-agent/test/suite/regressions/4741-hint-placement.test.tsindex 6401264d13..ccbe74f109 100644--- a/packages/coding-agent/test/suite/regressions/4741-hint-placement.test.ts+++ b/packages/coding-agent/test/suite/regressions/4741-hint-placement.test.ts@@ -39,7 +39,6 @@ function createFeatureHintMode() {featureHintComponent: undefined,featureHintRunPending: false,featureHintSuppressedByQueue: false,- childAgentPanelMode: undefined,options: { returnToAgentsView: true },getAppKeyDisplay: () => "Ctrl+Q",ui: { requestRender: vi.fn() },@@ -67,7 +66,7 @@ describe("ENG-4741 hint placement", () => {const queuedMessagesContainer = new Container();const sideQuestionContainer = new Container();const editorContainer = new Container();- const childAgentSummary = new Container();+ const subagentSummaryLine = new Container();const footerSlot = new Container();const mode = Object.assign(Object.create(InteractiveMode.prototype), {recapContainer,@@ -75,7 +74,7 @@ describe("ENG-4741 hint placement", () => {queuedMessagesContainer,sideQuestionContainer,editorContainer,- childAgentSummary,+ subagentSummaryLine,footerSlot,});@@ -85,7 +84,7 @@ describe("ENG-4741 hint placement", () => {queuedMessagesContainer,sideQuestionContainer,]);- expect(callPrivate(mode, "getPromptDockComponents")).toEqual([editorContainer, childAgentSummary, footerSlot]);+ expect(callPrivate(mode, "getPromptDockComponents")).toEqual([editorContainer, subagentSummaryLine, footerSlot]);});it("keeps hints in the fullscreen transcript instead of the prompt dock", () => {