@bismawy/pi-arnative 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,12 +6,14 @@
6
6
  * State lives in `<agent>/arnative/todos/<session id>.json`, so `/reload` and a resumed session
7
7
  * keep the list; every mutation rewrites the file.
8
8
  */
9
- import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
- import { dirname, join } from "node:path";
9
+ import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
11
12
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
13
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
13
14
  import type { TuiMouseEvent } from "@earendil-works/pi-tui";
14
15
  import { assert, isMain } from "../lib/check.ts";
16
+ import { writeAtomicSync } from "../lib/preset-store.ts";
15
17
  import { inSpans, screenTitle, type TextSpan, textSpans } from "../lib/box.ts";
16
18
  import { ListPicker, type ListPickerText } from "../lib/list-picker.ts";
17
19
  import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../lib/shortcuts.ts";
@@ -76,10 +78,48 @@ function store(): WidgetStore {
76
78
  return holder[STORE_KEY]!;
77
79
  }
78
80
 
81
+ /** Completed/empty session todo files older than this are pruned on session start. */
82
+ const TODO_PRUNE_AGE_MS = 30 * 24 * 60 * 60 * 1000;
83
+
84
+ const todosDir = (): string => join(getAgentDir(), "arnative", "todos");
85
+
79
86
  /** `<agent>/arnative/todos/<session id>.json` — one file per session, so two sessions in the
80
87
  * same checkout never overwrite each other's list. */
81
88
  const stateFile = (ctx: ExtensionContext): string =>
82
- join(getAgentDir(), "arnative", "todos", `${ctx.sessionManager.getSessionId()}.json`);
89
+ join(todosDir(), `${ctx.sessionManager.getSessionId()}.json`);
90
+
91
+ /** Remove old todo files whose tasks are all completed (or empty) so `todos/` does not grow unbounded. */
92
+ export function pruneCompletedTodos(
93
+ dir: string = todosDir(),
94
+ opts: { maxAgeMs?: number; now?: number; skipFile?: string } = {},
95
+ ): number {
96
+ const maxAgeMs = opts.maxAgeMs ?? TODO_PRUNE_AGE_MS;
97
+ const now = opts.now ?? Date.now();
98
+ let entries: string[];
99
+ try {
100
+ entries = readdirSync(dir);
101
+ } catch {
102
+ return 0;
103
+ }
104
+ let removed = 0;
105
+ for (const name of entries) {
106
+ if (!name.endsWith(".json")) continue;
107
+ const full = join(dir, name);
108
+ if (opts.skipFile && (full === opts.skipFile || name === opts.skipFile)) continue;
109
+ try {
110
+ if (now - statSync(full).mtimeMs < maxAgeMs) continue;
111
+ const parsed = normalizeState(JSON.parse(readFileSync(full, "utf8")) as unknown);
112
+ if (!parsed) continue;
113
+ if (parsed.tasks.length === 0 || allDone(parsed)) {
114
+ unlinkSync(full);
115
+ removed++;
116
+ }
117
+ } catch {
118
+ // leave unreadable or locked files alone
119
+ }
120
+ }
121
+ return removed;
122
+ }
83
123
 
