Skip to content

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

Rust

add verbosity controls + clean ui (#2193)

kt370c56235dce
diff --git a/packages/coding-agent/.changes/ui-chat-output.md b/packages/coding-agent/.changes/ui-chat-output.md
new file mode 100644
index 0000000000..2fedd10740
--- /dev/null
+++ b/packages/coding-agent/.changes/ui-chat-output.md
@@ -0,0 +1,19 @@
+- Changed assistant message body text to a new dimmed `mdBody` theme color, easing the wall of bright default-foreground text while headings, links, and code keep their styling.
+- Changed prime-theme inline code to a darker neutral (#c8c8cd) so it stays distinct from the dimmed body text.
+- Added a three-stage Ctrl+O cycle for overview, thinking and file diffs, and all output, replacing the separate Ctrl+J and Ctrl+T conversation shortcuts without changing saved traces.
+- Changed thinking rows to stay hidden in overview and appear as dim text without a repeated heading in the other detail modes, including newly streamed thinking.
+- Changed collapsed tool-call previews to render plain and dim instead of green or syntax-highlighted code, with dim line counts and durations, while expanded blocks keep full highlighting.
+- Changed decorative bold text in the conversation surface to normal weight, keeping bold only where it marks state or a single critical item (selected rows, active tabs, the login verification code).
+- Changed the conversation row hierarchy: event-row trailing detail (agent-message participants, tool command previews, line counts, durations) renders dim while leading labels keep their colors.
+- Changed background shell completions to update identifiable command rows, with compact fallback notices and full notifications shown once at their original conversation position in all output.
+- Replaced repeated conversation detail shortcut hints with a status label showing the current detail mode and configurable expand or collapse shortcut.
+- Changed expanded file diffs to start at the normal chat inset while preserving code indentation and diff gutters.
+- Changed sent and received agent messages to keep compact notices in overview and details, show full bodies only in all output, and use the shared detail cycle instead of a separate Ctrl+P toggle.
+- Fixed spacing after background shell completions and matched unique literal assignment-only shell launches to their completion notices.
+- Fixed multiline Python string colors across source lines and narrow wrapping, kept embedded string content out of collapsed code previews, and preserved statements after closing quotes.
+- Changed expanded Python cells to nest input directly under the summary, align marked output beneath it, and separate full tool and message blocks.
+- Fixed unwanted gaps between compact tool and agent-message rows when empty assistant messages or hidden thinking appear between them.
+- Fixed missing separation between refinement notices and subsequent collapsed background shell completions.
+- Fixed custom themes without `mdBody`, large expanded agent messages, and slow or unmatched shell completions caused by malformed launch arguments or blank lines.
+- Removed obsolete thinking-visibility settings and unused transcript heading and hint state.
+- Fixed indefinitely animated shell rows after ambiguous completion notifications while keeping unmatched results at their original timeline position.
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 5f6bd39454..eb182ed89a 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -182,9 +182,7 @@ See `/hotkeys` for the full list. Customize via `~/.prime/agent/keybindings.json
| Escape | Clear the input without interrupting active work |
| Escape twice | Open `/tree` |
| Ctrl+L | Open model selector |
-| Ctrl+P / Shift+Ctrl+P | Cycle scoped models forward/backward |
-| Ctrl+O | Collapse/expand tool output |
-| Ctrl+T | Collapse/expand thinking blocks |
+| Ctrl+O | Cycle overview → thinking and file diffs → all output |
### Message Queue
diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.md
index 72928d323f..8e7646b8e9 100644
--- a/packages/coding-agent/docs/keybindings.md
+++ b/packages/coding-agent/docs/keybindings.md
@@ -115,7 +115,6 @@ Modifier combinations: `ctrl+shift+x`, `alt+ctrl+x`, `ctrl+shift+alt+x`, `ctrl+1
|--------|---------|-------------|
| `app.model.select` | `ctrl+l` | Open model selector |
| `app.model.toggleScope` | `alt+s` | Toggle between all and scoped models |
-| `app.thinking.toggle` | `ctrl+t` | Collapse or expand thinking blocks |
### Configuration Pickers
@@ -125,15 +124,15 @@ Models, Providers, and MCP Connections open as separate pickers. Use `escape` to
| 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.edits.expand` | `ctrl+j` | Collapse or expand edit diffs |
+| `app.tools.expand` | `ctrl+o` | Cycle overview → thinking and file diffs → all output |
| `app.message.followUp` | `alt+enter` | Queue follow-up message |
| `app.message.navigateOlder` | `alt+up` | Select the next older pending message |
| `app.message.navigateNewer` | `alt+down` | Select the next newer pending message or restore the draft |
| `app.message.moveEarlier` | `ctrl+alt+up` | Move the selected pending message one place earlier in its queue |
| `app.message.moveLater` | `ctrl+alt+down` | Move the selected pending message one place later in its queue |
+Ctrl+O changes presentation only: the default hides thinking and collapses tools and diffs; the first press reveals thinking and file diffs; the second expands tool output and full agent-to-agent message bodies; the third returns to the default. Compact sent and received message notices remain visible in every mode. This also works for restored conversations and new streaming content. Ctrl+J, Ctrl+T, and Ctrl+P no longer control conversation expansion.
+
### Tree Navigation
| Keybinding id | Default | Description |
@@ -181,7 +180,7 @@ 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.
+Binding `ctrl+p` below moves the editor cursor up; shortcuts in other views keep their defaults.
```json
{
diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.md
index 1fa0cfbef1..d74475a087 100644
--- a/packages/coding-agent/docs/settings.md
+++ b/packages/coding-agent/docs/settings.md
@@ -18,7 +18,6 @@ Edit directly or use `/settings` for common options.
| `defaultProvider` | string | - | Default provider (e.g., `"anthropic"`, `"openai"`) |
| `defaultModel` | string | - | Default model ID |
| `defaultThinkingLevel` | string | `"xhigh"` | `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"` |
-| `hideThinkingBlock` | boolean | `false` | Hide thinking blocks in output |
| `thinkingBudgets` | object | - | Custom token budgets per thinking level |
#### thinkingBudgets
@@ -36,6 +35,8 @@ Edit directly or use `/settings` for common options.
### UI & Display
+Conversation output starts in overview. Ctrl+O cycles through details and all output; the old `hideThinkingBlock` setting no longer controls visibility.
+
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `theme` | string | `"dark"` | Theme name (`"dark"`, `"light"`, or custom) |
diff --git a/packages/coding-agent/docs/themes.md b/packages/coding-agent/docs/themes.md
index 44b8f108e5..251bd3a2f0 100644
--- a/packages/coding-agent/docs/themes.md
+++ b/packages/coding-agent/docs/themes.md
@@ -79,9 +79,12 @@ vim ~/.prime/agent/themes/my-theme.json
"toolPendingBg": "#1e1e2e",
"toolSuccessBg": "#1e2e1e",
"toolErrorBg": "#2e1e1e",
+ "toolDiffAddedBg": "#0a2f0a",
+ "toolDiffRemovedBg": "#2f0a0a",
"toolPanelBg": "#2d2d38",
"toolTitle": "primary",
"toolOutput": "",
+ "mdBody": "",
"mdHeading": "#ffaa00",
"mdLink": "primary",
"mdLinkUrl": "secondary",
@@ -94,6 +97,7 @@ vim ~/.prime/agent/themes/my-theme.json
"mdListBullet": "#00ffff",
"toolDiffAdded": "#00ff00",
"toolDiffRemoved": "#ff0000",
+ "toolDiffText": "secondary",
"toolDiffContext": "secondary",
"syntaxComment": "secondary",
"syntaxKeyword": "primary",
@@ -140,13 +144,13 @@ vim ~/.prime/agent/themes/my-theme.json
- `name` is required and must be unique.
- `vars` is optional. Define reusable colors here, then reference them in `colors`.
-- `colors` must define all 51 required tokens.
+- `colors` must define all required tokens. `mdBody` is optional and defaults to `text`.
The `$schema` field enables editor auto-completion and validation.
## Color Tokens
-Every theme must define all 51 color tokens. There are no optional colors.
+Every theme must define the color tokens below except `mdBody`, which defaults to `text` when omitted.
### Core UI (11 colors)
@@ -164,7 +168,7 @@ Every theme must define all 51 color tokens. There are no optional colors.
| `text` | Default text (usually `""`) |
| `thinkingText` | Thinking block text |
-### Backgrounds & Content (12 colors)
+### Backgrounds & Content (14 colors)
| Token | Purpose |
|-------|---------|
@@ -177,14 +181,17 @@ Every theme must define all 51 color tokens. There are no optional colors.
| `toolPendingBg` | Tool box (pending) |
| `toolSuccessBg` | Tool box (success) |
| `toolErrorBg` | Tool box (error) |
+| `toolDiffAddedBg` | Added-line background in tool diffs |
+| `toolDiffRemovedBg` | Removed-line background in tool diffs |
| `toolPanelBg` | Tool panel background |
| `toolTitle` | Tool title |
| `toolOutput` | Tool output text |
-### Markdown (10 colors)
+### Markdown (11 colors)
| Token | Purpose |
|-------|---------|
+| `mdBody` | Assistant output body text (optional; defaults to `text`) |
| `mdHeading` | Headings |
| `mdLink` | Link text |
| `mdLinkUrl` | Link URL |
@@ -196,12 +203,13 @@ Every theme must define all 51 color tokens. There are no optional colors.
| `mdHr` | Horizontal rule |
| `mdListBullet` | List bullets |
-### Tool Diffs (3 colors)
+### Tool Diffs (4 colors)
| Token | Purpose |
|-------|---------|
| `toolDiffAdded` | Added lines |
| `toolDiffRemoved` | Removed lines |
+| `toolDiffText` | Text on added and removed diff backgrounds |
| `toolDiffContext` | Context lines |
### Syntax Highlighting (9 colors)
diff --git a/packages/coding-agent/docs/tui.md b/packages/coding-agent/docs/tui.md
index 5e9c371255..4e2d2a48e7 100644
--- a/packages/coding-agent/docs/tui.md
+++ b/packages/coding-agent/docs/tui.md
@@ -413,7 +413,7 @@ renderResult(result, options, theme, context) {
| Messages | `userMessageText`, `customMessageText`, `customMessageLabel` |
| Tools | `toolTitle`, `toolOutput` |
| Diffs | `toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext` |
-| Markdown | `mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet` |
+| Markdown | `mdBody`, `mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet` |
| Syntax | `syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation` |
| Thinking | `thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh` |
| Modes | `bashMode` |
diff --git a/packages/coding-agent/examples/extensions/README.md b/packages/coding-agent/examples/extensions/README.md
index 3caef7deec..4de821e8a5 100644
--- a/packages/coding-agent/examples/extensions/README.md
+++ b/packages/coding-agent/examples/extensions/README.md
@@ -53,7 +53,7 @@ cp permission-gate.ts ~/.prime/agent/extensions/
| `status-line.ts` | Shows turn progress in footer via `ctx.ui.setStatus()` with themed colors |
| `github-issue-autocomplete.ts` | Adds `#1234` issue completions by stacking a custom autocomplete provider that preloads open issues from `gh issue list` |
| `widget-placement.ts` | Shows widgets above and below the editor via `ctx.ui.setWidget()` placement |
-| `hidden-thinking-label.ts` | Customizes the collapsed thinking label via `ctx.ui.setHiddenThinkingLabel()` |
+| `hidden-thinking-label.ts` | Legacy example for `ctx.ui.setHiddenThinkingLabel()`, now a no-op because thinking has no heading |
| `working-indicator.ts` | Customizes the streaming working indicator via `ctx.ui.setWorkingIndicator()` |
| `model-status.ts` | Shows model changes in status bar via `model_select` hook |
| `snake.ts` | Snake game with custom UI, keyboard handling, and session persistence |
diff --git a/packages/coding-agent/examples/extensions/hidden-thinking-label.ts b/packages/coding-agent/examples/extensions/hidden-thinking-label.ts
index bcdaab66aa..a50fc2a566 100644
--- a/packages/coding-agent/examples/extensions/hidden-thinking-label.ts
+++ b/packages/coding-agent/examples/extensions/hidden-thinking-label.ts
@@ -1,21 +1,21 @@
/**
* Hidden Thinking Label Extension
*
- * Demonstrates `ctx.ui.setHiddenThinkingLabel()` for customizing the label shown
- * when thinking blocks are hidden.
+ * Legacy example for the deprecated `ctx.ui.setHiddenThinkingLabel()` hook.
+ * The hook has no effect: thinking is now displayed without a heading.
*
* Usage:
* pi --extension examples/extensions/hidden-thinking-label.ts
*
* Test:
* 1. Load this extension
- * 2. Hide thinking blocks with Ctrl+T
+ * 2. Press Ctrl+O once to show thinking and file diffs
* 3. Ask for something that produces reasoning output
- * 4. The collapsed thinking block label will show the custom text
+ * 4. Thinking remains unlabeled; this extension does not change its rendering
*
* Commands:
- * /thinking-label <text> Set a custom hidden thinking label
- * /thinking-label Reset to the default label
+ * /thinking-label <text> Exercise the deprecated hook (no visible effect)
+ * /thinking-label Exercise the deprecated reset (no visible effect)
*/
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -34,20 +34,20 @@ export default function (pi: ExtensionAPI) {
});
pi.registerCommand("thinking-label", {
- description: "Set the hidden thinking label. Use without args to reset.",
+ description: "Legacy thinking-label hook (no visible effect).",
handler: async (args, ctx) => {
const nextLabel = args.trim();
if (!nextLabel) {
label = DEFAULT_LABEL;
ctx.ui.setHiddenThinkingLabel();
- ctx.ui.notify(`Hidden thinking label reset to: ${DEFAULT_LABEL}`);
+ ctx.ui.notify("Thinking labels are no longer displayed; resetting the legacy label has no effect.");
return;
}
label = nextLabel;
ctx.ui.setHiddenThinkingLabel(label);
- ctx.ui.notify(`Hidden thinking label set to: ${label}`);
+ ctx.ui.notify("Thinking labels are no longer displayed; setting the legacy label has no effect.");
},
});
}
diff --git a/packages/coding-agent/src/core/extensions/runner.ts b/packages/coding-agent/src/core/extensions/runner.ts
index 172f725003..e27b5c9111 100644
--- a/packages/coding-agent/src/core/extensions/runner.ts
+++ b/packages/coding-agent/src/core/extensions/runner.ts
@@ -67,9 +67,6 @@ const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [
"app.suspend",
"app.model.select",
"app.tools.expand",
- "app.messages.expand",
- "app.edits.expand",
- "app.thinking.toggle",
"app.subagents.focus",
"app.editor.external",
"app.message.followUp",
diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.ts
index 4ff321fdfd..21abe7a16a 100644
--- a/packages/coding-agent/src/core/extensions/types.ts
+++ b/packages/coding-agent/src/core/extensions/types.ts
@@ -145,7 +145,7 @@ export interface ExtensionUIContext {
*/
setWorkingIndicator(options?: WorkingIndicatorOptions): void;
- /** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */
+ /** @deprecated No effect: thinking is displayed without a heading. Retained for existing extension/daemon callers. */
setHiddenThinkingLabel(label?: string): void;
/** Set a widget to display above or below the editor. Accepts string array or component factory. */
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 57ffba268b..901ae51d7a 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -20,9 +20,6 @@ export interface AppKeybindings {
"app.model.select": true;
"app.model.toggleScope": true;
"app.tools.expand": true;
- "app.messages.expand": true;
- "app.edits.expand": true;
- "app.thinking.toggle": true;
"app.subagents.focus": true;
"app.heartbeats.open": true;
"app.heartbeats.openSelected": true;
@@ -86,18 +83,7 @@ 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.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.edits.expand": { defaultKeys: "ctrl+j", description: "Toggle edit diffs", defaultKeyScope: "editor" },
- "app.thinking.toggle": {
- defaultKeys: "ctrl+t",
- description: "Toggle thinking blocks",
- defaultKeyScope: "editor",
- },
+ "app.tools.expand": { defaultKeys: "ctrl+o", description: "Cycle conversation detail", defaultKeyScope: "editor" },
"app.subagents.focus": {
defaultKeys: "alt+a",
description: "Open child agents",
@@ -269,7 +255,6 @@ const KEYBINDING_NAME_MIGRATIONS = {
suspend: "app.suspend",
selectModel: "app.model.select",
expandTools: "app.tools.expand",
- toggleThinking: "app.thinking.toggle",
focusSubagents: "app.subagents.focus",
externalEditor: "app.editor.external",
followUp: "app.message.followUp",
diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts
index 1fb87cbdb4..669f30e501 100644
--- a/packages/coding-agent/src/core/settings-manager.ts
+++ b/packages/coding-agent/src/core/settings-manager.ts
@@ -148,7 +148,6 @@ export interface Settings {
telemetry?: TelemetrySettings;
branchSummary?: BranchSummarySettings;
retry?: RetrySettings;
- hideThinkingBlock?: boolean;
shellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)
quietStartup?: boolean;
shellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., "shopt -s expand_aliases" for alias support)
@@ -958,16 +957,6 @@ export class SettingsManager {
};
}
- getHideThinkingBlock(): boolean {
- return this.settings.hideThinkingBlock ?? false;
- }
-
- setHideThinkingBlock(hide: boolean): void {
- this.globalSettings.hideThinkingBlock = hide;
- this.markModified("hideThinkingBlock");
- this.save();
- }
-
getShellPath(): string | undefined {
return this.settings.shellPath;
}
diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.ts
index 9b72ffcc24..6143e6f98c 100644
--- a/packages/coding-agent/src/core/tools/bash.ts
+++ b/packages/coding-agent/src/core/tools/bash.ts
@@ -177,7 +177,7 @@ function formatDuration(ms: number): string {
function formatBashCall(args: { command?: string; timeout?: number } | undefined): string {
const command = str(args?.command);
const timeout = args?.timeout as number | undefined;
- const timeoutSuffix = timeout ? theme.fg("muted", ` (timeout ${timeout}s)`) : "";
+ const timeoutSuffix = timeout ? theme.fg("dim", ` (timeout ${timeout}s)`) : "";
let commandDisplay: string;
if (command === null) {
commandDisplay = invalidArgText(theme);
@@ -188,7 +188,7 @@ function formatBashCall(args: { command?: string; timeout?: number } | undefined
} else {
commandDisplay = theme.fg("toolOutput", "...");
}
- return theme.fg("toolTitle", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;
+ return theme.fg("dim", `$ ${commandDisplay}`) + timeoutSuffix;
}
function rebuildBashResultRenderComponent(
@@ -228,8 +228,8 @@ function rebuildBashResultRenderComponent(
}
if (state.cachedSkipped && state.cachedSkipped > 0) {
const hint = showExpandHint
- ? `${theme.fg("muted", `... ${state.cachedSkipped} earlier lines`)} ${expandCollapseHint("app.tools.expand", false)}`
- : theme.fg("muted", `... (${state.cachedSkipped} earlier lines)`);
+ ? `${theme.fg("dim", `... ${state.cachedSkipped} earlier lines`)} ${expandCollapseHint("app.tools.expand", false)}`
+ : theme.fg("dim", `... (${state.cachedSkipped} earlier lines)`);
return ["", truncateToWidth(hint, width, "..."), ...(state.cachedLines ?? [])];
}
return ["", ...(state.cachedLines ?? [])];
@@ -265,7 +265,7 @@ function rebuildBashResultRenderComponent(
if (startedAt !== undefined) {
const label = options.isPartial ? "Elapsed" : "Took";
const endTime = endedAt ?? Date.now();
- component.addChild(new Text(`\n${theme.fg("muted", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));
+ component.addChild(new Text(`\n${theme.fg("dim", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));
}
}
diff --git a/packages/coding-agent/src/core/tools/code-preview.ts b/packages/coding-agent/src/core/tools/code-preview.ts
index 0b2a42f67a..b868377a87 100644
--- a/packages/coding-agent/src/core/tools/code-preview.ts
+++ b/packages/coding-agent/src/core/tools/code-preview.ts
@@ -361,7 +361,7 @@ function firstPythonChildLine(lines: readonly string[], parentIndex: number): nu
function pythonLineScore(lines: readonly string[], index: number, paths: ReadonlyMap<string, string>): number {
const line = lines[index] ?? "";
const trimmed = line.trim();
- if (isSkippablePythonLine(line) || PYTHON_DECORATOR_PATTERN.test(trimmed)) {
+ if (isSkippablePythonLine(line) || PYTHON_DECORATOR_PATTERN.test(trimmed) || /^[)\]},;\s]+(?:#.*)?$/.test(trimmed)) {
return -1;
}
if (pythonFileOperation(line, paths)) {
@@ -458,30 +458,38 @@ function scanPythonStringLiteral(code: string, start: number, quote: string, raw
return { value, end: i, closed: false, unsupportedEscape };
}
-// True when the lines end inside an unterminated triple-quoted string.
-function endsInsideMultilineString(lines: readonly string[]): boolean {
- const text = lines.join("\n");
+/** Keep source-line positions while masking multiline-string continuations. */
+export function pythonStatementLines(code: string): string[] {
+ const lines = code.split("\n");
+ let line = 0;
let i = 0;
- while (i < text.length) {
- const char = text[i] ?? "";
+ while (i < code.length) {
+ const char = code[i]!;
if (char === "#") {
- const newline = text.indexOf("\n", i);
- if (newline < 0) return false;
- i = newline + 1;
+ const newline = code.indexOf("\n", i);
+ if (newline < 0) break;
+ i = newline;
continue;
}
if (char === '"' || char === "'") {
- const quote = text.startsWith(char.repeat(3), i) ? char.repeat(3) : char;
- const scan = scanPythonStringLiteral(text, i + quote.length, quote, true);
- if (!scan.closed && scan.end >= text.length) {
- return quote.length === 3;
+ const quote = code.startsWith(char.repeat(3), i) ? char.repeat(3) : char;
+ const scan = scanPythonStringLiteral(code, i + quote.length, quote, true);
+ const startLine = line;
+ for (let end = i; end < scan.end; end++) {
+ if (code[end] === "\n") lines[++line] = "";
+ }
+ if (scan.closed && line > startLine) {
+ const column = scan.end - code.lastIndexOf("\n", scan.end - 1) - 1;
+ const newline = code.indexOf("\n", scan.end);
+ lines[line] = " ".repeat(column) + code.slice(scan.end, newline < 0 ? undefined : newline);
}
i = scan.end;
continue;
}
- i += 1;
+ if (char === "\n") line++;
+ i++;
}
- return false;
+ return lines;
}
function extractBashSkillCommand(code: string): string | undefined {
@@ -499,7 +507,8 @@ function extractBashSkillCommand(code: string): string | undefined {
}
export function previewPythonCode(code: string): CodePreview {
- const lines = code.split("\n");
+ const rawLines = code.split("\n");
+ const lines = pythonStatementLines(code).map((line) => line.replace(/^(\s*);\s*/, "$1"));
const paths = pythonPathVars(lines);
let bestIndex: number | undefined;
let bestScore = -1;
@@ -514,10 +523,10 @@ export function previewPythonCode(code: string): CodePreview {
if (bestIndex !== undefined && bestScore >= 0) {
const previewIndex = pythonPreviewIndex(lines, bestIndex);
- // Extract from the full tail (literals may span lines), unless the chosen line is string text.
- const bashCommand = endsInsideMultilineString(lines.slice(0, previewIndex))
- ? undefined
- : extractBashSkillCommand(lines.slice(previewIndex).join("\n"));
+ // Keep the original tail for multiline commands, excluding any preceding string continuation.
+ const bashCommand = extractBashSkillCommand(
+ [lines[previewIndex], ...rawLines.slice(previewIndex + 1)].join("\n"),
+ );
if (bashCommand) {
return previewBashCommand(bashCommand);
}
diff --git a/packages/coding-agent/src/core/tools/edit.ts b/packages/coding-agent/src/core/tools/edit.ts
index df71f893f4..ffdc5a6674 100644
--- a/packages/coding-agent/src/core/tools/edit.ts
+++ b/packages/coding-agent/src/core/tools/edit.ts
@@ -4,11 +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 {
- countChangedLines,
- FILE_CHANGE_DIFF_INDENT,
- formatFileChangeSummaryLine,
-} from "../../modes/interactive/components/edit-summary.js";
+import { countChangedLines, formatFileChangeSummaryLine } from "../../modes/interactive/components/edit-summary.js";
import type { ToolDefinition } from "../extensions/types.js";
import {
applyEditsToNormalizedContent,
@@ -202,8 +198,8 @@ function formatEditCall(
const invalidArg = invalidArgText(theme);
const rawPath = str(args?.file_path ?? args?.path);
const path = rawPath !== null ? shortenPath(rawPath) : null;
- const pathDisplay = path === null ? invalidArg : path ? theme.fg("accent", path) : theme.fg("toolOutput", "...");
- return `${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`;
+ const pathDisplay = path === null ? invalidArg : path ? theme.fg("dim", path) : theme.fg("toolOutput", "...");
+ return `${theme.fg("toolTitle", "edit")} ${pathDisplay}`;
}
function formatEditResult(
@@ -249,26 +245,22 @@ function getEditHeaderBg(
return (text: string) => theme.bg("toolPendingBg", text);
}
-// Width-aware `╰─ <path> +N -M` summary plus optional indented diff rows: the
-// summary truncates to one row and wrapped diff lines keep the indent column.
+// Width-aware file summary with optional diff rows at the containing box's content margin.
class EditChangeSummaryComponent implements Component {
constructor(
private readonly rawPath: string,
private readonly cwd: string,
private readonly change: { added: number; removed: number },
- private readonly diffsExpanded: boolean | undefined,
private readonly diffLines: readonly string[] | undefined,
) {}
render(width: number): string[] {
const safeWidth = Math.max(1, width);
- const lines = [formatFileChangeSummaryLine(this.rawPath, this.cwd, this.change, this.diffsExpanded, safeWidth)];
+ const lines = [formatFileChangeSummaryLine(this.rawPath, this.cwd, this.change, safeWidth)];
if (this.diffLines !== undefined) {
- const indent = FILE_CHANGE_DIFF_INDENT.slice(0, Math.max(0, safeWidth - 1));
- const contentWidth = Math.max(1, safeWidth - indent.length);
for (const line of this.diffLines) {
- for (const row of wrapTextWithAnsi(line, contentWidth)) {
- lines.push(`${indent}${row}`);
+ for (const row of wrapTextWithAnsi(line, safeWidth)) {
+ lines.push(row);
}
}
}
@@ -299,8 +291,7 @@ function buildEditCallComponent(
return component;
}
- // The `╰─ <path> +N -M` summary line renders in both states; ctrl+j only
- // attaches or removes the indented diff lines underneath it.
+ // Keep the file summary visible while detail expansion reveals the diff.
const rawPath = str(args?.file_path ?? args?.path);
const change = countChangedLines(component.preview.diff);
component.addChild(new Spacer(1));
@@ -309,10 +300,6 @@ function buildEditCallComponent(
rawPath ?? "...",
cwd,
change,
- // The ctrl+j hint renders on every edit summary row (unlike the ctrl+o
- // hint, which the latest tool row owns), matching thinking and
- // agent-message hints.
- expanded,
expanded ? renderDiff(component.preview.diff).split("\n") : undefined,
),
);
diff --git a/packages/coding-agent/src/modes/interactive/components/agent-message.ts b/packages/coding-agent/src/modes/interactive/components/agent-message.ts
index cf6845a495..e171d9ba82 100644
--- a/packages/coding-agent/src/modes/interactive/components/agent-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/agent-message.ts
@@ -2,34 +2,22 @@ import {
type Component,
Container,
type MarkdownTheme,
- Spacer,
Text,
truncateToWidth,
- visibleWidth,
wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { type AgentSessionMessage, formatAgentMessageParticipant } from "../../../core/agent-messages.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
-
-function collapseText(text: string): string {
- return text.replace(/\s+/g, " ").trim();
-}
/** `◆ <label> · <participant>[ · <preview>]` summary line shared by received and sent agent-message UI. */
export function agentMessageSummaryLine(label: string, participant: string, preview?: string): string {
- const parts = [`${theme.fg("accent", "◆")} ${theme.fg("muted", label)}`, theme.fg("muted", participant)];
+ const parts = [`${theme.fg("accent", "◆")} ${theme.fg("muted", label)}`, theme.fg("dim", participant)];
if (preview) {
- parts.push(theme.fg("muted", preview));
+ parts.push(theme.fg("dim", preview));
}
return parts.join(theme.fg("dim", " · "));
}
-/** Single-line message preview sized to fit after the summary-line prefix. */
-export function agentMessagePreview(prefixWidth: number, message: string): string {
- return truncateToWidth(collapseText(message), Math.max(20, 100 - prefixWidth));
-}
-
/** `╰─`-guttered message body lines shared by received and sent agent-message UI. */
export function agentMessageBodyLines(message: string, width: number): string[] {
const safeWidth = Math.max(1, width);
@@ -57,19 +45,26 @@ class AgentMessageBodyComponent implements Component {
export class AgentMessageComponent extends Container {
private readonly content = new Container();
private readonly header = new Text("", 1, 0);
+ private readonly shouldAddLeadingSpace?: (expanded: boolean) => boolean;
private expanded = false;
constructor(
private readonly message: AgentSessionMessage,
_markdownTheme: MarkdownTheme = getMarkdownTheme(),
- options: { suppressLeadingSpace?: boolean } = {},
+ options: { shouldAddLeadingSpace?: (expanded: boolean) => boolean } = {},
) {
super();
- if (!options.suppressLeadingSpace) this.addChild(new Spacer(1));
+ this.shouldAddLeadingSpace = options.shouldAddLeadingSpace;
this.addChild(this.content);
this.updateDisplay();
}
+ override render(width: number): string[] {
+ const lines = super.render(width);
+ const leadingSpace = this.shouldAddLeadingSpace?.(this.expanded) ?? true;
+ return leadingSpace ? ["", ...lines] : lines;
+ }
+
setExpanded(expanded: boolean): void {
if (this.expanded === expanded) {
return;
@@ -99,13 +94,6 @@ 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)} ${hint}`;
- }
-
- const prefixWidth = visibleWidth(`◆ ${label} · ${participant} · `);
- const preview = agentMessagePreview(prefixWidth, this.message.details.message);
- return `${agentMessageSummaryLine(label, participant, preview)} ${hint}`;
+ return agentMessageSummaryLine(label, participant);
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
index 0d90836547..3efc563152 100644
--- a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
@@ -1,16 +1,7 @@
import { resolve, sep } from "node:path";
import { pathToFileURL } from "node:url";
import type { AssistantMessage } from "@earendil-works/pi-ai";
-import {
- type Component,
- Container,
- Markdown,
- type MarkdownTheme,
- Spacer,
- Text,
- truncateToWidth,
- visibleWidth,
-} from "@earendil-works/pi-tui";
+import { type Component, Container, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";
import { LOGIN_RECOVERY_MESSAGE } from "../../../core/auth-guidance.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
import {
@@ -19,7 +10,6 @@ import {
shouldCollapseErrorDetails,
summarizeErrorDetails,
} from "./collapsible-error.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
import type { MermaidMarkdownTransform } from "./mermaid.js";
const OSC133_ZONE_START = "\x1b]133;A\x07";
@@ -30,13 +20,13 @@ const LOGIN_RECOVERY_SUFFIX = `\n\n${LOGIN_RECOVERY_MESSAGE}`;
export interface AssistantMessageComponentOptions {
cwd?: string;
expanded?: boolean;
- precededByToolActivity?: boolean;
+ precededByToolActivity?: boolean | (() => boolean);
/** Replaces Mermaid code blocks in assistant text (never thinking) with Unicode diagrams. */
mermaidTransform?: MermaidMarkdownTransform;
}
function getThinkingMarkdownTheme(baseTheme: MarkdownTheme): MarkdownTheme {
- const quiet = (text: string) => theme.fg("thinkingText", text);
+ const quiet = (text: string) => theme.fg("dim", text);
return {
...baseTheme,
heading: quiet,
@@ -53,49 +43,6 @@ 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)) {
@@ -120,7 +67,6 @@ export class AssistantMessageComponent extends Container {
private contentContainer: Container;
private hideThinkingBlock: boolean;
private markdownTheme: MarkdownTheme;
- private hiddenThinkingLabel: string;
private lastMessage?: AssistantMessage;
private hasToolCalls = false;
private expanded = false;
@@ -128,7 +74,8 @@ export class AssistantMessageComponent extends Container {
private lastSignature?: string;
private blockMarkdowns = new Map<number, Markdown>();
private lastBlockTexts = new Map<number, string>();
- private precededByToolActivity: boolean;
+ private precededByToolActivity: boolean | (() => boolean);
+ private lastPrecededByToolActivity?: boolean;
private mermaidTransform?: MermaidMarkdownTransform;
private baseUrl?: string;
private isStreaming = false;
@@ -137,14 +84,12 @@ export class AssistantMessageComponent extends Container {
message?: AssistantMessage,
hideThinkingBlock = false,
markdownTheme: MarkdownTheme = getMarkdownTheme(),
- hiddenThinkingLabel = "Thinking...",
options: AssistantMessageComponentOptions = {},
) {
super();
this.hideThinkingBlock = hideThinkingBlock;
this.markdownTheme = markdownTheme;
- this.hiddenThinkingLabel = hiddenThinkingLabel;
this.expanded = options.expanded ?? false;
this.precededByToolActivity = options.precededByToolActivity ?? false;
this.mermaidTransform = options.mermaidTransform;
@@ -171,11 +116,6 @@ export class AssistantMessageComponent extends Container {
this.dirty = true;
}
- setHiddenThinkingLabel(label: string): void {
- this.hiddenThinkingLabel = label;
- this.dirty = true;
- }
-
setExpanded(expanded: boolean): void {
if (this.expanded !== expanded) {
this.expanded = expanded;
@@ -184,6 +124,12 @@ export class AssistantMessageComponent extends Container {
}
override render(width: number): string[] {
+ const precededByToolActivity = this.isPrecededByToolActivity();
+ if (this.lastPrecededByToolActivity !== precededByToolActivity) {
+ this.lastPrecededByToolActivity = precededByToolActivity;
+ this.lastSignature = undefined;
+ this.dirty = true;
+ }
if (this.dirty) {
if (this.lastMessage) {
this.reconcile(this.lastMessage);
@@ -200,6 +146,40 @@ export class AssistantMessageComponent extends Container {
return lines;
}
+ private isPrecededByToolActivity(): boolean {
+ return typeof this.precededByToolActivity === "function"
+ ? this.precededByToolActivity()
+ : this.precededByToolActivity;
+ }
+
+ private hasVisibleBody(): boolean {
+ return (this.lastMessage?.content ?? []).some(
+ (content) =>
+ (content?.type === "text" && content.text.trim()) ||
+ (content?.type === "thinking" && !this.hideThinkingBlock && content.thinking.trim()),
+ );
+ }
+
+ /** Mirrors the trailing separator rendered before this message's tool calls. */
+ hasTrailingSpace(): boolean {
+ return (
+ !!this.lastMessage?.content.some((content) => content?.type === "toolCall") &&
+ (this.hasVisibleBody() || this.lastMessage.stopReason === "aborted" || !this.isPrecededByToolActivity())
+ );
+ }
+
+ getSpacingContent(): "visible" | "tool-only" | "hidden" {
+ const message = this.lastMessage;
+ const hasToolCalls = message?.content.some((content) => content?.type === "toolCall");
+ if (
+ this.hasVisibleBody() ||
+ message?.stopReason === "aborted" ||
+ (message?.stopReason === "error" && !hasToolCalls)
+ )
+ return "visible";
+ return hasToolCalls ? "tool-only" : "hidden";
+ }
+
updateContent(message: AssistantMessage, isStreaming = this.isStreaming): void {
this.lastMessage = message;
this.isStreaming = isStreaming;
@@ -219,19 +199,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 ?? "invalid"}`);
}
}
parts.push(
`hide:${this.hideThinkingBlock}`,
- `label:${this.hiddenThinkingLabel}`,
`expanded:${this.expanded}`,
// In the signature so the streaming->final transition rebuilds (mermaid renders differently).
`streaming:${this.isStreaming}`,
@@ -277,7 +250,9 @@ export class AssistantMessageComponent extends Container {
this.lastBlockTexts.clear();
const hasVisibleContent = message.content.some(
- (c) => (c?.type === "text" && c.text.trim()) || (c?.type === "thinking" && c.thinking.trim()),
+ (c) =>
+ (c?.type === "text" && c.text.trim()) ||
+ (c?.type === "thinking" && !this.hideThinkingBlock && c.thinking.trim()),
);
if (hasVisibleContent) {
@@ -292,46 +267,39 @@ export class AssistantMessageComponent extends Container {
// Set paddingY=0 to avoid extra spacing before tool executions
const mermaidTransform = this.mermaidTransform;
const isStreaming = this.isStreaming;
- const markdown = new Markdown(content.text.trim(), 1, 0, this.markdownTheme, undefined, {
- baseUrl: this.baseUrl,
- transform:
- mermaidTransform && ((md, availableWidth) => mermaidTransform(md, availableWidth, isStreaming)),
- });
+ const markdown = new Markdown(
+ content.text.trim(),
+ 1,
+ 0,
+ this.markdownTheme,
+ {
+ color: (text: string) => theme.fg("mdBody", text),
+ },
+ {
+ baseUrl: this.baseUrl,
+ transform:
+ mermaidTransform && ((md, availableWidth) => mermaidTransform(md, availableWidth, isStreaming)),
+ },
+ );
this.blockMarkdowns.set(i, markdown);
this.lastBlockTexts.set(i, content.text.trim());
this.contentContainer.addChild(markdown);
} else if (content?.type === "thinking" && content.thinking.trim()) {
- // Add spacing only when another visible assistant content block follows.
- // This avoids a superfluous blank line before separately-rendered tool execution blocks.
- const hasVisibleContentAfter = message.content
- .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) {
- // 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 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),
- );
+ // Hidden thinking renders nothing at all; the working loader in the
+ // tray is the activity signal while the rows are hidden.
+ if (!this.hideThinkingBlock) {
+ // Add spacing only when another visible assistant content block follows.
+ const hasVisibleContentAfter = message.content
+ .slice(i + 1)
+ .some((c) => (c?.type === "text" && c.text.trim()) || (c?.type === "thinking" && c.thinking.trim()));
+
const markdown = new Markdown(
content.thinking.trim(),
1,
0,
getThinkingMarkdownTheme(this.markdownTheme),
{
- color: (text: string) => theme.fg("thinkingText", text),
+ color: (text: string) => theme.fg("dim", text),
},
{ baseUrl: this.baseUrl },
);
@@ -360,7 +328,7 @@ export class AssistantMessageComponent extends Container {
this.contentContainer.addChild(this.createErrorComponent(errorMsg, "Error"));
}
- if (hasToolCalls && (hasVisibleContent || message.stopReason === "aborted" || !this.precededByToolActivity)) {
+ if (hasToolCalls && (hasVisibleContent || message.stopReason === "aborted" || !this.isPrecededByToolActivity())) {
this.contentContainer.addChild(new Spacer(1));
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
index 2026e3fec9..27f2561d62 100644
--- a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
+++ b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
@@ -8,7 +8,7 @@ import {
} from "../../../core/tools/truncate.js";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
-import { expandCollapseHint, keyText } from "./keybinding-hints.js";
+import { keyText } from "./keybinding-hints.js";
import { truncateToVisualLines } from "./visual-truncate.js";
const PREVIEW_LINES = 20;
@@ -41,7 +41,7 @@ export class BashExecutionComponent extends Container {
this.contentContainer = new Container();
this.addChild(this.contentContainer);
- const header = new Text(theme.fg(colorKey, theme.bold(`$ ${command}`)), 1, 0);
+ const header = new Text(theme.fg(colorKey, `$ ${command}`), 1, 0);
this.contentContainer.addChild(header);
this.loader = new Loader(
@@ -127,7 +127,7 @@ export class BashExecutionComponent extends Container {
this.contentContainer.clear();
- const header = new Text(theme.fg("bashMode", theme.bold(`$ ${this.command}`)), 1, 0);
+ const header = new Text(theme.fg("bashMode", `$ ${this.command}`), 1, 0);
this.contentContainer.addChild(header);
if (availableLines.length > 0) {
@@ -162,14 +162,8 @@ export class BashExecutionComponent extends Container {
} else {
const statusParts: string[] = [];
- if (hiddenLineCount > 0) {
- if (this.expanded) {
- statusParts.push(expandCollapseHint("app.tools.expand", true));
- } else {
- statusParts.push(
- `${theme.fg("muted", `... ${hiddenLineCount} more lines`)} ${expandCollapseHint("app.tools.expand", false)}`,
- );
- }
+ if (hiddenLineCount > 0 && !this.expanded) {
+ statusParts.push(theme.fg("muted", `... ${hiddenLineCount} more lines`));
}
if (this.status === "cancelled") {
diff --git a/packages/coding-agent/src/modes/interactive/components/config-selector.ts b/packages/coding-agent/src/modes/interactive/components/config-selector.ts
index 208456f9bd..9fbb7d7f3c 100644
--- a/packages/coding-agent/src/modes/interactive/components/config-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/config-selector.ts
@@ -161,7 +161,7 @@ class ConfigSelectorHeader implements Component {
invalidate(): void {}
render(width: number): string[] {
- const title = theme.bold("Resource Configuration");
+ const title = "Resource Configuration";
const sep = theme.fg("muted", " · ");
const hint = rawKeyHint("space", "toggle") + sep + rawKeyHint("esc", "close");
const hintWidth = visibleWidth(hint);
@@ -333,7 +333,7 @@ class ResourceList implements Component, Focusable {
if (entry.type === "group") {
// Main group header (no cursor)
- const groupLine = theme.fg("accent", theme.bold(entry.group.label));
+ const groupLine = theme.fg("accent", entry.group.label);
lines.push(truncateToWidth(` ${groupLine}`, width, ""));
} else if (entry.type === "subgroup") {
// Subgroup header (indented, no cursor)
diff --git a/packages/coding-agent/src/modes/interactive/components/context-tree-format.ts b/packages/coding-agent/src/modes/interactive/components/context-tree-format.ts
index fd0129cf70..d7c32794d9 100644
--- a/packages/coding-agent/src/modes/interactive/components/context-tree-format.ts
+++ b/packages/coding-agent/src/modes/interactive/components/context-tree-format.ts
@@ -128,7 +128,7 @@ export function formatContextTree(root: ContextTreeNode, width: number): string
);
const lines: string[] = [];
- lines.push(theme.bold("Context"));
+ lines.push("Context");
lines.push("");
if (root.model) {
lines.push(`${theme.fg("dim", "Model:")} ${root.model.provider}/${root.model.id}`);
@@ -165,7 +165,7 @@ export function formatContextTree(root: ContextTreeNode, width: number): string
);
lines.push("");
- lines.push(theme.bold("Tokens"));
+ lines.push("Tokens");
lines.push(`${theme.fg("dim", "Input:")} ${totals.input.toLocaleString()}`);
lines.push(`${theme.fg("dim", "Output:")} ${totals.output.toLocaleString()}`);
if (totals.cacheRead > 0) {
@@ -178,14 +178,14 @@ export function formatContextTree(root: ContextTreeNode, width: number): string
if (totals.cost.total > 0) {
lines.push("");
- lines.push(theme.bold("Cost"));
+ lines.push("Cost");
lines.push(`${theme.fg("dim", "Total:")} $${totals.cost.total.toFixed(4)}`);
}
const rootContext = root.contextUsage;
if (rootContext) {
lines.push("");
- lines.push(theme.bold("Context"));
+ lines.push("Context");
if (rootContext.tokens === null || rootContext.percent === null) {
lines.push(`${theme.fg("dim", "Current:")} unknown after compaction`);
} else {
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
index e4075bb4be..d2d7026f09 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -2,7 +2,9 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { Component, MarkdownTheme, TUI } from "@earendil-works/pi-tui";
import { isAgentSessionMessage } from "../../../core/agent-messages.js";
import {
+ ASYNC_BASH_COMPLETION_CUSTOM_TYPE,
COMPACTION_OUTCOME_CUSTOM_TYPE,
+ type CustomMessage,
isCompactionOutcomeMessage,
isRefinementOutcomeMessage,
isSessionSlashCommandMessage,
@@ -24,6 +26,7 @@ import {
MalformedRefinementOutcomeMessageComponent,
RefinementOutcomeMessageComponent,
} from "./refinement-outcome-message.js";
+import { readShellCompletion, ShellCompletionComponent } from "./shell-completion.js";
import { SlashCommandMessageComponent } from "./slash-command-message.js";
import { SlashCommandResultMessageComponent } from "./slash-command-result-message.js";
import {
@@ -41,9 +44,7 @@ export interface ConversationComponentsOptions {
getToolDefinition: (name: string) => ToolExecutionDefinition | undefined;
markdownTheme?: MarkdownTheme;
hideThinkingBlock?: boolean;
- hiddenThinkingLabel?: string;
toolsExpanded?: boolean;
- agentMessagesExpanded?: boolean;
editDiffsExpanded?: boolean;
isRecognizedSlashCommand?: (name: string) => boolean;
}
@@ -53,10 +54,55 @@ export function isCompactAgentMessageNeighbor(component: Component | undefined):
component instanceof AgentMessageComponent ||
component instanceof ToolExecutionComponent ||
component instanceof IPythonCellComponent ||
- component instanceof BashExecutionComponent
+ component instanceof BashExecutionComponent ||
+ component instanceof ShellCompletionComponent
);
}
+export interface ConversationSpacing {
+ precededByToolActivity: () => boolean;
+ shouldAddLeadingSpace: (expanded: boolean) => boolean;
+}
+
+/** Keep spacing responsive to hidden thinking and late shell attachment without rendering prior blocks again. */
+export function createConversationSpacing(previous: readonly Component[]): ConversationSpacing {
+ const last = previous.at(-1);
+ let lastIndex = previous.length - 1;
+ const getPrevious = (): { component: Component; trailingSpace: boolean } | undefined => {
+ if (!last) return undefined;
+ if (previous[lastIndex] !== last) lastIndex = previous.indexOf(last);
+ let toolSeparator: AssistantMessageComponent | undefined;
+ for (let index = lastIndex; index >= 0; index--) {
+ const component = previous[index]!;
+ if (component instanceof AssistantMessageComponent) {
+ const content = component.getSpacingContent();
+ if (content === "hidden") continue;
+ if (content === "tool-only") {
+ toolSeparator ??= component;
+ continue;
+ }
+ return toolSeparator
+ ? { component: toolSeparator, trailingSpace: true }
+ : { component, trailingSpace: component.hasTrailingSpace() };
+ }
+ if (component instanceof ShellCompletionComponent && !component.isVisible()) continue;
+ if (toolSeparator && !isCompactAgentMessageNeighbor(component)) {
+ return { component: toolSeparator, trailingSpace: true };
+ }
+ return { component, trailingSpace: false };
+ }
+ return toolSeparator ? { component: toolSeparator, trailingSpace: true } : undefined;
+ };
+ return {
+ precededByToolActivity: () => isCompactAgentMessageNeighbor(getPrevious()?.component),
+ shouldAddLeadingSpace: (expanded) => {
+ const preceding = getPrevious();
+ if (preceding?.trailingSpace) return false;
+ return expanded ? preceding !== undefined : !isCompactAgentMessageNeighbor(preceding?.component);
+ },
+ };
+}
+
function readUserText(content: string | Array<{ type: string; text?: string }>): string {
if (typeof content === "string") {
return content;
@@ -69,6 +115,46 @@ function readUserText(content: string | Array<{ type: string; text?: string }>):
.join("");
}
+export function createShellCompletionComponent(
+ message: CustomMessage,
+ previous: readonly Component[],
+): ShellCompletionComponent | undefined {
+ if (message.customType !== ASYNC_BASH_COMPLETION_CUSTOM_TYPE) return undefined;
+ const spacing = createConversationSpacing(previous);
+ const component = new ShellCompletionComponent(message, false, {
+ shouldAddLeadingSpace: spacing.shouldAddLeadingSpace,
+ });
+ const completion = readShellCompletion(message);
+ if (!completion) return component;
+ const tools = previous.filter((entry): entry is ToolExecutionComponent => entry instanceof ToolExecutionComponent);
+ const cleanups: (() => void)[] = [];
+ const attach = () => {
+ // A completion can arrive before its creating cell's final tool result.
+ if (tools.some((tool) => tool.isResultPending())) return;
+ for (const cleanup of cleanups) cleanup();
+ const commandMatches = tools.filter(
+ (tool) =>
+ (tool.getBackgroundShellHandle()?.command ?? tool.getAssignedShellCommand()) === completion.details.command,
+ );
+ const pidMatches = commandMatches.filter(
+ (tool) => tool.getBackgroundShellHandle()?.pid === completion.details.pid,
+ );
+ const matches = pidMatches.length > 0 ? pidMatches : commandMatches;
+ if (matches.length !== 1) {
+ // An observed PID/command has ended, but its result cannot be assigned to one duplicate call.
+ for (const tool of pidMatches) tool.markShellCompletionAmbiguous();
+ return;
+ }
+ const match = matches[0]!;
+ const handle = match.getBackgroundShellHandle();
+ if (handle && handle.pid !== completion.details.pid) return;
+ if (match.attachShellCompletion(completion)) component.setAttached();
+ };
+ for (const tool of tools) if (tool.isResultPending()) cleanups.push(tool.onResultUpdate(attach));
+ attach();
+ return component;
+}
+
/** Build conversation components from a message list, matching tool results to their calls. */
export function buildConversationComponents(
messages: readonly AgentMessage[],
@@ -77,41 +163,36 @@ export function buildConversationComponents(
const components: Component[] = [];
const pendingTools = new Map<string, ToolExecutionComponent>();
const expanded = options.toolsExpanded ?? false;
- const agentMessagesExpanded = options.agentMessagesExpanded ?? false;
const editDiffsExpanded = options.editDiffsExpanded ?? false;
for (const message of messages) {
if (message.role === "assistant") {
components.push(
- new AssistantMessageComponent(
- message,
- options.hideThinkingBlock ?? false,
- options.markdownTheme,
- options.hiddenThinkingLabel ?? "Thinking...",
- {
- cwd: options.cwd,
- expanded,
- precededByToolActivity:
- components.at(-1) instanceof ToolExecutionComponent ||
- components.at(-1) instanceof AgentMessageComponent,
- },
- ),
+ new AssistantMessageComponent(message, options.hideThinkingBlock ?? false, options.markdownTheme, {
+ cwd: options.cwd,
+ expanded,
+ precededByToolActivity: createConversationSpacing(components).precededByToolActivity,
+ }),
);
for (const content of message.content) {
if (content.type !== "toolCall") {
continue;
}
+ const spacing = createConversationSpacing(components);
const tool = new ToolExecutionComponent(
content.name,
content.id,
content.arguments,
- { ...options.toolOptions, includeImageDimensions: false },
+ {
+ ...options.toolOptions,
+ includeImageDimensions: false,
+ shouldAddLeadingSpace: () => spacing.shouldAddLeadingSpace(true),
+ },
options.getToolDefinition(content.name),
options.ui,
options.cwd,
);
tool.setExpanded(expanded);
- tool.setAgentMessagesExpanded(agentMessagesExpanded);
tool.setEditDiffsExpanded(editDiffsExpanded);
tool.markExecutionStarted();
tool.setArgsComplete();
@@ -159,12 +240,14 @@ export function buildConversationComponents(
components.push(component);
} else if (isAgentSessionMessage(message) && message.display) {
const component = new AgentMessageComponent(message, options.markdownTheme, {
- suppressLeadingSpace: isCompactAgentMessageNeighbor(components.at(-1)),
+ shouldAddLeadingSpace: createConversationSpacing(components).shouldAddLeadingSpace,
});
- component.setExpanded(agentMessagesExpanded);
+ component.setExpanded(expanded);
components.push(component);
} else if (isInjectedPromptMessage(message) && message.display) {
- const component = new InjectedPromptMessageComponent(message, options.markdownTheme);
+ const component =
+ createShellCompletionComponent(message, components) ??
+ new InjectedPromptMessageComponent(message, options.markdownTheme);
component.setExpanded(expanded);
components.push(component);
} else if (message.role === "user") {
diff --git a/packages/coding-agent/src/modes/interactive/components/earendil-announcement.ts b/packages/coding-agent/src/modes/interactive/components/earendil-announcement.ts
index 6f5a0bde5c..0101c4bcca 100644
--- a/packages/coding-agent/src/modes/interactive/components/earendil-announcement.ts
+++ b/packages/coding-agent/src/modes/interactive/components/earendil-announcement.ts
@@ -29,7 +29,7 @@ export class EarendilAnnouncementComponent extends Container {
super();
this.addChild(new DynamicBorder((text) => theme.fg("accent", text)));
- this.addChild(new Text(theme.bold(theme.fg("accent", "pi has joined Earendil")), 1, 0));
+ this.addChild(new Text(theme.fg("accent", "pi has joined Earendil"), 1, 0));
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("muted", "Read the blog post:"), 1, 0));
this.addChild(new Text(theme.fg("mdLink", BLOG_URL), 1, 0));
diff --git a/packages/coding-agent/src/modes/interactive/components/edit-summary.ts b/packages/coding-agent/src/modes/interactive/components/edit-summary.ts
index dacf64e261..aa17ca8820 100644
--- a/packages/coding-agent/src/modes/interactive/components/edit-summary.ts
+++ b/packages/coding-agent/src/modes/interactive/components/edit-summary.ts
@@ -8,7 +8,6 @@ import type { IpythonToolDetails } from "../../../core/tools/ipython.js";
import { resolveToCwd } from "../../../core/tools/path-utils.js";
import { canonicalizePath, formatPathRelativeToCwdOrAbsolute } from "../../../utils/paths.js";
import { theme } from "../theme/theme.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
export interface FileChangeSummary {
path: string;
@@ -82,8 +81,8 @@ export function mergeTurnFileChanges(
/** Dim gutter that anchors every per-file change summary line. */
const FILE_CHANGE_SUMMARY_PREFIX = " ╰─ ";
-/** Indent that aligns diff rows with the summary line's text column. */
-export const FILE_CHANGE_DIFF_INDENT = " ".repeat(visibleWidth(FILE_CHANGE_SUMMARY_PREFIX));
+/** Standard content inset for full-width diff rows. */
+export const FILE_CHANGE_DIFF_INDENT = " ";
function formatChangeCounts(change: Pick<FileChangeSummary, "added" | "removed">): string {
return `${theme.fg("toolDiffAdded", `+${change.added}`)} ${theme.fg("toolDiffRemoved", `-${change.removed}`)}`;
@@ -98,31 +97,21 @@ function formatFileChangePath(path: string, cwd: string): string {
/**
* One ` ╰─ <path> +N -M` row, truncated to width; the path renders relative
- * to cwd where possible and the hint renders only when diffsExpanded is defined.
+ * to cwd where possible.
*/
export function formatFileChangeSummaryLine(
rawPath: string,
cwd: string | undefined,
change: Pick<FileChangeSummary, "added" | "removed">,
- diffsExpanded: boolean | undefined,
width: number,
): string {
const prefix = theme.fg("dim", FILE_CHANGE_SUMMARY_PREFIX);
- const hint =
- diffsExpanded === undefined
- ? ""
- : `${theme.fg("dim", " · ")}${expandCollapseHint("app.edits.expand", diffsExpanded)}`;
- // Size the path against the wider hint variant ("to collapse") so toggling
- // ctrl+j never re-truncates it — the summary line is a stable anchor.
- const widestHint =
- diffsExpanded === undefined ? "" : `${theme.fg("dim", " · ")}${expandCollapseHint("app.edits.expand", true)}`;
const counts = `${theme.fg("dim", " ")}${formatChangeCounts(change)}`;
- const suffix = `${counts}${hint}`;
const safeWidth = Math.max(1, width);
- const available = Math.max(1, safeWidth - visibleWidth(prefix) - visibleWidth(counts) - visibleWidth(widestHint));
+ const available = Math.max(1, safeWidth - visibleWidth(prefix) - visibleWidth(counts));
const displayPath = cwd === undefined ? rawPath : formatFileChangePath(rawPath, cwd);
const path = truncateToWidth(displayPath, available, "…");
- return truncateToWidth(`${prefix}${theme.fg("muted", path)}${suffix}`, safeWidth, "");
+ return truncateToWidth(`${prefix}${theme.fg("muted", path)}${counts}`, safeWidth, "");
}
export function formatTotalChangeSummary(changes: readonly FileChangeSummary[]): string {
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.ts
index 4e96c827b3..a639f930b3 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
@@ -11,7 +11,6 @@ import {
import { GOAL_CONTEXT_CUSTOM_TYPE, type GoalContextDetails } from "../../../core/goals.js";
import {
ASYNC_BASH_COMPLETION_CUSTOM_TYPE,
- ASYNC_BASH_COMPLETION_PREVIEW_LABEL,
type AsyncBashCompletionDetails,
type CustomMessage,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
@@ -24,8 +23,8 @@ import {
type RlmChildTerminalNoticeDetails,
} from "../../../core/messages.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
-import { agentMessageSummaryLine } from "./agent-message.js";
import { expandCollapseHint } from "./keybinding-hints.js";
+import { ShellCompletionComponent } from "./shell-completion.js";
type InjectedPromptDetails =
| AsyncBashCompletionDetails
@@ -95,7 +94,7 @@ export class InjectedPromptMessageComponent extends Container {
private readonly markdownTheme: MarkdownTheme = getMarkdownTheme(),
) {
super();
- this.addChild(new Spacer(1));
+ if (this.message.customType !== ASYNC_BASH_COMPLETION_CUSTOM_TYPE) this.addChild(new Spacer(1));
this.addChild(this.content);
this.updateDisplay();
}
@@ -115,6 +114,12 @@ export class InjectedPromptMessageComponent extends Container {
private updateDisplay(): void {
this.content.clear();
+ if (this.message.customType === ASYNC_BASH_COMPLETION_CUSTOM_TYPE) {
+ const shell = new ShellCompletionComponent(this.message);
+ shell.setExpanded(this.expanded);
+ this.content.addChild(shell);
+ return;
+ }
this.header.setText(this.headerText());
this.content.addChild(this.header);
if (this.expanded && this.message.customType !== IPYTHON_STATE_RESTORED_CUSTOM_TYPE) {
@@ -131,15 +136,6 @@ export class InjectedPromptMessageComponent extends Container {
if (this.message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE) {
return this.heartbeatHeaderText();
}
- if (this.message.customType === ASYNC_BASH_COMPLETION_CUSTOM_TYPE) {
- const details = this.message.details as AsyncBashCompletionDetails | undefined;
- const participant = details ? `pid ${details.pid}` : "bash";
- const status = details ? `exit ${details.exitCode}` : undefined;
- const hint = this.expanded ? "" : ` ${expandCollapseHint("app.tools.expand", false)}`;
- return (
- agentMessageSummaryLine(ASYNC_BASH_COMPLETION_PREVIEW_LABEL, participant, status) + theme.fg("dim", hint)
- );
- }
if (this.message.customType === IPYTHON_STATE_RESTORED_CUSTOM_TYPE) {
const details = this.message.details as IpythonStateRestoredDetails | undefined;
const label = details?.restored === false ? "Started fresh Python kernel" : "Restored Python kernel state";
diff --git a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
index 97be0c4c11..c0fbd5fd65 100644
--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
@@ -6,16 +6,16 @@ import {
wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { formatAgentMessageParticipant } from "../../../core/agent-messages.js";
-import { previewIpythonCode } from "../../../core/tools/code-preview.js";
+import { previewIpythonCode, pythonStatementLines } from "../../../core/tools/code-preview.js";
import { generateDiffString } from "../../../core/tools/edit-diff.js";
import { parseIpythonBashCell } from "../../../core/tools/ipython-cell-code.js";
import { getLanguageFromPath, highlightCode, theme } from "../theme/theme.js";
import { getWorkingPulseFrame, WORKING_ICON_FRAMES, workingIconFrame } from "../theme/working-icon.js";
-import { agentMessageBodyLines, agentMessagePreview, agentMessageSummaryLine } from "./agent-message.js";
+import { agentMessageBodyLines, agentMessageSummaryLine } from "./agent-message.js";
import { normalizeErrorDetails, summarizeErrorDetails } from "./collapsible-error.js";
import { renderDiffSeparator, renderRichDiff } from "./diff.js";
import { countChangedLines, FILE_CHANGE_DIFF_INDENT, formatFileChangeSummaryLine } from "./edit-summary.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
+import type { BackgroundShellHandle, ShellCompletion } from "./shell-completion.js";
export interface IPythonCellContentBlock {
type: string;
@@ -26,12 +26,14 @@ export interface IPythonCellContentBlock {
export interface IPythonCellState {
code: string;
+ backgroundShell?: BackgroundShellHandle;
+ shellCompletion?: ShellCompletion;
+ shellCompletionAmbiguous?: boolean;
content?: readonly IPythonCellContentBlock[];
details?: unknown;
isPartial?: boolean;
isError?: boolean;
expanded?: boolean;
- agentMessagesExpanded?: boolean;
editDiffsExpanded?: boolean;
showExpandHint?: boolean;
executionStarted?: boolean;
@@ -87,8 +89,8 @@ interface TracebackParts {
const MAGIC_LINE_PATTERN = /^\s*!/;
-// Two columns, matching the code body's "› "/" " gutter so output aligns under it.
-const OUTPUT_INDENT = " ";
+// Match the agent-message tree gutter; input and output text share the same column.
+const OUTPUT_INDENT = " ";
const SGR_PATTERN = /\x1b\[([0-9;]*)m/g;
@@ -396,19 +398,23 @@ export class IPythonCellComponent implements Component {
const parts = [`${this.marker(details)} ${theme.fg("muted", languageLabel)}`];
if (preview.text) {
- parts.push(this.highlightInputLine(preview.text, preview.language === "bash"));
+ // Collapsed preview stays plain and dim so the one-line summary reads as
+ // quiet metadata; the expanded block below keeps full highlighting.
+ parts.push(theme.fg("dim", preview.text));
} else if (!this.state.executionStarted) {
- parts.push(theme.fg("muted", "waiting for code"));
+ parts.push(theme.fg("dim", "waiting for code"));
}
const counts = this.lineCounts(details);
if (counts) {
- parts.push(theme.fg("muted", counts));
+ parts.push(theme.fg("dim", counts));
}
const duration = formatDuration(details.durationMs);
if (duration) {
- parts.push(theme.fg("muted", duration));
+ parts.push(
+ theme.fg("dim", this.state.backgroundShell || this.state.shellCompletion ? `cell ${duration}` : duration),
+ );
}
const errorName = !this.state.isPartial ? (details.error?.ename ?? details.errorEname) : undefined;
@@ -416,9 +422,10 @@ export class IPythonCellComponent implements Component {
parts.push(theme.fg("error", errorName));
}
- if (this.state.showExpandHint !== false) {
- parts.push(expandCollapseHint("app.tools.expand", this.state.expanded === true));
- }
+ if (this.state.shellCompletionAmbiguous) parts.push(theme.fg("dim", "completion unmatched"));
+
+ const shellExit = this.state.shellCompletion?.details.exitCode ?? this.state.backgroundShell?.exitCode;
+ if (shellExit !== undefined && shellExit !== 0) parts.push(theme.fg("error", `exit ${shellExit}`));
return parts.join(theme.fg("dim", " · "));
}
@@ -468,6 +475,11 @@ export class IPythonCellComponent implements Component {
private statusKind(details: IpythonDetails): "error" | "aborted" | "running" | "queued" | "done" {
const status = details.status;
+ if (this.state.shellCompletionAmbiguous) return "queued";
+ if ((this.state.backgroundShell || this.state.shellCompletion) && !this.state.isPartial) {
+ const exitCode = this.state.shellCompletion?.details.exitCode ?? this.state.backgroundShell?.exitCode;
+ return exitCode === undefined ? "running" : exitCode === 0 ? "done" : "error";
+ }
if (this.state.isError || status === "error") {
return "error";
}
@@ -501,20 +513,24 @@ export class IPythonCellComponent implements Component {
private renderCode(lines: string[], width: number): boolean {
const code = this.state.code.trimEnd();
if (!code) {
- this.addBlank(lines, width);
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "waiting for code"), width);
+ this.addWrapped(lines, theme.fg("dim", "╰─ "), theme.fg("muted", "waiting for code"), width);
return false;
}
- this.addBlank(lines, width);
const isBashCell = parseIpythonBashCell(code) !== undefined;
const rawLines = code.split("\n");
- // Highlight the whole cell at once so multi-line strings keep their color.
- const highlightedLines = isBashCell ? [] : highlightCode(code, "python");
+ // Reopen inherited ANSI styles on each source line before gutters reset them.
+ const sourceWidth = rawLines.reduce((max, line) => Math.max(max, visibleWidth(line)), 1);
+ const highlightedLines = isBashCell
+ ? []
+ : wrapTextWithAnsi(highlightCode(code, "python").join("\n"), sourceWidth);
+ const statementLines = isBashCell ? rawLines : pythonStatementLines(code);
for (const [index, rawLine] of rawLines.entries()) {
- const prefix = index === 0 ? theme.fg("dim", "› ") : theme.fg("dim", " ");
+ const prefix = index === 0 ? theme.fg("dim", "╰─ ") : OUTPUT_INDENT;
const highlighted =
- isBashCell || MAGIC_LINE_PATTERN.test(rawLine) || parseIpythonBashCell(rawLine) !== undefined
+ isBashCell ||
+ MAGIC_LINE_PATTERN.test(statementLines[index] ?? "") ||
+ parseIpythonBashCell(statementLines[index] ?? "") !== undefined
? theme.fg("bashMode", rawLine)
: (highlightedLines[index] ?? theme.fg("mdCodeBlock", rawLine));
this.addWrapped(lines, prefix, highlighted || " ", width);
@@ -523,14 +539,6 @@ export class IPythonCellComponent implements Component {
return true;
}
- private highlightInputLine(line: string, isBashCell: boolean): string {
- if (isBashCell || MAGIC_LINE_PATTERN.test(line) || parseIpythonBashCell(line) !== undefined) {
- return theme.fg("bashMode", line);
- }
- const highlighted = highlightCode(line, "python");
- return highlighted[0] ?? theme.fg("mdCodeBlock", line);
- }
-
// Only runs when expanded — shows full output below the code, no previews.
private renderOutput(lines: string[], width: number, details: IpythonDetails, hasCode: boolean): void {
const blocks = this.state.content ?? [];
@@ -547,6 +555,12 @@ export class IPythonCellComponent implements Component {
: undefined;
let outputStarted = false;
let renderedTextOutput = false;
+ let outputMarkerPending = true;
+ const outputPrefix = (): string => {
+ if (!outputMarkerPending) return OUTPUT_INDENT;
+ outputMarkerPending = false;
+ return theme.fg("dim", " › ");
+ };
const diffs = details.diffs ?? [];
const sentMessages = details.sentAgentMessages ?? [];
@@ -565,12 +579,12 @@ export class IPythonCellComponent implements Component {
if (details.stdout?.trim() && !isEditConfirmation(details.stdout, diffs)) {
startOutput();
renderedTextOutput = true;
- this.renderOutputText(lines, width, normalizeErrorDetails(details.stdout), "out");
+ this.renderOutputText(lines, width, normalizeErrorDetails(details.stdout), "out", outputPrefix);
}
if (details.stderr?.trim()) {
startOutput();
renderedTextOutput = true;
- this.renderOutputText(lines, width, normalizeErrorDetails(details.stderr), "err");
+ this.renderOutputText(lines, width, normalizeErrorDetails(details.stderr), "err", outputPrefix);
}
if (
details.result?.trim() &&
@@ -579,18 +593,24 @@ export class IPythonCellComponent implements Component {
) {
startOutput();
renderedTextOutput = true;
- this.renderOutputText(lines, width, normalizeErrorDetails(details.result), "out");
+ this.renderOutputText(lines, width, normalizeErrorDetails(details.result), "out", outputPrefix);
}
} else if (traceback) {
if (traceback.output) {
startOutput();
renderedTextOutput = true;
- this.renderOutputText(lines, width, traceback.output, "out");
+ this.renderOutputText(lines, width, traceback.output, "out", outputPrefix);
}
} else if (text.trim() && !isAgentMessageReceipt(text, sentMessages)) {
startOutput();
renderedTextOutput = true;
- this.renderOutputText(lines, width, normalizeErrorDetails(text), this.state.isError ? "err" : "out");
+ this.renderOutputText(
+ lines,
+ width,
+ normalizeErrorDetails(text),
+ this.state.isError ? "err" : "out",
+ outputPrefix,
+ );
}
// Without structured fields the fallback content text above already contains the appended background block.
@@ -603,10 +623,10 @@ export class IPythonCellComponent implements Component {
if (!renderedTextOutput && this.state.isPartial) {
startOutput();
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "waiting for output..."), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", "waiting for output..."), width);
} else if (!renderedTextOutput && this.state.executionStarted && !this.state.argsComplete) {
startOutput();
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "waiting for output..."), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", "waiting for output..."), width);
} else if (
!renderedTextOutput &&
!traceback &&
@@ -617,7 +637,7 @@ export class IPythonCellComponent implements Component {
imageCount === 0
) {
startOutput();
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "no output"), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", "no output"), width);
}
if (details.error) {
@@ -626,16 +646,17 @@ export class IPythonCellComponent implements Component {
lines,
width,
details.error.traceback.join("\n") || formatIpythonErrorSummary(details.error),
+ outputPrefix,
);
} else if (traceback) {
startOutput();
- this.renderTraceback(lines, width, traceback.traceback);
+ this.renderTraceback(lines, width, traceback.traceback, outputPrefix);
}
if (backgroundOutput) {
startOutput();
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "background output (unattributed)"), width);
- this.renderOutputText(lines, width, normalizeErrorDetails(backgroundOutput), "err");
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", "background output (unattributed)"), width);
+ this.renderOutputText(lines, width, normalizeErrorDetails(backgroundOutput), "err", outputPrefix);
}
if (imageCount > 0) {
@@ -643,43 +664,23 @@ export class IPythonCellComponent implements Component {
const text = this.state.showImages
? `${imageCount} image${imageCount === 1 ? "" : "s"} rendered below`
: `${imageCount} image${imageCount === 1 ? "" : "s"} hidden`;
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", text), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", text), width);
}
}
- // Summary line per message; expanding shows the message text in a `╰─` gutter
- // instead of the collapsed preview, matching received agent-message UI.
private renderSentAgentMessages(lines: string[], width: number, messages: readonly SentAgentMessageDisplay[]): void {
for (const message of messages) {
const label = message.deliveryStatus === "delivered" ? "Agent message sent" : "Agent message queued";
const recipient = formatAgentMessageParticipant("sent", message.receiverRole, message.target);
- const hint = expandCollapseHint("app.messages.expand", this.state.agentMessagesExpanded === true);
- if (this.state.agentMessagesExpanded) {
- this.addBlank(lines, width);
- this.addPlain(
- lines,
- truncateToWidth(`${agentMessageSummaryLine(label, recipient)} ${hint}`, Math.max(1, width - 1), "…"),
- );
- for (const bodyLine of agentMessageBodyLines(message.message, width)) {
- lines.push(bodyLine);
- }
- continue;
+ if (this.state.expanded) this.addBlank(lines, width);
+ this.addPlain(lines, truncateToWidth(agentMessageSummaryLine(label, recipient), Math.max(1, width - 1), "…"));
+ if (this.state.expanded) {
+ for (const line of agentMessageBodyLines(message.message, width)) lines.push(line);
}
- const prefixWidth = visibleWidth(`◆ ${label} · ${recipient} · `);
- const preview = agentMessagePreview(prefixWidth, message.message);
- this.addPlain(
- lines,
- truncateToWidth(
- `${agentMessageSummaryLine(label, recipient, preview)} ${hint}`,
- Math.max(1, width - 1),
- "…",
- ),
- );
}
}
- // The `╰─ <path> +N -M` summary line renders in both states; ctrl+j only
- // attaches or removes the indented diff rows underneath it.
+ // The path summary stays visible while conversation detail toggles the diff rows.
private renderDiffs(lines: string[], width: number, diffs: readonly DiffDisplay[], hasCode: boolean): void {
const diffsByPath = new Map<string, DiffDisplay[]>();
for (const diff of diffs) {
@@ -690,22 +691,14 @@ export class IPythonCellComponent implements Component {
if (hasCode) {
this.addPlain(lines, "");
}
- let index = 0;
for (const [path, edits] of diffsByPath) {
- index += 1;
- this.renderFileDiff(lines, width, path, edits, index === diffsByPath.size);
+ this.renderFileDiff(lines, width, path, edits);
}
}
- private renderFileDiff(
- lines: string[],
- width: number,
- path: string,
- edits: readonly DiffDisplay[],
- showHint: boolean,
- ): void {
+ private renderFileDiff(lines: string[], width: number, path: string, edits: readonly DiffDisplay[]): void {
const language = getLanguageFromPath(path);
- // Diff rows align with the summary line's text column (after the `╰─ ` gutter).
+ // The outer inset matches ordinary chat text; renderer gutters stay intact.
const indent = FILE_CHANGE_DIFF_INDENT.slice(0, Math.max(0, width - 1));
const contentWidth = Math.max(1, width - indent.length);
let added = 0;
@@ -728,27 +721,29 @@ export class IPythonCellComponent implements Component {
}
});
- // Unlike the ctrl+o hint (latest tool row only), the ctrl+j hint renders on
- // every tool row, matching the thinking and agent-message hints. Within a
- // row it renders once, on the last file's summary line (showHint).
- const hint = showHint ? this.state.editDiffsExpanded === true : undefined;
- lines.push(formatFileChangeSummaryLine(path, this.state.cwd, { added, removed }, hint, width));
+ lines.push(formatFileChangeSummaryLine(path, this.state.cwd, { added, removed }, width));
for (const row of rows) {
lines.push(row);
}
}
- private renderOutputText(lines: string[], width: number, text: string, label: "out" | "err"): void {
+ private renderOutputText(
+ lines: string[],
+ width: number,
+ text: string,
+ label: "out" | "err",
+ outputPrefix: () => string,
+ ): void {
const color = label === "err" ? "muted" : "toolOutput";
for (const line of text.split("\n")) {
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg(color, line || " "), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg(color, line || " "), width);
}
}
- private renderTraceback(lines: string[], width: number, traceback: string): void {
+ private renderTraceback(lines: string[], width: number, traceback: string, outputPrefix: () => string): void {
for (const line of traceback.split("\n")) {
- this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", line || " "), width);
+ this.addWrapped(lines, outputPrefix(), theme.fg("muted", line || " "), width);
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts b/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts
index 618b0e6399..2b578db173 100644
--- a/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts
+++ b/packages/coding-agent/src/modes/interactive/components/keybinding-hints.ts
@@ -66,9 +66,11 @@ export function keyHint(keybinding: Keybinding, description: string, options: Ke
return theme.fg("dim", keyText(keybinding, options)) + theme.fg("muted", ` ${description}`);
}
-/** Canonical bracketed expand/collapse hint, e.g. `(Ctrl+O to expand)`, fully dim. */
+/** Conversation detail uses the status bar; transcript rows omit shortcut hints. */
export function expandCollapseHint(keybinding: Keybinding, expanded: boolean): string {
- return theme.fg("dim", `(${keyText(keybinding)} ${expanded ? "to collapse" : "to expand"})`);
+ if (keybinding === "app.tools.expand") return "";
+ const action = expanded ? "to collapse" : "to expand";
+ return theme.fg("dim", `(${keyText(keybinding)} ${action})`);
}
export function rawKeyHint(key: string, description: string): string {
diff --git a/packages/coding-agent/src/modes/interactive/components/login-dialog.ts b/packages/coding-agent/src/modes/interactive/components/login-dialog.ts
index c3a20aaca8..f03cf8fd0c 100644
--- a/packages/coding-agent/src/modes/interactive/components/login-dialog.ts
+++ b/packages/coding-agent/src/modes/interactive/components/login-dialog.ts
@@ -57,7 +57,7 @@ class PrimeLoginHeader implements Component {
return [
...logoLines,
centeredLine("", safeWidth),
- centeredLine(theme.bold(theme.fg("text", "Login to Prime Inference")), safeWidth),
+ centeredLine(theme.fg("text", "Login to Prime Inference"), safeWidth),
centeredLine(
theme.fg("muted", "Connect your Prime Intellect account to enable Prime Inference models."),
safeWidth,
@@ -332,7 +332,7 @@ export class LoginDialogComponent extends Container implements Focusable {
}
private addSectionTitle(text: string): void {
- this.contentContainer.addChild(new Text(theme.bold(theme.fg("text", text)), 0, 0));
+ this.contentContainer.addChild(new Text(theme.fg("text", text), 0, 0));
}
private addLabel(text: string): void {
diff --git a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts b/packages/coding-agent/src/modes/interactive/components/menu-panel.ts
index 41e72209cd..9079f4e909 100644
--- a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts
+++ b/packages/coding-agent/src/modes/interactive/components/menu-panel.ts
@@ -281,7 +281,7 @@ export class MenuPanel extends Container {
const hasSubtitle = subtitle !== undefined && subtitle.length > 0;
const hasHeader = hasTitle || hasSubtitle;
if (hasTitle) {
- lines.push(surfaceLine(theme.bold(theme.fg("text", this.title)), safeWidth));
+ lines.push(surfaceLine(theme.fg("text", this.title), safeWidth));
}
if (hasSubtitle) {
lines.push(...surfaceWrappedLines(theme.fg("muted", subtitle), safeWidth));
diff --git a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
index 0a08f669ab..3bbe670cda 100644
--- a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
@@ -120,7 +120,7 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
this.addChild(new DynamicBorder());
this.addChild(new Spacer(1));
- this.addChild(new Text(theme.fg("accent", theme.bold("Model Configuration")), 0, 0));
+ this.addChild(new Text(theme.fg("accent", "Model Configuration"), 0, 0));
this.addChild(
new Text(theme.fg("muted", `Session-only. ${keyText("app.models.save")} to save to settings.`), 0, 0),
);
diff --git a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
index 8f2b6bd8f9..2820ba1597 100644
--- a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
@@ -45,7 +45,6 @@ export interface SettingsConfig {
availableThinkingLevels: ThinkingLevel[];
currentTheme: string;
availableThemes: string[];
- hideThinkingBlock: boolean;
mermaidRenderingMode: MermaidRenderingMode;
treeFilterMode: "default" | "no-tools" | "user-only" | "labeled-only" | "all";
showHardwareCursor: boolean;
@@ -72,7 +71,6 @@ export interface SettingsCallbacks {
onThinkingLevelChange: (level: ThinkingLevel) => void;
onThemeChange: (theme: string) => void;
onThemePreview?: (theme: string) => void;
- onHideThinkingBlockChange: (hidden: boolean) => void;
onMermaidRenderingModeChange: (mode: MermaidRenderingMode) => void;
onTreeFilterModeChange: (mode: "default" | "no-tools" | "user-only" | "labeled-only" | "all") => void;
onShowHardwareCursorChange: (enabled: boolean) => void;
@@ -142,7 +140,7 @@ class SelectSubmenu extends Container {
) {
super();
- this.addChild(new Text(theme.bold(theme.fg("accent", title)), 0, 0));
+ this.addChild(new Text(theme.fg("accent", title), 0, 0));
if (description) {
this.addChild(new Spacer(1));
@@ -237,13 +235,6 @@ export class SettingsSelectorComponent extends Container {
currentValue: config.transport,
values: ["sse", "websocket", "websocket-cached", "auto"],
},
- {
- id: "hide-thinking",
- label: "Hide thinking",
- description: "Hide thinking blocks in assistant responses",
- currentValue: config.hideThinkingBlock ? "true" : "false",
- values: ["true", "false"],
- },
{
id: "mermaid-rendering",
label: "Mermaid diagrams",
@@ -478,9 +469,6 @@ export class SettingsSelectorComponent extends Container {
case "transport":
callbacks.onTransportChange(newValue as Transport);
break;
- case "hide-thinking":
- callbacks.onHideThinkingBlockChange(newValue === "true");
- break;
case "mermaid-rendering":
callbacks.onMermaidRenderingModeChange(newValue as MermaidRenderingMode);
break;
diff --git a/packages/coding-agent/src/modes/interactive/components/shell-completion.ts b/packages/coding-agent/src/modes/interactive/components/shell-completion.ts
new file mode 100644
index 0000000000..69b20dced0
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/shell-completion.ts
@@ -0,0 +1,154 @@
+import type { Component } from "@earendil-works/pi-tui";
+import { Text, truncateToWidth } from "@earendil-works/pi-tui";
+import {
+ ASYNC_BASH_COMPLETION_CUSTOM_TYPE,
+ type AsyncBashCompletionDetails,
+ type CustomMessage,
+} from "../../../core/messages.js";
+import { theme } from "../theme/theme.js";
+
+export interface ShellCompletion {
+ details: AsyncBashCompletionDetails;
+ message: CustomMessage;
+}
+
+export interface BackgroundShellHandle {
+ pid: number;
+ command: string;
+ exitCode?: number;
+}
+
+export function readShellCompletion(message: CustomMessage): ShellCompletion | undefined {
+ if (message.customType !== ASYNC_BASH_COMPLETION_CUSTOM_TYPE) return undefined;
+ const details = message.details;
+ if (!details || typeof details !== "object") return undefined;
+ const record = details as Record<string, unknown>;
+ if (
+ typeof record.pid !== "number" ||
+ !Number.isSafeInteger(record.pid) ||
+ record.pid <= 0 ||
+ typeof record.command !== "string" ||
+ typeof record.exitCode !== "number" ||
+ !Number.isInteger(record.exitCode)
+ )
+ return undefined;
+ return { details: { pid: record.pid, command: record.command, exitCode: record.exitCode }, message };
+}
+
+function readPythonString(literal: string): string | undefined {
+ const quote = literal[0];
+ if ((quote !== "'" && quote !== '"') || literal.at(-1) !== quote) return undefined;
+ const escapes: Record<string, string> = { "\\": "\\", "'": "'", '"': '"', n: "\n", r: "\r", t: "\t" };
+ let value = "";
+ for (let index = 1; index < literal.length - 1; index++) {
+ const char = literal[index]!;
+ if (char === quote || char === "\n" || char === "\r") return undefined;
+ if (char !== "\\") {
+ value += char;
+ continue;
+ }
+ const escaped = escapes[literal[++index]!];
+ if (escaped === undefined || index >= literal.length - 1) return undefined;
+ value += escaped;
+ }
+ return value;
+}
+
+function readLiteralShellLaunch(code: string): { command: string; assignmentOnly: boolean } | undefined {
+ const launch = code
+ .trim()
+ .split("\n")
+ .filter((line) => line.trim() && !/^(?:from rlm import bash|import rlm)\s*$/.test(line));
+ // Split delimiters before matching the prefix so long malformed arguments cannot backtrack.
+ const source = launch[0]?.trimEnd() ?? "";
+ const open = source.indexOf("(");
+ if (open < 0 || !source.endsWith(")")) return undefined;
+ const call = /^(?:([A-Za-z_]\w*)\s*=\s*)?(?:rlm\.)?bash$/.exec(source.slice(0, open));
+ if (!call || (launch.length > 1 && (launch.length !== 2 || launch[1]?.trim() !== call[1]))) return undefined;
+ const command = readPythonString(source.slice(open + 1, -1).trim());
+ return command === undefined ? undefined : { command, assignmentOnly: !!call[1] && launch.length === 1 };
+}
+
+// Assignment-only cells save no handle repr. The caller must require a unique
+// exact command match; this does not infer a PID or inspect an await expression.
+export function readAssignedShellCommand(code: string, details: unknown): string | undefined {
+ if (!details || typeof details !== "object") return undefined;
+ const record = details as Record<string, unknown>;
+ if (record.status !== "ok" || (record.result !== undefined && record.result !== "")) return undefined;
+ const launch = readLiteralShellLaunch(code);
+ return launch?.assignmentOnly ? launch.command : undefined;
+}
+
+// Only literal commands and a complete handle repr establish identity. Ordinary
+// output containing PID digits or a similar command is deliberately insufficient.
+export function readBackgroundShellHandle(code: string, details: unknown): BackgroundShellHandle | undefined {
+ if (!details || typeof details !== "object" || !("result" in details) || typeof details.result !== "string")
+ return undefined;
+ const match =
+ /^<BashHandle pid=(\d+) (running|exit_code=-?\d+) command=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')>$/.exec(
+ details.result.trim(),
+ );
+ if (!match) return undefined;
+ const command = readPythonString(match[3]!);
+ if (command === undefined) return undefined;
+ const pid = Number(match[1]);
+ if (!Number.isSafeInteger(pid) || pid <= 0) return undefined;
+ if (readLiteralShellLaunch(code)?.command !== command) return undefined;
+ return { pid, command, exitCode: match[2] === "running" ? undefined : Number(match[2]!.slice(10)) };
+}
+
+export function shellCompletionText(completion: ShellCompletion): string {
+ const content = completion.message.content;
+ return typeof content === "string"
+ ? content
+ : content.map((block) => (block.type === "text" ? block.text : "[image]")).join("\n");
+}
+
+export function shellCompletionLabel(completion: ShellCompletion | undefined): string {
+ return completion && completion.details.exitCode !== 0
+ ? `Background shell command failed · exit ${completion.details.exitCode}`
+ : "Background shell command finished";
+}
+
+export class ShellCompletionComponent implements Component {
+ private expanded = false;
+ constructor(
+ private readonly message: CustomMessage,
+ private attached = false,
+ private readonly options: { shouldAddLeadingSpace?: (expanded: boolean) => boolean } = {},
+ ) {}
+ setAttached(): void {
+ this.attached = true;
+ }
+ setExpanded(expanded: boolean): void {
+ this.expanded = expanded;
+ }
+ isVisible(): boolean {
+ return !this.attached || this.expanded;
+ }
+ invalidate(): void {}
+ render(width: number): string[] {
+ if (this.attached && !this.expanded) return [];
+ const completion = readShellCompletion(this.message);
+ const color = completion?.details.exitCode ? "error" : "muted";
+ const label = shellCompletionLabel(completion);
+ const heading = this.attached
+ ? `${label} · pid ${completion?.details.pid} · ${formatShellCompletionTime(this.message.timestamp)}`
+ : `${completion?.details.exitCode ? "✗" : "✓"} ${label}`;
+ const header = truncateToWidth(theme.fg(color, ` ${heading}`), width, "");
+ const leadingSpace = this.options.shouldAddLeadingSpace?.(this.expanded) ?? this.expanded;
+ if (!this.expanded) return leadingSpace ? ["", header] : [header];
+ const raw = completion
+ ? shellCompletionText(completion)
+ : typeof this.message.content === "string"
+ ? this.message.content
+ : JSON.stringify(this.message.content);
+ const lines = [header, ...new Text(raw, 1, 0).render(width)];
+ return leadingSpace ? ["", ...lines] : lines;
+ }
+}
+
+export function formatShellCompletionTime(timestamp: number): string {
+ const date = new Date(timestamp);
+ return Number.isFinite(date.getTime()) ? date.toISOString() : "unknown time";
+}
diff --git a/packages/coding-agent/src/modes/interactive/components/side-question.ts b/packages/coding-agent/src/modes/interactive/components/side-question.ts
index 3cf901cb57..8a3689002a 100644
--- a/packages/coding-agent/src/modes/interactive/components/side-question.ts
+++ b/packages/coding-agent/src/modes/interactive/components/side-question.ts
@@ -13,13 +13,14 @@ interface SideQuestionTurnState {
/** A ! / !! run inside the pane, rendered by the same component the main thread uses. */
interface SideQuestionBashState {
kind: "bash";
- component: Component;
+ component: Component & { setExpanded?(expanded: boolean): void };
running: boolean;
}
export class SideQuestionComponent implements Component {
private readonly paddingX: number;
private readonly entries: (SideQuestionTurnState | SideQuestionBashState)[] = [];
+ private expanded = false;
constructor(event: AgentConnectionSideQuestionEvent, paddingX = 2) {
this.paddingX = Math.max(2, paddingX);
@@ -45,10 +46,18 @@ export class SideQuestionComponent implements Component {
this.entries.push({ kind: "turn", event, questionBubble, answer });
}
- addBash(component: Component): void {
+ addBash(component: SideQuestionBashState["component"]): void {
+ component.setExpanded?.(this.expanded);
this.entries.push({ kind: "bash", component, running: true });
}
+ setExpanded(expanded: boolean): void {
+ this.expanded = expanded;
+ for (const entry of this.entries) {
+ if (entry.kind === "bash") entry.component.setExpanded?.(expanded);
+ }
+ }
+
finishBash(): void {
for (const entry of this.entries) {
if (entry.kind === "bash") {
@@ -100,7 +109,7 @@ export class SideQuestionComponent implements Component {
lines.push(...entry.questionBubble.render(width));
} else {
const question = new Text(
- `${theme.fg("accent", "/btw")} ${theme.bold(theme.fg("userMessageText", entry.event.question))}`,
+ `${theme.fg("accent", "/btw")} ${theme.fg("userMessageText", entry.event.question)}`,
this.paddingX,
0,
).render(width);
diff --git a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
index 3785b4c64d..0620350179 100644
--- a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
+++ b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
@@ -10,9 +10,17 @@ import type { AgentConnectionToolDefinition } from "../../agent-connection/index
import { type Theme, theme } from "../theme/theme.js";
import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
import { getIpythonCodeFromArgs, IPythonCellComponent } from "./ipython-cell.js";
+import { expandCollapseHint } from "./keybinding-hints.js";
+import {
+ type BackgroundShellHandle,
+ readAssignedShellCommand,
+ readBackgroundShellHandle,
+ type ShellCompletion,
+} from "./shell-completion.js";
import { ToolPanel } from "./tool-panel.js";
export interface ToolExecutionOptions {
+ shouldAddLeadingSpace?: () => boolean;
showImages?: boolean;
/** Whether image metadata may parse dimensions from base64 data. */
includeImageDimensions?: boolean;
@@ -78,11 +86,11 @@ export class ToolExecutionComponent extends Container {
private toolCallId: string;
private args: any;
private expanded = false;
- private agentMessagesExpanded = false;
private editDiffsExpanded = false;
private showExpandHint = true;
private showImages: boolean;
private includeImageDimensions: boolean;
+ private readonly shouldAddLeadingSpace?: () => boolean;
private isPartial = true;
private toolDefinition?: ToolExecutionDefinition;
private builtInToolDefinition?: ToolDefinition<any, any>;
@@ -97,6 +105,9 @@ export class ToolExecutionComponent extends Container {
details?: any;
};
private hideComponent = false;
+ private shellCompletion?: ShellCompletion;
+ private shellCompletionAmbiguous = false;
+ private readonly resultListeners = new Set<() => void>();
constructor(
toolName: string,
@@ -115,6 +126,7 @@ export class ToolExecutionComponent extends Container {
this.builtInToolDefinition = createReplayBuiltInToolDefinition(toolName, cwd, toolDefinition);
this.showImages = options.showImages ?? true;
this.includeImageDimensions = options.includeImageDimensions ?? true;
+ this.shouldAddLeadingSpace = options.shouldAddLeadingSpace;
this.ui = ui;
this.cwd = cwd;
@@ -205,7 +217,7 @@ export class ToolExecutionComponent extends Container {
}
private createCallFallback(): Component {
- return new Text(theme.fg("toolTitle", theme.bold(this.toolName)), 0, 0);
+ return new Text(theme.fg("toolTitle", this.toolName), 0, 0);
}
private createResultFallback(): Component | undefined {
@@ -213,7 +225,7 @@ export class ToolExecutionComponent extends Container {
if (!output) {
return undefined;
}
- return new Text(theme.fg("toolOutput", output), 0, 0);
+ return new Text(theme.fg("toolOutput", this.formatFallbackPreview(output)), 0, 0);
}
updateArgs(args: any): void {
@@ -258,6 +270,54 @@ export class ToolExecutionComponent extends Container {
this.result = sentAgentMessages.length > 0 ? { ...result, details: { ...details, sentAgentMessages } } : result;
this.isPartial = isPartial;
this.updateDisplay();
+ for (const listener of this.resultListeners) listener();
+ }
+
+ getBackgroundShellHandle(): BackgroundShellHandle | undefined {
+ return this.shouldUseIpythonRenderer() && !this.isPartial && !this.result?.isError
+ ? readBackgroundShellHandle(getIpythonCodeFromArgs(this.args), this.result?.details)
+ : undefined;
+ }
+
+ getAssignedShellCommand(): string | undefined {
+ return this.shouldUseIpythonRenderer() && !this.isPartial && !this.result?.isError
+ ? readAssignedShellCommand(getIpythonCodeFromArgs(this.args), this.result?.details)
+ : undefined;
+ }
+
+ hasRunningBackgroundShell(): boolean {
+ const handle = this.getBackgroundShellHandle();
+ return (
+ handle !== undefined &&
+ handle.exitCode === undefined &&
+ this.shellCompletion === undefined &&
+ !this.shellCompletionAmbiguous
+ );
+ }
+
+ markShellCompletionAmbiguous(): void {
+ if (!this.hasRunningBackgroundShell()) return;
+ this.shellCompletionAmbiguous = true;
+ this.updateDisplay();
+ this.ui.requestRender();
+ }
+
+ onResultUpdate(listener: () => void): () => void {
+ this.resultListeners.add(listener);
+ return () => this.resultListeners.delete(listener);
+ }
+
+ isResultPending(): boolean {
+ return this.isPartial;
+ }
+
+ attachShellCompletion(completion: ShellCompletion): boolean {
+ if (this.shellCompletion) return false;
+ this.shellCompletion = completion;
+ this.shellCompletionAmbiguous = false;
+ this.updateDisplay();
+ this.ui.requestRender();
+ return true;
}
appendSentAgentMessage(message: KernelSentAgentMessage): void {
@@ -275,14 +335,6 @@ export class ToolExecutionComponent extends Container {
this.updateDisplay();
}
- setAgentMessagesExpanded(expanded: boolean): void {
- if (this.agentMessagesExpanded === expanded) {
- return;
- }
- this.agentMessagesExpanded = expanded;
- this.updateDisplay();
- }
-
setEditDiffsExpanded(expanded: boolean): void {
if (this.editDiffsExpanded === expanded) {
return;
@@ -323,7 +375,10 @@ export class ToolExecutionComponent extends Container {
if (this.isStatusAnimating() && !this.usesSelfRenderShell()) {
this.contentPanel.setHeader(this.panelHeader());
}
- return super.render(width);
+ const lines = super.render(width);
+ return this.expanded && this.shouldUseIpythonRenderer() && this.shouldAddLeadingSpace?.()
+ ? ["", ...lines]
+ : lines;
}
private isStatusAnimating(): boolean {
@@ -350,12 +405,14 @@ export class ToolExecutionComponent extends Container {
if (this.shouldUseIpythonRenderer()) {
const state = {
code: getIpythonCodeFromArgs(this.args),
+ backgroundShell: this.getBackgroundShellHandle(),
+ shellCompletion: this.shellCompletion,
+ shellCompletionAmbiguous: this.shellCompletionAmbiguous,
content: this.result?.content,
details: this.result?.details,
isPartial: this.isPartial,
isError: this.result?.isError ?? false,
expanded: this.expanded,
- agentMessagesExpanded: this.agentMessagesExpanded,
editDiffsExpanded: this.editDiffsExpanded,
executionStarted: this.executionStarted,
argsComplete: this.argsComplete,
@@ -505,15 +562,22 @@ export class ToolExecutionComponent extends Container {
});
}
+ private formatFallbackPreview(text: string): string {
+ if (this.expanded) return text;
+ const lines = text.split("\n");
+ if (lines.length <= 3) return text;
+ return `${lines.slice(0, 3).join("\n")}\n${theme.fg("dim", `… ${lines.length - 3} more lines`)}${this.showExpandHint ? ` ${expandCollapseHint("app.tools.expand", false)}` : ""}`;
+ }
+
private formatToolExecution(): string {
const parts: string[] = [];
const content = JSON.stringify(this.args, null, 2);
if (content) {
- parts.push(content);
+ parts.push(this.formatFallbackPreview(content));
}
const output = this.getTextOutput();
if (output) {
- parts.push(output);
+ parts.push(this.formatFallbackPreview(output));
}
return parts.join("\n\n");
}
diff --git a/packages/coding-agent/src/modes/interactive/components/tree-selector.ts b/packages/coding-agent/src/modes/interactive/components/tree-selector.ts
index e01bdfb79d..be93370782 100644
--- a/packages/coding-agent/src/modes/interactive/components/tree-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/tree-selector.ts
@@ -1172,7 +1172,7 @@ export class TreeSelectorComponent extends Container implements Focusable {
this.addChild(new Spacer(1));
this.addChild(new DynamicBorder());
- this.addChild(new Text(theme.bold(" Session Tree"), 1, 0));
+ this.addChild(new Text(" Session Tree", 1, 0));
const filterKeys = [
keyText("app.tree.filter.default"),
keyText("app.tree.filter.noTools"),
diff --git a/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts b/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
index 999d830344..4b88062e20 100644
--- a/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
@@ -97,7 +97,7 @@ export class UserMessageSelectorComponent extends Container {
super();
this.addChild(new Spacer(1));
- this.addChild(new Text(theme.bold("Fork from Message"), 1, 0));
+ this.addChild(new Text("Fork from Message", 1, 0));
this.addChild(
new Text(
theme.fg("muted", "Select a user message to copy the active path up to that point into a new session"),
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 4e42449e9a..87e7b1fb7a 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -194,7 +194,7 @@ import {
import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
import { ConfigurationMenuComponent, type ConfigurationMenuTab } from "./components/configuration-menu.js";
import { formatContextTree } from "./components/context-tree-format.js";
-import { isCompactAgentMessageNeighbor } from "./components/conversation-components.js";
+import { createConversationSpacing, createShellCompletionComponent } from "./components/conversation-components.js";
import { CountdownTimer } from "./components/countdown-timer.js";
import { CustomEditor } from "./components/custom-editor.js";
import { CustomMessageComponent } from "./components/custom-message.js";
@@ -332,19 +332,6 @@ function isExpandable(obj: unknown): obj is Expandable {
return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
}
-interface AgentMessagesExpandable {
- setAgentMessagesExpanded(expanded: boolean): void;
-}
-
-function hasAgentMessagesExpansion(obj: unknown): obj is AgentMessagesExpandable {
- return (
- typeof obj === "object" &&
- obj !== null &&
- "setAgentMessagesExpanded" in obj &&
- typeof (obj as AgentMessagesExpandable).setAgentMessagesExpanded === "function"
- );
-}
-
interface EditDiffsExpandable {
setEditDiffsExpanded(expanded: boolean): void;
}
@@ -977,8 +964,6 @@ export class InteractiveMode {
private contextUsageTokenBaseline = 0;
// Refresh ordering: a stale failure must never clobber a newer success.
private contextUsageRefresh = { generation: 0, lastSuccessGeneration: 0 };
- private readonly defaultHiddenThinkingLabel = "Thinking...";
- private hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
private ctrlCExitHintExpiresAt = 0;
private ctrlCExitHintTimer: ReturnType<typeof setTimeout> | undefined = undefined;
@@ -1036,10 +1021,9 @@ export class InteractiveMode {
private rosterBar: { summaries(): SessionSummary[]; dispose(): Promise<void> } | undefined;
private toolOutputExpanded = false;
- private agentMessagesExpanded = false;
private editDiffsExpanded = false;
- private hideThinkingBlock = false;
+ private hideThinkingBlock = true;
private readonly mermaidMarkdownTransform = createMermaidMarkdownTransform({
getMode: () => this.settingsManager.getMermaidRenderingMode(),
theme,
@@ -1200,8 +1184,6 @@ export class InteractiveMode {
this.footer.setAutoCompactEnabled(this.settingsManager.getCompactionEnabled());
this.setGoalAnnouncementBaseline(emptyGoalState());
- this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
-
setRegisteredThemes(this.uiServices.getThemes());
initTheme(this.settingsManager.getTheme(), true);
}
@@ -1454,10 +1436,7 @@ export class InteractiveMode {
keyHint("tui.editor.deleteToLineEnd", "to delete to end"),
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.edits.expand", "to expand edit diffs"),
- hint("app.thinking.toggle", "to expand thinking"),
+ hint("app.tools.expand", "to cycle conversation detail"),
hint("app.subagents.focus", "to inspect subagents"),
hint("app.editor.external", "for external editor"),
hint("app.prompt.stash", "to stash prompt"),
@@ -2556,7 +2535,6 @@ export class InteractiveMode {
this.connectionState?.autoCompactionEnabled ?? this.settingsManager.getCompactionEnabled(),
);
this.footerDataProvider.setCwd(this.getCurrentCwd());
- this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
const editorPaddingX = this.settingsManager.getEditorPaddingX();
@@ -3060,19 +3038,20 @@ export class InteractiveMode {
return componentAfterLoad;
}
+ const spacing = createConversationSpacing(this.chatContainer.children);
const component = new ToolExecutionComponent(
latestToolCall.name,
latestToolCall.id,
latestToolCall.arguments,
{
showImages: this.settingsManager.getShowImages(),
+ shouldAddLeadingSpace: () => spacing.shouldAddLeadingSpace(true),
},
toolDefinition,
this.ui,
this.getCurrentCwd(),
);
component.setExpanded(this.toolOutputExpanded);
- component.setAgentMessagesExpanded(this.agentMessagesExpanded);
component.setEditDiffsExpanded(this.editDiffsExpanded);
if (this.startedToolCalls.has(latestToolCall.id)) {
component.markExecutionStarted();
@@ -3294,7 +3273,11 @@ export class InteractiveMode {
}
private updateWorkingPulse(): void {
- const active = this.isAgentStreaming();
+ const active =
+ this.isAgentStreaming() ||
+ this.chatContainer.children.some(
+ (component) => component instanceof ToolExecutionComponent && component.hasRunningBackgroundShell(),
+ );
if (!active) {
this.stopWorkingPulse();
return;
@@ -3306,6 +3289,7 @@ export class InteractiveMode {
}
private tickWorkingPulse(): void {
+ this.updateWorkingPulse();
this.pulseFrame += 1;
setWorkingPulseFrame(this.pulseFrame);
this.ui.requestRender();
@@ -3437,17 +3421,8 @@ export class InteractiveMode {
this.ui.requestRender();
}
- private setHiddenThinkingLabel(label?: string): void {
- this.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;
- for (const child of this.chatContainer.children) {
- if (child instanceof AssistantMessageComponent) {
- child.setHiddenThinkingLabel(this.hiddenThinkingLabel);
- }
- }
- if (this.streamingComponent) {
- this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);
- }
- this.ui.requestRender();
+ private setHiddenThinkingLabel(_label?: string): void {
+ // Retain the extension/daemon UI hook; conversation thinking no longer has a heading.
}
private setExtensionWidget(
@@ -3533,7 +3508,6 @@ export class InteractiveMode {
if (this.loadingAnimation) {
this.updateWorkingLoaderMessage();
}
- this.setHiddenThinkingLabel();
}
private static readonly MAX_WIDGET_LINES = 10;
@@ -4094,9 +4068,6 @@ 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.edits.expand", () => this.toggleEditDiffExpansion());
- this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
this.defaultEditor.onAction("app.subagents.focus", () => this.focusSubagentSummary());
this.defaultEditor.onAction("app.heartbeats.open", () => {
void this.showHeartbeatManager();
@@ -4425,6 +4396,7 @@ export class InteractiveMode {
this.sideQuestionComponent.addTurn(event);
} else {
this.sideQuestionComponent = new SideQuestionComponent(event, this.settingsManager.getEditorPaddingX());
+ this.sideQuestionComponent.setExpanded(this.toolOutputExpanded);
this.sideQuestionContainer.addChild(new Spacer(1));
this.sideQuestionContainer.addChild(this.sideQuestionComponent);
}
@@ -5363,6 +5335,7 @@ export class InteractiveMode {
const component = new BashExecutionComponent(event.command, this.ui, event.excludeFromContext, {
suppressLeadingSpace: this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
});
+ component.setExpanded(this.toolOutputExpanded);
if (ownSideBash && this.sideQuestionComponent) {
// Same component as the main thread, mounted inside the pane.
this.sideQuestionComponent.addBash(component);
@@ -5705,12 +5678,9 @@ export class InteractiveMode {
undefined,
this.hideThinkingBlock,
this.getMarkdownThemeWithSettings(),
- this.hiddenThinkingLabel,
{
expanded: this.toolOutputExpanded,
- precededByToolActivity:
- this.chatContainer.children.at(-1) instanceof ToolExecutionComponent ||
- this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
+ precededByToolActivity: createConversationSpacing(this.chatContainer.children).precededByToolActivity,
mermaidTransform: this.mermaidMarkdownTransform,
cwd: this.getCurrentCwd(),
},
@@ -5965,19 +5935,6 @@ export class InteractiveMode {
this.toggleToolOutputExpansion();
return;
}
- if (this.keybindings.matches(data, "app.messages.expand")) {
- this.toggleAgentMessageExpansion();
- return;
- }
- // A raw "\n" is a newline for the editor, not ctrl+j.
- if (data !== "\n" && this.keybindings.matches(data, "app.edits.expand")) {
- this.toggleEditDiffExpansion();
- return;
- }
- if (this.keybindings.matches(data, "app.thinking.toggle")) {
- this.toggleThinkingBlockVisibility();
- return;
- }
this.focusEditor();
this.editor.handleInput(data);
}
@@ -6252,9 +6209,11 @@ export class InteractiveMode {
}
if (isAgentSessionMessage(message)) {
return new AgentMessageComponent(message, this.getMarkdownThemeWithSettings(), {
- suppressLeadingSpace: isCompactAgentMessageNeighbor(this.chatContainer.children.at(-1)),
+ shouldAddLeadingSpace: createConversationSpacing(this.chatContainer.children).shouldAddLeadingSpace,
});
}
+ const shellCompletion = createShellCompletionComponent(message, this.chatContainer.children);
+ if (shellCompletion) return shellCompletion;
if (isInjectedPromptMessage(message)) {
return new InjectedPromptMessageComponent(message, this.getMarkdownThemeWithSettings());
}
@@ -6273,6 +6232,7 @@ export class InteractiveMode {
const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext, {
suppressLeadingSpace: this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
});
+ component.setExpanded(this.toolOutputExpanded);
if (message.output) {
component.appendOutput(message.output);
}
@@ -6289,7 +6249,7 @@ export class InteractiveMode {
if (message.display) {
const component = this.createDisplayedCustomMessageComponent(message);
if (isExpandable(component)) {
- component.setExpanded(this.expansionStateFor(component));
+ component.setExpanded(this.toolOutputExpanded);
}
if (hasEditDiffsExpansion(component)) {
component.setEditDiffsExpanded(this.editDiffsExpanded);
@@ -6370,12 +6330,9 @@ export class InteractiveMode {
message,
this.hideThinkingBlock,
this.getMarkdownThemeWithSettings(),
- this.hiddenThinkingLabel,
{
expanded: this.toolOutputExpanded,
- precededByToolActivity:
- this.chatContainer.children.at(-1) instanceof ToolExecutionComponent ||
- this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
+ precededByToolActivity: createConversationSpacing(this.chatContainer.children).precededByToolActivity,
mermaidTransform: this.mermaidMarkdownTransform,
cwd: this.getCurrentCwd(),
},
@@ -6486,6 +6443,7 @@ export class InteractiveMode {
// Render tool call components
for (const content of message.content) {
if (content.type === "toolCall") {
+ const spacing = createConversationSpacing(this.chatContainer.children);
const component = new ToolExecutionComponent(
content.name,
content.id,
@@ -6493,13 +6451,13 @@ export class InteractiveMode {
{
showImages: this.settingsManager.getShowImages(),
includeImageDimensions: false,
+ shouldAddLeadingSpace: () => spacing.shouldAddLeadingSpace(true),
},
this.getCachedToolDefinition(content.name),
this.ui,
this.getCurrentCwd(),
);
component.setExpanded(this.toolOutputExpanded);
- component.setAgentMessagesExpanded(this.agentMessagesExpanded);
component.setEditDiffsExpanded(this.editDiffsExpanded);
selectLatestToolExpandHint(this.chatContainer.children, component);
this.chatContainer.addChild(component);
@@ -6537,6 +6495,7 @@ export class InteractiveMode {
}
}
+ this.updateWorkingPulse();
for (const [toolCallId, component] of renderedPendingTools) {
component.setIncludeImageDimensions(true);
this.pendingTools.set(toolCallId, component);
@@ -7227,27 +7186,19 @@ export class InteractiveMode {
}
private toggleToolOutputExpansion(): void {
- this.setToolsExpanded(!this.toolOutputExpanded);
- }
-
- private toggleAgentMessageExpansion(): void {
- this.agentMessagesExpanded = !this.agentMessagesExpanded;
- this.applyChatExpansion();
- }
-
- private toggleEditDiffExpansion(): void {
- this.editDiffsExpanded = !this.editDiffsExpanded;
- this.applyChatExpansion();
+ this.setChatDetail(this.toolOutputExpanded ? "overview" : this.editDiffsExpanded ? "all" : "details");
}
private setToolsExpanded(expanded: boolean): void {
- this.toolOutputExpanded = expanded;
- this.applyChatExpansion();
+ this.setChatDetail(expanded ? "all" : "overview");
}
- /** 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;
+ /** Presentation only: never rewrite messages, settings, or the session trace. */
+ private setChatDetail(detail: "overview" | "details" | "all"): void {
+ this.toolOutputExpanded = detail === "all";
+ this.editDiffsExpanded = detail !== "overview";
+ this.hideThinkingBlock = detail === "overview";
+ this.applyChatExpansion();
}
private applyChatExpansion(): void {
@@ -7255,12 +7206,17 @@ export class InteractiveMode {
if (isExpandable(activeHeader)) {
activeHeader.setExpanded(this.toolOutputExpanded);
}
- for (const child of this.chatContainer.children) {
- if (isExpandable(child)) {
- child.setExpanded(this.expansionStateFor(child));
+ for (const child of new Set([
+ ...this.chatContainer.children,
+ ...this.pendingBashComponents,
+ this.activeBashComponent,
+ this.sideQuestionComponent,
+ ])) {
+ if (child instanceof AssistantMessageComponent) {
+ child.setHideThinkingBlock(this.hideThinkingBlock);
}
- if (hasAgentMessagesExpansion(child)) {
- child.setAgentMessagesExpanded(this.agentMessagesExpanded);
+ if (isExpandable(child)) {
+ child.setExpanded(this.toolOutputExpanded);
}
if (hasEditDiffsExpansion(child)) {
child.setEditDiffsExpanded(this.editDiffsExpanded);
@@ -7277,27 +7233,6 @@ export class InteractiveMode {
}
}
- private toggleThinkingBlockVisibility(): void {
- this.hideThinkingBlock = !this.hideThinkingBlock;
- this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
-
- void (async () => {
- // Rebuild chat from session messages
- await this.rebuildChatFromMessages();
-
- // If streaming, re-add the streaming component with updated visibility and re-render
- if (this.streamingComponent && this.streamingMessage) {
- this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
- this.streamingComponent.updateContent(this.streamingMessage);
- this.chatContainer.addChild(this.streamingComponent);
- }
-
- this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
- })().catch((error) => {
- this.showError(error instanceof Error ? error.message : String(error));
- });
- }
-
private openExternalEditor(): void {
// Determine editor (respect $VISUAL, then $EDITOR)
const editorCmd = process.env.VISUAL || process.env.EDITOR;
@@ -7469,7 +7404,6 @@ export class InteractiveMode {
availableThinkingLevels: state.availableThinkingLevels,
currentTheme: this.settingsManager.getTheme() || "prime",
availableThemes: getAvailableThemes(),
- hideThinkingBlock: this.hideThinkingBlock,
mermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),
treeFilterMode: this.settingsManager.getTreeFilterMode(),
showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
@@ -7558,18 +7492,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
},
- onHideThinkingBlockChange: (hidden) => {
- this.hideThinkingBlock = hidden;
- this.settingsManager.setHideThinkingBlock(hidden);
- for (const child of this.chatContainer.children) {
- if (child instanceof AssistantMessageComponent) {
- child.setHideThinkingBlock(hidden);
- }
- }
- void this.rebuildChatFromMessages().catch((error) => {
- this.showError(error instanceof Error ? error.message : String(error));
- });
- },
onMermaidRenderingModeChange: (mode) => {
this.settingsManager.setMermaidRenderingMode(mode);
this.chatContainer.invalidate();
@@ -8879,7 +8801,6 @@ export class InteractiveMode {
activeHeader.setExpanded(this.toolOutputExpanded);
}
setRegisteredThemes(this.uiServices.getThemes());
- this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
const themeName = this.settingsManager.getTheme();
const themeResult = themeName ? setTheme(themeName, true) : { success: true };
if (!themeResult.success) {
@@ -9195,13 +9116,13 @@ export class InteractiveMode {
const stats = await this.agentConnection.getSessionStats();
const sessionName = this.getCurrentSessionName();
- let info = `${theme.bold("Session Info")}\n\n`;
+ let info = `Session Info\n\n`;
if (sessionName) {
info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
}
info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
- info += `${theme.bold("Messages")}\n`;
+ info += `Messages\n`;
info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
info += `${theme.fg("dim", "Tool Calls:")} ${stats.toolCalls}\n`;
@@ -9216,7 +9137,7 @@ export class InteractiveMode {
private handleLogsCommand(): void {
const logsDir = getLogsDir();
- let info = `${theme.bold("Logs")}\n\n`;
+ let info = `Logs\n\n`;
info += `${theme.fg("dim", "Directory:")} ${logsDir}\n\n`;
let files: string[] = [];
@@ -9249,7 +9170,7 @@ export class InteractiveMode {
private async handleSystemPromptCommand(): Promise<void> {
const prompt = await this.agentConnection.getSystemPrompt();
- const header = `${theme.bold("System Prompt")} ${theme.fg("dim", `(${prompt.length} chars)`)}`;
+ const header = `System Prompt ${theme.fg("dim", `(${prompt.length} chars)`)}`;
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Text(header, 1, 0));
@@ -9321,7 +9242,7 @@ export class InteractiveMode {
private formatTracePreview(result: Extract<AgentTracePreviewResult, { status: "ready" }>): string {
const lines = [
- theme.bold("Trace Preview"),
+ "Trace Preview",
theme.fg("dim", "Nothing has been uploaded by this command."),
"",
`${theme.fg("dim", "File:")} ${result.sessionFile}`,
@@ -9340,7 +9261,7 @@ export class InteractiveMode {
if (result.gitCommit) {
lines.push(`${theme.fg("dim", "Git commit:")} ${result.gitCommit}`);
}
- lines.push("", theme.bold("Raw JSONL payload preview"));
+ lines.push("", "Raw JSONL payload preview");
if (result.contentPreview) {
lines.push(result.contentPreview);
if (result.truncated) {
@@ -9382,7 +9303,7 @@ export class InteractiveMode {
const credential = await getPrimeAgentTraceCredential(this.modelRegistry.authStorage);
const state = await this.agentConnection.getState();
const info = [
- theme.bold("Trace Sharing"),
+ "Trace Sharing",
"",
`${theme.fg("dim", "Automatic uploads:")} ${this.settingsManager.getAgentTracesEnabled() ? "Enabled" : "Disabled"}`,
`${theme.fg("dim", "Credential:")} ${credential?.label ?? "Not configured"}`,
@@ -9696,7 +9617,7 @@ export class InteractiveMode {
const next = job.nextRunAt ? new Date(job.nextRunAt).toLocaleString() : "-";
const last = job.lastRunAt ? new Date(job.lastRunAt).toLocaleString() : "-";
const lines = [
- theme.bold("Heartbeat"),
+ "Heartbeat",
"",
`${theme.fg("dim", "Status:")} ${job.status}`,
`${theme.fg("dim", "Every:")} ${job.schedule.expression}`,
@@ -9728,7 +9649,7 @@ export class InteractiveMode {
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new DynamicBorder());
- this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
+ this.chatContainer.addChild(new Text(theme.fg("accent", "What's New"), 1, 0));
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
this.chatContainer.addChild(new DynamicBorder());
@@ -9762,9 +9683,6 @@ 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 expandEdits = this.getAppKeyDisplay("app.edits.expand");
- const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
const externalEditor = this.getAppKeyDisplay("app.editor.external");
const promptStash = this.getAppKeyDisplay("app.prompt.stash");
const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
@@ -9776,8 +9694,8 @@ export class InteractiveMode {
\`${clearInput}\` interrupt · press twice to rewind or clear the prompt
**Controls**
-\`${selectModel}\` select model · \`/effort\` set reasoning · \`${expandTools}\` tool output
-\`${expandMessages}\` agent messages · \`${expandEdits}\` edit diffs · \`${toggleThinking}\` thinking blocks · \`${promptStash}\` stash prompt · \`${externalEditor}\` edit in \`$EDITOR\`
+\`${selectModel}\` select model · \`/effort\` set reasoning · \`${expandTools}\` overview → thinking + diffs → all output
+\`${promptStash}\` stash prompt · \`${externalEditor}\` edit in \`$EDITOR\`
\`${pasteImage}\` paste image
**Help**
@@ -9815,9 +9733,6 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` ful
const 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 expandEdits = this.getAppKeyDisplay("app.edits.expand");
- const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
const focusSubagents = this.getAppKeyDisplay("app.subagents.focus");
const manageHeartbeats = this.getAppKeyDisplay("app.heartbeats.open");
const externalEditor = this.getAppKeyDisplay("app.editor.external");
@@ -9864,10 +9779,7 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` ful
| \`${clear}\` | Interrupt current operation (first) / exit (second) |
${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 |
-| \`${expandEdits}\` | Toggle edit diff expansion |
-| \`${toggleThinking}\` | Toggle thinking block visibility |
+| \`${expandTools}\` | Cycle overview → thinking + diffs → all output |
| \`${focusSubagents}\` | Focus the subagent summary / open the scoped agents view |
| \`${manageHeartbeats}\` | Manage heartbeats |
| \`${externalEditor}\` | Edit message in external editor |
diff --git a/packages/coding-agent/src/modes/interactive/theme/dark.json b/packages/coding-agent/src/modes/interactive/theme/dark.json
index 06b4788d0f..073f6ebb11 100644
--- a/packages/coding-agent/src/modes/interactive/theme/dark.json
+++ b/packages/coding-agent/src/modes/interactive/theme/dark.json
@@ -50,6 +50,7 @@
"toolTitle": "",
"toolOutput": "gray",
+ "mdBody": "#c4c4c4",
"mdHeading": "#b294bb",
"mdLink": "#81a2be",
"mdLinkUrl": "dimGray",
diff --git a/packages/coding-agent/src/modes/interactive/theme/light.json b/packages/coding-agent/src/modes/interactive/theme/light.json
index 16479d2b2a..f4895b74c2 100644
--- a/packages/coding-agent/src/modes/interactive/theme/light.json
+++ b/packages/coding-agent/src/modes/interactive/theme/light.json
@@ -49,6 +49,7 @@
"toolTitle": "",
"toolOutput": "mediumGray",
+ "mdBody": "#454545",
"mdHeading": "#7e57c2",
"mdLink": "blue",
"mdLinkUrl": "dimGray",
diff --git a/packages/coding-agent/src/modes/interactive/theme/prime.json b/packages/coding-agent/src/modes/interactive/theme/prime.json
index 843597d49f..05a2145d3e 100644
--- a/packages/coding-agent/src/modes/interactive/theme/prime.json
+++ b/packages/coding-agent/src/modes/interactive/theme/prime.json
@@ -55,10 +55,11 @@
"toolPanelBg": "surface",
"toolTitle": "",
"toolOutput": "muted",
+ "mdBody": "#d8d8dc",
"mdHeading": "primarySoft",
"mdLink": "info",
"mdLinkUrl": "dim",
- "mdCode": "neutral",
+ "mdCode": "#c8c8cd",
"mdCodeBlock": "stringMint",
"mdCodeBlockBorder": "grid",
"mdQuote": "muted",
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme-schema.json b/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
index 46b1e8f7ac..cf5a787015 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
+++ b/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
@@ -33,7 +33,7 @@
},
"colors": {
"type": "object",
- "description": "Theme color definitions (refinement colors have purple defaults)",
+ "description": "Theme color definitions (mdBody defaults to text; refinement colors have purple defaults)",
"required": [
"accent",
"border",
@@ -200,6 +200,10 @@
"$ref": "#/$defs/colorValue",
"description": "Tool execution box output text color"
},
+ "mdBody": {
+ "$ref": "#/$defs/colorValue",
+ "description": "Markdown body text (assistant output); defaults to text"
+ },
"mdHeading": {
"$ref": "#/$defs/colorValue",
"description": "Markdown heading text"
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme.ts b/packages/coding-agent/src/modes/interactive/theme/theme.ts
index a8dcca9859..9284e06e4c 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme.ts
+++ b/packages/coding-agent/src/modes/interactive/theme/theme.ts
@@ -65,7 +65,8 @@ const ThemeJsonSchema = Type.Object({
toolPanelBg: ColorValueSchema,
toolTitle: ColorValueSchema,
toolOutput: ColorValueSchema,
- // Markdown (10 colors)
+ // Markdown (11 colors)
+ mdBody: Type.Optional(ColorValueSchema),
mdHeading: ColorValueSchema,
mdLink: ColorValueSchema,
mdLinkUrl: ColorValueSchema,
@@ -145,6 +146,7 @@ export type ThemeColor =
| "refinementSummary"
| "toolTitle"
| "toolOutput"
+ | "mdBody"
| "mdHeading"
| "mdLink"
| "mdLinkUrl"
@@ -817,7 +819,11 @@ function loadThemeJson(name: string): ThemeJson {
function createTheme(themeJson: ThemeJson, mode?: ColorMode, sourcePath?: string): Theme {
const colorMode = mode ?? detectColorMode();
const resolvedColors = resolveThemeColors(
- { ...refinementColors(themeJson.name === "light"), ...themeJson.colors },
+ {
+ ...refinementColors(themeJson.name === "light"),
+ ...themeJson.colors,
+ mdBody: themeJson.colors.mdBody ?? themeJson.colors.text,
+ },
themeJson.vars,
);
const fgColors: Record<ThemeColor, string | number> = {} as Record<ThemeColor, string | number>;
diff --git a/packages/coding-agent/src/modes/shared/startup-notices.ts b/packages/coding-agent/src/modes/shared/startup-notices.ts
index 69323d52a9..484848ed48 100644
--- a/packages/coding-agent/src/modes/shared/startup-notices.ts
+++ b/packages/coding-agent/src/modes/shared/startup-notices.ts
@@ -110,7 +110,7 @@ export async function checkTmuxKeyboardSetup(): Promise<string | undefined> {
export function formatUpdateAvailableNotice(newVersion: string): string {
return (
- `${theme.bold(theme.fg("accent", "Update available:"))} ` +
+ `${theme.fg("accent", "Update available:")} ` +
`${theme.fg("muted", `v${newVersion}. Run `)}${theme.fg("accent", "/update")}`
);
}
@@ -118,7 +118,7 @@ export function formatUpdateAvailableNotice(newVersion: string): string {
export function formatPackageUpdateNotice(packages: string[]): string {
const packageList = packages.join(", ");
return (
- `${theme.bold(theme.fg("warning", "Package updates available:"))} ` +
+ `${theme.fg("warning", "Package updates available:")} ` +
`${theme.fg("muted", `${packageList}. Run `)}${theme.fg("accent", "/update --extensions")}`
);
}
diff --git a/packages/coding-agent/test/assistant-message.test.ts b/packages/coding-agent/test/assistant-message.test.ts
index f1bb1c8fdf..faa34fb06e 100644
--- a/packages/coding-agent/test/assistant-message.test.ts
+++ b/packages/coding-agent/test/assistant-message.test.ts
@@ -3,7 +3,7 @@ import { setKeybindings } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import { describe, expect, test } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
-import { AssistantMessageComponent, thinkingRecap } from "../src/modes/interactive/components/assistant-message.js";
+import { AssistantMessageComponent } 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";
@@ -98,11 +98,11 @@ describe("AssistantMessageComponent", () => {
"RuntimeError: backend crashed",
].join("\n"),
};
- const component = new AssistantMessageComponent(message, false, undefined, "Thinking...", { expanded: true });
+ const component = new AssistantMessageComponent(message, false, undefined, { expanded: true });
const rendered = stripAnsi(component.render(100).join("\n"));
expect(rendered).toContain("/tmp/internal.py");
- expect(rendered).not.toContain("Ctrl+O to expand");
+ expect(rendered).not.toContain("Ctrl+O");
});
test("renders auth recovery guidance inline for simple provider errors", () => {
@@ -118,7 +118,7 @@ describe("AssistantMessageComponent", () => {
const rendered = stripAnsi(raw);
expect(rendered).toContain("Error: 401 status code (no body) · Run /login to update credentials.");
- expect(rendered).not.toContain("Ctrl+O to expand");
+ expect(rendered).not.toContain("Ctrl+O");
expect(raw).toContain(theme.getFgAnsi("error"));
});
@@ -140,7 +140,7 @@ describe("AssistantMessageComponent", () => {
const rendered = stripAnsi(raw);
expect(rendered).toContain("Error: Provider request failed");
- expect(rendered).toContain("to expand");
+ expect(rendered).not.toContain("cycle detail");
expect(raw).toContain(theme.getFgAnsi("error"));
});
});
@@ -216,7 +216,7 @@ describe("AssistantMessageComponent streaming identity", () => {
}
});
- test("collapsed thinking shows a bold label, recap, and bracketed hint", () => {
+ test("hidden thinking renders nothing and the reveal shows the trace", () => {
initTheme("dark");
setKeybindings(new KeybindingsManager());
@@ -233,55 +233,70 @@ describe("AssistantMessageComponent streaming identity", () => {
{ 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...");
+ // Hidden by default: no thinking row at all, only the text block renders.
+ const hiddenRaw = new AssistantMessageComponent(message, true).render(120).join("\n");
+ const hidden = stripAnsi(hiddenRaw);
+ expect(hidden).toContain("Answer.");
+ expect(hidden).not.toContain("Thinking:");
+ expect(hidden).not.toContain("Some detail");
+ expect(hiddenRaw).not.toContain(theme.getFgAnsi("thinkingText"));
+
+ // Revealed thinking renders only the dim trace.
+ const revealedRaw = new AssistantMessageComponent(message, false).render(120).join("\n");
+ const revealed = stripAnsi(revealedRaw);
+ expect(revealed).not.toContain("Thinking:");
+ expect(revealed).not.toContain("Ctrl+O");
+ expect(revealed).toContain("Some detail about the options.");
+ expect(revealedRaw).not.toContain(theme.getFgAnsi("thinkingText"));
+ expect(revealedRaw).toContain(theme.getFgAnsi("dim"));
+ const traceLine = revealedRaw.split("\n").find((line) => line.includes("Some detail about the options."));
+ expect(traceLine).toBeDefined();
+ expect(traceLine).toContain(theme.getFgAnsi("dim"));
+ expect(traceLine).not.toContain("\x1b[1m");
});
- test("recap text with delimiters cannot mask structural changes", () => {
+ test("separates consecutive thinking blocks and the answer without header rows", () => {
initTheme("dark");
- setKeybindings(new KeybindingsManager());
+ const message = createAssistantMessage([
+ { type: "thinking", thinking: "First trace." },
+ { type: "thinking", thinking: "Second trace." },
+ { type: "text", text: "Answer." },
+ ]);
+ const component = new AssistantMessageComponent(message, false);
+ const render = () => component.render(80).map((line) => stripAnsi(line).trim());
- // 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);
+ expect(render()).toEqual(["", "First trace.", "", "Second trace.", "", "Answer."]);
+ component.setHideThinkingBlock(true);
+ expect(render()).toEqual(["", "Answer."]);
+ component.setHideThinkingBlock(false);
+ expect(render()).toEqual(["", "First trace.", "", "Second trace.", "", "Answer."]);
+ });
- component.updateContent(
- createAssistantMessage([
- { type: "thinking", thinking: "X" },
- { type: "text", text: "Visible answer." },
- ]),
- );
- const rendered = stripAnsi(component.render(120).join("\n"));
+ test("a thinking-only message renders nothing while hidden", () => {
+ initTheme("dark");
- expect(rendered).toContain("Visible answer.");
+ const message = createAssistantMessage([{ type: "thinking", thinking: "Trace only." }]);
+ const lines = new AssistantMessageComponent(message, true).render(80);
+ expect(lines).toEqual([]);
});
- test("collapsed thinking row truncates instead of wrapping on narrow widths", () => {
+ test("setHideThinkingBlock toggles the reveal without stale rows", () => {
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);
+ const component = new AssistantMessageComponent(undefined, true);
+ component.updateContent(createAssistantMessage([{ type: "thinking", thinking: "Trace." }]));
+ expect(component.render(120)).toEqual([]);
+
+ component.setHideThinkingBlock(false);
+ const revealed = stripAnsi(component.render(120).join("\n"));
+ expect(revealed).not.toContain("Thinking:");
+ expect(revealed).not.toContain("Ctrl+O");
+ expect(revealed).toContain("Trace.");
- expect(lines).toHaveLength(1);
- expect(lines[0]).toContain("Thinking...");
- expect(lines[0]).toContain("to expand");
+ component.setHideThinkingBlock(true);
+ expect(component.render(120)).toEqual([]);
});
test("setHideThinkingBlock and setExpanded mid-stream render identically", () => {
@@ -320,3 +335,56 @@ describe("AssistantMessageComponent streaming identity", () => {
}
});
});
+
+describe("AssistantMessageComponent body text color", () => {
+ test("renders assistant body text in the softened mdBody color", () => {
+ initTheme("dark");
+
+ const component = new AssistantMessageComponent(
+ createAssistantMessage([{ type: "text", text: "Plain answer." }]),
+ );
+ const raw = component.render(120).join("\n");
+
+ expect(stripAnsi(raw)).toContain("Plain answer.");
+ expect(raw).toContain(theme.getFgAnsi("mdBody"));
+ });
+
+ test("keeps heading and inline code colors on top of mdBody", () => {
+ initTheme("dark");
+
+ const message = createAssistantMessage([{ type: "text", text: "## Title\n\nBody with `code`." }]);
+ const raw = new AssistantMessageComponent(message).render(120).join("\n");
+
+ expect(raw).toContain(theme.getFgAnsi("mdHeading"));
+ expect(raw).toContain(theme.getFgAnsi("mdCode"));
+ expect(raw).toContain(theme.getFgAnsi("mdBody"));
+ });
+
+ test("renders the thinking trace in its existing dim color without a header", () => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+
+ const message = createAssistantMessage([{ type: "thinking", thinking: "Quiet reasoning." }]);
+ const raw = new AssistantMessageComponent(message, false).render(120).join("\n");
+
+ expect(stripAnsi(raw)).toContain("Quiet reasoning.");
+ expect(raw).toContain(theme.getFgAnsi("dim"));
+ expect(raw).not.toContain(theme.getFgAnsi("thinkingText"));
+ expect(raw).not.toContain(theme.getFgAnsi("mdBody"));
+ });
+
+ test("keeps assistant prose on mdBody while the thinking trace stays dim", () => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+
+ const message = createAssistantMessage([
+ { type: "thinking", thinking: "Trace line." },
+ { type: "text", text: "Answer prose." },
+ ]);
+ const raw = new AssistantMessageComponent(message, false).render(120).join("\n");
+
+ expect(raw).toContain(theme.getFgAnsi("dim"));
+ expect(raw).toContain(theme.getFgAnsi("mdBody"));
+ expect(theme.getFgAnsi("dim")).not.toBe(theme.getFgAnsi("mdBody"));
+ });
+});
diff --git a/packages/coding-agent/test/bash-execution-width.test.ts b/packages/coding-agent/test/bash-execution-width.test.ts
index e0f98cfa73..db6cdabbf7 100644
--- a/packages/coding-agent/test/bash-execution-width.test.ts
+++ b/packages/coding-agent/test/bash-execution-width.test.ts
@@ -1,7 +1,8 @@
import { visibleWidth } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
import { beforeAll, describe, expect, it } from "vitest";
import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
/** Minimal TUI stub that only exposes terminal.columns */
function createTuiStub(columns: number): { columns: number; stub: any } {
@@ -74,6 +75,23 @@ describe("BashExecutionComponent width handling (#2569)", () => {
}
});
+ it("expands long completed output without leaving an empty hint row", () => {
+ const { stub } = createTuiStub(120);
+ const component = new BashExecutionComponent("print-lines", stub);
+ component.appendOutput(Array.from({ length: 25 }, (_, index) => `line ${index}`).join("\n"));
+ component.setComplete(0, false);
+ const collapsed = stripAnsi(component.render(120).join("\n"));
+ expect(collapsed).toContain("... 5 more lines");
+ expect(collapsed).not.toContain("Ctrl+O");
+
+ component.setExpanded(true);
+ const expanded = component.render(120).map((line) => stripAnsi(line).trimEnd());
+ expect(expanded.join("\n")).toContain("line 0");
+ expect(expanded.join("\n")).not.toContain("more lines");
+ expect(expanded.join("\n")).not.toContain("Ctrl+O");
+ expect(expanded.at(-2)?.trim()).toBe("line 24");
+ });
+
it("renders an inline failure state via setFailed", () => {
const { stub } = createTuiStub(120);
const component = new BashExecutionComponent("boom", stub);
@@ -87,4 +105,14 @@ describe("BashExecutionComponent width handling (#2569)", () => {
expect(rendered).toContain("failed: spawn failure");
expect(rendered).not.toContain("Running...");
});
+
+ it("renders the command header at normal weight with its color kept", () => {
+ const { stub } = createTuiStub(120);
+ const component = new BashExecutionComponent("npm test", stub);
+ component.setComplete(0, false);
+
+ const raw = component.render(120).join("\n");
+ expect(raw).toContain(theme.fg("bashMode", "$ npm test"));
+ expect(raw).not.toContain("");
+ });
});
diff --git a/packages/coding-agent/test/code-preview.test.ts b/packages/coding-agent/test/code-preview.test.ts
index d40e0cd43d..f3d2066ff3 100644
--- a/packages/coding-agent/test/code-preview.test.ts
+++ b/packages/coding-agent/test/code-preview.test.ts
@@ -185,7 +185,7 @@ git add packages/foo.ts
it("keeps the python preview for bash-looking text inside a multiline string", () => {
expect(previewIpythonCode('doc = """\nbash("git status")\n"""')).toEqual({
language: "python",
- text: 'bash("git status")',
+ text: 'doc = """',
});
expect(previewIpythonCode(`doc = """usage"""\nr = await bash('git status')`)).toEqual({
language: "bash",
@@ -204,4 +204,34 @@ p.write_text("hello")
PY`;
expect(previewBashCommand(command)).toEqual({ language: "python", text: "write packages/foo.ts" });
});
+
+ it.each(['"""', "'''", 'r"""', "r'''", 'f"""'])("ignores multiline string bodies in previews (%s)", (opening) => {
+ const code = [
+ 'issue_title = "example"',
+ `issue_body = ${opening}## Summary`,
+ "```ts",
+ "if (!env || state.clientEnv) return;",
+ "```",
+ 'path = "/wrong/path"',
+ 'path.write_text("not executed")',
+ opening.slice(-3),
+ "print(len(issue_body))",
+ ].join("\n");
+ expect(previewPythonCode(code)).toEqual({ language: "python", text: 'issue_title = "example"' });
+ expect(previewPythonCode(`${code}\nsend_issue(issue_title, issue_body)`)).toEqual({
+ language: "python",
+ text: "send_issue(issue_title, issue_body)",
+ });
+ });
+
+ it("ignores unfinished strings while streaming and quotes inside comments", () => {
+ expect(previewPythonCode('body = """draft\nclient.execute("example")')).toEqual({
+ language: "python",
+ text: 'body = """draft',
+ });
+ expect(previewPythonCode('# """ inside a comment\nrun_check()')).toEqual({
+ language: "python",
+ text: "run_check()",
+ });
+ });
});
diff --git a/packages/coding-agent/test/conversation-detail-hints.test.ts b/packages/coding-agent/test/conversation-detail-hints.test.ts
new file mode 100644
index 0000000000..bc6dd4fd95
--- /dev/null
+++ b/packages/coding-agent/test/conversation-detail-hints.test.ts
@@ -0,0 +1,63 @@
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeEach, describe, expect, it } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { BranchSummaryMessageComponent } from "../src/modes/interactive/components/branch-summary-message.js";
+import { CompactionSummaryMessageComponent } from "../src/modes/interactive/components/compaction-summary-message.js";
+import { SkillInvocationMessageComponent } from "../src/modes/interactive/components/skill-invocation-message.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+describe("conversation detail hints", () => {
+ beforeEach(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ it("keeps notifications readable and expandable without inline detail hints", () => {
+ const cards = [
+ {
+ component: new CompactionSummaryMessageComponent({
+ role: "compactionSummary",
+ summary: "Preserved context details",
+ tokensBefore: 12000,
+ timestamp: 0,
+ }),
+ label: "Context compacted",
+ body: "Preserved context details",
+ },
+ {
+ component: new BranchSummaryMessageComponent({
+ role: "branchSummary",
+ summary: "Earlier branch details",
+ fromId: "branch-1",
+ timestamp: 0,
+ }),
+ label: "Branch summary",
+ body: "Earlier branch details",
+ },
+ {
+ component: new SkillInvocationMessageComponent({
+ name: "review",
+ location: "/tmp/review/SKILL.md",
+ content: "Review instructions",
+ userMessage: undefined,
+ }),
+ label: "review",
+ body: "Review instructions",
+ },
+ ];
+ for (const { component, label, body } of cards) {
+ const collapsed = stripAnsi(component.render(100).join("\n"));
+ expect(collapsed).toContain(label);
+ if (component instanceof CompactionSummaryMessageComponent) expect(collapsed).toContain(body);
+ else expect(collapsed).not.toContain(body);
+ expect(collapsed).not.toContain("Ctrl+O");
+ expect(collapsed).not.toMatch(/\(\s*\)|·\s*$/m);
+
+ component.setExpanded(true);
+ const expanded = stripAnsi(component.render(100).join("\n"));
+ expect(expanded).toContain(body);
+ expect(expanded).not.toContain("Ctrl+O");
+ }
+ });
+});
diff --git a/packages/coding-agent/test/conversation-detail-status.test.ts b/packages/coding-agent/test/conversation-detail-status.test.ts
new file mode 100644
index 0000000000..f2d6ec950e
--- /dev/null
+++ b/packages/coding-agent/test/conversation-detail-status.test.ts
@@ -0,0 +1,96 @@
+import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { formatConversationDetailStatus } from "../src/modes/interactive/components/keybinding-hints.js";
+import { PromptContextLine } from "../src/modes/interactive/components/prompt-context-line.js";
+import { SubagentSummaryLine } from "../src/modes/interactive/components/subagent-summary-line.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
+
+interface DetailMode {
+ toolOutputExpanded: boolean;
+ editDiffsExpanded: boolean;
+ getPromptContextLabel(width: number): string | undefined;
+ getTrayContextLabel(): string | undefined;
+ toggleToolOutputExpansion(): void;
+ setToolsExpanded(expanded: boolean): void;
+}
+function createMode(): DetailMode {
+ return Object.assign(Object.create(InteractiveMode.prototype), {
+ toolOutputExpanded: false,
+ editDiffsExpanded: false,
+ applyChatExpansion: vi.fn(),
+ isInlinePickerOpen: () => false,
+ getTrayGoalLabel: () => undefined,
+ getTrayHeartbeatLabel: () => undefined,
+ getConnectionContextUsage: () => undefined,
+ getCurrentModel: () => ({ id: "glm-5.3", provider: "prime", reasoning: true }),
+ connectionState: { thinkingLevel: "high" },
+ });
+}
+
+describe("conversation detail status", () => {
+ beforeEach(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ it("tracks the complete three-stage cycle above the prompt while keeping recap on the left", () => {
+ const mode = createMode();
+ const bar = new PromptContextLine(
+ () => "Updated files",
+ (width) => mode.getPromptContextLabel(width),
+ );
+ for (const expected of [
+ "Collapsed mode (Ctrl+O to expand)",
+ "Details mode (Ctrl+O to expand)",
+ "Expanded mode (Ctrl+O to collapse)",
+ "Collapsed mode (Ctrl+O to expand)",
+ ]) {
+ expect(mode.getPromptContextLabel(120)).toBe(theme.fg("dim", expected));
+ const line = stripAnsi(bar.render(120)[1]!);
+ expect(line).toMatch(/^ Recap: Updated files\s+/);
+ expect(line.trimEnd().endsWith(expected)).toBe(true);
+ expect(visibleWidth(line)).toBe(120);
+ mode.toggleToolOutputExpansion();
+ }
+ });
+
+ it("uses the configured primary key and omits an unbound shortcut without an empty wrapper", () => {
+ setKeybindings(new KeybindingsManager({ "app.tools.expand": ["ctrl+e", "alt+e"] }));
+ expect(formatConversationDetailStatus(false, false)).toBe("Collapsed mode (Ctrl+E to expand)");
+ expect(formatConversationDetailStatus(false, true)).toBe("Details mode (Ctrl+E to expand)");
+ expect(formatConversationDetailStatus(true, true)).toBe("Expanded mode (Ctrl+E to collapse)");
+ setKeybindings(new KeybindingsManager({ "app.tools.expand": [] }));
+ expect(formatConversationDetailStatus(false, false)).toBe("Collapsed mode");
+ expect(formatConversationDetailStatus(false, true)).toBe("Details mode");
+ expect(formatConversationDetailStatus(true, true)).toBe("Expanded mode");
+ });
+
+ it("reflects extension expansion setters", () => {
+ const mode = createMode();
+ mode.setToolsExpanded(true);
+ expect(stripAnsi(mode.getPromptContextLabel(120)!)).toBe("Expanded mode (Ctrl+O to collapse)");
+ mode.setToolsExpanded(false);
+ expect(stripAnsi(mode.getPromptContextLabel(120)!)).toBe("Collapsed mode (Ctrl+O to expand)");
+ });
+
+ it("preserves top-row bounds while the lower tray retains model metadata and navigation overrides", () => {
+ const mode = createMode();
+ const bar = new SubagentSummaryLine(
+ () => "manage",
+ () => mode.getTrayContextLabel(),
+ () => "Press Ctrl+C again to exit",
+ );
+ expect(stripAnsi(bar.render(120)[0]!)).toMatch(/^Press Ctrl\+C again to exit\s+glm-5.3:high$/);
+ const top = new PromptContextLine(
+ () => "Long recap needing truncation",
+ (width) => mode.getPromptContextLabel(width),
+ );
+ for (const width of [1, 10, 30, 40, 80]) {
+ for (const line of [...bar.render(width), ...top.render(width)])
+ expect(visibleWidth(line)).toBeLessThanOrEqual(width);
+ }
+ });
+});
diff --git a/packages/coding-agent/test/custom-editor.test.ts b/packages/coding-agent/test/custom-editor.test.ts
index ba1ce8873f..9a6baa1dc3 100644
--- a/packages/coding-agent/test/custom-editor.test.ts
+++ b/packages/coding-agent/test/custom-editor.test.ts
@@ -84,30 +84,43 @@ describe("CustomEditor", () => {
expect(editor.getText()).toBe("/");
});
- it("inserts a newline for a raw \\n byte instead of firing the ctrl+j edit-diff action", () => {
+ it("inserts a newline for a raw \\n byte instead of firing the conversation detail action", () => {
const editor = new CustomEditor(fakeTui, editorTheme, new KeybindingsManager());
- const toggleEditDiffs = vi.fn();
- editor.onAction("app.edits.expand", toggleEditDiffs);
+ const cycleDetail = vi.fn();
+ editor.onAction("app.tools.expand", cycleDetail);
editor.handleInput("a");
editor.handleInput("\n");
editor.handleInput("b");
- expect(toggleEditDiffs).not.toHaveBeenCalled();
+ expect(cycleDetail).not.toHaveBeenCalled();
expect(editor.getText()).toBe("a\nb");
});
- it("still fires the edit-diff action for kitty CSI-u ctrl+j", () => {
+ it("fires the conversation detail action for kitty CSI-u Ctrl+O", () => {
const editor = new CustomEditor(fakeTui, editorTheme, new KeybindingsManager());
- const toggleEditDiffs = vi.fn();
- editor.onAction("app.edits.expand", toggleEditDiffs);
+ const cycleDetail = vi.fn();
+ editor.onAction("app.tools.expand", cycleDetail);
- editor.handleInput("\x1b[106;5u");
+ editor.handleInput("\x1b[111;5u");
- expect(toggleEditDiffs).toHaveBeenCalledOnce();
+ expect(cycleDetail).toHaveBeenCalledOnce();
expect(editor.getText()).toBe("");
});
+ it("uses the configured conversation detail binding and releases the old default", () => {
+ const keybindings = new KeybindingsManager({ "app.tools.expand": "ctrl+e" });
+ const editor = new CustomEditor(fakeTui, editorTheme, keybindings);
+ const cycleDetail = vi.fn();
+ editor.onAction("app.tools.expand", cycleDetail);
+ editor.handleInput("\x0f");
+ expect(cycleDetail).not.toHaveBeenCalled();
+ editor.handleInput("\x05");
+ expect(cycleDetail).toHaveBeenCalledOnce();
+ expect(keybindings.getEffectiveConfig()).not.toHaveProperty("app.edits.expand");
+ expect(keybindings.getEffectiveConfig()).not.toHaveProperty("app.thinking.toggle");
+ });
+
it("routes Escape through its handler while dismissing autocomplete", async () => {
const editor = new CustomEditor(fakeTui, editorTheme, new KeybindingsManager());
const handler = vi.fn();
diff --git a/packages/coding-agent/test/edit-summary.test.ts b/packages/coding-agent/test/edit-summary.test.ts
index 94330bd64e..b34c7cd3a7 100644
--- a/packages/coding-agent/test/edit-summary.test.ts
+++ b/packages/coding-agent/test/edit-summary.test.ts
@@ -141,14 +141,15 @@ describe("edit summaries", () => {
describe("formatFileChangeSummaryLine", () => {
beforeAll(() => initTheme("dark"));
- test("keeps the truncated path stable when the ctrl+j hint flips", () => {
- const change = { added: 3, removed: 1 };
- const path = "src/some/deeply/nested/directory/with-a-long-file-name.ts";
- const width = 44;
- const pathPart = (line: string) => stripAnsi(line).replace(/\s*\+\d+ -\d+.*$/, "");
- const expanded = formatFileChangeSummaryLine(path, undefined, change, true, width);
- const collapsed = formatFileChangeSummaryLine(path, undefined, change, false, width);
- expect(stripAnsi(expanded)).toContain("…");
- expect(pathPart(expanded)).toBe(pathPart(collapsed));
+ test("preserves change counts when truncating a path without shortcut hints", () => {
+ const line = formatFileChangeSummaryLine(
+ "src/some/deeply/nested/directory/with-a-long-file-name.ts",
+ undefined,
+ { added: 3, removed: 1 },
+ 44,
+ );
+ expect(stripAnsi(line)).toContain("…");
+ expect(stripAnsi(line)).toMatch(/\+3 -1$/);
+ expect(stripAnsi(line)).not.toContain("Ctrl+O");
});
});
diff --git a/packages/coding-agent/test/event-row-hierarchy.test.ts b/packages/coding-agent/test/event-row-hierarchy.test.ts
new file mode 100644
index 0000000000..91556fef88
--- /dev/null
+++ b/packages/coding-agent/test/event-row-hierarchy.test.ts
@@ -0,0 +1,107 @@
+import { setKeybindings } from "@earendil-works/pi-tui";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type { AgentSessionMessage } from "../src/core/agent-messages.js";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { AgentMessageComponent } from "../src/modes/interactive/components/agent-message.js";
+import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
+
+/**
+ * Conversation event rows keep the leading label colored and render the
+ * trailing detail (participants, previews, commands) in the dim tone.
+ */
+describe("conversation event row hierarchy", () => {
+ let previousColorTerm: string | undefined;
+
+ beforeAll(() => {
+ previousColorTerm = process.env.COLORTERM;
+ process.env.COLORTERM = "truecolor";
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ afterAll(() => {
+ if (previousColorTerm === undefined) {
+ delete process.env.COLORTERM;
+ } else {
+ process.env.COLORTERM = previousColorTerm;
+ }
+ });
+
+ function createTuiStub(): any {
+ return {
+ terminal: {
+ get columns() {
+ return 100;
+ },
+ get rows() {
+ return 30;
+ },
+ },
+ addInterval: () => ({ dispose: () => {} }),
+ removeInterval: () => {},
+ requestRender: () => {},
+ };
+ }
+
+ it("dims the participant and preserves the expanded agent message body", () => {
+ const message: AgentSessionMessage = {
+ role: "custom",
+ customType: "agent_message",
+ content: "[task from parent]\n\nReview shard seven.",
+ display: true,
+ details: {
+ id: "spawn:sub-worker",
+ message: "Review shard seven.",
+ from: { sessionId: "parent-session", sessionName: "Planner" },
+ fromRelationship: "parent",
+ },
+ timestamp: 123,
+ };
+
+ const component = new AgentMessageComponent(message);
+ component.setExpanded(true);
+ const raw = component.render(100).join("\n");
+
+ expect(raw).toContain(theme.fg("muted", "Agent message received"));
+ expect(raw).toContain(theme.fg("dim", "from parent Planner"));
+ expect(raw).toContain(theme.fg("customMessageText", "Review shard seven."));
+ });
+
+ it("dims the bash tool command on the call row", () => {
+ const tool = new ToolExecutionComponent(
+ "bash",
+ "t1",
+ { command: "npm test" },
+ {},
+ undefined,
+ createTuiStub(),
+ "/tmp",
+ );
+ tool.markExecutionStarted();
+ tool.setArgsComplete();
+
+ const raw = tool.render(100).join("\n");
+
+ expect(raw).toContain(theme.fg("dim", "$ npm test"));
+ });
+
+ it("keeps the edit label and dims the path on the call row", () => {
+ const tool = new ToolExecutionComponent(
+ "edit",
+ "t2",
+ { path: "src/foo.ts", oldStr: "a", newStr: "b" },
+ {},
+ undefined,
+ createTuiStub(),
+ "/tmp",
+ );
+ tool.markExecutionStarted();
+ tool.setArgsComplete();
+
+ const raw = tool.render(100).join("\n");
+
+ expect(raw).toContain(theme.fg("toolTitle", "edit"));
+ expect(raw).toContain(theme.fg("dim", "src/foo.ts"));
+ });
+});
diff --git a/packages/coding-agent/test/extensions-runner.test.ts b/packages/coding-agent/test/extensions-runner.test.ts
index 2f58f82538..e9c5593d70 100644
--- a/packages/coding-agent/test/extensions-runner.test.ts
+++ b/packages/coding-agent/test/extensions-runner.test.ts
@@ -183,7 +183,7 @@ describe("ExtensionRunner", () => {
it("blocks shortcuts when reserved key is also bound to non-reserved actions", async () => {
const extCode = `
export default function(pi) {
- pi.registerShortcut("ctrl+t", {
+ pi.registerShortcut("ctrl+o", {
description: "Conflicts with shared reserved default",
handler: async () => {},
});
@@ -195,10 +195,11 @@ describe("ExtensionRunner", () => {
const result = await discoverAndLoadExtensions([], tempDir, tempDir);
const runner = new ExtensionRunner(result.extensions, result.runtime, tempDir, sessionManager, modelRegistry);
- const shortcuts = runner.getShortcuts(defaultKeybindings);
+ const keybindings = { ...defaultKeybindings, "app.clipboard.pasteImage": "ctrl+o" as KeyId };
+ const shortcuts = runner.getShortcuts(keybindings);
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("conflicts with built-in"));
- expect(shortcuts.has("ctrl+t")).toBe(false);
+ expect(shortcuts.has("ctrl+o")).toBe(false);
warnSpy.mockRestore();
});
diff --git a/packages/coding-agent/test/interactive-mode-startup.test.ts b/packages/coding-agent/test/interactive-mode-startup.test.ts
index 6847e25c76..f3617c4153 100644
--- a/packages/coding-agent/test/interactive-mode-startup.test.ts
+++ b/packages/coding-agent/test/interactive-mode-startup.test.ts
@@ -738,6 +738,34 @@ describe("InteractiveMode startup hints", () => {
expect(getLabel(subagent)).toBe("depth 1");
});
+ it("keeps remapped conversation detail shortcuts out of the footer while typing", () => {
+ setKeybindings(new KeybindingsManager({ "app.tools.expand": ["ctrl+e", "ctrl+g"] }));
+ const mode = createMode(2, false, () => "draft prompt");
+ const label = stripAnsi(Reflect.get(InteractiveMode.prototype, "getTrayLocationLabel").call(mode));
+
+ expect(label).toBe("");
+ expect(label).not.toContain("detail");
+ expect(label).not.toContain("Ctrl+E");
+ expect(label).not.toContain("Ctrl+O");
+ expect(label).not.toContain("Ctrl+G");
+ });
+
+ it("omits the detail hint when the binding is disabled", () => {
+ setKeybindings(new KeybindingsManager({ "app.tools.expand": [] }));
+ const label = stripAnsi(Reflect.get(InteractiveMode.prototype, "getTrayLocationLabel").call(createMode(1)));
+
+ expect(label).toBe("");
+ expect(label).not.toContain("detail");
+ });
+
+ it("keeps the footer free of detail shortcuts while an overlay owns the input", () => {
+ const mode = createMode(1);
+ mode.ui.hasOverlay = () => true;
+ const label = Reflect.get(InteractiveMode.prototype, "getTrayLocationLabel").call(mode);
+
+ expect(label).toBeUndefined();
+ });
+
it("keeps the question-mark shortcut guide compact", () => {
const guide = Reflect.get(InteractiveMode.prototype, "getShortcutGuide").call(createMode());
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 5db797ec29..5163e92c3a 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -4296,6 +4296,7 @@ describe("InteractiveMode goal status announcements", () => {
});
describe("InteractiveMode tray goal label", () => {
+ beforeAll(() => setKeybindings(new KeybindingsManager()));
type TrayUsage = { contextWindow: number; tokens: number | null; percent: number | null };
type TrayLabelHarness = {
heartbeatCatalog: AgentConnectionHeartbeat[];
@@ -4402,7 +4403,9 @@ describe("InteractiveMode tray goal label", () => {
fakeThis.ui = { hasOverlay: () => false };
fakeThis.editorContainer = { children: [] };
- expect(stripAnsi(getTrayContextLabel.call(fakeThis)!)).toBe("Pursuing goal (1m 05s) · 1 heartbeat · 75k (75%)");
+ expect(stripAnsi(getTrayContextLabel.call(fakeThis)!)).toBe(
+ "Pursuing goal (1m 05s) · 1 heartbeat (Ctrl+R) · 75k (75%)",
+ );
});
test("omits the usage segment when token count is unknown", () => {
@@ -4593,8 +4596,9 @@ describe("InteractiveMode.setToolsExpanded", () => {
function createExpansionFakeThis(chatChildren: unknown[]): any {
const fakeThis: any = {
toolOutputExpanded: false,
- agentMessagesExpanded: false,
editDiffsExpanded: false,
+ hideThinkingBlock: true,
+ pendingBashComponents: [],
customHeader: undefined,
builtInHeader: { setExpanded: vi.fn() },
chatContainer: { children: chatChildren },
@@ -4621,56 +4625,66 @@ describe("InteractiveMode.setToolsExpanded", () => {
expect(fakeThis.ui.requestRenderPreservingViewport).toHaveBeenCalledTimes(1);
});
- test("toggles agent messages separately from tools", () => {
+ test("keeps agent message notices visible and reveals bodies only with all output", () => {
const toolChild = { setExpanded: vi.fn() };
- const ipythonChild = { setExpanded: vi.fn(), setAgentMessagesExpanded: vi.fn(), setEditDiffsExpanded: vi.fn() };
+ const ipythonChild = { setExpanded: vi.fn(), setEditDiffsExpanded: vi.fn() };
const messageChild = new AgentMessageComponent({
role: "custom",
customType: "agent_message",
content: "Ping.",
display: true,
- details: { id: "agentmsg_split", message: "Ping.", from: null },
+ details: { id: "agentmsg_split", message: "Ping." },
timestamp: 123,
- } as any);
- const messageSetExpanded = vi.spyOn(messageChild, "setExpanded");
+ });
const fakeThis = createExpansionFakeThis([toolChild, ipythonChild, messageChild]);
- fakeThis.toggleAgentMessageExpansion();
+ expect(messageChild.render(80).join("\n")).toContain("Agent message received");
+ expect(messageChild.render(80).join("\n")).not.toContain("Ping.");
+ fakeThis.toggleToolOutputExpansion();
+ expect(messageChild.render(80).join("\n")).toContain("Agent message received");
+ expect(messageChild.render(80).join("\n")).not.toContain("Ping.");
+ expect(toolChild.setExpanded).toHaveBeenLastCalledWith(false);
+ expect(ipythonChild.setExpanded).toHaveBeenLastCalledWith(false);
- expect(fakeThis.agentMessagesExpanded).toBe(true);
- expect(fakeThis.toolOutputExpanded).toBe(false);
- expect(messageSetExpanded).toHaveBeenCalledWith(true);
- expect(toolChild.setExpanded).toHaveBeenCalledWith(false);
- expect(ipythonChild.setExpanded).toHaveBeenCalledWith(false);
- expect(ipythonChild.setAgentMessagesExpanded).toHaveBeenCalledWith(true);
-
- fakeThis.setToolsExpanded(true);
+ fakeThis.toggleToolOutputExpansion();
+ expect(messageChild.render(80).join("\n")).toContain("Ping.");
+ expect(toolChild.setExpanded).toHaveBeenLastCalledWith(true);
+ expect(ipythonChild.setExpanded).toHaveBeenLastCalledWith(true);
- expect(toolChild.setExpanded).toHaveBeenCalledWith(true);
- expect(messageSetExpanded).toHaveBeenLastCalledWith(true);
- expect(ipythonChild.setExpanded).toHaveBeenCalledWith(true);
- expect(ipythonChild.setAgentMessagesExpanded).toHaveBeenLastCalledWith(true);
- expect(fakeThis.agentMessagesExpanded).toBe(true);
+ fakeThis.toggleToolOutputExpansion();
+ expect(messageChild.render(80).join("\n")).toContain("Agent message received");
+ expect(messageChild.render(80).join("\n")).not.toContain("Ping.");
+ expect(toolChild.setExpanded).toHaveBeenLastCalledWith(false);
+ expect(ipythonChild.setExpanded).toHaveBeenLastCalledWith(false);
});
- test("toggles edit diffs separately from tools and agent messages", () => {
- const child = { setExpanded: vi.fn(), setAgentMessagesExpanded: vi.fn(), setEditDiffsExpanded: vi.fn() };
+ test("cycles from overview through details and all back to overview", () => {
+ const child = { setExpanded: vi.fn(), setEditDiffsExpanded: vi.fn() };
const fakeThis = createExpansionFakeThis([child]);
- fakeThis.toggleEditDiffExpansion();
+ fakeThis.toggleToolOutputExpansion();
expect(fakeThis.editDiffsExpanded).toBe(true);
+ expect(fakeThis.hideThinkingBlock).toBe(false);
expect(fakeThis.toolOutputExpanded).toBe(false);
- expect(fakeThis.agentMessagesExpanded).toBe(false);
expect(child.setEditDiffsExpanded).toHaveBeenCalledWith(true);
expect(child.setExpanded).toHaveBeenCalledWith(false);
- expect(child.setAgentMessagesExpanded).toHaveBeenCalledWith(false);
- fakeThis.setToolsExpanded(true);
+ fakeThis.toggleToolOutputExpansion();
expect(fakeThis.editDiffsExpanded).toBe(true);
+ expect(fakeThis.hideThinkingBlock).toBe(false);
+ expect(fakeThis.toolOutputExpanded).toBe(true);
expect(child.setEditDiffsExpanded).toHaveBeenLastCalledWith(true);
expect(child.setExpanded).toHaveBeenLastCalledWith(true);
+
+ fakeThis.toggleToolOutputExpansion();
+
+ expect(fakeThis.editDiffsExpanded).toBe(false);
+ expect(fakeThis.hideThinkingBlock).toBe(true);
+ expect(fakeThis.toolOutputExpanded).toBe(false);
+ expect(child.setEditDiffsExpanded).toHaveBeenLastCalledWith(false);
+ expect(child.setExpanded).toHaveBeenLastCalledWith(false);
});
});
diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.ts
index 1641635da3..1a8f4d0628 100644
--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts
+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts
@@ -2,6 +2,7 @@ import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
import { Container, type MarkdownTheme, type TUI } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import { beforeAll, describe, expect, test, vi } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
import type { AgentConnectionSessionEvent } from "../src/modes/agent-connection/index.js";
import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js";
import type { AssistantMessageComponent } from "../src/modes/interactive/components/assistant-message.js";
@@ -63,11 +64,10 @@ type GetUserInput = (this: {
}) => Promise<string | undefined>;
type HandleSubagentSummaryChatAction = (
this: {
- keybindings: { matches(data: string, action: string): boolean };
+ keybindings: KeybindingsManager;
editor: { handleInput(data: string): void };
focusEditor(): void;
toggleToolOutputExpansion(): void;
- toggleThinkingBlockVisibility(): void;
},
data: string,
) => void;
@@ -315,36 +315,33 @@ describe("InteractiveMode streaming events", () => {
await expect(getUserInput.call({ agentsViewRequest: "agents_view" })).resolves.toBeUndefined();
});
- test("forwards typed keys from focused subagent summary back to the editor", () => {
+ test.each(["x", "\x10"])("forwards typed key %j from focused subagent summary back to the editor", (key) => {
const handleSubagentSummaryChatAction = (
InteractiveMode.prototype as unknown as { handleSubagentSummaryChatAction: HandleSubagentSummaryChatAction }
).handleSubagentSummaryChatAction;
const fakeThis = {
- keybindings: { matches: vi.fn(() => false) },
+ keybindings: new KeybindingsManager(),
editor: { handleInput: vi.fn() },
focusEditor: vi.fn(),
toggleToolOutputExpansion: vi.fn(),
- toggleThinkingBlockVisibility: vi.fn(),
};
- handleSubagentSummaryChatAction.call(fakeThis, "x");
+ handleSubagentSummaryChatAction.call(fakeThis, key);
expect(fakeThis.focusEditor).toHaveBeenCalledOnce();
- expect(fakeThis.editor.handleInput).toHaveBeenCalledWith("x");
+ expect(fakeThis.editor.handleInput).toHaveBeenCalledWith(key);
expect(fakeThis.toggleToolOutputExpansion).not.toHaveBeenCalled();
- expect(fakeThis.toggleThinkingBlockVisibility).not.toHaveBeenCalled();
});
- test("keeps focused subagent summary shortcuts in the chat surface", () => {
+ test("keeps the conversation detail shortcut in the chat surface", () => {
const handleSubagentSummaryChatAction = (
InteractiveMode.prototype as unknown as { handleSubagentSummaryChatAction: HandleSubagentSummaryChatAction }
).handleSubagentSummaryChatAction;
const fakeThis = {
- keybindings: { matches: vi.fn((_data: string, action: string) => action === "app.tools.expand") },
+ keybindings: new KeybindingsManager(),
editor: { handleInput: vi.fn() },
focusEditor: vi.fn(),
toggleToolOutputExpansion: vi.fn(),
- toggleThinkingBlockVisibility: vi.fn(),
};
handleSubagentSummaryChatAction.call(fakeThis, "\x0f");
@@ -361,6 +358,7 @@ describe("InteractiveMode streaming events", () => {
const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;
Object.assign(mode, {
connectionState: { isStreaming: false },
+ chatContainer: new Container(),
subagentSnapshots: new Map([["worker", { id: "worker", status: "running" }]]),
pulseTimer: undefined,
ui: { requestRender },
diff --git a/packages/coding-agent/test/ipython-cell-diff.test.ts b/packages/coding-agent/test/ipython-cell-diff.test.ts
index 6441b7d8ed..bca6acf4be 100644
--- a/packages/coding-agent/test/ipython-cell-diff.test.ts
+++ b/packages/coding-agent/test/ipython-cell-diff.test.ts
@@ -114,7 +114,7 @@ describe("IPythonCellComponent diff rendering", () => {
expect(diffRows.some(hasBackground)).toBe(true);
});
- it("always shows the summary line and indents diff rows to its text column", () => {
+ it("keeps the summary visible and renders diff rows at the normal content margin", () => {
const state = {
code: "await edit(...)",
details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
@@ -125,26 +125,36 @@ describe("IPythonCellComponent diff rendering", () => {
const hidden = renderCell({ ...state, editDiffsExpanded: false }).split("\n");
const hiddenSummary = hidden.find((l) => l.includes("╰─ a.ts"));
- expect(hiddenSummary).toMatch(/^ {4}╰─ a\.ts \+1 -1 · .*to expand\)$/);
+ expect(hiddenSummary).toMatch(/^ {4}╰─ a\.ts \+1 -1$/);
const notLatest = renderCell({ ...state, editDiffsExpanded: false, showExpandHint: false }).split("\n");
- expect(notLatest.find((l) => l.includes("╰─ a.ts"))).toMatch(/to expand\)$/);
+ expect(notLatest.find((l) => l.includes("╰─ a.ts"))).toBe(hiddenSummary);
expect(hidden.some((l) => /1 - .*x/.test(l))).toBe(false);
const shown = renderCell({ ...state, editDiffsExpanded: true }).split("\n");
const summary = shown.find((l) => l.includes("╰─ a.ts"));
- expect(summary).toMatch(/^ {4}╰─ a\.ts \+1 -1 · .*to collapse\)$/);
- const textColumn = (summary ?? "").indexOf("a.ts");
+ expect(summary).toMatch(/^ {4}╰─ a\.ts \+1 -1$/);
const removed = shown.find((l) => /1 - .*x/.test(l));
const added = shown.find((l) => /1 \+ .*X/.test(l));
expect(removed).toBeDefined();
expect(added).toBeDefined();
- for (const row of [removed ?? "", added ?? ""]) {
- expect(row.startsWith(" ".repeat(textColumn))).toBe(true);
- }
+ expect(removed?.trimEnd()).toBe(" 1 - x");
+ expect(added?.trimEnd()).toBe(" 1 + X");
expect(shown.filter((l) => !/\d+ [-+ ] /.test(l) && !l.includes("⋮")).length).toBe(hidden.length);
});
+ it("preserves source indentation inside the diff after removing the outer nesting", () => {
+ const out = renderCell({
+ code: "await edit(...)",
+ details: { status: "ok", diffs: [{ path: "a.py", oldStr: " old()", newStr: " new()", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ editDiffsExpanded: true,
+ }).split("\n");
+ expect(out.find((line) => line.includes("old()"))?.trimEnd()).toBe(" 1 - old()");
+ expect(out.find((line) => line.includes("new()"))?.trimEnd()).toBe(" 1 + new()");
+ });
+
it("renders an edit path relative to the session cwd, or absolute when outside it", () => {
const cwd = "/home/me/project";
const inside = renderCell({
@@ -230,10 +240,10 @@ describe("IPythonCellComponent diff rendering", () => {
expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
const summary = lines.map(stripAnsi).find((line) => line.includes("…"));
expect(summary).toBeDefined();
- expect(summary).toMatch(/\+1 -1 · /);
+ expect(summary).toMatch(/\+1 -1$/);
});
- it("advertises the collapse key once per cell when diffs are expanded", () => {
+ it("keeps every file summary free of detail hints when diffs are expanded", () => {
const lines = new IPythonCellComponent({
code: "await edit(...)",
details: {
@@ -249,9 +259,9 @@ describe("IPythonCellComponent diff rendering", () => {
editDiffsExpanded: true,
}).render(120);
const plain = lines.map(stripAnsi);
- const hinted = plain.filter((line) => line.includes("to collapse") && /[+]\d+ -\d+/.test(line));
- expect(hinted).toHaveLength(1);
- expect(hinted[0]).toContain("b.ts");
+ const summaries = plain.filter((line) => /╰─ [ab]\.ts/.test(line));
+ expect(summaries).toEqual([" ╰─ a.ts +1 -1", " ╰─ b.ts +1 -1"]);
+ expect(plain.join("\n")).not.toContain("Ctrl+O");
});
it("never overflows a narrow pane when expanded diffs render", () => {
@@ -311,10 +321,9 @@ describe("IPythonCellComponent diff rendering", () => {
expanded: true,
editDiffsExpanded: true,
}).split("\n");
- expect(out[0]).toContain("to collapse");
- expect(out[1].trim()).toBe("");
- expect(out[2]).toContain("await edit(...)");
- expect(out.findIndex((line) => line.includes("a.ts"))).toBeGreaterThan(2);
+ expect(out[0]).not.toContain("cycle detail");
+ expect(out[1]).toBe(" ╰─ await edit(...)");
+ expect(out.findIndex((line) => line.includes("a.ts"))).toBeGreaterThan(1);
});
it("keeps the summary line but hides diff rows when edit diffs are collapsed", () => {
@@ -326,7 +335,7 @@ describe("IPythonCellComponent diff rendering", () => {
expanded: false,
});
expect(collapsed).toContain("╰─ big.py +1 -1");
- expect(collapsed).toContain("to expand");
+ expect(collapsed).not.toContain("cycle detail");
expect(collapsed).not.toContain("old");
expect(collapsed).not.toContain("NEW");
});
@@ -360,7 +369,7 @@ describe("IPythonCellComponent diff rendering", () => {
expanded: false,
});
expect(collapsed.split("\n")).toHaveLength(1);
- expect(collapsed).toContain("to expand");
+ expect(collapsed).not.toContain("cycle detail");
expect(collapsed).not.toContain("world");
});
@@ -385,7 +394,7 @@ describe("IPythonCellComponent diff rendering", () => {
expect((out.match(/⋮/g) ?? []).length).toBe(2);
});
- it("keeps the top line stable when expanded — only the hint flips, no header line, no layout shift", () => {
+ it("keeps the top line stable without a detail hint when expanded", () => {
const state = {
code: "print(55)",
content: [{ type: "text", text: "55" }],
@@ -396,10 +405,9 @@ describe("IPythonCellComponent diff rendering", () => {
const collapsed = new IPythonCellComponent({ ...state, expanded: false }).render(80);
const expanded = new IPythonCellComponent({ ...state, expanded: true }).render(80);
- 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]));
+ expect(stripAnsi(collapsed[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s$/);
+ expect(stripAnsi(expanded[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s$/);
+ expect(stripAnsi(expanded[0])).toBe(stripAnsi(collapsed[0]));
const stripped = expanded.map(stripAnsi);
expect(stripped.filter((l) => /python · done/.test(l)).length).toBe(0);
diff --git a/packages/coding-agent/test/ipython-cell-preview.test.ts b/packages/coding-agent/test/ipython-cell-preview.test.ts
new file mode 100644
index 0000000000..a2c4fb6f6b
--- /dev/null
+++ b/packages/coding-agent/test/ipython-cell-preview.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { IPythonCellComponent } from "../src/modes/interactive/components/ipython-cell.js";
+import { initTheme, preloadCodeHighlighter, theme } from "../src/modes/interactive/theme/theme.js";
+
+type CellState = ConstructorParameters<typeof IPythonCellComponent>[0];
+
+/**
+ * The collapsed summary row shows a one-line code preview next to the status
+ * marker. It renders plain and dim (matching the quieted thinking trace) so it
+ * reads as metadata; the expanded block keeps full highlighting.
+ */
+describe("IPythonCellComponent collapsed preview styling", () => {
+ let previousColorTerm: string | undefined;
+
+ beforeAll(async () => {
+ previousColorTerm = process.env.COLORTERM;
+ await preloadCodeHighlighter();
+ });
+
+ afterAll(() => {
+ if (previousColorTerm === undefined) {
+ delete process.env.COLORTERM;
+ } else {
+ process.env.COLORTERM = previousColorTerm;
+ }
+ });
+
+ function useTruecolor(): void {
+ process.env.COLORTERM = "truecolor";
+ initTheme("dark");
+ }
+
+ function renderCell(state: CellState): string {
+ return new IPythonCellComponent(state).render(100).join("\n");
+ }
+
+ it("renders the collapsed python preview plain and dim, without syntax colors", () => {
+ useTruecolor();
+ const raw = renderCell({
+ code: 'print("hello world")',
+ content: [{ type: "text", text: "hello world" }],
+ details: { status: "ok", durationMs: 12, stdout: "hello world" },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ });
+
+ expect(raw).toContain(theme.fg("dim", 'print("hello world")'));
+ expect(raw).not.toContain(theme.getFgAnsi("syntaxString"));
+ // Line counts and duration render in the same dim tone as the preview.
+ expect(raw).toContain(theme.fg("dim", "↑ 1 ↓ 1 lines"));
+ expect(raw).toContain(theme.fg("dim", "12ms"));
+ });
+
+ it("renders the collapsed bash preview dim instead of bash-mode green", () => {
+ useTruecolor();
+ const raw = renderCell({
+ code: "!git status --short",
+ content: [{ type: "text", text: "ok" }],
+ details: { status: "ok", durationMs: 12, stdout: "ok" },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ });
+
+ expect(raw).toContain(theme.fg("dim", "!git status --short"));
+ expect(raw).not.toContain(theme.fg("bashMode", "!git status --short"));
+ });
+
+ it("keeps syntax highlighting on the expanded python code block", () => {
+ useTruecolor();
+ const raw = renderCell({
+ code: 'print("hello world")',
+ content: [{ type: "text", text: "hello world" }],
+ details: { status: "ok", durationMs: 12, stdout: "hello world" },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: true,
+ });
+
+ expect(raw).toContain(theme.getFgAnsi("syntaxString"));
+ });
+
+ it("keeps bash-mode green on the expanded bash code block", () => {
+ useTruecolor();
+ const raw = renderCell({
+ code: "!git status --short",
+ content: [{ type: "text", text: "ok" }],
+ details: { status: "ok", durationMs: 12, stdout: "ok" },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: true,
+ });
+
+ expect(raw).toContain(theme.fg("bashMode", "!git status --short"));
+ });
+});
diff --git a/packages/coding-agent/test/ipython-cell-wrap.test.ts b/packages/coding-agent/test/ipython-cell-wrap.test.ts
index d70cef26d8..9deb270993 100644
--- a/packages/coding-agent/test/ipython-cell-wrap.test.ts
+++ b/packages/coding-agent/test/ipython-cell-wrap.test.ts
@@ -1,7 +1,8 @@
import { visibleWidth } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
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 { initTheme, preloadCodeHighlighter, theme } from "../src/modes/interactive/theme/theme.js";
type CellState = ConstructorParameters<typeof IPythonCellComponent>[0];
@@ -48,8 +49,92 @@ const WRAPPING_STATE: CellState = {
};
describe("IPythonCellComponent wrapping", () => {
- beforeAll(() => {
+ beforeAll(async () => {
initTheme("dark");
+ await preloadCodeHighlighter();
+ });
+
+ it.each(['"""', "'''", 'r"""'])(
+ "preserves multiline string colors across physical and wrapped lines (%s)",
+ (opening) => {
+ const code = [
+ `body = ${opening}stringtoken`,
+ "stringtoken stringtoken stringtoken stringtoken",
+ "",
+ "```ts",
+ "if (!env || state.clientEnv) return; // stringtoken",
+ "!not_a_shell stringtoken",
+ "```",
+ opening.slice(-3),
+ "after_value = 7",
+ ].join("\n");
+ for (const width of [20, 34, 120]) {
+ const lines = new IPythonCellComponent({
+ ...WRAPPING_STATE,
+ code,
+ content: [],
+ details: { status: "ok" },
+ }).render(width);
+ const codeLines = lines.slice(1);
+ const tokenLines = codeLines.filter((line) => line.includes("stringtoken"));
+ expect(tokenLines.length).toBeGreaterThanOrEqual(4);
+ for (const line of tokenLines) {
+ const escapes = [...line.slice(0, line.indexOf("stringtoken")).matchAll(/\x1b\[[0-9;]*m/g)];
+ expect(escapes.at(-1)?.[0]).toBe(theme.getFgAnsi("syntaxString"));
+ }
+ const afterLine = codeLines.find((line) => line.includes("after_value"));
+ expect(afterLine).toBeDefined();
+ expect(foregroundLeftOpen(afterLine!.slice(0, afterLine!.indexOf("after_value")))).toBe(false);
+ expect(afterLine).toContain(`${theme.getFgAnsi("syntaxNumber")}7`);
+ expect(lines.some(foregroundLeftOpen)).toBe(false);
+ expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
+ }
+ },
+ );
+
+ it("nests source directly beneath the summary and marks only the output", () => {
+ const state: CellState = {
+ ...WRAPPING_STATE,
+ code: "if True:\n print('hello')",
+ details: { status: "ok", stdout: "hello\nworld", result: "42" },
+ };
+ const lines = new IPythonCellComponent(state).render(80).map(stripAnsi);
+ expect(lines[1]).toBe(" ╰─ if True:");
+ expect(lines[2]).toBe(" print('hello')");
+ expect(lines[3]).toBe("");
+ expect(lines[4]).toBe(" › hello");
+ expect(lines[5]).toBe(" world");
+ expect(lines[6]).toBe(" 42");
+ expect(lines.filter((line) => line.includes("›"))).toHaveLength(1);
+ });
+
+ it.each([
+ { details: { status: "ok" }, expected: "no output" },
+ { details: { status: "ok" }, isPartial: true, expected: "waiting for output..." },
+ {
+ details: {
+ status: "error",
+ error: { ename: "NameError", evalue: "broken", traceback: ["Traceback:", "NameError: broken"] },
+ },
+ expected: "Traceback:",
+ },
+ {
+ details: { status: "ok" },
+ content: [{ type: "image", data: "", mimeType: "image/png" }],
+ showImages: true,
+ expected: "1 image rendered below",
+ },
+ ])("marks empty, pending, error, and image output: $expected", ({ expected, ...outputState }) => {
+ const lines = new IPythonCellComponent({
+ ...WRAPPING_STATE,
+ code: "work()",
+ content: [],
+ ...outputState,
+ })
+ .render(100)
+ .map(stripAnsi);
+ expect(lines[1]).toBe(" ╰─ work()");
+ expect(lines).toContain(` › ${expected}`);
});
it("never leaves a foreground color open at a wrapped line end", () => {
diff --git a/packages/coding-agent/test/keybinding-hints.test.ts b/packages/coding-agent/test/keybinding-hints.test.ts
index 5624c5c046..189bc7715c 100644
--- a/packages/coding-agent/test/keybinding-hints.test.ts
+++ b/packages/coding-agent/test/keybinding-hints.test.ts
@@ -1,7 +1,31 @@
-import { describe, expect, it } from "vitest";
-import { formatKeyText } from "../src/modes/interactive/components/keybinding-hints.js";
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeEach, describe, expect, it } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { expandCollapseHint, formatKeyText } from "../src/modes/interactive/components/keybinding-hints.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
describe("keybinding hint formatting", () => {
+ beforeEach(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ it("omits inline conversation detail hints for both expansion states", () => {
+ for (const expanded of [false, true]) {
+ expect(expandCollapseHint("app.tools.expand", expanded)).toBe("");
+ }
+ setKeybindings(new KeybindingsManager({ "app.tools.expand": "ctrl+e" }));
+ expect(expandCollapseHint("app.tools.expand", false)).toBe("");
+ });
+
+ it("preserves explicit picker expansion instructions", () => {
+ expect(stripAnsi(expandCollapseHint("app.agents.expand", false))).toContain("to expand");
+ expect(stripAnsi(expandCollapseHint("app.agents.expand", true))).toContain("to collapse");
+ setKeybindings(new KeybindingsManager({ "app.agents.expand": "ctrl+e" }));
+ expect(stripAnsi(expandCollapseHint("app.agents.expand", false))).toBe("(Ctrl+E to expand)");
+ });
+
it("uses macOS modifier names on darwin but keeps Ctrl literal", () => {
expect(formatKeyText("ctrl+p", "darwin")).toBe("Ctrl+P");
expect(formatKeyText("alt+enter", "darwin")).toBe("Option+Enter");
diff --git a/packages/coding-agent/test/keybindings-migration.test.ts b/packages/coding-agent/test/keybindings-migration.test.ts
index b94f5208b0..96605e77e3 100644
--- a/packages/coding-agent/test/keybindings-migration.test.ts
+++ b/packages/coding-agent/test/keybindings-migration.test.ts
@@ -3,7 +3,7 @@ import * as os from "node:os";
import * as path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ENV_AGENT_DIR } from "../src/config.js";
-import { KeybindingsManager } from "../src/core/keybindings.js";
+import { KEYBINDINGS, KeybindingsManager } from "../src/core/keybindings.js";
import { runMigrations } from "../src/migrations.js";
describe("keybindings migration", () => {
@@ -90,26 +90,33 @@ describe("keybindings migration", () => {
it("gives explicit editor bindings precedence over application defaults", () => {
const keybindings = new KeybindingsManager({
- "tui.editor.cursorUp": ["up", "ctrl+p"],
+ "tui.editor.cursorUp": ["up", "ctrl+o"],
"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("tui.editor.cursorUp")).toEqual(["up", "ctrl+o"]);
+ expect(keybindings.getKeys("app.tools.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",
+ "tui.editor.cursorUp": ["up", "ctrl+o"],
+ "app.tools.expand": "ctrl+o",
});
expect(keybindings.getConflicts()).toContainEqual({
- key: "ctrl+p",
- keybindings: ["tui.editor.cursorUp", "app.messages.expand"],
+ key: "ctrl+o",
+ keybindings: ["tui.editor.cursorUp", "app.tools.expand"],
});
- expect(keybindings.getKeys("app.messages.expand")).toEqual(["ctrl+p"]);
+ expect(keybindings.getKeys("app.tools.expand")).toEqual(["ctrl+o"]);
+ });
+
+ it("does not define an independent message expansion action", () => {
+ expect(KEYBINDINGS).not.toHaveProperty("app.messages.expand");
+ const keybindings = new KeybindingsManager({ "tui.editor.cursorUp": ["up", "ctrl+p"] });
+ expect(keybindings.getKeys("tui.editor.cursorUp")).toEqual(["up", "ctrl+p"]);
+ expect(keybindings.getKeys("app.tools.expand")).toEqual(["ctrl+o"]);
});
});
diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.ts
index c328106e2e..c4bc0dfe77 100644
--- a/packages/coding-agent/test/marquee-components.test.ts
+++ b/packages/coding-agent/test/marquee-components.test.ts
@@ -98,7 +98,7 @@ describe("marquee TUI components", () => {
expect(collapsed).toContain("ValueError");
expect(collapsed).not.toContain("ValueError: bad");
expect(collapsed).not.toContain("ipython");
- expect(collapsed).toContain("Ctrl+O to expand");
+ expect(collapsed).not.toContain("Ctrl+O");
expect(collapsed).not.toContain("traceback collapsed");
expect(collapsed).not.toContain('File "<stdin>"');
@@ -147,7 +147,8 @@ 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.trimEnd()).toMatch(/CalledProcessError$/);
+ expect(collapsed).not.toContain("Ctrl+O");
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");
@@ -182,7 +183,8 @@ 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.trimEnd()).toMatch(/RuntimeError$/);
+ expect(collapsed).not.toContain("Ctrl+O");
expect(collapsed).not.toContain("no output");
expect(collapsed).not.toContain("/tmp/internal.py");
expect(collapsed).not.toContain("line 12");
@@ -230,7 +232,8 @@ describe("marquee TUI components", () => {
expect(collapsed).toContain("line_0 = 0");
expect(collapsed).not.toContain("line_7 = 7");
expect(collapsed).toContain("↑ 8");
- expect(collapsed.match(/to expand/g)?.length).toBe(1);
+ expect(collapsed).not.toContain("Ctrl+O");
+ expect(collapsed.trimEnd()).not.toMatch(/·$/);
component.update({ ...state, expanded: true });
const expanded = stripAnsi(component.render(100).join("\n"));
@@ -238,7 +241,7 @@ describe("marquee TUI components", () => {
expect(expanded).toContain("line_7 = 7");
});
- test("shows one expand hint when ipython input and output are both collapsed", () => {
+ test("keeps collapsed ipython input and output summaries free of repeated detail hints", () => {
const code = Array.from({ length: 8 }, (_, index) => `line_${index} = ${index}`).join("\n");
const output = Array.from({ length: 8 }, (_, index) => `out_${index}`).join("\n");
const component = new IPythonCellComponent({
@@ -252,7 +255,8 @@ describe("marquee TUI components", () => {
const collapsed = stripAnsi(component.render(100).join("\n"));
expect(collapsed).toContain("↑ 8 ↓ 8 lines");
- expect(collapsed.match(/to expand/g)?.length).toBe(1);
+ expect(collapsed).not.toContain("Ctrl+O");
+ expect(collapsed.trimEnd()).not.toMatch(/·$/);
});
test("reflows cached ipython cells when terminal width changes", () => {
@@ -305,7 +309,7 @@ describe("marquee TUI components", () => {
const collapsed = component.render(100);
const collapsedText = stripAnsi(collapsed.join("\n"));
- expect(collapsedText).toContain("Ctrl+O to expand");
+ expect(collapsedText).not.toContain("Ctrl+O");
expect(collapsedText).not.toContain("traceback collapsed");
expect(collapsedText).not.toContain('File "<stdin>"');
@@ -351,7 +355,7 @@ describe("marquee TUI components", () => {
const collapsed = stripAnsi(component.render(100).join("\n"));
expect(collapsed).toContain("Error: Provider request failed");
- expect(collapsed).toContain("Ctrl+O to expand");
+ expect(collapsed).not.toContain("Ctrl+O");
expect(collapsed).not.toContain("error details collapsed");
expect(collapsed).not.toContain("/tmp/internal.py");
@@ -397,7 +401,7 @@ describe("marquee TUI components", () => {
const short = stripAnsi(shortComponent.render(100).join("\n"));
expect(short).toContain("Error: provider failure");
expect(short).not.toContain("error details collapsed");
- expect(short).not.toContain("Ctrl+O to expand");
+ expect(short).not.toContain("Ctrl+O");
});
test("routes built-in ipython tool rows through the cell renderer", () => {
@@ -422,7 +426,7 @@ describe("marquee TUI components", () => {
const collapsed = stripAnsi(collapsedLines.join("\n"));
expect(collapsed).toContain("python");
expect(collapsed).toContain("12ms");
- expect(collapsed).toContain("Ctrl+O to expand");
+ expect(collapsed).not.toContain("Ctrl+O");
expect(collapsed).not.toContain("ipython");
expect(collapsed).not.toContain('"code"');
@@ -431,7 +435,7 @@ describe("marquee TUI components", () => {
const expanded = stripAnsi(expandedLines.join("\n"));
const expandedStatus = expandedLines.map(stripAnsi).find((line) => line.includes("python · print(55)"));
expect(expandedStatus).toContain("↑ 1 ↓ 1 lines · 12ms");
- expect(expanded).toContain("Ctrl+O to collapse");
+ expect(expanded).not.toContain("Ctrl+O");
expect(expanded).toContain("print(55)");
expect(expanded).toContain("55");
expect(expanded).not.toContain('"code"');
diff --git a/packages/coding-agent/test/refinement-outcome-message.test.ts b/packages/coding-agent/test/refinement-outcome-message.test.ts
index ab8418389c..5408dc77ee 100644
--- a/packages/coding-agent/test/refinement-outcome-message.test.ts
+++ b/packages/coding-agent/test/refinement-outcome-message.test.ts
@@ -361,6 +361,7 @@ describe("RefinementOutcomeMessageComponent", () => {
const live = new RefinementOutcomeMessageComponent(message);
const mode = Object.assign(Object.create(InteractiveMode.prototype), {
chatContainer: { children: [live] },
+ pendingBashComponents: [],
ui: { isFullscreen: () => true, requestRender: vi.fn() },
});
for (const [toolsExpanded, editDiffsExpanded] of [
diff --git a/packages/coding-agent/test/settings-selector.test.ts b/packages/coding-agent/test/settings-selector.test.ts
index f5be873682..f8a5a7bf78 100644
--- a/packages/coding-agent/test/settings-selector.test.ts
+++ b/packages/coding-agent/test/settings-selector.test.ts
@@ -23,7 +23,6 @@ const config: SettingsConfig = {
availableThinkingLevels: ["off"],
currentTheme: "dark",
availableThemes: ["dark"],
- hideThinkingBlock: false,
mermaidRenderingMode: "streaming",
treeFilterMode: "user-only",
showHardwareCursor: false,
@@ -49,7 +48,6 @@ const callbacks: SettingsCallbacks = {
onTransportChange: () => {},
onThinkingLevelChange: () => {},
onThemeChange: () => {},
- onHideThinkingBlockChange: () => {},
onMermaidRenderingModeChange: () => {},
onTreeFilterModeChange: () => {},
onShowHardwareCursorChange: () => {},
@@ -68,6 +66,12 @@ describe("SettingsSelectorComponent", () => {
initTheme("dark");
});
+ test("does not offer a separate hide-thinking setting", () => {
+ const component = new SettingsSelectorComponent(config, callbacks);
+ for (const character of "hide thinking") component.getSettingsList().handleInput(character);
+ expect(stripAnsi(component.render(120).join("\n"))).not.toContain("Hide thinking");
+ });
+
test("shows the image metadata toggle without a terminal graphics protocol", () => {
setCapabilities({ images: null, trueColor: true, hyperlinks: true });
try {
diff --git a/packages/coding-agent/test/suite/regressions/2068-shell-message-steering.test.ts b/packages/coding-agent/test/suite/regressions/2068-shell-message-steering.test.ts
index 012e911574..3226171654 100644
--- a/packages/coding-agent/test/suite/regressions/2068-shell-message-steering.test.ts
+++ b/packages/coding-agent/test/suite/regressions/2068-shell-message-steering.test.ts
@@ -113,7 +113,7 @@ describe("#2068 shell message steering", () => {
harness.setResponses([
(context) => {
requests++;
- expect(getMessageText(context.messages.at(-1))).toContain("Source: bash");
+ expect(getMessageText(context.messages.at(-1))).toContain("[bash-done pid:42 exit:0]");
return fauxAssistantMessage("Inspected the shell result.");
},
]);
@@ -185,7 +185,7 @@ describe("#2068 shell message steering", () => {
.render(120)
.join("\n")
.replace(/\u001b\[[0-9;]*m/g, "");
- expect(render()).toContain("◆ Background command finished · pid 42 · exit 0");
+ expect(render()).toContain("✓ Background shell command finished");
expect(render()).not.toMatch(/Follow-up:|Steering:|Agent message received/);
component.setExpanded(true);
expect(render()).toContain("[bash-done pid:42 exit:0]");
diff --git a/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts b/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts
index 5dadaa46b4..3bb705b4b6 100644
--- a/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts
+++ b/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts
@@ -63,7 +63,6 @@ describe("assistant Markdown file links", () => {
{ ...message, content: [{ type: "text", text: `[Audit report](${href})` }] },
false,
undefined,
- undefined,
{ cwd },
);
const lines = component.render(80);
@@ -107,7 +106,7 @@ describe("assistant Markdown file links", () => {
});
test("streamed reference links and thinking links retain their base after invalidation", () => {
- const component = new AssistantMessageComponent(undefined, false, undefined, undefined, { cwd });
+ const component = new AssistantMessageComponent(undefined, false, undefined, { cwd });
component.updateContent({ ...message, content: [{ type: "text", text: "[Audit report][report]" }] }, true);
expect(linkTargets(component.render(80))).toEqual([]);
component.updateContent(
@@ -127,7 +126,7 @@ describe("assistant Markdown file links", () => {
test("keeps the visible path fallback when the terminal does not support hyperlinks", () => {
setCapabilities({ images: null, trueColor: true, hyperlinks: false });
- const component = new AssistantMessageComponent(message, false, undefined, undefined, { cwd });
+ const component = new AssistantMessageComponent(message, false, undefined, { cwd });
const lines = component.render(80);
expect(linkTargets(lines)).toEqual([]);
expect(stripAnsi(lines.join("\n")).trim()).toBe("Audit report (audit-out/report.md)");
diff --git a/packages/coding-agent/test/suite/regressions/2193-chat-detail-cycle.test.ts b/packages/coding-agent/test/suite/regressions/2193-chat-detail-cycle.test.ts
new file mode 100644
index 0000000000..33371e5653
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2193-chat-detail-cycle.test.ts
@@ -0,0 +1,334 @@
+import { readFileSync } from "node:fs";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import { fauxAssistantMessage, fauxText, fauxThinking, fauxToolCall } from "@earendil-works/pi-ai";
+import { type Container, setKeybindings, type TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { Type } from "typebox";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { createAgentSessionMessage } from "../../../src/core/agent-messages.js";
+import { KeybindingsManager } from "../../../src/core/keybindings.js";
+import { createAsyncBashCompletionMessage } from "../../../src/core/messages.js";
+import { SessionManager } from "../../../src/core/session-manager.js";
+import type { AgentConnection, AgentConnectionSessionEvent } from "../../../src/modes/agent-connection/index.js";
+import { BashExecutionComponent } from "../../../src/modes/interactive/components/bash-execution.js";
+import type { CustomEditor } from "../../../src/modes/interactive/components/custom-editor.js";
+import { SideQuestionComponent } from "../../../src/modes/interactive/components/side-question.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { createInteractiveModeUiServices } from "../../../src/modes/interactive/interactive-mode-services.js";
+import { initTheme, stopThemeWatcher } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+const output = "preview-one\npreview-two\npreview-three\nFULL_TOOL_OUTPUT";
+const tools: AgentTool[] = [
+ {
+ name: "generic",
+ label: "Generic",
+ description: "Fixture output",
+ parameters: Type.Object({}),
+ execute: async () => ({ content: [{ type: "text", text: output }], details: {} }),
+ },
+ {
+ name: "edit",
+ label: "Edit",
+ description: "Fixture diff",
+ parameters: Type.Object({ path: Type.String() }),
+ execute: async () => ({
+ content: [],
+ details: { diff: "-1 OLD_FILE_CONTENT\n+1 NEW_FILE_CONTENT", firstChangedLine: 1 },
+ }),
+ },
+];
+type ModeControls = {
+ chatContainer: Container;
+ defaultEditor: CustomEditor;
+ ui: TUI;
+ setupKeyHandlers(): void;
+ renderSessionContext(
+ context: ReturnType<SessionManager["buildSessionContext"]>,
+ options?: { clearChat: boolean },
+ ): Promise<void>;
+ handleEvent(event: AgentConnectionSessionEvent): Promise<void>;
+};
+let harness: Harness | undefined;
+const modes: InteractiveMode[] = [];
+afterEach(() => {
+ for (const mode of modes.splice(0)) mode.stop();
+ stopThemeWatcher();
+ harness?.cleanup();
+ harness = undefined;
+ vi.restoreAllMocks();
+});
+function createMode(harness: Harness): ModeControls {
+ initTheme("dark");
+ const connection = {
+ onBeforeSessionInvalidate: () => () => {},
+ getToolDefinition: async () => undefined,
+ } as unknown as AgentConnection;
+ const mode = new InteractiveMode({
+ agentConnection: connection,
+ uiServices: createInteractiveModeUiServices(harness.session),
+ });
+ modes.push(mode);
+ const controls = mode as unknown as ModeControls;
+ vi.spyOn(controls.ui, "requestRender").mockImplementation(() => {});
+ vi.spyOn(controls.ui, "requestRenderPreservingViewport").mockImplementation(() => {});
+ const keybindings = new KeybindingsManager();
+ setKeybindings(keybindings);
+ Object.assign(mode, { keybindings, isInitialized: true });
+ controls.setupKeyHandlers();
+ return controls;
+}
+function render(mode: ModeControls): string {
+ return stripAnsi(mode.chatContainer.render(120).join("\n"));
+}
+function cycle(mode: ModeControls): void {
+ mode.defaultEditor.handleInput("\x0f");
+}
+function assertMode(mode: ModeControls, detail: "overview" | "details" | "all"): void {
+ const text = render(mode);
+ expect(text).toContain("Visible assistant answer");
+ expect(text).toContain("+1 -1");
+ expect(text.includes("PRIVATE_THINKING")).toBe(detail !== "overview");
+ expect(text.includes("NEW_FILE_CONTENT")).toBe(detail !== "overview");
+ expect(text.includes("FULL_TOOL_OUTPUT")).toBe(detail === "all");
+ expect(text.includes("AGENT_MESSAGE_BODY")).toBe(detail === "all");
+ expect(text).toContain("Agent message received");
+}
+describe("conversation detail cycle", () => {
+ test("cycles a reopened saved chat without changing messages or JSONL", async () => {
+ harness = await createHarness({
+ tools,
+ persistSession: true,
+ settings: { theme: "dark", ...{ hideThinkingBlock: false } },
+ });
+ harness.setResponses([
+ fauxAssistantMessage(
+ [
+ fauxThinking("PRIVATE_THINKING"),
+ fauxText("Visible assistant answer"),
+ fauxToolCall("generic", {}, { id: "generic-call" }),
+ fauxToolCall("edit", { path: "example.ts" }, { id: "edit-call" }),
+ ],
+ { stopReason: "toolUse" },
+ ),
+ fauxAssistantMessage("Done."),
+ ]);
+ await harness.session.prompt("Show the fixture");
+ await harness.session.sendCustomMessage(
+ createAgentSessionMessage({
+ id: "detail-agent",
+ source: "agent_message",
+ target: { activeSessionId: "parent", sessionId: "parent" },
+ message: "AGENT_MESSAGE_BODY",
+ from: { activeSessionId: "child", sessionId: "child" },
+ fromRelationship: "child",
+ }),
+ { triggerTurn: false },
+ );
+ const sessionFile = harness.sessionManager.getSessionFile();
+ if (!sessionFile) throw new Error("Expected persisted fixture");
+ const savedTrace = readFileSync(sessionFile, "utf8");
+ const context = SessionManager.open(sessionFile).buildSessionContext();
+ const source = JSON.stringify(context.messages);
+ const mode = createMode(harness);
+ await mode.renderSessionContext(context);
+ assertMode(mode, "overview");
+ cycle(mode);
+ assertMode(mode, "details");
+ cycle(mode);
+ assertMode(mode, "all");
+ mode.defaultEditor.handleInput("\x10");
+ assertMode(mode, "all");
+ await mode.renderSessionContext(context, { clearChat: true });
+ assertMode(mode, "all");
+ cycle(mode);
+ assertMode(mode, "overview");
+ expect(JSON.stringify(context.messages)).toBe(source);
+ expect(readFileSync(sessionFile, "utf8")).toBe(savedTrace);
+ expect(harness.settingsManager.getGlobalSettings()).toMatchObject({ hideThinkingBlock: false });
+ });
+ test("keeps full shell notifications at their arrival position through live and reopened detail cycles", async () => {
+ const code = "h = bash('printf done')\nh";
+ const ipython: AgentTool = {
+ name: "ipython",
+ label: "ipython",
+ description: "Fixture shell launch",
+ parameters: Type.Object({ code: Type.String() }),
+ execute: async () => ({
+ content: [],
+ details: { result: "<BashHandle pid=42 running command='printf done'>", status: "ok" },
+ }),
+ };
+ harness = await createHarness({ tools: [...tools, ipython], persistSession: true });
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("ipython", { code }, { id: "shell-launch" }), { stopReason: "toolUse" }),
+ fauxAssistantMessage(
+ [fauxText("Work before notification."), fauxToolCall("generic", {}, { id: "intervening-tool" })],
+ { stopReason: "toolUse" },
+ ),
+ fauxAssistantMessage("Waiting for notification."),
+ ]);
+ await harness.session.prompt("Run the shell fixture");
+ const notice = createAsyncBashCompletionMessage({ pid: 42, command: "printf done", exitCode: 0 }, 10000);
+ await harness.session.sendCustomMessage(notice, { triggerTurn: false });
+ harness.setResponses([fauxAssistantMessage("Work after notification.")]);
+ await harness.session.prompt("Continue the fixture");
+ const sessionFile = harness.sessionManager.getSessionFile()!;
+ const savedTrace = readFileSync(sessionFile, "utf8");
+ const context = SessionManager.open(sessionFile).buildSessionContext();
+ const source = JSON.stringify(context.messages);
+ const live = createMode(harness);
+ for (const event of harness.events) {
+ if (
+ event.type === "message_start" ||
+ event.type === "message_update" ||
+ event.type === "message_end" ||
+ event.type === "tool_execution_start" ||
+ event.type === "tool_execution_update" ||
+ event.type === "tool_execution_end"
+ )
+ await live.handleEvent(event);
+ }
+ const reopened = createMode(harness);
+ await reopened.renderSessionContext(context);
+ for (const mode of [live, reopened]) {
+ for (const detail of ["overview", "details", "all"] as const) {
+ const text = render(mode);
+ expect(text).toContain("Work before notification.");
+ expect(text).toContain("Work after notification.");
+ if (detail === "all") {
+ expect(text.match(/\[bash-done pid:42 exit:0\]/g)).toHaveLength(1);
+ for (const line of notice.content.split("\n").filter(Boolean)) expect(text).toContain(line);
+ const launch = text.indexOf("h = bash");
+ const work = text.indexOf("Work before notification.");
+ const output = text.indexOf("FULL_TOOL_OUTPUT");
+ const waiting = text.indexOf("Waiting for notification.");
+ const notification = text.indexOf("[bash-done pid:42 exit:0]");
+ const after = text.indexOf("Work after notification.");
+ expect(launch).toBeGreaterThanOrEqual(0);
+ expect(work).toBeGreaterThan(launch);
+ expect(output).toBeGreaterThan(work);
+ expect(waiting).toBeGreaterThan(output);
+ expect(notification).toBeGreaterThan(waiting);
+ expect(after).toBeGreaterThan(notification);
+ } else {
+ expect(text).not.toContain("[bash-done pid:42 exit:0]");
+ expect(text).not.toContain("Background shell command");
+ }
+ cycle(mode);
+ }
+ expect(render(mode)).not.toContain("[bash-done pid:42 exit:0]");
+ cycle(mode);
+ cycle(mode);
+ expect(render(mode).match(/\[bash-done pid:42 exit:0\]/g)).toHaveLength(1);
+ }
+ expect(JSON.stringify(context.messages)).toBe(source);
+ expect(readFileSync(sessionFile, "utf8")).toBe(savedTrace);
+ });
+
+ test("applies the chosen mode to streamed thinking, tool results, and future turns", async () => {
+ harness = await createHarness({ tools });
+ harness.setResponses([
+ fauxAssistantMessage(
+ [
+ fauxThinking("STREAM_THINKING"),
+ fauxText("Streaming answer"),
+ fauxToolCall("generic", {}, { id: "stream-tool" }),
+ ],
+ { stopReason: "toolUse" },
+ ),
+ fauxAssistantMessage([fauxThinking("NEXT_TURN_THINKING"), fauxText("Next answer")]),
+ ]);
+ await harness.session.prompt("Stream the fixture");
+ const mode = createMode(harness);
+ cycle(mode);
+ for (const event of harness.events) {
+ if (
+ event.type === "message_start" ||
+ event.type === "message_update" ||
+ event.type === "message_end" ||
+ event.type === "tool_execution_start" ||
+ event.type === "tool_execution_update" ||
+ event.type === "tool_execution_end"
+ )
+ await mode.handleEvent(event);
+ }
+ expect(render(mode)).toContain("STREAM_THINKING");
+ expect(render(mode)).toContain("NEXT_TURN_THINKING");
+ expect(render(mode)).toContain("Next answer");
+ expect(render(mode)).not.toContain("FULL_TOOL_OUTPUT");
+ cycle(mode);
+ expect(render(mode)).toContain("FULL_TOOL_OUTPUT");
+ cycle(mode);
+ expect(render(mode)).not.toContain("STREAM_THINKING");
+ expect(render(mode)).not.toContain("NEXT_TURN_THINKING");
+ expect(render(mode)).toContain("Streaming answer");
+ await mode.handleEvent({
+ type: "message_start",
+ message: fauxAssistantMessage([fauxThinking("LATER_THINKING"), fauxText("Later answer")]),
+ });
+ expect(render(mode)).not.toContain("LATER_THINKING");
+ cycle(mode);
+ expect(render(mode)).toContain("LATER_THINKING");
+ });
+ test("keeps live agent notices visible while only all output reveals bodies", async () => {
+ harness = await createHarness();
+ const mode = createMode(harness);
+ const message = createAgentSessionMessage({
+ id: "live-agent",
+ source: "agent_message",
+ message: "LIVE_AGENT_BODY",
+ from: { activeSessionId: "child", sessionId: "child" },
+ target: { activeSessionId: "parent", sessionId: "parent" },
+ fromRelationship: "child",
+ });
+ await mode.handleEvent({ type: "message_start", message });
+ expect(render(mode)).not.toContain("LIVE_AGENT_BODY");
+ expect(render(mode)).toContain("Agent message received");
+ cycle(mode);
+ expect(render(mode)).toContain("Agent message received");
+ cycle(mode);
+ expect(render(mode)).toContain("LIVE_AGENT_BODY");
+ await mode.handleEvent({
+ type: "message_start",
+ message: { ...message, details: { ...message.details, id: "later-agent", message: "LATER_AGENT_BODY" } },
+ });
+ expect(render(mode)).toContain("LATER_AGENT_BODY");
+ mode.defaultEditor.handleInput("\x10");
+ expect(render(mode)).toContain("LATER_AGENT_BODY");
+ cycle(mode);
+ expect(render(mode)).toContain("Agent message received");
+ expect(render(mode)).not.toContain("LIVE_AGENT_BODY");
+ expect(render(mode)).not.toContain("LATER_AGENT_BODY");
+ });
+
+ test("cycles finished side-pane and pending main-chat bash output", async () => {
+ harness = await createHarness();
+ const mode = createMode(harness);
+ const side = new SideQuestionComponent({
+ id: "side",
+ question: "Question",
+ answer: "Answer",
+ status: "complete",
+ });
+ const makeBash = () => {
+ const bash = new BashExecutionComponent("fixture", mode.ui);
+ bash.appendOutput(["HIDDEN_BASH_HEAD", ...Array.from({ length: 25 }, (_, i) => `line ${i}`)].join("\n"));
+ bash.setComplete(0, false);
+ return bash;
+ };
+ const sideBash = makeBash();
+ const pendingBash = makeBash();
+ side.addBash(sideBash);
+ side.finishBash();
+ Object.assign(mode, { sideQuestionComponent: side, pendingBashComponents: [pendingBash] });
+ const bashText = () => stripAnsi([...side.render(120), ...pendingBash.render(120)].join("\n"));
+ expect(bashText()).not.toContain("HIDDEN_BASH_HEAD");
+ cycle(mode);
+ expect(bashText()).not.toContain("HIDDEN_BASH_HEAD");
+ cycle(mode);
+ expect(bashText().match(/HIDDEN_BASH_HEAD/g)).toHaveLength(2);
+ cycle(mode);
+ expect(bashText()).not.toContain("HIDDEN_BASH_HEAD");
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/2193-rendering-review.test.ts b/packages/coding-agent/test/suite/regressions/2193-rendering-review.test.ts
new file mode 100644
index 0000000000..e2e6ba8c3a
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2193-rendering-review.test.ts
@@ -0,0 +1,152 @@
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { fauxAssistantMessage } from "@earendil-works/pi-ai";
+import stripAnsi from "strip-ansi";
+import { afterEach, describe, expect, test } from "vitest";
+import { previewPythonCode, pythonStatementLines } from "../../../src/core/tools/code-preview.js";
+import { AssistantMessageComponent } from "../../../src/modes/interactive/components/assistant-message.js";
+import { IPythonCellComponent } from "../../../src/modes/interactive/components/ipython-cell.js";
+import {
+ readAssignedShellCommand,
+ readBackgroundShellHandle,
+} from "../../../src/modes/interactive/components/shell-completion.js";
+import {
+ initTheme,
+ loadThemeFromPath,
+ preloadCodeHighlighter,
+ preloadThemeValidator,
+ setThemeInstance,
+ theme,
+} from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+let harness: Harness | undefined;
+afterEach(() => {
+ harness?.cleanup();
+ harness = undefined;
+});
+
+describe("conversation rendering review regressions", () => {
+ test.each([
+ ['print("""text\n""")', 'print("""text'],
+ ['print(["""text\n"""])', 'print(["""text'],
+ ['print(("""text\n"""));', 'print(("""text'],
+ ['print("""text\n""") # finished', 'print("""text'],
+ ])("ignores punctuation-only string closer suffixes in previews (%s)", (code, expected) => {
+ expect(previewPythonCode(code)).toEqual({ language: "python", text: expected });
+ expect(previewPythonCode(`${code}\npublish()`)).toEqual({ language: "python", text: "publish()" });
+ });
+
+ test.each(['"""', "'''", 'r"""', 'f"""'])(
+ "preserves statements after a multiline string closes (%s)",
+ async (opener) => {
+ initTheme("dark");
+ await preloadCodeHighlighter();
+ const closer = opener.slice(-3);
+ const code = `body = ${opener}draft\n!not_a_command\n${closer}; publish(body)\n!echo done`;
+ const statements = pythonStatementLines(code);
+ expect(statements).toHaveLength(4);
+ expect(statements[1]).toBe("");
+ expect(statements[2]?.trim()).toBe("; publish(body)");
+ expect(statements[3]).toBe("!echo done");
+ expect(previewPythonCode(code)).toEqual({ language: "python", text: "publish(body)" });
+ expect(previewPythonCode(`body = ${opener}draft\n${closer}; bash('git status')`)).toEqual({
+ language: "bash",
+ text: "git status",
+ });
+ expect(pythonStatementLines(`body = ${opener}draft\nnot closed`)[1]).toBe("");
+ const rows = new IPythonCellComponent({
+ code,
+ expanded: true,
+ argsComplete: true,
+ details: { status: "ok" },
+ }).render(120);
+ const stringRow = rows.find((row) => stripAnsi(row).includes("!not_a_command"))!;
+ const commandRow = rows.find((row) => stripAnsi(row).trim() === "!echo done")!;
+ expect(stringRow).toContain(theme.getFgAnsi("syntaxString"));
+ expect(commandRow).toContain(theme.getFgAnsi("bashMode"));
+ expect(rows.some((row) => stripAnsi(row).includes(`${closer}; publish(body)`))).toBe(true);
+ },
+ );
+
+ test("loads custom themes without mdBody before and after validator initialization", async () => {
+ harness = await createHarness();
+ const custom = JSON.parse(
+ readFileSync(new URL("../../../src/modes/interactive/theme/dark.json", import.meta.url), "utf8"),
+ ) as { name: string; colors: Record<string, string | number> };
+ custom.name = "optional-body";
+ custom.colors.text = "#123456";
+ delete custom.colors.mdBody;
+ const path = join(harness.tempDir, "optional-body.json");
+ const source = JSON.stringify(custom);
+ writeFileSync(path, source);
+ for (const validate of [false, true]) {
+ if (validate) await preloadThemeValidator();
+ setThemeInstance(loadThemeFromPath(path));
+ expect(theme.fg("mdBody", "Body")).toBe(theme.fg("text", "Body"));
+ const rendered = new AssistantMessageComponent(fauxAssistantMessage("Body")).render(80).join("\n");
+ expect(stripAnsi(rendered)).toContain("Body");
+ expect(rendered).toContain(theme.getFgAnsi("text"));
+ }
+ expect(readFileSync(path, "utf8")).toBe(source);
+ custom.colors.mdBody = "#abcdef";
+ writeFileSync(path, JSON.stringify(custom));
+ const explicit = loadThemeFromPath(path);
+ expect(explicit.fg("mdBody", "Body")).not.toBe(explicit.fg("text", "Body"));
+ });
+
+ test("renders large sent agent messages without exceeding the JavaScript argument limit", () => {
+ initTheme("dark");
+ const message = `${"x\n".repeat(140000)}final message line`;
+ const state = {
+ code: "await agent_message.send('child', message)",
+ executionStarted: true,
+ details: {
+ status: "ok",
+ sentAgentMessages: [
+ {
+ id: "huge",
+ message,
+ deliveryStatus: "delivered",
+ receiverRole: "child",
+ target: { activeSessionId: "child", sessionId: "child" },
+ },
+ ],
+ },
+ };
+ const cell = new IPythonCellComponent(state);
+ expect(cell.render(80)).toHaveLength(2);
+ cell.update({ ...state, expanded: true });
+ const rows = cell.render(80);
+ expect(rows.filter((row) => stripAnsi(row).trim() === "x")).toHaveLength(139999);
+ expect(rows.some((row) => stripAnsi(row).includes("final message line"))).toBe(true);
+ cell.update(state);
+ expect(cell.render(80)).toHaveLength(2);
+ });
+
+ test("matches literal launches across blank import lines and rejects malformed or additional code", () => {
+ const details = { status: "ok", result: "<BashHandle pid=42 running command='printf done'>" };
+ for (const prefix of ["from rlm import bash\n\n", "import rlm\n \n", ""]) {
+ expect(readBackgroundShellHandle(`${prefix}job = bash('printf done')\n\njob`, details)).toEqual({
+ pid: 42,
+ command: "printf done",
+ exitCode: undefined,
+ });
+ expect(readAssignedShellCommand(`${prefix}job = bash('printf done')\n\n`, { status: "ok" })).toBe(
+ "printf done",
+ );
+ }
+ for (const code of [
+ "bash('printf done'); other()",
+ "bash('printf done')\nother()",
+ "bash('printf done' + extra)",
+ "bash('printf done', other)",
+ `bash(${"\t".repeat(100000)}x`,
+ `bash(${"\t".repeat(100000)}x)`,
+ "job = bash('printf done')\nother",
+ ]) {
+ expect(readBackgroundShellHandle(code, details)).toBeUndefined();
+ expect(readAssignedShellCommand(code, { status: "ok" })).toBeUndefined();
+ }
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/2193-shell-completion-presentation.test.ts b/packages/coding-agent/test/suite/regressions/2193-shell-completion-presentation.test.ts
new file mode 100644
index 0000000000..cafee095a9
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2193-shell-completion-presentation.test.ts
@@ -0,0 +1,346 @@
+import { readFileSync } from "node:fs";
+import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
+import { type Component, Container, type TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { Type } from "typebox";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { type CustomMessage, createAsyncBashCompletionMessage } from "../../../src/core/messages.js";
+import {
+ buildConversationComponents,
+ createShellCompletionComponent,
+} from "../../../src/modes/interactive/components/conversation-components.js";
+import {
+ readBackgroundShellHandle,
+ ShellCompletionComponent,
+} from "../../../src/modes/interactive/components/shell-completion.js";
+import { ToolExecutionComponent } from "../../../src/modes/interactive/components/tool-execution.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+const ui = { requestRender: vi.fn() } as unknown as TUI;
+const code = "job = bash('printf done')\njob";
+const result = {
+ content: [{ type: "text" as const, text: "<BashHandle pid=42 running command='printf done'>" }],
+ details: {
+ result: "<BashHandle pid=42 running command='printf done'>",
+ stdout: "launch output",
+ status: "ok",
+ durationMs: 3,
+ },
+ isError: false,
+};
+const completion = (exitCode = 0, pid = 42, command = "printf done") =>
+ createAsyncBashCompletionMessage({ pid, command, exitCode }, 10000);
+const render = (components: readonly Component[]) =>
+ components
+ .flatMap((component) => component.render(240))
+ .map(stripAnsi)
+ .join("\n");
+const tool = (id = "launch", source = code) =>
+ new ToolExecutionComponent("ipython", id, { code: source }, {}, undefined, ui, "/tmp");
+const options = { ui, cwd: "/tmp", toolOptions: {}, getToolDefinition: () => undefined };
+interface ModePresentation {
+ createDisplayedCustomMessageComponent(message: CustomMessage): Component;
+}
+function liveCompletion(message: CustomMessage, tools: Component[]): Component {
+ const chatContainer = new Container();
+ for (const entry of tools) chatContainer.addChild(entry);
+ const mode = Object.assign(Object.create(InteractiveMode.prototype), { chatContainer });
+ return (mode as ModePresentation).createDisplayedCustomMessageComponent(message);
+}
+function expand(components: readonly Component[]) {
+ for (const component of components)
+ if ("setExpanded" in component && typeof component.setExpanded === "function") component.setExpanded(true);
+}
+
+describe("#2193 shell completion presentation", () => {
+ let harness: Harness | undefined;
+ beforeAll(() => initTheme("dark"));
+ afterEach(() => {
+ harness?.cleanup();
+ harness = undefined;
+ });
+ it.each([0, 7])("matches live and replay rendering for exit %i without changing the trace", async (exitCode) => {
+ const ipython: AgentTool = {
+ name: "ipython",
+ label: "ipython",
+ description: "test shell",
+ parameters: Type.Object({ code: Type.String() }),
+ execute: async () => result,
+ };
+ harness = await createHarness({ tools: [ipython], persistSession: true });
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("ipython", { code }, { id: "launch" }), { stopReason: "toolUse" }),
+ fauxAssistantMessage("Other work."),
+ ]);
+ await harness.session.prompt("Run in background");
+ const notice = completion(exitCode);
+ await harness.session.sendCustomMessage(notice, { triggerTurn: false });
+ const messages = harness.session.messages;
+ const serialized = JSON.stringify(messages);
+ const sessionFile = harness.sessionManager.getSessionFile()!;
+ const trace = readFileSync(sessionFile, "utf8");
+ const replay = buildConversationComponents(messages, options).filter(
+ (entry) => entry instanceof ToolExecutionComponent || entry instanceof ShellCompletionComponent,
+ );
+ const launch = tool();
+ launch.markExecutionStarted();
+ launch.updateResult(result);
+ expect(launch.hasRunningBackgroundShell()).toBe(true);
+ expect(render([launch])).not.toContain("✓");
+ const storedNotice = messages.find(
+ (message): message is CustomMessage => message.role === "custom" && message.customType === notice.customType,
+ )!;
+ const live = [launch, liveCompletion(storedNotice, [launch])];
+ expect(launch.hasRunningBackgroundShell()).toBe(false);
+ expect(render(live)).toBe(render(replay));
+ expect(render(live)).toContain(exitCode === 0 ? "✓" : "✗");
+ expect(render(live)).toContain("cell 3ms");
+ expect(render(live)).not.toMatch(/Shell message received|Background shell command|pid 42|exit 0|cycle detail/);
+ if (exitCode !== 0) expect(render(live)).toContain("exit 7");
+ expand(live);
+ expand(replay);
+ expect(render(live)).toBe(render(replay));
+ for (const line of notice.content.split("\n").filter(Boolean)) expect(render([live[1]!])).toContain(line);
+ expect(render([launch])).toContain("launch output");
+ expect(render([launch])).not.toContain("[bash-done ");
+ expect(render([live[1]!])).toContain("pid 42");
+ expect(JSON.stringify(messages)).toBe(serialized);
+ expect(readFileSync(sessionFile, "utf8")).toBe(trace);
+ });
+ it("converges when completion is delivered before the final tool result", () => {
+ const launch = tool();
+ launch.markExecutionStarted();
+ const notice = completion();
+ const event = liveCompletion(notice, [launch]);
+ expect(render([event])).toContain("Background shell command finished");
+ launch.updateResult(result, true);
+ expect(render([event])).toContain("Background shell command finished");
+ launch.updateResult(result);
+ expect(render([event])).toBe("");
+ expect(render([launch])).toContain("✓");
+ const messages: AgentMessage[] = [
+ fauxAssistantMessage(fauxToolCall("ipython", { code }, { id: "launch" }), { stopReason: "toolUse" }),
+ notice,
+ { role: "toolResult", toolCallId: "launch", toolName: "ipython", ...result, timestamp: 10001 },
+ ];
+ const replay = buildConversationComponents(messages, options).filter(
+ (entry) => entry instanceof ToolExecutionComponent || entry instanceof ShellCompletionComponent,
+ );
+ expand([launch, event]);
+ expand(replay);
+ expect(render([launch, event])).toBe(render(replay));
+ });
+ it.each([0, 8])("retains unmatched exit %i as one compact line and raw full output", (exitCode) => {
+ const notice = completion(exitCode, 99);
+ const launch = tool();
+ launch.updateResult(result);
+ const event = createShellCompletionComponent(notice, [launch])!;
+ expect(event.render(100)).toHaveLength(1);
+ expect(render([event])).toBe(
+ exitCode === 0 ? " ✓ Background shell command finished" : " ✗ Background shell command failed · exit 8",
+ );
+ expand([event]);
+ for (const line of notice.content.split("\n").filter(Boolean)) expect(render([event])).toContain(line);
+ expect(launch.hasRunningBackgroundShell()).toBe(true);
+ });
+ it("keeps duplicate candidates and reused PIDs unmatched", () => {
+ const first = tool("first");
+ first.updateResult(result);
+ const second = tool("second");
+ second.updateResult(result);
+ expect(render([createShellCompletionComponent(completion(), [first, second])!])).toContain(
+ "Background shell command finished",
+ );
+ expect(render([createShellCompletionComponent(completion(0, 42, "different command"), [first])!])).toContain(
+ "Background shell command finished",
+ );
+ });
+ it("stops ambiguous duplicate handles from pulsing without assigning their result or stopping unrelated shells", () => {
+ const first = tool("first");
+ first.updateResult(result);
+ const second = tool("second");
+ second.updateResult(result);
+ const unrelated = tool("unrelated");
+ unrelated.updateResult({
+ ...result,
+ details: { ...result.details, result: result.details.result.replace("pid=42", "pid=43") },
+ });
+ const notice = completion(7);
+ const event = createShellCompletionComponent(notice, [first, second, unrelated])!;
+ for (const candidate of [first, second]) {
+ expect(candidate.hasRunningBackgroundShell()).toBe(false);
+ expect(render([candidate])).toContain("completion unmatched");
+ expect(render([candidate])).not.toContain("exit 7");
+ }
+ expect(unrelated.hasRunningBackgroundShell()).toBe(true);
+ expect(render([event])).toContain("Background shell command failed · exit 7");
+ const messages: AgentMessage[] = [
+ fauxAssistantMessage(
+ [fauxToolCall("ipython", { code }, { id: "first" }), fauxToolCall("ipython", { code }, { id: "second" })],
+ { stopReason: "toolUse" },
+ ),
+ { role: "toolResult", toolCallId: "first", toolName: "ipython", ...result, timestamp: 1 },
+ { role: "toolResult", toolCallId: "second", toolName: "ipython", ...result, timestamp: 2 },
+ notice,
+ ];
+ const serialized = JSON.stringify(messages);
+ const replay = buildConversationComponents(messages, options);
+ for (const expanded of [true, false]) {
+ for (const component of [...replay, first, second, event])
+ if ("setExpanded" in component && typeof component.setExpanded === "function")
+ component.setExpanded(expanded);
+ expect(render(replay).match(/completion unmatched/g)).toHaveLength(2);
+ expect(render(replay).match(/\[bash-done /g)?.length ?? 0).toBe(expanded ? 1 : 0);
+ }
+ expect(JSON.stringify(messages)).toBe(serialized);
+ });
+ it.each([0, 9])("matches unique assignment-only launches by their full command for exit %i", (exitCode) => {
+ const source = "h = bash('printf done')";
+ const assignedResult = {
+ ...result,
+ details: { status: "ok", durationMs: 13 },
+ content: [{ type: "text" as const, text: "" }],
+ };
+ const launch = tool("assigned", source);
+ launch.markExecutionStarted();
+ launch.setArgsComplete();
+ const event = liveCompletion(completion(exitCode), [launch]);
+ launch.updateResult(assignedResult);
+ expect(render([event])).toBe("");
+ expect(render([launch])).toContain(exitCode ? "✗" : "✓");
+ expect(render([launch])).toContain("cell 13ms");
+ if (exitCode) expect(render([launch])).toContain("exit 9");
+ const messages: AgentMessage[] = [
+ fauxAssistantMessage(fauxToolCall("ipython", { code: source }, { id: "assigned" }), { stopReason: "toolUse" }),
+ { role: "toolResult", toolCallId: "assigned", toolName: "ipython", ...assignedResult, timestamp: 1 },
+ fauxAssistantMessage(fauxToolCall("ipython", { code: "await h" }, { id: "await" }), { stopReason: "toolUse" }),
+ {
+ role: "toolResult",
+ toolCallId: "await",
+ toolName: "ipython",
+ content: [{ type: "text", text: "BashResult" }],
+ details: { status: "ok", result: `BashResult(exit_code=${exitCode}, output='done', duration=0.1)` },
+ isError: false,
+ timestamp: 2,
+ },
+ completion(exitCode),
+ ];
+ const serialized = JSON.stringify(messages);
+ const replay = buildConversationComponents(messages, options);
+ expect(render(replay)).not.toContain("Background shell command");
+ expect(render([replay[1]!])).toBe(render([launch]));
+ expand(replay);
+ expand([launch, event]);
+ expect(render([replay[1]!])).toBe(render([launch]));
+ expect(render([launch])).not.toContain("[bash-done ");
+ expect(render([event])).toContain("[bash-done ");
+ expect(JSON.stringify(messages)).toBe(serialized);
+ });
+ it("keeps ambiguous, failed, complex, or mismatched assignment launches standalone", () => {
+ const assigned = (id: string, source = "h = bash('printf done')", isError = false) => {
+ const entry = tool(id, source);
+ entry.updateResult({ content: [], details: { status: isError ? "error" : "ok" }, isError });
+ return entry;
+ };
+ const knownOtherPid = tool("known");
+ knownOtherPid.updateResult({
+ ...result,
+ details: { ...result.details, result: result.details.result.replace("pid=42", "pid=41") },
+ });
+ for (const previous of [
+ [assigned("a"), assigned("b")],
+ [assigned("a"), knownOtherPid],
+ [assigned("a", "h = bash('printf done')", true)],
+ [assigned("a", "h = bash('printf done')\nother_work()")],
+ [assigned("a", "h = bash(prefix + 'printf done')")],
+ [assigned("a", "h = bash('printf done suffix')")],
+ [assigned("a", "await h")],
+ ])
+ expect(render([createShellCompletionComponent(completion(), previous)!])).toContain(
+ "Background shell command finished",
+ );
+ });
+ it.each([true, false])(
+ "keeps following tool rows adjacent to attached=%s completions during live rendering and replay",
+ (matched) => {
+ const launch = tool();
+ launch.updateResult(result);
+ const notice = completion(0, matched ? 42 : 99);
+ const event = liveCompletion(notice, [launch]);
+ const next = fauxAssistantMessage(fauxToolCall("ipython", { code: "await h" }, { id: "next" }), {
+ stopReason: "toolUse",
+ });
+ const chatContainer = new Container();
+ chatContainer.addChild(launch);
+ chatContainer.addChild(event);
+ const mode = Object.assign(Object.create(InteractiveMode.prototype), {
+ chatContainer,
+ hideThinkingBlock: true,
+ toolOutputExpanded: false,
+ getMarkdownThemeWithSettings: () => undefined,
+ getCurrentCwd: () => "/tmp",
+ });
+ Reflect.get(InteractiveMode.prototype, "startAssistantStreamingMessage").call(mode, next);
+ expect(chatContainer.children[2]!.render(120)).toEqual([]);
+ const replay = buildConversationComponents(
+ [
+ fauxAssistantMessage(fauxToolCall("ipython", { code }, { id: "launch" }), { stopReason: "toolUse" }),
+ { role: "toolResult", toolName: "ipython", toolCallId: "launch", ...result, timestamp: 1 },
+ notice,
+ next,
+ ],
+ options,
+ );
+ expect(replay[3]!.render(120)).toEqual([]);
+ },
+ );
+
+ it("never overwrites an earlier raw notification with a duplicate", () => {
+ const launch = tool();
+ launch.updateResult(result);
+ const first = createShellCompletionComponent(completion(), [launch])!;
+ const secondNotice = { ...completion(), content: "second raw completion" };
+ const second = createShellCompletionComponent(secondNotice, [launch, first])!;
+ expand([launch, first, second]);
+ expect(render([launch])).not.toContain("[bash-done ");
+ expect(render([first])).toContain("[bash-done ");
+ expect(render([second])).toContain("second raw completion");
+ });
+ it("matches escaped literal commands exactly and recognizes already finished handles", () => {
+ for (const command of ["printf 'a'", 'printf "b"', "printf first\nprintf second", "printf C:\\temp"]) {
+ const literal = JSON.stringify(command);
+ expect(
+ readBackgroundShellHandle(`bash(${literal})`, {
+ result: `<BashHandle pid=42 exit_code=-9 command=${literal}>`,
+ }),
+ ).toEqual({ pid: 42, command, exitCode: -9 });
+ }
+ expect(readBackgroundShellHandle("bash('other')", result.details)).toBeUndefined();
+ expect(readBackgroundShellHandle("job", result.details)).toBeUndefined();
+ expect(readBackgroundShellHandle(code, { result: "42" })).toBeUndefined();
+ expect(readBackgroundShellHandle("bash('printf done' + suffix)", result.details)).toBeUndefined();
+ const launch = tool();
+ launch.updateResult({
+ ...result,
+ details: { ...result.details, result: result.details.result.replace("running", "exit_code=0") },
+ });
+ expect(render([launch])).toContain("✓");
+ expect(launch.hasRunningBackgroundShell()).toBe(false);
+ });
+ it("renders malformed legacy metadata without crashing or dropping raw content", () => {
+ const notice = { ...completion(), timestamp: Number.NaN };
+ const launch = tool();
+ launch.updateResult(result);
+ const event = createShellCompletionComponent(notice, [launch])!;
+ expand([launch, event]);
+ expect(render([launch, event])).toContain("unknown time");
+ expect(render([launch])).not.toContain("[bash-done ");
+ expect(render([event])).toContain("[bash-done ");
+ const malformed = createShellCompletionComponent({ ...notice, details: { pid: "42" } }, [])!;
+ expand([malformed]);
+ expect(render([malformed])).toContain("[bash-done ");
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/2193-visible-message-spacing.test.ts b/packages/coding-agent/test/suite/regressions/2193-visible-message-spacing.test.ts
new file mode 100644
index 0000000000..34d3c2c6db
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2193-visible-message-spacing.test.ts
@@ -0,0 +1,289 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import {
+ fauxAssistantMessage,
+ fauxText,
+ fauxThinking,
+ fauxToolCall,
+ type ToolResultMessage,
+} from "@earendil-works/pi-ai";
+import { type Component, type Container, setKeybindings, type TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { createAgentSessionMessage } from "../../../src/core/agent-messages.js";
+import { KeybindingsManager } from "../../../src/core/keybindings.js";
+import { createAsyncBashCompletionMessage, createRefinementOutcomeMessage } from "../../../src/core/messages.js";
+import type {
+ AgentConnection,
+ AgentConnectionSessionContext,
+ AgentConnectionSessionEvent,
+} from "../../../src/modes/agent-connection/index.js";
+import { AssistantMessageComponent } from "../../../src/modes/interactive/components/assistant-message.js";
+import {
+ buildConversationComponents,
+ createConversationSpacing,
+} from "../../../src/modes/interactive/components/conversation-components.js";
+import type { CustomEditor } from "../../../src/modes/interactive/components/custom-editor.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { createInteractiveModeUiServices } from "../../../src/modes/interactive/interactive-mode-services.js";
+import { initTheme, stopThemeWatcher } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+type ModeControls = {
+ chatContainer: Container;
+ defaultEditor: CustomEditor;
+ ui: TUI;
+ setupKeyHandlers(): void;
+ renderSessionContext(context: AgentConnectionSessionContext): Promise<void>;
+ handleEvent(event: AgentConnectionSessionEvent): Promise<void>;
+};
+let harness: Harness | undefined;
+const modes: InteractiveMode[] = [];
+afterEach(() => {
+ for (const mode of modes.splice(0)) mode.stop();
+ stopThemeWatcher();
+ harness?.cleanup();
+ harness = undefined;
+ vi.restoreAllMocks();
+});
+function createMode(harness: Harness): ModeControls {
+ initTheme("dark");
+ const connection = {
+ onBeforeSessionInvalidate: () => () => {},
+ getToolDefinition: async () => undefined,
+ } as unknown as AgentConnection;
+ const mode = new InteractiveMode({
+ agentConnection: connection,
+ uiServices: createInteractiveModeUiServices(harness.session),
+ });
+ modes.push(mode);
+ const controls = mode as unknown as ModeControls;
+ vi.spyOn(controls.ui, "requestRender").mockImplementation(() => {});
+ vi.spyOn(controls.ui, "requestRenderPreservingViewport").mockImplementation(() => {});
+ const keybindings = new KeybindingsManager();
+ setKeybindings(keybindings);
+ Object.assign(mode, { keybindings, isInitialized: true });
+ controls.setupKeyHandlers();
+ return controls;
+}
+function notice(id: string) {
+ return createAgentSessionMessage({
+ id,
+ source: "agent_message",
+ message: `Body ${id}`,
+ from: { activeSessionId: id, sessionId: id, sessionName: id },
+ fromRelationship: "child",
+ target: { activeSessionId: "parent", sessionId: "parent" },
+ });
+}
+function call(id: string) {
+ return fauxToolCall("ipython", { code: `print('${id}')` }, { id });
+}
+function result(id: string): ToolResultMessage {
+ return {
+ role: "toolResult",
+ toolCallId: id,
+ toolName: "ipython",
+ content: [],
+ isError: false,
+ details: { status: "ok", stdout: `output ${id}` },
+ timestamp: 1,
+ };
+}
+function rows(components: readonly Component[]) {
+ return components.flatMap((component) => component.render(120)).map((line) => stripAnsi(line).trimEnd());
+}
+function precedingGap(lines: string[], match: string) {
+ const index = lines.findIndex((line) => line.includes(match));
+ expect(index, `Missing ${match}`).toBeGreaterThanOrEqual(0);
+ let gap = 0;
+ for (let i = index - 1; i >= 0 && lines[i]?.trim() === ""; i--) gap++;
+ return gap;
+}
+function fixtures(): AgentMessage[] {
+ return [
+ notice("start"),
+ fauxAssistantMessage(call("one"), { stopReason: "toolUse" }),
+ result("one"),
+ fauxAssistantMessage([fauxText("")]),
+ notice("after-empty"),
+ fauxAssistantMessage([fauxThinking("Hidden reasoning"), fauxText("")]),
+ notice("after-thinking"),
+ fauxAssistantMessage([call("two"), call("three")], { stopReason: "toolUse" }),
+ result("two"),
+ result("three"),
+ notice("after-tools"),
+ createAsyncBashCompletionMessage({ pid: 99, command: "unmatched fixture", exitCode: 0 }, 10000),
+ fauxAssistantMessage("Visible prose"),
+ notice("after-prose"),
+ ];
+}
+async function deliver(mode: ModeControls, messages: AgentMessage[]) {
+ for (const message of messages) {
+ if (message.role === "toolResult") {
+ await mode.handleEvent({
+ type: "tool_execution_end",
+ toolCallId: message.toolCallId,
+ toolName: message.toolName,
+ result: { content: message.content, details: message.details },
+ isError: message.isError,
+ });
+ continue;
+ }
+ await mode.handleEvent({ type: "message_start", message });
+ if (message.role === "assistant")
+ for (const block of message.content) {
+ if (block.type === "toolCall")
+ await mode.handleEvent({
+ type: "tool_execution_start",
+ toolCallId: block.id,
+ toolName: block.name,
+ args: block.arguments,
+ });
+ }
+ await mode.handleEvent({ type: "message_end", message });
+ }
+}
+function assertSpacing(lines: string[], detail: number) {
+ expect(precedingGap(lines, "from child after-empty")).toBe(detail === 2 ? 1 : 0);
+ expect(precedingGap(lines, "from child after-thinking")).toBe(detail === 0 ? 0 : 1);
+ expect(precedingGap(lines, "from child after-tools")).toBe(detail === 2 ? 1 : 0);
+ expect(precedingGap(lines, "from child after-prose")).toBe(1);
+ const two = lines.findIndex((line) => line.includes("python") && line.includes("print('two')"));
+ const three = lines.findIndex((line) => line.includes("python") && line.includes("print('three')"));
+ expect(two).toBeGreaterThan(0);
+ expect(three).toBeGreaterThan(two);
+ expect(lines[two - 1]?.trim() === "").toBe(detail === 2);
+ expect(lines[three - 1]?.trim() === "").toBe(detail === 2);
+ if (detail === 2) {
+ expect(lines[two + 1]).toContain("╰─");
+ expect(lines[three + 1]).toContain("╰─");
+ }
+ expect(precedingGap(lines, "Background shell command finished")).toBe(detail === 2 ? 1 : 0);
+ expect(lines.some((line) => line.includes("Hidden reasoning"))).toBe(detail !== 0);
+}
+describe("visible conversation spacing", () => {
+ test("keeps compact rows adjacent across hidden wrappers in live and reopened chats, then spaces expanded blocks", async () => {
+ harness = await createHarness();
+ const messages = fixtures();
+ const source = JSON.stringify(messages);
+ const context = {
+ messages,
+ thinkingLevel: "off",
+ serviceTier: "default",
+ model: null,
+ } satisfies AgentConnectionSessionContext;
+ const live = createMode(harness);
+ await deliver(live, messages);
+ const reopened = createMode(harness);
+ await reopened.renderSessionContext(context);
+ for (const mode of [live, reopened])
+ for (const detail of [0, 1, 2, 0]) {
+ assertSpacing(rows(mode.chatContainer.children), detail);
+ mode.defaultEditor.handleInput("\x0f");
+ }
+ expect(JSON.stringify(messages)).toBe(source);
+ });
+ test("uses the same mode-aware spacing in side-pane conversation builders", async () => {
+ harness = await createHarness();
+ const mode = createMode(harness);
+ const components = buildConversationComponents(fixtures(), {
+ ui: mode.ui,
+ cwd: harness.tempDir,
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ hideThinkingBlock: true,
+ });
+ for (const detail of [0, 1, 2, 0]) {
+ for (const component of components) {
+ if (component instanceof AssistantMessageComponent) component.setHideThinkingBlock(detail === 0);
+ if ("setExpanded" in component && typeof component.setExpanded === "function")
+ component.setExpanded(detail === 2);
+ }
+ assertSpacing(rows(components), detail);
+ }
+ });
+ test("separates shell notices from the previous visible event in live, replay and all detail modes", async () => {
+ harness = await createHarness();
+ const refinement = createRefinementOutcomeMessage({
+ id: "spacing-refinement",
+ summary: "Remember the verified shell behavior.",
+ rationale: "Keep the result.",
+ expectedOutcome: "Retain verified knowledge.",
+ appliedEdits: [{ action: "create", kind: "memory", id: "verified-shell", applied: true }],
+ harnessStatePath: "/tmp/harness.json",
+ scope: "local",
+ });
+ const messages: AgentMessage[] = [
+ refinement,
+ fauxAssistantMessage([fauxText("")]),
+ createAsyncBashCompletionMessage({ pid: 91, command: "unmatched", exitCode: 0 }, 10000),
+ fauxAssistantMessage([fauxThinking("Reasoning after completion"), fauxText("")]),
+ createAsyncBashCompletionMessage({ pid: 92, command: "another unmatched", exitCode: 0 }, 20000),
+ ];
+ const source = JSON.stringify(messages);
+ const live = createMode(harness);
+ await deliver(live, messages);
+ const reopened = createMode(harness);
+ await reopened.renderSessionContext({ messages, thinkingLevel: "off", serviceTier: "default", model: null });
+ for (const mode of [live, reopened]) {
+ const [refinementComponent, empty, firstShell, thinking, secondShell] = mode.chatContainer.children;
+ for (const detail of [0, 1, 2, 0]) {
+ expect(empty!.render(120)).toEqual([]);
+ const refinementRows = refinementComponent!.render(120);
+ const firstShellRows = firstShell!.render(120);
+ expect(firstShellRows[0]).toBe("");
+ expect(stripAnsi(firstShellRows[1]!)).toContain("Background shell command finished");
+ // No trailing separator is added to an event merely because it ends the transcript.
+ expect(mode.chatContainer.render(120).slice(0, refinementRows.length)).toEqual(refinementRows);
+ expect(secondShell!.render(120)[0] === "").toBe(detail !== 0);
+ expect(thinking!.render(120).length > 0).toBe(detail !== 0);
+ mode.defaultEditor.handleInput("\x0f");
+ }
+ }
+ expect(JSON.stringify(messages)).toBe(source);
+ });
+
+ test("handles long invisible histories without losing the preceding compact row", async () => {
+ harness = await createHarness();
+ const mode = createMode(harness);
+ const messages = [
+ notice("start"),
+ ...Array.from({ length: 400 }, () => fauxAssistantMessage([fauxThinking("hidden"), fauxText("")])),
+ notice("end"),
+ ];
+ const components = buildConversationComponents(messages, {
+ ui: mode.ui,
+ cwd: harness.tempDir,
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ hideThinkingBlock: true,
+ });
+ expect(rows(components).filter((line) => line.trim())).toHaveLength(2);
+ expect(precedingGap(rows(components), "from child end")).toBe(0);
+ });
+ test("does not recursively inspect adjacent streamed tool-only wrappers", async () => {
+ harness = await createHarness();
+ const mode = createMode(harness);
+ const components = buildConversationComponents([notice("start")], {
+ ui: mode.ui,
+ cwd: harness.tempDir,
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ hideThinkingBlock: true,
+ });
+ for (let index = 0; index < 500; index++) {
+ const spacing = createConversationSpacing(components);
+ components.push(
+ new AssistantMessageComponent(
+ fauxAssistantMessage(call(`pending-${index}`), { stopReason: "toolUse" }),
+ true,
+ undefined,
+ { precededByToolActivity: spacing.precededByToolActivity },
+ ),
+ );
+ }
+ expect(createConversationSpacing(components).precededByToolActivity()).toBe(true);
+ expect(createConversationSpacing(components).shouldAddLeadingSpace(false)).toBe(false);
+ expect(rows(components).filter((line) => line.trim())).toHaveLength(1);
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
index 4aa258a4f8..2bee786245 100644
--- a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
@@ -502,7 +502,7 @@ describe("ENG-4482 heartbeat injected prompt UI", () => {
expect(collapsed).toContain("♥");
expect(collapsed).toContain("Heartbeat prompt");
expect(collapsed).toContain("every 5m");
- expect(collapsed).toContain("to expand");
+ expect(collapsed).not.toContain("cycle detail");
expect(collapsed).not.toContain("Check whether the long-running task needs another step.");
component.setExpanded(true);
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.ts
index 4e67d9b4e8..e98fe87c0b 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
@@ -48,6 +48,7 @@ function stripAnsi(text: string): string {
}
function render(component: AgentMessageComponent): string {
+ component.setExpanded(true);
return stripAnsi(component.render(120).join("\n"));
}
@@ -337,6 +338,7 @@ describe("ENG-4531 agent message UI", () => {
ui: { requestRender: () => {} } as unknown as TUI,
cwd: "/tmp",
toolOptions: {},
+ toolsExpanded: true,
getToolDefinition: () => undefined,
});
@@ -345,7 +347,7 @@ describe("ENG-4531 agent message UI", () => {
expect(render(components[0] as AgentMessageComponent)).toContain("Agent message received · from parent Planner");
});
- it("uses compact rebuilt spacing for agent messages next to messages and tool cells", () => {
+ it.each([false, true])("uses mode-aware rebuilt agent-message spacing with all output=%s", (expanded) => {
const first = createAgentSessionMessage(createPayload("First notification."));
const second = createAgentSessionMessage({ ...createPayload("Second notification."), id: "agentmsg_4531_2" });
const toolCall = fauxAssistantMessage(fauxToolCall("ipython", { code: "print('ready')" }), {
@@ -355,6 +357,7 @@ describe("ENG-4531 agent message UI", () => {
ui: { requestRender: () => {} } as unknown as TUI,
cwd: "/tmp",
toolOptions: {},
+ toolsExpanded: expanded,
getToolDefinition: () => undefined,
};
@@ -362,13 +365,13 @@ describe("ENG-4531 agent message UI", () => {
const adjacent = buildConversationComponents([first, second], options);
expect(adjacent).toHaveLength(2);
- expect(adjacent[0]?.render(120)[0]).toBe("");
- expect(adjacent[1]?.render(120)[0]).not.toBe("");
+ expect(adjacent[0]?.render(120)[0] === "").toBe(!expanded);
+ expect(adjacent[1]?.render(120)[0] === "").toBe(expanded);
const toolThenMessage = buildConversationComponents([toolCall, second], options);
- expect(toolThenMessage.at(-1)?.render(120)[0]).not.toBe("");
+ expect(toolThenMessage.at(-1)?.render(120)[0] === "").toBe(expanded);
const messageThenTool = buildConversationComponents([first, toolCall], options);
- expect(messageThenTool.at(-1)?.render(120)[0]).not.toBe("");
+ expect(messageThenTool.at(-1)?.render(120)[0] === "").toBe(expanded);
const userThenMessage = buildConversationComponents(
[{ role: "user", content: "intervening prompt", timestamp: 123 }, second] as AgentMessage[],
@@ -383,11 +386,11 @@ describe("ENG-4531 agent message UI", () => {
expect(assistantThenMessage[1]?.render(120)[0]).toBe("");
});
- it("suppresses live spacing between agent messages and following tool activity", () => {
+ it.each([false, true])("uses mode-aware live agent-message spacing with all output=%s", (expanded) => {
const chatContainer = new Container();
const mode = {
chatContainer,
- toolOutputExpanded: false,
+ toolOutputExpanded: expanded,
getCurrentCwd: () => "/tmp",
getMarkdownThemeWithSettings: () => undefined,
};
@@ -399,8 +402,8 @@ describe("ENG-4531 agent message UI", () => {
addMessage(first);
addMessage(second);
- expect(chatContainer.children[0]?.render(120)[0]).toBe("");
- expect(chatContainer.children[1]?.render(120)[0]).not.toBe("");
+ expect(chatContainer.children[0]?.render(120)[0] === "").toBe(!expanded);
+ expect(chatContainer.children[1]?.render(120)[0] === "").toBe(expanded);
addMessage(fauxAssistantMessage(fauxToolCall("ipython", { code: "print('live')" }), { stopReason: "toolUse" }));
expect(chatContainer.children[2]?.render(120)[0]).not.toBe("");
@@ -411,6 +414,7 @@ describe("ENG-4531 agent message UI", () => {
ui: { requestRender: () => {} } as unknown as TUI,
cwd: "/tmp",
toolOptions: {},
+ toolsExpanded: expanded,
getToolDefinition: () => undefined,
},
);
@@ -418,7 +422,7 @@ describe("ENG-4531 agent message UI", () => {
if (!toolComponent) throw new Error("Missing tool component");
chatContainer.addChild(toolComponent);
addMessage(second);
- expect(chatContainer.children[4]?.render(120)[0]).not.toBe("");
+ expect(chatContainer.children[4]?.render(120)[0] === "").toBe(expanded);
chatContainer.addChild(new Container());
addMessage(second);
@@ -474,20 +478,19 @@ describe("ENG-4531 agent message UI", () => {
expect(render(expanded)).toContain("Agent message received · from sibling Peer");
});
- it("renders a compact row and an aligned multiline gutter when expanded", () => {
+ it("keeps the received notice compact and reveals its multiline body only in all output", () => {
const body = "Reply to your parent with exactly: hi\nThen wait for more work.";
const component = new AgentMessageComponent(createAgentSessionMessage(createPayload(body)));
- const collapsed = render(component);
-
- expect(collapsed).toContain("◆ Agent message received · from Planner");
- expect(collapsed).toContain("to expand");
- expect(collapsed).not.toContain("Then wait for more work.");
+ expect(component.render(120).map((line) => stripAnsi(line).trimEnd())).toEqual([
+ "",
+ " ◆ Agent message received · from Planner",
+ ]);
component.setExpanded(true);
const expanded = render(component);
- expect(expanded).toContain("to collapse");
+ expect(expanded).not.toContain("to collapse");
const expandedLines = expanded.split("\n");
- expect(expandedLines[1]?.trimEnd()).toMatch(/^ ◆ Agent message received · from Planner \(.*to collapse\)$/);
+ expect(expandedLines[1]?.trimEnd()).toBe(" ◆ Agent message received · from Planner");
expect(expandedLines.slice(2)).toEqual([
" ╰─ Reply to your parent with exactly: hi",
" Then wait for more work.",
@@ -509,7 +512,6 @@ describe("ENG-4531 agent message UI", () => {
executionStarted: true,
argsComplete: true,
expanded: true,
- agentMessagesExpanded: true,
details: {
status: "ok",
result: receipt,
@@ -534,7 +536,7 @@ describe("ENG-4531 agent message UI", () => {
expect(lines).toEqual([
expect.stringContaining("python"),
expect.stringContaining("await agent_message.send"),
- expect.stringMatching(/^ ◆ Agent message sent · to parent Worker \(.*to collapse\)$/),
+ " ◆ Agent message sent · to parent Worker",
" ╰─ Continue with shard eight.",
" Then report back.",
]);
@@ -554,7 +556,6 @@ describe("ENG-4531 agent message UI", () => {
executionStarted: true,
argsComplete: true,
expanded: true,
- agentMessagesExpanded: true,
details: {
status: "ok",
result: receipts,
@@ -585,7 +586,6 @@ describe("ENG-4531 agent message UI", () => {
executionStarted: true,
argsComplete: true,
expanded: true,
- agentMessagesExpanded: true,
details: {
status: "ok",
result: "{'referenced_message': 'agentmsg_4531_ref', 'answer': 42}",
@@ -615,7 +615,6 @@ describe("ENG-4531 agent message UI", () => {
executionStarted: true,
argsComplete: true,
expanded: true,
- agentMessagesExpanded: true,
details: {
status: "ok",
result: "'done'",
@@ -641,7 +640,7 @@ describe("ENG-4531 agent message UI", () => {
expect(rendered).toContain("done");
});
- it("decouples sent-message expansion from tool-output expansion", () => {
+ it("keeps sent notices compact until all output reveals their bodies", () => {
const sentAgentMessage = {
id: "agentmsg_4531_decoupled",
message: "Decouple me.",
@@ -660,21 +659,13 @@ describe("ENG-4531 agent message UI", () => {
details: { status: "ok", sentAgentMessages: [sentAgentMessage] },
};
- const agentExpanded = stripAnsi(
- new IPythonCellComponent({ ...baseState, expanded: false, agentMessagesExpanded: true })
- .render(120)
- .join("\n"),
- );
- expect(agentExpanded).toContain(" ◆ Agent message sent · to parent Worker");
- expect(agentExpanded).toContain(" ╰─ Decouple me.");
- expect(agentExpanded).not.toContain("· Decouple me.");
-
- const toolExpanded = stripAnsi(
- new IPythonCellComponent({ ...baseState, expanded: true, agentMessagesExpanded: false })
- .render(120)
- .join("\n"),
- );
- expect(toolExpanded).toContain(" ◆ Agent message sent · to parent Worker · Decouple me.");
- expect(toolExpanded).not.toContain("╰─");
+ const collapsed = stripAnsi(new IPythonCellComponent({ ...baseState, expanded: false }).render(120).join("\n"));
+ expect(collapsed).toContain("◆ Agent message sent · to parent Worker");
+ expect(collapsed.split("\n")).toHaveLength(2);
+ expect(collapsed).not.toContain("╰─ Decouple me.");
+
+ const toolExpanded = stripAnsi(new IPythonCellComponent({ ...baseState, expanded: true }).render(120).join("\n"));
+ expect(toolExpanded).toContain(" ◆ Agent message sent · to parent Worker");
+ expect(toolExpanded).toContain("╰─ Decouple me.");
});
});
diff --git a/packages/coding-agent/test/suite/regressions/4583-latest-tool-expand-hint.test.ts b/packages/coding-agent/test/suite/regressions/4583-latest-tool-expand-hint.test.ts
index f4da578caf..c83ee4cdc6 100644
--- a/packages/coding-agent/test/suite/regressions/4583-latest-tool-expand-hint.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4583-latest-tool-expand-hint.test.ts
@@ -32,7 +32,7 @@ describe("ENG-4583 latest tool expand hint", () => {
harness = undefined;
});
- it("shows the expand or collapse hint only on the latest tool row", async () => {
+ it("keeps repeated detail hints out of all tool rows during replay and expansion", async () => {
harness = await createHarness({ tools: [ipythonTool] });
harness.setResponses([
fauxAssistantMessage(
@@ -66,15 +66,16 @@ describe("ENG-4583 latest tool expand hint", () => {
if (!latest) {
throw new Error("Expected a latest tool component");
}
- expect(render(tools.slice(0, -1))).not.toContain("to expand");
- expect(render([latest])).toContain("to expand");
- expect(render(tools).match(/to expand/g)).toHaveLength(1);
+ expect(render(tools.slice(0, -1))).not.toContain("cycle detail");
+ expect(render([latest])).toContain("3 + 3");
+ expect(render([latest])).not.toContain("Ctrl+O");
+ expect(render(tools)).not.toContain("Ctrl+O");
for (const tool of tools) {
tool.setExpanded(true);
}
- expect(render(tools.slice(0, -1))).not.toContain("to collapse");
- expect(render(tools).match(/to collapse/g)).toHaveLength(1);
+ expect(render(tools.slice(0, -1))).not.toContain("cycle detail");
+ expect(render(tools)).not.toContain("Ctrl+O");
});
});
diff --git a/packages/coding-agent/test/thinking-visibility.test.ts b/packages/coding-agent/test/thinking-visibility.test.ts
new file mode 100644
index 0000000000..d475691041
--- /dev/null
+++ b/packages/coding-agent/test/thinking-visibility.test.ts
@@ -0,0 +1,43 @@
+import { fauxAssistantMessage, fauxText, fauxThinking } from "@earendil-works/pi-ai";
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, test } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { AssistantMessageComponent } from "../src/modes/interactive/components/assistant-message.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+describe("thinking visibility", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ test("hides thinking without hiding assistant text or changing the source message", () => {
+ const message = fauxAssistantMessage([fauxThinking("Trace one."), fauxText("Answer.")]);
+ const original = JSON.stringify(message);
+ const component = new AssistantMessageComponent(message, true);
+ const render = () => stripAnsi(component.render(100).join("\n"));
+ expect(render()).toContain("Answer.");
+ expect(render()).not.toContain("Trace one.");
+ component.setHideThinkingBlock(false);
+ expect(render()).not.toContain("Thinking:");
+ expect(render()).not.toContain("Ctrl+O");
+ expect(render()).toContain("Trace one.");
+ component.setHideThinkingBlock(true);
+ expect(render()).not.toContain("Trace one.");
+ expect(render()).toContain("Answer.");
+ expect(JSON.stringify(message)).toBe(original);
+ });
+
+ test("keeps the selected thinking visibility for subsequent streaming updates", () => {
+ const component = new AssistantMessageComponent(undefined, true);
+ component.updateContent(fauxAssistantMessage(fauxThinking("Partial")), true);
+ expect(component.render(100)).toEqual([]);
+ component.setHideThinkingBlock(false);
+ component.updateContent(fauxAssistantMessage(fauxThinking("Partial reasoning completed.")), true);
+ expect(stripAnsi(component.render(100).join("\n"))).toContain("Partial reasoning completed.");
+ component.setHideThinkingBlock(true);
+ component.updateContent(fauxAssistantMessage(fauxThinking("Next reasoning update.")), true);
+ expect(component.render(100)).toEqual([]);
+ });
+});
diff --git a/packages/coding-agent/test/tool-execution-component.test.ts b/packages/coding-agent/test/tool-execution-component.test.ts
index 7e00a2dbad..ce8f28a938 100644
--- a/packages/coding-agent/test/tool-execution-component.test.ts
+++ b/packages/coding-agent/test/tool-execution-component.test.ts
@@ -450,22 +450,20 @@ describe("ToolExecutionComponent parity", () => {
const collapsed = stripAnsi(component.render(120).join("\n"));
expect(collapsed).not.toContain("-1 before");
expect(collapsed).toContain("+1 -1");
- // The collapsed `╰─ path +N -M` summary line carries the ctrl+j hint —
- // and it is the only carrier: the header must not duplicate it.
- expect(collapsed.split("\n").find((line) => line.includes("╰─"))).toContain("to expand");
- expect(collapsed.split("to expand").length - 1).toBe(1);
+ // The file summary keeps its counts without inline detail hints.
+ expect(collapsed.split("\n").find((line) => line.includes("╰─"))).not.toContain("cycle detail");
+ expect(collapsed).not.toContain("Ctrl+O");
component.setEditDiffsExpanded(true);
const withDiffLines = stripAnsi(component.render(120).join("\n")).split("\n");
- // The summary line stays put; the diff renders under it, indented to its text column.
+ // The summary stays put while diff rows use the normal content margin.
const summaryIndex = withDiffLines.findIndex((line) => line.includes("╰─ README.md +1 -1"));
expect(summaryIndex).toBeGreaterThanOrEqual(0);
- expect(withDiffLines[summaryIndex]).toContain("to collapse");
- const textColumn = withDiffLines[summaryIndex].indexOf("README.md");
+ expect(withDiffLines[summaryIndex]).not.toContain("cycle detail");
const removed = withDiffLines.find((line) => line.includes("-1 before"));
const added = withDiffLines.find((line) => line.includes("+1 after"));
- expect(removed?.startsWith(" ".repeat(textColumn))).toBe(true);
- expect(added?.startsWith(" ".repeat(textColumn))).toBe(true);
+ expect(removed?.trimEnd()).toBe(" -1 before");
+ expect(added?.trimEnd()).toBe(" +1 after");
component.setEditDiffsExpanded(false);
const collapsedAgain = stripAnsi(component.render(120).join("\n"));
@@ -517,7 +515,7 @@ describe("ToolExecutionComponent parity", () => {
}
});
- test("built-in edit summary truncates a long path to one row and keeps counts and hint", () => {
+ test("built-in edit summary truncates a long path to one row and keeps counts", () => {
const longPath = "deeply/nested/directory/structure/with/a/really/long/file-name-that-overflows.md";
const component = new ToolExecutionComponent(
"edit",
@@ -537,13 +535,13 @@ describe("ToolExecutionComponent parity", () => {
expect(summaryLines.length).toBe(1);
expect(summaryLines[0]).toContain("…");
expect(summaryLines[0]).toContain("+1 -1");
- expect(summaryLines[0]).toContain("to expand");
+ expect(summaryLines[0]).not.toContain("cycle detail");
for (const line of lines) {
expect(line.length).toBeLessThanOrEqual(40);
}
});
- test("built-in edit diff rows keep the summary text column when a diff line wraps", () => {
+ test("built-in edit diff rows wrap at the normal content margin", () => {
const component = new ToolExecutionComponent(
"edit",
"tool-4g",
@@ -563,12 +561,12 @@ describe("ToolExecutionComponent parity", () => {
const lines = stripAnsi(component.render(60).join("\n")).split("\n");
const summaryIndex = lines.findIndex((line) => line.includes("╰─ README.md"));
expect(summaryIndex).toBeGreaterThanOrEqual(0);
- const textColumn = lines[summaryIndex].indexOf("README.md");
+ const textColumn = 1;
const diffRows: string[] = [];
for (let i = summaryIndex + 1; i < lines.length && lines[i].trim() !== ""; i++) {
diffRows.push(lines[i]);
}
- // The single logical diff line wraps; every continuation row stays anchored at the text column.
+ // Wrapped rows retain the normal one-column content inset.
expect(diffRows.length).toBeGreaterThan(1);
for (const row of diffRows) {
expect(row.startsWith(" ".repeat(textColumn))).toBe(true);
@@ -577,7 +575,7 @@ describe("ToolExecutionComponent parity", () => {
expect(diffRows.join(" ")).toContain("tau");
});
- test("renders exactly one ctrl+j hint before and after the result lands", async () => {
+ test("keeps file summaries free of detail hints before and after the result lands", async () => {
const dir = mkdtempSync(join(tmpdir(), "edit-hint-"));
const filePath = join(dir, "sample.txt");
writeFileSync(filePath, "before\n");
@@ -595,21 +593,27 @@ describe("ToolExecutionComponent parity", () => {
component.render(120);
// The preview computes asynchronously; poll until it lands.
await vi.waitFor(() => {
- expect(stripAnsi(component.render(120).join("\n"))).toContain("to expand");
+ expect(stripAnsi(component.render(120).join("\n"))).toContain("╰─ sample.txt +1 -1");
});
- // Pre-result: the preview's summary line already carries the hint.
+ // The preview shows complete file counts before the result arrives.
const preResult = stripAnsi(component.render(120).join("\n"));
- expect(preResult.split("\n").find((line) => line.includes("╰─"))).toContain("to expand");
- expect(preResult.split("to expand").length - 1).toBe(1);
+ expect(preResult.split("\n").find((line) => line.includes("╰─"))).not.toContain("cycle detail");
+ expect(preResult).not.toContain("Ctrl+O");
- // A successful result keeps a single hint on the summary line.
+ // A successful result keeps the same compact summary.
component.updateResult(
{ content: [], details: { diff: "-1 before\n+1 after", firstChangedLine: 1 }, isError: false },
false,
);
const settled = stripAnsi(component.render(120).join("\n"));
- expect(settled.split("\n").find((line) => line.includes("╰─"))).toContain("to expand");
- expect(settled.split("to expand").length - 1).toBe(1);
+ expect(settled.split("\n").find((line) => line.includes("╰─"))).not.toContain("cycle detail");
+ expect(settled).not.toContain("Ctrl+O");
+ expect(
+ settled
+ .split("\n")
+ .find((line) => line.includes("╰─"))
+ ?.trim(),
+ ).toBe("╰─ sample.txt +1 -1");
} finally {
rmSync(dir, { recursive: true, force: true });
}
@@ -881,7 +885,7 @@ describe("ToolExecutionComponent parity", () => {
expect(collapsed).not.toMatch(/1 - before/);
expect(collapsed).not.toMatch(/1 \+ after/);
- // Tool expansion shows the full source but never the diff; that belongs to ctrl+j.
+ // The source and diff flags are independent at the component level.
component.setExpanded(true);
const expanded = stripAnsi(component.render(120).join("\n"));
expect(expanded).toContain('hidden_side_effect = "only in full source"');
diff --git a/packages/tui/.changes/ui-chat-output.md b/packages/tui/.changes/ui-chat-output.md
new file mode 100644
index 0000000000..aaffee3bff
--- /dev/null
+++ b/packages/tui/.changes/ui-chat-output.md
@@ -0,0 +1 @@
+- Fixed the follow-output hint shifting horizontally while scrolling over tabs or wide characters.
diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.ts
index a3f6e836c0..a3db69e009 100644
--- a/packages/tui/src/tui.ts
+++ b/packages/tui/src/tui.ts
@@ -1407,15 +1407,23 @@ export class TUI extends Container {
// Single pass through baseLine extracts both before and after segments
const afterStart = startCol + overlayWidth;
- const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
+ const base = extractSegments(
+ normalizeTerminalOutput(baseLine),
+ startCol,
+ afterStart,
+ totalWidth - afterStart,
+ true,
+ );
+ // Clip a wide character crossing the overlay boundary instead of shifting the overlay.
+ const before = sliceWithWidth(base.before, 0, startCol, true);
// Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
// Pad segments to target widths
- const beforePad = Math.max(0, startCol - base.beforeWidth);
+ const beforePad = Math.max(0, startCol - before.width);
const overlayPad = Math.max(0, overlayWidth - overlay.width);
- const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
+ const actualBeforeWidth = Math.max(startCol, before.width);
const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
const afterPad = Math.max(0, afterTarget - base.afterWidth);
@@ -1423,7 +1431,7 @@ export class TUI extends Container {
// Compose result
const r = TUI.SEGMENT_RESET;
const result =
- base.before +
+ before.text +
" ".repeat(beforePad) +
r +
overlay.text +
diff --git a/packages/tui/test/fullscreen-follow-hint.test.ts b/packages/tui/test/fullscreen-follow-hint.test.ts
new file mode 100644
index 0000000000..e62b117bf6
--- /dev/null
+++ b/packages/tui/test/fullscreen-follow-hint.test.ts
@@ -0,0 +1,89 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { getKeybindings } from "../src/keybindings.js";
+import { type Component, TUI } from "../src/tui.js";
+import { visibleWidth } from "../src/utils.js";
+import { VirtualTerminal } from "./virtual-terminal.js";
+
+class Transcript implements Component {
+ lines: string[] = [];
+ render(): string[] {
+ return this.lines;
+ }
+ invalidate(): void {}
+}
+
+describe("fullscreen follow hint alignment", () => {
+ for (const columns of [32, 80, 161]) {
+ it(`keeps the hint centered while scrolling expanded output at ${columns} columns`, async () => {
+ const terminal = new VirtualTerminal(columns, 10);
+ const tui = new TUI(terminal);
+ const transcript = new Transcript();
+ const dock = new Transcript();
+ dock.lines = ["> prompt", "footer"];
+ const followKey = getKeybindings().getKeys("tui.viewport.follow")[0]!;
+ const label = ` ${followKey} to follow `;
+ const column = Math.floor((columns - visibleWidth(label)) / 2);
+ const output = [
+ "",
+ "short",
+ "\tvalue = 1",
+ "\x1b[32m\t\treturn result\x1b[0m",
+ `${"x".repeat(Math.max(0, column - 1))}界 rest`,
+ "x".repeat(columns),
+ ];
+ transcript.lines = [...output, ...output, ...output];
+ tui.start();
+ tui.enterFullscreen({ scroll: [transcript], dock });
+ try {
+ await terminal.waitForRender();
+ tui.scrollToTop();
+ await terminal.waitForRender();
+ for (let index = 0; index < output.length; index++) {
+ const row = terminal.getViewport()[7]!;
+ const prefix = row.slice(0, row.indexOf(followKey));
+ assert.equal(visibleWidth(prefix), column + 1, `scroll row ${index}: ${JSON.stringify(row)}`);
+ assert.equal(terminal.getViewport().filter((line) => line.includes("to follow")).length, 1);
+ transcript.lines.push(`new output ${index}`);
+ tui.requestRender();
+ await terminal.waitForRender();
+ assert.equal(terminal.getViewport()[7], row, "new output must not move the hint");
+ tui.scrollBy(1);
+ await terminal.waitForRender();
+ }
+ tui.scrollToBottom();
+ await terminal.waitForRender();
+ assert.ok(terminal.getViewport().every((line) => !line.includes("to follow")));
+ } finally {
+ tui.stop();
+ }
+ });
+ }
+ it("uses the configured follow binding without shifting over tabbed output", async () => {
+ const keybindings = getKeybindings();
+ const previousBindings = keybindings.getUserBindings();
+ const terminal = new VirtualTerminal(60, 10);
+ const tui = new TUI(terminal);
+ const transcript = new Transcript();
+ transcript.lines = Array.from({ length: 20 }, () => "\t\toutput");
+ const dock = new Transcript();
+ dock.lines = ["> prompt"];
+ try {
+ keybindings.setUserBindings({ ...previousBindings, "tui.viewport.follow": "ctrl+f" });
+ tui.start();
+ tui.enterFullscreen({ scroll: [transcript], dock });
+ await terminal.waitForRender();
+ tui.scrollToTop();
+ await terminal.waitForRender();
+ const row = terminal.getViewport()[8]!;
+ assert.equal(row.indexOf("ctrl+f"), Math.floor((60 - " ctrl+f to follow ".length) / 2) + 1);
+ assert.ok(!row.includes("ctrl+shift+down"));
+ terminal.sendInput("\x06");
+ await terminal.waitForRender();
+ assert.equal(tui.getScrollInfo()?.following, true);
+ } finally {
+ tui.stop();
+ keybindings.setUserBindings(previousBindings);
+ }
+ });
+});