Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Windows: port the live diff engine (DiffEngine.swift) to TypeScript

Claude4b0a411a4ca7
diff --git a/windows/src/core/diff.ts b/windows/src/core/diff.ts
new file mode 100644
index 00000000..477471de
--- /dev/null
+++ b/windows/src/core/diff.ts
@@ -0,0 +1,326 @@
+// Live diff — port of DiffEngine.swift (NotchBuddy/Sources/CoucouKit).
+//
+// Line diff (LCS) with 3-line context hunks, used for the Edit / MultiEdit /
+// Write tool calls the hooks see. Same size guards as macOS: beyond 200 KB or
+// 4 000 lines, or when the LCS table would pass a million cells, only the
+// +N −M counts are kept and the diff is marked `tooLarge`.
+//
+// Also home to `toOneLine` (Claude's final message → one line of plain text)
+// and the diff step encoding the ticker reads.
+
+export type DiffKind = "context" | "added" | "removed";
+
+export interface DiffLine {
+ kind: DiffKind;
+ text: string;
+ /** 1-based; -1 for pure adds. */
+ origLine: number;
+ /** 1-based; -1 for pure removes. */
+ newLine: number;
+}
+
+export interface DiffHunk {
+ origStart: number;
+ newStart: number;
+ lines: DiffLine[];
+}
+
+export interface FileDiff {
+ /** Stable identifier assigned by State.appendSessionDiff. */
+ id: number;
+ path: string;
+ added: number;
+ removed: number;
+ hunks: DiffHunk[];
+ tooLarge: boolean;
+ /** True when produced by fromNew (Write tool). */
+ isNewFile: boolean;
+}
+
+/** FileDiff.maxBytes / maxLines on macOS. */
+export const DIFF_MAX_BYTES = 200 * 1024;
+export const DIFF_MAX_LINES = 4000;
+/** LCS is O(m·n): bail out before the quadratic blowup. */
+const DIFF_MAX_CELLS = 1_000_000;
+const CONTEXT = 3;
+
+const encoder = new TextEncoder();
+const utf8Length = (s: string) => encoder.encode(s).length;
+
+/** Last path component, Windows or POSIX separators. */
+export function fileName(path: string): string {
+ const cleaned = path.replace(/[\\/]+$/, "");
+ const idx = Math.max(cleaned.lastIndexOf("\\"), cleaned.lastIndexOf("/"));
+ return idx >= 0 ? cleaned.slice(idx + 1) : cleaned;
+}
+
+// ── Public API ────────────────────────────────────────────────────────────────
+
+export function fromEdit(oldText: string, newText: string, path: string): FileDiff {
+ if (utf8Length(oldText) + utf8Length(newText) > DIFF_MAX_BYTES) {
+ return countFallback(oldText, newText, path);
+ }
+ const oldLines = splitLines(oldText);
+ const newLines = splitLines(newText);
+ if (oldLines.length + newLines.length > DIFF_MAX_LINES) {
+ return countFallback(oldText, newText, path);
+ }
+ if (oldLines.length * newLines.length > DIFF_MAX_CELLS) {
+ return countFallback(oldText, newText, path);
+ }
+ const flat = buildDiffLines(oldLines, newLines);
+ let added = 0;
+ let removed = 0;
+ for (const l of flat) {
+ if (l.kind === "added") added++;
+ else if (l.kind === "removed") removed++;
+ }
+ return {
+ id: 0, path, added, removed, hunks: buildHunks(flat, CONTEXT), tooLarge: false, isNewFile: false,
+ };
+}
+
+export function fromNew(content: string, path: string): FileDiff {
+ if (utf8Length(content) > DIFF_MAX_BYTES) {
+ const lineCount = content.split("\n").length;
+ return { id: 0, path, added: lineCount, removed: 0, hunks: [], tooLarge: true, isNewFile: true };
+ }
+ const lines = splitLines(content);
+ if (lines.length > DIFF_MAX_LINES) {
+ return { id: 0, path, added: lines.length, removed: 0, hunks: [], tooLarge: true, isNewFile: true };
+ }
+ const diffLines: DiffLine[] = lines.map((text, i) => ({
+ kind: "added", text, origLine: -1, newLine: i + 1,
+ }));
+ return {
+ id: 0,
+ path,
+ added: diffLines.length,
+ removed: 0,
+ hunks: diffLines.length ? [{ origStart: 0, newStart: 1, lines: diffLines }] : [],
+ tooLarge: false,
+ isNewFile: true,
+ };
+}
+
+/**
+ * HookServer.buildFileDiff — the diff of one Edit, MultiEdit or Write tool call,
+ * or null when the call changes nothing (or is not a file edit at all).
+ */
+export function buildFileDiff(tool: string, input: Record<string, unknown>): FileDiff | null {
+ const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
+ const path = str(input.file_path);
+ switch (tool) {
+ case "Edit": {
+ const oldText = str(input.old_string);
+ const newText = str(input.new_string);
+ if (oldText == null || newText == null || path == null) return null;
+ if (!oldText && !newText) return null;
+ const d = fromEdit(oldText, newText, path);
+ return d.added > 0 || d.removed > 0 ? d : null;
+ }
+ case "MultiEdit": {
+ const edits = input.edits;
+ if (path == null || !Array.isArray(edits) || edits.length === 0) return null;
+ let added = 0;
+ let removed = 0;
+ let tooLarge = false;
+ const hunks: DiffHunk[] = [];
+ for (const edit of edits) {
+ if (!edit || typeof edit !== "object") continue;
+ const e = edit as Record<string, unknown>;
+ const oldText = str(e.old_string);
+ const newText = str(e.new_string);
+ if (oldText == null || newText == null) continue;
+ const d = fromEdit(oldText, newText, path);
+ added += d.added;
+ removed += d.removed;
+ hunks.push(...d.hunks);
+ if (d.tooLarge) tooLarge = true;
+ }
+ if (added === 0 && removed === 0) return null;
+ return { id: 0, path, added, removed, hunks, tooLarge, isNewFile: false };
+ }
+ case "Write": {
+ const content = str(input.content);
+ if (path == null || !content) return null;
+ const d = fromNew(content, path);
+ return d.added > 0 || d.removed > 0 ? d : null;
+ }
+ default:
+ return null;
+ }
+}
+
+// ── Line splitting ────────────────────────────────────────────────────────────
+
+function splitLines(text: string): string[] {
+ const parts = text.replace(/\r\n/g, "\n").split("\n");
+ // A trailing newline leaves one empty element behind.
+ if (parts[parts.length - 1] === "") parts.pop();
+ return parts;
+}
+
+// ── LCS diff ──────────────────────────────────────────────────────────────────
+
+function buildDiffLines(oldLines: string[], newLines: string[]): DiffLine[] {
+ const m = oldLines.length;
+ const n = newLines.length;
+ const w = n + 1;
+ // dp[i*w + j] = LCS length of oldLines[0..<i] and newLines[0..<j]. Lengths stay
+ // under DIFF_MAX_LINES, so 16 bits are plenty and the table is half the size.
+ const dp = new Uint16Array((m + 1) * w);
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ dp[i * w + j] = oldLines[i - 1] === newLines[j - 1]
+ ? dp[(i - 1) * w + j - 1] + 1
+ : Math.max(dp[(i - 1) * w + j], dp[i * w + j - 1]);
+ }
+ }
+
+ // Backtrack to the matching pairs.
+ const matches: [number, number][] = [];
+ let i = m;
+ let j = n;
+ while (i > 0 && j > 0) {
+ if (oldLines[i - 1] === newLines[j - 1]) {
+ matches.push([i - 1, j - 1]);
+ i--;
+ j--;
+ } else if (dp[(i - 1) * w + j] >= dp[i * w + j - 1]) {
+ i--;
+ } else {
+ j--;
+ }
+ }
+ matches.reverse();
+
+ const result: DiffLine[] = [];
+ let prevOld = -1;
+ let prevNew = -1;
+ const removedLine = (k: number): DiffLine => ({ kind: "removed", text: oldLines[k], origLine: k + 1, newLine: -1 });
+ const addedLine = (k: number): DiffLine => ({ kind: "added", text: newLines[k], origLine: -1, newLine: k + 1 });
+ for (const [oi, ni] of matches) {
+ for (let k = prevOld + 1; k < oi; k++) result.push(removedLine(k));
+ for (let k = prevNew + 1; k < ni; k++) result.push(addedLine(k));
+ result.push({ kind: "context", text: oldLines[oi], origLine: oi + 1, newLine: ni + 1 });
+ prevOld = oi;
+ prevNew = ni;
+ }
+ for (let k = prevOld + 1; k < m; k++) result.push(removedLine(k));
+ for (let k = prevNew + 1; k < n; k++) result.push(addedLine(k));
+ return result;
+}
+
+// ── Hunks ─────────────────────────────────────────────────────────────────────
+
+function buildHunks(lines: DiffLine[], context: number): DiffHunk[] {
+ const merged: [number, number][] = [];
+ lines.forEach((line, i) => {
+ if (line.kind === "context") return;
+ const start = Math.max(0, i - context);
+ const end = Math.min(lines.length - 1, i + context);
+ const last = merged[merged.length - 1];
+ if (last && start <= last[1] + 1) last[1] = Math.max(last[1], end);
+ else merged.push([start, end]);
+ });
+ return merged.map(([start, end]) => {
+ const hunkLines = lines.slice(start, end + 1);
+ return {
+ origStart: hunkLines.find((l) => l.origLine > 0)?.origLine ?? 1,
+ newStart: hunkLines.find((l) => l.newLine > 0)?.newLine ?? 1,
+ lines: hunkLines,
+ };
+ });
+}
+
+// ── Count fallback (too large) ────────────────────────────────────────────────
+
+function countFallback(oldText: string, newText: string, path: string): FileDiff {
+ const oldLines = oldText.split("\n");
+ const newLines = newText.split("\n");
+ const oldSet = new Set(oldLines);
+ const newSet = new Set(newLines);
+ const added = newLines.filter((l) => l !== "" && !oldSet.has(l)).length;
+ const removed = oldLines.filter((l) => l !== "" && !newSet.has(l)).length;
+ return { id: 0, path, added, removed, hunks: [], tooLarge: true, isNewFile: false };
+}
+
+// ── toOneLine ─────────────────────────────────────────────────────────────────
+
+/**
+ * A possibly multi-line Markdown message as one line of plain text: only the
+ * first non-empty paragraph (a blank line, a horizontal rule or a table row ends
+ * it), without `**`, `__`, backticks, leading `#` or list markers.
+ */
+export function toOneLine(text: string, maxChars = 200): string {
+ const trimWS = (s: string) => s.replace(/^[ \t]+|[ \t]+$/g, "");
+ const paragraphs: string[][] = [];
+ let current: string[] = [];
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
+ const t = trimWS(line);
+ const isHR = t.length >= 3 && (/^-+$/.test(t) || /^\*+$/.test(t) || /^_+$/.test(t));
+ if (t === "" || isHR || t.startsWith("|")) {
+ if (current.length) paragraphs.push(current);
+ current = [];
+ } else {
+ current.push(line);
+ }
+ }
+ if (current.length) paragraphs.push(current);
+
+ for (const para of paragraphs) {
+ const s = para.join("\n").replaceAll("**", "").replaceAll("__", "").replaceAll("`", "");
+ const processed: string[] = [];
+ for (const line of s.split("\n")) {
+ let l = trimWS(line.replace(/^#+/, ""));
+ if (l.startsWith("- ") || l.startsWith("* ") || l.startsWith("• ")) l = l.slice(2);
+ else l = l.replace(/^\d+\.\s+/, "");
+ l = trimWS(l);
+ if (l) processed.push(l);
+ }
+ const collapsed = processed.join(" ").split(/\s+/).filter(Boolean).join(" ");
+ if (collapsed) return Array.from(collapsed).slice(0, maxChars).join("");
+ }
+ return "";
+}
+
+// ── Diff steps ────────────────────────────────────────────────────────────────
+// A diff shows up in the ticker as a step string the user never sees raw:
+// `"<filename>\t<added>:<removed>:<diffId>"` — same format as macOS.
+
+export const DIFF_STEP_MARKER = "";
+
+export interface DiffStep {
+ filename: string;
+ added: number;
+ removed: number;
+ diffId: number;
+}
+
+export function isDiffStep(step: string): boolean {
+ return step.startsWith(DIFF_STEP_MARKER);
+}
+
+export function makeDiffStep(filename: string, added: number, removed: number, diffId: number): string {
+ return `${DIFF_STEP_MARKER}${filename}\t${added}:${removed}:${diffId}`;
+}
+
+export function parseDiffStep(step: string): DiffStep | null {
+ if (!isDiffStep(step)) return null;
+ const body = step.slice(DIFF_STEP_MARKER.length);
+ const tab = body.indexOf("\t");
+ if (tab < 0) return null;
+ const parts = body.slice(tab + 1).split(":");
+ if (parts.length !== 3 || !parts.every((p) => /^-?\d+$/.test(p))) return null;
+ const [added, removed, diffId] = parts.map(Number);
+ return { filename: body.slice(0, tab), added, removed, diffId };
+}
+
+/** The last step that is text, never a diff marker. */
+export function lastTextStep(steps: readonly string[]): string | undefined {
+ for (let i = steps.length - 1; i >= 0; i--) {
+ if (!isDiffStep(steps[i])) return steps[i];
+ }
+ return undefined;
+}
diff --git a/windows/tests/diff.test.mjs b/windows/tests/diff.test.mjs
new file mode 100644
index 00000000..fc558e1b
--- /dev/null
+++ b/windows/tests/diff.test.mjs
@@ -0,0 +1,192 @@
+// Live diff engine (src/core/diff.ts) — port of tests/DiffEngineTests.swift,
+// plus the tool-input glue (buildFileDiff) HookServer.swift does on macOS.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DIFF_MAX_LINES, buildFileDiff, fileName, fromEdit, fromNew, isDiffStep, lastTextStep,
+ makeDiffStep, parseDiffStep, toOneLine,
+} from "../src/core/diff.ts";
+
+const allLines = (d) => d.hunks.flatMap((h) => h.lines);
+
+test("fromEdit — additions", () => {
+ const d = fromEdit("", "hello\nworld\n", "/a/b.swift");
+ assert.equal(d.added, 2);
+ assert.equal(d.removed, 0);
+ assert.equal(d.tooLarge, false);
+ assert.equal(d.hunks.length, 1);
+ assert.equal(fileName(d.path), "b.swift");
+});
+
+test("fromEdit — removals", () => {
+ const d = fromEdit("hello\nworld\n", "", "/x.py");
+ assert.equal(d.added, 0);
+ assert.equal(d.removed, 2);
+ assert.equal(d.hunks.length, 1);
+});
+
+test("fromEdit — replacement keeps context lines", () => {
+ const d = fromEdit("foo\nbar\nbaz\n", "foo\nqux\nbaz\n", "/f.ts");
+ assert.equal(d.added, 1);
+ assert.equal(d.removed, 1);
+ assert.ok(d.hunks[0].lines.some((l) => l.kind === "context"));
+ assert.deepEqual(
+ d.hunks[0].lines.map((l) => [l.kind, l.text, l.origLine, l.newLine]),
+ [
+ ["context", "foo", 1, 1],
+ ["removed", "bar", 2, -1],
+ ["added", "qux", -1, 2],
+ ["context", "baz", 3, 3],
+ ],
+ );
+});
+
+test("fromNew — new file, every line added", () => {
+ const d = fromNew("line1\nline2\nline3\n", "/new.rs");
+ assert.equal(d.added, 3);
+ assert.equal(d.removed, 0);
+ assert.equal(d.isNewFile, true);
+ assert.ok(allLines(d).every((l) => l.kind === "added"));
+});
+
+test("fromEdit — two separate edits of a MultiEdit", () => {
+ const d1 = fromEdit("aaa\n", "bbb\n", "/m.kt");
+ const d2 = fromEdit("ccc\n", "ddd\n", "/m.kt");
+ assert.deepEqual([d1.added, d1.removed, d2.added, d2.removed], [1, 1, 1, 1]);
+});
+
+test("tooLarge past 200 KB: counts only, no hunks", () => {
+ const d = fromEdit("x".repeat(150 * 1024), "y".repeat(60 * 1024), "/big.swift");
+ assert.equal(d.tooLarge, true);
+ assert.deepEqual(d.hunks, []);
+ assert.equal(d.added, 1);
+ assert.equal(d.removed, 1);
+});
+
+test("the 200 KB guard counts UTF-8 bytes, not characters", () => {
+ const d = fromEdit("é".repeat(60 * 1024), "è".repeat(60 * 1024), "/accents.txt");
+ assert.equal(d.tooLarge, true);
+});
+
+test("CRLF is normalised", () => {
+ const d = fromEdit("a\r\nb\r\n", "a\r\nc\r\n", "/win.txt");
+ assert.equal(d.added, 1);
+ assert.equal(d.removed, 1);
+});
+
+test("no trailing newline", () => {
+ const d = fromEdit("hello", "hello\nworld", "/t.txt");
+ assert.equal(d.added, 1);
+ assert.equal(d.removed, 0);
+});
+
+test("3 lines of context around a change", () => {
+ const lines = Array.from({ length: 10 }, (_, i) => `line${i + 1}`);
+ const changed = lines.map((l, i) => (i === 4 ? "changed" : l));
+ const d = fromEdit(`${lines.join("\n")}\n`, `${changed.join("\n")}\n`, "/ctx.swift");
+ assert.equal(d.added, 1);
+ assert.equal(d.removed, 1);
+ assert.equal(d.hunks.length, 1);
+ const context = d.hunks[0].lines.filter((l) => l.kind === "context");
+ assert.equal(context.length, 6);
+ assert.equal(d.hunks[0].origStart, 2);
+ assert.equal(d.hunks[0].newStart, 2);
+});
+
+test("distant changes make separate hunks", () => {
+ const lines = Array.from({ length: 30 }, (_, i) => `l${i}`);
+ const changed = lines.map((l, i) => (i === 2 || i === 25 ? `${l}!` : l));
+ const d = fromEdit(lines.join("\n"), changed.join("\n"), "/two.ts");
+ assert.equal(d.hunks.length, 2);
+ assert.equal(d.added, 2);
+ assert.equal(d.removed, 2);
+});
+
+test("m·n > 1 000 000 → tooLarge before the quadratic table", () => {
+ const many = Array.from({ length: 1001 }, (_, i) => `line${i}`).join("\n");
+ const d = fromEdit(many, `${many}\nextra`, "/big.swift");
+ assert.equal(d.tooLarge, true);
+ assert.deepEqual(d.hunks, []);
+});
+
+test("fromNew — too large keeps the line count", () => {
+ const d = fromNew("x\n".repeat(DIFF_MAX_LINES + 1), "/new.swift");
+ assert.equal(d.tooLarge, true);
+ assert.equal(d.isNewFile, true);
+ assert.deepEqual(d.hunks, []);
+ assert.ok(d.added > 0);
+});
+
+test("makeDiffStep / parseDiffStep round-trip", () => {
+ const s = makeDiffStep("foo.swift", 3, 1, 7);
+ assert.ok(isDiffStep(s));
+ assert.deepEqual(parseDiffStep(s), { filename: "foo.swift", added: 3, removed: 1, diffId: 7 });
+ assert.equal(parseDiffStep(makeDiffStep("bar.ts", 0, 2, 42))?.diffId, 42);
+ assert.equal(isDiffStep("Edit foo.swift"), false);
+ assert.equal(parseDiffStep("Edit foo.swift"), null);
+ assert.equal(parseDiffStep("\uE001no-tab"), null);
+ assert.equal(parseDiffStep("\uE001f\t1:2"), null);
+ assert.equal(parseDiffStep("\uE001f\t1:2:x"), null);
+});
+
+test("lastTextStep skips diff markers", () => {
+ assert.equal(lastTextStep(["Lit · a.ts", makeDiffStep("a.ts", 1, 0, 1)]), "Lit · a.ts");
+ assert.equal(lastTextStep([makeDiffStep("a.ts", 1, 0, 1)]), undefined);
+ assert.equal(lastTextStep([]), undefined);
+});
+
+test("toOneLine", () => {
+ assert.equal(toOneLine("line one\nline two\nline three"), "line one line two line three");
+ assert.equal(toOneLine("**hello** world"), "hello world");
+ assert.equal(toOneLine("## My Title\nsome text"), "My Title some text");
+ assert.equal(toOneLine(""), "");
+ assert.ok(toOneLine("x ".repeat(200), 10).length <= 10);
+ assert.equal(toOneLine("First para.\n\nSecond para."), "First para.");
+ assert.equal(
+ toOneLine("Done. Single commit 450a657 on github-pulse.\n\n---\n\nFiles touched (7)…"),
+ "Done. Single commit 450a657 on github-pulse.",
+ );
+ assert.equal(toOneLine("Summary line.\n***\nMore details."), "Summary line.");
+ assert.equal(toOneLine("Result:\n| Col1 | Col2 |\n|---|---|\n| A | B |"), "Result:");
+ assert.equal(toOneLine("- item one\n- item two"), "item one item two");
+ assert.equal(toOneLine("* first\n* second"), "first second");
+ assert.equal(toOneLine("1. step one\n2. step two"), "step one step two");
+ assert.equal(toOneLine("\n\nActual content."), "Actual content.");
+ // Windows line endings split paragraphs too.
+ assert.equal(toOneLine("Fixed `it`.\r\n\r\nDetails"), "Fixed it.");
+});
+
+test("buildFileDiff — Edit", () => {
+ const d = buildFileDiff("Edit", { file_path: "C:\\p\\a.ts", old_string: "a\nb", new_string: "a\nc\nd" });
+ assert.equal(fileName(d.path), "a.ts");
+ assert.deepEqual([d.added, d.removed, d.isNewFile], [2, 1, false]);
+ // Nothing changed, nothing given, or not a string: no diff.
+ assert.equal(buildFileDiff("Edit", { file_path: "/a", old_string: "x", new_string: "x" }), null);
+ assert.equal(buildFileDiff("Edit", { file_path: "/a", old_string: "", new_string: "" }), null);
+ assert.equal(buildFileDiff("Edit", { old_string: "x", new_string: "y" }), null);
+ assert.equal(buildFileDiff("Edit", { file_path: "/a", old_string: 1, new_string: "y" }), null);
+});
+
+test("buildFileDiff — MultiEdit sums its edits", () => {
+ const d = buildFileDiff("MultiEdit", {
+ file_path: "/p/m.kt",
+ edits: [
+ { old_string: "aaa", new_string: "bbb" },
+ { old_string: "ccc", new_string: "ddd\neee" },
+ { old_string: 3 },
+ null,
+ ],
+ });
+ assert.deepEqual([d.added, d.removed, d.hunks.length], [3, 2, 2]);
+ assert.equal(buildFileDiff("MultiEdit", { file_path: "/p/m.kt", edits: [] }), null);
+ assert.equal(buildFileDiff("MultiEdit", { file_path: "/p/m.kt" }), null);
+});
+
+test("buildFileDiff — Write and other tools", () => {
+ const d = buildFileDiff("Write", { file_path: "/p/n.md", content: "# Hi\n\nThere\n" });
+ assert.deepEqual([d.added, d.removed, d.isNewFile], [3, 0, true]);
+ assert.equal(buildFileDiff("Write", { file_path: "/p/n.md", content: "" }), null);
+ assert.equal(buildFileDiff("Bash", { command: "ls" }), null);
+ assert.equal(buildFileDiff("Read", { file_path: "/p/n.md" }), null);
+});