84
124
  function loadState(ctx: ExtensionContext, reload = false): void {
85
125
  const s = store();
@@ -98,22 +138,8 @@ function loadState(ctx: ExtensionContext, reload = false): void {
98
138
  }
99
139
 
100
140
  function saveState(ctx: ExtensionContext): void {
101
- const path = stateFile(ctx);
102
141
  try {
103
- mkdirSync(dirname(path), { recursive: true });
104
- const payload = `${JSON.stringify(store().state, null, 2)}\n`;
105
- const tmp = `${path}.${process.pid}.tmp`;
106
- writeFileSync(tmp, payload, "utf8");
107
- try {
108
- renameSync(tmp, path);
109
- } catch (error) {
110
- // Windows refuses the replace while another process holds the file; an in-place
111
- // write still lands, and a lost list is worse than the truncation window.
112
- const code = (error as NodeJS.ErrnoException).code;
113
- if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw error;
114
- writeFileSync(path, payload, "utf8");
115
- rmSync(tmp, { force: true });
116
- }
142
+ writeAtomicSync(stateFile(ctx), `${JSON.stringify(store().state, null, 2)}\n`);
117
143
  } catch {
118
144
  // ignore: the list still renders from memory
119
145
  }
@@ -302,6 +328,14 @@ function refresh(ctx: ExtensionContext, force = false): void {
302
328
  holdRepeat = undefined;
303
329
  }
304
330
  };
331
+ const toggleExpanded = (): { handled: true; render: true } => {
332
+ s.expanded = !s.expanded;
333
+ s.top = null;
334
+ if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
335
+ else cancelHide(s);
336
+ s.tui?.requestRender(true);
337
+ return { handled: true, render: true };
338
+ };
305
339
  /** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
306
340
  * window parks at the end of the list instead of drifting. */
307
341
  const scroll = (delta: number): void => {
@@ -367,14 +401,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
367
401
  const onHint = inSpans(spans, event.y, event.x);
368
402
  const onCounter = event.y === layout.up || event.y === layout.down;
369
403
  if (!onHint && !onCounter) {
370
- if (event.type === "click" && (event.clickCount ?? 1) === 1) {
371
- s.expanded = !s.expanded;
372
- s.top = null;
373
- if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
374
- else cancelHide(s);
375
- s.tui?.requestRender(true);
376
- return { handled: true, render: true };
377
- }
404
+ if (event.type === "click" && (event.clickCount ?? 1) === 1) return toggleExpanded();
378
405
  return undefined;
379
406
  }
380
407
  // The press already did it, so the release and the click that may follow are
@@ -387,12 +414,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
387
414
  startHold(delta);
388
415
  return { handled: true, render: true };
389
416
  }
390
- s.expanded = !s.expanded;
391
- s.top = null;
392
- if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
393
- else cancelHide(s);
394
- s.tui?.requestRender(true);
395
- return { handled: true, render: true };
417
+ return toggleExpanded();
396
418
  },
397
419
  dispose: (): void => {
398
420
  stopHold();
@@ -485,7 +507,9 @@ export default function (pi: ExtensionAPI) {
485
507
  });
486
508
 
487
509
  pi.on("session_start", async (event, ctx) => {
488
- loadState(ctx, (event as { reason?: string } | undefined)?.reason === "reload");
510
+ const reload = (event as { reason?: string } | undefined)?.reason === "reload";
511
+ loadState(ctx, reload);
512
+ if (!reload) pruneCompletedTodos(todosDir(), { skipFile: stateFile(ctx) });
489
513
  refresh(ctx, true);
490
514
  });
491
515
 
@@ -583,5 +607,31 @@ if (isMain(import.meta.url)) {
583
607
  // A new session with no file on disk starts empty instead of inheriting the previous session's list.
584
608
  loadState({ sessionManager: { getSessionId: () => `empty-${process.pid}-${Date.now()}` } } as never);
585
609
  assert(store().state.tasks.length === 0 && store().expanded === false, "session_start: a fresh session starts with an empty list");
610
+ // Auto-prune removes old completed/empty todo files while keeping open, recent, and active-session files.
611
+ const pruneTmp = mkdtempSync(join(tmpdir(), "arnative-todos-prune-"));
612
+ try {
613
+ const now = Date.now();
614
+ const oldSec = (now - TODO_PRUNE_AGE_MS - 60_000) / 1000;
615
+ const put = (name: string, data: unknown, old: boolean): string => {
616
+ const p = join(pruneTmp, name);
617
+ writeFileSync(p, JSON.stringify(data));
618
+ if (old) utimesSync(p, oldSec, oldSec);
619
+ return p;
620
+ };
621
+ put("old-done.json", { nextId: 2, tasks: [{ id: 1, subject: "a", status: "completed" }] }, true);
622
+ put("old-empty.json", { nextId: 1, tasks: [] }, true);
623
+ put("old-open.json", { nextId: 2, tasks: [{ id: 1, subject: "b", status: "pending" }] }, true);
624
+ put("recent-done.json", { nextId: 2, tasks: [{ id: 1, subject: "c", status: "completed" }] }, false);
625
+ const activePath = put("active-done.json", { nextId: 2, tasks: [{ id: 1, subject: "d", status: "completed" }] }, true);
626
+ const removed = pruneCompletedTodos(pruneTmp, { now, skipFile: activePath });
627
+ const left = readdirSync(pruneTmp).sort();
628
+ assert(removed === 2, `prune: expected 2 removed, got ${removed}`);
629
+ assert(
630
+ left.join(",") === "active-done.json,old-open.json,recent-done.json",
631
+ `prune: expected open/recent/active kept, got ${left.join(",")}`,
632
+ );
633
+ } finally {
634
+ rmSync(pruneTmp, { recursive: true, force: true });
635
+ }
586
636
  console.log("todos extension self-check OK");
587
637
  }
