xonecas.io
64875
Mc

mini-coder / commit 67f38c9

feat: show diffs when the models change files with bash

xonecas2026-09-28 67f38c9bbd54aa0a66108a3ccc9328aa219caa59 parent cedf815

7 files changed

package-lock.json+2−2
@@ -1,12 +1,12 @@
11 {
22 "name": "mini-coder",
3- "version": "0.8.0",
3+ "version": "0.8.1",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "mini-coder",
9- "version": "0.8.0",
9+ "version": "0.8.1",
1010 "license": "MIT",
1111 "dependencies": {
1212 "@earendil-works/pi-ai": "0.87.0",
src/agent.ts+9−3
@@ -14,7 +14,7 @@ import {
1414 } from "@earendil-works/pi-ai";
1515 import type { Session } from "./session.ts";
1616 import type { ToolName } from "./config.ts";
17-import { acceptsImages, executeTool, type ToolResult } from "./tools/index.ts";
17+import { acceptsImages, executeTool, type FileDiff, type ToolResult } from "./tools/index.ts";
1818
1919 export type Phase = "preparing" | "waitingModel" | "streaming" | "runningTool" | "pausing" | "idle";
2020
@@ -25,7 +25,7 @@ export type AgentEvent =
2525 | { type: "toolCallStart"; name: string }
2626 | { type: "toolCall"; name: string; arguments: JsonObject }
2727 | { type: "toolOutput"; chunk: string }
28- | { type: "toolResult"; name: string; text: string; isError: boolean }
28+ | { type: "toolResult"; name: string; text: string; isError: boolean; diffs?: FileDiff[] }
2929 | { type: "message"; message: AssistantMessage }
3030 | { type: "error"; message: string }
3131 | { type: "cancelled" }
@@ -203,7 +203,13 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
203203 };
204204 messages.push(toolMessage);
205205 session.appendMessage(toolMessage);
206- onEvent({ type: "toolResult", name: call.name, text: result.text, isError: result.isError });
206+ onEvent({
207+ type: "toolResult",
208+ name: call.name,
209+ text: result.text,
210+ isError: result.isError,
211+ diffs: result.diffs,
212+ });
207213 }
208214 steer(held.join("\n"));
209215 }
src/tools/bash.ts+5−1
@@ -1,6 +1,7 @@
11 import { spawn } from "node:child_process";
22 import { Type, type Static } from "@earendil-works/pi-ai";
33 import type { ToolContext, ToolResult } from "./common.ts";
4+import { diffTrees, snapshot } from "./snapshot.ts";
45
56 export const BASH_PARAMS = Type.Object(
67 { command: Type.String({ description: "Command to run" }) },
@@ -14,6 +15,8 @@ const TRUNCATED = "\n\n... output truncated ...\n\n";
1415
1516 export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
1617 return new Promise((resolve) => {
18+ const startMs = Date.now();
19+ const before = snapshot();
1720 const child = spawn("bash", ["-c", args.command], {
1821 cwd: process.cwd(),
1922 detached: true,
@@ -50,7 +53,8 @@ export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
5053 const exit = code ?? (ctx.signal.aborted ? "aborted" : "unknown");
5154 const body = truncated ? head + TRUNCATED + tail : head + tail;
5255 const text = body + (body.endsWith("\n") || body === "" ? "" : "\n") + `exit code: ${exit}`;
53- resolve({ text, isError: code !== 0 });
56+ const diffs = diffTrees(before, snapshot(startMs));
57+ resolve({ text, isError: code !== 0, diffs });
5458 };
5559
5660 let killTimer: NodeJS.Timeout | undefined;
src/tools/common.ts+12−0
@@ -7,9 +7,21 @@ export interface ToolContext {
77 onOutput?: (chunk: string) => void;
88 }
99
10+/** One changed file, display-only; never reaches the model. */
11+export interface FileDiff {
12+ /** Path relative to the working directory. */
13+ path: string;
14+ /** Unified diff body; absent when content cannot be tracked. */
15+ patch?: string;
16+ /** Why no patch is available, e.g. "binary file changed". */
17+ note?: string;
18+}
19+
1020 export interface ToolResult {
1121 text: string;
1222 isError: boolean;
1323 /** Image blocks appended to the tool result, after `text`. */
1424 images?: ImageContent[];
25+ /** Files the tool changed under the working directory, for display only. */
26+ diffs?: FileDiff[];
1527 }
src/tools/index.ts+1−1
@@ -5,7 +5,7 @@ import { BASH_PARAMS, bash, type BashArgs } from "./bash.ts";
55 import { EDIT_PARAMS, edit, type EditArgs } from "./edit.ts";
66 import { READ_PARAMS, read, type ReadArgs } from "./read.ts";
77
8-export type { ToolResult } from "./common.ts";
8+export type { FileDiff, ToolResult } from "./common.ts";
99
1010 /** Whether a model accepts image input. Drives `read`'s description and results. */
1111 export function acceptsImages(model: Model<Api>): boolean {
src/tools/snapshot.ts+171−0
@@ -0,0 +1,171 @@
1+import { type Dirent, lstatSync, readFileSync, readdirSync, type Stats } from "node:fs";
2+import { join, relative } from "node:path";
3+import { createTwoFilesPatch } from "diff";
4+import type { FileDiff } from "./common.ts";
5+
6+const MAX_FILE_BYTES = 1 << 20;
7+const MAX_TOTAL_BYTES = 32 << 20;
8+const BINARY_SNIFF = 8192;
9+
10+const IGNORED_DIRS = new Set([
11+ ".git",
12+ ".hg",
13+ ".svn",
14+ "node_modules",
15+ ".venv",
16+ "venv",
17+ "__pycache__",
18+ ".mypy_cache",
19+ ".pytest_cache",
20+]);
21+
22+type Kind = "text" | "binary" | "large" | "link" | "untracked";
23+
24+interface FileState {
25+ size: number;
26+ mtimeMs: number;
27+ ino: number;
28+ kind: Kind;
29+ content: string | null;
30+}
31+
32+/** Relpath -> state. A shallow copy, safe against later captures. */
33+export type Tree = Map<string, FileState>;
34+
35+interface Entry {
36+ rel: string;
37+ abs: string;
38+ size: number;
39+ mtimeMs: number;
40+ ino: number;
41+ link: boolean;
42+}
43+
44+function* walk(): Generator<Entry> {
45+ const root = process.cwd();
46+ const stack = [root];
47+ while (stack.length > 0) {
48+ const dir = stack.pop()!;
49+ let entries: Dirent[];
50+ try {
51+ entries = readdirSync(dir, { withFileTypes: true });
52+ } catch {
53+ continue;
54+ }
55+ for (const dirent of entries) {
56+ const abs = join(dir, dirent.name);
57+ if (dirent.isDirectory()) {
58+ if (!IGNORED_DIRS.has(dirent.name)) stack.push(abs);
59+ continue;
60+ }
61+ const link = dirent.isSymbolicLink();
62+ if (!link && !dirent.isFile()) continue;
63+ let stat: Stats;
64+ try {
65+ stat = lstatSync(abs);
66+ } catch {
67+ continue;
68+ }
69+ yield { rel: relative(root, abs), abs, size: stat.size, mtimeMs: stat.mtimeMs, ino: stat.ino, link };
70+ }
71+ }
72+}
73+
74+function build(entry: Entry, overBudget: boolean): FileState {
75+ const base = { size: entry.size, mtimeMs: entry.mtimeMs, ino: entry.ino };
76+ if (entry.size > MAX_FILE_BYTES) return { ...base, kind: "large", content: null };
77+ if (overBudget) return { ...base, kind: "untracked", content: null };
78+ let buffer;
79+ try {
80+ buffer = readFileSync(entry.abs);
81+ } catch {
82+ return { ...base, kind: "untracked", content: null };
83+ }
84+ if (buffer.subarray(0, BINARY_SNIFF).includes(0)) return { ...base, kind: "binary", content: null };
85+ return { ...base, kind: "text", content: buffer.toString("utf8") };
86+}
87+
88+type StatKey = Pick<FileState, "size" | "mtimeMs" | "ino">;
89+
90+function sameStat(a: StatKey, b: StatKey): boolean {
91+ return a.size === b.size && a.mtimeMs === b.mtimeMs && a.ino === b.ino;
92+}
93+
94+/**
95+ * Caches file content across calls, keyed by the stat triple `(size, mtimeMs,
96+ * ino)`, so a second capture only reads what the stat walk shows as changed.
97+ */
98+class SnapshotCache {
99+ private cache = new Map<string, FileState>();
100+
101+ capture(forceSinceMs?: number): Tree {
102+ const next: Tree = new Map();
103+ let total = 0;
104+ for (const entry of walk()) {
105+ const cached = this.cache.get(entry.rel);
106+ const forced = forceSinceMs !== undefined && entry.mtimeMs >= forceSinceMs;
107+ const reuse = !entry.link && !forced && cached !== undefined && sameStat(cached, entry);
108+ const state = reuse
109+ ? cached!
110+ : entry.link
111+ ? { size: entry.size, mtimeMs: entry.mtimeMs, ino: entry.ino, kind: "link" as const, content: null }
112+ : build(entry, total >= MAX_TOTAL_BYTES);
113+ if (state.content !== null) total += state.size;
114+ next.set(entry.rel, state);
115+ }
116+ this.cache = next;
117+ return new Map(next);
118+ }
119+}
120+
121+let cache: SnapshotCache | undefined;
122+
123+/** Captures the working tree, re-reading content only when its stat key moved. */
124+export function snapshot(forceSinceMs?: number): Tree {
125+ cache ??= new SnapshotCache();
126+ return cache.capture(forceSinceMs);
127+}
128+
129+function patch(path: string, before: string, after: string): string {
130+ return createTwoFilesPatch(path, path, before, after, "", "", { context: 3 });
131+}
132+
133+function noteFor(kind: Kind, verb: string): string {
134+ if (kind === "binary") return `binary file ${verb}`;
135+ if (kind === "large") return `large file ${verb}`;
136+ return `file not tracked (${verb})`;
137+}
138+
139+function diffOne(path: string, before: FileState | undefined, after: FileState | undefined): FileDiff | null {
140+ if (before === undefined) {
141+ if (after!.kind === "link") return { path, note: "symlink created" };
142+ return after!.content === null
143+ ? { path, note: noteFor(after!.kind, "created") }
144+ : { path, patch: patch(path, "", after!.content) };
145+ }
146+ if (after === undefined) {
147+ if (before.kind === "link") return { path, note: "symlink removed" };
148+ return before.content === null
149+ ? { path, note: noteFor(before.kind, "deleted") }
150+ : { path, patch: patch(path, before.content, "") };
151+ }
152+ if (before.kind === "link" || after.kind === "link") {
153+ return sameStat(before, after) ? null : { path, note: "symlink changed" };
154+ }
155+ if (before.content !== null && after.content !== null) {
156+ return before.content === after.content ? null : { path, patch: patch(path, before.content, after.content) };
157+ }
158+ if (sameStat(before, after)) return null;
159+ return { path, note: noteFor(after.content === null ? after.kind : before.kind, "changed") };
160+}
161+
162+/** The files that differ between two captures, sorted for stable output. */
163+export function diffTrees(before: Tree, after: Tree): FileDiff[] {
164+ const paths = new Set([...before.keys(), ...after.keys()]);
165+ const diffs: FileDiff[] = [];
166+ for (const path of [...paths].sort()) {
167+ const diff = diffOne(path, before.get(path), after.get(path));
168+ if (diff !== null) diffs.push(diff);
169+ }
170+ return diffs;
171+}
src/tui/tui.ts+27−3
@@ -13,7 +13,7 @@ import {
1313 type UserMessage,
1414 } from "@earendil-works/pi-ai";
1515 import { runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
16-import { acceptsImages, toolSchemas } from "../tools/index.ts";
16+import { acceptsImages, toolSchemas, type FileDiff } from "../tools/index.ts";
1717 import { Terminal, expandTabs, sanitize, wrapLine, type Key } from "./term.ts";
1818 import { Editor } from "./editor.ts";
1919 import { completeCommand, findCommand, type Command, type CommandContext } from "./commands.ts";
@@ -88,6 +88,26 @@ function resultLines(name: string, text: string, isError: boolean): BodyLine[] {
8888 return lines.map((line) => (diff ? diffLine(line) : { text: line }));
8989 }
9090
91+/**
92+ * Styled lines for a `bash` call's changed files: one label per file, then its
93+ * patch body with the file headers stripped, or a note when no patch exists.
94+ * Shown in full, like `edit`.
95+ */
96+function diffRows(diffs: FileDiff[]): BodyLine[] {
97+ const out: BodyLine[] = [];
98+ for (const d of diffs) {
99+ out.push({ text: d.path, style: cyan });
100+ if (d.patch !== undefined) {
101+ const lines = d.patch.trimEnd().split("\n");
102+ while (lines.length > 0 && EDIT_HEADER.test(lines[0])) lines.shift();
103+ for (const line of lines) out.push(diffLine(line));
104+ } else if (d.note !== undefined) {
105+ out.push({ text: d.note, style: dim });
106+ }
107+ }
108+ return out;
109+}
110+
91111 /**
92112 * Wraps plain text, then styles each row: styling after the break is what lets a
93113 * continuation row inherit its source line's style. A continuation row carries
@@ -565,7 +585,7 @@ class Tui {
565585 break;
566586 case "toolResult":
567587 this.activity.reset();
568- this.commitToolResult(event.name, event.text, event.isError);
588+ this.commitToolResult(event.name, event.text, event.isError, event.diffs);
569589 break;
570590 case "error":
571591 this.endTurn(red(`! ${event.message}`));
@@ -614,7 +634,7 @@ class Tui {
614634 this.streamed = "";
615635 }
616636
617- private commitToolResult(name: string, text: string, isError: boolean): void {
637+ private commitToolResult(name: string, text: string, isError: boolean, diffs?: FileDiff[]): void {
618638 const call = this.pendingCalls.shift();
619639 this.separator = true;
620640 if (call !== undefined) this.commitLines([call]);
@@ -626,6 +646,10 @@ class Tui {
626646 const prefix = isError && i === rows.length - 1 ? ERROR_CHROME : BODY_CHROME;
627647 this.push(prefix + rows[i]);
628648 }
649+ if (diffs !== undefined && diffs.length > 0) {
650+ this.separator = true;
651+ for (const row of renderRows(diffRows(diffs), width)) this.push(BODY_CHROME + row);
652+ }
629653 this.separator = true;
630654 }