A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): independently expand/collapse tool calls, a2a messages, & thinking (#767)
Sebastian Müllerd1b072686d6b
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex f0ec06063b..4ed805b0d7 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,9 @@## [Unreleased]+- Added `app.messages.expand` (`ctrl+p`) to collapse or expand agent-to-agent messages separately from `ctrl+o` tool output.+- Added a `ctrl+t` expand hint to collapsed thinking blocks, matching the tool output hint.+- Changed expand/collapse hints to a consistent bracketed `(Ctrl+O to expand)` style across tool, message, summary, and error rows.- Added a configurable copy action to login dialogs so raw sign-in URLs can be copied without selecting wrapped text ([#643](https://github.com/PrimeIntellect-ai/prime-agent/issues/643)).- Added privacy-safe pseudonymous product analytics for onboarding, command use, execution modes, run outcomes, TTFT, latency, usage, tools, retries, and compactions, with disclosure and opt-out controls ([ENG-4682](https://linear.app/primeintellect/issue/ENG-4682/add-privacy-safe-posthog-analytics-to-prime-agent)).- Changed sent agent messages in the IPython cell UI to show only the message text with a `╰─` gutter when expanded, matching received messages, and hid the raw `agent_message.send` receipt dictionary.diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.mdindex 2f21fc7c85..1db87a4cd5 100644--- a/packages/coding-agent/docs/keybindings.md+++ b/packages/coding-agent/docs/keybindings.md@@ -130,6 +130,7 @@ Use `tab` to cycle forward and `shift+tab` to cycle backward through Providers,| Keybinding id | Default | Description ||--------|---------|-------------|| `app.tools.expand` | `ctrl+o` | Collapse or expand tool output |+| `app.messages.expand` | `ctrl+p` | Collapse or expand agent-to-agent messages || `app.message.followUp` | `alt+enter` | Queue follow-up message || `app.message.dequeue` | `alt+up` | Restore queued messages to editor |@@ -180,6 +181,8 @@ On native Windows, `app.suspend` has no default binding because Windows terminal### Emacs Example+Binding `ctrl+p` below releases the conflicting `app.messages.expand` default; shortcuts in other views keep their defaults.+```json{"tui.editor.cursorUp": ["up", "ctrl+p"],diff --git a/packages/coding-agent/src/core/extensions/runner.ts b/packages/coding-agent/src/core/extensions/runner.tsindex c087f0d22d..17cc02e561 100644--- a/packages/coding-agent/src/core/extensions/runner.ts+++ b/packages/coding-agent/src/core/extensions/runner.ts@@ -66,6 +66,7 @@ const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = ["app.suspend","app.model.select","app.tools.expand",+ "app.messages.expand","app.thinking.toggle","app.subagents.focus","app.editor.external",diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.tsindex a880b56320..77a9a4912b 100644--- a/packages/coding-agent/src/core/keybindings.ts+++ b/packages/coding-agent/src/core/keybindings.ts@@ -21,6 +21,7 @@ export interface AppKeybindings {"app.model.toggleScope": true;"app.configuration.previousTab": true;"app.tools.expand": true;+ "app.messages.expand": true;"app.thinking.toggle": true;"app.subagents.focus": true;"app.heartbeats.open": true;@@ -82,10 +83,16 @@ export const KEYBINDINGS = {"app.model.select": { defaultKeys: "ctrl+l", description: "Open model selector" },"app.model.toggleScope": { defaultKeys: "alt+s", description: "Toggle model selector scope" },"app.configuration.previousTab": { defaultKeys: "shift+tab", description: "Select previous configuration tab" },- "app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output" },+ "app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output", defaultKeyScope: "editor" },+ "app.messages.expand": {+ defaultKeys: "ctrl+p",+ description: "Toggle agent message expansion",+ defaultKeyScope: "editor",+ },"app.thinking.toggle": {defaultKeys: "ctrl+t",description: "Toggle thinking blocks",+ defaultKeyScope: "editor",},"app.subagents.focus": {defaultKeys: "alt+a",diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.tsindex efc260eae1..8329572ce7 100644--- a/packages/coding-agent/src/core/tools/bash.ts+++ b/packages/coding-agent/src/core/tools/bash.ts@@ -3,7 +3,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";import { Container, Text, truncateToWidth } from "@earendil-works/pi-tui";import { spawn } from "child_process";import { type Static, Type } from "typebox";-import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";+import { expandCollapseHint } from "../../modes/interactive/components/keybinding-hints.js";import { truncateToVisualLines } from "../../modes/interactive/components/visual-truncate.js";import { theme } from "../../modes/interactive/theme/theme.js";import { waitForChildProcess } from "../../utils/child-process.js";@@ -232,8 +232,7 @@ function rebuildBashResultRenderComponent(}if (state.cachedSkipped && state.cachedSkipped > 0) {const hint = showExpandHint- ? theme.fg("muted", `... (${state.cachedSkipped} earlier lines,`) +- ` ${keyHint("app.tools.expand", "to expand")})`+ ? `${theme.fg("muted", `... ${state.cachedSkipped} earlier lines`)} ${expandCollapseHint("app.tools.expand", false)}`: theme.fg("muted", `... (${state.cachedSkipped} earlier lines)`);return ["", truncateToWidth(hint, width, "..."), ...(state.cachedLines ?? [])];}diff --git a/packages/coding-agent/src/core/tools/edit.ts b/packages/coding-agent/src/core/tools/edit.tsindex 746d89da62..2582ead14a 100644--- a/packages/coding-agent/src/core/tools/edit.ts+++ b/packages/coding-agent/src/core/tools/edit.ts@@ -4,7 +4,7 @@ import { constants } from "fs";import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";import { type Static, Type } from "typebox";import { renderDiff } from "../../modes/interactive/components/diff.js";-import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";+import { expandCollapseHint } from "../../modes/interactive/components/keybinding-hints.js";import type { ToolDefinition } from "../extensions/types.js";import {applyEditsToNormalizedContent,@@ -259,9 +259,7 @@ function buildEditCallComponent(component.clear();const canExpand = component.preview !== undefined && !("error" in component.preview);const expandHint =- canExpand && showExpandHint- ? `${theme.fg("dim", " · ")}${keyHint("app.tools.expand", expanded ? "to collapse" : "to expand")}`- : "";+ canExpand && showExpandHint ? `${theme.fg("dim", " · ")}${expandCollapseHint("app.tools.expand", expanded)}` : "";component.addChild(new Text(`${formatEditCall(args, theme)}${expandHint}`, 0, 0));const body =diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex b22701bbcb..4b0d834ccc 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -592,6 +592,7 @@ export class DaemonSupervisor {private readonly clients = new Set<DaemonSocketClient>();private readonly protocolClientIds = new WeakMap<DaemonSocketClient, string>();private readonly workers = new Map<string, ResidentWorker>();+ private workerStopCounts?: Map<ResidentWorker, number>;private readonly openingWorkers = new Map<string, Promise<ResidentWorker>>();/** Public admission ids are scoped to the socket that registered them. */private readonly promptAdmissions = new Map<DaemonSocketClient, Map<string, SupervisorPromptAdmission>>();@@ -1548,6 +1549,9 @@ export class DaemonSupervisor {);const worker = direct ?? (await this.findWorkerForClient(client, command.activeSessionId)).worker;this.assertWorkerAccessibleToClient(client, worker, command.activeSessionId);+ if ((this.workerStopCounts?.get(worker) ?? 0) > 0) {+ throw new Error("Session worker is stopping; retry after it finishes");+ }worker.intentionalStop = false;worker.descriptor.stopRequestedAt = undefined;worker.descriptor.archiveOnStop = undefined;@@ -4507,6 +4511,26 @@ export class DaemonSupervisor {archiveSession = false,recoveryCleanup = false,directChild?: { child: ChildProcess; closed: Promise<void> },+ ): Promise<void> {+ if (!this.workerStopCounts) this.workerStopCounts = new Map();+ const stopCounts = this.workerStopCounts;+ stopCounts.set(worker, (stopCounts.get(worker) ?? 0) + 1);+ try {+ await this.stopWorkerUntracked(worker, removeDescriptor, force, archiveSession, recoveryCleanup, directChild);+ } finally {+ const remaining = (stopCounts.get(worker) ?? 1) - 1;+ if (remaining === 0) stopCounts.delete(worker);+ else stopCounts.set(worker, remaining);+ }+ }++ private async stopWorkerUntracked(+ worker: ResidentWorker,+ removeDescriptor: boolean,+ force = false,+ archiveSession = false,+ recoveryCleanup = false,+ directChild?: { child: ChildProcess; closed: Promise<void> },): Promise<void> {if (worker.ownerCleanupTimer) {clearTimeout(worker.ownerCleanupTimer);diff --git a/packages/coding-agent/src/modes/interactive/components/agent-message.ts b/packages/coding-agent/src/modes/interactive/components/agent-message.tsindex 532b1eef11..cf6845a495 100644--- a/packages/coding-agent/src/modes/interactive/components/agent-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/agent-message.ts@@ -10,7 +10,7 @@ import {} from "@earendil-works/pi-tui";import { type AgentSessionMessage, formatAgentMessageParticipant } from "../../../core/agent-messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";-import { keyText } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";function collapseText(text: string): string {return text.replace(/\s+/g, " ").trim();@@ -99,13 +99,13 @@ export class AgentMessageComponent extends Container {this.message.details.fromRelationship,this.message.details.from,);+ const hint = expandCollapseHint("app.messages.expand", this.expanded);if (this.expanded) {- return agentMessageSummaryLine(label, participant);+ return `${agentMessageSummaryLine(label, participant)} ${hint}`;}const prefixWidth = visibleWidth(`◆ ${label} · ${participant} · `);const preview = agentMessagePreview(prefixWidth, this.message.details.message);- const hint = theme.fg("dim", ` (${keyText("app.tools.expand")} to expand)`);- return `${agentMessageSummaryLine(label, participant, preview)}${hint}`;+ return `${agentMessageSummaryLine(label, participant, preview)} ${hint}`;}}diff --git a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts b/packages/coding-agent/src/modes/interactive/components/assistant-message.tsindex 9a40769790..522969cbc0 100644--- a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts@@ -1,5 +1,14 @@import type { AssistantMessage } from "@earendil-works/pi-ai";-import { type Component, Container, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";+import {+ type Component,+ Container,+ Markdown,+ type MarkdownTheme,+ Spacer,+ Text,+ truncateToWidth,+ visibleWidth,+} from "@earendil-works/pi-tui";import { LOGIN_RECOVERY_MESSAGE } from "../../../core/auth-guidance.js";import { getMarkdownTheme, theme } from "../theme/theme.js";import {@@ -8,6 +17,7 @@ import {shouldCollapseErrorDetails,summarizeErrorDetails,} from "./collapsible-error.js";+import { expandCollapseHint } from "./keybinding-hints.js";const OSC133_ZONE_START = "\x1b]133;A\x07";const OSC133_ZONE_END = "\x1b]133;B\x07";@@ -37,6 +47,49 @@ function getThinkingMarkdownTheme(baseTheme: MarkdownTheme): MarkdownTheme {};}+/** Single collapsed-thinking row that truncates the recap to the render width instead of wrapping. */+class CollapsedThinkingRow implements Component {+ constructor(+ private readonly label: string,+ private readonly recap: string,+ private readonly hint: string,+ ) {}++ render(width: number): string[] {+ const safeWidth = Math.max(1, width);+ const separator = theme.fg("dim", " · ");+ const fixedWidth = visibleWidth(` ${this.label}${separator} ${this.hint}`);+ const recapWidth = Math.max(8, safeWidth - fixedWidth);+ const recap = theme.fg("thinkingText", truncateToWidth(this.recap, recapWidth));+ return [truncateToWidth(` ${this.label}${separator}${recap} ${this.hint}`, safeWidth, "")];+ }++ invalidate(): void {}+}++/**+ * One-line recap for a collapsed thinking block: the last bold section header+ * when the trace has one (reasoning summaries usually do), otherwise the first+ * non-empty line, stripped of markdown emphasis and truncated.+ */+export function thinkingRecap(thinking: string, fallback: string, maxWidth = 120): string {+ const lines = thinking+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ const lastHeader = [...lines].reverse().find((line) => /^\*\*[^*]+\*\*:?$/.test(line) || /^#{1,6}\s+\S/.test(line));+ const source = lastHeader ?? lines[0] ?? fallback;+ const plain = source+ .replace(/^#{1,6}\s+/, "")+ .replace(/\*\*([^*]+)\*\*/g, "$1")+ .replace(/\*([^*]+)\*/g, "$1")+ .replace(/`([^`]+)`/g, "$1")+ .replace(/\s+/g, " ")+ .replace(/:$/, "")+ .trim();+ return truncateToWidth(plain || fallback, Math.max(20, maxWidth));+}+function formatInlineLoginRecoveryMessage(message: string): string | undefined {const normalized = normalizeErrorDetails(message);if (!normalized.endsWith(LOGIN_RECOVERY_SUFFIX)) {@@ -154,6 +207,12 @@ export class AssistantMessageComponent extends Container {parts.push(`${i}:text:${content.text.trim() ? 1 : 0}`);} else if (content.type === "thinking") {parts.push(`${i}:thinking:${content.thinking.trim() ? 1 : 0}`);+ if (this.hideThinkingBlock && content.thinking.trim()) {+ // The collapsed row bakes the recap into a static line, so a recap+ // change must count as a structural change during streaming.+ // JSON-encode the free text so it cannot forge part boundaries.+ parts.push(`${i}:recap:${JSON.stringify(thinkingRecap(content.thinking, this.hiddenThinkingLabel))}`);+ }} else {parts.push(`${i}:${content.type}`);}@@ -224,16 +283,24 @@ export class AssistantMessageComponent extends Container {.slice(i + 1).some((c) => (c.type === "text" && c.text.trim()) || (c.type === "thinking" && c.thinking.trim()));+ const thinkingLabel = theme.bold(theme.fg("thinkingText", this.hiddenThinkingLabel));if (this.hideThinkingBlock) {- // Show static thinking label when hidden+ // Collapsed row: bold label, a one-line recap of the trace, and the+ // hint. The row truncates the recap to the render width so it never+ // wraps onto a second line on narrow terminals.+ const recap = thinkingRecap(content.thinking, this.hiddenThinkingLabel);this.contentContainer.addChild(- new Text(theme.italic(theme.fg("thinkingText", this.hiddenThinkingLabel)), 1, 0),+ new CollapsedThinkingRow(thinkingLabel, recap, expandCollapseHint("app.thinking.toggle", false)),);if (hasVisibleContentAfter) {this.contentContainer.addChild(new Spacer(1));}} else {+ // Expanded: the same label line with the collapse hint, then the trace.// Thinking traces keep Markdown structure but stay visually quiet.+ this.contentContainer.addChild(+ new Text(`${thinkingLabel} ${expandCollapseHint("app.thinking.toggle", true)}`, 1, 0),+ );const markdown = new Markdown(content.thinking.trim(),1,diff --git a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts b/packages/coding-agent/src/modes/interactive/components/bash-execution.tsindex 28a43d0b99..661bbfe8c6 100644--- a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts+++ b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts@@ -12,7 +12,7 @@ import {} from "../../../core/tools/truncate.js";import { theme } from "../theme/theme.js";import { DynamicBorder } from "./dynamic-border.js";-import { keyHint, keyText } from "./keybinding-hints.js";+import { expandCollapseHint, keyText } from "./keybinding-hints.js";import { truncateToVisualLines } from "./visual-truncate.js";// Preview line limit when not expanded (matches tool execution behavior)@@ -185,10 +185,10 @@ export class BashExecutionComponent extends Container {// Show how many lines are hidden (collapsed preview)if (hiddenLineCount > 0) {if (this.expanded) {- statusParts.push(`(${keyHint("app.tools.expand", "to collapse")})`);+ statusParts.push(expandCollapseHint("app.tools.expand", true));} else {statusParts.push(- `${theme.fg("muted", `... ${hiddenLineCount} more lines`)} (${keyHint("app.tools.expand", "to expand")})`,+ `${theme.fg("muted", `... ${hiddenLineCount} more lines`)} ${expandCollapseHint("app.tools.expand", false)}`,);}}diff --git a/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts b/packages/coding-agent/src/modes/interactive/components/branch-summary-message.tsindex b140f49688..1aa49bb7a8 100644--- a/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts@@ -1,7 +1,7 @@import { Box, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";import type { BranchSummaryMessage } from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";-import { keyText } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";/*** Component that renders a branch summary message with collapsed/expanded state.@@ -46,9 +46,7 @@ export class BranchSummaryMessageComponent extends Box {} else {this.addChild(new Text(- theme.fg("customMessageText", "Branch summary (") +- theme.fg("dim", keyText("app.tools.expand")) +- theme.fg("customMessageText", " to expand)"),+ `${theme.fg("customMessageText", "Branch summary")} ${expandCollapseHint("app.tools.expand", false)}`,0,0,),diff --git a/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts b/packages/coding-agent/src/modes/interactive/components/collapsible-error.tsindex 11e29cdaae..247b260e5f 100644--- a/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts+++ b/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts@@ -1,7 +1,7 @@import { type Component, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { theme } from "../theme/theme.js";-import { keyHint } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";export interface CollapsibleErrorOptions {text: string;@@ -102,7 +102,7 @@ export class CollapsibleErrorComponent implements Component {}const summary = normalizeErrorDetails(this.options.summary ?? summarizeErrorDetails(text));- const inlineHint = `${summary} ${theme.fg("dim", "·")} ${keyHint("app.tools.expand", "to expand")}`;+ const inlineHint = `${summary} ${expandCollapseHint("app.tools.expand", false)}`;return this.renderText(inlineHint, width, "error");}diff --git a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.tsindex ef7788c54e..24164a157d 100644--- a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts@@ -1,7 +1,7 @@import { Box, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";import type { CompactionSummaryMessage } from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";-import { keyText } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";/*** Component that renders a compaction message with collapsed/expanded state.@@ -52,9 +52,7 @@ export class CompactionSummaryMessageComponent extends Box {const focus = instructions ? ` · focus: ${instructions}` : "";this.addChild(new Text(- theme.fg("customMessageText", `Compacted from ${tokenStr} tokens${focus} (`) +- theme.fg("dim", keyText("app.tools.expand")) +- theme.fg("customMessageText", " to expand)"),+ `${theme.fg("customMessageText", `Compacted from ${tokenStr} tokens${focus}`)} ${expandCollapseHint("app.tools.expand", false)}`,0,0,),diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.tsindex deb58575cd..4b032b2585 100644--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts@@ -37,6 +37,7 @@ export interface ConversationComponentsOptions {hideThinkingBlock?: boolean;hiddenThinkingLabel?: string;toolsExpanded?: boolean;+ agentMessagesExpanded?: boolean;isRecognizedSlashCommand?: (name: string) => boolean;}@@ -69,6 +70,7 @@ export function buildConversationComponents(const components: Component[] = [];const pendingTools = new Map<string, ToolExecutionComponent>();const expanded = options.toolsExpanded ?? false;+ const agentMessagesExpanded = options.agentMessagesExpanded ?? false;for (const message of messages) {if (message.role === "assistant") {@@ -140,7 +142,7 @@ export function buildConversationComponents(const component = new AgentMessageComponent(message, options.markdownTheme, {suppressLeadingSpace: isCompactAgentMessageNeighbor(components.at(-1)),});- component.setExpanded(expanded);+ component.setExpanded(agentMessagesExpanded);components.push(component);} else if (isInjectedPromptMessage(message) && message.display) {const component = new InjectedPromptMessageComponent(message, options.markdownTheme);diff --git a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.tsindex 450b376383..eec0e2428d 100644--- a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts@@ -21,7 +21,7 @@ import {type RlmChildTerminalNoticeDetails,} from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";-import { keyText } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";type InjectedPromptDetails =| GoalContextDetails@@ -134,14 +134,14 @@ export class InjectedPromptMessageComponent extends Container {this.message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE ||this.message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE) {- const hint = this.expanded ? "" : ` (${keyText("app.tools.expand")} to expand)`;+ const hint = this.expanded ? "" : ` ${expandCollapseHint("app.tools.expand", false)}`;return theme.fg("muted", "RLM child status") + theme.fg("dim", hint);}const details = this.message.details;const title = goalLabel(details as GoalContextDetails | undefined);const meta = this.metaText();- const hint = this.expanded ? "" : ` (${keyText("app.tools.expand")} to expand)`;+ const hint = this.expanded ? "" : ` ${expandCollapseHint("app.tools.expand", false)}`;return theme.fg("muted", title) + meta + theme.fg("dim", hint);}@@ -149,7 +149,7 @@ export class InjectedPromptMessageComponent extends Container {const details = this.message.details as HeartbeatPromptDetails | undefined;const pulse = theme.fg("error", "♥");const schedule = theme.fg("muted", heartbeatPromptSchedule(details?.schedule));- const hint = this.expanded ? "" : ` (${keyText("app.tools.expand")} to expand)`;+ const hint = this.expanded ? "" : ` ${expandCollapseHint("app.tools.expand", false)}`;return `${pulse} ${theme.fg("muted", "Heartbeat prompt")}${theme.fg("dim", " · ")}${schedule}${theme.fg("dim", hint)}`;}diff --git a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts b/packages/coding-agent/src/modes/interactive/components/ipython-cell.tsindex ff9cf98be2..d1703ff33d 100644--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts@@ -16,7 +16,7 @@ import { getWorkingPulseFrame, WORKING_ICON_FRAMES, workingIconFrame } from "../import { agentMessageBodyLines, agentMessagePreview, agentMessageSummaryLine } from "./agent-message.js";import { normalizeErrorDetails, summarizeErrorDetails } from "./collapsible-error.js";import { renderDiffSeparator, renderRichDiff } from "./diff.js";-import { keyHint } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";export interface IPythonCellContentBlock {type: string;@@ -426,7 +426,7 @@ export class IPythonCellComponent implements Component {}if (this.state.showExpandHint !== false) {- parts.push(keyHint("app.tools.expand", this.state.expanded ? "to collapse" : "to expand"));+ parts.push(expandCollapseHint("app.tools.expand", this.state.expanded === true));}return parts.join(theme.fg("dim", " · "));}diff --git a/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts b/packages/coding-agent/src/modes/interactive/components/keybinding-hints.tsindex c0e0db2552..22d681d7c1 100644--- a/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts+++ b/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts@@ -66,6 +66,11 @@ export function keyHint(keybinding: Keybinding, description: string, options: Kereturn theme.fg("dim", keyText(keybinding, options)) + theme.fg("muted", ` ${description}`);}+/** Canonical bracketed expand/collapse hint, e.g. `(Ctrl+O to expand)`, fully dim. */+export function expandCollapseHint(keybinding: Keybinding, expanded: boolean): string {+ return theme.fg("dim", `(${keyText(keybinding)} ${expanded ? "to collapse" : "to expand"})`);+}+export function rawKeyHint(key: string, description: string): string {return theme.fg("dim", formatKeyText(key)) + theme.fg("muted", ` ${description}`);}diff --git a/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts b/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.tsindex 66b024164c..c5491eb795 100644--- a/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts@@ -1,7 +1,7 @@import { Box, Markdown, type MarkdownTheme, Text } from "@earendil-works/pi-tui";import type { ParsedSkillBlock } from "../../../core/skill-blocks.js";import { getMarkdownTheme, theme } from "../theme/theme.js";-import { keyText } from "./keybinding-hints.js";+import { expandCollapseHint } from "./keybinding-hints.js";/*** Component that renders a skill invocation message with collapsed/expanded state.@@ -48,7 +48,7 @@ export class SkillInvocationMessageComponent extends Box {const line =theme.fg("customMessageLabel", `\x1b[1m[skill]\x1b[22m `) +theme.fg("customMessageText", this.skillBlock.name) +- theme.fg("dim", ` (${keyText("app.tools.expand")} to expand)`);+ ` ${expandCollapseHint("app.tools.expand", false)}`;this.addChild(new Text(line, 0, 0));}}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 0ec1d8bcd7..50207b73ea 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -947,6 +947,7 @@ export class InteractiveMode {// Tool output expansion stateprivate toolOutputExpanded = false;+ private agentMessagesExpanded = false;// Thinking block visibility stateprivate hideThinkingBlock = false;@@ -1370,6 +1371,7 @@ export class InteractiveMode {rawKeyHint("/effort", "to set thinking level"),hint("app.model.select", "to select model"),hint("app.tools.expand", "to expand tools"),+ hint("app.messages.expand", "to expand agent messages"),hint("app.thinking.toggle", "to expand thinking"),hint("app.subagents.focus", "to inspect subagents"),hint("app.editor.external", "for external editor"),@@ -4136,6 +4138,7 @@ export class InteractiveMode {};this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());+ this.defaultEditor.onAction("app.messages.expand", () => this.toggleAgentMessageExpansion());this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());this.defaultEditor.onAction("app.subagents.focus", () => this.focusSubagentSummary());this.defaultEditor.onAction("app.heartbeats.open", () => {@@ -5941,6 +5944,10 @@ export class InteractiveMode {this.toggleToolOutputExpansion();return;}+ if (this.keybindings.matches(data, "app.messages.expand")) {+ this.toggleAgentMessageExpansion();+ return;+ }if (this.keybindings.matches(data, "app.thinking.toggle")) {this.toggleThinkingBlockVisibility();return;@@ -6248,7 +6255,7 @@ export class InteractiveMode {this.getMarkdownThemeWithSettings(),);if (!(component instanceof UserMessageComponent)) {- component.setExpanded(this.toolOutputExpanded);+ component.setExpanded(this.expansionStateFor(component));}if (isSessionSlashCommandMessage(message) && this.chatContainer.children.length > 0) {this.chatContainer.addChild(new Spacer(1));@@ -6981,15 +6988,29 @@ export class InteractiveMode {this.setToolsExpanded(!this.toolOutputExpanded);}+ private toggleAgentMessageExpansion(): void {+ this.agentMessagesExpanded = !this.agentMessagesExpanded;+ this.applyChatExpansion();+ }+private setToolsExpanded(expanded: boolean): void {this.toolOutputExpanded = expanded;+ this.applyChatExpansion();+ }++ /** Expansion state for a chat component: agent messages toggle separately from tools. */+ private expansionStateFor(component: unknown): boolean {+ return component instanceof AgentMessageComponent ? this.agentMessagesExpanded : this.toolOutputExpanded;+ }++ private applyChatExpansion(): void {const activeHeader = this.customHeader ?? this.builtInHeader;if (isExpandable(activeHeader)) {- activeHeader.setExpanded(expanded);+ activeHeader.setExpanded(this.toolOutputExpanded);}for (const child of this.chatContainer.children) {if (isExpandable(child)) {- child.setExpanded(expanded);+ child.setExpanded(this.expansionStateFor(child));}}// Expanding/collapsing changes blocks above the viewport, which would@@ -9440,6 +9461,7 @@ export class InteractiveMode {const shortcutsKey = this.getAppKeyDisplay("app.shortcuts");const selectModel = this.getAppKeyDisplay("app.model.select");const expandTools = this.getAppKeyDisplay("app.tools.expand");+ const expandMessages = this.getAppKeyDisplay("app.messages.expand");const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");const externalEditor = this.getAppKeyDisplay("app.editor.external");const promptStash = this.getAppKeyDisplay("app.prompt.stash");@@ -9453,7 +9475,7 @@ export class InteractiveMode {**Controls**\`${selectModel}\` select model · \`/effort\` set reasoning · \`${expandTools}\` tool output-\`${toggleThinking}\` thinking blocks · \`${promptStash}\` stash prompt · \`${externalEditor}\` edit in \`$EDITOR\`+\`${expandMessages}\` agent messages · \`${toggleThinking}\` thinking blocks · \`${promptStash}\` stash prompt · \`${externalEditor}\` edit in \`$EDITOR\`\`${pasteImage}\` paste image**Help**@@ -9491,6 +9513,7 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` fulconst exit = this.getAppKeyDisplay("app.exit");const selectModel = this.getAppKeyDisplay("app.model.select");const expandTools = this.getAppKeyDisplay("app.tools.expand");+ const expandMessages = this.getAppKeyDisplay("app.messages.expand");const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");const focusSubagents = this.getAppKeyDisplay("app.subagents.focus");const manageHeartbeats = this.getAppKeyDisplay("app.heartbeats.open");@@ -9538,6 +9561,7 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` ful${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shortcutsKey ? `| \`${shortcutsKey}\` | Show quick shortcuts |\n` : ""}| \`${exit}\` | Exit (when editor is empty) || \`${selectModel}\` | Open model selector || \`${expandTools}\` | Toggle tool output expansion |+| \`${expandMessages}\` | Toggle agent message expansion || \`${toggleThinking}\` | Toggle thinking block visibility || \`${focusSubagents}\` | Focus the subagent summary / open the scoped agents view || \`${manageHeartbeats}\` | Manage heartbeats |diff --git a/packages/coding-agent/test/assistant-message.test.ts b/packages/coding-agent/test/assistant-message.test.tsindex a18ebcc9d7..8c33619216 100644--- a/packages/coding-agent/test/assistant-message.test.ts+++ b/packages/coding-agent/test/assistant-message.test.ts@@ -1,7 +1,9 @@import type { AssistantMessage } from "@earendil-works/pi-ai";+import { setKeybindings } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { describe, expect, test } from "vitest";-import { AssistantMessageComponent } from "../src/modes/interactive/components/assistant-message.js";+import { KeybindingsManager } from "../src/core/keybindings.js";+import { AssistantMessageComponent, thinkingRecap } from "../src/modes/interactive/components/assistant-message.js";import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";const OSC133_ZONE_START = "\x1b]133;A\x07";@@ -202,6 +204,74 @@ describe("AssistantMessageComponent streaming identity", () => {}});+ test("collapsed thinking shows a bold label, recap, and bracketed hint", () => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());++ const thinking = [+ "**Weighing options**",+ "",+ "Some detail about the options.",+ "",+ "**Deciding the approach**",+ "",+ "More detail.",+ ].join("\n");+ const message = createAssistantMessage([+ { type: "thinking", thinking },+ { type: "text", text: "Answer." },+ ]);+ const rendered = stripAnsi(new AssistantMessageComponent(message, true).render(120).join("\n"));++ expect(rendered).toContain("Thinking... · Deciding the approach (Ctrl+T to expand)");+ expect(rendered).not.toContain("Some detail");++ const expanded = stripAnsi(new AssistantMessageComponent(message, false).render(120).join("\n"));+ expect(expanded).toContain("Thinking... (Ctrl+T to collapse)");+ expect(expanded).toContain("Some detail about the options.");++ // A whitespace-only trace falls back to the label instead of an empty recap.+ expect(thinkingRecap(" \n\t\n", "Thinking...")).toBe("Thinking...");+ });++ test("recap text with delimiters cannot mask structural changes", () => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());++ // Unescaped, the first recap "X|1:text:1" makes this signature identical+ // to the next structure's (recap "X" plus a real text block), so the+ // rebuild that renders the new text block would be skipped.+ const component = new AssistantMessageComponent(undefined, true);+ component.updateContent(createAssistantMessage([{ type: "thinking", thinking: "X|1:text:1" }]));+ component.render(120);++ component.updateContent(+ createAssistantMessage([+ { type: "thinking", thinking: "X" },+ { type: "text", text: "Visible answer." },+ ]),+ );+ const rendered = stripAnsi(component.render(120).join("\n"));++ expect(rendered).toContain("Visible answer.");+ });++ test("collapsed thinking row truncates instead of wrapping on narrow widths", () => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());++ const thinking = `**${"A deliberately verbose reasoning summary header that keeps going ".repeat(3).trim()}**`;+ const message = createAssistantMessage([{ type: "thinking", thinking }]);+ const lines = new AssistantMessageComponent(message, true)+ .render(60)+ .map((line) => stripAnsi(line))+ .filter((line) => line.trim().length > 0);++ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain("Thinking...");+ expect(lines[0]).toContain("to expand");+ });+test("setHideThinkingBlock and setExpanded mid-stream render identically", () => {initTheme("dark");const component = new AssistantMessageComponent();diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex 1814acbf7e..036a05f4c4 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -1311,6 +1311,74 @@ describe("daemon worker supervisor monitoring", () => {expect(persistWorker.mock.invocationCallOrder[0]).toBeLessThan(recoverWorker.mock.invocationCallOrder[0]!);});+ it("rejects retry while the worker is actively stopping", async () => {+ type RetryWorker = {+ descriptor: {+ workerId: string;+ rootActiveSessionId: string;+ rootSessionId: string;+ lifecycle: "ready";+ consecutiveFailures: number;+ stopRequestedAt: string;+ archiveOnStop: boolean;+ };+ intentionalStop: boolean;+ summaries: Map<string, SessionSummary>;+ };+ type RetryHarness = {+ stopWorker(worker: RetryWorker, removeDescriptor: boolean): Promise<void>;+ handleCommand(+ client: DaemonSocketClient,+ command: { type: "retry_worker"; activeSessionId: string },+ ): Promise<unknown>;+ };+ const worker: RetryWorker = {+ descriptor: {+ workerId: "worker-stopping",+ rootActiveSessionId: "active-stopping",+ rootSessionId: "session-stopping",+ lifecycle: "ready",+ consecutiveFailures: 2,+ stopRequestedAt: new Date().toISOString(),+ archiveOnStop: true,+ },+ intentionalStop: true,+ summaries: new Map(),+ };+ const stopStarted = createDeferred<void>();+ const releaseStop = createDeferred<void>();+ const persistWorker = vi.fn();+ const recoverWorker = vi.fn();+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ workerStopCounts: new Map(),+ stopWorkerUntracked: vi.fn(async () => {+ stopStarted.resolve();+ await releaseStop.promise;+ }),+ persistWorker,+ recoverWorker,+ assertWorkerAccessibleToClient: vi.fn(),+ }) as RetryHarness;++ const stopping = supervisor.stopWorker(worker, true);+ await stopStarted.promise;+ await expect(+ supervisor.handleCommand({} as DaemonSocketClient, {+ type: "retry_worker",+ activeSessionId: worker.descriptor.rootSessionId,+ }),+ ).rejects.toThrow("Session worker is stopping; retry after it finishes");++ expect(worker.intentionalStop).toBe(true);+ expect(worker.descriptor.stopRequestedAt).toBeDefined();+ expect(worker.descriptor.archiveOnStop).toBe(true);+ expect(persistWorker).not.toHaveBeenCalled();+ expect(recoverWorker).not.toHaveBeenCalled();+ releaseStop.resolve();+ await stopping;+ });+it("cancels an in-flight recovery after an intentional stop tombstone", async () => {vi.useFakeTimers();type RecoveryWorker = {diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 7098e2f08a..c2acc7aa7f 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -42,6 +42,7 @@ import type {import { AgentConnectionPromptAdmissionError } from "../src/modes/agent-connection/types.js";import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js";import type { AuthenticationResult } from "../src/modes/interactive/auth-flows.js";+import { AgentMessageComponent } from "../src/modes/interactive/components/agent-message.js";import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";import type { ConfigurationMenuComponent } from "../src/modes/interactive/components/configuration-menu.js";import type { AuthSelectorProvider } from "../src/modes/interactive/components/oauth-selector.js";@@ -4193,29 +4194,62 @@ describe("truncatePathMiddle", () => {});describe("InteractiveMode.setToolsExpanded", () => {- test("applies expansion state to the active header and chat entries", () => {- const header = { setExpanded: vi.fn() };- const chatChild = { setExpanded: vi.fn() };+ function createExpansionFakeThis(chatChildren: unknown[]): any {const fakeThis: any = {toolOutputExpanded: false,+ agentMessagesExpanded: false,customHeader: undefined,- builtInHeader: header,- chatContainer: { children: [chatChild] },+ builtInHeader: { setExpanded: vi.fn() },+ chatContainer: { children: chatChildren },ui: {requestRender: vi.fn(),requestRenderPreservingViewport: vi.fn(),isFullscreen: vi.fn().mockReturnValue(false),},};+ Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);+ return fakeThis;+ }++ test("applies expansion state to the active header and chat entries", () => {+ const chatChild = { setExpanded: vi.fn() };+ const fakeThis = createExpansionFakeThis([chatChild]);- (InteractiveMode as any).prototype.setToolsExpanded.call(fakeThis, true);+ fakeThis.setToolsExpanded(true);expect(fakeThis.toolOutputExpanded).toBe(true);- expect(header.setExpanded).toHaveBeenCalledWith(true);+ expect(fakeThis.builtInHeader.setExpanded).toHaveBeenCalledWith(true);expect(chatChild.setExpanded).toHaveBeenCalledWith(true);// Expansion keeps the user anchored, so it uses the viewport-preserving path.expect(fakeThis.ui.requestRenderPreservingViewport).toHaveBeenCalledTimes(1);});++ test("toggles agent messages separately from tools", () => {+ const toolChild = { setExpanded: vi.fn() };+ const messageChild = new AgentMessageComponent({+ role: "custom",+ customType: "agent_message",+ content: "Ping.",+ display: true,+ details: { id: "agentmsg_split", message: "Ping.", from: null },+ timestamp: 123,+ } as any);+ const messageSetExpanded = vi.spyOn(messageChild, "setExpanded");+ const fakeThis = createExpansionFakeThis([toolChild, messageChild]);++ fakeThis.toggleAgentMessageExpansion();++ expect(fakeThis.agentMessagesExpanded).toBe(true);+ expect(fakeThis.toolOutputExpanded).toBe(false);+ expect(messageSetExpanded).toHaveBeenCalledWith(true);+ expect(toolChild.setExpanded).toHaveBeenCalledWith(false);++ fakeThis.setToolsExpanded(true);++ expect(toolChild.setExpanded).toHaveBeenCalledWith(true);+ expect(messageSetExpanded).toHaveBeenLastCalledWith(true);+ expect(fakeThis.agentMessagesExpanded).toBe(true);+ });});describe("InteractiveMode.createExtensionUIContext setTheme", () => {diff --git a/packages/coding-agent/test/ipython-cell-diff.test.ts b/packages/coding-agent/test/ipython-cell-diff.test.tsindex ea0028012c..ce62599882 100644--- a/packages/coding-agent/test/ipython-cell-diff.test.ts+++ b/packages/coding-agent/test/ipython-cell-diff.test.ts@@ -298,9 +298,9 @@ describe("IPythonCellComponent diff rendering", () => {// Top line is unchanged through the duration; only the trailing hint flips// "to expand" → "to collapse", so nothing before it can shift.- expect(stripAnsi(collapsed[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · .*to expand$/);- expect(stripAnsi(expanded[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · .*to collapse$/);- const upToHint = (line: string) => stripAnsi(line).replace(/· [^·]*to (expand|collapse)$/, "");+ expect(stripAnsi(collapsed[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · \(.*to expand\)$/);+ expect(stripAnsi(expanded[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · \(.*to collapse\)$/);+ const upToHint = (line: string) => stripAnsi(line).replace(/· \([^·]*to (expand|collapse)\)$/, "");expect(upToHint(expanded[0])).toBe(upToHint(collapsed[0]));// No separate "python · done · 780.0s" header line below the top line.diff --git a/packages/coding-agent/test/kernel-attach-image-skill.test.ts b/packages/coding-agent/test/kernel-attach-image-skill.test.tsindex b0dddcc607..b47be17c3a 100644--- a/packages/coding-agent/test/kernel-attach-image-skill.test.ts+++ b/packages/coding-agent/test/kernel-attach-image-skill.test.ts@@ -58,7 +58,7 @@ describe("attach-image skill over the kernel host bridge", () => {expect(blocks).toEqual([{ type: "image", data: PNG_BASE64, mimeType: "image/png" }]);});- it("compresses large attached images before storing them in the tool result", async () => {+ it("compresses large attached images before storing them in the tool result", { retry: 1 }, async () => {const imagePath = join(tempDir, "large.png");provisioner = new IpythonKernelProvisioner(tempDir, {diff --git a/packages/coding-agent/test/keybindings-migration.test.ts b/packages/coding-agent/test/keybindings-migration.test.tsindex 0799ff2532..ef0e257586 100644--- a/packages/coding-agent/test/keybindings-migration.test.ts+++ b/packages/coding-agent/test/keybindings-migration.test.ts@@ -85,4 +85,29 @@ describe("keybindings migration", () => {expect(effective["tui.select.confirm"]).toBe("enter");expect(effective["app.interrupt"]).toBe("ctrl+x");});++ it("gives explicit editor bindings precedence over application defaults", () => {+ const keybindings = new KeybindingsManager({+ "tui.editor.cursorUp": ["up", "ctrl+p"],+ "tui.editor.cursorDown": ["down", "ctrl+n"],+ });++ expect(keybindings.getKeys("tui.editor.cursorUp")).toEqual(["up", "ctrl+p"]);+ expect(keybindings.getKeys("app.messages.expand")).toEqual([]);+ expect(keybindings.getKeys("app.models.toggleProvider")).toEqual(["ctrl+p"]);+ expect(keybindings.getKeys("app.agents.new")).toEqual(["ctrl+n"]);+ });++ it("reports an application default that is explicitly retained against an editor binding", () => {+ const keybindings = new KeybindingsManager({+ "tui.editor.cursorUp": ["up", "ctrl+p"],+ "app.messages.expand": "ctrl+p",+ });++ expect(keybindings.getConflicts()).toContainEqual({+ key: "ctrl+p",+ keybindings: ["tui.editor.cursorUp", "app.messages.expand"],+ });+ expect(keybindings.getKeys("app.messages.expand")).toEqual(["ctrl+p"]);+ });});diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.tsindex 2fb63ea4c4..e4c45dd8a6 100644--- a/packages/coding-agent/test/marquee-components.test.ts+++ b/packages/coding-agent/test/marquee-components.test.ts@@ -148,7 +148,7 @@ describe("marquee TUI components", () => {const collapsed = stripAnsi(component.render(100).join("\n"));expect(collapsed).toContain("cat /tmp/missing-file");- expect(collapsed).toContain("CalledProcessError · Ctrl+O to expand");+ expect(collapsed).toContain("CalledProcessError · (Ctrl+O to expand)");expect(collapsed).not.toContain("No such file or directory");expect(collapsed).not.toContain("returned non-zero exit status 1.");expect(collapsed).not.toContain("traceback collapsed");@@ -183,7 +183,7 @@ describe("marquee TUI components", () => {const component = new IPythonCellComponent(state);const collapsed = stripAnsi(component.render(100).join("\n"));- expect(collapsed).toContain("RuntimeError · Ctrl+O to expand");+ expect(collapsed).toContain("RuntimeError · (Ctrl+O to expand)");expect(collapsed).not.toContain("no output");expect(collapsed).not.toContain("/tmp/internal.py");expect(collapsed).not.toContain("line 12");diff --git a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.tsindex 1493055708..8a0cd73be9 100644--- a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts+++ b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts@@ -482,8 +482,9 @@ describe("ENG-4531 agent message UI", () => {component.setExpanded(true);const expanded = render(component);+ expect(expanded).toContain("to collapse");const expandedLines = expanded.split("\n");- expect(expandedLines[1]?.trimEnd()).toBe(" ◆ Agent message received · from Planner");+ expect(expandedLines[1]?.trimEnd()).toMatch(/^ ◆ Agent message received · from Planner \(.*to collapse\)$/);expect(expandedLines.slice(2)).toEqual([" ╰─ Reply to your parent with exactly: hi"," Then wait for more work.",diff --git a/packages/tui/src/keybindings.ts b/packages/tui/src/keybindings.tsindex 2d1f6b0d9e..4308c35b97 100644--- a/packages/tui/src/keybindings.ts+++ b/packages/tui/src/keybindings.ts@@ -51,79 +51,98 @@ export type Keybinding = keyof Keybindings;export interface KeybindingDefinition {defaultKeys: KeyId | KeyId[];description?: string;+ defaultKeyScope?: string;}export type KeybindingDefinitions = Record<string, KeybindingDefinition>;export type KeybindingsConfig = Record<string, KeyId | KeyId[] | undefined>;export const TUI_KEYBINDINGS = {- "tui.editor.cursorUp": { defaultKeys: "up", description: "Move cursor up" },- "tui.editor.cursorDown": { defaultKeys: "down", description: "Move cursor down" },+ "tui.editor.cursorUp": { defaultKeys: "up", description: "Move cursor up", defaultKeyScope: "editor" },+ "tui.editor.cursorDown": { defaultKeys: "down", description: "Move cursor down", defaultKeyScope: "editor" },"tui.editor.cursorLeft": {defaultKeys: ["left", "ctrl+b"],description: "Move cursor left",+ defaultKeyScope: "editor",},"tui.editor.cursorRight": {defaultKeys: ["right", "ctrl+f"],description: "Move cursor right",+ defaultKeyScope: "editor",},"tui.editor.cursorWordLeft": {defaultKeys: ["alt+left", "ctrl+left", "alt+b"],description: "Move cursor word left",+ defaultKeyScope: "editor",},"tui.editor.cursorWordRight": {defaultKeys: ["alt+right", "ctrl+right", "alt+f"],description: "Move cursor word right",+ defaultKeyScope: "editor",},"tui.editor.cursorLineStart": {defaultKeys: ["home", "ctrl+a"],description: "Move to line start",+ defaultKeyScope: "editor",},"tui.editor.cursorLineEnd": {defaultKeys: ["end", "ctrl+e"],description: "Move to line end",+ defaultKeyScope: "editor",},"tui.editor.jumpForward": {defaultKeys: "ctrl+]",description: "Jump forward to character",+ defaultKeyScope: "editor",},"tui.editor.jumpBackward": {defaultKeys: "ctrl+alt+]",description: "Jump backward to character",+ defaultKeyScope: "editor",},- "tui.editor.pageUp": { defaultKeys: "pageUp", description: "Page up" },- "tui.editor.pageDown": { defaultKeys: "pageDown", description: "Page down" },+ "tui.editor.pageUp": { defaultKeys: "pageUp", description: "Page up", defaultKeyScope: "editor" },+ "tui.editor.pageDown": { defaultKeys: "pageDown", description: "Page down", defaultKeyScope: "editor" },"tui.editor.deleteCharBackward": {defaultKeys: "backspace",description: "Delete character backward",+ defaultKeyScope: "editor",},"tui.editor.deleteCharForward": {defaultKeys: ["delete", "ctrl+d"],description: "Delete character forward",+ defaultKeyScope: "editor",},"tui.editor.deleteWordBackward": {defaultKeys: ["ctrl+w", "alt+backspace"],description: "Delete word backward",+ defaultKeyScope: "editor",},"tui.editor.deleteWordForward": {defaultKeys: ["alt+d", "alt+delete"],description: "Delete word forward",+ defaultKeyScope: "editor",},"tui.editor.deleteToLineStart": {defaultKeys: "ctrl+u",description: "Delete to line start",+ defaultKeyScope: "editor",},"tui.editor.deleteToLineEnd": {defaultKeys: "ctrl+k",description: "Delete to line end",+ defaultKeyScope: "editor",},- "tui.editor.yank": { defaultKeys: "ctrl+y", description: "Yank" },- "tui.editor.yankPop": { defaultKeys: "alt+y", description: "Yank pop" },- "tui.editor.undo": { defaultKeys: "ctrl+-", description: "Undo" },- "tui.input.newLine": { defaultKeys: "shift+enter", description: "Insert newline" },- "tui.input.submit": { defaultKeys: "enter", description: "Submit input" },- "tui.input.tab": { defaultKeys: "tab", description: "Tab / autocomplete" },- "tui.input.copy": { defaultKeys: "ctrl+c", description: "Copy selection" },+ "tui.editor.yank": { defaultKeys: "ctrl+y", description: "Yank", defaultKeyScope: "editor" },+ "tui.editor.yankPop": { defaultKeys: "alt+y", description: "Yank pop", defaultKeyScope: "editor" },+ "tui.editor.undo": { defaultKeys: "ctrl+-", description: "Undo", defaultKeyScope: "editor" },+ "tui.input.newLine": {+ defaultKeys: "shift+enter",+ description: "Insert newline",+ defaultKeyScope: "editor",+ },+ "tui.input.submit": { defaultKeys: "enter", description: "Submit input", defaultKeyScope: "editor" },+ "tui.input.tab": { defaultKeys: "tab", description: "Tab / autocomplete", defaultKeyScope: "editor" },+ "tui.input.copy": { defaultKeys: "ctrl+c", description: "Copy selection", defaultKeyScope: "editor" },"tui.viewport.pageUp": {defaultKeys: "pageUp",description: "Scroll transcript up a page (fullscreen)",@@ -189,17 +208,25 @@ export class KeybindingsManager {this.keysById.clear();this.conflicts = [];- const userClaims = new Map<KeyId, Set<Keybinding>>();+ const explicitClaims = new Map<KeyId, Set<Keybinding>>();+ const addedClaims = new Map<KeyId, Set<Keybinding>>();for (const [keybinding, keys] of Object.entries(this.userBindings)) {- if (!(keybinding in this.definitions)) continue;+ const definition = this.definitions[keybinding];+ if (!definition) continue;+ const defaults = new Set(normalizeKeys(definition.defaultKeys));for (const key of normalizeKeys(keys)) {- const claimants = userClaims.get(key) ?? new Set<Keybinding>();- claimants.add(keybinding as Keybinding);- userClaims.set(key, claimants);+ const explicitClaimants = explicitClaims.get(key) ?? new Set<Keybinding>();+ explicitClaimants.add(keybinding as Keybinding);+ explicitClaims.set(key, explicitClaimants);+ if (!defaults.has(key)) {+ const addedClaimants = addedClaims.get(key) ?? new Set<Keybinding>();+ addedClaimants.add(keybinding as Keybinding);+ addedClaims.set(key, addedClaimants);+ }}}- for (const [key, keybindings] of userClaims) {+ for (const [key, keybindings] of explicitClaims) {if (keybindings.size > 1) {this.conflicts.push({ key, keybindings: [...keybindings] });}@@ -207,7 +234,15 @@ export class KeybindingsManager {for (const [id, definition] of Object.entries(this.definitions)) {const userKeys = this.userBindings[id];- const keys = userKeys === undefined ? normalizeKeys(definition.defaultKeys) : normalizeKeys(userKeys);+ const keys =+ userKeys === undefined+ ? normalizeKeys(definition.defaultKeys).filter((key) => {+ if (!definition.defaultKeyScope) return true;+ return ![...(addedClaims.get(key) ?? [])].some(+ (claimant) => this.definitions[claimant]?.defaultKeyScope === definition.defaultKeyScope,+ );+ })+ : normalizeKeys(userKeys);this.keysById.set(id as Keybinding, keys);}}diff --git a/packages/tui/test/keybindings.test.ts b/packages/tui/test/keybindings.test.tsindex 7e255b0a29..a4c86bf922 100644--- a/packages/tui/test/keybindings.test.ts+++ b/packages/tui/test/keybindings.test.ts@@ -3,7 +3,7 @@ import { describe, it } from "node:test";import { KeybindingsManager, TUI_KEYBINDINGS } from "../src/keybindings.js";describe("KeybindingsManager", () => {- it("does not evict selector confirm when input submit is rebound", () => {+ it("keeps shared defaults when a user binding repeats its own default", () => {const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, {"tui.input.submit": ["enter", "ctrl+enter"],});@@ -12,7 +12,7 @@ describe("KeybindingsManager", () => {assert.deepStrictEqual(keybindings.getKeys("tui.select.confirm"), ["enter"]);});- it("does not evict cursor bindings when another action reuses the same key", () => {+ it("keeps shared cursor defaults when a user binding repeats its own default", () => {const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, {"tui.select.up": ["up", "ctrl+p"],});@@ -21,7 +21,16 @@ describe("KeybindingsManager", () => {assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorUp"), ["up"]);});- it("still reports direct user binding conflicts without evicting defaults", () => {+ it("evicts defaults claimed as an added user binding", () => {+ const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, {+ "tui.editor.cursorUp": ["up", "ctrl+b"],+ });++ assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorUp"), ["up", "ctrl+b"]);+ assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorLeft"), ["left"]);+ });++ it("still reports direct user binding conflicts", () => {const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, {"tui.input.submit": "ctrl+x","tui.select.confirm": "ctrl+x",@@ -35,4 +44,20 @@ describe("KeybindingsManager", () => {]);assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorLeft"), ["left", "ctrl+b"]);});++ it("reports conflicts when an explicit binding restates its default", () => {+ const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, {+ "tui.editor.cursorUp": ["up", "ctrl+b"],+ "tui.editor.cursorLeft": ["left", "ctrl+b"],+ });++ assert.deepStrictEqual(keybindings.getConflicts(), [+ {+ key: "ctrl+b",+ keybindings: ["tui.editor.cursorUp", "tui.editor.cursorLeft"],+ },+ ]);+ assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorUp"), ["up", "ctrl+b"]);+ assert.deepStrictEqual(keybindings.getKeys("tui.editor.cursorLeft"), ["left", "ctrl+b"]);+ });});