@@ -37,14 +37,18 @@ import {
37
37
  ToolExecutionComponent,
38
38
  } from "@earendil-works/pi-coding-agent";
39
39
  import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
40
- import { homedir } from "node:os";
40
+ import { mkdtempSync, rmSync } from "node:fs";
41
+ import { homedir, tmpdir } from "node:os";
42
+ import { join } from "node:path";
41
43
  import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
42
44
  import { getActiveTheme, stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
43
45
  import { actionWord } from "../lib/todos.ts";
46
+ import { EDIT_DIFF_KEY, choiceSetting, resetPresetCache } from "../lib/preset-store.ts";
47
+ import { clearRenderCache } from "./render-cache.ts";
44
48
  import { assert, isMain } from "../lib/check.ts";
45
49
  import { markPatched, originalOf } from "../lib/patch.ts";
46
50
 
47
- type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string };
51
+ type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; inverse?(text: string): string };
48
52
  type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: any };
49
53
  type TCtx = { isError?: boolean; toolCallId?: string; args?: any; state?: Record<string, unknown>; durationMs?: number };
50
54
  type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
@@ -881,7 +885,7 @@ function minimal(
881
885
  name: (th: Theme, soft: (s: string) => string) => string,
882
886
  call: (a: any, th: Theme, soft: (s: string) => string, expanded: boolean) => string,
883
887
  res: Res = resText,
884
- full: (r: TResult, th: Theme) => string[] = fullText,
888
+ full: (r: TResult, th: Theme, inner: number) => string[] = fullText,
885
889
  ): void {
886
890
  OWN_BOX.add(String(tool.name ?? ""));
887
891
  pi.registerTool({
@@ -950,7 +954,7 @@ function minimal(
950
954
  label,
951
955
  );
952
956
  const resLine = res(result, theme, soft, isErr, expanded);
953
- if (expanded) rows.push(...full(result, theme));
957
+ if (expanded) rows.push(...full(result, theme, inner));
954
958
  else if (resLine) rows.push(oneRow(resLine, inner));
955
959
  return box(theme, width, rows);
956
960
  });
@@ -978,6 +982,7 @@ function arnativeTools(pi: ExtensionAPI) {
978
982
  });
