Skip to content

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

Rust

Add improved code previews for bash and python tool calls. (#248)

az9767d27bcdae
diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.ts
index 1d6591d45f..0e17eb3d10 100644
--- a/packages/coding-agent/src/core/tools/bash.ts
+++ b/packages/coding-agent/src/core/tools/bash.ts
@@ -15,6 +15,7 @@ import {
untrackDetachedChildPid,
} from "../../utils/shell.js";
import type { ToolDefinition, ToolRenderResultOptions } from "../extensions/types.js";
+import { previewBashCommand } from "./code-preview.js";
import { OutputAccumulator } from "./output-accumulator.js";
import { getTextOutput, invalidArgText, str } from "./render-utils.js";
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
@@ -181,7 +182,16 @@ function formatBashCall(args: { command?: string; timeout?: number } | undefined
const command = str(args?.command);
const timeout = args?.timeout as number | undefined;
const timeoutSuffix = timeout ? theme.fg("muted", ` (timeout ${timeout}s)`) : "";
- const commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg("toolOutput", "...");
+ let commandDisplay: string;
+ if (command === null) {
+ commandDisplay = invalidArgText(theme);
+ } else if (command) {
+ const preview = previewBashCommand(command);
+ const label = preview.language === "bash" ? "" : `${preview.language}: `;
+ commandDisplay = preview.text ? `${label}${preview.text}` : command;
+ } else {
+ commandDisplay = theme.fg("toolOutput", "...");
+ }
return theme.fg("toolTitle", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;
}
diff --git a/packages/coding-agent/src/core/tools/code-preview.ts b/packages/coding-agent/src/core/tools/code-preview.ts
new file mode 100644
index 0000000000..6865b1b13f
--- /dev/null
+++ b/packages/coding-agent/src/core/tools/code-preview.ts
@@ -0,0 +1,442 @@
+const DESCRIPTOR_MAX_WIDTH = 64;
+
+const CELL_MAGIC_PATTERN = /^\s*%%bash\b/;
+const MAGIC_LINE_PATTERN = /^\s*!/;
+const COMMENT_LINE_PATTERN = /^\s*#/;
+const CD_PREFIX_PATTERN = /^\s*cd\s+([^&;|]+)(?:&&|;)\s*/;
+const BASH_SET_PATTERN = /^\s*set\s+[-+][A-Za-z]*(?:\s+[-+]?\w+)*(?:\s+pipefail)?\s*$/;
+const BASH_SETUP_PATTERN = /^(?:export\s+\w+=|source\s+\S+|\.\s+\S+)/;
+const PYTHON_IMPORT_PATTERN = /^\s*(?:import\s+\S|from\s+\S+\s+import\s+)/;
+const PYTHON_DECORATOR_PATTERN = /^\s*@/;
+const PYTHON_DEFINITION_PATTERN = /^\s*(?:async\s+def|def|class)\s+/;
+const PYTHON_MAIN_PATTERN = /^\s*if\s+__name__\s*==\s*['"]__main__['"]\s*:/;
+const PYTHON_CONTROL_PATTERN = /^\s*(?:if|elif|else|for|while|with|try|except|finally)\b.*:\s*$/;
+const PYTHON_CALL_PATTERN = /^\s*(?:await\s+)?[A-Za-z_][A-Za-z0-9_.]*\s*\(/;
+const PYTHON_LOW_SIGNAL_CALL_PATTERN = /^\s*(?:await\s+)?(?:print|len|str|repr|int|float|list|dict|set|tuple)\s*\(/;
+const PYTHON_ASSIGNMENT_CALL_PATTERN =
+ /^\s*[A-Za-z_][A-Za-z0-9_]*(?:\s*:\s*[^=]+)?\s*=\s*(?:await\s+)?[A-Za-z_][A-Za-z0-9_.]*\s*\(/;
+const PYTHON_LOW_SIGNAL_ASSIGNMENT_CALL_PATTERN =
+ /^\s*[A-Za-z_][A-Za-z0-9_]*(?:\s*:\s*[^=]+)?\s*=\s*(?:await\s+)?(?:Path|pathlib\.Path|json\.loads|json\.dumps|str|int|float|list|dict|set|tuple)\s*\(/;
+const PYTHON_EFFECT_CALL_PATTERN =
+ /^\s*(?:await\s+)?[A-Za-z_][A-Za-z0-9_.]*\.(?:write_text|write_bytes|mkdir|unlink|rename|replace|touch|append|extend|update|add|remove|discard|close|commit|execute|run)\s*\(/;
+const HEREDOC_PATTERN = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
+const PATH_ASSIGN_PATTERN = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:Path|pathlib\.Path)\(["']([^"']+)["']\)/;
+const STRING_ASSIGN_PATTERN = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*["']([^"']+)["']/;
+
+export type CodePreviewLanguage = "bash" | "python";
+
+export interface CodePreview {
+ language: CodePreviewLanguage;
+ text: string;
+}
+
+interface PreviewCandidate {
+ language: CodePreviewLanguage;
+ text: string;
+ score: number;
+ index: number;
+}
+
+function collapseWhitespace(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+function truncateDescriptor(text: string): string {
+ if (text.length <= DESCRIPTOR_MAX_WIDTH) {
+ return text;
+ }
+ return `${text.slice(0, DESCRIPTOR_MAX_WIDTH - 1).trimEnd()}…`;
+}
+
+function redactNoise(text: string): string {
+ return text
+ .replace(/[A-Za-z0-9+/]{80,}={0,2}/g, "<blob>")
+ .replace(/\b((?=\w*(?:token|key|secret|password))[A-Za-z_]\w*)\s*=\s*(["'])[^"']*\2/gi, "$1=<redacted>")
+ .replace(
+ /\b((?=\w*(?:token|key|secret|password))[A-Za-z_]\w*)\s*=\s*(?!<redacted>)(?!["'])\S+/gi,
+ "$1=<redacted>",
+ )
+ .replace(/(["'])sk-[^"']+\1/g, "$1<redacted>$1")
+ .replace(/(["']).{160,}\1/g, "$1…$1");
+}
+
+function descriptor(text: string): string {
+ return truncateDescriptor(collapseWhitespace(redactNoise(text)));
+}
+
+function stripBashPrefix(line: string): string {
+ return line.replace(MAGIC_LINE_PATTERN, "").trim().replace(CD_PREFIX_PATTERN, "").trim();
+}
+
+function isSkippableBashLine(line: string): boolean {
+ const trimmed = line.trim();
+ return (
+ !trimmed ||
+ COMMENT_LINE_PATTERN.test(trimmed) ||
+ BASH_SET_PATTERN.test(trimmed) ||
+ BASH_SETUP_PATTERN.test(trimmed)
+ );
+}
+
+function shellWords(line: string): string[] {
+ const words: string[] = [];
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g;
+ for (const match of line.matchAll(pattern)) {
+ words.push(match[1] ?? match[2] ?? match[3] ?? "");
+ }
+ return words;
+}
+
+function pathTail(path: string): string {
+ return path.replace(/^\.\//, "");
+}
+
+function simplifyRunnerCommand(line: string): string | undefined {
+ const words = shellWords(line);
+ const joined = words.join(" ");
+ const vitestIndex = words.findIndex((word) => /(?:^|\/)vitest\/dist\/cli\.js$/.test(word));
+ if (words[0] === "npx" && words[1] === "tsx" && vitestIndex >= 2) {
+ return `vitest ${words.slice(vitestIndex + 1).join(" ")}`.trim();
+ }
+ if (words[0] === "npm") {
+ const prefixIndex = words.indexOf("--prefix");
+ const cwd = prefixIndex >= 0 ? words[prefixIndex + 1] : undefined;
+ const runIndex = words.indexOf("run");
+ if (runIndex >= 0 && words[runIndex + 1]) {
+ const command = `npm ${words[runIndex + 1]} ${words.slice(runIndex + 2).join(" ")}`.trim();
+ return cwd ? `${command} (${pathTail(cwd)})` : command;
+ }
+ }
+ if (words[0] === "pnpm") {
+ const cwdIndex = words.findIndex((word) => word === "-C" || word === "--dir");
+ const cwd = cwdIndex >= 0 ? words[cwdIndex + 1] : undefined;
+ const rest = words.filter((_, index) => index !== cwdIndex && index !== cwdIndex + 1);
+ return cwd ? `${rest.join(" ")} (${pathTail(cwd)})` : undefined;
+ }
+ const pytestIndex = words.findIndex(
+ (word, index) => word === "pytest" || (word === "pytest" && words[index - 1] === "-m"),
+ );
+ if (words[0] === "uv" && words[1] === "run" && pytestIndex >= 0) {
+ return `pytest ${words.slice(pytestIndex + 1).join(" ")}`.trim();
+ }
+ if ((words[0] === "python" || words[0] === "python3") && words[1] === "-m" && words[2] === "pytest") {
+ return `pytest ${words.slice(3).join(" ")}`.trim();
+ }
+ if (joined.includes("node_modules/.bin/")) {
+ return joined.replace(/\S*node_modules\/\.bin\//g, "");
+ }
+ return undefined;
+}
+
+function simplifyMutationCommand(line: string): string | undefined {
+ const words = shellWords(line);
+ if (words.length === 0) return undefined;
+ if (words[0] === "cat" && words[1] === ">" && words[2]) return `write ${pathTail(words[2])}`;
+ if (words[0] === "tee" && words.at(-1))
+ return `${words.includes("-a") ? "append" : "write"} ${pathTail(words.at(-1) ?? "")}`;
+ if (words[0] === "apply_patch") return "apply patch";
+ if (["rm", "mv", "cp", "git", "npm"].includes(words[0] ?? "")) return line;
+ if (
+ (words[0] === "sed" && words.some((word) => word.startsWith("-i"))) ||
+ (words[0] === "perl" && words.includes("-pi"))
+ ) {
+ return line;
+ }
+ return undefined;
+}
+
+function simplifyBashCommandLine(line: string): string {
+ return simplifyRunnerCommand(line) ?? simplifyMutationCommand(line) ?? line;
+}
+
+function splitCommandChain(line: string): string[] {
+ return line
+ .split(/\s*(?:&&|;)\s*/)
+ .map((part) => part.trim())
+ .filter(Boolean);
+}
+
+function heredocBody(lines: readonly string[], startIndex: number, delimiter: string): string | undefined {
+ // While args stream, preview the partial heredoc body rather than the low-signal heredoc opener.
+ const body: string[] = [];
+ for (let i = startIndex + 1; i < lines.length; i++) {
+ const line = lines[i] ?? "";
+ if (line.trim() === delimiter) {
+ return body.join("\n");
+ }
+ body.push(line);
+ }
+ return body.length > 0 ? body.join("\n") : undefined;
+}
+
+function previewHeredoc(lines: readonly string[]): CodePreview | undefined {
+ // A generic heredoc body is low-signal; keep it as a fallback and prefer a
+ // later, more specific heredoc (python/bash/node/write) if one follows.
+ let fallback: CodePreview | undefined;
+ for (let i = 0; i < lines.length; i++) {
+ const line = stripBashPrefix(lines[i] ?? "");
+ if (isSkippableBashLine(line)) {
+ continue;
+ }
+ const heredocMatch = line.match(HEREDOC_PATTERN);
+ const delimiter = heredocMatch?.[1];
+ if (!delimiter) {
+ continue;
+ }
+ const body = heredocBody(lines, i, delimiter);
+ if (!body) {
+ continue;
+ }
+ if (/\b(?:uv\s+run\s+)?python3?\b/.test(line)) {
+ const preview = previewPythonCode(body);
+ if (preview.text) {
+ return preview;
+ }
+ continue;
+ }
+ // Match bash/sh as an interpreter word (incl. /bin/sh), not a path suffix like script.sh.
+ if (/(?<![\w.])(?:bash|sh)\b/.test(line)) {
+ const preview = previewBashCommand(body);
+ return preview.text ? preview : { language: "bash", text: descriptor(body) };
+ }
+ if (/\bnode\b/.test(line)) {
+ return { language: "bash", text: `node: ${descriptor(body)}` };
+ }
+ const catWrite = line.match(/\b(?:cat|tee)\b.*(?:>|\s)(\S+)\s*<<-?/);
+ if (catWrite?.[1]) {
+ return { language: "bash", text: `${line.includes("tee -a") ? "append" : "write"} ${pathTail(catWrite[1])}` };
+ }
+ if (/\bapply_patch\b/.test(line)) {
+ return { language: "bash", text: "apply patch" };
+ }
+ fallback ??= { language: "bash", text: descriptor(body) };
+ }
+ return fallback;
+}
+
+function bashLineScore(line: string, index: number): number {
+ const simplified = simplifyBashCommandLine(line);
+ const words = shellWords(line);
+ let score = 30;
+ if (simplified !== line) score += 40;
+ if (["rm", "mv", "cp", "git", "npm", "pnpm", "pytest", "vitest"].includes(words[0] ?? "")) score += 20;
+ if (/\b(?:rm|mv|cp|git\s+(?:add|commit)|npm\s+install|sed\s+-i|perl\s+-pi|tee|cat\s*>|apply_patch)\b/.test(line))
+ score += 40;
+ return score + index;
+}
+
+export function previewBashCommand(command: string): CodePreview {
+ const lines = command.split("\n");
+ const heredoc = previewHeredoc(lines);
+ if (heredoc?.text) {
+ return { language: heredoc.language, text: descriptor(heredoc.text) };
+ }
+
+ let best: PreviewCandidate | undefined;
+ let index = 0;
+ for (const rawLine of lines) {
+ for (const rawPart of splitCommandChain(rawLine)) {
+ const commandLine = stripBashPrefix(rawPart.trim());
+ if (!commandLine || isSkippableBashLine(commandLine)) {
+ continue;
+ }
+ const candidate = {
+ language: "bash" as const,
+ text: simplifyBashCommandLine(commandLine),
+ score: bashLineScore(commandLine, index),
+ index,
+ };
+ if (!best || candidate.score > best.score) {
+ best = candidate;
+ }
+ index += 1;
+ }
+ }
+ return { language: "bash", text: best ? descriptor(best.text) : "" };
+}
+
+function isSkippablePythonLine(line: string): boolean {
+ const trimmed = line.trim();
+ return !trimmed || COMMENT_LINE_PATTERN.test(trimmed) || PYTHON_IMPORT_PATTERN.test(trimmed);
+}
+
+function pythonIndent(line: string): number {
+ const match = line.match(/^\s*/);
+ return match?.[0].length ?? 0;
+}
+
+function pythonPrintInnerCall(line: string): string | undefined {
+ const printMatch = line.trim().match(/^print\((.*)\)$/);
+ const inner = printMatch?.[1]?.trim();
+ return inner && PYTHON_CALL_PATTERN.test(inner) ? inner : undefined;
+}
+
+function pythonPathVars(lines: readonly string[]): Map<string, string> {
+ const vars = new Map<string, string>();
+ for (const line of lines) {
+ const pathMatch = line.match(PATH_ASSIGN_PATTERN) ?? line.match(STRING_ASSIGN_PATTERN);
+ if (pathMatch?.[1] && pathMatch[2]?.includes("/")) {
+ vars.set(pathMatch[1], pathMatch[2]);
+ }
+ }
+ return vars;
+}
+
+function pythonFileOperation(line: string, paths: ReadonlyMap<string, string>): string | undefined {
+ const match = line
+ .trim()
+ .match(
+ /^(?:await\s+)?([A-Za-z_][A-Za-z0-9_]*)\.(write_text|write_bytes|read_text|read_bytes|mkdir|unlink|rename|replace|touch)\s*\(/,
+ );
+ if (!match?.[1] || !match[2]) return undefined;
+ const path = paths.get(match[1]);
+ if (!path) return undefined;
+ const action: Record<string, string> = {
+ write_text: "write",
+ write_bytes: "write",
+ read_text: "read",
+ read_bytes: "read",
+ mkdir: "mkdir",
+ unlink: "delete",
+ rename: "rename",
+ replace: "replace",
+ touch: "touch",
+ };
+ return `${action[match[2]] ?? match[2]} ${pathTail(path)}`;
+}
+
+function pythonSubprocessCommand(line: string): string | undefined {
+ const trimmed = line.trim();
+ const shellMatch = trimmed.match(/subprocess\.(?:run|check_call|check_output|Popen)\(\s*["`]([^"`]+)["`]/);
+ if (shellMatch?.[1]) return simplifyBashCommandLine(shellMatch[1]);
+ const listMatch = trimmed.match(/subprocess\.(?:run|check_call|check_output|Popen)\(\s*\[([^\]]+)\]/);
+ if (listMatch?.[1]) {
+ const words = [...listMatch[1].matchAll(/["']([^"']+)["']/g)].map((match) => match[1] ?? "");
+ return simplifyBashCommandLine(words.join(" "));
+ }
+ return undefined;
+}
+
+function simplifyPythonPreviewLine(line: string, paths: ReadonlyMap<string, string>): string {
+ return (
+ pythonFileOperation(line, paths) ?? pythonSubprocessCommand(line) ?? pythonPrintInnerCall(line) ?? line.trim()
+ );
+}
+
+function pythonPreviewLine(lines: readonly string[], index: number, paths: ReadonlyMap<string, string>): string {
+ const line = lines[index] ?? "";
+ if (index > 0 && PYTHON_DEFINITION_PATTERN.test(line)) {
+ const previous = lines[index - 1] ?? "";
+ if (PYTHON_DECORATOR_PATTERN.test(previous.trim())) {
+ return `${previous.trim()} ${line.trim()}`;
+ }
+ }
+ if (PYTHON_CONTROL_PATTERN.test(line)) {
+ const childIndex = firstPythonChildLine(lines, index);
+ if (childIndex !== undefined) {
+ return `${line.trim().replace(/:\s*$/, ":")} ${simplifyPythonPreviewLine(lines[childIndex] ?? "", paths)}`;
+ }
+ }
+ return simplifyPythonPreviewLine(line, paths);
+}
+
+function firstPythonChildLine(lines: readonly string[], parentIndex: number): number | undefined {
+ const parentIndent = pythonIndent(lines[parentIndex] ?? "");
+ for (let i = parentIndex + 1; i < lines.length; i++) {
+ const line = lines[i] ?? "";
+ if (isSkippablePythonLine(line) || PYTHON_DECORATOR_PATTERN.test(line.trim())) {
+ continue;
+ }
+ if (pythonIndent(line) <= parentIndent) {
+ return undefined;
+ }
+ return i;
+ }
+ return undefined;
+}
+
+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)) {
+ return -1;
+ }
+ if (pythonFileOperation(line, paths)) {
+ return 95;
+ }
+ if (pythonSubprocessCommand(line)) {
+ return 90;
+ }
+ if (PYTHON_MAIN_PATTERN.test(line)) {
+ return 70;
+ }
+ if (PYTHON_EFFECT_CALL_PATTERN.test(line)) {
+ return 80;
+ }
+ if (PYTHON_CONTROL_PATTERN.test(line)) {
+ const childIndex = firstPythonChildLine(lines, index);
+ return childIndex === undefined ? 20 : Math.max(20, pythonLineScore(lines, childIndex, paths) - 5);
+ }
+ if (PYTHON_DEFINITION_PATTERN.test(line)) {
+ return 50;
+ }
+ if (PYTHON_LOW_SIGNAL_ASSIGNMENT_CALL_PATTERN.test(line)) {
+ return 25;
+ }
+ const printInnerCall = pythonPrintInnerCall(line);
+ if (printInnerCall && !PYTHON_LOW_SIGNAL_CALL_PATTERN.test(printInnerCall)) {
+ return 55;
+ }
+ if (PYTHON_ASSIGNMENT_CALL_PATTERN.test(line)) {
+ return 60;
+ }
+ if (PYTHON_CALL_PATTERN.test(line) && !PYTHON_LOW_SIGNAL_CALL_PATTERN.test(line)) {
+ return 65;
+ }
+ if (PYTHON_CALL_PATTERN.test(line)) {
+ return 15;
+ }
+ return 30;
+}
+
+function pythonPreviewIndex(lines: readonly string[], index: number): number {
+ const line = lines[index] ?? "";
+ if (!PYTHON_CONTROL_PATTERN.test(line)) {
+ return index;
+ }
+ const childIndex = firstPythonChildLine(lines, index);
+ return childIndex === undefined ? index : pythonPreviewIndex(lines, childIndex);
+}
+
+export function previewPythonCode(code: string): CodePreview {
+ const lines = code.split("\n");
+ const paths = pythonPathVars(lines);
+ let bestIndex: number | undefined;
+ let bestScore = -1;
+
+ for (let i = 0; i < lines.length; i++) {
+ const score = pythonLineScore(lines, i, paths);
+ if (score > bestScore) {
+ bestIndex = i;
+ bestScore = score;
+ }
+ }
+
+ if (bestIndex !== undefined && bestScore >= 0) {
+ const previewIndex = pythonPreviewIndex(lines, bestIndex);
+ return {
+ language: "python",
+ text: descriptor(pythonPreviewLine(lines, previewIndex, paths)),
+ };
+ }
+ return { language: "python", text: "" };
+}
+
+export function previewIpythonCode(code: string): CodePreview {
+ const trimmedCode = code.trimEnd();
+ const lines = trimmedCode.split("\n");
+ if (CELL_MAGIC_PATTERN.test(lines[0] ?? "")) {
+ return previewBashCommand(lines.slice(1).join("\n"));
+ }
+ return previewPythonCode(trimmedCode);
+}
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 858ae17f40..557e4aae26 100644
--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
@@ -6,6 +6,7 @@ import {
visibleWidth,
wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
+import { previewIpythonCode } from "../../../core/tools/code-preview.js";
import { generateDiffString } from "../../../core/tools/edit-diff.js";
import { shortenPath } from "../../../core/tools/render-utils.js";
import { getLanguageFromPath, highlightCode, theme } from "../theme/theme.js";
@@ -74,13 +75,6 @@ const CELL_MAGIC_PATTERN = /^\s*%%bash\b/;
const OUTPUT_PREVIEW_LINES = 5;
const INPUT_PREVIEW_LINES = 3;
-// Cap so the trailing duration/counts stay visible on narrow widths.
-const DESCRIPTOR_MAX_WIDTH = 64;
-
-const COMMENT_LINE_PATTERN = /^\s*#/;
-// Strip a leading `cd … &&` to surface the real command.
-const CD_PREFIX_PATTERN = /^\s*cd\s+[^&;|]+(?:&&|;)\s*/;
-
const SGR_PATTERN = /\x1b\[([0-9;]*)m/g;
/**
@@ -118,36 +112,6 @@ function closeOpenSgr(line: string): string {
return fgOpen || bgOpen ? `${line}\x1b[0m` : line;
}
-function collapseWhitespace(text: string): string {
- return text.replace(/\s+/g, " ").trim();
-}
-
-function truncateDescriptor(text: string): string {
- if (text.length <= DESCRIPTOR_MAX_WIDTH) {
- return text;
- }
- return `${text.slice(0, DESCRIPTOR_MAX_WIDTH - 1).trimEnd()}…`;
-}
-
-/** Leading meaningful command of a cell; "" while code is still streaming. */
-function summarizeCell(code: string): string {
- const lines = code.split("\n");
- const isBashCell = CELL_MAGIC_PATTERN.test(lines[0] ?? "");
- const body = isBashCell ? lines.slice(1) : lines;
- for (const rawLine of body) {
- const trimmed = rawLine.trim();
- if (!trimmed || COMMENT_LINE_PATTERN.test(trimmed)) {
- continue;
- }
- const command = trimmed.replace(MAGIC_LINE_PATTERN, "").trim();
- if (!command) {
- continue;
- }
- return truncateDescriptor(collapseWhitespace(command.replace(CD_PREFIX_PATTERN, "")));
- }
- return "";
-}
-
export function getIpythonCodeFromArgs(args: unknown): string {
if (!args || typeof args !== "object" || !("code" in args)) {
return "";
@@ -373,19 +337,17 @@ export class IPythonCellComponent implements Component {
return this.renderCache.set(safeWidth, cacheVersion, lines);
}
- // Command is bash-only: python first-lines are usually imports/setup, not intent.
private collapsedLine(details: IpythonDetails): string {
const code = this.state.code.trimEnd();
const isBashCell = CELL_MAGIC_PATTERN.test(code.split("\n")[0] ?? "");
- const parts = [`${this.marker(details)} ${theme.fg("muted", isBashCell ? "bash" : "python")}`];
-
- if (isBashCell) {
- const command = summarizeCell(code);
- if (command) {
- parts.push(this.highlightInputLine(command, true));
- } else if (!this.state.executionStarted) {
- parts.push(theme.fg("muted", "waiting for code"));
- }
+ const preview = previewIpythonCode(code);
+ const languageLabel = isBashCell && preview.language !== "bash" ? `bash · ${preview.language}` : preview.language;
+ const parts = [`${this.marker(details)} ${theme.fg("muted", languageLabel)}`];
+
+ if (preview.text) {
+ parts.push(this.highlightInputLine(preview.text, preview.language === "bash"));
+ } else if (!this.state.executionStarted) {
+ parts.push(theme.fg("muted", "waiting for code"));
}
const counts = this.lineCounts(details);
diff --git a/packages/coding-agent/test/code-preview.test.ts b/packages/coding-agent/test/code-preview.test.ts
new file mode 100644
index 0000000000..3ec121ae74
--- /dev/null
+++ b/packages/coding-agent/test/code-preview.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest";
+import { previewBashCommand, previewIpythonCode, previewPythonCode } from "../src/core/tools/code-preview.js";
+
+describe("code preview", () => {
+ it("skips bash setup and previews the real command", () => {
+ expect(previewBashCommand("set -e\nnpm run check")).toEqual({ language: "bash", text: "npm check" });
+ });
+
+ it("simplifies common runner wrappers", () => {
+ expect(
+ previewBashCommand("npx tsx ../../node_modules/vitest/dist/cli.js --run test/code-preview.test.ts"),
+ ).toEqual({
+ language: "bash",
+ text: "vitest --run test/code-preview.test.ts",
+ });
+ });
+
+ it("unwraps python heredocs in bash", () => {
+ const command = `set -e
+python3 - <<'PY'
+from pathlib import Path
+path = Path("package.json")
+text = path.read_text()
+path.write_text(text)
+PY`;
+ expect(previewBashCommand(command)).toEqual({ language: "python", text: "path.write_text(text)" });
+ });
+
+ it("unwraps bash cells in ipython", () => {
+ const code = `%%bash
+set -e
+python3 - <<'PY'
+import json
+data = json.loads("{}")
+print(data.keys())
+PY`;
+ expect(previewIpythonCode(code)).toEqual({ language: "python", text: "data.keys()" });
+ });
+
+ it("prefers meaningful python effects over setup assignments", () => {
+ const code = `from pathlib import Path
+p = Path("packages/coding-agent/src/modes/interactive/components/ipython-cell.ts")
+txt = p.read_text()
+p.write_text(txt.replace("old", "new"))`;
+ expect(previewPythonCode(code)).toEqual({
+ language: "python",
+ text: "write packages/coding-agent/src/modes/interactive/components/ip…",
+ });
+ });
+
+ it("handles stronger bash heuristics", () => {
+ expect(previewBashCommand("cd packages/coding-agent && npm --prefix ../.. run check")).toEqual({
+ language: "bash",
+ text: "npm check (../..)",
+ });
+ expect(previewBashCommand("echo setup\ngit add packages/foo.ts")).toEqual({
+ language: "bash",
+ text: "git add packages/foo.ts",
+ });
+ expect(previewBashCommand("cat > packages/foo.ts <<'EOF'\nhello\nEOF")).toEqual({
+ language: "bash",
+ text: "write packages/foo.ts",
+ });
+ });
+
+ it("extracts python subprocesses and control-block effects", () => {
+ const subprocessCode = `import subprocess
+subprocess.run(["npm", "run", "check"])
+`;
+ expect(previewPythonCode(subprocessCode)).toEqual({ language: "python", text: "npm check" });
+
+ const controlCode = `from pathlib import Path
+p = Path("packages/foo.ts")
+if p.exists():
+ p.unlink()
+`;
+ expect(previewPythonCode(controlCode)).toEqual({ language: "python", text: "delete packages/foo.ts" });
+ });
+
+ it("prefers executable calls over helper definitions", () => {
+ const code = `def helper():
+ return 1
+run_check()
+`;
+ expect(previewPythonCode(code)).toEqual({ language: "python", text: "run_check()" });
+ });
+
+ it("redacts sensitive python preview values", () => {
+ expect(previewPythonCode('password = "supersecretvalue"')).toEqual({
+ language: "python",
+ text: "password=<redacted>",
+ });
+ expect(previewPythonCode('client = OpenAI(api_key="sk-testsecretvalue")')).toEqual({
+ language: "python",
+ text: "client = OpenAI(api_key=<redacted>)",
+ });
+ });
+
+ it("falls back when heredoc has no useful preview", () => {
+ const command = `npm run check
+python3 - <<'PY'
+import json
+from pathlib import Path
+PY`;
+ expect(previewBashCommand(command)).toEqual({ language: "bash", text: "npm check" });
+ });
+
+ it("continues past empty python heredocs", () => {
+ const command = `python3 - <<'PY'
+import json
+from pathlib import Path
+PY
+python3 - <<'PY'
+from pathlib import Path
+p = Path("packages/foo.ts")
+p.write_text("hello")
+PY`;
+ expect(previewBashCommand(command)).toEqual({ language: "python", text: "write packages/foo.ts" });
+ });
+
+ it("does not treat a .sh script path as an inline bash heredoc", () => {
+ const command = `./script.sh <<'EOF'
+hello world
+EOF`;
+ // The .sh suffix must not trigger the bash-interpreter branch; preview the body.
+ expect(previewBashCommand(command)).toEqual({ language: "bash", text: "hello world" });
+ });
+
+ it("prefers a later meaningful heredoc over an earlier generic one", () => {
+ const command = `cat <<'CFG'
+key=value
+CFG
+python3 - <<'PY'
+from pathlib import Path
+p = Path("packages/foo.ts")
+p.write_text("hello")
+PY`;
+ expect(previewBashCommand(command)).toEqual({ language: "python", text: "write packages/foo.ts" });
+ });
+});
diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.ts
index 2e264a871b..9d3d6afeb3 100644
--- a/packages/coding-agent/test/marquee-components.test.ts
+++ b/packages/coding-agent/test/marquee-components.test.ts
@@ -242,8 +242,8 @@ describe("marquee TUI components", () => {
const component = new IPythonCellComponent(state);
const collapsed = stripAnsi(component.render(100).join("\n"));
- // Collapsed python shows no code — just the input line count and expand hint.
- expect(collapsed).not.toContain("line_0 = 0");
+ // Collapsed python shows a one-line preview, the input line count, and the expand hint.
+ 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);
@@ -321,19 +321,19 @@ describe("marquee TUI components", () => {
};
const component = new IPythonCellComponent(state);
- const collapsed = component.render(80);
+ const collapsed = component.render(100);
const collapsedText = stripAnsi(collapsed.join("\n"));
expect(collapsedText).toContain("Ctrl+O to expand");
expect(collapsedText).not.toContain("traceback collapsed");
expect(collapsedText).not.toContain('File "<stdin>"');
component.update({ ...state, expanded: true });
- const expanded = component.render(80);
+ const expanded = component.render(100);
expect(expanded).not.toBe(collapsed);
const expandedText = stripAnsi(expanded.join("\n"));
expect(expandedText).toContain("Traceback (most recent call last):");
expect(expandedText).toContain('File "<stdin>"');
- expect(component.render(80)).toBe(expanded);
+ expect(component.render(100)).toBe(expanded);
});
test("renders sub-agent tree nodes with status, previews, and transcript expansion", async () => {