Skip to content

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

Rust

feat(coding-agent): summarize collapsed file edits (#393)

Sebastian Müllere768fd495959
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index ff0db42032..1169681047 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,7 +2,10 @@
## [Unreleased]
+- Added compact file change stats to collapsed tool calls and an agent-run edit total above the recap.
+- Changed tool expansion hints to appear only on the latest tool row instead of every tool call ([ENG-4583](https://linear.app/primeintellect/issue/ENG-4583/too-many-ctrlo-alerts)).
- Changed IPython kernels to set `NO_COLOR=1`, preventing ANSI color escapes from inflating `%%bash` output.
+- Fixed tool-only responses rendering directly against the preceding user prompt.
## [0.3.0] - 2026-07-13
diff --git a/packages/coding-agent/skills/edit/src/edit/__init__.py b/packages/coding-agent/skills/edit/src/edit/__init__.py
index cea04af3d6..e3e0e01465 100644
--- a/packages/coding-agent/skills/edit/src/edit/__init__.py
+++ b/packages/coding-agent/skills/edit/src/edit/__init__.py
@@ -40,8 +40,9 @@ async def run(path: str, old_str: str, new_str: str) -> str:
match_index = content.index(old_str)
start_line = content.count("\n", 0, match_index) + 1
filepath.write_text(content.replace(old_str, new_str, 1), encoding="utf-8")
- _emit_diff(path, old_str, new_str, start_line)
- return f"Edited {path}"
+ resolved_path = str(filepath.resolve())
+ _emit_diff(resolved_path, old_str, new_str, start_line)
+ return f"Edited {resolved_path}"
# Keep in sync with DIFF_DISPLAY_MIME in src/core/kernel/index.ts.
diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.ts
index 77545d1b11..6863256cda 100644
--- a/packages/coding-agent/src/core/extensions/types.ts
+++ b/packages/coding-agent/src/core/extensions/types.ts
@@ -407,6 +407,8 @@ export interface ToolRenderContext<TState = any, TArgs = any> {
isPartial: boolean;
/** Whether the result view is expanded. */
expanded: boolean;
+ /** Whether this row should show the global tool expansion shortcut. */
+ showExpandHint?: boolean;
/** Whether inline images are currently shown in the TUI. */
showImages: boolean;
/** Whether image fallback labels may parse dimensions from base64 data. */
diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.ts
index 2f848d84e9..efc260eae1 100644
--- a/packages/coding-agent/src/core/tools/bash.ts
+++ b/packages/coding-agent/src/core/tools/bash.ts
@@ -204,6 +204,7 @@ function rebuildBashResultRenderComponent(
options: ToolRenderResultOptions,
showImages: boolean,
includeImageDimensions: boolean,
+ showExpandHint: boolean,
startedAt: number | undefined,
endedAt: number | undefined,
): void {
@@ -230,9 +231,10 @@ function rebuildBashResultRenderComponent(
state.cachedWidth = width;
}
if (state.cachedSkipped && state.cachedSkipped > 0) {
- const hint =
- theme.fg("muted", `... (${state.cachedSkipped} earlier lines,`) +
- ` ${keyHint("app.tools.expand", "to expand")})`;
+ const hint = showExpandHint
+ ? theme.fg("muted", `... (${state.cachedSkipped} earlier lines,`) +
+ ` ${keyHint("app.tools.expand", "to expand")})`
+ : theme.fg("muted", `... (${state.cachedSkipped} earlier lines)`);
return ["", truncateToWidth(hint, width, "..."), ...(state.cachedLines ?? [])];
}
return ["", ...(state.cachedLines ?? [])];
@@ -438,6 +440,7 @@ export function createBashToolDefinition(
options,
context.showImages,
context.includeImageDimensions,
+ context.showExpandHint !== false,
state.startedAt,
state.endedAt,
);
diff --git a/packages/coding-agent/src/core/tools/edit.ts b/packages/coding-agent/src/core/tools/edit.ts
index f81ab3ce53..746d89da62 100644
--- a/packages/coding-agent/src/core/tools/edit.ts
+++ b/packages/coding-agent/src/core/tools/edit.ts
@@ -4,6 +4,7 @@ import { constants } from "fs";
import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";
import { type Static, Type } from "typebox";
import { renderDiff } from "../../modes/interactive/components/diff.js";
+import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
import type { ToolDefinition } from "../extensions/types.js";
import {
applyEditsToNormalizedContent,
@@ -251,19 +252,29 @@ function buildEditCallComponent(
component: EditCallRenderComponent,
args: RenderableEditArgs | undefined,
theme: typeof import("../../modes/interactive/theme/theme.js").theme,
+ expanded: boolean,
+ showExpandHint: boolean,
): EditCallRenderComponent {
component.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));
component.clear();
- component.addChild(new Text(formatEditCall(args, theme), 0, 0));
-
- if (!component.preview) {
- return component;
- }
+ const canExpand = component.preview !== undefined && !("error" in component.preview);
+ const expandHint =
+ canExpand && showExpandHint
+ ? `${theme.fg("dim", " · ")}${keyHint("app.tools.expand", expanded ? "to collapse" : "to expand")}`
+ : "";
+ component.addChild(new Text(`${formatEditCall(args, theme)}${expandHint}`, 0, 0));
const body =
- "error" in component.preview ? theme.fg("error", component.preview.error) : renderDiff(component.preview.diff);
- component.addChild(new Spacer(1));
- component.addChild(new Text(body, 0, 0));
+ component.preview &&
+ ("error" in component.preview
+ ? theme.fg("error", component.preview.error)
+ : expanded
+ ? renderDiff(component.preview.diff)
+ : undefined);
+ if (body) {
+ component.addChild(new Spacer(1));
+ component.addChild(new Text(body, 0, 0));
+ }
return component;
}
@@ -438,7 +449,7 @@ export function createEditToolDefinition(
});
}
- return buildEditCallComponent(component, args, theme);
+ return buildEditCallComponent(component, args, theme, context.expanded, context.showExpandHint !== false);
},
renderResult(result, _options, theme, context) {
const callComponent = context.state.callComponent;
@@ -463,7 +474,13 @@ export function createEditToolDefinition(
changed = true;
}
if (changed) {
- buildEditCallComponent(callComponent, context.args as RenderableEditArgs | undefined, theme);
+ buildEditCallComponent(
+ callComponent,
+ context.args as RenderableEditArgs | undefined,
+ theme,
+ context.expanded,
+ context.showExpandHint !== false,
+ );
}
}
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 75c56a22f4..0e14c82834 100644
--- a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
@@ -265,7 +265,7 @@ export class AssistantMessageComponent extends Container {
this.contentContainer.addChild(this.createErrorComponent(errorMsg, "Error"));
}
- if (hasToolCalls && (hasVisibleContent || message.stopReason === "aborted")) {
+ if (hasToolCalls) {
this.contentContainer.addChild(new Spacer(1));
}
}
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 64568e51ec..ad84f3275c 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -4,7 +4,12 @@ import { isAgentSessionMessage } from "../../../core/agent-messages.js";
import { AgentMessageComponent } from "./agent-message.js";
import { AssistantMessageComponent } from "./assistant-message.js";
import { InjectedPromptMessageComponent, isInjectedPromptMessage } from "./injected-prompt-message.js";
-import { ToolExecutionComponent, type ToolExecutionDefinition, type ToolExecutionOptions } from "./tool-execution.js";
+import {
+ selectLatestToolExpandHint,
+ ToolExecutionComponent,
+ type ToolExecutionDefinition,
+ type ToolExecutionOptions,
+} from "./tool-execution.js";
import { UserMessageComponent } from "./user-message.js";
export interface ConversationComponentsOptions {
@@ -67,6 +72,7 @@ export function buildConversationComponents(
tool.setExpanded(expanded);
tool.markExecutionStarted();
tool.setArgsComplete();
+ selectLatestToolExpandHint(components, tool);
components.push(tool);
if (message.stopReason === "aborted" || message.stopReason === "error") {
tool.updateResult({
diff --git a/packages/coding-agent/src/modes/interactive/components/edit-summary.ts b/packages/coding-agent/src/modes/interactive/components/edit-summary.ts
new file mode 100644
index 0000000000..0681f546b3
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/edit-summary.ts
@@ -0,0 +1,140 @@
+import { isAbsolute } from "node:path";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import type { ToolResultMessage } from "@earendil-works/pi-ai";
+import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
+import type { EditToolDetails } from "../../../core/tools/edit.js";
+import { generateDiffString } from "../../../core/tools/edit-diff.js";
+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";
+
+export interface FileChangeSummary {
+ path: string;
+ added: number;
+ removed: number;
+}
+
+const FILE_SUMMARY_LIMIT = 5;
+
+function countChangedLines(diff: string): { added: number; removed: number } {
+ let added = 0;
+ let removed = 0;
+ for (const line of diff.split("\n")) {
+ if (line.startsWith("+")) added++;
+ else if (line.startsWith("-")) removed++;
+ }
+ return { added, removed };
+}
+
+function mergeFileChange(target: Map<string, FileChangeSummary>, change: FileChangeSummary, cwd: string): void {
+ if (change.added === 0 && change.removed === 0) return;
+ const key = canonicalizePath(resolveToCwd(change.path, cwd));
+ const existing = target.get(key);
+ if (existing) {
+ existing.added += change.added;
+ existing.removed += change.removed;
+ } else {
+ target.set(key, { ...change });
+ }
+}
+
+function formatFileChangePath(path: string, cwd: string): string {
+ const resolvedPath = resolveToCwd(path, cwd);
+ const lexicalPath = formatPathRelativeToCwdOrAbsolute(resolvedPath, cwd);
+ if (!isAbsolute(lexicalPath)) {
+ return lexicalPath;
+ }
+ return formatPathRelativeToCwdOrAbsolute(canonicalizePath(resolvedPath), canonicalizePath(cwd));
+}
+
+export function getToolFileChanges(
+ toolName: string,
+ args: unknown,
+ result: { details?: unknown; isError: boolean },
+ cwd: string,
+): FileChangeSummary[] {
+ const changes = new Map<string, FileChangeSummary>();
+ if (toolName === "ipython") {
+ for (const display of (result.details as IpythonToolDetails | undefined)?.diffs ?? []) {
+ const { diff } = generateDiffString(display.oldStr, display.newStr, 4, display.startLine ?? 1);
+ mergeFileChange(changes, { path: display.path, ...countChangedLines(diff) }, cwd);
+ }
+ } else if (toolName === "edit" && !result.isError) {
+ const editArgs = args as { path?: unknown; file_path?: unknown } | undefined;
+ const path = typeof editArgs?.path === "string" ? editArgs.path : editArgs?.file_path;
+ const diff = (result.details as EditToolDetails | undefined)?.diff;
+ if (typeof path === "string" && diff) {
+ mergeFileChange(changes, { path, ...countChangedLines(diff) }, cwd);
+ }
+ }
+ return [...changes.values()];
+}
+
+export function mergeTurnFileChanges(
+ target: Map<string, FileChangeSummary>,
+ message: AgentMessage,
+ toolResults: readonly ToolResultMessage[],
+ cwd: string,
+): void {
+ if (message.role !== "assistant") return;
+ const calls = new Map(
+ message.content.filter((content) => content.type === "toolCall").map((content) => [content.id, content] as const),
+ );
+ for (const result of toolResults) {
+ const call = calls.get(result.toolCallId);
+ if (!call) continue;
+ for (const change of getToolFileChanges(call.name, call.arguments, result, cwd)) {
+ mergeFileChange(target, change, cwd);
+ }
+ }
+}
+
+function counts(change: Pick<FileChangeSummary, "added" | "removed">): string {
+ return `${theme.fg("toolDiffAdded", `+${change.added}`)} ${theme.fg("toolDiffRemoved", `-${change.removed}`)}`;
+}
+
+export class FileChangeSummaryComponent implements Component {
+ constructor(
+ private readonly changes: readonly FileChangeSummary[],
+ private readonly cwd: string,
+ ) {}
+
+ render(width: number): string[] {
+ const safeWidth = Math.max(1, width);
+ const prefix = theme.fg("dim", " ╰─ ");
+ const shown = this.changes.slice(0, FILE_SUMMARY_LIMIT).map((change) => {
+ const suffix = `${theme.fg("dim", " ")}${counts(change)}`;
+ const available = Math.max(1, safeWidth - visibleWidth(prefix) - visibleWidth(suffix));
+ const path = truncateToWidth(formatFileChangePath(change.path, this.cwd), available, "…");
+ return truncateToWidth(`${prefix}${theme.fg("muted", path)}${suffix}`, safeWidth, "");
+ });
+ if (this.changes.length > FILE_SUMMARY_LIMIT) {
+ const hidden = this.changes.slice(FILE_SUMMARY_LIMIT);
+ const hiddenTotals = hidden.reduce(
+ (sum, change) => ({ added: sum.added + change.added, removed: sum.removed + change.removed }),
+ { added: 0, removed: 0 },
+ );
+ const files = `${hidden.length} more file${hidden.length === 1 ? "" : "s"}`;
+ shown.push(
+ truncateToWidth(
+ `${prefix}${theme.fg("muted", `[${files}`)}${theme.fg("dim", " ")}${counts(hiddenTotals)}${theme.fg("muted", "]")}`,
+ safeWidth,
+ "",
+ ),
+ );
+ }
+ return shown;
+ }
+
+ invalidate(): void {}
+}
+
+export function formatTotalChangeSummary(changes: readonly FileChangeSummary[]): string {
+ const totals = changes.reduce(
+ (sum, change) => ({ added: sum.added + change.added, removed: sum.removed + change.removed }),
+ { added: 0, removed: 0 },
+ );
+ const files = `${changes.length} file${changes.length === 1 ? "" : "s"} changed`;
+ return `${theme.fg("muted", files)}${theme.fg("dim", " | ")}${counts(totals)}`;
+}
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 f5909eb033..819654be56 100644
--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
@@ -30,6 +30,7 @@ export interface IPythonCellState {
isPartial?: boolean;
isError?: boolean;
expanded?: boolean;
+ showExpandHint?: boolean;
executionStarted?: boolean;
argsComplete?: boolean;
showImages?: boolean;
@@ -358,8 +359,7 @@ export class IPythonCellComponent implements Component {
const lines = [truncateToWidth(` ${this.collapsedLine(details)}`, safeWidth, "")];
const hasDiffs = (details.diffs?.length ?? 0) > 0;
- // Edits always show their diff under the top line, regardless of expand state.
- if (hasDiffs) {
+ if (hasDiffs && this.state.expanded) {
this.renderDiffs(lines, safeWidth, details.diffs ?? [], this.marker(details));
}
if ((details.sentAgentMessages?.length ?? 0) > 0) {
@@ -370,7 +370,7 @@ export class IPythonCellComponent implements Component {
return this.renderCache.set(safeWidth, cacheVersion, lines);
}
- const hasCode = this.renderCode(lines, safeWidth, hasDiffs);
+ const hasCode = this.renderCode(lines, safeWidth);
this.renderOutput(lines, safeWidth, details, hasCode);
return this.renderCache.set(safeWidth, cacheVersion, lines);
}
@@ -403,7 +403,9 @@ export class IPythonCellComponent implements Component {
parts.push(theme.fg("error", errorName));
}
- parts.push(keyHint("app.tools.expand", this.state.expanded ? "to collapse" : "to expand"));
+ if (this.state.showExpandHint !== false) {
+ parts.push(keyHint("app.tools.expand", this.state.expanded ? "to collapse" : "to expand"));
+ }
return parts.join(theme.fg("dim", " · "));
}
@@ -479,11 +481,7 @@ export class IPythonCellComponent implements Component {
}
// Only runs when expanded — shows the full source below the fixed top line.
- // Edits skip the source: their diff already renders above and conveys the change.
- private renderCode(lines: string[], width: number, hasDiffs: boolean): boolean {
- if (hasDiffs) {
- return false;
- }
+ private renderCode(lines: string[], width: number): boolean {
const code = this.state.code.trimEnd();
if (!code) {
this.addBlank(lines, width);
@@ -628,7 +626,6 @@ export class IPythonCellComponent implements Component {
}
}
- // Edits always render in full, regardless of expand state. Grouped by file.
private renderDiffs(lines: string[], width: number, diffs: readonly DiffDisplay[], marker: string): void {
const diffsByPath = new Map<string, DiffDisplay[]>();
for (const diff of diffs) {
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 ec73f5bd5b..58e0af6b47 100644
--- a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
+++ b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
@@ -10,6 +10,7 @@ import { convertToPng } from "../../../utils/image-convert.js";
import type { AgentConnectionToolDefinition } from "../../agent-connection/index.js";
import { type Theme, theme } from "../theme/theme.js";
import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
+import { FileChangeSummaryComponent, getToolFileChanges } from "./edit-summary.js";
import { getIpythonCodeFromArgs, IPythonCellComponent } from "./ipython-cell.js";
import { ToolPanel } from "./tool-panel.js";
@@ -85,6 +86,7 @@ export class ToolExecutionComponent extends Container {
private toolCallId: string;
private args: any;
private expanded = false;
+ private showExpandHint = true;
private showImages: boolean;
private allowInlineImages: boolean;
private imageWidthCells: number;
@@ -202,6 +204,7 @@ export class ToolExecutionComponent extends Container {
argsComplete: this.argsComplete,
isPartial: this.isPartial,
expanded: this.expanded,
+ showExpandHint: this.showExpandHint,
showImages: renderInlineImages,
includeImageDimensions: this.allowInlineImages,
isError: this.result?.isError ?? false,
@@ -304,6 +307,14 @@ export class ToolExecutionComponent extends Container {
this.updateDisplay();
}
+ setShowExpandHint(show: boolean): void {
+ if (this.showExpandHint === show) {
+ return;
+ }
+ this.showExpandHint = show;
+ this.updateDisplay();
+ }
+
setShowImages(show: boolean): void {
this.showImages = show;
if (show) {
@@ -374,6 +385,7 @@ export class ToolExecutionComponent extends Container {
expanded: this.expanded,
executionStarted: this.executionStarted,
argsComplete: this.argsComplete,
+ showExpandHint: this.showExpandHint,
showImages: renderInlineImages,
cwd: this.cwd,
};
@@ -438,6 +450,18 @@ export class ToolExecutionComponent extends Container {
}
}
+ const isBuiltInEdit =
+ this.toolName === "edit" &&
+ (this.toolDefinition === undefined || this.toolDefinition.replayBuiltInToolName === "edit");
+ if (!this.expanded && this.result && (isBuiltInEdit || this.shouldUseIpythonRenderer())) {
+ const changes = getToolFileChanges(this.toolName, this.args, this.result, this.cwd);
+ if (changes.length > 0) {
+ const container = this.usesSelfRenderShell() ? this.selfRenderContainer : this.contentPanel;
+ container.addChild(new FileChangeSummaryComponent(changes, this.cwd));
+ hasContent = true;
+ }
+ }
+
if (this.hasRendererDefinition() && !hasContent && this.imageComponents.length === 0) {
this.hideComponent = true;
}
@@ -542,3 +566,17 @@ export class ToolExecutionComponent extends Container {
return parts.join("\n\n");
}
}
+
+export function selectLatestToolExpandHint(
+ existingComponents: readonly Component[],
+ latestComponent: ToolExecutionComponent,
+): void {
+ for (let index = existingComponents.length - 1; index >= 0; index--) {
+ const component = existingComponents[index];
+ if (component instanceof ToolExecutionComponent) {
+ component.setShowExpandHint(false);
+ break;
+ }
+ }
+ latestComponent.setShowExpandHint(true);
+}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 11bc19c84e..3d6442a82b 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -167,6 +167,7 @@ import { CustomMessageComponent } from "./components/custom-message.js";
import { DaxnutsComponent } from "./components/daxnuts.js";
import { DynamicBorder } from "./components/dynamic-border.js";
import { EarendilAnnouncementComponent } from "./components/earendil-announcement.js";
+import { type FileChangeSummary, formatTotalChangeSummary, mergeTurnFileChanges } from "./components/edit-summary.js";
import { ExtensionEditorComponent } from "./components/extension-editor.js";
import { ExtensionInputComponent } from "./components/extension-input.js";
import { ExtensionSelectorComponent } from "./components/extension-selector.js";
@@ -181,7 +182,11 @@ import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { SideQuestionComponent } from "./components/side-question.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
-import { ToolExecutionComponent, type ToolExecutionDefinition } from "./components/tool-execution.js";
+import {
+ selectLatestToolExpandHint,
+ ToolExecutionComponent,
+ type ToolExecutionDefinition,
+} from "./components/tool-execution.js";
import { TreeSelectorComponent } from "./components/tree-selector.js";
import { UserMessageComponent } from "./components/user-message.js";
import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
@@ -742,6 +747,7 @@ export class InteractiveMode {
private startedToolCalls = new Set<string>();
private pendingToolGeneration = 0;
private toolDefinitionCache = new Map<string, ToolExecutionDefinition | undefined>();
+ private agentRunFileChanges = new Map<string, FileChangeSummary>();
// RLM child-agent tray: inline list below the editor, full-screen detail on open.
private childAgentSummary: ChildAgentSummaryComponent;
@@ -2466,6 +2472,8 @@ export class InteractiveMode {
this.activityTracker.reset();
this.contextUsageTokenBaseline = 0;
this.resetPendingToolState();
+ this.agentRunFileChanges.clear();
+ this.renderRecap();
this.ipythonToolComponents.clear();
this.lateIpythonSentAgentMessages.clear();
this.resetChildAgentInspector();
@@ -2591,6 +2599,7 @@ export class InteractiveMode {
if (this.startedToolCalls.has(latestToolCall.id)) {
component.markExecutionStarted();
}
+ selectLatestToolExpandHint(this.chatContainer.children, component);
this.chatContainer.addChild(component);
this.pendingTools.set(latestToolCall.id, component);
this.registerIpythonToolComponent(latestToolCall.name, latestToolCall.id, component);
@@ -2985,13 +2994,20 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /** Render the recap line above the editor when one exists. */
private renderRecap(): void {
if (!this.recapContainer) return;
this.recapContainer.clear();
const recap = this.childAgentPanelMode ? undefined : this.sessionRecap?.trim();
+ const showChanges = !this.childAgentPanelMode && !this.isAgentStreaming() && this.agentRunFileChanges.size > 0;
+ if (showChanges) {
+ this.recapContainer.addChild(
+ new TruncatedText(formatTotalChangeSummary([...this.agentRunFileChanges.values()]), 1, 0),
+ );
+ }
if (recap) {
this.recapContainer.addChild(new TruncatedText(theme.fg("dim", `Recap: ${recap}`), 1, 0));
+ }
+ if (recap || showChanges) {
this.recapContainer.addChild(new Spacer(1));
}
this.ui.requestRender();
@@ -4375,6 +4391,8 @@ export class InteractiveMode {
this.contextUsageTokenBaseline = 0;
this.setSessionHasMessages(true);
this.clearShortcutGuide();
+ this.agentRunFileChanges.clear();
+ this.renderRecap();
}
this.activityTracker.handleEvent(event);
this.updateWorkingLoaderMessage();
@@ -4382,6 +4400,7 @@ export class InteractiveMode {
switch (event.type) {
case "agent_start":
this.resetPendingToolState();
+ this.renderRecap();
if (this.settingsManager.getShowTerminalProgress()) {
this.ui.terminal.setProgress(true);
}
@@ -4577,6 +4596,10 @@ export class InteractiveMode {
break;
}
+ case "turn_end":
+ mergeTurnFileChanges(this.agentRunFileChanges, event.message, event.toolResults, this.getCurrentCwd());
+ break;
+
case "agent_end":
if (this.settingsManager.getShowTerminalProgress()) {
this.ui.terminal.setProgress(false);
@@ -4594,6 +4617,7 @@ export class InteractiveMode {
}
this.flushPendingBashComponents();
this.resetPendingToolState();
+ this.renderRecap();
this.applyOptimisticContextUsage();
await this.refreshConnectionContextUsage();
@@ -5661,6 +5685,7 @@ export class InteractiveMode {
this.getCurrentCwd(),
);
component.setExpanded(this.toolOutputExpanded);
+ selectLatestToolExpandHint(this.chatContainer.children, component);
this.chatContainer.addChild(component);
this.registerIpythonToolComponent(content.name, content.id, component);
diff --git a/packages/coding-agent/test/assistant-message.test.ts b/packages/coding-agent/test/assistant-message.test.ts
index d25f37962f..e2ed0dcfcb 100644
--- a/packages/coding-agent/test/assistant-message.test.ts
+++ b/packages/coding-agent/test/assistant-message.test.ts
@@ -72,7 +72,7 @@ describe("AssistantMessageComponent", () => {
expect(lines.at(-1)).toBe("");
});
- test("does not add spacing for a tool-only assistant message", () => {
+ test("adds one leading spacer before a tool-only batch", () => {
initTheme("dark");
const component = new AssistantMessageComponent(
@@ -82,7 +82,7 @@ describe("AssistantMessageComponent", () => {
]),
);
- expect(component.render(60)).toEqual([]);
+ expect(component.render(60)).toEqual([""]);
});
test("renders an abort status for messages with tool calls", () => {
diff --git a/packages/coding-agent/test/edit-summary.test.ts b/packages/coding-agent/test/edit-summary.test.ts
new file mode 100644
index 0000000000..64d07c3635
--- /dev/null
+++ b/packages/coding-agent/test/edit-summary.test.ts
@@ -0,0 +1,154 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AssistantMessage, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, test } from "vitest";
+import {
+ FileChangeSummaryComponent,
+ formatTotalChangeSummary,
+ getToolFileChanges,
+ mergeTurnFileChanges,
+} from "../src/modes/interactive/components/edit-summary.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+const usage: Usage = {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+};
+
+function assistant(content: AssistantMessage["content"]): AssistantMessage {
+ return {
+ role: "assistant",
+ content,
+ api: "test",
+ provider: "test",
+ model: "test",
+ usage,
+ stopReason: "toolUse",
+ timestamp: 0,
+ };
+}
+
+function result(toolCallId: string, toolName: string, details: unknown, isError = false): ToolResultMessage {
+ return { role: "toolResult", toolCallId, toolName, content: [], details, isError, timestamp: 0 };
+}
+
+describe("edit summaries", () => {
+ beforeAll(() => initTheme("dark"));
+
+ test("only reports successful edits that changed lines", () => {
+ expect(getToolFileChanges("edit", { path: "a.ts" }, { details: { diff: "" }, isError: false }, "/tmp")).toEqual(
+ [],
+ );
+ expect(
+ getToolFileChanges("edit", { path: "a.ts" }, { details: { diff: "-1 old\n+1 new" }, isError: true }, "/tmp"),
+ ).toEqual([]);
+ expect(
+ getToolFileChanges("edit", { path: "a.ts" }, { details: { diff: "-1 old\n+1 new" }, isError: false }, "/tmp"),
+ ).toEqual([{ path: "a.ts", added: 1, removed: 1 }]);
+ expect(
+ getToolFileChanges(
+ "ipython",
+ {},
+ { details: { diffs: [{ path: "b.ts", oldStr: "old", newStr: "new" }] }, isError: true },
+ "/tmp",
+ ),
+ ).toEqual([{ path: "b.ts", added: 1, removed: 1 }]);
+ });
+
+ test("limits a collapsed tool summary to five files plus hidden totals", () => {
+ const changes = Array.from({ length: 7 }, (_, index) => ({
+ path: `src/${index}.ts`,
+ added: index + 1,
+ removed: 1,
+ }));
+ const lines = new FileChangeSummaryComponent(changes, "/tmp").render(80).map(stripAnsi);
+ expect(lines).toHaveLength(6);
+ expect(lines[0]).toBe(" ╰─ src/0.ts +1 -1");
+ expect(lines[4]).toBe(" ╰─ src/4.ts +5 -1");
+ expect(lines[5]).toBe(" ╰─ [2 more files +13 -2]");
+ });
+
+ test("renders one total line for all changed files in an agent run", () => {
+ const line = formatTotalChangeSummary([
+ { path: "a.ts", added: 2, removed: 1 },
+ { path: "b.ts", added: 3, removed: 4 },
+ ]);
+ expect(stripAnsi(line)).toBe("2 files changed | +5 -5");
+ });
+
+ test("coalesces direct and IPython edits by file", () => {
+ const message = assistant([
+ { type: "toolCall", id: "one", name: "edit", arguments: { path: "a.ts" } },
+ { type: "toolCall", id: "two", name: "ipython", arguments: {} },
+ ]);
+ const changes = new Map();
+ mergeTurnFileChanges(
+ changes,
+ message,
+ [
+ result("one", "edit", { diff: "-1 old\n+1 new" }),
+ result("two", "ipython", { diffs: [{ path: "a.ts", oldStr: "new", newStr: "newer" }] }),
+ ],
+ "/tmp",
+ );
+ expect([...changes.values()]).toEqual([{ path: "a.ts", added: 2, removed: 2 }]);
+ });
+
+ test("coalesces home-relative and absolute paths", () => {
+ const absolutePath = `${homedir()}/same.ts`;
+ const message = assistant([
+ { type: "toolCall", id: "one", name: "edit", arguments: { path: "~/same.ts" } },
+ { type: "toolCall", id: "two", name: "ipython", arguments: {} },
+ ]);
+ const changes = new Map();
+ mergeTurnFileChanges(
+ changes,
+ message,
+ [
+ result("one", "edit", { diff: "-1 old\n+1 new" }),
+ result("two", "ipython", { diffs: [{ path: absolutePath, oldStr: "new", newStr: "newer" }] }),
+ ],
+ "/tmp",
+ );
+ expect([...changes.values()]).toEqual([{ path: "~/same.ts", added: 2, removed: 2 }]);
+ });
+
+ test("coalesces canonical paths and renders them relative to a symlinked cwd", () => {
+ const root = mkdtempSync(join(tmpdir(), "edit-summary-symlink-"));
+ try {
+ const realCwd = join(root, "real");
+ const linkedCwd = join(root, "linked");
+ const file = join(realCwd, "same.ts");
+ mkdirSync(realCwd);
+ writeFileSync(file, "old");
+ symlinkSync(realCwd, linkedCwd, "dir");
+
+ const message = assistant([
+ { type: "toolCall", id: "one", name: "ipython", arguments: {} },
+ { type: "toolCall", id: "two", name: "edit", arguments: { path: "same.ts" } },
+ ]);
+ const changes = new Map();
+ mergeTurnFileChanges(
+ changes,
+ message,
+ [
+ result("one", "ipython", { diffs: [{ path: realpathSync(file), oldStr: "old", newStr: "new" }] }),
+ result("two", "edit", { diff: "-1 new\n+1 newer" }),
+ ],
+ linkedCwd,
+ );
+
+ expect([...changes.values()]).toEqual([{ path: realpathSync(file), added: 2, removed: 2 }]);
+ const lines = new FileChangeSummaryComponent([...changes.values()], linkedCwd).render(80).map(stripAnsi);
+ expect(lines).toEqual([" ╰─ same.ts +2 -2"]);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/coding-agent/test/edit-tool-no-full-redraw.test.ts b/packages/coding-agent/test/edit-tool-no-full-redraw.test.ts
index 57aa376951..e346f5c0a4 100644
--- a/packages/coding-agent/test/edit-tool-no-full-redraw.test.ts
+++ b/packages/coding-agent/test/edit-tool-no-full-redraw.test.ts
@@ -126,6 +126,7 @@ describe("edit tool TUI rendering", () => {
tui.start();
await waitForRender();
+ component.setExpanded(true);
component.setArgsComplete();
tui.requestRender();
await waitForRender();
@@ -195,6 +196,7 @@ describe("edit tool TUI rendering", () => {
tui.start();
await waitForRender();
+ component.setExpanded(true);
component.updateResult(
{
content: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${filePath}.` }],
diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
index 853d3ed336..2335e181eb 100644
--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -55,6 +55,9 @@ type ResetHarness = PromptStashLiveMarkerHarness & {
pendingBashComponents: unknown[];
activityTracker: { reset: Mock };
contextUsageTokenBaseline: number;
+ agentRunFileChanges: Map<string, unknown>;
+ recapContainer: { clear: Mock };
+ ui: { requestRender: Mock };
ipythonToolComponents: Map<string, unknown>;
lateIpythonSentAgentMessages: Map<string, unknown>;
resetPendingToolState: Mock;
@@ -350,6 +353,9 @@ describe("InteractiveMode prompt stash", () => {
pendingBashComponents: [],
activityTracker: { reset: vi.fn() },
contextUsageTokenBaseline: 1,
+ agentRunFileChanges: new Map(),
+ recapContainer: { clear: vi.fn() },
+ ui: { requestRender: vi.fn() },
ipythonToolComponents: new Map(),
lateIpythonSentAgentMessages: new Map(),
resetPendingToolState: vi.fn(),
@@ -383,6 +389,9 @@ describe("InteractiveMode prompt stash", () => {
pendingBashComponents: [],
activityTracker: { reset: vi.fn() },
contextUsageTokenBaseline: 1,
+ agentRunFileChanges: new Map(),
+ recapContainer: { clear: vi.fn() },
+ ui: { requestRender: vi.fn() },
ipythonToolComponents: new Map(),
lateIpythonSentAgentMessages: new Map(),
resetPendingToolState: vi.fn(),
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index cb511d8da2..4b11e9ea49 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -648,6 +648,9 @@ describe("InteractiveMode pending bash components", () => {
activeBashComponent: component,
pendingBashComponents: [component],
activityTracker: { reset: vi.fn() },
+ agentRunFileChanges: new Map(),
+ recapContainer: new Container(),
+ renderRecap: vi.fn(),
ipythonToolComponents: new Map(),
lateIpythonSentAgentMessages: new Map(),
resetPendingToolState: vi.fn(),
diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.ts
index ebe4e5da02..e7f860f68f 100644
--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts
+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts
@@ -5,6 +5,7 @@ import { beforeAll, describe, expect, test, vi } from "vitest";
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";
+import type { FileChangeSummary } from "../src/modes/interactive/components/edit-summary.js";
import type { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
import { getMarkdownTheme, initTheme } from "../src/modes/interactive/theme/theme.js";
@@ -27,21 +28,31 @@ const EMPTY_USAGE: Usage = {
type HandleEventThis = {
isInitialized: boolean;
settingsManager: { getShowTerminalProgress(): boolean };
+ connectionState: { isStreaming: boolean };
+ toolOutputExpanded: boolean;
footer: { invalidate(): void };
ui: TUI;
chatContainer: Container;
+ recapContainer: Container;
+ sessionRecap: string | undefined;
+ childAgentPanelMode: undefined;
hideThinkingBlock: boolean;
hiddenThinkingLabel: string;
streamingComponent: AssistantMessageComponent | undefined;
streamingMessage: AssistantMessage | undefined;
pendingTools: Map<string, ToolExecutionComponent>;
+ agentRunFileChanges: Map<string, FileChangeSummary>;
updateConnectionStateFromEvent(event: AgentConnectionSessionEvent): void;
getMarkdownThemeWithSettings(): MarkdownTheme;
getOrCreatePendingToolComponent(): Promise<ToolExecutionComponent | undefined>;
getRetryAttempt(): number;
+ getCurrentCwd(): string;
stopWorkingLoader(): void;
resetPendingToolState(): void;
checkShutdownRequested(): Promise<void>;
+ setSessionHasMessages(hasMessages: boolean): void;
+ clearShortcutGuide(): void;
+ addMessageToChat(): void;
};
type HandleEvent = (this: HandleEventThis, event: AgentConnectionSessionEvent) => Promise<void>;
@@ -64,10 +75,15 @@ function createFakeInteractiveModeThis(): HandleEventThis {
const fakeThis = {
isInitialized: true,
settingsManager: { getShowTerminalProgress: () => false },
+ connectionState: { isStreaming: false },
+ toolOutputExpanded: false,
footer: { invalidate: vi.fn() },
activityTracker: new AgentActivityTracker(),
ui: { requestRender: vi.fn() } as unknown as TUI,
chatContainer: new Container(),
+ recapContainer: new Container(),
+ sessionRecap: "Updated files",
+ childAgentPanelMode: undefined,
hideThinkingBlock: false,
hiddenThinkingLabel: "Thinking...",
streamingComponent: undefined,
@@ -75,13 +91,18 @@ function createFakeInteractiveModeThis(): HandleEventThis {
pendingMessagesContainer: new Container(),
pendingBashComponents: [],
pendingTools: new Map<string, ToolExecutionComponent>(),
+ agentRunFileChanges: new Map<string, FileChangeSummary>(),
updateConnectionStateFromEvent: vi.fn(),
getMarkdownThemeWithSettings: () => getMarkdownTheme(),
getOrCreatePendingToolComponent: vi.fn(async () => undefined),
getRetryAttempt: () => 0,
+ getCurrentCwd: () => "/tmp",
stopWorkingLoader: vi.fn(),
resetPendingToolState: vi.fn(),
checkShutdownRequested: vi.fn(async () => {}),
+ setSessionHasMessages: vi.fn(),
+ clearShortcutGuide: vi.fn(),
+ addMessageToChat: vi.fn(),
};
Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);
return fakeThis;
@@ -171,6 +192,77 @@ describe("InteractiveMode streaming events", () => {
expect(fakeThis.streamingMessage).toBeUndefined();
});
+ test("renders one agent-run edit total only when files changed", async () => {
+ const fakeThis = createFakeInteractiveModeThis();
+ const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
+ const message = createAssistantMessage("");
+ message.content = [{ type: "toolCall", id: "edit-1", name: "edit", arguments: { path: "a.ts" } }];
+
+ await handleEvent.call(fakeThis, {
+ type: "turn_end",
+ message,
+ toolResults: [
+ {
+ role: "toolResult",
+ toolCallId: "edit-1",
+ toolName: "edit",
+ content: [],
+ details: { diff: "-1 old\n+1 new" },
+ isError: false,
+ timestamp: 0,
+ },
+ ],
+ });
+ await handleEvent.call(fakeThis, { type: "agent_end", messages: [] });
+ const recap = renderChat(fakeThis.recapContainer);
+ expect(recap).toContain("Recap: Updated files");
+ expect(recap).toContain("1 file changed | +1 -1");
+ expect(recap.indexOf("1 file changed")).toBeLessThan(recap.indexOf("Recap:"));
+ expect(renderChat(fakeThis.chatContainer)).not.toContain("file changed");
+
+ const unchanged = createFakeInteractiveModeThis();
+ await handleEvent.call(unchanged, { type: "agent_end", messages: [] });
+ expect(renderChat(unchanged.recapContainer)).not.toContain("file changed");
+ });
+
+ test("keeps edit totals across automatic retries", async () => {
+ const fakeThis = createFakeInteractiveModeThis();
+ fakeThis.agentRunFileChanges.set("/tmp/a.ts", { path: "a.ts", added: 1, removed: 1 });
+ fakeThis.getRetryAttempt = () => 1;
+ const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
+
+ await handleEvent.call(fakeThis, { type: "agent_start" });
+
+ expect([...fakeThis.agentRunFileChanges.values()]).toEqual([{ path: "a.ts", added: 1, removed: 1 }]);
+ });
+
+ test("keeps edit totals when compaction restarts the agent", async () => {
+ const fakeThis = createFakeInteractiveModeThis();
+ fakeThis.agentRunFileChanges.set("/tmp/a.ts", { path: "a.ts", added: 1, removed: 1 });
+ const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
+
+ await handleEvent.call(fakeThis, { type: "agent_start" });
+
+ expect([...fakeThis.agentRunFileChanges.values()]).toEqual([{ path: "a.ts", added: 1, removed: 1 }]);
+ });
+
+ test("clears edit totals when a new user prompt starts", async () => {
+ const fakeThis = createFakeInteractiveModeThis();
+ fakeThis.agentRunFileChanges.set("/tmp/a.ts", { path: "a.ts", added: 1, removed: 1 });
+ const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
+ await handleEvent.call(fakeThis, { type: "agent_end", messages: [] });
+ expect(renderChat(fakeThis.recapContainer)).toContain("1 file changed");
+
+ await handleEvent.call(fakeThis, {
+ type: "message_start",
+ message: { role: "user", content: "next task", timestamp: Date.now() },
+ });
+
+ expect(fakeThis.agentRunFileChanges.size).toBe(0);
+ expect(renderChat(fakeThis.recapContainer)).not.toContain("file changed");
+ expect(renderChat(fakeThis.recapContainer)).toContain("Recap: Updated files");
+ });
+
test("resolves input immediately after return to agents view was requested", async () => {
const getUserInput = (InteractiveMode.prototype as unknown as { getUserInput: GetUserInput }).getUserInput;
diff --git a/packages/coding-agent/test/ipython-bootstrap.test.ts b/packages/coding-agent/test/ipython-bootstrap.test.ts
index 2cc0ba6be8..caa5c3d18c 100644
--- a/packages/coding-agent/test/ipython-bootstrap.test.ts
+++ b/packages/coding-agent/test/ipython-bootstrap.test.ts
@@ -1,5 +1,5 @@
import { spawnSync } from "node:child_process";
-import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
@@ -74,4 +74,46 @@ describeIfKernel("IPython RLM bootstrap (real kernel)", () => {
await manager.dispose();
}
}, 60_000);
+
+ it("emits canonical paths for edits after the kernel changes directories", async () => {
+ const firstDir = join(dir, "first");
+ const secondDir = join(dir, "second");
+ mkdirSync(firstDir, { recursive: true });
+ mkdirSync(secondDir, { recursive: true });
+ writeFileSync(join(firstDir, "same.txt"), "old");
+ writeFileSync(join(secondDir, "same.txt"), "old");
+ const editSkillRoot = join(process.cwd(), "skills", "edit");
+ const manager = new KernelManager({
+ python: python as string,
+ cwd: dir,
+ env: { PYTHONPATH: join(editSkillRoot, "src") },
+ });
+ try {
+ await manager.start();
+ const bootstrap = await manager.execute(
+ buildRlmBootstrapCode([
+ {
+ name: "edit",
+ importName: "edit",
+ packagePath: editSkillRoot,
+ pyprojectPath: join(editSkillRoot, "pyproject.toml"),
+ },
+ ]),
+ );
+ expect(bootstrap.status).toBe("ok");
+
+ const first = await manager.execute(
+ 'import os\nos.chdir("first")\nawait edit(path="same.txt", old_str="old", new_str="new")',
+ );
+ const second = await manager.execute(
+ 'os.chdir("../second")\nawait edit(path="same.txt", old_str="old", new_str="new")',
+ );
+
+ expect(first.diffs?.[0]?.path).toBe(realpathSync(join(firstDir, "same.txt")));
+ expect(second.diffs?.[0]?.path).toBe(realpathSync(join(secondDir, "same.txt")));
+ expect(first.diffs?.[0]?.path).not.toBe(second.diffs?.[0]?.path);
+ } finally {
+ await manager.dispose();
+ }
+ }, 60_000);
});
diff --git a/packages/coding-agent/test/ipython-cell-diff.test.ts b/packages/coding-agent/test/ipython-cell-diff.test.ts
index 97d3973aff..826e089619 100644
--- a/packages/coding-agent/test/ipython-cell-diff.test.ts
+++ b/packages/coding-agent/test/ipython-cell-diff.test.ts
@@ -45,6 +45,8 @@ describe("IPythonCellComponent diff rendering", () => {
expect(out).toMatch(/10 .*alpha/);
// The redundant "Edited sample.py" confirmation must not render as its own line.
expect(out.split("\n").some((line) => /^\s*'?Edited sample\.py'?\s*$/.test(line.trim()))).toBe(false);
+ // Expanded edit cells still show the full source that produced the diff.
+ expect(out).toContain('await edit(path="sample.py", old_str="gamma", new_str="GAMMA")');
});
it("renders diff rows as full-width colored blocks", () => {
@@ -72,7 +74,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).split("\n");
// Summary line and header share the same single-space indent.
expect(done[0]).toMatch(/^ ✓ python/);
@@ -83,7 +85,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "error", diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
isError: true,
});
expect(failed).toMatch(/✗ a\.ts/);
@@ -97,7 +99,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: `${cwd}/src/app.ts`, oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
});
expect(inside).toContain("src/app.ts");
expect(inside).not.toContain(`${cwd}/src/app.ts`);
@@ -108,7 +110,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: "/etc/hosts", oldStr: "a", newStr: "b", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
});
expect(outside).toContain("/etc/hosts");
});
@@ -121,7 +123,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "const x = 1;", newStr: longLine, startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).render(width);
// No rendered row may exceed the terminal width (the TUI throws if one does).
@@ -142,7 +144,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: longPath, oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).render(width);
expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
const header = lines.map(stripAnsi).find((line) => line.includes("…"));
@@ -161,7 +163,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: "big.txt", oldStr, newStr, startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).render(80),
).not.toThrow();
});
@@ -173,7 +175,7 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "const x = 1;", newStr: longLine, startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).split("\n");
// The added line wraps; every row carrying its content shows a "+" gutter.
const addedRows = out.filter((line) => /arg\d/.test(line));
@@ -187,52 +189,39 @@ describe("IPythonCellComponent diff rendering", () => {
details: { status: "ok", durationMs: 4, diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
+ expanded: true,
}).split("\n");
- expect(out[0]).toContain("to expand");
+ expect(out[0]).toContain("to collapse");
expect(out[1].trim()).toBe("");
expect(out[2]).toContain("a.ts");
});
- it("shows the full diff in the collapsed view so file changes never hide behind expand", () => {
- const oldStr = Array.from({ length: 30 }, (_, i) => `row ${i}`).join("\n");
- const newStr = oldStr
- .split("\n")
- .map((line, i) => (i % 2 === 0 ? line.toUpperCase() : line))
- .join("\n");
-
+ it("hides the full diff when collapsed", () => {
const collapsed = renderCell({
code: "await edit(...)",
- details: { status: "ok", durationMs: 9, diffs: [{ path: "big.py", oldStr, newStr, startLine: 1 }] },
+ details: { status: "ok", diffs: [{ path: "big.py", oldStr: "old", newStr: "NEW", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
expanded: false,
});
expect(collapsed).toContain("to expand");
- expect(collapsed).toContain("big.py");
- expect(collapsed).toContain("ROW");
- // Every changed row is present — the diff is never truncated when collapsed.
- expect((collapsed.match(/\+.*ROW \d+/g) ?? []).length).toBe(15);
+ expect(collapsed).not.toContain("big.py");
+ expect(collapsed).not.toContain("NEW");
});
- it("renders multiple files' diffs in the collapsed view", () => {
- const collapsed = renderCell({
- code: "await edit(...); await edit(...)",
- details: {
- status: "ok",
- diffs: [
- { path: "a.py", oldStr: "one", newStr: "ONE", startLine: 1 },
- { path: "b.py", oldStr: "two", newStr: "TWO", startLine: 2 },
- ],
- },
+ it("hides edit source when collapsed and shows it when globally expanded", () => {
+ const state = {
+ code: 'hidden_side_effect = "only in full source"\nawait edit(path="a.py", old_str="old", new_str="new")',
+ details: { status: "ok", diffs: [{ path: "a.py", oldStr: "old", newStr: "new", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: false,
- });
- expect(collapsed).toContain("a.py");
- expect(collapsed).toContain("b.py");
- expect(collapsed).toContain("ONE");
- expect(collapsed).toContain("TWO");
+ };
+ const collapsed = renderCell({ ...state, expanded: false });
+ const expanded = renderCell({ ...state, expanded: true });
+
+ expect(collapsed).not.toContain("hidden_side_effect");
+ expect(expanded).toContain('hidden_side_effect = "only in full source"');
+ expect(expanded).toContain("a.py");
});
it("keeps non-edit cells collapsed to a single summary line", () => {
diff --git a/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts b/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts
index c025c23b83..65f554aac8 100644
--- a/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4533-preserve-recap.test.ts
@@ -8,6 +8,8 @@ type RecapRenderMode = {
recapContainer: Container;
childAgentPanelMode?: "detail";
sessionRecap?: string;
+ agentRunFileChanges: Map<string, never>;
+ isAgentStreaming: () => boolean;
ui: { requestRender: () => void };
};
@@ -27,6 +29,7 @@ type MessageStartMode = {
addMessageToChat: (message: AgentMessage) => void;
ui: { requestRender: () => void };
sessionRecap?: string;
+ agentRunFileChanges: Map<string, never>;
renderRecap: () => void;
updatePendingMessagesDisplay: () => void;
};
@@ -42,6 +45,8 @@ function createRenderMode(sessionRecap?: string): RecapRenderMode {
return Object.assign(Object.create(InteractiveMode.prototype), {
recapContainer: new Container(),
sessionRecap,
+ agentRunFileChanges: new Map(),
+ isAgentStreaming: () => false,
ui: { requestRender: vi.fn() },
}) as RecapRenderMode;
}
@@ -59,6 +64,7 @@ function createMessageStartMode(): MessageStartMode {
addMessageToChat: vi.fn(),
ui: { requestRender: vi.fn() },
sessionRecap: "previous recap",
+ agentRunFileChanges: new Map(),
renderRecap: vi.fn(),
updatePendingMessagesDisplay: vi.fn(),
}) as MessageStartMode;
@@ -90,7 +96,7 @@ describe("ENG-4533 recap layout", () => {
expect(mode.addMessageToChat).toHaveBeenCalledWith(message);
expect(mode.sessionRecap).toBe("previous recap");
- expect(mode.renderRecap).not.toHaveBeenCalled();
+ expect(mode.renderRecap).toHaveBeenCalledOnce();
expect(mode.updatePendingMessagesDisplay).not.toHaveBeenCalled();
});
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
new file mode 100644
index 0000000000..0a0bd43c63
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4583-latest-tool-expand-hint.test.ts
@@ -0,0 +1,83 @@
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
+import 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 { buildConversationComponents } from "../../../src/modes/interactive/components/conversation-components.js";
+import { ToolExecutionComponent } from "../../../src/modes/interactive/components/tool-execution.js";
+import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+const ipythonTool: AgentTool = {
+ name: "ipython",
+ label: "ipython",
+ description: "Execute a test IPython cell",
+ parameters: Type.Object({ code: Type.String() }),
+ execute: async () => ({
+ content: [{ type: "text", text: "ok" }],
+ details: { status: "ok", durationMs: 1 },
+ }),
+};
+
+describe("ENG-4583 latest tool expand hint", () => {
+ let harness: Harness | undefined;
+
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ afterEach(() => {
+ harness?.cleanup();
+ harness = undefined;
+ });
+
+ it("shows the expand or collapse hint only on the latest tool row", async () => {
+ harness = await createHarness({ tools: [ipythonTool] });
+ harness.setResponses([
+ fauxAssistantMessage(
+ [
+ fauxToolCall("ipython", { code: "1 + 1" }, { id: "tool-4583-a" }),
+ fauxToolCall("ipython", { code: "2 + 2" }, { id: "tool-4583-b" }),
+ ],
+ { stopReason: "toolUse" },
+ ),
+ fauxAssistantMessage(fauxToolCall("ipython", { code: "3 + 3" }, { id: "tool-4583-c" }), {
+ stopReason: "toolUse",
+ }),
+ fauxAssistantMessage("done"),
+ ]);
+
+ await harness.session.prompt("run three cells");
+
+ const components = buildConversationComponents(harness.session.messages, {
+ ui: { requestRender: vi.fn() } as unknown as TUI,
+ cwd: harness.tempDir,
+ toolOptions: { allowInlineImages: false },
+ getToolDefinition: () => undefined,
+ });
+ const tools = components.filter(
+ (component): component is ToolExecutionComponent => component instanceof ToolExecutionComponent,
+ );
+ const latest = tools.at(-1);
+
+ expect(tools).toHaveLength(3);
+ expect(latest).toBeDefined();
+ 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);
+
+ 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);
+ });
+});
+
+function render(components: readonly ToolExecutionComponent[]): string {
+ return components.map((component) => stripAnsi(component.render(120).join("\n"))).join("\n");
+}
diff --git a/packages/coding-agent/test/tool-execution-component.test.ts b/packages/coding-agent/test/tool-execution-component.test.ts
index cd1ac2955d..969eba028d 100644
--- a/packages/coding-agent/test/tool-execution-component.test.ts
+++ b/packages/coding-agent/test/tool-execution-component.test.ts
@@ -546,4 +546,98 @@ describe("ToolExecutionComponent parity", () => {
expect(rendered).toContain("custom_tool");
expect(rendered).toContain("done");
});
+ test("does not add built-in edit stats to custom IPython renderers", () => {
+ const component = new ToolExecutionComponent(
+ "ipython",
+ "custom-ipython",
+ {},
+ {},
+ {
+ ...createBaseToolDefinition("ipython"),
+ renderCall: () => new Text("custom ipython", 0, 0),
+ },
+ createFakeTui(),
+ process.cwd(),
+ );
+ component.updateResult({
+ content: [],
+ details: { diffs: [{ path: "README.md", oldStr: "before", newStr: "after" }] },
+ isError: false,
+ });
+
+ const rendered = stripAnsi(component.render(120).join("\n"));
+ expect(rendered).toContain("custom ipython");
+ expect(rendered).not.toContain("README.md +1 -1");
+ });
+
+ test("globally expands built-in IPython source associated with diffs", () => {
+ const component = new ToolExecutionComponent(
+ "ipython",
+ "tool-ipython-edit",
+ {
+ code: 'hidden_side_effect = "only in full source"\nawait edit(path="README.md", old_str="before", new_str="after")',
+ },
+ {},
+ undefined,
+ createFakeTui(),
+ process.cwd(),
+ );
+ component.markExecutionStarted();
+ component.setArgsComplete();
+ component.updateResult(
+ {
+ content: [],
+ details: {
+ status: "ok",
+ diffs: [{ path: "README.md", oldStr: "before", newStr: "after", startLine: 1 }],
+ },
+ isError: false,
+ },
+ false,
+ );
+
+ const collapsed = stripAnsi(component.render(120).join("\n"));
+ expect(collapsed).not.toContain("hidden_side_effect");
+ expect(collapsed).toContain("README.md +1 -1");
+
+ component.setExpanded(true);
+ const expanded = stripAnsi(component.render(120).join("\n"));
+ expect(expanded).toContain('hidden_side_effect = "only in full source"');
+ expect(expanded).toContain("before");
+ expect(expanded).toContain("after");
+ });
+
+ test("collapses built-in edit diffs to a one-line file stat", () => {
+ const component = new ToolExecutionComponent(
+ "edit",
+ "tool-collapsed-edit",
+ { path: "README.md", edits: [{ oldText: "before", newText: "after" }] },
+ {},
+ createEditToolDefinition(process.cwd()),
+ createFakeTui(),
+ process.cwd(),
+ );
+ component.setArgsComplete();
+ component.updateResult(
+ { content: [], details: { diff: "-1 before\n+1 after", firstChangedLine: 1 }, isError: false },
+ false,
+ );
+
+ const collapsed = stripAnsi(component.render(120).join("\n"));
+ expect(collapsed).toContain("╰─ README.md +1 -1");
+ expect(collapsed).toContain("to expand");
+ expect(collapsed).not.toContain("before");
+ expect(collapsed).not.toContain("after");
+
+ component.setShowExpandHint(false);
+ expect(stripAnsi(component.render(120).join("\n"))).not.toContain("to expand");
+
+ component.setShowExpandHint(true);
+ component.setExpanded(true);
+ const expanded = stripAnsi(component.render(120).join("\n"));
+ expect(expanded).toContain("before");
+ expect(expanded).toContain("after");
+ expect(expanded).toContain("to collapse");
+ expect(expanded).not.toContain("README.md +1 -1");
+ });
});