979
983
  pi.on("session_shutdown", async () => {
980
984
  TIMINGS.clear();
985
+ ACTIVE = 0;
981
986
  if (TICK) {
982
987
  clearInterval(TICK);
983
988
  TICK = null;
@@ -987,21 +992,18 @@ function arnativeTools(pi: ExtensionAPI) {
987
992
 
988
993
  // Gap is only stripped for our own boxes (see OWN_BOX above).
989
994
 
995
+ const shellCall = (a: { command?: string }, _th: Theme, soft: (s: string) => string, expanded: boolean): string => {
996
+ const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
997
+ return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
998
+ };
999
+
990
1000
  // powershell: pi core registers it as a separate builtin (only on Windows); without
991
1001
  // our own registration it keeps pi's "default" shell and renders as a bg block, not a
992
1002
  // box (the same reason `bash` is re-registered below). Windows only: on any other
993
1003
  // platform `getPowerShellConfig()` throws, and an unregistered tool would stay off
994
1004
  // while our registration is active on load.
995
1005
  if (process.platform === "win32")
996
- minimal(
997
- pi,
998
- createPowerShellTool(cwd),
999
- (th) => th.fg("accent", "PS>"),
1000
- (a, _th, soft, expanded) => {
1001
- const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
1002
- return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
1003
- },
1004
- );
1006
+ minimal(pi, createPowerShellTool(cwd), (th) => th.fg("accent", "PS>"), shellCall);
1005
1007
 
1006
1008
  // ls: no renderShell of its own, so pi's default shell turns it into a bg block.
1007
1009
  minimal(
@@ -1013,15 +1015,7 @@ function arnativeTools(pi: ExtensionAPI) {
1013
1015
  );
1014
1016
 
1015
1017
  // bash: `󰔟 $ <6 words>…` / `✓ $ <full title when expanded> 0.1s`
1016
- minimal(
1017
- pi,
1018
- createBashTool(cwd),
1019
- (th) => th.fg("accent", "$"),
1020
- (a, _th, soft, expanded) => {
1021
- const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
1022
- return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
1023
- },
1024
- );
1018
+ minimal(pi, createBashTool(cwd), (th) => th.fg("accent", "$"), shellCall);
1025
1019
 
1026
1020
  // read: `read path[:range]` → `󱞩 N lines`
1027
1021
  minimal(
@@ -1080,20 +1074,188 @@ function arnativeTools(pi: ExtensionAPI) {
1080
1074
  }
1081
1075
  return `${resHead(th)} ${th.fg("toolDiffAdded", `+${add}`)} / ${th.fg("toolDiffRemoved", `-${del}`)}`;
1082
1076
  },
1083
- (r, th) => {
1084
- const diff: string = r.details?.diff ?? "";
1085
- if (!diff) return fullText(r, th);
1086
- return diff.split("\n").map((l) =>
1087
- l.startsWith("+") && !l.startsWith("+++")
1088
- ? th.fg("toolDiffAdded", l)
1089
- : l.startsWith("-") && !l.startsWith("---")
1090
- ? th.fg("toolDiffRemoved", l)
1091
- : th.fg("toolDiffContext", l),
1092
- );
1093
- },
1077
+ (r, th, inner) => formatEditDiff(r, th, inner),
1078
+ );
1079
+ }
1080
+
1081
+ const SPLIT_DIFF_MIN_WIDTH = 50;
1082
+ const INTRA_LINE_MAX_TOKENS = 200;
1083
+
1084
+ export type EditDiffMode = "Split" | "Unified";
1085
+ export const EDIT_DIFF_CHOICES: readonly EditDiffMode[] = ["Split", "Unified"];
1086
+ const editDiffSetting = choiceSetting(EDIT_DIFF_KEY, EDIT_DIFF_CHOICES, "Split");
1087
+ const EDIT_DIFF_CONFIG_KEY = editDiffSetting.slot;
1088
+
1089
+ export const activeEditDiff = (): EditDiffMode => editDiffSetting.get();
1090
+
1091
+ export function setEditDiff(mode: EditDiffMode): void {
1092
+ editDiffSetting.set(mode);
1093
+ clearRenderCache();
1094
+ }
1095
+
1096
+ type DiffSide = { styled: string } | null;
1097
+
1098
+ function unifiedDiffLines(diff: string, th: Theme): string[] {
1099
+ return diff.split("\n").map((l) =>
1100
+ l.startsWith("+") && !l.startsWith("+++")
1101
+ ? th.fg("toolDiffAdded", l)
1102
+ : l.startsWith("-") && !l.startsWith("---")
1103
+ ? th.fg("toolDiffRemoved", l)
1104
+ : th.fg("toolDiffContext", l),
1094
1105
  );
1095
1106
  }
1096
1107
 
1108
+ function tokenizeDiffLine(s: string): string[] {
1109
+ return s.match(/[A-Za-z0-9_]+|\s+|[^\sA-Za-z0-9_]/g) ?? [];
1110
+ }
1111
+
1112
+ /**
1113
+ * Highlights changed tokens between paired old/new lines using `inverse`,
1114
+ * keeping leading indentation un-highlighted.
1115
+ */
1116
+ function highlightLinePair(oldText: string, newText: string, th: Theme): { left: string; right: string } {
1117
+ const a = tokenizeDiffLine(oldText);
1118
+ const b = tokenizeDiffLine(newText);
1119
+ if (a.length === 0 || b.length === 0 || a.length > INTRA_LINE_MAX_TOKENS || b.length > INTRA_LINE_MAX_TOKENS) {
1120
+ return { left: th.fg("toolDiffRemoved", oldText), right: th.fg("toolDiffAdded", newText) };
1121
+ }
1122
+
1123
+ const m = a.length;
1124
+ const n = b.length;
1125
+ const dp: Uint16Array[] = Array.from({ length: m + 1 }, () => new Uint16Array(n + 1));
1126
+ for (let i = m - 1; i >= 0; i--) {
1127
+ for (let j = n - 1; j >= 0; j--) {
1128
+ dp[i]![j] = a[i] === b[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);
1129
+ }
1130
+ }
1131
+
1132
+ const inv = (s: string) => (th.inverse ? th.inverse(s) : `\x1b[7m${s}\x1b[27m`);
1133
+ let left = "";
1134
+ let right = "";
1135
+ let i = 0;
1136
+ let j = 0;
1137
+ let seenNonWsLeft = false;
1138
+ let seenNonWsRight = false;
1139
+
1140
+ const emitChanged = (tok: string, color: string, seenNonWs: boolean): [string, boolean] => {
1141
+ if (!seenNonWs && /^\s+$/.test(tok)) return [th.fg(color, tok), false];
1142
+ return [th.fg(color, inv(tok)), true];
1143
+ };
1144
+
1145
+ while (i < m && j < n) {
1146
+ if (a[i] === b[j]) {
1147
+ const tok = a[i]!;
1148
+ if (tok.trim()) {
1149
+ seenNonWsLeft = true;
1150
+ seenNonWsRight = true;
1151
+ }
1152
+ left += th.fg("toolDiffRemoved", tok);
1153
+ right += th.fg("toolDiffAdded", tok);
1154
+ i++;
1155
+ j++;
1156
+ } else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) {
1157
+ const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
1158
+ left += chunk;
1159
+ seenNonWsLeft = seen;
1160
+ i++;
1161
+ } else {
1162
+ const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
1163
+ right += chunk;
1164
+ seenNonWsRight = seen;
1165
+ j++;
1166
+ }
1167
+ }
1168
+ while (i < m) {
1169
+ const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
1170
+ left += chunk;
1171
+ seenNonWsLeft = seen;
1172
+ i++;
1173
+ }
1174
+ while (j < n) {
1175
+ const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
1176
+ right += chunk;
1177
+ seenNonWsRight = seen;
1178
+ j++;
1179
+ }
1180
+ return { left, right };
1181
+ }
1182
+
1183
+ function wrapDiffCell(side: DiffSide, width: number): string[] {
1184
+ if (!side) return [""];
1185
+ const clean = side.styled.replace(/\t/g, " ");
1186
+ return clean === "" ? [""] : wrapTextWithAnsi(clean, width);
1187
+ }
1188
+
1189
+ function renderSplitPair(left: DiffSide, right: DiffSide, leftW: number, rightW: number, sep: string): string[] {
1190
+ const leftLines = wrapDiffCell(left, leftW);
1191
+ const rightLines = wrapDiffCell(right, rightW);
1192
+ const count = Math.max(leftLines.length, rightLines.length);
1193
+ const rows: string[] = [];
1194
+ for (let i = 0; i < count; i++) {
1195
+ const l = leftLines[i] ?? "";
1196
+ const r = rightLines[i] ?? "";
1197
+ const pad = " ".repeat(Math.max(0, leftW - visibleWidth(l)));
1198
+ rows.push(`${l}${pad}${sep}${r}`);
1199
+ }
1200
+ return rows;
1201
+ }
1202
+
1203
+ /**
1204
+ * Formats an `edit` diff side-by-side (Before | After) when the box inner width
1205
+ * is at least {@link SPLIT_DIFF_MIN_WIDTH}, falling back to unified diff on
1206
+ * narrow terminals or when `details.diff` is absent.
1207
+ */
1208
+ export function formatEditDiff(r: TResult, th: Theme, inner: number, mode: EditDiffMode = activeEditDiff()): string[] {
1209
+ const diff: string = r.details?.diff ?? "";
1210
+ if (!diff) return fullText(r, th);
1211
+ if (mode === "Unified" || inner < SPLIT_DIFF_MIN_WIDTH) return unifiedDiffLines(diff, th);
1212
+
1213
+ const sep = th.fg("dim", " │ ");
1214
+ const leftW = Math.floor((inner - 3) / 2);
1215
+ const rightW = inner - 3 - leftW;
1216
+ const out: string[] = [
1217
+ `${th.fg("dim", "Before")}${" ".repeat(Math.max(0, leftW - 6))}${sep}${th.fg("dim", "After")}`,
1218
+ th.fg("dim", `${"─".repeat(leftW)}─┼─${"─".repeat(rightW)}`),
1219
+ ];
1220
+
1221
+ let dels: string[] = [];
1222
+ let adds: string[] = [];
1223
+ const flushChanges = () => {
1224
+ const count = Math.max(dels.length, adds.length);
1225
+ for (let i = 0; i < count; i++) {
1226
+ const d = dels[i];
1227
+ const a = adds[i];
1228
+ if (d !== undefined && a !== undefined) {
1229
+ const { left, right } = highlightLinePair(d, a, th);
1230
+ out.push(...renderSplitPair({ styled: left }, { styled: right }, leftW, rightW, sep));
1231
+ } else {
1232
+ const left: DiffSide = d !== undefined ? { styled: th.fg("toolDiffRemoved", d) } : null;
1233
+ const right: DiffSide = a !== undefined ? { styled: th.fg("toolDiffAdded", a) } : null;
1234
+ out.push(...renderSplitPair(left, right, leftW, rightW, sep));
1235
+ }
1236
+ }
1237
+ dels = [];
1238
+ adds = [];
1239
+ };
1240
+
1241
+ for (const line of diff.split("\n")) {
1242
+ if (line.startsWith("-") && !line.startsWith("---")) {
1243
+ dels.push(line.slice(1));
1244
+ } else if (line.startsWith("+") && !line.startsWith("+++")) {
1245
+ adds.push(line.slice(1));
1246
+ } else if (line.startsWith(" ")) {
1247
+ flushChanges();
1248
+ const side: DiffSide = { styled: th.fg("toolDiffContext", line.slice(1)) };
1249
+ out.push(...renderSplitPair(side, side, leftW, rightW, sep));
1250
+ } else {
1251
+ flushChanges();
1252
+ out.push(th.fg("toolDiffContext", line));
1253
+ }
1254
+ }
1255
+ flushChanges();
1256
+ return out;
1257
+ }
1258
+
1097
1259
  // codemode: pi's renderer wrapped in our box. renderShell "self" keeps the
1098
1260
  // execution defaults; renderCall/renderResult draw the box. state.hasResult
1099
1261
  // guarantees one box per call, also after reload/restore.
@@ -1734,6 +1896,40 @@ if (isMain(import.meta.url)) {
1734
1896
  minRender("edit", { path: "README.md" }, diffRes).every((l) => visibleWidth(l) === 74),
1735
1897
  "minimal(): hint row still fills the box width",
1736
1898
  );
1899
+ // Side-by-side edit diff: Before | After at wide widths, unified fallback when narrow
1900
+ const diffTmp = mkdtempSync(join(tmpdir(), "arnative-editdiff-"));
1901
+ const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
1902
+ process.env.PI_CODING_AGENT_DIR = diffTmp;
1903
+ delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
1904
+ resetPresetCache();
1905
+ try {
1906
+ const openedIsolated = minRender("edit", { path: "README.md" }, diffRes, true);
1907
+ assert(openedIsolated.some((l) => l.includes("Before") && l.includes("│") && l.includes("After")), "edit: expanded view shows Before | After header");
1908
+ assert(openedIsolated.some((l) => l.includes("─┼─")), "edit: expanded view shows header separator");
1909
+ assert(openedIsolated.some((l) => l.includes("old") && !l.includes("-old") && l.includes("│") && l.includes("new") && !l.includes("+new")), "edit: expanded view pairs old and new without +/- prefix");
1910
+ const intraRes = { content: [{ type: "text", text: "ok" }], details: { diff: "-const x = 1;\n+const x = 2;" } };
1911
+ const intraLines = formatEditDiff(intraRes, th, 70);
1912
+ assert(intraLines.some((l) => l.includes("const x = \x1b[7m1\x1b[27m;") && l.includes("const x = \x1b[7m2\x1b[27m;")), "edit: intra-line diff highlights only changed tokens");
1913
+ const pureAdd = minRender("edit", { path: "README.md" }, { content: [{ type: "text", text: "ok" }], details: { diff: "+ 10 added\n 11 ctx" } }, true);
1914
+ assert(pureAdd.some((l) => /^\│\s+\│\s+10 added/.test(l)), "edit: pure addition leaves Before column blank and strips +");
1915
+ assert(pureAdd.some((l) => l.includes("11 ctx") && l.indexOf("11 ctx") !== l.lastIndexOf("11 ctx")), "edit: context line appears in both columns");
1916
+ assert(pureAdd.every((l) => visibleWidth(l) === 74), "edit: side-by-side rows keep exact box width");
1917
+ const narrow = formatEditDiff(diffRes, th, 40);
1918
+ assert(!narrow.some((l) => l.includes("Before") && l.includes("After")), "edit: narrow width falls back to unified diff");
1919
+ setEditDiff("Unified");
1920
+ const liveUnified = minRender("edit", { path: "README.md" }, diffRes, true);
1921
+ assert(!liveUnified.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Unified') switches immediately");
1922
+ assert(liveUnified.some((l) => l.includes("-old")) && liveUnified.some((l) => l.includes("+new")), "edit: Unified mode keeps +/- lines");
1923
+ setEditDiff("Split");
1924
+ const liveSplit = minRender("edit", { path: "README.md" }, diffRes, true);
1925
+ assert(liveSplit.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Split') switches back immediately");
1926
+ } finally {
1927
+ if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
1928
+ else process.env.PI_CODING_AGENT_DIR = prevAgentDir;
1929
+ delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
1930
+ resetPresetCache();
1931
+ rmSync(diffTmp, { recursive: true, force: true });
1932
+ }
1737
1933
  }
1738
1934
 
1739
1935
  // Chrome DevTools: their bare renderers are replaced by our box (title + summary).
@@ -16,8 +16,9 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
16
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
17
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
18
18
  import { tmpdir } from "node:os";
19
- import { dirname, join } from "node:path";
19
+ import { join } from "node:path";
20
20
  import { assert, isMain } from "../lib/check.ts";
21
+ import { writeAtomicSync } from "../lib/preset-store.ts";
21
22
  import { collectUsageSummary, resetUsageCache, type UsageSummary } from "../lib/usage-store.ts";
22
23
 
23
24
  /** At most one write per minute, whatever the turn rate. */
@@ -77,17 +78,7 @@ export function renderProm(summary: UsageSummary, now: number): string {
77
78
  * target open) falls back to an in-place write and removes its temp file — the
78
79
  * `lib/preset-store.ts` pattern. */
79
80
  export function writePromFile(text: string, path: string, rename: (from: string, to: string) => void = renameSync): void {
80
- const tmp = `${path}.${process.pid}.tmp`;
81
- mkdirSync(dirname(path), { recursive: true });
82
- writeFileSync(tmp, text, "utf8");
83
- try {
84
- rename(tmp, path);
85
- } catch (e) {
86
- const code = (e as NodeJS.ErrnoException).code;
87
- if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
88
- writeFileSync(path, text, "utf8");
89
- rmSync(tmp, { force: true });
90
- }
81
+ writeAtomicSync(path, text, rename);
91
82
  }
92
83
 
93
84
  let lastExportMs = 0;