Skip to content

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

Rust

make subagents first-class sessions instead of a parent projection (#282)

kt3b4685563ea1
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index 7c9c033804..9822e4f28b 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -11,7 +11,12 @@ import { flushAgentTraceUpload } from "./agent-traces.js";
import { isNoModelsAvailableMessage } from "./auth-guidance.js";
import type { ReplacedSessionContext, SessionShutdownEvent, SessionStartEvent } from "./extensions/index.js";
import { emitSessionShutdownEvent } from "./extensions/runner.js";
-import type { CreateRlmSubagentRuntimeOptions, RlmSubagentRuntime, SubagentRuntimeHost } from "./rlm-runtime.js";
+import type {
+ CreateRlmSubagentRuntimeOptions,
+ RlmSubagentReleaseStatus,
+ RlmSubagentRuntime,
+ SubagentRuntimeHost,
+} from "./rlm-runtime.js";
import type { CreateAgentSessionResult } from "./sdk.js";
import { assertSessionCwdExists } from "./session-cwd.js";
import { SessionImportFileNotFoundError } from "./session-import-errors.js";
@@ -300,11 +305,23 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
async releaseRlmSubagentRuntime(
runtime: RlmSubagentRuntime,
options: CreateRlmSubagentRuntimeOptions,
+ status: RlmSubagentReleaseStatus,
): Promise<void> {
const tracked = this.subagentRuntimes.get(options.id);
if (tracked === runtime) {
this.subagentRuntimes.delete(options.id);
}
+ // Keep a successful run's session readable via the parent's inspector (disposed
+ // with the parent); errored/cancelled runs have nothing to show, so dispose now.
+ if (status === "done") {
+ // Flush traces now since the runtime's own shutdown path is skipped while retained.
+ await flushAgentTraceUpload(runtime.session.sessionManager).catch(() => undefined);
+ // Retention can decline if the parent is already tearing down; if so, fall
+ // through and dispose the runtime instead of leaving it dangling.
+ if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
+ return;
+ }
+ }
if (runtime instanceof AgentSessionRuntime) {
await runtime.dispose();
} else {
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 729a57d8ea..0bcdc7c2a5 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -28,15 +28,7 @@ import {
type ShouldStopAfterTurnContext,
type ThinkingLevel,
} from "@earendil-works/pi-agent-core";
-import type {
- AssistantMessage,
- ImageContent,
- Message,
- Model,
- TextContent,
- Usage,
- UserMessage,
-} from "@earendil-works/pi-ai";
+import type { AssistantMessage, ImageContent, Message, Model, TextContent, Usage } from "@earendil-works/pi-ai";
import {
clampThinkingLevel,
cleanupSessionResources,
@@ -49,6 +41,7 @@ import { theme } from "../modes/interactive/theme/theme.js";
import { stripFrontmatter } from "../utils/frontmatter.js";
import { sleep } from "../utils/sleep.js";
import { ensureTool, MISSING_RIPGREP_MESSAGE } from "../utils/tools-manager.js";
+import { flushAgentTraceUpload } from "./agent-traces.js";
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
import { type BashResult, executeBashWithOperations } from "./bash-executor.js";
import {
@@ -139,6 +132,7 @@ import {
createRlmRunHostHandler,
type RlmInternalRunResult,
type RlmRunResult,
+ type RlmSubagentReleaseStatus,
type RlmSubagentRuntime,
type RlmUsage,
type SubagentRuntimeHost,
@@ -160,7 +154,7 @@ import { type BashOperations, createLocalBashOperations } from "./tools/bash.js"
import { createAllToolDefinitions } from "./tools/index.js";
import { IpythonKernelProvisioner } from "./tools/ipython.js";
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
-import { addAssistantUsage, cloneUsage, emptyUsage } from "./usage.js";
+import { addAssistantUsage, emptyUsage } from "./usage.js";
import { SERPER_CREDENTIAL_ID, SERPER_ENV_VAR, WEBSEARCH_SKILL_NAME } from "./websearch-credential.js";
export type { GoalState, GoalStatus } from "./goals.js";
@@ -169,51 +163,15 @@ export { type ParsedSkillBlock, parseSkillBlock } from "./skill-blocks.js";
export type RlmChildAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";
-export interface RlmChildAgentTranscriptLine {
- role: "user" | "assistant" | "tool" | "system";
- text: string;
-}
-
-export interface RlmChildAgentToolResult {
- content: (TextContent | ImageContent)[];
- details?: unknown;
- isError: boolean;
-}
-
-export interface RlmChildAgentMessageTranscriptEntry {
- type: "message";
- role: "user" | "assistant";
- text: string;
- message: UserMessage | AssistantMessage;
-}
-
-export interface RlmChildAgentToolTranscriptEntry {
- type: "tool";
- role: "tool";
- text: string;
- toolCallId: string;
- toolName: string;
- args: unknown;
- result?: RlmChildAgentToolResult;
- isPartial: boolean;
- executionStarted: boolean;
- argsComplete: boolean;
-}
-
-export interface RlmChildAgentSystemTranscriptEntry {
- type: "system";
- role: "system";
- text: string;
+export interface RlmChildAgentActivity {
+ kind: "waiting" | "writing" | "executing";
+ toolName?: string;
}
-export type RlmChildAgentStructuredTranscriptEntry =
- | RlmChildAgentMessageTranscriptEntry
- | RlmChildAgentToolTranscriptEntry
- | RlmChildAgentSystemTranscriptEntry;
-
export interface RlmChildAgentSnapshot {
id: string;
parentId?: string;
+ activeSessionId?: string;
label: string;
status: RlmChildAgentStatus;
durationMs?: number;
@@ -225,8 +183,9 @@ export interface RlmChildAgentSnapshot {
/** Latest recap of what the subagent is doing, from the summarizer. */
recap?: string;
sessionDir: string;
- transcript: readonly RlmChildAgentTranscriptLine[];
- structuredTranscript?: readonly RlmChildAgentStructuredTranscriptEntry[];
+ activity?: RlmChildAgentActivity;
+ /** Failure reason when status is "error". */
+ error?: string;
}
/** Session-specific events that extend the core AgentEvent */
@@ -478,16 +437,6 @@ export function rlmChildLabel(prompt: string): string {
return prompt.replace(/\s+/g, " ").trim() || "child agent";
}
-function readTextBlocks(content: string | Array<{ type: string; text?: string }>): string {
- if (typeof content === "string") {
- return content;
- }
- return content
- .filter((block) => block.type === "text" && typeof block.text === "string")
- .map((block) => block.text ?? "")
- .join("\n");
-}
-
function readAssistantText(message: AssistantMessage): string {
return message.content
.filter((block) => block.type === "text")
@@ -495,165 +444,6 @@ function readAssistantText(message: AssistantMessage): string {
.join("");
}
-function readAssistantThinking(message: AssistantMessage): string {
- return message.content
- .filter((block) => block.type === "thinking")
- .map((block) => block.thinking)
- .join("");
-}
-
-function cloneTextImageContentBlock(block: TextContent | ImageContent): TextContent | ImageContent {
- if (block.type === "text") {
- return {
- type: "text",
- text: block.text,
- ...(block.textSignature !== undefined ? { textSignature: block.textSignature } : {}),
- };
- }
- return {
- type: "image",
- data: block.data,
- mimeType: block.mimeType,
- };
-}
-
-function cloneUserMessage(message: UserMessage): UserMessage {
- return {
- role: "user",
- content:
- typeof message.content === "string"
- ? message.content
- : message.content.map((block) => cloneTextImageContentBlock(block)),
- timestamp: message.timestamp,
- };
-}
-
-function cloneAssistantContentBlock(block: AssistantMessage["content"][number]): AssistantMessage["content"][number] {
- switch (block.type) {
- case "text":
- return {
- type: "text",
- text: block.text,
- ...(block.textSignature !== undefined ? { textSignature: block.textSignature } : {}),
- };
- case "thinking":
- return {
- type: "thinking",
- thinking: block.thinking,
- ...(block.thinkingSignature !== undefined ? { thinkingSignature: block.thinkingSignature } : {}),
- ...(block.redacted !== undefined ? { redacted: block.redacted } : {}),
- };
- case "toolCall":
- return {
- type: "toolCall",
- id: block.id,
- name: block.name,
- arguments: { ...block.arguments },
- ...(block.thoughtSignature !== undefined ? { thoughtSignature: block.thoughtSignature } : {}),
- };
- }
-}
-
-function cloneAssistantMessage(message: AssistantMessage): AssistantMessage {
- return {
- role: "assistant",
- content: message.content.map((block) => cloneAssistantContentBlock(block)),
- api: message.api,
- provider: message.provider,
- model: message.model,
- ...(message.responseModel !== undefined ? { responseModel: message.responseModel } : {}),
- ...(message.responseId !== undefined ? { responseId: message.responseId } : {}),
- ...(message.diagnostics !== undefined
- ? { diagnostics: message.diagnostics.map((diagnostic) => ({ ...diagnostic })) }
- : {}),
- usage: cloneUsage(message.usage),
- stopReason: message.stopReason,
- ...(message.errorMessage !== undefined ? { errorMessage: message.errorMessage } : {}),
- timestamp: message.timestamp,
- };
-}
-
-function createAssistantTextMessage(text: string, model: Model<any>, timestamp = Date.now()): AssistantMessage {
- return {
- role: "assistant",
- content: [{ type: "text", text }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: emptyUsage(),
- stopReason: "stop",
- timestamp,
- };
-}
-
-function cloneUnknownTextImageContentBlock(block: unknown): TextContent | ImageContent | undefined {
- if (!block || typeof block !== "object" || !("type" in block)) {
- return undefined;
- }
- const typedBlock = block as { type?: unknown; text?: unknown; data?: unknown; mimeType?: unknown };
- if (typedBlock.type === "text" && typeof typedBlock.text === "string") {
- return { type: "text", text: typedBlock.text };
- }
- if (typedBlock.type === "image" && typeof typedBlock.data === "string" && typeof typedBlock.mimeType === "string") {
- return { type: "image", data: typedBlock.data, mimeType: typedBlock.mimeType };
- }
- return undefined;
-}
-
-function cloneRlmToolResult(result: unknown, isError: boolean): RlmChildAgentToolResult | undefined {
- if (!result || typeof result !== "object" || !("content" in result)) {
- return undefined;
- }
- const resultRecord = result as { content?: unknown; details?: unknown };
- if (!Array.isArray(resultRecord.content)) {
- return undefined;
- }
- const content: (TextContent | ImageContent)[] = [];
- for (const block of resultRecord.content) {
- const cloned = cloneUnknownTextImageContentBlock(block);
- if (cloned) {
- content.push(cloned);
- }
- }
- return {
- content,
- ...(resultRecord.details !== undefined ? { details: resultRecord.details } : {}),
- isError,
- };
-}
-
-function readToolResultText(result: unknown): string | undefined {
- if (!result || typeof result !== "object" || !("content" in result)) {
- return undefined;
- }
- const content = (result as { content?: unknown }).content;
- if (!Array.isArray(content)) {
- return undefined;
- }
- const text = content
- .filter(
- (block): block is { type: string; text: string } =>
- !!block &&
- typeof block === "object" &&
- "type" in block &&
- "text" in block &&
- block.type === "text" &&
- typeof block.text === "string",
- )
- .map((block) => block.text)
- .join("\n");
- return text.trim() ? text : undefined;
-}
-
-function formatRlmToolArgs(args: unknown): string | undefined {
- try {
- const text = JSON.stringify(args);
- return text && text !== "{}" ? compactRlmText(text, 96) : undefined;
- } catch {
- return undefined;
- }
-}
-
function attributeChildUsage(parentUsage: Usage, childUsage: Usage): void {
const parentContextTokens =
parentUsage.totalTokens ||
@@ -737,6 +527,10 @@ export class AgentSession {
private _extensionErrorListener?: ExtensionErrorListener;
private _extensionErrorUnsubscriber?: () => void;
private _disposed = false;
+ // Set at the start of async teardown so a child finishing mid-disposeAsync doesn't
+ // re-populate the retained map after it's been cleared.
+ private _disposing = false;
+ private _disposeAsyncPromise?: Promise<void>;
private _ipythonKernelProvisioner?: IpythonKernelProvisioner;
/** Artifact dir backing the current provisioner's kernel snapshot, if any. */
private _ipythonKernelSnapshotDir?: string;
@@ -749,6 +543,12 @@ export class AgentSession {
private _rlmParentNodeId?: string;
private _subagentRuntimeHost?: SubagentRuntimeHost;
private _activeRlmChildRuns = new Map<string, RlmChildRun>();
+ // Inline mode keeps finished child sessions so the inspector can still read them;
+ // the daemon does the same by leaving the child session resident in its registry.
+ private _retainedRlmChildSessions = new Map<string, AgentSession>();
+ // Kept alive for retained children so nested updates (e.g. a grandchild cancel)
+ // still forward to root; torn down when the retained child is disposed.
+ private _retainedRlmChildUnsubscribes = new Map<string, () => void>();
/** Latest recap for this session, written by the daemon summarizer; read by a parent to label its child snapshots. */
private _currentRecap?: string;
@@ -1848,6 +1648,32 @@ export class AgentSession {
if (this._disposed) {
return;
}
+ // Concurrent callers await the same in-flight teardown so none resolves before
+ // the kernel snapshot flush finishes.
+ if (this._disposeAsyncPromise) {
+ return this._disposeAsyncPromise;
+ }
+ this._disposing = true;
+ this._disposeAsyncPromise = this._disposeAsyncOnce();
+ return this._disposeAsyncPromise;
+ }
+
+ private async _disposeAsyncOnce(): Promise<void> {
+ // Flush kernels/traces for both still-running and retained children; the sync
+ // dispose() below only tears them down synchronously.
+ for (const run of this._activeRlmChildRuns.values()) {
+ if (run.session) {
+ await run.session.disposeAsync().catch(() => undefined);
+ }
+ }
+ for (const unsubscribe of this._retainedRlmChildUnsubscribes.values()) {
+ unsubscribe();
+ }
+ this._retainedRlmChildUnsubscribes.clear();
+ for (const session of this._retainedRlmChildSessions.values()) {
+ await session.disposeAsync().catch(() => undefined);
+ }
+ this._retainedRlmChildSessions.clear();
try {
await this._ipythonKernelProvisioner?.dispose();
} catch {
@@ -1862,6 +1688,14 @@ export class AgentSession {
}
this._disposed = true;
this._cancelActiveRlmChildRuns("Parent session disposed");
+ for (const unsubscribe of this._retainedRlmChildUnsubscribes.values()) {
+ unsubscribe();
+ }
+ this._retainedRlmChildUnsubscribes.clear();
+ for (const session of this._retainedRlmChildSessions.values()) {
+ session.dispose();
+ }
+ this._retainedRlmChildSessions.clear();
this._pendingNextTurnMessages = [];
this._steeringMessages = [];
this._followUpMessages = [];
@@ -3994,13 +3828,24 @@ export class AgentSession {
private async _releaseRlmSubagentRuntime(
runtime: RlmSubagentRuntime,
options: CreateRlmSubagentRuntimeOptions,
+ status: RlmSubagentReleaseStatus,
): Promise<void> {
if (this._subagentRuntimeHost?.releaseRlmSubagentRuntime) {
- await this._subagentRuntimeHost.releaseRlmSubagentRuntime(runtime, options);
+ await this._subagentRuntimeHost.releaseRlmSubagentRuntime(runtime, options, status);
return;
}
- runtime.session.dispose();
+ // Inline: keep a successful run readable (disposed with the parent); errored or
+ // cancelled runs have nothing useful to show, so dispose them now. retainFinished…
+ // disposes the child itself when it declines, so only dispose here otherwise.
+ if (status === "done") {
+ await flushAgentTraceUpload(runtime.session.sessionManager).catch(() => undefined);
+ if (!options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
+ runtime.session.dispose();
+ }
+ } else {
+ runtime.session.dispose();
+ }
}
private _createInlineRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): RlmSubagentRuntime {
@@ -4081,6 +3926,62 @@ export class AgentSession {
return this._activeRlmChildRuns.get(childId)?.status;
}
+ /**
+ * Retain a finished child session so the inspector can still read it; disposed with
+ * the parent. Returns false (and disposes the child) when the parent is already
+ * tearing down, so the caller can drop the matching event forwarder too.
+ */
+ retainFinishedRlmChildSession(childId: string, session: AgentSession): boolean {
+ // A child can finish concurrently while the parent is (or has) torn down; don't
+ // resurrect the map (it would never be disposed), just drop the child now.
+ if (this._disposed || this._disposing) {
+ void session.disposeAsync().catch(() => undefined);
+ return false;
+ }
+ this._retainedRlmChildSessions.set(childId, session);
+ return true;
+ }
+
+ /** True when any direct or nested subagent is still running or queued. */
+ hasRunningRlmChildren(): boolean {
+ for (const run of this._activeRlmChildRuns.values()) {
+ if (run.status === "running" || run.status === "queued") {
+ return true;
+ }
+ if (run.session?.hasRunningRlmChildren()) {
+ return true;
+ }
+ }
+ // A finished direct child can still have a running nested subagent.
+ for (const session of this._retainedRlmChildSessions.values()) {
+ if (session.hasRunningRlmChildren()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Inline (non-daemon) mode only; daemon clients attach to the child session directly.
+ getRlmChildSession(childId: string): AgentSession | undefined {
+ const direct = this._activeRlmChildRuns.get(childId)?.session ?? this._retainedRlmChildSessions.get(childId);
+ if (direct) {
+ return direct;
+ }
+ for (const candidate of this._activeRlmChildRuns.values()) {
+ const nested = candidate.session?.getRlmChildSession(childId);
+ if (nested) {
+ return nested;
+ }
+ }
+ for (const retained of this._retainedRlmChildSessions.values()) {
+ const nested = retained.getRlmChildSession(childId);
+ if (nested) {
+ return nested;
+ }
+ }
+ return undefined;
+ }
+
/**
* Cancel a single RLM child run by id, searching nested child sessions.
*
@@ -4097,6 +3998,12 @@ export class AgentSession {
return true;
}
}
+ // A finished, retained child can still have a running nested subagent.
+ for (const retained of this._retainedRlmChildSessions.values()) {
+ if (retained.cancelRlmChildRun(childId, reason)) {
+ return true;
+ }
+ }
return false;
}
@@ -4119,12 +4026,15 @@ export class AgentSession {
const childNodeId = basename(childSessionDir);
const startedAt = Date.now();
const parentAssistantForUsage = this._findLastAssistantMessage();
- const transcript: RlmChildAgentTranscriptLine[] = [];
- const structuredTranscript: RlmChildAgentStructuredTranscriptEntry[] = [];
const label = rlmChildLabel(prompt);
let answerPreview: string | undefined;
let durationMs: number | undefined;
let toolUseCount = 0;
+ let runningToolCount = 0;
+ let activity: RlmChildAgentActivity | undefined;
+ // Held for emitChildUpdate so post-run events (a retained child's forwarder still
+ // fires) keep reading recap/tokens after run.session is cleared in the finally.
+ let childSession: AgentSession | undefined;
const run: RlmChildRun = {
id: childNodeId,
prompt,
@@ -4133,11 +4043,7 @@ export class AgentSession {
abort: noopRlmChildAbort,
};
this._activeRlmChildRuns.set(run.id, run);
- // Index of the assistant entry currently being streamed. Cleared whenever the
- // conversation moves on (new assistant message, tool call) so subsequent assistant
- // text appends a fresh entry in chronological order instead of overwriting in place.
- let currentAssistantIndex: number | undefined;
- let lastToolTranscriptIndex: number | undefined;
+ // Status-only relay; the conversation is read from the child's own session.
const emitChildUpdate = () => {
this._emit({
type: "rlm_child_update",
@@ -4149,89 +4055,15 @@ export class AgentSession {
durationMs,
answerPreview,
toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,
- tokenCount: run.session?._contextTokensForCurrentMessages(),
- recap: run.session?.getCurrentRecap(),
+ tokenCount: childSession?._contextTokensForCurrentMessages(),
+ recap: childSession?.getCurrentRecap(),
sessionDir: childSessionDir,
- transcript: [...transcript],
- structuredTranscript: [...structuredTranscript],
+ activity,
+ error: run.error,
},
});
};
run.emitUpdate = emitChildUpdate;
- const recordAssistantMessage = (message: AssistantMessage) => {
- const text = compactRlmText(readAssistantText(message));
- const thinking = compactRlmText(readAssistantThinking(message));
- const compact = text || thinking;
- if (!compact) {
- return;
- }
- if (text) {
- answerPreview = text;
- }
- const entry: RlmChildAgentMessageTranscriptEntry = {
- type: "message",
- role: "assistant",
- text: compact,
- message: cloneAssistantMessage(message),
- };
- if (currentAssistantIndex === undefined) {
- currentAssistantIndex = transcript.length;
- transcript.push({ role: "assistant", text: compact });
- structuredTranscript.push(entry);
- } else {
- transcript[currentAssistantIndex] = { role: "assistant", text: compact };
- structuredTranscript[currentAssistantIndex] = entry;
- }
- };
- const recordAssistantText = (text: string, sourceMessage?: AssistantMessage) => {
- const compact = compactRlmText(text);
- if (!compact) {
- return;
- }
- const sourceCompact = sourceMessage
- ? compactRlmText(readAssistantText(sourceMessage)) || compactRlmText(readAssistantThinking(sourceMessage))
- : undefined;
- const message =
- sourceMessage && sourceCompact === compact
- ? sourceMessage
- : createAssistantTextMessage(text, model, sourceMessage?.timestamp);
- recordAssistantMessage(message);
- };
- const recordUserMessage = (message: UserMessage) => {
- const text = compactRlmText(readTextBlocks(message.content));
- if (!text) {
- return;
- }
- transcript.push({ role: "user", text });
- structuredTranscript.push({
- type: "message",
- role: "user",
- text,
- message: cloneUserMessage(message),
- });
- };
- const createToolTranscriptEntry = (
- event: { toolCallId: string; toolName: string; args?: unknown },
- text: string,
- result: RlmChildAgentToolResult | undefined,
- isPartial: boolean,
- ): RlmChildAgentToolTranscriptEntry => {
- const entry: RlmChildAgentToolTranscriptEntry = {
- type: "tool",
- role: "tool",
- text,
- toolCallId: event.toolCallId,
- toolName: event.toolName,
- args: event.args,
- isPartial,
- executionStarted: true,
- argsComplete: true,
- };
- if (result) {
- entry.result = result;
- }
- return entry;
- };
emitChildUpdate();
const subagentOptions = this._createRlmSubagentRuntimeOptions({
@@ -4251,6 +4083,7 @@ export class AgentSession {
}
childRuntime = await this._createRlmSubagentRuntime(subagentOptions);
const child = childRuntime.session;
+ childSession = child;
run.session = child;
run.abort = () => {
void child.abort();
@@ -4260,92 +4093,37 @@ export class AgentSession {
this._emit(event);
return;
}
- if (event.type === "recap_update") {
- // The summarizer set the child's recap; refresh its snapshot so the parent UI shows it.
- emitChildUpdate();
- return;
- }
switch (event.type) {
- case "message_start": {
- if (event.message.role === "user") {
- recordUserMessage(event.message);
- currentAssistantIndex = undefined;
- } else if (event.message.role === "assistant") {
- // New assistant turn: append a fresh entry so prior text isn't overwritten.
- currentAssistantIndex = undefined;
- recordAssistantMessage(event.message as AssistantMessage);
- }
+ case "recap_update":
emitChildUpdate();
break;
- }
+ case "message_start":
case "message_update":
case "message_end": {
if (event.message.role === "assistant") {
- recordAssistantMessage(event.message as AssistantMessage);
+ const text = compactRlmText(readAssistantText(event.message as AssistantMessage));
+ if (text) {
+ answerPreview = text;
+ }
+ activity = { kind: "writing" };
emitChildUpdate();
}
break;
}
case "tool_execution_start": {
- const args = formatRlmToolArgs(event.args);
- const text = args ? `${event.toolName} running ${args}` : `${event.toolName} running`;
toolUseCount += 1;
- // Tool break: next assistant text starts a new entry after this tool row.
- currentAssistantIndex = undefined;
- lastToolTranscriptIndex = transcript.length;
- transcript.push({ role: "tool", text });
- structuredTranscript.push(createToolTranscriptEntry(event, text, undefined, true));
+ runningToolCount += 1;
+ activity = { kind: "executing", toolName: event.toolName };
emitChildUpdate();
break;
}
- case "tool_execution_update": {
- const text = readToolResultText(event.partialResult);
- if (lastToolTranscriptIndex !== undefined) {
- const previous = structuredTranscript[lastToolTranscriptIndex];
- const summary = text
- ? `${event.toolName} running: ${compactRlmText(text)}`
- : transcript[lastToolTranscriptIndex]?.text || `${event.toolName} running`;
- transcript[lastToolTranscriptIndex] = { role: "tool", text: summary };
- structuredTranscript[lastToolTranscriptIndex] = createToolTranscriptEntry(
- {
- toolCallId: event.toolCallId,
- toolName: event.toolName,
- args: previous?.type === "tool" ? previous.args : event.args,
- },
- summary,
- cloneRlmToolResult(event.partialResult, false),
- true,
- );
- emitChildUpdate();
- }
- break;
- }
case "tool_execution_end": {
- const text = readToolResultText(event.result);
- const summary = text ? `${event.toolName}: ${compactRlmText(text)}` : `${event.toolName} done`;
- const previous =
- lastToolTranscriptIndex === undefined
- ? undefined
- : structuredTranscript[lastToolTranscriptIndex];
- const entry = createToolTranscriptEntry(
- {
- toolCallId: event.toolCallId,
- toolName: event.toolName,
- args: previous?.type === "tool" ? previous.args : undefined,
- },
- summary,
- cloneRlmToolResult(event.result, event.isError),
- false,
- );
- if (lastToolTranscriptIndex === undefined) {
- lastToolTranscriptIndex = transcript.length;
- transcript.push({ role: "tool", text: summary });
- structuredTranscript.push(entry);
- } else {
- transcript[lastToolTranscriptIndex] = { role: "tool", text: summary };
- structuredTranscript[lastToolTranscriptIndex] = entry;
+ runningToolCount = Math.max(0, runningToolCount - 1);
+ // Stay "executing" while sibling tools from the same turn run.
+ if (runningToolCount === 0) {
+ activity = { kind: "waiting" };
+ emitChildUpdate();
}
- emitChildUpdate();
break;
}
}
@@ -4365,16 +4143,9 @@ export class AgentSession {
this._attributeRlmChildUsageToParent(assistantUsage, parentAssistantForUsage);
run.status = "done";
durationMs = Date.now() - startedAt;
- // Streaming events usually capture the final assistant text already. Only
- // record again when it's missing — otherwise a child whose last streamed
- // event was tool_execution_start would have currentAssistantIndex cleared,
- // causing the final answer to be appended as a duplicate row.
+ activity = undefined;
const compactAnswer = compactRlmText(answer);
- const lastAssistantText = [...transcript].reverse().find((line) => line.role === "assistant")?.text;
- if (compactAnswer && compactAnswer !== lastAssistantText) {
- const lastAssistant = child._findLastAssistantMessage();
- recordAssistantText(answer, lastAssistant);
- } else if (compactAnswer) {
+ if (compactAnswer) {
answerPreview = compactAnswer;
}
emitChildUpdate();
@@ -4392,14 +4163,23 @@ export class AgentSession {
}
durationMs = Date.now() - startedAt;
run.error = error instanceof Error ? error.message : String(error);
- transcript.push({ role: "system", text: run.error });
- structuredTranscript.push({ type: "system", role: "system", text: run.error });
+ activity = undefined;
emitChildUpdate();
throw error;
} finally {
- unsubscribeChild?.();
+ const releaseStatus: RlmSubagentReleaseStatus =
+ run.status === "cancelled" || run.status === "error" ? run.status : "done";
if (childRuntime) {
- await this._releaseRlmSubagentRuntime(childRuntime, subagentOptions);
+ await this._releaseRlmSubagentRuntime(childRuntime, subagentOptions, releaseStatus);
+ }
+ // Keep the forwarder only if the child was actually retained (retention can
+ // decline when the parent is disposing); otherwise drop it.
+ if (unsubscribeChild) {
+ if (this._retainedRlmChildSessions.has(run.id)) {
+ this._retainedRlmChildUnsubscribes.set(run.id, unsubscribeChild);
+ } else {
+ unsubscribeChild();
+ }
}
run.abort = noopRlmChildAbort;
run.session = undefined;
diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.ts
index 9cba6226b5..41555344f8 100644
--- a/packages/coding-agent/src/core/rlm-runtime.ts
+++ b/packages/coding-agent/src/core/rlm-runtime.ts
@@ -69,8 +69,15 @@ export interface CreateRlmSubagentRuntimeOptions {
spawnCode?: string;
}
+/** Terminal status of an RLM child run, passed to the host when releasing its runtime. */
+export type RlmSubagentReleaseStatus = "done" | "error" | "cancelled";
+
export interface SubagentRuntimeHost {
createRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): Promise<RlmSubagentRuntime>;
- releaseRlmSubagentRuntime?(runtime: RlmSubagentRuntime, options: CreateRlmSubagentRuntimeOptions): Promise<void>;
+ releaseRlmSubagentRuntime?(
+ runtime: RlmSubagentRuntime,
+ options: CreateRlmSubagentRuntimeOptions,
+ status: RlmSubagentReleaseStatus,
+ ): Promise<void>;
disposeRlmSubagentRuntimes?(): Promise<void>;
}
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 11e844c415..bdb8e2cc66 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -43,6 +43,7 @@ import type {
AgentConnectionSessionContext,
AgentConnectionSessionListProgress,
AgentConnectionSessionTreeNode,
+ AgentConnectionSessionWatcher,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionState,
@@ -655,6 +656,23 @@ export class DaemonAgentConnection implements AgentConnection {
});
}
+ async watchSession(activeSessionId: string): Promise<AgentConnectionSessionWatcher | undefined> {
+ // A second connection on the shared client; each one filters to its own session id.
+ // attach() rejects for an unknown/exited session — treat that as unreachable.
+ let connection: DaemonAgentConnection;
+ try {
+ connection = await DaemonAgentConnection.attach(this.client, activeSessionId, { closeClientOnDispose: false });
+ } catch {
+ return undefined;
+ }
+ return {
+ getMessages: () => connection.getMessages(),
+ subscribe: (listener) => connection.subscribe(listener),
+ getToolDefinition: (name) => connection.getToolDefinition(name),
+ close: () => connection.dispose(),
+ };
+ }
+
async dispose(): Promise<void> {
this.unsubscribeDaemonMessages();
this.unsubscribeDaemonClose();
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index d3f89996fa..72594cc946 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -39,6 +39,7 @@ import type {
AgentConnectionSessionContext,
AgentConnectionSessionListProgress,
AgentConnectionSessionTreeNode,
+ AgentConnectionSessionWatcher,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionState,
@@ -368,6 +369,32 @@ export class InProcessAgentConnection implements AgentConnection {
return deleteSessionFile(sessionPath);
}
+ async watchSession(childId: string): Promise<AgentConnectionSessionWatcher | undefined> {
+ const child = this.session.getRlmChildSession(childId);
+ if (!child) {
+ return undefined;
+ }
+ const unsubscribes = new Set<() => void>();
+ return {
+ getMessages: async () => child.messages,
+ subscribe: (listener) => {
+ const unsubscribe = child.subscribe((event) => void listener({ type: "session_event", event }));
+ unsubscribes.add(unsubscribe);
+ return () => {
+ unsubscribes.delete(unsubscribe);
+ unsubscribe();
+ };
+ },
+ getToolDefinition: async (name) => createAgentConnectionToolDefinition(child.getToolDefinition(name)),
+ close: async () => {
+ for (const unsubscribe of unsubscribes) {
+ unsubscribe();
+ }
+ unsubscribes.clear();
+ },
+ };
+ }
+
async dispose(): Promise<void> {
this.unsubscribeSessionEvents?.();
this.unsubscribeSessionEvents = undefined;
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index 6eac24da31..10b3f2cdfb 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -38,10 +38,9 @@ export type {
AgentConnectionResourceSkill,
AgentConnectionResourceSnapshot,
AgentConnectionResourceTheme,
+ AgentConnectionRlmChildAgentActivity,
AgentConnectionRlmChildAgentSnapshot,
AgentConnectionRlmChildAgentStatus,
- AgentConnectionRlmChildAgentStructuredTranscriptEntry,
- AgentConnectionRlmChildAgentTranscriptLine,
AgentConnectionSavedSessionInfo,
AgentConnectionSavedSessionScope,
AgentConnectionSavedSessionState,
@@ -56,6 +55,7 @@ export type {
AgentConnectionSessionMessageEntry,
AgentConnectionSessionStateEntry,
AgentConnectionSessionTreeNode,
+ AgentConnectionSessionWatcher,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionSourceInfo,
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 38f7892cbb..92620bf0b2 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -1,14 +1,5 @@
import type { AgentEvent, AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
-import type {
- Api,
- AssistantMessage,
- ImageContent,
- Model,
- TextContent,
- Transport,
- Usage,
- UserMessage,
-} from "@earendil-works/pi-ai";
+import type { Api, ImageContent, Model, TextContent, Transport, Usage } from "@earendil-works/pi-ai";
import type { CompactionResult } from "../../core/compaction/index.js";
import type { ContextTreeNode } from "../../core/context-tree.js";
import type { AgentCronJob, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";
@@ -425,51 +416,16 @@ export interface AgentConnectionExtensionUiRequest {
export type AgentConnectionRlmChildAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";
-export interface AgentConnectionRlmChildAgentTranscriptLine {
- role: "user" | "assistant" | "tool" | "system";
- text: string;
-}
-
-export interface AgentConnectionRlmChildAgentToolResult {
- content: (TextContent | ImageContent)[];
- details?: unknown;
- isError: boolean;
-}
-
-export interface AgentConnectionRlmChildAgentMessageTranscriptEntry {
- type: "message";
- role: "user" | "assistant";
- text: string;
- message: UserMessage | AssistantMessage;
-}
-
-export interface AgentConnectionRlmChildAgentToolTranscriptEntry {
- type: "tool";
- role: "tool";
- text: string;
- toolCallId: string;
- toolName: string;
- args: unknown;
- result?: AgentConnectionRlmChildAgentToolResult;
- isPartial: boolean;
- executionStarted: boolean;
- argsComplete: boolean;
-}
-
-export interface AgentConnectionRlmChildAgentSystemTranscriptEntry {
- type: "system";
- role: "system";
- text: string;
+export interface AgentConnectionRlmChildAgentActivity {
+ kind: "waiting" | "writing" | "executing";
+ toolName?: string;
}
-export type AgentConnectionRlmChildAgentStructuredTranscriptEntry =
- | AgentConnectionRlmChildAgentMessageTranscriptEntry
- | AgentConnectionRlmChildAgentToolTranscriptEntry
- | AgentConnectionRlmChildAgentSystemTranscriptEntry;
-
export interface AgentConnectionRlmChildAgentSnapshot {
id: string;
parentId?: string;
+ /** The child's own daemon active-session id, for attaching to it directly. */
+ activeSessionId?: string;
label: string;
status: AgentConnectionRlmChildAgentStatus;
durationMs?: number;
@@ -481,8 +437,9 @@ export interface AgentConnectionRlmChildAgentSnapshot {
/** Latest recap of what the subagent is doing. */
recap?: string;
sessionDir: string;
- transcript: readonly AgentConnectionRlmChildAgentTranscriptLine[];
- structuredTranscript?: readonly AgentConnectionRlmChildAgentStructuredTranscriptEntry[];
+ activity?: AgentConnectionRlmChildAgentActivity;
+ /** Failure reason when status is "error". */
+ error?: string;
}
export type AgentConnectionSessionEvent =
@@ -613,5 +570,15 @@ export interface AgentConnection {
renameSavedSession(sessionPath: string, name: string): Promise<void>;
deleteSavedSession(sessionPath: string): Promise<DeleteSessionFileResult>;
+ /** Read-only watcher on another live session (a subagent); undefined if the transport can't reach it. */
+ watchSession(activeSessionId: string): Promise<AgentConnectionSessionWatcher | undefined>;
+
dispose(): Promise<void>;
}
+
+export interface AgentConnectionSessionWatcher {
+ getMessages(): Promise<AgentMessage[]>;
+ subscribe(listener: AgentConnectionEventListener): () => void;
+ getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined>;
+ close(): Promise<void>;
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 2803c4f824..53f1a4d806 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -15,6 +15,7 @@ import {
type CreateAgentSessionRuntimeFactory,
createAgentSessionRuntime,
} from "../../core/agent-session-runtime.js";
+import { flushAgentTraceUpload } from "../../core/agent-traces.js";
import {
type AgentCronJob,
AgentCronJobStore,
@@ -694,10 +695,22 @@ export class AgentDaemon {
throw cascadeError;
}
},
- releaseRlmSubagentRuntime: async (runtime) => {
+ releaseRlmSubagentRuntime: async (runtime, options, status) => {
const state = this.findRuntimeState(runtime);
+ // A successful subagent stays resident so it's still viewable (torn down with the
+ // parent via closeChildSessions); errored/cancelled would re-seed as "done", so close them.
+ if (state && status === "done") {
+ // Run shutdown side effects without disposing the still-readable session.
+ this.cancelSubagentRlmHeartbeats(state);
+ await flushAgentTraceUpload(state.runtime.session.sessionManager).catch(() => undefined);
+ // Retention can decline if the parent is already tearing down; if so, close
+ // the session here so it doesn't linger in the registry.
+ if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
+ return;
+ }
+ }
if (state) {
- await this.closeSession(state, "completed");
+ await this.closeSession(state, status === "cancelled" ? "killed" : "completed");
return;
}
if (runtime instanceof AgentSessionRuntime) {
@@ -1661,6 +1674,7 @@ export class AgentDaemon {
void this.closeSession(state, "killed");
}
}
+ this.stampRlmChildActiveSessionId(message);
const sequencedMessage = this.addSessionEventMeta(state, message);
for (const client of state.clients) {
if (!shouldSendDaemonOutboundToClient(client, sequencedMessage)) {
@@ -1670,6 +1684,24 @@ export class AgentDaemon {
}
}
+ // The AgentSession doesn't know its own daemon active-session id, so fill it in here.
+ private stampRlmChildActiveSessionId(message: DaemonOutbound): void {
+ if (
+ message.type !== "session_event" ||
+ message.event.type !== "rlm_child_update" ||
+ message.event.child.activeSessionId
+ ) {
+ return;
+ }
+ const childId = message.event.child.id;
+ for (const candidate of this.sessions.values()) {
+ if (candidate.runtime.metadata.rlmChildId === childId) {
+ message.event.child.activeSessionId = candidate.activeSessionId;
+ return;
+ }
+ }
+ }
+
private addSessionEventMeta(state: ActiveSessionState, message: DaemonOutbound): DaemonOutbound {
if (!isSequencedSessionOutbound(message) || message.meta) {
return message;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 0998bf8700..4ad7782ef2 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -6,10 +6,7 @@ import { compactRlmText } from "../../core/agent-session.js";
import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";
import type { AgentSessionRuntimeDiagnostic } from "../../core/agent-session-services.js";
import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js";
-import type {
- AgentConnectionRlmChildAgentSnapshot,
- AgentConnectionRlmChildAgentTranscriptLine,
-} from "../agent-connection/types.js";
+import type { AgentConnectionRlmChildAgentSnapshot } from "../agent-connection/types.js";
import type { ActiveSessionState } from "./active-session-state.js";
// Durable lifecycle; decides agents-view visibility. Only "live" is shown.
@@ -253,19 +250,13 @@ function rlmChildSnapshotForActiveSession(
parent: ActiveSessionState | undefined,
): AgentConnectionRlmChildAgentSnapshot {
const session = activeSession.runtime.session;
- const transcript: AgentConnectionRlmChildAgentTranscriptLine[] = [];
let answerPreview: string | undefined;
for (const message of session.messages) {
- if (message.role !== "user" && message.role !== "assistant") {
- continue;
- }
- const text = compactRlmText(readMessageText(message.content));
- if (!text) {
- continue;
- }
- transcript.push({ role: message.role, text });
if (message.role === "assistant") {
- answerPreview = text;
+ const text = compactRlmText(readMessageText(message.content));
+ if (text) {
+ answerPreview = text;
+ }
}
}
// The parent session's run tracker is the source of truth for child status;
@@ -275,14 +266,17 @@ function rlmChildSnapshotForActiveSession(
const runStatus = metadata.rlmChildId
? parent?.runtime.session.getRlmChildRunStatus(metadata.rlmChildId)
: undefined;
+ const status = runStatus ?? (session.isStreaming || session.pendingMessageCount > 0 ? "running" : "done");
return {
id: metadata.rlmChildId ?? activeSession.activeSessionId,
parentId: parentNodeId,
+ activeSessionId: activeSession.activeSessionId,
label: compactRlmText(metadata.prompt ?? "", 80) || "child agent",
- status: runStatus ?? (session.isStreaming || session.pendingMessageCount > 0 ? "running" : "done"),
+ status,
answerPreview,
+ recap: session.getCurrentRecap(),
sessionDir: metadata.sessionDir ?? session.sessionManager.getSessionDir(),
- transcript,
+ activity: status === "running" ? { kind: session.isStreaming ? "writing" : "waiting" } : undefined,
};
}
@@ -321,13 +315,21 @@ function readMessageText(content: unknown): string {
// Agent doing work, ignoring the classification verdict.
export function isActiveSessionBusy(activeSession: ActiveSessionState): boolean {
const session = activeSession.runtime.session;
- return session.isStreaming || session.isCompacting || session.pendingMessageCount > 0;
+ // Background subagents keep the parent "working" even after its own turn ends.
+ return (
+ session.isStreaming || session.isCompacting || session.pendingMessageCount > 0 || session.hasRunningRlmChildren()
+ );
}
export function activeActivityForSession(activeSession: ActiveSessionState): SessionActivity {
if (isActiveSessionBusy(activeSession)) {
return "working";
}
+ // A finished subagent is resident but never gets a summarizer verdict, so don't hold
+ // it at "working" waiting for one — a not-busy subagent is simply idle/done.
+ if (activeSession.runtime.metadata?.kind === "subagent") {
+ return "idle";
+ }
// Hold at "working" until the idle verdict is current, so the view never
// buckets an unlabeled idle session.
return isSummaryCurrent(activeSession) ? "idle" : "working";
diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
index 43297c2c21..c134fa1d0c 100644
--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
@@ -1,70 +1,29 @@
-import type { AssistantMessage, ImageContent, TextContent, UserMessage } from "@earendil-works/pi-ai";
import {
type Component,
type Focusable,
getKeybindings,
type Keybinding,
- type MarkdownTheme,
- Text,
+ Loader,
type TUI,
truncateToWidth,
visibleWidth,
- wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
+import { AGENT_ACTIVITY_LABELS } from "../agent-activity.js";
import { theme } from "../theme/theme.js";
import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
-import { AssistantMessageComponent } from "./assistant-message.js";
-import { CollapsibleErrorComponent, shouldCollapseErrorDetails } from "./collapsible-error.js";
import { keyText } from "./keybinding-hints.js";
-import { ToolExecutionComponent, type ToolExecutionDefinition, type ToolExecutionOptions } from "./tool-execution.js";
-import { UserMessageComponent } from "./user-message.js";
export type ChildAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";
-export interface ChildAgentTranscriptLine {
- role: "user" | "assistant" | "tool" | "system";
- text: string;
+export interface ChildAgentActivity {
+ kind: "waiting" | "writing" | "executing";
+ toolName?: string;
}
-export interface ChildAgentToolResult {
- content: (TextContent | ImageContent)[];
- details?: unknown;
- isError: boolean;
-}
-
-export interface ChildAgentMessageTranscriptEntry {
- type: "message";
- role: "user" | "assistant";
- text: string;
- message: UserMessage | AssistantMessage;
-}
-
-export interface ChildAgentToolTranscriptEntry {
- type: "tool";
- role: "tool";
- text: string;
- toolCallId: string;
- toolName: string;
- args: unknown;
- result?: ChildAgentToolResult;
- isPartial: boolean;
- executionStarted: boolean;
- argsComplete: boolean;
-}
-
-export interface ChildAgentSystemTranscriptEntry {
- type: "system";
- role: "system";
- text: string;
-}
-
-export type ChildAgentStructuredTranscriptEntry =
- | ChildAgentMessageTranscriptEntry
- | ChildAgentToolTranscriptEntry
- | ChildAgentSystemTranscriptEntry;
-
export interface ChildAgentInspectorNode {
id: string;
+ /** The child's own daemon active-session id, for attaching directly to its stream. */
+ activeSessionId?: string;
label: string;
status: ChildAgentStatus;
durationMs?: number;
@@ -73,20 +32,13 @@ export interface ChildAgentInspectorNode {
tokenCount?: number;
recap?: string;
sessionDir: string;
- transcript: readonly ChildAgentTranscriptLine[];
- structuredTranscript?: readonly ChildAgentStructuredTranscriptEntry[];
+ activity?: ChildAgentActivity;
+ error?: string;
children?: readonly ChildAgentInspectorNode[];
}
export interface ChildAgentDetailOptions {
ui?: TUI;
- getCwd?: () => string;
- getToolDefinition?: (toolName: string) => ToolExecutionDefinition | undefined;
- getToolOptions?: () => ToolExecutionOptions;
- getMarkdownTheme?: () => MarkdownTheme;
- getToolsExpanded?: () => boolean;
- getHideThinkingBlock?: () => boolean;
- getHiddenThinkingLabel?: () => string;
}
interface FlatChildAgentNode {
@@ -107,10 +59,16 @@ function isExpandableComponent(component: Component): component is ExpandableCom
return "setExpanded" in component && typeof (component as { setExpanded?: unknown }).setExpanded === "function";
}
+// Active before finished, so completed agents settle to the bottom.
+function childAgentSortRank(status: ChildAgentStatus): number {
+ return status === "running" || status === "queued" ? 0 : 1;
+}
+
function flattenChildAgentNodes(nodes: readonly ChildAgentInspectorNode[]): FlatChildAgentNode[] {
const result: FlatChildAgentNode[] = [];
const walk = (items: readonly ChildAgentInspectorNode[], depth: number): void => {
- for (const node of items) {
+ const ordered = [...items].sort((a, b) => childAgentSortRank(a.status) - childAgentSortRank(b.status));
+ for (const node of ordered) {
result.push({ node, depth });
walk(node.children ?? [], depth + 1);
}
@@ -147,10 +105,28 @@ function hintLine(hints: ReadonlyArray<string | undefined>, width: number): stri
// 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(status: ChildAgentStatus): string {
switch (status) {
@@ -369,7 +345,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
const promptPrefix = this.sharedPromptPrefix(window);
const promptSuffix = this.sharedPromptSuffix(window, promptPrefix);
- const lines: string[] = [theme.fg("borderMuted", "─".repeat(width))];
+ const lines: string[] = [];
for (const entry of window) {
const selected = this.focused && entry.node.id === this.selectedId;
const number = flat.indexOf(entry) + 1;
@@ -587,12 +563,14 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
export class ChildAgentDetailComponent implements Component, Focusable {
focused = false;
private node: ChildAgentInspectorNode | undefined;
- private transcriptComponents: Component[] = [];
- private readonly fallbackTui = { requestRender: () => {} } as TUI;
+ 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;
@@ -601,17 +579,25 @@ export class ChildAgentDetailComponent implements Component, Focusable {
constructor(
_getViewportHeight: () => number = () => 0,
private readonly options: ChildAgentDetailOptions = {},
- ) {
- this.toolsExpanded = this.options.getToolsExpanded?.() ?? false;
- }
+ ) {}
setNode(node: ChildAgentInspectorNode | undefined): void {
if (node?.id !== this.node?.id) {
this.clearKillConfirmation({ render: false });
}
this.node = node;
- this.toolsExpanded = this.options.getToolsExpanded?.() ?? this.toolsExpanded;
- this.rebuildTranscriptComponents();
+ // 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 {
@@ -620,7 +606,7 @@ export class ChildAgentDetailComponent implements Component, Focusable {
setToolsExpanded(expanded: boolean): void {
this.toolsExpanded = expanded;
- for (const component of this.transcriptComponents) {
+ for (const component of this.bodyComponents) {
if (isExpandableComponent(component)) {
component.setExpanded(expanded);
}
@@ -628,8 +614,7 @@ export class ChildAgentDetailComponent implements Component, Focusable {
}
invalidate(): void {
- this.rebuildTranscriptComponents();
- for (const component of this.transcriptComponents) {
+ for (const component of this.bodyComponents) {
component.invalidate?.();
}
}
@@ -640,11 +625,74 @@ export class ChildAgentDetailComponent implements Component, Focusable {
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,
@@ -724,120 +772,16 @@ export class ChildAgentDetailComponent implements Component, Focusable {
};
}
- const headerLines = [
- this.panelLine(
- this.headerLine(`${this.statusLabel(selected.status)} ${theme.fg("dim", selected.label)}`, width),
- width,
- ),
- ];
- const sessionDirParts = selected.sessionDir.split("/");
- const leaf = sessionDirParts[sessionDirParts.length - 1];
- if (leaf) {
- headerLines.push(this.panelLine(this.truncate(theme.fg("dim", leaf), width), width));
- }
+ 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[] = [];
- if (selected.structuredTranscript && selected.structuredTranscript.length > 0) {
- for (const component of this.transcriptComponents) {
- bodyLines.push(...component.render(width));
- }
- return { headerLines, bodyLines };
- }
- for (const line of selected.transcript) {
- const label = theme.fg("dim", `${line.role}: `);
- const wrapped = wrapTextWithAnsi(line.text, Math.max(1, width - visibleWidth(label)));
- for (const [index, wrappedLine] of wrapped.entries()) {
- const prefix = index === 0 ? label : " ".repeat(visibleWidth(label));
- bodyLines.push(this.panelLine(this.truncate(prefix + wrappedLine, width), width));
- }
+ for (const component of this.bodyComponents) {
+ bodyLines.push(...component.render(width));
}
return { headerLines, bodyLines };
}
- private rebuildTranscriptComponents(): void {
- const transcript = this.node?.structuredTranscript;
- if (!transcript || transcript.length === 0) {
- this.transcriptComponents = [];
- return;
- }
-
- const components: Component[] = [];
- for (const entry of transcript) {
- switch (entry.type) {
- case "message":
- components.push(this.createMessageComponent(entry));
- break;
- case "tool":
- components.push(this.createToolComponent(entry));
- break;
- case "system":
- components.push(this.createSystemComponent(entry));
- break;
- }
- }
- this.transcriptComponents = components;
- }
-
- private createMessageComponent(entry: ChildAgentMessageTranscriptEntry): Component {
- if (entry.message.role === "user") {
- const text = this.readUserMessageText(entry.message);
- return text
- ? new UserMessageComponent(text, this.options.getMarkdownTheme?.())
- : new Text(theme.fg("userMessageText", entry.text), 1, 0);
- }
- return new AssistantMessageComponent(
- entry.message,
- this.options.getHideThinkingBlock?.() ?? false,
- this.options.getMarkdownTheme?.(),
- this.options.getHiddenThinkingLabel?.() ?? "Thinking...",
- { expanded: this.toolsExpanded },
- );
- }
-
- private createSystemComponent(entry: ChildAgentSystemTranscriptEntry): Component {
- if (!shouldCollapseErrorDetails(entry.text)) {
- return new Text(theme.fg("error", entry.text), 1, 0);
- }
- return new CollapsibleErrorComponent({
- text: entry.text,
- expanded: this.toolsExpanded,
- });
- }
-
- private createToolComponent(entry: ChildAgentToolTranscriptEntry): Component {
- const component = new ToolExecutionComponent(
- entry.toolName,
- entry.toolCallId,
- entry.args,
- this.options.getToolOptions?.() ?? {},
- this.options.getToolDefinition?.(entry.toolName),
- this.options.ui ?? this.fallbackTui,
- this.options.getCwd?.() ?? process.cwd(),
- );
- component.setExpanded(this.toolsExpanded);
- if (entry.executionStarted) {
- component.markExecutionStarted();
- }
- if (entry.argsComplete) {
- component.setArgsComplete();
- }
- if (entry.result) {
- component.updateResult(entry.result, entry.isPartial);
- }
- return component;
- }
-
- private readUserMessageText(message: UserMessage): string {
- if (typeof message.content === "string") {
- return message.content;
- }
- return message.content
- .filter((block) => block.type === "text")
- .map((block) => block.text)
- .join("");
- }
-
private headerLine(text: string, width: number): string {
const plainWidth = visibleWidth(text);
const rule = "─".repeat(Math.max(1, width - plainWidth - 1));
@@ -858,21 +802,6 @@ export class ChildAgentDetailComponent implements Component, Focusable {
);
}
- private statusLabel(status: ChildAgentStatus): string {
- switch (status) {
- case "queued":
- return theme.fg("muted", "queued");
- case "running":
- return theme.fg("accent", "running");
- case "done":
- return theme.fg("success", "done");
- case "error":
- return theme.fg("error", "error");
- case "cancelled":
- return theme.fg("warning", "cancelled");
- }
- }
-
private panelLine(line: string, width: number): string {
return this.truncate(line, width);
}
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
new file mode 100644
index 0000000000..e43f28580d
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -0,0 +1,93 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import type { Component, MarkdownTheme, TUI } from "@earendil-works/pi-tui";
+import { AssistantMessageComponent } from "./assistant-message.js";
+import { ToolExecutionComponent, type ToolExecutionDefinition, type ToolExecutionOptions } from "./tool-execution.js";
+import { UserMessageComponent } from "./user-message.js";
+
+export interface ConversationComponentsOptions {
+ ui: TUI;
+ cwd: string;
+ toolOptions: ToolExecutionOptions;
+ getToolDefinition: (name: string) => ToolExecutionDefinition | undefined;
+ markdownTheme?: MarkdownTheme;
+ hideThinkingBlock?: boolean;
+ hiddenThinkingLabel?: string;
+ toolsExpanded?: boolean;
+}
+
+function readUserText(content: string | Array<{ type: string; text?: string }>): string {
+ if (typeof content === "string") {
+ return content;
+ }
+ return content
+ .filter(
+ (block): block is { type: "text"; text: string } => block.type === "text" && typeof block.text === "string",
+ )
+ .map((block) => block.text)
+ .join("");
+}
+
+/** Build conversation components from a message list, matching tool results to their calls. */
+export function buildConversationComponents(
+ messages: readonly AgentMessage[],
+ options: ConversationComponentsOptions,
+): Component[] {
+ const components: Component[] = [];
+ const pendingTools = new Map<string, ToolExecutionComponent>();
+ const expanded = options.toolsExpanded ?? false;
+
+ for (const message of messages) {
+ if (message.role === "assistant") {
+ components.push(
+ new AssistantMessageComponent(
+ message,
+ options.hideThinkingBlock ?? false,
+ options.markdownTheme,
+ options.hiddenThinkingLabel ?? "Thinking...",
+ { expanded },
+ ),
+ );
+ for (const content of message.content) {
+ if (content.type !== "toolCall") {
+ continue;
+ }
+ const tool = new ToolExecutionComponent(
+ content.name,
+ content.id,
+ content.arguments,
+ // Replayed history rebuilds on every event; don't re-emit inline images.
+ { ...options.toolOptions, allowInlineImages: false },
+ options.getToolDefinition(content.name),
+ options.ui,
+ options.cwd,
+ );
+ tool.setExpanded(expanded);
+ tool.markExecutionStarted();
+ tool.setArgsComplete();
+ components.push(tool);
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
+ tool.updateResult({
+ content: [{ type: "text", text: message.errorMessage || "Operation aborted" }],
+ isError: true,
+ });
+ } else {
+ pendingTools.set(content.id, tool);
+ }
+ }
+ } else if (message.role === "toolResult") {
+ pendingTools.get(message.toolCallId)?.updateResult(message);
+ pendingTools.delete(message.toolCallId);
+ } else if (message.role === "user") {
+ const text = readUserText(message.content);
+ const hasContent =
+ typeof message.content === "string" ? message.content.length > 0 : message.content.length > 0;
+ // An image-only prompt has no text; show a placeholder rather than dropping it.
+ const display = text || (hasContent ? "[image]" : "");
+ if (display) {
+ components.push(new UserMessageComponent(display, options.markdownTheme));
+ }
+ }
+ // Non-conversational messages (bash/branch-summary/compaction/custom) aren't shown.
+ }
+ return components;
+}
diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.ts
index bc2e248257..a044085a9c 100644
--- a/packages/coding-agent/src/modes/interactive/components/index.ts
+++ b/packages/coding-agent/src/modes/interactive/components/index.ts
@@ -9,7 +9,6 @@ export {
type ChildAgentInspectorNode,
type ChildAgentStatus,
ChildAgentSummaryComponent,
- type ChildAgentTranscriptLine,
} from "./child-agent-inspector.js";
export { CompactionSummaryMessageComponent } from "./compaction-summary-message.js";
export { CustomEditor } from "./custom-editor.js";
@@ -37,13 +36,6 @@ export { SessionSelectorComponent } from "./session-selector.js";
export { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from "./settings-selector.js";
export { ShowImagesSelectorComponent } from "./show-images-selector.js";
export { SkillInvocationMessageComponent } from "./skill-invocation-message.js";
-export {
- type SubAgentStatus,
- type SubAgentTranscriptLine,
- SubAgentTreeComponent,
- type SubAgentTreeNode,
- type SubAgentTreeOptions,
-} from "./sub-agent-tree.js";
export { SubagentTreeView } from "./subagent-tree-view.js";
export { ThemeSelectorComponent } from "./theme-selector.js";
export { ThinkingSelectorComponent } from "./thinking-selector.js";
diff --git a/packages/coding-agent/src/modes/interactive/components/sub-agent-tree.ts b/packages/coding-agent/src/modes/interactive/components/sub-agent-tree.ts
deleted file mode 100644
index cdd5efa8ad..0000000000
--- a/packages/coding-agent/src/modes/interactive/components/sub-agent-tree.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { type Component, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
-import { theme } from "../theme/theme.js";
-
-export type SubAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";
-
-export interface SubAgentTranscriptLine {
- role: "user" | "assistant" | "tool" | "system";
- text: string;
-}
-
-export interface SubAgentTreeNode {
- id: string;
- label: string;
- status: SubAgentStatus;
- durationMs?: number;
- tokenCount?: number;
- costUsd?: number;
- answerPreview?: string;
- transcript?: readonly SubAgentTranscriptLine[];
- children?: readonly SubAgentTreeNode[];
- expanded?: boolean;
-}
-
-export interface SubAgentTreeOptions {
- rootLabel?: string;
- nodes?: readonly SubAgentTreeNode[];
- emptyText?: string;
-}
-
-type SubAgentNodePatch = Partial<Omit<SubAgentTreeNode, "id" | "children">> & {
- children?: readonly SubAgentTreeNode[];
-};
-
-export class SubAgentTreeComponent implements Component {
- private rootLabel: string;
- private emptyText: string;
- private nodes: readonly SubAgentTreeNode[];
- private expandedIds = new Set<string>();
- private expandAll = false;
-
- constructor(options: SubAgentTreeOptions = {}) {
- this.rootLabel = options.rootLabel ?? "sub-agents";
- this.emptyText = options.emptyText ?? "no recursive calls in this turn";
- this.nodes = options.nodes ?? [];
- }
-
- setNodes(nodes: readonly SubAgentTreeNode[]): void {
- this.nodes = nodes;
- }
-
- setExpanded(expanded: boolean): void;
- setExpanded(nodeId: string, expanded: boolean): void;
- setExpanded(nodeIdOrExpanded: string | boolean, expanded?: boolean): void {
- if (typeof nodeIdOrExpanded === "boolean") {
- this.expandAll = nodeIdOrExpanded;
- return;
- }
- if (expanded) {
- this.expandedIds.add(nodeIdOrExpanded);
- } else {
- this.expandedIds.delete(nodeIdOrExpanded);
- }
- }
-
- toggleNode(nodeId: string): void {
- this.setExpanded(nodeId, !this.expandedIds.has(nodeId));
- }
-
- updateNode(nodeId: string, patch: SubAgentNodePatch): void {
- this.nodes = this.nodes.map((node) => this.patchNode(node, nodeId, patch));
- }
-
- invalidate(): void {
- // Rendering is derived from node state.
- }
-
- render(width: number): string[] {
- const safeWidth = Math.max(1, width);
- const lines: string[] = [];
- lines.push(theme.fg("borderMuted", "─".repeat(safeWidth)));
-
- const headerParts = [theme.bold(this.rootLabel)];
- lines.push(truncateToWidth(headerParts.join(" "), safeWidth));
-
- if (this.nodes.length === 0) {
- lines.push(truncateToWidth(` ${theme.fg("muted", this.emptyText)}`, safeWidth));
- lines.push(theme.fg("borderMuted", "─".repeat(safeWidth)));
- return lines;
- }
-
- for (const [index, node] of this.nodes.entries()) {
- this.renderNode(lines, node, "", index === this.nodes.length - 1, safeWidth);
- }
- lines.push(theme.fg("borderMuted", "─".repeat(safeWidth)));
- return lines;
- }
-
- private patchNode(node: SubAgentTreeNode, nodeId: string, patch: SubAgentNodePatch): SubAgentTreeNode {
- const children = node.children?.map((child) => this.patchNode(child, nodeId, patch));
- if (node.id !== nodeId) {
- return children ? { ...node, children } : node;
- }
- return {
- ...node,
- ...patch,
- children: patch.children ?? children ?? node.children,
- };
- }
-
- private renderNode(lines: string[], node: SubAgentTreeNode, prefix: string, isLast: boolean, width: number): void {
- const connector = `${prefix}${isLast ? " └─ " : " ├─ "}`;
- const line = this.treeEdge(connector) + this.nodeSummary(node);
- lines.push(truncateToWidth(line, width));
-
- const childPrefix = `${prefix}${isLast ? " " : " │ "}`;
- if (this.expandAll || node.expanded || this.expandedIds.has(node.id)) {
- this.renderTranscript(lines, node, childPrefix, width);
- }
-
- const children = node.children ?? [];
- for (const [index, child] of children.entries()) {
- this.renderNode(lines, child, childPrefix, index === children.length - 1, width);
- }
- }
-
- private renderTranscript(lines: string[], node: SubAgentTreeNode, prefix: string, width: number): void {
- const transcript = node.transcript ?? [];
- const renderedPrefix = this.treeEdge(prefix);
- if (transcript.length === 0) {
- lines.push(truncateToWidth(`${renderedPrefix} ${theme.fg("muted", "(transcript unavailable)")}`, width));
- return;
- }
-
- for (const entry of transcript) {
- const label = theme.fg("dim", `${entry.role}: `);
- const wrapped = wrapTextWithAnsi(
- entry.text,
- Math.max(1, width - visibleWidth(prefix) - 3 - visibleWidth(label)),
- );
- for (const [index, line] of wrapped.entries()) {
- const entryPrefix =
- index === 0 ? `${renderedPrefix} ${label}` : `${renderedPrefix} ${" ".repeat(visibleWidth(label))}`;
- lines.push(truncateToWidth(entryPrefix + line, width));
- }
- }
- }
-
- private nodeSummary(node: SubAgentTreeNode): string {
- const parts = [this.statusLabel(node.status), theme.fg("dim", node.label)];
- const meta: string[] = [];
- const duration = this.formatDuration(node.durationMs);
- if (duration) {
- meta.push(duration);
- }
- if (meta.length > 0) {
- parts.push(theme.fg("muted", `· ${meta.join(" · ")}`));
- }
- if (node.answerPreview) {
- parts.push(theme.fg("toolOutput", `· "${node.answerPreview}"`));
- }
- return parts.join(" ");
- }
-
- private statusLabel(status: SubAgentStatus): string {
- switch (status) {
- case "queued":
- return theme.fg("muted", "queued");
- case "running":
- return theme.fg("accent", "running");
- case "done":
- return theme.fg("success", "done");
- case "error":
- return theme.fg("error", "error");
- case "cancelled":
- return theme.fg("warning", "cancelled");
- }
- }
-
- private formatDuration(durationMs: number | undefined): string | undefined {
- if (durationMs === undefined) {
- return undefined;
- }
- if (durationMs < 1000) {
- return `${Math.round(durationMs)}ms`;
- }
- return `${(durationMs / 1000).toFixed(1)}s`;
- }
-
- private treeEdge(text: string): string {
- return theme.fg("accent", text);
- }
-}
diff --git a/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts b/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
index 6b5f1565a8..93105d1456 100644
--- a/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
+++ b/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
@@ -2,7 +2,7 @@ import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/p
import { formatTokenCount } from "../agent-activity.js";
import { theme } from "../theme/theme.js";
import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
-import type { ChildAgentInspectorNode, ChildAgentStructuredTranscriptEntry } from "./child-agent-inspector.js";
+import { type ChildAgentInspectorNode, nodeActivityLabel } from "./child-agent-inspector.js";
/** Left padding so the tree aligns with the loader message / tool-call text. */
const PAD = " ";
@@ -112,43 +112,6 @@ export class SubagentTreeView implements Component {
}
}
-/**
- * A main-agent-style activity label ("Waiting" / "Writing" / "Executing") derived from
- * the subagent's latest transcript entry, shown until its recap lands.
- */
-function nodeActivityLabel(node: ChildAgentInspectorNode): string {
- if (node.status === "queued") {
- return "Waiting";
- }
- const last = lastMeaningfulEntry(node.structuredTranscript);
- if (!last) {
- return "Waiting";
- }
- if (last.type === "tool") {
- // Still running its tool vs. finished and about to think again.
- return last.isPartial ? `Executing ${last.toolName}` : "Waiting";
- }
- if (last.type === "message" && last.role === "assistant") {
- return "Writing";
- }
- return "Waiting";
-}
-
-function lastMeaningfulEntry(
- transcript: readonly ChildAgentStructuredTranscriptEntry[] | undefined,
-): ChildAgentStructuredTranscriptEntry | undefined {
- if (!transcript) {
- return undefined;
- }
- for (let i = transcript.length - 1; i >= 0; i--) {
- const entry = transcript[i];
- if (entry && entry.type !== "system") {
- return entry;
- }
- }
- return undefined;
-}
-
/** First few words of the prompt, clipped to a sensible width with an ellipsis. */
function compactLabel(label: string): string {
const words = label.trim().split(/\s+/);
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 06ce59d422..a9cea56394 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -113,6 +113,7 @@ import type {
AgentConnectionSessionContext,
AgentConnectionSessionEvent,
AgentConnectionSessionTreeNode,
+ AgentConnectionSessionWatcher,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionSourceInfo,
@@ -136,12 +137,11 @@ import { showFullPaneOverlay } from "./components/centered-overlay.js";
import {
ChildAgentDetailComponent,
type ChildAgentInspectorNode,
- type ChildAgentStructuredTranscriptEntry,
ChildAgentSummaryComponent,
- type ChildAgentTranscriptLine,
} from "./components/child-agent-inspector.js";
import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.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";
@@ -271,6 +271,7 @@ export interface BrandSplashMetadataLine {
export interface BrandSplashHeaderOptions {
logo?: string;
getExtraMetadata?: () => readonly BrandSplashMetadataLine[];
+ getHideStartHint?: () => boolean;
}
export class BrandSplashHeader implements Component {
@@ -307,14 +308,14 @@ export class BrandSplashHeader implements Component {
return theme.fg("dim", label.padEnd(this.labelWidth)) + theme.fg("muted", displayValue);
};
const extraMetadata = this.options.getExtraMetadata?.() ?? [];
+ const hideStartHint = this.options.getHideStartHint?.() ?? false;
const metaLines = showMeta
? [
labelled("version", `v${this.version}`),
labelled("model", this.getModelId() ?? "—"),
labelled("cwd", formatSplashCwd(this.getCwd())),
...extraMetadata.map((line) => labelled(line.label, line.value)),
- "",
- theme.fg("dim", "type to start"),
+ ...(hideStartHint ? [] : ["", theme.fg("dim", "type to start")]),
]
: [];
const metaStart = Math.max(0, Math.floor((this.logoRaw.length - metaLines.length) / 2));
@@ -567,6 +568,14 @@ export class InteractiveMode {
private childAgentDetailNodeId: string | undefined;
private childAgentPanelMode: "detail" | undefined;
private enteredSessionViaSubagentDetail = false;
+ private childAgentWatcher: AgentConnectionSessionWatcher | undefined;
+ private childAgentWatcherToken = 0;
+ private childAgentWatcherMessages: AgentMessage[] = [];
+ // Monotonic per-watch counter so a late-resolving getMessages can't clobber a newer one.
+ private childAgentRefreshSeq = 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;
// Tool output expansion state
private toolOutputExpanded = false;
@@ -677,16 +686,6 @@ export class InteractiveMode {
this.queuedMessagesContainer = new Container();
this.childAgentDetail = new ChildAgentDetailComponent(() => this.getChildAgentPanelRows(), {
ui: this.ui,
- getCwd: () => this.getCurrentCwd(),
- getToolDefinition: (toolName) => this.getCachedToolDefinition(toolName),
- getToolOptions: () => ({
- showImages: this.settingsManager.getShowImages(),
- imageWidthCells: this.settingsManager.getImageWidthCells(),
- }),
- getMarkdownTheme: () => this.getMarkdownThemeWithSettings(),
- getToolsExpanded: () => this.toolOutputExpanded,
- getHideThinkingBlock: () => this.hideThinkingBlock,
- getHiddenThinkingLabel: () => this.hiddenThinkingLabel,
});
this.childAgentDetail.onCancel = () => {
if (this.options.returnToAgentsView && this.enteredSessionViaSubagentDetail) {
@@ -948,6 +947,7 @@ export class InteractiveMode {
() => this.getCurrentModelId(),
() => this.getCurrentCwd(),
verboseInstructions,
+ { getHideStartHint: () => this.childAgentPanelMode !== undefined },
);
this.headerContainer.addChild(new Spacer(1));
this.headerContainer.addChild(this.builtInHeader);
@@ -2592,7 +2592,10 @@ export class InteractiveMode {
}
private shouldShowWorkingLoader(): boolean {
- return this.workingVisible && (this.isAgentStreaming() || this.countRunningChildAgents() > 0);
+ // Background subagents (agent turn done, asyncio tasks still running) would
+ // otherwise show a textless spinner; the subagent tree above the loader carries
+ // that state, so the loader only shows while the main agent is itself streaming.
+ return this.workingVisible && this.isAgentStreaming();
}
// Reconcile the loader with current state for transitions that fire no live
@@ -2754,7 +2757,8 @@ export class InteractiveMode {
private renderRecap(): void {
if (!this.recapContainer) return;
this.recapContainer.clear();
- const recap = this.sessionRecap?.trim();
+ // The subagent panel shows its own recap; suppress the parent's while it's open.
+ const recap = this.childAgentPanelMode ? undefined : this.sessionRecap?.trim();
if (recap) {
this.recapContainer.addChild(new Text(theme.fg("dim", `Recap: ${recap}`), 1, 0));
// Blank line between the recap and the prompt bar below it.
@@ -4137,7 +4141,7 @@ export class InteractiveMode {
if (this.settingsManager.getShowTerminalProgress()) {
this.ui.terminal.setProgress(false);
}
- // Keep the loader up if async subagents outlive the parent turn.
+ // Drops the loader; background subagents are shown by the tree, not the loader.
this.syncWorkingLoader();
if (this.streamingComponent) {
if (this.streamingMessage) {
@@ -4477,6 +4481,7 @@ export class InteractiveMode {
return;
}
this.childAgentDetail.setNode(detailNode);
+ this.maybeRetryChildAgentWatch(detailNode);
}
this.ui.requestRender();
}
@@ -4661,6 +4666,8 @@ export class InteractiveMode {
this.childAgentPanelMode = "detail";
this.childAgentDetailNodeId = nodeId;
this.childAgentDetail.setNode(node);
+ this.childAgentDetail.setBodyComponents([]);
+ this.renderRecap();
this.childAgentSummary.setHidden(true);
this.editorContainer.clear();
this.queuedMessagesContainer.clear();
@@ -4668,17 +4675,136 @@ export class InteractiveMode {
this.mainViewContainer.addChild(this.childAgentDetail);
this.ui.setFocus(this.childAgentDetail);
this.ui.requestRender();
+ void this.startChildAgentWatch(node);
return true;
}
+ 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;
+ }
+ // session_replaced carries a fresh messages array; both need a rebuild.
+ if (event.type === "session_event" || event.type === "session_replaced") {
+ 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 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>();
+ await Promise.all(
+ [...toolNames].map(async (name) => {
+ definitions.set(name, (await watcher.getToolDefinition(name).catch(() => undefined)) ?? undefined);
+ }),
+ );
+ // A newer refresh (or a close) may have superseded this build while awaiting defs.
+ if (token !== this.childAgentWatcherToken) {
+ return;
+ }
+ this.childAgentDetail.setBodyComponents(
+ buildConversationComponents(messages, {
+ ui: this.ui,
+ cwd: this.getCurrentCwd(),
+ toolOptions: {
+ showImages: this.settingsManager.getShowImages(),
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
+ },
+ getToolDefinition: (name) => definitions.get(name),
+ markdownTheme: this.getMarkdownThemeWithSettings(),
+ hideThinkingBlock: this.hideThinkingBlock,
+ hiddenThinkingLabel: this.hiddenThinkingLabel,
+ toolsExpanded: this.toolOutputExpanded,
+ }),
+ );
+ }
+
+ 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.enteredSessionViaSubagentDetail = false;
this.childAgentDetail.setBackHintLabel("back to chat");
this.childAgentDetail.setNode(undefined);
+ this.childAgentDetail.setBodyComponents([]);
this.childAgentSummary.setHidden(false);
this.restoreMainAgentView();
+ // 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();
@@ -4704,6 +4830,7 @@ export class InteractiveMode {
const build = (child: AgentConnectionRlmChildAgentSnapshot): ChildAgentInspectorNode => ({
id: child.id,
+ activeSessionId: child.activeSessionId,
label: child.label,
status: child.status,
durationMs: child.durationMs,
@@ -4712,15 +4839,8 @@ export class InteractiveMode {
tokenCount: child.tokenCount,
recap: child.recap,
sessionDir: child.sessionDir,
- transcript: child.transcript.map(
- (line): ChildAgentTranscriptLine => ({
- role: line.role,
- text: line.text,
- }),
- ),
- structuredTranscript: child.structuredTranscript?.map(
- (entry): ChildAgentStructuredTranscriptEntry => ({ ...entry }),
- ),
+ activity: child.activity,
+ error: child.error,
children: childrenByParent.get(child.id)?.map(build),
});
@@ -5367,6 +5487,11 @@ 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));
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index 36a0d161e5..b997828f1b 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -255,8 +255,6 @@ describe("AgentSession rlm recursion", () => {
answerPreview?: string;
tokenCount?: number;
toolUseCount?: number;
- transcript: readonly { role: string; text: string }[];
- structuredTranscript?: readonly { type: string; role: string; text: string }[];
}> = [];
root.subscribe((event) => {
if (event.type === "rlm_child_update") {
@@ -281,14 +279,6 @@ describe("AgentSession rlm recursion", () => {
// Context tokens from the child's own assistant usage (input 7 + output 3); no tools ran.
expect(doneUpdate?.tokenCount).toBe(10);
expect(doneUpdate?.toolUseCount).toBeUndefined();
- expect(doneUpdate?.transcript).toContainEqual({ role: "user", text: "summarize shard 1" });
- expect(doneUpdate?.transcript).toContainEqual({ role: "assistant", text: "child answer: summarize shard 1" });
- expect(doneUpdate?.structuredTranscript).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ type: "message", role: "user", text: "summarize shard 1" }),
- expect.objectContaining({ type: "message", role: "assistant", text: "child answer: summarize shard 1" }),
- ]),
- );
});
it("surfaces a child's recap on its snapshot once the summarizer sets it", async () => {
@@ -336,7 +326,7 @@ describe("AgentSession rlm recursion", () => {
toolsManagerMock.ensureTool.mockResolvedValueOnce(undefined);
const streamFn = vi.fn((_model, context: Context) => streamAnswer(`child answer: ${userText(context)}`));
const root = createSession({ streamFn });
- const childUpdates: Array<{ status: string; transcript: readonly { role: string; text: string }[] }> = [];
+ const childUpdates: Array<{ status: string }> = [];
root.subscribe((event) => {
if (event.type === "rlm_child_update") {
childUpdates.push(event.child);
@@ -348,7 +338,7 @@ describe("AgentSession rlm recursion", () => {
expect(toolsManagerMock.ensureTool).toHaveBeenCalledWith("rg", true);
expect(streamFn).not.toHaveBeenCalled();
const errorUpdate = [...childUpdates].reverse().find((update) => update.status === "error");
- expect(errorUpdate?.transcript).toContainEqual({ role: "system", text: MISSING_RIPGREP_MESSAGE });
+ expect(errorUpdate).toBeDefined();
});
it("adds child usage to the parent session aggregate", async () => {
diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.ts
index 602c924c63..215c6a41f3 100644
--- a/packages/coding-agent/test/child-agent-summary-list.test.ts
+++ b/packages/coding-agent/test/child-agent-summary-list.test.ts
@@ -12,7 +12,7 @@ function stripAnsi(text: string): string {
}
function node(id: string, status: ChildAgentInspectorNode["status"] = "running"): ChildAgentInspectorNode {
- return { id, label: id, status, sessionDir: `/tmp/${id}`, transcript: [] };
+ return { id, label: id, status, sessionDir: `/tmp/${id}` };
}
describe("ChildAgentSummaryComponent inline list", () => {
@@ -149,13 +149,6 @@ describe("ChildAgentSummaryComponent inline list", () => {
expect(forwarded).toBe("\x0f");
});
- it("renders a separator line above the list", () => {
- const summary = new ChildAgentSummaryComponent();
- summary.setNodes([node("only")]);
- const lines = summary.render(40).map(stripAnsi);
- expect(lines.some((line) => line.includes("─"))).toBe(true);
- });
-
it("opens the selected subagent's detail on confirm", () => {
const summary = new ChildAgentSummaryComponent();
summary.focused = true;
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 5bb6a12340..4440bb9f0d 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -55,6 +55,43 @@ describe("buildSessionList", () => {
]);
});
+ it("keeps a session working while background subagents run", () => {
+ const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
+ const entries = buildSessionList(
+ [
+ makeState({
+ activeSessionId: "parent",
+ sessionFile: "/tmp/parent.jsonl",
+ isStreaming: false,
+ hasRunningRlmChildren: true,
+ messages: oneMessage,
+ summaryState: { basedOnMessageCount: 1 } as ActiveSessionState["summaryState"],
+ }),
+ ],
+ [],
+ );
+ expect(entries[0]?.activity).toBe("working");
+ });
+
+ it("marks a finished subagent idle instead of holding it at working", () => {
+ const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
+ const entries = buildSessionList(
+ [
+ makeState({
+ activeSessionId: "child",
+ sessionFile: "/tmp/child.jsonl",
+ isStreaming: false,
+ hasRunningRlmChildren: false,
+ messages: oneMessage,
+ // No current summary verdict — a resident finished subagent never gets one.
+ metadata: { kind: "subagent", createdAt: 1, parentActiveSessionId: "parent", rlmChildId: "c1" },
+ }),
+ ],
+ [],
+ );
+ expect(entries[0]?.activity).toBe("idle");
+ });
+
it("merges active records with saved sessions and marks inactive sessions", () => {
const activePath = resolve("/tmp/project/active.jsonl");
const sleepingPath = resolve("/tmp/project/sleeping.jsonl");
@@ -303,10 +340,7 @@ describe("buildRlmChildSnapshots", () => {
label: "Summarize the repo layout",
answerPreview: "The repo is an npm workspace.",
sessionDir: "/tmp/artifacts/sub-aaa",
- transcript: [
- { role: "user", text: "Summarize the repo layout" },
- { role: "assistant", text: "The repo is an npm workspace." },
- ],
+ activeSessionId: "child",
});
});
@@ -390,6 +424,7 @@ interface StateOptions {
hasUserContent?: boolean;
summaryState?: ActiveSessionState["summaryState"];
childRunStatuses?: Record<string, "queued" | "running" | "done" | "error" | "cancelled">;
+ hasRunningRlmChildren?: boolean;
metadata?: {
kind: "top-level" | "subagent";
createdAt: number;
@@ -432,6 +467,8 @@ function makeState(options: StateOptions): ActiveSessionState {
},
messages: options.messages ?? ([] as AgentMessage[]),
getRlmChildRunStatus: (childId: string) => options.childRunStatuses?.[childId],
+ hasRunningRlmChildren: () => options.hasRunningRlmChildren ?? false,
+ getCurrentRecap: () => undefined,
pendingMessageCount: 0,
state: {
streamingMessage: undefined,
diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.ts
index 9d3d6afeb3..0f0795567d 100644
--- a/packages/coding-agent/test/marquee-components.test.ts
+++ b/packages/coding-agent/test/marquee-components.test.ts
@@ -10,8 +10,8 @@ import {
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 { SubAgentTreeComponent } from "../src/modes/interactive/components/sub-agent-tree.js";
import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
import { initTheme } from "../src/modes/interactive/theme/theme.js";
@@ -69,6 +69,16 @@ 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);
@@ -336,51 +346,6 @@ describe("marquee TUI components", () => {
expect(component.render(100)).toBe(expanded);
});
- test("renders sub-agent tree nodes with status, previews, and transcript expansion", async () => {
- const component = new SubAgentTreeComponent({
- rootLabel: "root: triage logs",
- nodes: [
- {
- id: "shard-0",
- label: "shard-0",
- status: "done",
- durationMs: 12300,
- tokenCount: 4200,
- costUsd: 0.25,
- answerPreview: "no anomaly, normal loss curve",
- transcript: [{ role: "assistant", text: "no anomaly found in this shard" }],
- },
- {
- id: "shard-1",
- label: "shard-1",
- status: "running",
- durationMs: 7800,
- },
- {
- id: "shard-2",
- label: "shard-2",
- status: "done",
- durationMs: 11100,
- tokenCount: 4700,
- answerPreview: "NaN at step 2103",
- },
- ],
- });
-
- const collapsed = await renderInVirtualTerminal(component);
- expect(collapsed).toContain("root: triage logs");
- expect(collapsed).toContain(' ├─ done shard-0 · 12.3s · "no anomaly, normal loss curve"');
- expect(collapsed).toContain(" ├─ running shard-1 · 7.8s");
- expect(collapsed).toContain(' └─ done shard-2 · 11.1s · "NaN at step 2103"');
- expect(collapsed).not.toContain("tok");
- expect(collapsed).not.toContain("$0.25");
- expect(collapsed).not.toContain("no anomaly found in this shard");
-
- component.setExpanded("shard-0", true);
- const expanded = await renderInVirtualTerminal(component);
- expect(expanded).toContain("assistant: no anomaly found in this shard");
- });
-
test("renders assistant thinking as quiet text without background styling", () => {
const component = new AssistantMessageComponent(
createAssistantMessage("answer", "Check **bold** and `code` first.\n```ts\nconst value = 1;\n```"),
@@ -473,47 +438,12 @@ describe("marquee TUI components", () => {
label: "inspect training logs",
status: "running",
sessionDir: "/tmp/session/sub-a",
- transcript: [
- { role: "user", text: "inspect training logs" },
- { role: "assistant", text: "reading shard metrics" },
- { role: "tool", text: "bash: hi" },
- ],
- structuredTranscript: [
- {
- type: "message",
- role: "user",
- text: "inspect training logs",
- message: createUserMessage("inspect training logs"),
- },
- {
- type: "message",
- role: "assistant",
- text: "reading shard metrics",
- message: createAssistantMessage("reading shard metrics", "checking loss curve"),
- },
- {
- type: "tool",
- role: "tool",
- text: "bash: hi",
- toolCallId: "tool-sub-a",
- toolName: "bash",
- args: { command: "echo hi" },
- result: {
- content: [{ type: "text", text: "hi" }],
- isError: false,
- },
- isPartial: false,
- executionStarted: true,
- argsComplete: true,
- },
- ],
children: [
{
id: "sub-b",
label: "check shard 2",
status: "done",
sessionDir: "/tmp/session/sub-b",
- transcript: [{ role: "assistant", text: "no anomaly" }],
},
],
};
@@ -527,7 +457,6 @@ describe("marquee TUI components", () => {
expect(summaryText).toContain("37% context left");
expect(summaryText).toContain("Subagent 1");
expect(summaryText).toContain("inspect training logs");
- expect(summaryLines.some((line) => line.includes("─"))).toBe(true);
const infoRow = summary.render(90)[0] ?? "";
expect(visibleWidth(infoRow)).toBe(90);
@@ -542,50 +471,25 @@ describe("marquee TUI components", () => {
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("running inspect training logs");
- expect(detail).toContain("sub-a");
expect(detail).toContain("inspect training logs");
- expect(detail).toContain("checking loss curve");
expect(detail).toContain("reading shard metrics");
- expect(detail).toContain("$ echo hi");
- expect(detail).toContain("hi");
expect(detail).toContain("← back to chat");
expect(detail).not.toContain("user: inspect training logs");
expect(detail).not.toContain("assistant: reading shard metrics");
- expect(detail).not.toContain("tool: bash");
});
- test("collapses multiline child agent system errors in detail view", () => {
- const detailComponent = new ChildAgentDetailComponent(() => 20);
- const errorText = [
- "ChildProcessError: child exited with status 1",
- "Traceback (most recent call last):",
- ' File "/tmp/rlm_harness/internal.py", line 10, in run',
- "ChildProcessError: child exited with status 1",
- ].join("\n");
- detailComponent.setNode({
- id: "sub-error",
- label: "inspect failure",
- status: "error",
- sessionDir: "/tmp/session/sub-error",
- transcript: [],
- structuredTranscript: [{ type: "system", role: "system", text: errorText }],
- });
-
- const collapsed = stripAnsi(detailComponent.render(100).join("\n"));
- expect(collapsed).toContain("ChildProcessError: child exited with status 1");
- expect(collapsed).toContain("Ctrl+O to expand");
- expect(collapsed).not.toContain("error details collapsed");
- expect(collapsed).not.toContain("/tmp/rlm_harness/internal.py");
-
- detailComponent.setToolsExpanded(true);
- const expanded = stripAnsi(detailComponent.render(100).join("\n"));
- expect(expanded).toContain("/tmp/rlm_harness/internal.py");
- });
-
- test("keeps child agent assistant errors expanded after transcript rebuilds", () => {
+ test("renders child agent assistant errors in the detail view", () => {
const detailComponent = new ChildAgentDetailComponent(() => 20);
detailComponent.setToolsExpanded(true);
const assistantError: AssistantMessage = {
@@ -604,25 +508,11 @@ describe("marquee TUI components", () => {
label: "inspect failure",
status: "error",
sessionDir: "/tmp/session/sub-assistant-error",
- transcript: [],
- structuredTranscript: [
- {
- type: "message",
- role: "assistant",
- text: assistantError.errorMessage ?? "",
- message: assistantError,
- },
- ],
});
+ detailComponent.setBodyComponents(buildConversationComponents([assistantError], bodyOptions(true)));
const expanded = stripAnsi(detailComponent.render(100).join("\n"));
expect(expanded).toContain("/tmp/internal.py");
- expect(expanded).not.toContain("Ctrl+O to expand");
-
- detailComponent.invalidate();
- const afterInvalidate = stripAnsi(detailComponent.render(100).join("\n"));
- expect(afterInvalidate).toContain("/tmp/internal.py");
- expect(afterInvalidate).not.toContain("Ctrl+O to expand");
});
test("routes child agent detail tool expansion through app keybindings", () => {
@@ -638,24 +528,6 @@ describe("marquee TUI components", () => {
label: "inspect training logs",
status: "running",
sessionDir: "/tmp/session/sub-a",
- transcript: [],
- structuredTranscript: [
- {
- type: "tool",
- role: "tool",
- text: "bash: hi",
- toolCallId: "tool-sub-a",
- toolName: "bash",
- args: { command: "echo hi" },
- result: {
- content: [{ type: "text", text: "hi" }],
- isError: false,
- },
- isPartial: false,
- executionStarted: true,
- argsComplete: true,
- },
- ],
});
const before = stripAnsi(detailComponent.render(80).join("\n"));
@@ -682,7 +554,6 @@ describe("marquee TUI components", () => {
label: "inspect training logs",
status: "running",
sessionDir: "/tmp/session/sub-a",
- transcript: [],
},
]);
@@ -702,16 +573,20 @@ describe("marquee TUI components", () => {
label: "inspect long output",
status: "done",
sessionDir: "/tmp/session/sub-scroll",
- transcript: Array.from({ length: 12 }, (_, index) => ({
- role: "assistant" as const,
- text: `fallback transcript row ${String(index + 1).padStart(2, "0")}`,
- })),
});
+ 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("fallback transcript row 01");
- expect(first).toContain("fallback transcript row 12");
+ 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("↓");
diff --git a/packages/coding-agent/test/subagent-tree-view.test.ts b/packages/coding-agent/test/subagent-tree-view.test.ts
index 40d3bbbbce..bccfece5e3 100644
--- a/packages/coding-agent/test/subagent-tree-view.test.ts
+++ b/packages/coding-agent/test/subagent-tree-view.test.ts
@@ -11,7 +11,6 @@ function node(overrides: Partial<ChildAgentInspectorNode> & { id: string }): Chi
label: overrides.id,
status: "running",
sessionDir: `/tmp/${overrides.id}`,
- transcript: [],
...overrides,
};
}
@@ -125,48 +124,24 @@ describe("SubagentTreeView", () => {
test("falls back to a live activity label until the recap lands", () => {
const view = new SubagentTreeView();
- // No transcript yet -> Waiting.
+ // No activity yet -> Waiting.
view.setNodes([node({ id: "x", label: "scout" })]);
// header + blank + 2 node lines = 4
expect(view.render(100)).toHaveLength(4);
expect(renderText(view)).toContain("Waiting");
// A tool still running -> Executing <tool>.
- view.setNodes([
- node({
- id: "x",
- label: "scout",
- structuredTranscript: [
- {
- type: "tool",
- role: "tool",
- text: "",
- toolCallId: "1",
- toolName: "Bash",
- args: {},
- isPartial: true,
- executionStarted: true,
- argsComplete: true,
- },
- ],
- }),
- ]);
+ view.setNodes([node({ id: "x", label: "scout", activity: { kind: "executing", toolName: "Bash" } })]);
expect(renderText(view)).toContain("Executing Bash");
// Assistant text streaming -> Writing.
- view.setNodes([
- node({
- id: "x",
- label: "scout",
- structuredTranscript: [
- { type: "message", role: "assistant", text: "thinking out loud", message: {} as never },
- ],
- }),
- ]);
+ view.setNodes([node({ id: "x", label: "scout", activity: { kind: "writing" } })]);
expect(renderText(view)).toContain("Writing");
- // Queued -> Waiting regardless of transcript.
- view.setNodes([node({ id: "x", label: "scout", status: "queued" })]);
+ // Queued -> Waiting regardless of activity.
+ view.setNodes([
+ node({ id: "x", label: "scout", status: "queued", activity: { kind: "executing", toolName: "Bash" } }),
+ ]);
expect(renderText(view)).toContain("Waiting");
});
@@ -177,19 +152,7 @@ describe("SubagentTreeView", () => {
id: "x",
label: "scout",
recap: "Searching for 6 patterns",
- structuredTranscript: [
- {
- type: "tool",
- role: "tool",
- text: "",
- toolCallId: "1",
- toolName: "Bash",
- args: {},
- isPartial: true,
- executionStarted: true,
- argsComplete: true,
- },
- ],
+ activity: { kind: "executing", toolName: "Bash" },
}),
]);
const text = renderText(view);
@@ -206,12 +169,6 @@ describe("SubagentTreeView", () => {
expect(summaryLine).toMatch(/[◇◈◆]/);
});
- test("never leaks the transcript onto the recap line", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "x", label: "scout", transcript: [{ role: "tool", text: "Bash: rm -rf secret" }] })]);
- expect(renderText(view)).not.toContain("Bash: rm -rf secret");
- });
-
test("caps the label to a few words", () => {
const view = new SubagentTreeView();
view.setNodes([node({ id: "x", label: "find every place the parser touches the old config schema" })]);