A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
improve subagent ux in the chat view (#247)
kte55d8d6c9df8
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 325718bcfc..01affb8ac9 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -451,6 +451,13 @@ export function compactRlmText(text: string, maxLength = 160): string {return `${compact.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;}+// Child-agent label: collapse to one line but keep the full prompt — the TUI+// truncates to the visible width and elides shared prefixes, so capping here+// would only hide the divergence between near-identical sibling prompts.+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;@@ -3984,7 +3991,7 @@ export class AgentSession {const parentAssistantForUsage = this._findLastAssistantMessage();const transcript: RlmChildAgentTranscriptLine[] = [];const structuredTranscript: RlmChildAgentStructuredTranscriptEntry[] = [];- const label = compactRlmText(prompt, 80) || "child agent";+ const label = rlmChildLabel(prompt);let answerPreview: string | undefined;let durationMs: number | undefined;const run: RlmChildRun = {@@ -4997,7 +5004,7 @@ export class AgentSession {children: [],}),id: run.id,- label: compactRlmText(run.prompt, 80) || "child agent",+ label: rlmChildLabel(run.prompt),status: run.status,});}diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex e66646ab47..45395cc535 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -36,6 +36,7 @@ import {stopThemeWatcher,theme,} from "../interactive/theme/theme.js";+import { WORKING_ICON_INTERVAL_MS, workingIconFrame } from "../interactive/theme/working-icon.js";import {formatPackageUpdateNotice,formatTmuxWarningNotice,@@ -61,7 +62,6 @@ import {} from "./agents-view-state.js";const POLL_INTERVAL_MS = 1000;-const WORKING_ICON_INTERVAL_MS = 250;const EXIT_HINT_DURATION_MS = 2000;const DELETE_CONFIRM_DURATION_MS = 2000;const STATUS_MESSAGE_DURATION_MS = 4500;@@ -70,7 +70,6 @@ const DEFAULT_PROMPT_PLACEHOLDER = "Describe a task for a new session";const REPLY_PROMPT_FALLBACK_PLACEHOLDER = "Write a reply to this agent";const COMPLETED_ROW_ICON = "✓";const NEEDS_INPUT_ROW_ICON = "●";-const WORKING_ICON_FRAMES = ["◇", "◈", "◆", "◈"] as const;const SELECTED_ROW_MARKER = "\0agents-view-selected-row\0";// Tags a spawn-code line so finalize can wrap the whole row in a panel// background, visually segmenting the program from the agent rows.@@ -1773,7 +1772,7 @@ class AgentsViewMode implements Component, Focusable {private getRowIcon(section: AgentsViewSection): string {switch (section) {case "working":- return WORKING_ICON_FRAMES[this.workingIconFrame % WORKING_ICON_FRAMES.length] ?? WORKING_ICON_FRAMES[0];+ return workingIconFrame(this.workingIconFrame);case "needs-input":return NEEDS_INPUT_ROW_ICON;case "completed":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.tsindex f12e8be769..fa8f8c67fc 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@@ -12,6 +12,7 @@ import {wrapTextWithAnsi,} from "@earendil-works/pi-tui";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";@@ -90,11 +91,6 @@ interface FlatChildAgentNode {depth: number;}-interface InspectorLine {- text: string;- selected: boolean;-}-interface DetailSections {headerLines: string[];bodyLines: string[];@@ -120,14 +116,6 @@ function flattenChildAgentNodes(nodes: readonly ChildAgentInspectorNode[]): Flatreturn result;}-function countRunning(nodes: readonly FlatChildAgentNode[]): number {- return nodes.filter((entry) => entry.node.status === "running").length;-}--function pluralize(count: number, singular: string, plural = `${singular}s`): string {- return count === 1 ? singular : plural;-}-interface KeyActionOptions {primaryOnly?: boolean;}@@ -218,19 +206,30 @@ function padTableCell(value: string, width: number): string {return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));}-function padRightTableCell(value: string, width: number): string {- const truncated = truncateToWidth(value, width, "");- return " ".repeat(Math.max(0, width - visibleWidth(truncated))) + truncated;-}+// Rows shown at once in the inline list below the prompt; extras scroll.+const SUMMARY_VISIBLE_ROWS = 5;+const SUMMARY_LIST_INDENT = 1;+const SHARED_PREFIX_MIN = 12;+// Gap between the "Subagent N" column and the prompt.+const SUMMARY_LABEL_GAP = 4;+// Opening chars of the prompt kept for context before eliding a shared prefix.+const PROMPT_LEADING_CONTEXT = 14;+// Words of context kept on each side of the divergence.+const PROMPT_DIFF_CONTEXT_WORDS = 2;export class ChildAgentSummaryComponent implements Component, Focusable {focused = false;private readonly paddingX = 1;private nodes: readonly ChildAgentInspectorNode[] = [];private hidden = false;+ private selectedId: string | undefined;onOpen?: () => void;onCancel?: () => void;+ onExit?: () => void;+ onOpenDetail?: (nodeId: string) => void;+ // Chat actions that should still work while the list holds focus.+ onChatAction?: (data: string) => void;constructor(private readonly getLocationLabel: () => string | undefined = () => undefined,@@ -240,132 +239,28 @@ export class ChildAgentSummaryComponent implements Component, Focusable {setNodes(nodes: readonly ChildAgentInspectorNode[]): void {this.nodes = nodes;- }-- setHidden(hidden: boolean): void {- this.hidden = hidden;- }-- hasNodes(): boolean {- return flattenChildAgentNodes(this.nodes).length > 0;- }-- invalidate(): void {- // Render output is derived from node state.- }-- render(width: number): string[] {- if (this.hidden) {- return [];- }-- const safeWidth = Math.max(1, width);const flat = flattenChildAgentNodes(this.nodes);- const overrideLabel = this.getOverrideLabel()?.trim();- const locationLabel = this.getLocationLabel()?.trim();- const contextLabel = this.getContextLabel()?.trim();- const override = overrideLabel ? theme.fg("muted", overrideLabel) : "";- const location = !override && locationLabel ? theme.fg("muted", locationLabel) : "";- const context = contextLabel ? theme.fg("muted", contextLabel) : "";- const subagents = !override && flat.length > 0 ? this.subagentSummary(flat, this.focused) : "";- const summaryHint = !override && this.focused && flat.length > 0 ? this.summaryHint() : "";- const leftSegments = [override, location, subagents, summaryHint].filter((segment) => segment.length > 0);- if (leftSegments.length === 0 && !context) {- return [];- }-- const rawLeft = leftSegments.join(theme.fg("dim", " "));- const paddedLine = context- ? this.renderSplitLine(rawLeft, context, safeWidth)- : this.renderCompactLine(rawLeft, safeWidth);- return [paddedLine];- }-- handleInput(data: string): void {- const kb = getKeybindings();- if (kb.matches(data, "tui.select.confirm")) {- this.onOpen?.();+ if (flat.length === 0) {+ this.selectedId = undefined;return;}- if (kb.matches(data, "tui.select.cancel") || kb.matches(data, "tui.select.up")) {- this.onCancel?.();+ if (!this.selectedId || !flat.some((entry) => entry.node.id === this.selectedId)) {+ this.selectedId = flat.find((entry) => entry.node.status === "running")?.node.id ?? flat[0]?.node.id;}}- private truncate(line: string, width: number): string {- return truncateToWidth(line, width, "");- }-- private renderCompactLine(line: string, width: number): string {- const panelWidth = Math.min(width, visibleWidth(line) + this.paddingX * 2);- const contentWidth = Math.max(1, panelWidth - this.paddingX * 2);- const truncated = this.truncate(line, contentWidth);- return `${" ".repeat(this.paddingX)}${truncated}${" ".repeat(Math.max(0, panelWidth - this.paddingX - visibleWidth(truncated)))}`;- }-- private renderSplitLine(left: string, right: string, width: number): string {- const contentWidth = Math.max(1, width - this.paddingX);- const gapWidth = left ? 2 : 0;- const leftWidth = visibleWidth(left);- const rightWidthLimit =- left && contentWidth > gapWidth && leftWidth + gapWidth + visibleWidth(right) > contentWidth- ? contentWidth - gapWidth - Math.min(leftWidth, Math.max(1, Math.floor((contentWidth - gapWidth) / 3)))- : contentWidth;- const renderedRight = this.truncate(right, Math.max(0, rightWidthLimit));- const rightWidth = visibleWidth(renderedRight);- const renderedLeftWidth = Math.max(0, contentWidth - rightWidth - gapWidth);- const renderedLeft = renderedLeftWidth > 0 ? this.truncate(left, renderedLeftWidth) : "";- const gap = Math.max(0, contentWidth - visibleWidth(renderedLeft) - rightWidth);- return `${" ".repeat(this.paddingX)}${renderedLeft}${" ".repeat(gap)}${renderedRight}`;+ setHidden(hidden: boolean): void {+ this.hidden = hidden;}- private subagentSummary(flat: readonly FlatChildAgentNode[], selected: boolean): string {- const running = countRunning(flat);- const summary =- running > 0- ? `${running} ${pluralize(running, "subagent")} running`- : `${flat.length} ${pluralize(flat.length, "subagent")}`;- const rendered = theme.bold(summary);- if (!selected) {- return rendered;+ selectNode(nodeId: string): void {+ if (flattenChildAgentNodes(this.nodes).some((entry) => entry.node.id === nodeId)) {+ this.selectedId = nodeId;}- return theme.bg("selectedBg", rendered);}- private summaryHint(): string {- return joinHints([keyAction("tui.select.confirm", "open")]);- }-}--export class ChildAgentInspectorComponent implements Component, Focusable {- focused = false;- private readonly paddingX = 1;- private nodes: readonly ChildAgentInspectorNode[] = [];- private selectedId: string | undefined;- private pendingKillId: string | undefined;- private killConfirmExpiresAt = 0;- private killConfirmTimer: ReturnType<typeof setTimeout> | undefined;-- onCancel?: () => void;- onOpenDetail?: (nodeId: string) => void;- onKill?: (nodeId: string) => void;-- constructor(- private readonly getViewportHeight: () => number = () => 0,- private readonly requestRender: () => void = () => {},- ) {}-- setNodes(nodes: readonly ChildAgentInspectorNode[]): void {- this.nodes = nodes;- const flat = this.flatten();- if (flat.length === 0) {- this.selectedId = undefined;- this.clearKillConfirmation({ render: false });- return;- }- if (!this.selectedId || !flat.some((entry) => entry.node.id === this.selectedId)) {- this.selectedId = flat.find((entry) => entry.node.status === "running")?.node.id ?? flat[0]?.node.id;- }+ hasNodes(): boolean {+ return flattenChildAgentNodes(this.nodes).length > 0;}invalidate(): void {@@ -373,106 +268,54 @@ export class ChildAgentInspectorComponent implements Component, Focusable {}render(width: number): string[] {- if (this.nodes.length === 0) {+ if (this.hidden) {return [];}const safeWidth = Math.max(1, width);- const lines = [theme.fg("borderMuted", "─".repeat(safeWidth))];- for (const line of this.renderList(safeWidth)) {- lines.push(this.panelLine(line.text, safeWidth, line.selected));- }+ const flat = flattenChildAgentNodes(this.nodes);+ const lines = [...this.renderInfoLine(safeWidth)];+ lines.push(...this.renderSubagentList(flat, safeWidth));return lines;}handleInput(data: string): void {const kb = getKeybindings();- const flat = this.flatten();- if (flat.length === 0) {+ const flat = flattenChildAgentNodes(this.nodes);+ const open = () => (this.selectedId ? this.onOpenDetail?.(this.selectedId) : this.onOpen?.());+ if (kb.matches(data, "tui.select.confirm") || kb.matches(data, "app.agents.open")) {+ open();return;}-- // Any input other than the kill key disarms the pending confirmation,- // matching the agents view delete flow.- if (!kb.matches(data, "app.agents.delete")) {- this.clearKillConfirmation({ render: false });- }if (kb.matches(data, "app.agents.back")) {- this.onCancel?.();+ this.onExit?.();return;}- if (kb.matches(data, "tui.select.confirm")) {- if (this.selectedId) {- this.onOpenDetail?.(this.selectedId);- }- return;- }- if (kb.matches(data, "app.agents.delete")) {- this.handleKillKey();+ if (kb.matches(data, "tui.select.down")) {+ this.moveSelection(1, flat);return;}if (kb.matches(data, "tui.select.up")) {- this.moveSelection(-1);- return;- }- if (kb.matches(data, "tui.select.down")) {- this.moveSelection(1);+ if (this.isAtFirstRow(flat)) {+ this.onCancel?.();+ } else {+ this.moveSelection(-1, flat);+ }return;}- if (kb.matches(data, "tui.select.pageUp")) {- this.moveSelection(-5);+ if (kb.matches(data, "tui.select.cancel")) {+ this.onCancel?.();return;}- if (kb.matches(data, "tui.select.pageDown")) {- this.moveSelection(5);- }+ // Keys the list doesn't own fall through to chat actions (expand tools, etc.).+ this.onChatAction?.(data);}- private renderList(width: number): InspectorLine[] {- const contentWidth = Math.max(1, width - this.paddingX * 2);- const flat = this.flatten();- const running = countRunning(flat);- const targetHeight = Math.max(0, this.getViewportHeight());- const lines: InspectorLine[] = [{ text: this.headerLine(running, flat.length, contentWidth), selected: false }];- const availableRows = targetHeight > 0 ? Math.max(0, targetHeight - 3) : flat.length;-- const selectedIndex = Math.max(- 0,- flat.findIndex((entry) => entry.node.id === this.selectedId),- );- const start = Math.max(0, Math.min(selectedIndex - Math.floor(availableRows / 2), flat.length - availableRows));- if (availableRows > 0) {- for (const entry of flat.slice(start, start + availableRows)) {- const selected = this.focused && entry.node.id === this.selectedId;- lines.push({ text: this.renderListEntry(entry, contentWidth), selected });- }- }- while (targetHeight > 0 && lines.length < targetHeight - 2) {- lines.push({ text: "", selected: false });- }- lines.push({ text: this.listHintLine(contentWidth), selected: false });- return lines;+ private isAtFirstRow(flat: readonly FlatChildAgentNode[]): boolean {+ return flat.length === 0 || flat[0]?.node.id === this.selectedId;}- private renderListEntry(entry: FlatChildAgentNode, width: number): string {- const indent = " ".repeat(Math.min(6, entry.depth * 2));- const rawIcon = childAgentStatusIcon(entry.node.status);- const icon = formatChildAgentStatusIcon(entry.node.status, rawIcon);- const timeWidth = 6;- const titleWidth = Math.max(0, width - visibleWidth(indent) - visibleWidth(rawIcon) - timeWidth - 2);- const pendingKill = this.isPendingKillNode(entry.node);- const title = pendingKill ? `${keyText("app.agents.delete").trim()} again to stop` : entry.node.label;- const titleCell = padTableCell(title, titleWidth);- const timeCell = padRightTableCell(formatChildAgentDuration(entry.node.durationMs), timeWidth);- const renderedTitleCell = pendingKill ? theme.fg("error", titleCell) : titleCell;- return this.truncate(`${indent}${icon} ${renderedTitleCell} ${timeCell}`, width, "");- }- private flatten(): FlatChildAgentNode[] {- return flattenChildAgentNodes(this.nodes);- }-- private moveSelection(delta: number): void {- const flat = this.flatten();+ private moveSelection(delta: number, flat: readonly FlatChildAgentNode[]): void {if (flat.length === 0) {return;}@@ -480,85 +323,226 @@ export class ChildAgentInspectorComponent implements Component, Focusable {0,flat.findIndex((entry) => entry.node.id === this.selectedId),);- const next = (current + delta + flat.length) % flat.length;+ const next = Math.max(0, Math.min(flat.length - 1, current + delta));this.selectedId = flat[next]?.node.id;}- private handleKillKey(): void {- const selected = this.flatten().find((entry) => entry.node.id === this.selectedId)?.node;- if (!selected || !isKillableChildAgentStatus(selected.status)) {- this.clearKillConfirmation({ render: false });- return;- }- if (this.pendingKillId === selected.id && this.isKillConfirmationVisible()) {- this.clearKillConfirmation({ render: false });- this.onKill?.(selected.id);- return;+ private renderInfoLine(width: number): string[] {+ const overrideLabel = this.getOverrideLabel()?.trim();+ const locationLabel = this.getLocationLabel()?.trim();+ const contextLabel = this.getContextLabel()?.trim();+ const override = overrideLabel ? theme.fg("muted", overrideLabel) : "";+ const location = !override && locationLabel ? theme.fg("muted", locationLabel) : "";+ const context = contextLabel ? theme.fg("muted", contextLabel) : "";+ const leftSegments = [override, location].filter((segment) => segment.length > 0);+ if (leftSegments.length === 0 && !context) {+ return [];}- this.showKillConfirmation(selected.id);- }- private isPendingKillNode(node: ChildAgentInspectorNode): boolean {- return (- node.id === this.pendingKillId && isKillableChildAgentStatus(node.status) && this.isKillConfirmationVisible()- );+ const rawLeft = leftSegments.join(theme.fg("dim", " "));+ const paddedLine = context+ ? this.renderSplitLine(rawLeft, context, width)+ : this.renderCompactLine(rawLeft, width);+ return [paddedLine];}- private showKillConfirmation(nodeId: string): void {- if (this.killConfirmTimer) {- clearTimeout(this.killConfirmTimer);+ private renderSubagentList(flat: readonly FlatChildAgentNode[], width: number): string[] {+ if (flat.length === 0) {+ return [];}- this.pendingKillId = nodeId;- this.killConfirmExpiresAt = Date.now() + KILL_CONFIRM_DURATION_MS;- this.killConfirmTimer = setTimeout(() => {- this.killConfirmTimer = undefined;- this.pendingKillId = undefined;- this.killConfirmExpiresAt = 0;- this.requestRender();- }, KILL_CONFIRM_DURATION_MS);- this.killConfirmTimer.unref?.();- this.requestRender();+ const contentWidth = Math.max(1, width - this.paddingX * 2);+ const selectedIndex = Math.max(+ 0,+ flat.findIndex((entry) => entry.node.id === this.selectedId),+ );+ const start = Math.max(+ 0,+ Math.min(selectedIndex - (SUMMARY_VISIBLE_ROWS - 1), flat.length - SUMMARY_VISIBLE_ROWS),+ );+ const clampedStart = Math.max(0, start);+ const window = flat.slice(clampedStart, clampedStart + SUMMARY_VISIBLE_ROWS);++ const labelWidth = `Subagent ${flat.length}`.length;+ const promptPrefix = this.sharedPromptPrefix(window);+ const promptSuffix = this.sharedPromptSuffix(window, promptPrefix);++ const lines: string[] = [theme.fg("borderMuted", "─".repeat(width))];+ for (const entry of window) {+ const selected = this.focused && entry.node.id === this.selectedId;+ const number = flat.indexOf(entry) + 1;+ lines.push(+ this.panelLine(+ this.renderListEntry(entry, number, labelWidth, promptPrefix, promptSuffix, contentWidth),+ width,+ selected,+ ),+ );+ }+ const scrollHint = this.scrollHint(flat.length, clampedStart, contentWidth);+ if (scrollHint) {+ lines.push(this.panelLine(scrollHint, width, false));+ }+ return lines;}- private clearKillConfirmation(options: { render?: boolean } = {}): void {- if (!this.killConfirmTimer && this.killConfirmExpiresAt === 0) {- return;+ // Only elide when the prefix is long enough and leaves a distinguishing tail.+ private sharedPromptPrefix(flat: readonly FlatChildAgentNode[]): string {+ if (flat.length < 2) {+ return "";}- if (this.killConfirmTimer) {- clearTimeout(this.killConfirmTimer);- this.killConfirmTimer = undefined;+ const labels = flat.map((entry) => entry.node.label);+ let prefix = labels[0] ?? "";+ for (const label of labels) {+ let i = 0;+ while (i < prefix.length && i < label.length && prefix[i] === label[i]) {+ i++;+ }+ prefix = prefix.slice(0, i);+ if (!prefix) {+ break;+ }}- this.pendingKillId = undefined;- this.killConfirmExpiresAt = 0;- if (options.render !== false) {- this.requestRender();+ const minTail = labels.some((label) => label.length <= prefix.length);+ return prefix.length >= SHARED_PREFIX_MIN && !minTail ? prefix : "";+ }++ // Common trailing run after the divergence, so the diff window can also drop a+ // shared tail. Only used when it leaves room past the prefix for a real diff.+ private sharedPromptSuffix(flat: readonly FlatChildAgentNode[], prefix: string): string {+ if (flat.length < 2 || !prefix) {+ return "";+ }+ const labels = flat.map((entry) => entry.node.label);+ let suffix = labels[0] ?? "";+ for (const label of labels) {+ let i = 0;+ while (+ i < suffix.length &&+ i < label.length &&+ suffix[suffix.length - 1 - i] === label[label.length - 1 - i]+ ) {+ i++;+ }+ suffix = suffix.slice(suffix.length - i);+ }+ // Keep the suffix clear of the prefix on every label so the diff survives.+ const safe = labels.every((label) => prefix.length + suffix.length < label.length);+ return safe && suffix.length >= SHARED_PREFIX_MIN ? suffix : "";+ }++ private renderListEntry(+ entry: FlatChildAgentNode,+ number: number,+ labelWidth: number,+ sharedPrefix: string,+ sharedSuffix: string,+ width: number,+ ): string {+ const indent = " ".repeat(SUMMARY_LIST_INDENT + Math.min(6, entry.depth * 2));+ // Running rows pulse the shared working glyph; other states stay static.+ const rawIcon =+ entry.node.status === "running"+ ? workingIconFrame(getWorkingPulseFrame())+ : childAgentStatusIcon(entry.node.status);+ const icon = formatChildAgentStatusIcon(entry.node.status, rawIcon);+ const numberCell = theme.fg("muted", padTableCell(`Subagent ${number}`, labelWidth));+ const time = formatChildAgentDuration(entry.node.durationMs);+ const timeWidth = 6;+ // Fixed columns consume: icon + space, the label gap, and a space before time.+ const fixed = visibleWidth(indent) + visibleWidth(rawIcon) + 1 + labelWidth + SUMMARY_LABEL_GAP + 1 + timeWidth;+ // The prompt may use all remaining space; the elision keeps it short and the+ // gap fill still right-aligns the time.+ const promptWidth = Math.max(0, width - fixed);+ const prompt = this.elidePrompt(entry.node.label, sharedPrefix, sharedSuffix, promptWidth);+ const promptCell = theme.fg("dim", prompt);+ const labelGap = " ".repeat(SUMMARY_LABEL_GAP);+ const fillWidth = Math.max(+ 0,+ width -+ visibleWidth(indent) -+ visibleWidth(rawIcon) -+ 1 -+ labelWidth -+ SUMMARY_LABEL_GAP -+ visibleWidth(prompt) -+ visibleWidth(time) -+ 1,+ );+ const fill = " ".repeat(fillWidth);+ const timeCell = theme.fg("muted", time);+ return `${indent}${icon} ${numberCell}${labelGap}${promptCell}${fill} ${timeCell}`;+ }++ // Coloring is applied by the caller so the trailing ellipsis matches the text.+ private elidePrompt(label: string, sharedPrefix: string, sharedSuffix: string, width: number): string {+ const text = this.elideAroundDiff(label, sharedPrefix, sharedSuffix);+ // Column-aware truncation (handles wide/combining chars), with the ellipsis+ // reserved inside the budget rather than appended past it.+ return truncateToWidth(text, Math.max(0, width), "…");+ }++ // Window the prompt around its divergence: "<leading context>…<~2 words before+ // the diff><diff><~2 words after the diff>…", dropping the shared head and tail.+ private elideAroundDiff(label: string, sharedPrefix: string, sharedSuffix: string): string {+ // Nothing useful to elide if the whole shared run fits in the leading window.+ if (!sharedPrefix || !label.startsWith(sharedPrefix) || sharedPrefix.length <= PROMPT_LEADING_CONTEXT) {+ return label;+ }+ // Snap the leading window to a word boundary so it doesn't cut mid-word.+ const leadSpace = label.lastIndexOf(" ", PROMPT_LEADING_CONTEXT);+ const lead = label.slice(0, leadSpace > 0 ? leadSpace : PROMPT_LEADING_CONTEXT).trimEnd();++ // Back the window start up a couple words before the divergence.+ let start = sharedPrefix.length;+ for (let words = 0; words < PROMPT_DIFF_CONTEXT_WORDS && start > 0; words++) {+ const prevSpace = label.lastIndexOf(" ", start - 2);+ if (prevSpace <= lead.length) {+ break;+ }+ start = prevSpace + 1;}- }- private isKillConfirmationVisible(): boolean {- return this.killConfirmExpiresAt > Date.now();- }+ // Advance the window end a couple words past where the labels re-converge.+ let end = label.length;+ if (sharedSuffix && label.endsWith(sharedSuffix)) {+ end = label.length - sharedSuffix.length;+ for (let words = 0; words < PROMPT_DIFF_CONTEXT_WORDS && end < label.length; words++) {+ const nextSpace = label.indexOf(" ", end + 1);+ if (nextSpace < 0) {+ end = label.length;+ break;+ }+ end = nextSpace;+ }+ }- private headerLine(running: number, total: number, width: number): string {- const left = theme.bold("subagents");- const right =- running > 0 ? theme.fg("muted", `${running} running · ${total} total`) : theme.fg("muted", `${total} total`);- const gap = " ".repeat(Math.max(1, width - visibleWidth(left) - visibleWidth(right)));- return this.truncate(`${left}${gap}${right}`, width);+ const middle = label.slice(start, end).trimEnd();+ const tail = end < label.length ? "…" : "";+ return `${lead}…${middle}${tail}`;}- private listHintLine(width: number): string {- const selected = this.flatten().find((entry) => entry.node.id === this.selectedId)?.node;- const killable = selected !== undefined && isKillableChildAgentStatus(selected.status);- return hintLine(- [- combinedKeyAction(["tui.select.up", "tui.select.down"], "move"),- keyAction("tui.select.confirm", "open"),- killable ? keyAction("app.agents.delete", "stop", { primaryOnly: true }) : undefined,- keyAction("app.agents.back", "back to chat", { primaryOnly: true }),- ],- width,- );+ private scrollHint(total: number, start: number, width: number): string | undefined {+ if (total <= SUMMARY_VISIBLE_ROWS) {+ return undefined;+ }+ const above = start;+ const below = total - (start + SUMMARY_VISIBLE_ROWS);+ const segments: string[] = [];+ if (above > 0) {+ segments.push(theme.fg("dim", `▴ ${above} above`));+ }+ if (below > 0) {+ segments.push(theme.fg("dim", `▾ ${below} below`));+ }+ const hint = this.focused+ ? joinHints([+ combinedKeyAction(["tui.select.up", "tui.select.down"], "scroll"),+ keyAction("tui.select.confirm", "open"),+ ])+ : "";+ const left = segments.join(theme.fg("dim", " · "));+ const body = hint ? `${left}${theme.fg("dim", " ")}${hint}` : left;+ return this.truncate(`${" ".repeat(SUMMARY_LIST_INDENT)}${body}`, width);}private panelLine(line: string, width: number, selected: boolean): string {@@ -569,8 +553,31 @@ export class ChildAgentInspectorComponent implements Component, Focusable {return selected ? theme.bg("selectedBg", padded) : padded;}- private truncate(line: string, width: number, ellipsis = ""): string {- return truncateToWidth(line, width, ellipsis);+ private truncate(line: string, width: number): string {+ return truncateToWidth(line, width, "");+ }++ private renderCompactLine(line: string, width: number): string {+ const panelWidth = Math.min(width, visibleWidth(line) + this.paddingX * 2);+ const contentWidth = Math.max(1, panelWidth - this.paddingX * 2);+ const truncated = this.truncate(line, contentWidth);+ return `${" ".repeat(this.paddingX)}${truncated}${" ".repeat(Math.max(0, panelWidth - this.paddingX - visibleWidth(truncated)))}`;+ }++ private renderSplitLine(left: string, right: string, width: number): string {+ const contentWidth = Math.max(1, width - this.paddingX);+ const gapWidth = left ? 2 : 0;+ const leftWidth = visibleWidth(left);+ const rightWidthLimit =+ left && contentWidth > gapWidth && leftWidth + gapWidth + visibleWidth(right) > contentWidth+ ? contentWidth - gapWidth - Math.min(leftWidth, Math.max(1, Math.floor((contentWidth - gapWidth) / 3)))+ : contentWidth;+ const renderedRight = this.truncate(right, Math.max(0, rightWidthLimit));+ const rightWidth = visibleWidth(renderedRight);+ const renderedLeftWidth = Math.max(0, contentWidth - rightWidth - gapWidth);+ const renderedLeft = renderedLeftWidth > 0 ? this.truncate(left, renderedLeftWidth) : "";+ const gap = Math.max(0, contentWidth - visibleWidth(renderedLeft) - rightWidth);+ return `${" ".repeat(this.paddingX)}${renderedLeft}${" ".repeat(gap)}${renderedRight}`;}}@@ -838,7 +845,7 @@ export class ChildAgentDetailComponent implements Component, Focusable {? theme.fg("error", `${keyText("app.agents.delete", { primaryOnly: true }).trim()} again to stop`): keyAction("app.agents.delete", "stop", { primaryOnly: true });return hintLine(- [keyAction("app.agents.back", "back to subagents", { primaryOnly: true }), expandAction, stopAction],+ [keyAction("app.agents.back", "back to chat", { primaryOnly: true }), expandAction, stopAction],width,);}diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.tsindex 743b129719..ec593a7a8e 100644--- a/packages/coding-agent/src/modes/interactive/components/index.ts+++ b/packages/coding-agent/src/modes/interactive/components/index.ts@@ -6,7 +6,6 @@ export { BorderedLoader } from "./bordered-loader.js";export { BranchSummaryMessageComponent } from "./branch-summary-message.js";export {ChildAgentDetailComponent,- ChildAgentInspectorComponent,type ChildAgentInspectorNode,type ChildAgentStatus,ChildAgentSummaryComponent,diff --git a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts b/packages/coding-agent/src/modes/interactive/components/ipython-cell.tsindex af6ef9ad34..858ae17f40 100644--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts@@ -9,6 +9,7 @@ import {import { generateDiffString } from "../../../core/tools/edit-diff.js";import { shortenPath } from "../../../core/tools/render-utils.js";import { getLanguageFromPath, highlightCode, theme } from "../theme/theme.js";+import { getWorkingPulseFrame, WORKING_ICON_FRAMES, workingIconFrame } from "../theme/working-icon.js";import { normalizeErrorDetails, summarizeErrorDetails } from "./collapsible-error.js";import { renderDiffSeparator, renderRichDiff } from "./diff.js";import { keyHint } from "./keybinding-hints.js";@@ -328,13 +329,19 @@ export class IPythonCellComponent implements Component {render(width: number): string[] {const safeWidth = Math.max(1, width);- const cached = this.renderCache.get(safeWidth, this.stateVersion);+ const details = readDetails(this.state.details);+ // Fold the animation frame into the cache key while running (offset within+ // a stateVersion slot so it never collides with another version).+ const frames = WORKING_ICON_FRAMES.length;+ const cacheVersion =+ this.statusKind(details) === "running"+ ? this.stateVersion * frames + (getWorkingPulseFrame() % frames)+ : this.stateVersion * frames;+ const cached = this.renderCache.get(safeWidth, cacheVersion);if (cached) {return cached;}- const details = readDetails(this.state.details);-// Collapsed default: one line, indented to match message text. Cached by// state version so it never re-renders on unrelated repaints (would flicker).// Edits are the exception: the diff always shows in full under the summary@@ -342,11 +349,11 @@ export class IPythonCellComponent implements Component {if (!this.state.expanded) {const summary = truncateToWidth(` ${this.collapsedLine(details)}`, safeWidth, "");if ((details.diffs?.length ?? 0) === 0) {- return this.renderCache.set(safeWidth, this.stateVersion, [summary]);+ return this.renderCache.set(safeWidth, cacheVersion, [summary]);}const lines = [summary];this.renderDiffs(lines, safeWidth, details.diffs ?? [], this.marker(details));- return this.renderCache.set(safeWidth, this.stateVersion, lines);+ return this.renderCache.set(safeWidth, cacheVersion, lines);}const lines: string[] = [];@@ -363,7 +370,7 @@ export class IPythonCellComponent implements Component {lines.push(toolPanelLine(this.header(details), safeWidth));const hasCode = this.renderCode(lines, safeWidth, withExpandHint, hasDiffs);this.renderOutput(lines, safeWidth, details, hasCode, withExpandHint);- return this.renderCache.set(safeWidth, this.stateVersion, lines);+ return this.renderCache.set(safeWidth, cacheVersion, lines);}// Command is bash-only: python first-lines are usually imports/setup, not intent.@@ -410,7 +417,7 @@ export class IPythonCellComponent implements Component {case "done":return theme.fg("success", "✓");case "running":- return theme.fg("bashMode", "▸");+ return theme.fg("bashMode", workingIconFrame(getWorkingPulseFrame()));default: // queuedreturn theme.fg("muted", "▸");}diff --git a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts b/packages/coding-agent/src/modes/interactive/components/tool-execution.tsindex 5a4259051b..2447e5bbd7 100644--- a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts+++ b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts@@ -6,6 +6,7 @@ import { getTextOutput as getRenderedTextOutput } from "../../../core/tools/rendimport { convertToPng } from "../../../utils/image-convert.js";import type { AgentConnectionToolDefinition } from "../../agent-connection/index.js";import { type Theme, theme } from "../theme/theme.js";+import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";import { getIpythonCodeFromArgs, IPythonCellComponent } from "./ipython-cell.js";import { ToolPanel } from "./tool-panel.js";@@ -245,9 +246,29 @@ export class ToolExecutionComponent extends Container {if (this.hideComponent) {return [];}+ // Refresh the animated glyph without rebuilding the whole panel, for as long+ // as panelStatus() is still animating (including partial streaming results).+ if (this.isStatusAnimating() && !this.usesSelfRenderShell()) {+ this.contentPanel.setHeader(this.panelHeader());+ }return super.render(width);}+ private isStatusAnimating(): boolean {+ if (!this.executionStarted) {+ return false;+ }+ // Matches panelStatus(): animating until a non-partial or error result lands.+ if (this.result && !this.isPartial) {+ return false;+ }+ return !this.result?.isError;+ }++ private usesSelfRenderShell(): boolean {+ return this.hasRendererDefinition() && this.getRenderShell() === "self";+ }+private updateDisplay(): void {let hasContent = false;this.hideComponent = false;@@ -408,7 +429,7 @@ export class ToolExecutionComponent extends Container {return theme.fg("error", "error");}if (this.executionStarted) {- return theme.fg("bashMode", "running");+ return theme.fg("bashMode", `${workingIconFrame(getWorkingPulseFrame())} running`);}return theme.fg("muted", "queued");}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex f9fa4a2bf0..4263a319ab 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -133,7 +133,6 @@ import { BranchSummaryMessageComponent } from "./components/branch-summary-messaimport { showFullPaneOverlay } from "./components/centered-overlay.js";import {ChildAgentDetailComponent,- ChildAgentInspectorComponent,type ChildAgentInspectorNode,type ChildAgentStructuredTranscriptEntry,ChildAgentSummaryComponent,@@ -191,6 +190,7 @@ import {type ThemeColor,theme,} from "./theme/theme.js";+import { setWorkingPulseFrame, WORKING_ICON_INTERVAL_MS } from "./theme/working-icon.js";/** Interface for components that can be expanded/collapsed */interface Expandable {@@ -516,6 +516,8 @@ export class InteractiveMode {private workingIndicatorOptions: LoaderIndicatorOptions | undefined = undefined;private workingStartedAt: number | undefined = undefined;private workingTimer: NodeJS.Timeout | undefined = undefined;+ private pulseTimer: NodeJS.Timeout | undefined = undefined;+ private pulseFrame = 0;private readonly activityTracker = new AgentActivityTracker();private readonly defaultHiddenThinkingLabel = "Thinking...";private hiddenThinkingLabel = this.defaultHiddenThinkingLabel;@@ -548,14 +550,13 @@ export class InteractiveMode {private pendingToolGeneration = 0;private toolDefinitionCache = new Map<string, ToolExecutionDefinition | undefined>();- // RLM child-agent tray: compact entry below the editor, bounded list/detail in the main view.+ // RLM child-agent tray: inline list below the editor, full-screen detail on open.private childAgentSummary: ChildAgentSummaryComponent;- private childAgentInspector: ChildAgentInspectorComponent;private childAgentDetail: ChildAgentDetailComponent;private childAgentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();private childAgentNodes: ChildAgentInspectorNode[] = [];private childAgentDetailNodeId: string | undefined;- private childAgentPanelMode: "list" | "detail" | undefined;+ private childAgentPanelMode: "detail" | undefined;// Tool output expansion stateprivate toolOutputExpanded = false;@@ -664,13 +665,6 @@ export class InteractiveMode {this.pendingMessagesContainer = new Container();this.statusContainer = new Container();this.queuedMessagesContainer = new Container();- this.childAgentInspector = new ChildAgentInspectorComponent(- () => this.getChildAgentPanelRows(),- () => this.ui.requestRender(),- );- this.childAgentInspector.onCancel = () => this.closeChildAgentPanel();- this.childAgentInspector.onOpenDetail = (nodeId) => this.openChildAgentDetail(nodeId);- this.childAgentInspector.onKill = (nodeId) => void this.killChildAgent(nodeId);this.childAgentDetail = new ChildAgentDetailComponent(() => this.getChildAgentPanelRows(), {ui: this.ui,getCwd: () => this.getCurrentCwd(),@@ -684,7 +678,7 @@ export class InteractiveMode {getHideThinkingBlock: () => this.hideThinkingBlock,getHiddenThinkingLabel: () => this.hiddenThinkingLabel,});- this.childAgentDetail.onCancel = () => this.showChildAgentList();+ this.childAgentDetail.onCancel = () => this.closeChildAgentPanel({ selectNodeId: this.childAgentDetailNodeId });this.childAgentDetail.onToggleToolsExpanded = () => this.toggleToolOutputExpansion();this.childAgentDetail.onKill = (nodeId) => void this.killChildAgent(nodeId);this.widgetContainerAbove = new Container();@@ -710,8 +704,12 @@ export class InteractiveMode {() => this.getTrayContextLabel(),() => this.getTrayOverrideLabel(),);- this.childAgentSummary.onOpen = () => this.openChildAgentList();+ this.childAgentSummary.onOpenDetail = (nodeId) => this.openChildAgentDetail(nodeId);+ // Fallback for Enter when the list emptied out while focused (no selection).+ this.childAgentSummary.onOpen = () => this.focusEditor();this.childAgentSummary.onCancel = () => this.focusEditor();+ this.childAgentSummary.onExit = () => this.handleSubagentSummaryExit();+ this.childAgentSummary.onChatAction = (data) => this.handleSubagentSummaryChatAction(data);this.footerDataProvider = new FooterDataProvider(this.uiServices.getInitialCwd());this.footer = new FooterComponent(this.footerDataProvider);this.footer.setAutoCompactEnabled(this.settingsManager.getCompactionEnabled());@@ -1990,6 +1988,7 @@ export class InteractiveMode {this.footer.setAutoCompactEnabled(state.autoCompactionEnabled);this.sessionRecap = state.recap;this.renderRecap();+ this.updateWorkingPulse();}private patchConnectionState(patch: Partial<AgentConnectionState>): void {@@ -1997,6 +1996,7 @@ export class InteractiveMode {return;}this.connectionState = { ...this.connectionState, ...patch };+ this.updateWorkingPulse();}private updateConnectionStateFromEvent(event: AgentConnectionSessionEvent): void {@@ -2116,6 +2116,7 @@ export class InteractiveMode {this.updateTerminalTitle();this.setGoalAnnouncementBaseline(this.getGoalState());this.syncGoalTray(this.getGoalState());+ this.syncWorkingLoader();}private async handleFatalRuntimeError(prefix: string, error: unknown): Promise<never> {@@ -2168,6 +2169,7 @@ export class InteractiveMode {private async renderCurrentSessionState(): Promise<void> {this.resetCurrentSessionRenderState();await this.renderInitialMessages();+ this.syncWorkingLoader();}private getCachedToolDefinition(toolName: string): ToolExecutionDefinition | undefined {@@ -2359,12 +2361,23 @@ export class InteractiveMode {this.workingStartedAt === undefined? undefined: this.formatWorkingElapsed(Date.now() - this.workingStartedAt);+ const status = this.activityTracker.getStatus();+ const runningSubagents = this.countRunningChildAgents();+ // Subagents-only (turn ended, subagents still running): just the count, no+ // elapsed timer (it resets on view return) and no stale extension message.+ if (!this.isAgentStreaming()) {+ return runningSubagents > 0+ ? `${runningSubagents} ${runningSubagents === 1 ? "subagent" : "subagents"} running`+ : "";+ }if (this.workingMessage !== undefined) {// Extensions and tool bootstrap own the message; keep the plain "<message> <elapsed>" form.return elapsed === undefined ? this.workingMessage : `${this.workingMessage} ${elapsed}`;}- const status = this.activityTracker.getStatus();- const parts = [AGENT_ACTIVITY_LABELS[status.activity]];+ const parts: string[] = [AGENT_ACTIVITY_LABELS[status.activity]];+ if (runningSubagents > 0) {+ parts.push(`${runningSubagents} ${runningSubagents === 1 ? "subagent" : "subagents"} running`);+ }if (elapsed !== undefined) {parts.push(elapsed);}@@ -2427,6 +2440,65 @@ export class InteractiveMode {this.statusContainer.clear();}+ private updateWorkingPulse(): void {+ const active = this.isAgentStreaming() || this.countRunningChildAgents() > 0;+ if (!active) {+ this.stopWorkingPulse();+ return;+ }+ if (!this.pulseTimer) {+ this.pulseTimer = setInterval(() => this.tickWorkingPulse(), WORKING_ICON_INTERVAL_MS);+ this.pulseTimer.unref?.();+ }+ }++ private tickWorkingPulse(): void {+ this.pulseFrame += 1;+ setWorkingPulseFrame(this.pulseFrame);+ this.ui.requestRender();+ }++ private stopWorkingPulse(): void {+ if (this.pulseTimer) {+ clearInterval(this.pulseTimer);+ this.pulseTimer = undefined;+ }+ }++ private countRunningChildAgents(): number {+ let count = 0;+ for (const child of this.childAgentSnapshots.values()) {+ if (child.status === "running") {+ count += 1;+ }+ }+ return count;+ }++ private shouldShowWorkingLoader(): boolean {+ return this.workingVisible && (this.isAgentStreaming() || this.countRunningChildAgents() > 0);+ }++ // Reconcile the loader with current state for transitions that fire no live+ // agent_start edge (returning from agents view, resuming mid-stream).+ private syncWorkingLoader(): void {+ // Compaction/retry own the status container while active; don't fight them.+ if (this.autoCompactionLoader || this.retryLoader) {+ return;+ }+ if (this.shouldShowWorkingLoader()) {+ // A bare `loadingAnimation != null` check isn't proof it's on screen:+ // other paths clear statusContainer without nulling it, orphaning the+ // loader. Re-attach unless it is actually mounted.+ if (!this.loadingAnimation || !this.statusContainer.children.includes(this.loadingAnimation)) {+ this.startWorkingLoader();+ }+ } else if (this.loadingAnimation) {+ this.stopWorkingLoader();+ }+ this.ui.requestRender();+ }+private setWorkingVisible(visible: boolean): void {this.workingVisible = visible;if (!visible) {@@ -2434,7 +2506,7 @@ export class InteractiveMode {this.ui.requestRender();return;}- if (this.isAgentStreaming() && !this.loadingAnimation) {+ if (this.shouldShowWorkingLoader() && !this.loadingAnimation) {this.statusContainer.clear();this.startWorkingLoader();}@@ -3143,7 +3215,7 @@ export class InteractiveMode {this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());- this.defaultEditor.onAction("app.subagents.focus", () => this.focusChildAgentInspector());+ this.defaultEditor.onAction("app.subagents.focus", () => this.focusChildAgentSummary());this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());this.defaultEditor.onAction("app.message.dequeue", () => {@@ -3930,7 +4002,8 @@ export class InteractiveMode {if (this.settingsManager.getShowTerminalProgress()) {this.ui.terminal.setProgress(false);}- this.stopWorkingLoader();+ // Keep the loader up if async subagents outlive the parent turn.+ this.syncWorkingLoader();if (this.streamingComponent) {if (this.streamingMessage) {this.streamingComponent.updateContent(this.streamingMessage);@@ -3953,6 +4026,8 @@ export class InteractiveMode {this.ui.terminal.setProgress(true);}// Keep editor active; submissions are queued during compaction.+ // Fully stop the working loader (not just detach) so it isn't orphaned.+ this.stopWorkingLoader();this.statusContainer.clear();const cancelHint = `(${keyText("app.clear")} to cancel)`;const focus = event.customInstructions@@ -3982,6 +4057,8 @@ export class InteractiveMode {this.autoCompactionLoader = undefined;this.statusContainer.clear();}+ // Restore the working loader if streaming/subagents still warrant it.+ this.syncWorkingLoader();if (event.aborted) {if (event.reason === "manual") {this.showError("Compaction cancelled");@@ -4017,6 +4094,7 @@ export class InteractiveMode {case "auto_retry_start": {// Show retry indicator+ this.stopWorkingLoader();this.statusContainer.clear();this.retryCountdown?.dispose();const retryMessage = (seconds: number) =>@@ -4053,6 +4131,8 @@ export class InteractiveMode {this.retryLoader = undefined;this.statusContainer.clear();}+ // Restore the working loader if streaming/subagents still warrant it.+ this.syncWorkingLoader();// Show error only on final failure (success shows normal response)if (!event.success) {this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);@@ -4247,19 +4327,17 @@ export class InteractiveMode {}this.childAgentNodes = this.buildChildAgentInspectorNodes();this.childAgentSummary.setNodes(this.childAgentNodes);- this.childAgentInspector.setNodes(this.childAgentNodes);+ this.updateWorkingPulse();+ this.syncWorkingLoader();+ this.updateWorkingLoaderMessage();if (this.childAgentDetailNodeId) {const detailNode = this.findChildAgentInspectorNode(this.childAgentDetailNodeId);if (!detailNode && this.childAgentPanelMode === "detail") {- this.showChildAgentList();+ this.closeChildAgentPanel();return;}this.childAgentDetail.setNode(detailNode);}- if (this.childAgentPanelMode === "list" && this.childAgentNodes.length === 0) {- this.closeChildAgentPanel();- return;- }this.ui.requestRender();}@@ -4284,12 +4362,15 @@ export class InteractiveMode {this.childAgentNodes = [];this.childAgentSummary.setNodes([]);this.childAgentSummary.setHidden(false);- this.childAgentInspector.setNodes([]);this.childAgentDetail.setNode(undefined);this.childAgentDetailNodeId = undefined;if (this.childAgentPanelMode) {this.closeChildAgentPanel();}+ // Clearing snapshots can drop the last running subagent; reconcile the+ // pulse and loader so neither lingers when nothing is in flight.+ this.updateWorkingPulse();+ this.syncWorkingLoader();}private getChildAgentPanelRows(): number {@@ -4311,6 +4392,28 @@ export class InteractiveMode {return true;}+ // Left from the focused subagent list: exit to manage sessions if available,+ // otherwise just drop focus back to the editor.+ private handleSubagentSummaryExit(): void {+ if (this.options.returnToAgentsView && !this.editor.getText().trim()) {+ void this.returnToAgentsView();+ return;+ }+ this.focusEditor();+ }++ // Chat actions stay live while the subagent list holds focus; the editor's+ // own handlers are bypassed because input routes only to the focused list.+ private handleSubagentSummaryChatAction(data: string): void {+ if (this.keybindings.matches(data, "app.tools.expand")) {+ this.toggleToolOutputExpansion();+ return;+ }+ if (this.keybindings.matches(data, "app.thinking.toggle")) {+ this.toggleThinkingBlockVisibility();+ }+ }+private getTrayOverrideLabel(): string | undefined {if (this.isCtrlCExitHintVisible()) {const clearKey = keyText("app.clear");@@ -4336,7 +4439,7 @@ export class InteractiveMode {if (this.editor.getText().trim()) {return undefined;}- return keyHint("app.agents.back", "agents");+ return keyHint("app.agents.back", "manage sessions");}private getTrayContextLabel(): string | undefined {@@ -4388,13 +4491,6 @@ export class InteractiveMode {return `${hours}h ${remainingMinutes.toString().padStart(2, "0")}m`;}- private openChildAgentList(): void {- if (this.childAgentNodes.length === 0) {- return;- }- this.showChildAgentList();- }-private async killChildAgent(nodeId: string): Promise<void> {try {const cancelled = await this.agentConnection.cancelRlmChild(nodeId);@@ -4407,24 +4503,6 @@ export class InteractiveMode {this.ui.requestRender();}- private showChildAgentList(): void {- if (this.childAgentNodes.length === 0) {- this.closeChildAgentPanel();- return;- }- this.childAgentPanelMode = "list";- this.childAgentDetailNodeId = undefined;- this.childAgentDetail.setNode(undefined);- this.childAgentSummary.setHidden(true);- this.childAgentInspector.setNodes(this.childAgentNodes);- this.editorContainer.clear();- this.queuedMessagesContainer.clear();- this.mainViewContainer.clear();- this.mainViewContainer.addChild(this.childAgentInspector);- this.ui.setFocus(this.childAgentInspector);- this.ui.requestRender();- }-private openChildAgentDetail(nodeId: string): boolean {const node = this.findChildAgentInspectorNode(nodeId);if (!node) {@@ -4443,14 +4521,7 @@ export class InteractiveMode {return true;}- private focusChildAgentInspector(): void {- if (this.childAgentNodes.length === 0) {- return;- }- this.showChildAgentList();- }-- private closeChildAgentPanel(): void {+ private closeChildAgentPanel(options: { selectNodeId?: string } = {}): void {this.childAgentPanelMode = undefined;this.childAgentDetailNodeId = undefined;this.childAgentDetail.setNode(undefined);@@ -4460,7 +4531,14 @@ export class InteractiveMode {this.updatePendingMessagesDisplay();this.editorContainer.clear();this.editorContainer.addChild(this.editor);- this.ui.setFocus(this.editor);+ // Returning from a subagent's detail keeps that subagent selected in the+ // inline list; other closes drop back to the editor.+ if (options.selectNodeId && this.childAgentSummary.hasNodes()) {+ this.childAgentSummary.selectNode(options.selectNodeId);+ this.ui.setFocus(this.childAgentSummary);+ } else {+ this.ui.setFocus(this.editor);+ }this.ui.requestRender();}@@ -7292,6 +7370,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}| \`${this.ui.terminal.setProgress(false);}this.stopWorkingLoader();+ this.stopWorkingPulse();this.stopGoalTrayTimer();this.clearExtensionTerminalInputListeners();this.footer.dispose();diff --git a/packages/coding-agent/src/modes/interactive/theme/working-icon.ts b/packages/coding-agent/src/modes/interactive/theme/working-icon.tsnew file mode 100644index 0000000000..be57b900b0--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/theme/working-icon.ts@@ -0,0 +1,21 @@+// Shared "still working" indicator used across the agents view, the chat+// subagent tray, and in-progress tool markers so motion reads consistently.+export const WORKING_ICON_FRAMES = ["◇", "◈", "◆", "◈"] as const;+export const WORKING_ICON_INTERVAL_MS = 250;++export function workingIconFrame(frame: number): string {+ const frames = WORKING_ICON_FRAMES;+ return frames[((frame % frames.length) + frames.length) % frames.length] ?? frames[0];+}++// Process-wide frame counter for in-place chat tool markers, advanced by the+// interactive mode's single ticker and read during render.+let pulseFrame = 0;++export function getWorkingPulseFrame(): number {+ return pulseFrame;+}++export function setWorkingPulseFrame(frame: number): void {+ pulseFrame = frame;+}diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.tsnew file mode 100644index 0000000000..602c924c63--- /dev/null+++ b/packages/coding-agent/test/child-agent-summary-list.test.ts@@ -0,0 +1,182 @@+import { visibleWidth } from "@earendil-works/pi-tui";+import { beforeAll, describe, expect, it } from "vitest";+import {+ type ChildAgentInspectorNode,+ ChildAgentSummaryComponent,+} from "../src/modes/interactive/components/child-agent-inspector.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";+import { setWorkingPulseFrame, workingIconFrame } from "../src/modes/interactive/theme/working-icon.js";++function stripAnsi(text: string): string {+ return text.replace(/\x1b\[[0-9;]*m/g, "");+}++function node(id: string, status: ChildAgentInspectorNode["status"] = "running"): ChildAgentInspectorNode {+ return { id, label: id, status, sessionDir: `/tmp/${id}`, transcript: [] };+}++describe("ChildAgentSummaryComponent inline list", () => {+ beforeAll(() => {+ initTheme("dark");+ });++ it("renders one row per subagent when within the cap", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([node("alpha"), node("beta")]);+ const out = stripAnsi(summary.render(80).join("\n"));+ expect(out).toContain("alpha");+ expect(out).toContain("beta");+ expect(out).not.toMatch(/more (above|below)/);+ });++ it("caps the list at five rows and shows a scroll indicator", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f"), node("g")]);+ const lines = summary.render(80).map(stripAnsi);+ // Row lines carry a status glyph; the scroll-hint line does not.+ const rowLines = lines.filter((line) => /[◇◈◆✓✗]/.test(line));+ expect(rowLines.length).toBe(5);+ expect(lines.join("\n")).toContain("2 below");+ });++ it("scrolls the window and updates the indicator as selection moves down", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.focused = true;+ summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f"), node("g")]);+ // Drive selection past the initial window via the down key.+ for (let i = 0; i < 6; i++) {+ summary.handleInput("\x1b[B");+ }+ const out = summary.render(80).map(stripAnsi).join("\n");+ expect(out).toContain("g");+ expect(out).toContain("above");+ });++ it("animates the running row glyph across pulse frames", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([node("a", "running")]);+ setWorkingPulseFrame(0);+ const frame0 = stripAnsi(summary.render(80).join("\n"));+ setWorkingPulseFrame(1);+ const frame1 = stripAnsi(summary.render(80).join("\n"));+ expect(frame0).toContain(workingIconFrame(0));+ expect(frame1).toContain(workingIconFrame(1));+ expect(frame0).not.toBe(frame1);+ });++ it("can reselect a node by id when returning from its detail view", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.focused = true;+ summary.setNodes([node("a"), node("b"), node("c")]);+ summary.selectNode("c");+ let opened: string | undefined;+ summary.onOpenDetail = (id) => {+ opened = id;+ };+ summary.handleInput("\r");+ expect(opened).toBe("c");+ });++ it("prefixes rows with a fixed-width Subagent N column", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([node("first task"), node("second task")]);+ const out = stripAnsi(summary.render(80).join("\n"));+ expect(out).toContain("Subagent 1");+ expect(out).toContain("Subagent 2");+ });++ it("never exceeds the row width with wide (CJK) characters", () => {+ const wide = "実行するタスクは非常に長い説明を含んでいてこれは折り返しのテストです".repeat(3);+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([{ ...node("a"), label: wide }]);+ for (const width of [40, 60, 80]) {+ for (const line of summary.render(width)) {+ expect(visibleWidth(line)).toBeLessThanOrEqual(width);+ }+ }+ });++ it("elides a shared prompt prefix so rows surface where they differ", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([+ { ...node("a"), label: "Refactor the authentication module for tokens" },+ { ...node("b"), label: "Refactor the authentication module for refresh" },+ ]);+ const out = stripAnsi(summary.render(120).join("\n"));+ // The shared prefix is replaced by an ellipsis; the differing tail survives.+ expect(out).toContain("…");+ expect(out).not.toContain("Refactor the authentication module for tokens");+ });++ it("surfaces the divergence even when the shared prefix is very long", () => {+ const prefix = "You are a sleeper subagent in a parallel batch. Please sleep for exactly ";+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([+ { ...node("a"), label: `${prefix}30 seconds then report done` },+ { ...node("b"), label: `${prefix}120 seconds then report done` },+ ]);+ const out = stripAnsi(summary.render(130).join("\n"));+ expect(out).toContain("30 seconds");+ expect(out).toContain("120 seconds");+ });++ it("windows tightly around the diff when prompts share a head and tail", () => {+ const head =+ "Hello there. You are a subagent and we give subagents different tasks. Your task is to sleep since you are subagent ";+ const tail = " and therefore you were assigned to sleep ten minutes total today";+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([+ { ...node("a"), label: `${head}#1${tail}` },+ { ...node("b"), label: `${head}#2${tail}` },+ ]);+ const out = stripAnsi(summary.render(120).join("\n"));+ expect(out).toContain("#1");+ expect(out).toContain("#2");+ // The shared tail is dropped behind a trailing ellipsis, not shown in full.+ expect(out).not.toContain("assigned to sleep ten minutes total today");+ });++ it("forwards unhandled keys to the chat action callback", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.focused = true;+ summary.setNodes([node("a")]);+ let forwarded: string | undefined;+ summary.onChatAction = (data) => {+ forwarded = data;+ };+ // Ctrl+O isn't a list key, so it should bubble to the chat action handler.+ summary.handleInput("\x0f");+ expect(forwarded).toBe("\x0f");+ });++ it("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;+ summary.setNodes([node("a"), node("b")]);+ let opened: string | undefined;+ summary.onOpenDetail = (id) => {+ opened = id;+ };+ summary.handleInput("\r");+ expect(opened).toBe("a");+ });++ it("falls back to onOpen when confirm is pressed with no selection", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.focused = true;+ summary.setNodes([]); // list emptied while focused: no selection+ let fellBack = false;+ summary.onOpen = () => {+ fellBack = true;+ };+ summary.handleInput("\r");+ expect(fellBack).toBe(true);+ });+});diff --git a/packages/coding-agent/test/interactive-mode-compaction.test.ts b/packages/coding-agent/test/interactive-mode-compaction.test.tsindex db1edcf2ad..2f89468738 100644--- a/packages/coding-agent/test/interactive-mode-compaction.test.ts+++ b/packages/coding-agent/test/interactive-mode-compaction.test.ts@@ -11,6 +11,8 @@ describe("InteractiveMode compaction events", () => {activityTracker: new AgentActivityTracker(),updateWorkingLoaderMessage: vi.fn(),autoCompactionLoader: undefined,+ retryLoader: undefined,+ syncWorkingLoader: vi.fn(),defaultEditor: {},statusContainer: { clear: vi.fn() },chatContainer: { clear: vi.fn() },diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.tsindex 3835015634..2e264a871b 100644--- a/packages/coding-agent/test/marquee-components.test.ts+++ b/packages/coding-agent/test/marquee-components.test.ts@@ -7,7 +7,6 @@ import { KeybindingsManager } from "../src/core/keybindings.js";import { AssistantMessageComponent } from "../src/modes/interactive/components/assistant-message.js";import {ChildAgentDetailComponent,- ChildAgentInspectorComponent,type ChildAgentInspectorNode,ChildAgentSummaryComponent,} from "../src/modes/interactive/components/child-agent-inspector.js";@@ -464,12 +463,11 @@ describe("marquee TUI components", () => {expect(short).not.toContain("Ctrl+O to expand");});- test("renders child agent summary and bounded inspector list", () => {+ test("renders child agent summary inline list and detail view", () => {const summary = new ChildAgentSummaryComponent(() => "agents-sidebar",() => "37% context left",);- const component = new ChildAgentInspectorComponent();const node: ChildAgentInspectorNode = {id: "sub-a",label: "inspect training logs",@@ -520,73 +518,27 @@ describe("marquee TUI components", () => {],};summary.setNodes([node]);- component.setNodes([node]);- const summaryText = stripAnsi(summary.render(60).join("\n"));+ // The info line carries location/context; the list renders the subagents+ // below a separator, with the time pinned at the right edge.+ const summaryLines = summary.render(90).map(stripAnsi);+ const summaryText = summaryLines.join("\n");expect(summaryText).toContain("agents-sidebar");expect(summaryText).toContain("37% context left");- expect(summaryText).toContain("1 subagent running");- expect(summaryText).not.toContain("2 total");- expect(summary.render(60)).toHaveLength(1);+ 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);summary.focused = true;- const focusedSummary = stripAnsi(summary.render(60).join("\n"));- expect(focusedSummary).toContain("agents-sidebar");- expect(focusedSummary).toContain("37% context left");- expect(focusedSummary).toContain("1 subagent running");- expect(focusedSummary).not.toContain("▌");- const focusedSummaryWide = stripAnsi(summary.render(96).join("\n"));- expect(focusedSummaryWide).toContain("Enter open");- expect(focusedSummaryWide).not.toContain("editor");- expect(focusedSummaryWide).not.toContain("ctrl+c");- const summaryRow = summary.render(60).at(-1) ?? "";- expect(visibleWidth(summaryRow)).toBe(60);- expect(stripAnsi(summaryRow).endsWith("37% context left")).toBe(true);-- const queueSummary = new ChildAgentSummaryComponent(- () => "agents-sidebar",- () => "37% context left",- () => "alt+enter to queue message",- );- queueSummary.setNodes([node]);- const queueText = stripAnsi(queueSummary.render(60).join("\n"));- expect(queueText).toContain("alt+enter to queue message");- expect(queueText).toContain("37% context left");- expect(queueText).not.toContain("1 subagent running");- expect(queueSummary.render(60)).toHaveLength(1);-- const compact = stripAnsi(component.render(42).join("\n"));- expect(compact).toContain("subagents");- expect(compact).toContain("─");- expect(visibleWidth(component.render(42)[0] ?? "")).toBe(42);- expect(compact).toContain("1 running · 2 total");- expect(compact).toContain("◆ inspect training logs");- expect(compact).toContain("✓ check shard 2");- expect(compact).not.toContain("└─");- expect(compact).not.toContain("├─");- expect(compact).not.toContain("assistant: reading shard metrics");- const wideList = stripAnsi(component.render(96).join("\n"));- expect(wideList).toContain("↑/↓ move");- expect(wideList).toContain("Enter open");- expect(wideList).toContain("← back to chat");- expect(wideList).not.toContain("ctrl+c close");- for (const line of component.render(96)) {- expect(visibleWidth(line)).toBe(96);- }-- component.focused = true;- const focused = stripAnsi(component.render(42).join("\n"));- expect(focused).not.toContain("▌");- expect(focused).toContain("◆ inspect training logs");- expect(focused).not.toContain("assistant: reading shard metrics");-let openedNodeId: string | undefined;- component.onOpenDetail = (nodeId) => {+ summary.onOpenDetail = (nodeId) => {openedNodeId = nodeId;};- component.handleInput("\r");+ // Right opens the selected subagent, like Enter.+ summary.handleInput("\x1b[C");expect(openedNodeId).toBe("sub-a");- expect(stripAnsi(component.render(42).join("\n"))).not.toContain("assistant: reading shard metrics");const detailComponent = new ChildAgentDetailComponent(() => 20);detailComponent.setNode(node);@@ -599,23 +551,10 @@ describe("marquee TUI components", () => {expect(detail).toContain("reading shard metrics");expect(detail).toContain("$ echo hi");expect(detail).toContain("hi");- expect(detail).toContain("← back to subagents");+ 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");-- component.handleInput("\x1b");- const returned = stripAnsi(component.render(42).join("\n"));- expect(returned).not.toContain("▌");- expect(returned).toContain("◆ inspect training logs");- expect(returned).not.toContain("assistant: reading shard metrics");-- for (const line of component.render(42)) {- expect(visibleWidth(line)).toBeLessThanOrEqual(42);- }-- const narrow = stripAnsi(component.render(24).join("\n"));- expect(narrow).toContain("◆ inspect train");});test("collapses multiline child agent system errors in detail view", () => {@@ -747,12 +686,13 @@ describe("marquee TUI components", () => {},]);- const row = summary.render(32)[0] ?? "";- const text = stripAnsi(row);+ const lines = summary.render(32);+ const infoRow = lines[0] ?? "";- expect(visibleWidth(row)).toBe(32);- expect(text).toContain("1 sub");- expect(text).toContain("Pursuing goal");+ expect(visibleWidth(infoRow)).toBe(32);+ expect(stripAnsi(infoRow)).toContain("Pursuing goal");+ // The subagent itself renders as a list row below the info line.+ expect(stripAnsi(lines.join("\n"))).toContain("Subagent 1");});test("renders full child agent detail without internal scroll controls", () => {@@ -772,7 +712,7 @@ describe("marquee TUI components", () => {const first = stripAnsi(firstLines.join("\n"));expect(first).toContain("fallback transcript row 01");expect(first).toContain("fallback transcript row 12");- expect(first).toContain("← back to subagents");+ expect(first).toContain("← back to chat");expect(first).not.toContain("↑");expect(first).not.toContain("↓");expect(firstLines.length).toBeGreaterThan(6);diff --git a/packages/coding-agent/test/tool-execution-component.test.ts b/packages/coding-agent/test/tool-execution-component.test.tsindex 8071932788..42d0bf3247 100644--- a/packages/coding-agent/test/tool-execution-component.test.ts+++ b/packages/coding-agent/test/tool-execution-component.test.ts@@ -7,6 +7,7 @@ import { type BashOperations, createBashTool, createBashToolDefinition } from ".import { createEditToolDefinition } from "../src/core/tools/edit.js";import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";import { initTheme } from "../src/modes/interactive/theme/theme.js";+import { getWorkingPulseFrame, workingIconFrame } from "../src/modes/interactive/theme/working-icon.js";function createBaseToolDefinition(name = "custom_tool"): ToolDefinition {return {@@ -287,7 +288,10 @@ describe("ToolExecutionComponent parity", () => {expect(stripAnsi(component.render(100).join("\n"))).toContain("bash · queued");component.markExecutionStarted();- expect(stripAnsi(component.render(100).join("\n"))).toContain("bash · running");+ // Running status leads with the animated working glyph for the current frame.+ expect(stripAnsi(component.render(100).join("\n"))).toContain(+ `bash · ${workingIconFrame(getWorkingPulseFrame())} running`,+ );component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);const lines = component.render(100);diff --git a/packages/coding-agent/test/working-icon-animation.test.ts b/packages/coding-agent/test/working-icon-animation.test.tsnew file mode 100644index 0000000000..95f14a328e--- /dev/null+++ b/packages/coding-agent/test/working-icon-animation.test.ts@@ -0,0 +1,52 @@+import { beforeAll, describe, expect, it } from "vitest";+import { IPythonCellComponent } from "../src/modes/interactive/components/ipython-cell.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";+import {+ setWorkingPulseFrame,+ WORKING_ICON_FRAMES,+ workingIconFrame,+} from "../src/modes/interactive/theme/working-icon.js";++function stripAnsi(text: string): string {+ return text.replace(/\x1b\[[0-9;]*m/g, "");+}++describe("workingIconFrame", () => {+ it("cycles through the frames and wraps in both directions", () => {+ for (let i = 0; i < WORKING_ICON_FRAMES.length; i++) {+ expect(workingIconFrame(i)).toBe(WORKING_ICON_FRAMES[i]);+ }+ expect(workingIconFrame(WORKING_ICON_FRAMES.length)).toBe(WORKING_ICON_FRAMES[0]);+ expect(workingIconFrame(-1)).toBe(WORKING_ICON_FRAMES[WORKING_ICON_FRAMES.length - 1]);+ });+});++describe("IPythonCellComponent running marker", () => {+ beforeAll(() => {+ initTheme("dark");+ });++ it("animates the marker while running and stays static once done", () => {+ const running = new IPythonCellComponent({ code: "print(1)", executionStarted: true, isPartial: true });+ setWorkingPulseFrame(0);+ const frame0 = stripAnsi(running.render(80).join("\n"));+ setWorkingPulseFrame(1);+ const frame1 = stripAnsi(running.render(80).join("\n"));+ expect(frame0).toContain(workingIconFrame(0));+ expect(frame1).toContain(workingIconFrame(1));+ expect(frame0).not.toBe(frame1);++ const done = new IPythonCellComponent({+ code: "print(1)",+ executionStarted: true,+ isPartial: false,+ details: { status: "ok", result: "1" },+ });+ setWorkingPulseFrame(0);+ const doneFrame0 = stripAnsi(done.render(80).join("\n"));+ setWorkingPulseFrame(1);+ const doneFrame1 = stripAnsi(done.render(80).join("\n"));+ expect(doneFrame0).toBe(doneFrame1);+ expect(doneFrame0).toContain("✓");+ });+});