Skip to content

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

Rust

show edit diffs in the collapsed ipython view (#232)

kt86361749832c
diff --git a/packages/coding-agent/src/modes/interactive/components/diff.ts b/packages/coding-agent/src/modes/interactive/components/diff.ts
index c0ea50e57d..5e22bc1110 100644
--- a/packages/coding-agent/src/modes/interactive/components/diff.ts
+++ b/packages/coding-agent/src/modes/interactive/components/diff.ts
@@ -1,4 +1,4 @@
-import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
+import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
import * as Diff from "diff";
import { highlightCode, theme } from "../theme/theme.js";
@@ -171,6 +171,8 @@ function highlightContent(content: string, language: string | undefined): string
interface DiffLineSpec {
bg: ThemeBg;
gutter: string;
+ /** Gutter for wrapped continuation rows; defaults to blanks. */
+ contGutter?: string;
gutterFg: ThemeColor;
content: string;
language: string | undefined;
@@ -179,23 +181,37 @@ interface DiffLineSpec {
contentFg?: ThemeColor;
}
-/** Build one diff row filling `width` on a single background block. */
-function buildRichDiffLine(spec: DiffLineSpec): string {
- const styledGutter = theme.fg(spec.gutterFg, spec.gutter);
- const renderedContent = spec.contentFg
- ? theme.fg(spec.contentFg, spec.content)
- : highlightContent(spec.content, spec.language);
- let inner = `${styledGutter}${renderedContent}\x1b[39m`;
- if (visibleWidth(inner) > spec.width) {
- inner = truncateToWidth(inner, spec.width, "");
+function padToWidth(inner: string, width: number): string {
+ if (visibleWidth(inner) > width) {
+ inner = truncateToWidth(inner, width, "");
}
// Pad after truncating too: a 2-cell character straddling the cutoff leaves
// the result a cell short.
- const pad = spec.width - visibleWidth(inner);
- if (pad > 0) {
- inner += " ".repeat(pad);
+ const pad = width - visibleWidth(inner);
+ return pad > 0 ? inner + " ".repeat(pad) : inner;
+}
+
+// One diff line as one-or-more full-width background rows. Content wider than the
+// row wraps onto continuation rows with a blank gutter, so nothing is truncated.
+function buildRichDiffLine(spec: DiffLineSpec): string[] {
+ const renderedContent = spec.contentFg
+ ? theme.fg(spec.contentFg, spec.content)
+ : highlightContent(spec.content, spec.language);
+
+ const gutterWidth = visibleWidth(spec.gutter);
+ const contentWidth = Math.max(1, spec.width - gutterWidth);
+ const contentRows = wrapTextWithAnsi(renderedContent, contentWidth);
+ if (contentRows.length === 0) {
+ contentRows.push("");
}
- return theme.bg(spec.bg, inner);
+
+ const styledGutter = theme.fg(spec.gutterFg, spec.gutter);
+ const cont = spec.contGutter ?? " ".repeat(gutterWidth);
+ const styledCont = theme.fg(spec.gutterFg, cont);
+ return contentRows.map((row, index) => {
+ const gutter = index === 0 ? styledGutter : styledCont;
+ return theme.bg(spec.bg, padToWidth(`${gutter}${row}\x1b[39m`, spec.width));
+ });
}
export interface RichDiffOptions {
@@ -224,10 +240,11 @@ export function renderRichDiff(diffText: string, contentWidth: number, options:
const parsed = parseDiffLine(rawLine);
if (!parsed) {
rows.push(
- buildRichDiffLine({
+ ...buildRichDiffLine({
bg: "toolPanelBg",
gutterFg: "toolDiffContext",
- gutter: "",
+ // Leading space keeps the text off the edge while the bg still reaches it.
+ gutter: " ",
content: replaceTabs(rawLine),
language,
width,
@@ -236,35 +253,39 @@ export function renderRichDiff(diffText: string, contentWidth: number, options:
continue;
}
const { prefix, lineNum, content } = parsed;
- const gutter = `${lineNum} ${prefix === " " ? " " : prefix} `;
+ const gutter = ` ${lineNum} ${prefix === " " ? " " : prefix} `;
+ // Wrapped rows keep the +/- sign but drop the line number.
+ const contGutter = ` ${" ".repeat(lineNum.length)} ${prefix === " " ? " " : prefix} `;
const text = replaceTabs(content);
if (prefix === "+") {
rows.push(
- buildRichDiffLine({
+ ...buildRichDiffLine({
bg: useBlocks ? "toolDiffAddedBg" : "toolPanelBg",
gutterFg: "toolDiffAdded",
gutter,
+ contGutter,
content: text,
language,
width,
- contentFg: useBlocks ? undefined : "toolDiffAdded",
+ contentFg: useBlocks ? "toolDiffText" : "toolDiffAdded",
}),
);
} else if (prefix === "-") {
rows.push(
- buildRichDiffLine({
+ ...buildRichDiffLine({
bg: useBlocks ? "toolDiffRemovedBg" : "toolPanelBg",
gutterFg: "toolDiffRemoved",
gutter,
+ contGutter,
content: text,
language,
width,
- contentFg: useBlocks ? undefined : "toolDiffRemoved",
+ contentFg: useBlocks ? "toolDiffText" : "toolDiffRemoved",
}),
);
} else {
rows.push(
- buildRichDiffLine({
+ ...buildRichDiffLine({
bg: "toolPanelBg",
gutterFg: "toolDiffContext",
gutter,
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 3f9282aff2..af6ef9ad34 100644
--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
@@ -1,3 +1,4 @@
+import { isAbsolute, relative } from "node:path";
import {
type Component,
truncateToWidth,
@@ -6,11 +7,12 @@ import {
wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { generateDiffString } from "../../../core/tools/edit-diff.js";
+import { shortenPath } from "../../../core/tools/render-utils.js";
import { getLanguageFromPath, highlightCode, theme } from "../theme/theme.js";
import { normalizeErrorDetails, summarizeErrorDetails } from "./collapsible-error.js";
import { renderDiffSeparator, renderRichDiff } from "./diff.js";
import { keyHint } from "./keybinding-hints.js";
-import { TOOL_PANEL_PADDING_X, toolPanelContentWidth, toolPanelLine } from "./tool-panel.js";
+import { toolPanelContentWidth, toolPanelLine } from "./tool-panel.js";
export interface IPythonCellContentBlock {
type: string;
@@ -29,6 +31,8 @@ export interface IPythonCellState {
executionStarted?: boolean;
argsComplete?: boolean;
showImages?: boolean;
+ /** Session cwd — edit paths nested under it render relative, else absolute. */
+ cwd?: string;
}
interface DiffDisplay {
@@ -68,7 +72,6 @@ const CELL_MAGIC_PATTERN = /^\s*%%bash\b/;
const OUTPUT_PREVIEW_LINES = 5;
const INPUT_PREVIEW_LINES = 3;
-const DIFF_PREVIEW_LINES = 12;
// Cap so the trailing duration/counts stay visible on narrow widths.
const DESCRIPTOR_MAX_WIDTH = 64;
@@ -246,6 +249,18 @@ function hiddenLinesLabel(hidden: number): string {
return `… +${hidden} line${hidden === 1 ? "" : "s"}`;
}
+// Relative to the session cwd when nested under it, else the absolute path.
+function displayEditPath(path: string, cwd: string | undefined): string {
+ if (cwd && isAbsolute(path)) {
+ const rel = relative(cwd, path);
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
+ return rel;
+ }
+ return shortenPath(path);
+ }
+ return path;
+}
+
function isImageBlock(block: IPythonCellContentBlock): boolean {
return block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string";
}
@@ -322,9 +337,16 @@ export class IPythonCellComponent implements Component {
// Collapsed default: one line, indented to match message text. Cached by
// state version so it never re-renders on unrelated repaints (would flicker).
+ // Edits are the exception: the diff always shows in full under the summary
+ // line so file changes are visible without expanding.
if (!this.state.expanded) {
- const line = truncateToWidth(` ${this.collapsedLine(details)}`, safeWidth, "");
- return this.renderCache.set(safeWidth, this.stateVersion, [line]);
+ const summary = truncateToWidth(` ${this.collapsedLine(details)}`, safeWidth, "");
+ if ((details.diffs?.length ?? 0) === 0) {
+ return this.renderCache.set(safeWidth, this.stateVersion, [summary]);
+ }
+ const lines = [summary];
+ this.renderDiffs(lines, safeWidth, details.diffs ?? [], this.marker(details));
+ return this.renderCache.set(safeWidth, this.stateVersion, lines);
}
const lines: string[] = [];
@@ -556,21 +578,11 @@ export class IPythonCellComponent implements Component {
}
};
- // Group edits by file: one block per file, edits shown as `⋮`-separated hunks.
- const diffsByPath = new Map<string, DiffDisplay[]>();
- for (const diff of diffs) {
- const existing = diffsByPath.get(diff.path);
- if (existing) existing.push(diff);
- else diffsByPath.set(diff.path, [diff]);
- }
- let fileIndex = 0;
- for (const [path, edits] of diffsByPath) {
- startOutput();
- if (fileIndex > 0) {
- this.addBlank(lines, width);
- }
- fileIndex++;
- this.renderFileDiff(lines, width, path, edits, withExpandHint);
+ if (diffs.length > 0) {
+ // renderDiffs adds its own leading blank, so skip startOutput's to avoid
+ // a double gap; mark output started for the trailing text below.
+ outputStarted = true;
+ this.renderDiffs(lines, width, diffs, this.marker(details));
renderedTextOutput = true;
}
@@ -654,19 +666,31 @@ 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) {
+ const existing = diffsByPath.get(diff.path);
+ if (existing) existing.push(diff);
+ else diffsByPath.set(diff.path, [diff]);
+ }
+ for (const [path, edits] of diffsByPath) {
+ this.addPlain(lines, "");
+ this.renderFileDiff(lines, width, path, edits, marker);
+ }
+ }
+
private renderFileDiff(
lines: string[],
width: number,
path: string,
edits: readonly DiffDisplay[],
- withExpandHint: ExpandHintFormatter,
+ marker: string,
): void {
- const contentWidth = toolPanelContentWidth(width);
const language = getLanguageFromPath(path);
-
- const rows: string[] = [];
let added = 0;
let removed = 0;
+ const rows: string[] = [];
edits.forEach((edit, index) => {
const { diff: diffText } = generateDiffString(edit.oldStr, edit.newStr, 4, edit.startLine ?? 1);
for (const row of diffText.split("\n")) {
@@ -674,25 +698,23 @@ export class IPythonCellComponent implements Component {
else if (row.startsWith("-")) removed++;
}
if (index > 0) {
- rows.push(renderDiffSeparator(contentWidth));
+ rows.push(renderDiffSeparator(width));
+ }
+ // Append, not spread: a huge edit's diff can exceed the JS arg-count limit.
+ for (const row of renderRichDiff(diffText, width, { language })) {
+ rows.push(row);
}
- rows.push(...renderRichDiff(diffText, contentWidth, { language }));
});
const counts = `${theme.fg("toolDiffAdded", `+${added}`)} ${theme.fg("toolDiffRemoved", `-${removed}`)}`;
- this.addWrapped(lines, "", `${theme.fg("muted", "edit")} ${path} ${counts}`, width);
+ const displayPath = displayEditPath(path, this.state.cwd);
+ // Truncate the path (not the counts) so it can't push the header past width.
+ const fixed = visibleWidth(marker) + 1 + 2 + visibleWidth(counts);
+ const shownPath = truncateToWidth(displayPath, Math.max(1, width - 1 - fixed), "…");
+ this.addPlain(lines, `${marker} ${shownPath} ${counts}`);
- const expanded = this.state.expanded ?? false;
- const showCollapsed = !expanded && rows.length > DIFF_PREVIEW_LINES;
- const visibleRows = showCollapsed ? rows.slice(0, DIFF_PREVIEW_LINES) : rows;
- // Rows already fill the content width; just add the panel side padding.
- const sidePad = theme.bg("toolPanelBg", " ".repeat(TOOL_PANEL_PADDING_X));
- for (const row of visibleRows) {
- lines.push(sidePad + row + sidePad);
- }
- if (showCollapsed) {
- const hidden = rows.length - DIFF_PREVIEW_LINES;
- this.addWrapped(lines, "", withExpandHint(hiddenLinesLabel(hidden)), width);
+ for (const row of rows) {
+ lines.push(row);
}
}
@@ -737,4 +759,9 @@ export class IPythonCellComponent implements Component {
private addBlank(lines: string[], width: number): void {
lines.push(toolPanelLine("", width));
}
+
+ // No-background line, indented one space to align with the summary line above.
+ private addPlain(lines: string[], text: string): void {
+ lines.push(` ${text}`);
+ }
}
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 8e2bcf18aa..5a4259051b 100644
--- a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
+++ b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts
@@ -265,6 +265,7 @@ export class ToolExecutionComponent extends Container {
executionStarted: this.executionStarted,
argsComplete: this.argsComplete,
showImages: this.showImages,
+ cwd: this.cwd,
};
if (!this.ipythonCellComponent) {
this.ipythonCellComponent = new IPythonCellComponent(state);
diff --git a/packages/coding-agent/src/modes/interactive/theme/dark.json b/packages/coding-agent/src/modes/interactive/theme/dark.json
index 0d90a5f7df..342efc81b7 100644
--- a/packages/coding-agent/src/modes/interactive/theme/dark.json
+++ b/packages/coding-agent/src/modes/interactive/theme/dark.json
@@ -61,6 +61,7 @@
"toolDiffAdded": "#3fb950",
"toolDiffRemoved": "#f85149",
+ "toolDiffText": "#9aa0a6",
"toolDiffContext": "gray",
"syntaxComment": "#6A9955",
diff --git a/packages/coding-agent/src/modes/interactive/theme/light.json b/packages/coding-agent/src/modes/interactive/theme/light.json
index 80bff5cfc7..fa75668844 100644
--- a/packages/coding-agent/src/modes/interactive/theme/light.json
+++ b/packages/coding-agent/src/modes/interactive/theme/light.json
@@ -60,6 +60,7 @@
"toolDiffAdded": "green",
"toolDiffRemoved": "red",
+ "toolDiffText": "#57606a",
"toolDiffContext": "mediumGray",
"syntaxComment": "#008000",
diff --git a/packages/coding-agent/src/modes/interactive/theme/prime.json b/packages/coding-agent/src/modes/interactive/theme/prime.json
index 1c9252a0c6..9234278279 100644
--- a/packages/coding-agent/src/modes/interactive/theme/prime.json
+++ b/packages/coding-agent/src/modes/interactive/theme/prime.json
@@ -65,6 +65,7 @@
"mdListBullet": "muted",
"toolDiffAdded": "#3fb950",
"toolDiffRemoved": "#f85149",
+ "toolDiffText": "#9aa0a6",
"toolDiffContext": "muted",
"syntaxComment": "muted",
"syntaxKeyword": "info",
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 2f2ffa3533..bd64afe9fd 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
+++ b/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
@@ -72,6 +72,7 @@
"mdListBullet",
"toolDiffAdded",
"toolDiffRemoved",
+ "toolDiffText",
"toolDiffContext",
"syntaxComment",
"syntaxKeyword",
@@ -239,6 +240,10 @@
"$ref": "#/$defs/colorValue",
"description": "Removed lines in tool diffs"
},
+ "toolDiffText": {
+ "$ref": "#/$defs/colorValue",
+ "description": "Diff line content on colored add/remove blocks"
+ },
"toolDiffContext": {
"$ref": "#/$defs/colorValue",
"description": "Context lines in tool diffs"
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme.ts b/packages/coding-agent/src/modes/interactive/theme/theme.ts
index 83de347200..9e2a8da79d 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme.ts
+++ b/packages/coding-agent/src/modes/interactive/theme/theme.ts
@@ -77,6 +77,7 @@ const ThemeJsonSchema = Type.Object({
// Tool Diffs (3 colors)
toolDiffAdded: ColorValueSchema,
toolDiffRemoved: ColorValueSchema,
+ toolDiffText: ColorValueSchema,
toolDiffContext: ColorValueSchema,
// Syntax Highlighting (9 colors)
syntaxComment: ColorValueSchema,
@@ -152,6 +153,7 @@ export type ThemeColor =
| "mdListBullet"
| "toolDiffAdded"
| "toolDiffRemoved"
+ | "toolDiffText"
| "toolDiffContext"
| "syntaxComment"
| "syntaxKeyword"
diff --git a/packages/coding-agent/test/ipython-cell-diff.test.ts b/packages/coding-agent/test/ipython-cell-diff.test.ts
index de3537e1d7..d6e6350af4 100644
--- a/packages/coding-agent/test/ipython-cell-diff.test.ts
+++ b/packages/coding-agent/test/ipython-cell-diff.test.ts
@@ -7,6 +7,10 @@ function stripAnsi(text: string): string {
return text.replace(/\x1b\[[0-9;]*m/g, "");
}
+function hasBackground(line: string): boolean {
+ return /\x1b\[4[0-9]m|\x1b\[48[;:]/.test(line);
+}
+
function renderCell(state: ConstructorParameters<typeof IPythonCellComponent>[0]): string {
return stripAnsi(new IPythonCellComponent(state).render(80).join("\n"));
}
@@ -16,7 +20,7 @@ describe("IPythonCellComponent diff rendering", () => {
initTheme("dark");
});
- it("renders a streamed diff with absolute line numbers and suppresses the Edited confirmation", () => {
+ it("renders a diff with absolute line numbers and suppresses the Edited confirmation", () => {
const out = renderCell({
code: 'await edit(path="sample.py", old_str="gamma", new_str="GAMMA")',
details: {
@@ -31,19 +35,21 @@ describe("IPythonCellComponent diff rendering", () => {
expanded: true,
});
- // Header carries the path and the +/- line counts.
- expect(out).toContain("edit sample.py");
+ // Header carries the path (no "edit" label) and the +/- line counts.
+ expect(out).toContain("sample.py");
+ expect(out).not.toMatch(/edit sample\.py/);
expect(out).toMatch(/\+1\s+-1/);
- // Removed line keeps the old line number + content; added line the new one.
- expect(out).toMatch(/11 -.*gamma/);
- expect(out).toMatch(/11 \+.*GAMMA/);
+ // Removed line keeps the old line number; added line the new one.
+ expect(out).toMatch(/11 - .*gamma/);
+ expect(out).toMatch(/11 \+ .*GAMMA/);
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);
});
- it("pads every diff row to the full content width on a single background block", () => {
- const out = new IPythonCellComponent({
+ it("renders diff rows as full-width colored blocks", () => {
+ const width = 72;
+ const lines = new IPythonCellComponent({
code: "await edit(...)",
details: {
status: "ok",
@@ -52,29 +58,143 @@ describe("IPythonCellComponent diff rendering", () => {
executionStarted: true,
argsComplete: true,
expanded: true,
- }).render(72);
- // Every rendered line is exactly the panel width (no ragged backgrounds).
- expect(out.every((line) => stripAnsi(line).length === 72)).toBe(true);
+ }).render(width);
+ const diffRows = lines.filter((line) => /alpha|gamma|GAMMA/.test(stripAnsi(line)));
+ expect(diffRows.length).toBeGreaterThan(0);
+ // Each changed row is a background block spanning the full width.
+ expect(diffRows.every((line) => visibleWidth(line) === width)).toBe(true);
+ expect(diffRows.some(hasBackground)).toBe(true);
});
- it("keeps full width when a wide character straddles the truncation boundary", () => {
- // CJK chars are 2 cells wide; a narrow render forces truncation mid-character.
- const wide = "値".repeat(60);
- const out = new IPythonCellComponent({
+ it("prefixes the header with the cell's status marker and aligns it with the summary line", () => {
+ const done = renderCell({
code: "await edit(...)",
- details: {
- status: "ok",
- diffs: [{ path: "a.py", oldStr: "x = 1", newStr: `x = "${wide}"`, startLine: 1 }],
- },
+ details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
executionStarted: true,
argsComplete: true,
- expanded: true,
- }).render(40);
- // Measure display cells, not code units (CJK chars are 2 cells wide).
- expect(out.every((line) => visibleWidth(line) === 40)).toBe(true);
+ expanded: false,
+ }).split("\n");
+ // Summary line and header share the same single-space indent.
+ expect(done[0]).toMatch(/^ ✓ python/);
+ expect(done.find((l) => l.includes("a.ts"))).toMatch(/^ ✓ a\.ts/);
+
+ const failed = renderCell({
+ code: "await edit(...)",
+ details: { status: "error", diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ isError: true,
+ });
+ expect(failed).toMatch(/✗ a\.ts/);
+ });
+
+ it("renders an edit path relative to the session cwd, or absolute when outside it", () => {
+ const cwd = "/home/me/project";
+ const inside = renderCell({
+ code: "await edit(...)",
+ cwd,
+ details: { status: "ok", diffs: [{ path: `${cwd}/src/app.ts`, oldStr: "x", newStr: "X", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ });
+ expect(inside).toContain("src/app.ts");
+ expect(inside).not.toContain(`${cwd}/src/app.ts`);
+
+ const outside = renderCell({
+ code: "await edit(...)",
+ cwd,
+ details: { status: "ok", diffs: [{ path: "/etc/hosts", oldStr: "a", newStr: "b", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ });
+ expect(outside).toContain("/etc/hosts");
+ });
+
+ it("wraps a long diff line across rows without truncating or overflowing the width", () => {
+ const width = 92;
+ const longLine = `const x = ${Array.from({ length: 30 }, (_, i) => `arg${i}`).join(", ")};`;
+ const lines = new IPythonCellComponent({
+ code: "await edit(...)",
+ details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "const x = 1;", newStr: longLine, startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ }).render(width);
+
+ // No rendered row may exceed the terminal width (the TUI throws if one does).
+ expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
+ // The full content survives across the wrapped rows (nothing truncated away).
+ const joined = lines.map(stripAnsi).join("");
+ expect(joined).toContain("arg0");
+ expect(joined).toContain("arg29");
+ // The added line spilled onto at least one continuation row.
+ expect(lines.filter((line) => /arg\d/.test(stripAnsi(line))).length).toBeGreaterThan(1);
+ });
+
+ it("truncates a long header path so it never overflows the width, keeping the counts", () => {
+ const width = 40;
+ const longPath = `src/${"very-long-directory-name/".repeat(8)}file.ts`;
+ const lines = new IPythonCellComponent({
+ code: "await edit(...)",
+ details: { status: "ok", diffs: [{ path: longPath, oldStr: "x", newStr: "X", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ }).render(width);
+ expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
+ const header = lines.map(stripAnsi).find((line) => line.includes("…"));
+ expect(header).toBeDefined();
+ // The +/- counts survive truncation; only the path is shortened.
+ expect(header).toMatch(/\+1 -1\s*$/);
});
- it("collapses a long diff and shows an expand hint", () => {
+ it("renders a large diff without spreading the row array (no RangeError)", () => {
+ const n = 5000;
+ const oldStr = Array.from({ length: n }, (_, i) => `line ${i}`).join("\n");
+ const newStr = Array.from({ length: n }, (_, i) => `LINE ${i}`).join("\n");
+ expect(() =>
+ new IPythonCellComponent({
+ code: "await edit(...)",
+ details: { status: "ok", diffs: [{ path: "big.txt", oldStr, newStr, startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ }).render(80),
+ ).not.toThrow();
+ });
+
+ it("repeats the +/- sign on wrapped continuation rows", () => {
+ const longLine = `const x = ${Array.from({ length: 20 }, (_, i) => `arg${i}`).join(", ")};`;
+ const out = renderCell({
+ code: "await edit(...)",
+ details: { status: "ok", diffs: [{ path: "a.ts", oldStr: "const x = 1;", newStr: longLine, startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ }).split("\n");
+ // The added line wraps; every row carrying its content shows a "+" gutter.
+ const addedRows = out.filter((line) => /arg\d/.test(line));
+ expect(addedRows.length).toBeGreaterThan(1);
+ expect(addedRows.every((line) => /^\s*\+ /.test(line) || /\d+ \+ /.test(line))).toBe(true);
+ });
+
+ it("separates the diff from the summary line with a blank line", () => {
+ const out = renderCell({
+ code: "await edit(...)",
+ details: { status: "ok", durationMs: 4, diffs: [{ path: "a.ts", oldStr: "x", newStr: "X", startLine: 1 }] },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ }).split("\n");
+ expect(out[0]).toContain("to expand");
+ 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")
@@ -88,26 +208,18 @@ describe("IPythonCellComponent diff rendering", () => {
argsComplete: true,
expanded: false,
});
- // Collapsed is a single line: the diff itself is hidden behind the expand hint.
expect(collapsed).toContain("to expand");
- expect(collapsed).not.toContain("ROW");
-
- const expanded = renderCell({
- code: "await edit(...)",
- details: { status: "ok", durationMs: 9, diffs: [{ path: "big.py", oldStr, newStr, startLine: 1 }] },
- executionStarted: true,
- argsComplete: true,
- expanded: true,
- });
- expect(expanded).toContain("ROW");
+ 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);
});
- it("renders multiple diffs from a single cell", () => {
- const out = renderCell({
+ it("renders multiple files' diffs in the collapsed view", () => {
+ const collapsed = renderCell({
code: "await edit(...); await edit(...)",
details: {
status: "ok",
- durationMs: 5,
diffs: [
{ path: "a.py", oldStr: "one", newStr: "ONE", startLine: 1 },
{ path: "b.py", oldStr: "two", newStr: "TWO", startLine: 2 },
@@ -115,10 +227,26 @@ describe("IPythonCellComponent diff rendering", () => {
},
executionStarted: true,
argsComplete: true,
- expanded: true,
+ expanded: false,
});
- expect(out).toContain("edit a.py");
- expect(out).toContain("edit b.py");
+ expect(collapsed).toContain("a.py");
+ expect(collapsed).toContain("b.py");
+ expect(collapsed).toContain("ONE");
+ expect(collapsed).toContain("TWO");
+ });
+
+ it("keeps non-edit cells collapsed to a single summary line", () => {
+ const collapsed = renderCell({
+ code: "print('hello')",
+ details: { status: "ok", durationMs: 3, stdout: "hello\nworld\nmore\noutput\nlines" },
+ executionStarted: true,
+ argsComplete: true,
+ expanded: false,
+ });
+ // No diffs → the collapsed view stays a single line; output hides behind expand.
+ expect(collapsed.split("\n")).toHaveLength(1);
+ expect(collapsed).toContain("to expand");
+ expect(collapsed).not.toContain("world");
});
it("coalesces multiple edits to one file into a single block with hunk separators", () => {
@@ -137,10 +265,9 @@ describe("IPythonCellComponent diff rendering", () => {
argsComplete: true,
});
// One consolidated header for the file, with summed counts.
- expect(out.split("\n").filter((l) => l.includes("edit app.py")).length).toBe(1);
- expect(out).toMatch(/edit app\.py\s+\+3\s+-3/);
- // Non-adjacent hunks are separated by the vertical-ellipsis marker.
- expect(out).toContain("⋮");
+ expect(out.split("\n").filter((l) => l.includes("app.py")).length).toBe(1);
+ expect(out).toMatch(/app\.py\s+\+3\s+-3/);
+ // Hunks are separated by the vertical-ellipsis marker.
expect((out.match(/⋮/g) ?? []).length).toBe(2);
});
});