ceulen 0.10.1 → 0.12.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +107 -1
  2. package/README.md +56 -1
  3. package/extensions/index.ts +5 -1
  4. package/extensions/lib/env.test.ts +147 -0
  5. package/extensions/lib/env.ts +180 -0
  6. package/extensions/lib/order.test.ts +74 -0
  7. package/extensions/lib/plan-bridge.ts +18 -0
  8. package/extensions/lib/registry.test.ts +8 -5
  9. package/extensions/lib/registry.ts +22 -3
  10. package/extensions/modules/a2a/configPanel.ts +42 -1
  11. package/extensions/modules/a2a/index.ts +4 -2
  12. package/extensions/modules/a2a/lib/config.ts +8 -3
  13. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  14. package/extensions/modules/advisor/index.ts +6 -3
  15. package/extensions/modules/advisor/test/module.test.ts +31 -0
  16. package/extensions/modules/attachments/configPanel.ts +91 -0
  17. package/extensions/modules/attachments/index.ts +274 -0
  18. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  19. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  20. package/extensions/modules/attachments/lib/paths.ts +74 -0
  21. package/extensions/modules/attachments/lib/registry.ts +70 -0
  22. package/extensions/modules/attachments/lib/settings.ts +99 -0
  23. package/extensions/modules/attachments/lib/tray.ts +74 -0
  24. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  25. package/extensions/modules/attachments/test/index.test.ts +870 -0
  26. package/extensions/modules/attachments/test/module.test.ts +53 -0
  27. package/extensions/modules/classifier/index.ts +55 -1
  28. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  29. package/extensions/modules/composer/test/module.test.ts +2 -2
  30. package/extensions/modules/config/index.ts +3 -0
  31. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  32. package/extensions/modules/cron/configPanel.ts +103 -0
  33. package/extensions/modules/cron/index.ts +638 -0
  34. package/extensions/modules/cron/lib/jobs.ts +201 -0
  35. package/extensions/modules/cron/lib/schedule.ts +161 -0
  36. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  37. package/extensions/modules/cron/test/index.test.ts +859 -0
  38. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  39. package/extensions/modules/munin/index.ts +3 -1
  40. package/extensions/modules/permission/index.ts +567 -0
  41. package/extensions/modules/permission/test/permission.test.ts +789 -0
  42. package/extensions/modules/plan/index.ts +5 -0
  43. package/extensions/modules/repair/index.ts +160 -5
  44. package/extensions/modules/repair/test/freshness.test.ts +209 -0
  45. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  46. package/extensions/modules/router/configPanel.ts +4 -4
  47. package/extensions/modules/router/index.ts +1 -1
  48. package/extensions/modules/router/lib/config.ts +9 -4
  49. package/extensions/modules/router/lib/systemone.ts +17 -4
  50. package/extensions/modules/router/test/unit.test.ts +46 -1
  51. package/extensions/modules/rules/index.ts +13 -3
  52. package/extensions/modules/rules/lib/rules.ts +24 -12
  53. package/extensions/modules/rules/test/lib.test.ts +20 -0
  54. package/extensions/modules/rules/test/module.test.ts +21 -0
  55. package/extensions/modules/subagent/index.ts +49 -10
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +356 -14
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  61. package/extensions/modules/usage/index.ts +193 -71
  62. package/extensions/modules/usage/test/context.test.ts +160 -120
  63. package/extensions/modules/web/configPanel.ts +67 -8
  64. package/extensions/modules/web/index.ts +3 -1
  65. package/extensions/modules/web/test/a11y.test.ts +1 -1
  66. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  67. package/extensions/modules/web/test/settings.test.ts +6 -0
  68. package/package.json +2 -2
  69. package/skills/cron/SKILL.md +58 -0
@@ -0,0 +1,870 @@
1
+ /**
2
+ * Tests for ceulen attachments: path extraction (incl. prose false-positives),
3
+ * input transform (images, text-file inlining, size cap, no-op, source skip),
4
+ * and clipboard uri-list parsing.
5
+ */
6
+
7
+ import assert from "node:assert/strict";
8
+ import { after, before, describe, it } from "node:test";
9
+ import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { ABSOLUTE_PATH_RE, absolutePathSpans, extractImagePaths } from "../lib/paths";
13
+ import { parseUriList } from "../lib/clipboard-files";
14
+ import { DEFAULTS, isValidShortcut, loadSettings } from "../lib/settings";
15
+ import { lookup, remember, registryPath } from "../lib/registry";
16
+ import { savePaste } from "../lib/pastes";
17
+ import { AttachmentTray } from "../lib/tray";
18
+ import piAttachments from "../index";
19
+
20
+ const TMP = mkdtempSync(path.join(os.tmpdir(), "ceulen-attachments-test-"));
21
+
22
+ // Minimal valid 1x1 PNG (67 bytes, standard test fixture).
23
+ const PNG_BYTES = Buffer.from(
24
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
25
+ "base64",
26
+ );
27
+
28
+ before(() => {
29
+ // Isolate the persistent token registry (remember()/lookup()) from the real
30
+ // ~/.pi/agent — tests must never write user-visible state.
31
+ // NOTE: mocha runs this root before() before every test in the file — keep
32
+ // registry/env isolation HERE (not in per-describe hooks) so later describes
33
+ // can't accidentally restore-and-delete the override.
34
+ mkdirSync(path.join(TMP, "agent"), { recursive: true });
35
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "agent");
36
+ writeFileSync(path.join(TMP, "shot.png"), PNG_BYTES);
37
+ writeFileSync(path.join(TMP, "notes.md"), "# Notes\nhello\n");
38
+ writeFileSync(path.join(TMP, "big.md"), "x".repeat(150_000));
39
+ });
40
+ after(() => {
41
+ rmSync(TMP, { recursive: true, force: true });
42
+ delete process.env.PI_CODING_AGENT_DIR;
43
+ });
44
+
45
+ const img = path.join(TMP, "shot.png");
46
+ const md = path.join(TMP, "notes.md");
47
+ const big = path.join(TMP, "big.md");
48
+
49
+ /** Minimal ExtensionAPI double capturing the registered input handler. */
50
+ function harness() {
51
+ const handlers: Record<string, Function> = {};
52
+ const shortcuts: Array<{ shortcut: string; options: any }> = [];
53
+ const fake = {
54
+ on: (event: string, handler: Function) => {
55
+ handlers[event] = handler;
56
+ },
57
+ registerShortcut: (shortcut: string, options: any) => shortcuts.push({ shortcut, options }),
58
+ } as any;
59
+ piAttachments(fake);
60
+ return { input: handlers["input"], start: handlers["session_start"], shortcuts };
61
+ }
62
+
63
+ /** Wire session_start (registers terminal-input listener) and capture it. */
64
+ function harnessWithPaste(h: ReturnType<typeof harness>) {
65
+ let terminalHandler: Function | undefined;
66
+ h.start({}, { ui: { onTerminalInput: (fn: Function) => (terminalHandler = fn), setWidget: () => {} } });
67
+ return (data: string) => terminalHandler?.(data);
68
+ }
69
+
70
+ const run = async (
71
+ h: ReturnType<typeof harness>,
72
+ text: string,
73
+ source = "interactive",
74
+ images?: Array<{ type: "image"; data: string; mimeType: string }>,
75
+ ) =>
76
+ (
77
+ (await h.input(
78
+ { type: "input", text, source, ...(images ? { images } : {}) },
79
+ { ui: { getEditorText: () => text, setWidget: () => {} } },
80
+ )) ?? { action: "continue" }
81
+ );
82
+
83
+
84
+ describe("extractImagePaths", () => {
85
+ it("finds existing image paths, deduped", () => {
86
+ assert.deepEqual(extractImagePaths(`look at ${img} and ${img}`), [img]);
87
+ });
88
+
89
+ it("ignores nonexistent image paths", () => {
90
+ assert.deepEqual(extractImagePaths("see /tmp/definitely-missing-xyz.png here"), []);
91
+ });
92
+
93
+ it("prose false-positives produce zero matches", () => {
94
+ assert.deepEqual(extractImagePaths("the .jpg extension is common"), []);
95
+ assert.deepEqual(extractImagePaths("rename file png to webp"), []);
96
+ assert.deepEqual(extractImagePaths("output: 'quoted.png' stays unquoted"), []);
97
+ });
98
+
99
+ it("matches paths with escaped spaces (terminal drop form)", () => {
100
+ const spaced = path.join(TMP, "with space.png");
101
+ writeFileSync(spaced, PNG_BYTES);
102
+ const escaped = spaced.replace(/ /g, "\\ "); // Terminal.app pastes "with\ space.png"
103
+ assert.deepEqual(extractImagePaths(`dropped ${escaped}`), [spaced]);
104
+ });
105
+
106
+ it("matches Windows drive-letter paths (image + text)", () => {
107
+ // On POSIX isFile() rejects these paths, so assert raw regex matching.
108
+ const matches = (t: string) => t.match(new RegExp(ABSOLUTE_PATH_RE.source, "g")) ?? [];
109
+ assert.deepEqual(matches("C:\\Users\\me\\notes.md"), ["C:\\Users\\me\\notes.md"]);
110
+ assert.deepEqual(matches("C:/Users/me/notes.md"), ["C:/Users/me/notes.md"]);
111
+ assert.deepEqual(matches("D:/data/with\\ space.md"), ["D:/data/with\\ space.md"]);
112
+ assert.deepEqual(absolutePathSpans(md).map((s) => s.path), [md]);
113
+ assert.deepEqual(matches("/posix/never-created.md"), ["/posix/never-created.md"], "POSIX branch unchanged");
114
+ });
115
+ });
116
+
117
+ describe("parseUriList", () => {
118
+ it("parses file URIs and percent-decodes spaces", () => {
119
+ assert.deepEqual(parseUriList("file:///tmp/a%20b.png\r\ncopy\nfile:///tmp/c.md"), ["/tmp/a b.png", "/tmp/c.md"]);
120
+ });
121
+
122
+ it("ignores non-file lines and malformed uris", () => {
123
+ assert.deepEqual(parseUriList("copy\nhttps://x.com/y\nfile://\nfile:///tmp/ok.md"), ["/tmp/ok.md"]);
124
+ });
125
+ });
126
+
127
+ describe("windows clipboard FileDropList parsing", () => {
128
+ // readWindows() joins with `n and splits on /\r?\n/ — a filename containing
129
+ // ';' must survive. PowerShell itself is not exercised in tests (parser only).
130
+ it("newline-split keeps filenames containing ';'", () => {
131
+ const stdout = "C:\\Users\\me\\a;b.txt\r\nC:\\Users\\me\\c.txt";
132
+ const paths = stdout.split(/\r?\n/).map((p) => p.trim()).filter(Boolean);
133
+ assert.deepEqual(paths, ["C:\\Users\\me\\a;b.txt", "C:\\Users\\me\\c.txt"]);
134
+ });
135
+ });
136
+
137
+ describe("loadSettings", () => {
138
+ it("returns defaults when settings file is absent", () => {
139
+ // Don't touch PI_CODING_AGENT_DIR here: the root after() restores it.
140
+ const saved = process.env.PI_CODING_AGENT_DIR;
141
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "no-such-dir");
142
+ try {
143
+ assert.deepEqual(loadSettings(), DEFAULTS);
144
+ } finally {
145
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
146
+ else process.env.PI_CODING_AGENT_DIR = saved;
147
+ }
148
+ });
149
+
150
+ it("reads the attachments key and falls back per-field", () => {
151
+ const dir = path.join(TMP, "cfg");
152
+ mkdirSync(dir, { recursive: true });
153
+ writeFileSync(path.join(dir, "settings.json"), JSON.stringify({ attachments: { maxInlineBytes: 5 } }));
154
+ const saved = process.env.PI_CODING_AGENT_DIR;
155
+ process.env.PI_CODING_AGENT_DIR = dir;
156
+ try {
157
+ const s = loadSettings();
158
+ assert.equal(s.maxInlineBytes, 5);
159
+ assert.equal(s.inlineTextFiles, DEFAULTS.inlineTextFiles);
160
+ assert.equal(s.pasteFileShortcut, DEFAULTS.pasteFileShortcut);
161
+ } finally {
162
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
163
+ else process.env.PI_CODING_AGENT_DIR = saved;
164
+ }
165
+ });
166
+ });
167
+
168
+ describe("isValidShortcut", () => {
169
+ it("accepts modifier combos, bare keys, symbols and specials", () => {
170
+ // pi-tui lowercases the whole KeyId, so uppercase variants are valid too.
171
+ for (const ok of ["alt+shift+v", "Ctrl+Shift+V", "Alt+Shift+V", "ctrl+c", "ctrl+shift+alt+delete", "super+k", "f2", "v", "/", "pageUp", "ctrl+enter"])
172
+ assert.equal(isValidShortcut(ok), true, ok);
173
+ });
174
+
175
+ it("rejects bad grammar and empty", () => {
176
+ for (const bad of ["", "not+a+key", "ctrl+", "+v", "ctrl v", "f13"])
177
+ assert.equal(isValidShortcut(bad), false, JSON.stringify(bad));
178
+ });
179
+ });
180
+
181
+ describe("pasteFileShortcut validation warning", () => {
182
+ const writeCfg = (shortcut: string) => {
183
+ const dir = path.join(TMP, "cfg-shortcut");
184
+ mkdirSync(dir, { recursive: true });
185
+ writeFileSync(path.join(dir, "settings.json"), JSON.stringify({ attachments: { pasteFileShortcut: shortcut } }));
186
+ const saved = process.env.PI_CODING_AGENT_DIR;
187
+ process.env.PI_CODING_AGENT_DIR = dir;
188
+ return () => {
189
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
190
+ else process.env.PI_CODING_AGENT_DIR = saved;
191
+ };
192
+ };
193
+
194
+ it("warns via ui.notify when the configured shortcut is invalid", () => {
195
+ const restore = writeCfg("garbage-key");
196
+ try {
197
+ const h = harness();
198
+ const notifies: Array<{ msg: string; level: string }> = [];
199
+ h.start({}, {
200
+ ui: {
201
+ notify: (msg: string, level: string) => notifies.push({ msg, level }),
202
+ onTerminalInput: () => {},
203
+ setWidget: () => {},
204
+ },
205
+ });
206
+ assert.equal(notifies.length, 1, "exactly one warning");
207
+ assert.equal(notifies[0].level, "warning");
208
+ assert.match(notifies[0].msg, /pasteFileShortcut/);
209
+ assert.match(notifies[0].msg, /never trigger/);
210
+ } finally {
211
+ restore();
212
+ }
213
+ });
214
+
215
+ it("no warning for a valid shortcut; console.warn fallback without ui", () => {
216
+ const restore = writeCfg("alt+shift+v");
217
+ const origWarn = console.warn;
218
+ const warns: string[] = [];
219
+ console.warn = (m: string) => warns.push(m);
220
+ try {
221
+ const h = harness();
222
+ const notifies: unknown[] = [];
223
+ h.start({}, {
224
+ ui: { notify: (...a: unknown[]) => notifies.push(a), onTerminalInput: () => {}, setWidget: () => {} },
225
+ });
226
+ assert.equal(notifies.length, 0, "valid shortcut stays silent");
227
+ } finally {
228
+ restore();
229
+ }
230
+ // Fallback path: invalid shortcut + no ui.notify → console.warn.
231
+ const restore2 = writeCfg("nope");
232
+ try {
233
+ const h = harness();
234
+ h.start({}, { ui: { onTerminalInput: () => {}, setWidget: () => {} } });
235
+ assert.equal(warns.length, 1);
236
+ assert.match(warns[0], /pasteFileShortcut/);
237
+ } finally {
238
+ console.warn = origWarn;
239
+ restore2();
240
+ }
241
+ });
242
+ });
243
+
244
+ describe("registry persistence", () => {
245
+ it("remember() creates a fresh agent dir and an atomic, parseable registry file", () => {
246
+ const dir = path.join(TMP, "fresh-agent");
247
+ const fresh = path.join(TMP, "fresh.md");
248
+ writeFileSync(fresh, "fresh\n");
249
+ const saved = process.env.PI_CODING_AGENT_DIR;
250
+ process.env.PI_CODING_AGENT_DIR = dir;
251
+ try {
252
+ remember("fresh.md", fresh);
253
+ assert.equal(lookup("fresh.md"), fresh);
254
+ const raw = JSON.parse(readFileSync(registryPath(), "utf-8"));
255
+ assert.equal(raw["fresh.md"], fresh);
256
+ } finally {
257
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
258
+ else process.env.PI_CODING_AGENT_DIR = saved;
259
+ }
260
+ });
261
+ });
262
+
263
+ describe("AttachmentTray", () => {
264
+ it("adds, renders, expands, prunes, clears", () => {
265
+ const tray = new AttachmentTray();
266
+ const a = tray.add("/tmp/a.png");
267
+ const b = tray.add("/tmp/b.md");
268
+ assert.equal(tray.size, 2);
269
+ assert.equal(a.token, "[[attach:a.png]]");
270
+ assert.equal(b.token, "[[attach:b.md]]");
271
+ assert.deepEqual(tray.render(), ["📎 a.png · b.md"]);
272
+ const expanded = tray.expand(`look ${a.token} and ${b.token}`);
273
+ assert.equal(expanded, "look /tmp/a.png and /tmp/b.md");
274
+ assert.deepEqual(tray.resolve(`look ${a.token} and ${b.token}`), [a, b]);
275
+ tray.prune(`only ${a.token} left`);
276
+ assert.deepEqual(tray.render(), ["📎 a.png"]);
277
+ assert.deepEqual(tray.resolve(`${a.token} x`), [a]);
278
+ tray.clear();
279
+ assert.equal(tray.size, 0);
280
+ assert.deepEqual(tray.render(), []);
281
+ });
282
+
283
+ it("same-basename files get unique token names", () => {
284
+ const tray = new AttachmentTray();
285
+ const a = tray.add("/tmp/dir1/demo.jpeg");
286
+ const b = tray.add("/tmp/dir2/demo.jpeg");
287
+ assert.equal(a.token, "[[attach:demo.jpeg]]");
288
+ assert.equal(b.token, "[[attach:demo-2.jpeg]]");
289
+ assert.ok(tray.expand(`${a.token} ${b.token}`).includes("/tmp/dir2/demo.jpeg"));
290
+ });
291
+ });
292
+
293
+ let inlineDirCounter = 0;
294
+
295
+ /** 0.3.1: session_start re-reads settings — keep a temp PI_CODING_AGENT_DIR
296
+ * active through start (and input for start-less runs); restore after first use. */
297
+ function keepSettingsThrough(h: ReturnType<typeof harness>, saved: string | undefined): ReturnType<typeof harness> {
298
+ const restore = () => {
299
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
300
+ else process.env.PI_CODING_AGENT_DIR = saved;
301
+ };
302
+ let restored = false;
303
+ const once = () => { if (!restored) { restored = true; restore(); } };
304
+ const realStart = h.start;
305
+ h.start = (event: unknown, ctx: unknown) => {
306
+ try { return realStart(event, ctx); } finally { once(); }
307
+ };
308
+ const realInput = h.input;
309
+ h.input = (event: unknown, ctx: unknown) => {
310
+ try { return realInput(event, ctx); } finally { once(); }
311
+ };
312
+ return h;
313
+ }
314
+
315
+ /** Harness whose piAttachments() sees inlineTextFiles: true via a temp settings dir. */
316
+ function inlineHarness() {
317
+ const dir = path.join(TMP, `inline-${inlineDirCounter++}`);
318
+ mkdirSync(dir, { recursive: true });
319
+ writeFileSync(
320
+ path.join(dir, "settings.json"),
321
+ JSON.stringify({ attachments: { inlineTextFiles: true, pasteCollapseLines: 10 } }),
322
+ );
323
+ const saved = process.env.PI_CODING_AGENT_DIR;
324
+ process.env.PI_CODING_AGENT_DIR = dir;
325
+ return keepSettingsThrough(harness(), saved);
326
+ }
327
+
328
+ describe("input transform", () => {
329
+ it("converts an existing image path into an ImageContent part", async () => {
330
+ const result = await run(harness(), `what is in ${img}?`);
331
+ assert.equal(result.action, "transform");
332
+ assert.equal(result.images.length, 1);
333
+ assert.equal(result.images[0].mimeType, "image/png");
334
+ assert.equal(Buffer.from(result.images[0].data, "base64").length, PNG_BYTES.length);
335
+ assert.ok(result.text.includes(img)); // path text kept as reference
336
+ });
337
+
338
+ it("inlines small text files as <file> blocks (inlineTextFiles opt-in)", async () => {
339
+ const result = await run(inlineHarness(), `summarize ${md}`);
340
+ assert.equal(result.action, "transform");
341
+ assert.ok(result.text.includes(`<file name="${md}">\n# Notes\nhello\n</file>`));
342
+ assert.ok(!result.text.includes(`summarize ${md}`));
343
+ });
344
+
345
+ it("default mode: typed text path is left as a bare path (no inline, no token)", async () => {
346
+ const result = await run(harness(), `summarize ${md}`);
347
+ assert.equal(result.action, "continue");
348
+ });
349
+
350
+ it("default mode: dropped-text-file token resolves to a 📎 path, no content dump", async () => {
351
+ const cookies = path.join(TMP, "medium.com_cookies.txt");
352
+ writeFileSync(cookies, "k=v\n");
353
+ remember("cookies.txt", cookies);
354
+ const h = harness();
355
+ const result = await run(h, `what is in [[attach:cookies.txt]] ?`);
356
+ assert.equal(result.action, "transform");
357
+ assert.ok(result.text.includes(`📎 ${cookies}`));
358
+ assert.ok(!result.text.includes("<file"), "no content block");
359
+ assert.ok(!result.text.includes("[[attach:"), "token resolved");
360
+ });
361
+
362
+ it("registry token whose file was deleted stays literal (stale lookup)", async () => {
363
+ const stale = path.join(TMP, "gone.txt");
364
+ writeFileSync(stale, "temp\n");
365
+ remember("gone.txt", stale);
366
+ rmSync(stale); // file deleted since the drop (or machine restarted)
367
+ assert.equal(lookup("gone.txt"), undefined, "lookup() drops stale entries");
368
+ const h = harness();
369
+ const result = await run(h, "summarize [[attach:gone.txt]]");
370
+ assert.equal(result.action, "continue");
371
+ assert.ok(result.text === undefined, "no transform — token left as-is for the model");
372
+ });
373
+
374
+ it("substring paths don't corrupt each other (inline mode)", async () => {
375
+ const bak = md + ".bak";
376
+ writeFileSync(bak, "backup content\n");
377
+ const result = await run(inlineHarness(), `compare ${md} with ${bak}`);
378
+ assert.equal(result.action, "transform");
379
+ assert.ok(result.text.includes(`<file name="${md}">`), "shorter path inlined");
380
+ assert.ok(result.text.includes(`<file name="${bak}">`), "longer path inlined intact");
381
+ assert.ok(result.text.includes("backup content"));
382
+ const blocks = result.text.match(/<file name="[^"]+">[\s\S]*?<\/file>/g) ?? [];
383
+ assert.equal(blocks.length, 2, "exactly two blocks, no nesting");
384
+ });
385
+
386
+ it("skips text files over the size cap (inline mode)", async () => {
387
+ const result = await run(inlineHarness(), `read ${big}`);
388
+ assert.equal(result.action, "continue");
389
+ assert.ok(!result.text?.includes("<file"), "oversized file is not inlined");
390
+ });
391
+
392
+ it("no-op for plain prose", async () => {
393
+ assert.equal((await run(harness(), "hello there, no paths here")).action, "continue");
394
+ });
395
+
396
+ it("skips extension-sourced input", async () => {
397
+ const h = harness();
398
+ assert.ok(!(await h.input({ type: "input", text: `check ${img}`, source: "extension" }, {} as any)));
399
+ });
400
+
401
+ it("token from a PREVIOUS session resolves via the persistent registry", async () => {
402
+ // Simulate: file dropped in an earlier session (registry written), tray now empty.
403
+ const footer = path.join(TMP, "custom-footer.ts");
404
+ writeFileSync(footer, "export const x = 1;\n");
405
+ remember("custom-footer.ts", footer);
406
+ assert.equal(lookup("custom-footer.ts"), footer);
407
+
408
+ // Fresh extension load (new session) — tray is empty but registry knows the file.
409
+ const h = harness();
410
+ const result = await run(h, "what is [[attach:custom-footer.ts]] ?");
411
+ assert.equal(result.action, "transform");
412
+ assert.ok(result.text.includes(footer), "token expanded via registry");
413
+ assert.ok(!result.text.includes("[[attach:"), "no dead token left");
414
+ });
415
+
416
+ it("registers the paste-file shortcut", () => {
417
+ const h = harness();
418
+ assert.equal(h.shortcuts.length, 1);
419
+ assert.equal(h.shortcuts[0].shortcut, DEFAULTS.pasteFileShortcut);
420
+ });
421
+
422
+ it("path-only bracketed paste is rewritten to attachment tokens", () => {
423
+ const h = harness();
424
+ const onPaste = harnessWithPaste(h);
425
+ const result = onPaste(`\x1b[200~${img} ${path.join(TMP, "notes.md")}\x1b[201~`) as any;
426
+ assert.ok(result?.data);
427
+ const tokens = result.data.split(" ");
428
+ assert.equal(tokens.length, 2);
429
+ assert.match(tokens[0], /^\[\[attach:[^\]]+\]\]$/);
430
+ // tokens expand back to real paths at submit → images/text inline as usual
431
+ });
432
+
433
+ it("directory paste passes through untouched (no token, no chip)", () => {
434
+ const dir = path.join(TMP, "dropped-dir");
435
+ mkdirSync(dir, { recursive: true });
436
+ const spacedDir = path.join(TMP, "spaced dir");
437
+ mkdirSync(spacedDir, { recursive: true });
438
+ const h = harness();
439
+ const onPaste = harnessWithPaste(h);
440
+ assert.equal(onPaste(`\x1b[200~${dir}\x1b[201~`), undefined);
441
+ assert.equal(
442
+ onPaste(`\x1b[200~${spacedDir.replace(/ /g, "\\ ")}\x1b[201~`),
443
+ undefined,
444
+ "escaped-space directory passes through",
445
+ );
446
+ });
447
+
448
+ it("mixed file + directory paste tokenizes only the file", () => {
449
+ const dir = path.join(TMP, "mixed-dir");
450
+ mkdirSync(dir, { recursive: true });
451
+ const h = harness();
452
+ const onPaste = harnessWithPaste(h);
453
+ const result = onPaste(`\x1b[200~${img} ${dir}\x1b[201~`) as any;
454
+ assert.ok(result?.data);
455
+ const [token, literal] = result.data.split(" ");
456
+ assert.match(token, /^\[\[attach:shot\.png\]\]$/);
457
+ assert.equal(literal, dir, "directory stays literal text");
458
+ });
459
+
460
+ it("mixed paste with an escaped-space directory keeps the escaped literal", () => {
461
+ const spacedDir = path.join(TMP, "mixed spaced dir");
462
+ mkdirSync(spacedDir, { recursive: true });
463
+ const escaped = spacedDir.replace(/ /g, "\\ ");
464
+ const h = harness();
465
+ const onPaste = harnessWithPaste(h);
466
+ const result = onPaste(`\x1b[200~${img} ${escaped}\x1b[201~`) as any;
467
+ assert.ok(result?.data);
468
+ assert.ok(result.data.startsWith("[[attach:shot.png]] "), "file tokenized");
469
+ assert.ok(result.data.endsWith(escaped), "escaped directory kept verbatim");
470
+ });
471
+
472
+ it("mixed file + directory paste survives submit: dir literal, file attached", async () => {
473
+ const dir = path.join(TMP, "submit-dir");
474
+ mkdirSync(dir, { recursive: true });
475
+ const h = harness();
476
+ const onPaste = harnessWithPaste(h);
477
+ const pasted = onPaste(`\x1b[200~${img} ${dir}\x1b[201~`) as any;
478
+ const result = await run(h, pasted.data);
479
+ assert.equal(result.action, "transform");
480
+ assert.equal(result.images.length, 1, "file attached as image");
481
+ assert.ok(result.text.includes(dir), "directory stays literal text");
482
+ assert.ok(!result.text.includes("[[attach:"), "no dead token left");
483
+ });
484
+
485
+ it("inline mode: mixed paste submits to exactly one <file> block + literal dir", async () => {
486
+ const dir = path.join(TMP, "inline-mixed-dir");
487
+ mkdirSync(dir, { recursive: true });
488
+ const h = inlineHarness();
489
+ const onPaste = harnessWithPaste(h);
490
+ const pasted = onPaste(`\x1b[200~${path.join(TMP, "notes.md")} ${dir}\x1b[201~`) as any;
491
+ const result = await run(h, pasted.data);
492
+ assert.equal(result.action, "transform");
493
+ assert.equal((result.text.match(/<file name="/g) ?? []).length, 1, "exactly one <file> block");
494
+ assert.ok(!result.text.includes('<file name="<file'), "no nested <file> block");
495
+ assert.ok(result.text.includes(dir), "directory stays literal");
496
+ });
497
+
498
+ it("mixed text paste passes through untouched", () => {
499
+ const h = harness();
500
+ const onPaste = harnessWithPaste(h);
501
+ assert.equal(onPaste("\x1b[200~hello world /tmp\x1b[201~"), undefined);
502
+ assert.equal(onPaste("plain keys"), undefined);
503
+ });
504
+
505
+ it("Windows drive-letter paste payload is treated as path-like (not text-collapse)", () => {
506
+ // On POSIX `C:\...` doesn't exist, so nothing tokenizes and the payload
507
+ // passes through (undefined, not a paste-collapse token). The assertion
508
+ // pins the looksLikePathPayload drive-letter branch; on Windows the real
509
+ // fs decides and existing files become [[attach:]] tokens.
510
+ const h = harness();
511
+ const onPaste = harnessWithPaste(h);
512
+ assert.equal(onPaste("\x1b[200~C:\\Users\\me\\shot.png\x1b[201~"), undefined);
513
+ });
514
+
515
+ it("token flow: pasted tokens expand to real content at submit", async () => {
516
+ const h = harness();
517
+ const onPaste = harnessWithPaste(h);
518
+ const pasted = onPaste(`\x1b[200~${img}\x1b[201~`) as any;
519
+ const token = pasted.data.trim();
520
+ const result = await run(h, `what is ${token}?`);
521
+ assert.equal(result.action, "transform");
522
+ assert.equal(result.images.length, 1);
523
+ assert.ok(result.text.includes(img), "expanded to the real path");
524
+ assert.ok(!result.text.includes(token), "token replaced");
525
+ });
526
+
527
+ it("basename containing ] is attached on submit (no dead token)", async () => {
528
+ const weird = path.join(TMP, "we]ird.png");
529
+ writeFileSync(weird, PNG_BYTES);
530
+ const h = harness();
531
+ const onPaste = harnessWithPaste(h);
532
+ const pasted = onPaste(`\x1b[200~${weird}\x1b[201~`) as any;
533
+ const result = await run(h, pasted.data.trim());
534
+ assert.equal(result.action, "transform");
535
+ assert.equal(result.images.length, 1, "image attached");
536
+ assert.ok(result.text.includes(weird), "resolved to the real path");
537
+ assert.ok(!result.text.includes("[[attach:"), "no dead token left");
538
+ });
539
+
540
+ it("escaped-space path drop becomes a token and resolves to the real path", async () => {
541
+ const spaced = path.join(TMP, "with space.png");
542
+ writeFileSync(spaced, PNG_BYTES);
543
+ const escaped = spaced.replace(/ /g, "\\ "); // Terminal.app drop form
544
+ const h = harness();
545
+ const onPaste = harnessWithPaste(h);
546
+ const pasted = onPaste(`\x1b[200~${escaped}\x1b[201~`) as any;
547
+ assert.equal(pasted.data, "[[attach:with space.png]]");
548
+ const result = await run(h, `what is ${pasted.data}?`);
549
+ assert.equal(result.action, "transform");
550
+ assert.equal(result.images.length, 1);
551
+ assert.ok(result.text.includes(spaced), "token resolved to the unescaped path");
552
+ });
553
+
554
+ it("same image via two tokens is attached only once", async () => {
555
+ const h = harness();
556
+ const onPaste = harnessWithPaste(h);
557
+ const pasted = onPaste(`\x1b[200~${img} ${img}\x1b[201~`) as any;
558
+ const [t1, t2] = pasted.data.split(" ");
559
+ assert.notEqual(t1, t2, "second drop gets a unique token");
560
+ const result = await run(h, `${t1} ${t2}`);
561
+ assert.equal(result.action, "transform");
562
+ assert.equal(result.images.length, 1, "duplicate path attached once");
563
+ assert.equal((result.text.match(/📎/g) ?? []).length, 2, "both tokens replaced by the path chip");
564
+ });
565
+
566
+ it("preserves pre-existing event images when adding discovered ones", async () => {
567
+ const prior = { type: "image" as const, data: "UVp", mimeType: "image/png" };
568
+ const result = await run(harness(), `what is in ${img}?`, "interactive", [prior]);
569
+ assert.equal(result.action, "transform");
570
+ assert.equal(result.images.length, 2);
571
+ assert.equal(result.images[0].data, "UVp", "original event image kept first");
572
+ assert.equal(result.images[1].mimeType, "image/png", "discovered image appended");
573
+ });
574
+
575
+ it("escaped-space text path is inlined like its image counterpart (inline mode)", async () => {
576
+ const spaced = path.join(TMP, "with space.md");
577
+ writeFileSync(spaced, "spaced content\n");
578
+ const escaped = spaced.replace(/ /g, "\\ ");
579
+ const result = await run(inlineHarness(), `summarize ${escaped}`);
580
+ assert.equal(result.action, "transform");
581
+ assert.ok(result.text.includes(`<file name="${spaced}">\nspaced content\n</file>`));
582
+ });
583
+
584
+ it("inline mode: dropped text-file token inlines exactly once (no nested <file>)", async () => {
585
+ const h = inlineHarness();
586
+ const onPaste = harnessWithPaste(h);
587
+ const pasted = onPaste(`\x1b[200~${path.join(TMP, "notes.md")}\x1b[201~`) as any;
588
+ const result = await run(h, pasted.data.trim());
589
+ assert.equal(result.action, "transform");
590
+ assert.equal((result.text.match(/<file name="/g) ?? []).length, 1, "exactly one <file> block");
591
+ assert.ok(!result.text.includes('<file name="<file'), "no nested <file> block");
592
+ });
593
+ });
594
+
595
+ describe("attachment removal flow", () => {
596
+ function fullHarness(withEditorText = true) {
597
+ const handlers: Record<string, Function> = {};
598
+ let widget: string[] | null = null;
599
+ let pasteHandler: Function | undefined;
600
+ let editorText = "";
601
+ const ui = {
602
+ onTerminalInput: (fn: Function) => { pasteHandler = fn; },
603
+ setWidget: (_key: string, lines: string[]) => { widget = lines; },
604
+ ...(withEditorText ? { getEditorText: () => editorText } : {}),
605
+ };
606
+ piAttachments({ on: (e: string, h: Function) => { handlers[e] = h; }, registerShortcut: () => {} } as any);
607
+ handlers["session_start"]({}, { ui });
608
+ return {
609
+ paste: (data: string) => pasteHandler?.(data),
610
+ type: (t: string) => { editorText = t; pasteHandler?.("x"); }, // any keystroke syncs
611
+ submit: (text?: string) =>
612
+ handlers["input"]({ type: "input", text: text ?? editorText, source: "interactive" }, { ui }),
613
+ get widget() { return widget; },
614
+ };
615
+ }
616
+
617
+ it("keystroke prune is skipped on UIs without getEditorText (chips survive)", async () => {
618
+ const file = path.join(TMP, "rm-c.png");
619
+ writeFileSync(file, PNG_BYTES);
620
+ const h = fullHarness(false); // UI lacking getEditorText (prune would see "")
621
+
622
+ const pasted: any = h.paste(`\x1b[200~${file}\x1b[201~`);
623
+ h.type(pasted.data); // fires onTerminalInput → the buggy prune ran here
624
+ assert.ok(h.widget![0].includes("rm-c.png"), "chip survives the keystroke");
625
+
626
+ // submit still attaches: the input hook falls back to event.text for prune
627
+ const result: any = await h.submit();
628
+ assert.equal(result.images.length, 1);
629
+ assert.ok(!result.text.includes("[[attach:"), "token resolved");
630
+ });
631
+
632
+ it("deleting a token from the prompt removes its chip and its attachment", async () => {
633
+ const fileA = path.join(TMP, "rm-a.png");
634
+ const fileB = path.join(TMP, "rm-b.txt");
635
+ writeFileSync(fileA, PNG_BYTES);
636
+ writeFileSync(fileB, "b\n");
637
+ try {
638
+ const h = fullHarness();
639
+
640
+ const pasted: any = h.paste(`\x1b[200~${fileA} ${fileB}\x1b[201~`);
641
+ const tokenA = pasted.data.split(" ")[0];
642
+ const tokenB = pasted.data.split(" ")[1];
643
+ h.type(pasted.data);
644
+ assert.ok(h.widget![0].includes("·"), "both chips shown");
645
+
646
+ // user deletes the second token → next keystroke prunes its chip
647
+ h.type(`${tokenA} look`);
648
+ assert.equal(h.widget!.length, 1, "single chip line");
649
+ assert.ok(h.widget![0].includes("rm-a.png"));
650
+ assert.ok(!h.widget![0].includes("rm-b.txt"), "removed chip is gone");
651
+
652
+ // submit sends only the surviving image
653
+ const result: any = await h.submit();
654
+ assert.equal(result.images.length, 1);
655
+ assert.ok(!result.text.includes("rm-b"), "removed file is not attached");
656
+ assert.ok(!result.text.includes(tokenB), "removed token is gone");
657
+ } finally {
658
+ rmSync(fileA, { force: true });
659
+ rmSync(fileB, { force: true });
660
+ }
661
+ });
662
+
663
+ it("all tokens hand-deleted before submit → tray cleared, no stale chips", async () => {
664
+ const file = path.join(TMP, "rm-all.png");
665
+ writeFileSync(file, PNG_BYTES);
666
+ const h = fullHarness();
667
+
668
+ const pasted: any = h.paste(`\x1b[200~${file}\x1b[201~`);
669
+ h.type(pasted.data);
670
+ assert.equal(h.widget!.length, 1, "chip shown");
671
+
672
+ // The stale case: the submitted text no longer contains the token, but the
673
+ // editor (seen by keystroke prune) still does — e.g. submit raced the
674
+ // keystroke sync. Prune misses it; the submit hook must clear instead.
675
+ const result: any = await h.submit("plain question, no token");
676
+ assert.ok(!result || result.action === "continue", "nothing attached");
677
+ assert.deepEqual(h.widget, [], "tray cleared — no stale chip");
678
+ });
679
+ });
680
+
681
+ describe("terminal-input listener lifecycle", () => {
682
+ // session_start fires once per session; the disposer returned by
683
+ // onTerminalInput must be called before re-registering, or listeners
684
+ // stack across sessions and one paste produces duplicate tokens.
685
+ function sessionCtx(listeners: Function[]) {
686
+ return {
687
+ ui: {
688
+ onTerminalInput: (fn: Function) => {
689
+ listeners.push(fn);
690
+ return () => { listeners.splice(listeners.indexOf(fn), 1); };
691
+ },
692
+ setWidget: () => {},
693
+ },
694
+ };
695
+ }
696
+
697
+ it("second session_start disposes the first listener (no stacking)", () => {
698
+ const h = harness();
699
+ const listeners: Function[] = [];
700
+ h.start({}, sessionCtx(listeners));
701
+ h.start({}, sessionCtx(listeners));
702
+ assert.equal(listeners.length, 1, "exactly one live listener after two sessions");
703
+ const result = (listeners[0] as Function)(`\x1b[200~${img}\x1b[201~`) as any;
704
+ assert.match(result?.data, /^\[\[attach:shot\.png\]\]$/, "paste still works after re-register");
705
+ });
706
+ });
707
+
708
+ describe("paste collapse", () => {
709
+ const wrap = (payload: string) => `\x1b[200~${payload}\x1b[201~`;
710
+ const logWall = (n: number) => Array.from({ length: n }, (_, i) => `log line ${i}`).join("\n");
711
+
712
+ it("large multi-line paste collapses to a paste file + token, resolved read-on-demand", async () => {
713
+ const h = harness();
714
+ const onPaste = harnessWithPaste(h);
715
+ const payload = logWall(15);
716
+ const pasted: any = onPaste(wrap(payload));
717
+ assert.ok(pasted?.data?.startsWith("[[attach:paste_"), "editor receives one paste token");
718
+ assert.ok(!pasted.data.includes("log line"), "payload not inlined into the editor");
719
+
720
+ const result: any = await run(h, pasted.data);
721
+ assert.equal(result.action, "transform");
722
+ const m = result.text.match(/📎 (\S*paste_\d+_\d{6}_\d+\.txt) \(pasted text, 15 lines\)/);
723
+ assert.ok(m, "resolves to the paste path with line-count hint");
724
+ assert.ok(!result.text.includes("log line 3"), "content is not re-inlined");
725
+ assert.equal(readFileSync(m![1], "utf-8"), payload, "paste file holds the payload");
726
+ });
727
+
728
+ it("short paste passes through untouched", () => {
729
+ const onPaste = harnessWithPaste(harness());
730
+ assert.equal(onPaste(wrap("just one line")), undefined);
731
+ });
732
+
733
+ it("char threshold collapses one-line walls (minified JSON)", () => {
734
+ const onPaste = harnessWithPaste(harness());
735
+ const pasted: any = onPaste(wrap(JSON.stringify({ pad: "x".repeat(2500) })));
736
+ assert.ok(pasted?.data?.startsWith("[[attach:paste_"));
737
+ });
738
+
739
+ it("slash-command editor text passes through", () => {
740
+ const h = harness();
741
+ let pasteHandler: Function | undefined;
742
+ h.start({}, { ui: { onTerminalInput: (fn: Function) => (pasteHandler = fn), setWidget: () => {}, getEditorText: () => "/review " } });
743
+ assert.equal(pasteHandler?.(wrap(logWall(15))), undefined);
744
+ });
745
+
746
+ it("pasteCollapseLines/pasteCollapseChars: 0 disables collapse", () => {
747
+ const dir = path.join(TMP, "collapse-off");
748
+ mkdirSync(dir, { recursive: true });
749
+ writeFileSync(path.join(dir, "settings.json"), JSON.stringify({ attachments: { pasteCollapseLines: 0, pasteCollapseChars: 0 } }));
750
+ const saved = process.env.PI_CODING_AGENT_DIR;
751
+ process.env.PI_CODING_AGENT_DIR = dir;
752
+ // keepSettingsThrough: session_start re-reads settings, so the override
753
+ // must stay active through start.
754
+ const h = keepSettingsThrough(harness(), saved);
755
+ const onPaste = harnessWithPaste(h);
756
+ assert.equal(onPaste(wrap(logWall(15))), undefined);
757
+ });
758
+
759
+ it("savePaste sweeps oldest files beyond the cap", () => {
760
+ const saved = process.env.PI_CODING_AGENT_DIR;
761
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "sweep-agent");
762
+ try {
763
+ const a = savePaste("a");
764
+ utimesSync(a, new Date(1000), new Date(1000)); // force oldest mtime
765
+ const b = savePaste("b");
766
+ const c = savePaste("c", 2);
767
+ assert.ok(!existsSync(a), "oldest swept");
768
+ assert.ok(existsSync(b) && existsSync(c), "newer pastes kept");
769
+ const dir = path.join(TMP, "sweep-agent", "pastes");
770
+ assert.equal(readdirSync(dir).filter((f) => /^paste_\d+_\d{6}_\d+\.txt$/.test(f)).length, 2);
771
+ } finally {
772
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
773
+ else process.env.PI_CODING_AGENT_DIR = saved;
774
+ }
775
+ });
776
+
777
+ it("pid-suffixed filenames: two saves in the same second never collide", () => {
778
+ const saved = process.env.PI_CODING_AGENT_DIR;
779
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "pid-agent");
780
+ try {
781
+ const a = savePaste("first payload");
782
+ const b = savePaste("second payload");
783
+ assert.equal(statSync(a).mode & 0o777, 0o600, "paste files are owner-only");
784
+ assert.notEqual(a, b, "distinct paths");
785
+ assert.equal(readFileSync(a, "utf-8"), "first payload");
786
+ assert.equal(readFileSync(b, "utf-8"), "second payload");
787
+ } finally {
788
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
789
+ else process.env.PI_CODING_AGENT_DIR = saved;
790
+ }
791
+ });
792
+
793
+ it("inlineTextFiles does not re-inline a collapsed paste (read-on-demand kept)", async () => {
794
+ const h = inlineHarness();
795
+ const onPaste = harnessWithPaste(h);
796
+ const pasted: any = onPaste(wrap(logWall(15)));
797
+ assert.ok(pasted?.data?.startsWith("[[attach:paste_"));
798
+ const result: any = await run(h, pasted.data);
799
+ assert.equal(result.action, "transform");
800
+ assert.match(result.text, /📎 \S*paste_\d+_\d{6}_\d+\.txt \(pasted text, 15 lines\)/);
801
+ assert.ok(!result.text.includes("<file"), "no <file> block — paste stays read-on-demand");
802
+ });
803
+
804
+ it("CRLF paste is normalized to LF on disk and in the line-count hint", async () => {
805
+ const h = harness();
806
+ const onPaste = harnessWithPaste(h);
807
+ const lf = Array.from({ length: 15 }, (_, i) => `line${i + 1}`).join("\n");
808
+ const pasted: any = onPaste(wrap(lf.replace(/\n/g, "\r\n")));
809
+ assert.ok(pasted?.data?.startsWith("[[attach:paste_"));
810
+ const result: any = await run(h, pasted.data);
811
+ const m = result.text.match(/📎 (\S*paste_\d+_\d{6}_\d+\.txt) \(pasted text, 15 lines\)/);
812
+ assert.ok(m, "hint counts normalized lines");
813
+ const saved = readFileSync(m![1], "utf-8");
814
+ assert.equal(saved, lf, "file content is LF-normalized");
815
+ assert.ok(!saved.includes("\r"), "no stray \\r anywhere");
816
+ });
817
+
818
+ it("disk failure degrades gracefully: no throw, paste passes through untouched", () => {
819
+ // TMP/not-a-dir is a regular FILE, so <agentDir>/pastes mkdirSync throws
820
+ // ENOTDIR deterministically (even as root).
821
+ writeFileSync(path.join(TMP, "not-a-dir"), "i am a file");
822
+ const saved = process.env.PI_CODING_AGENT_DIR;
823
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "not-a-dir", "sub");
824
+ try {
825
+ const h = harness(); // settings load at registration
826
+ const onPaste = harnessWithPaste(h);
827
+ let result: any;
828
+ assert.doesNotThrow(() => {
829
+ result = onPaste(wrap(logWall(15)));
830
+ });
831
+ assert.equal(result, undefined, "paste passes through to the editor");
832
+ } finally {
833
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
834
+ else process.env.PI_CODING_AGENT_DIR = saved;
835
+ }
836
+ });
837
+
838
+ it("unwritable agent dir: file drop degrades gracefully, no crash", () => {
839
+ // remember() in the path-drop branch must not throw either — pi-tui has no
840
+ // try/catch around terminal-input listeners.
841
+ writeFileSync(path.join(TMP, "not-a-dir"), "i am a file");
842
+ const saved = process.env.PI_CODING_AGENT_DIR;
843
+ process.env.PI_CODING_AGENT_DIR = path.join(TMP, "not-a-dir", "sub");
844
+ try {
845
+ const onPaste = harnessWithPaste(harness());
846
+ let result: any;
847
+ assert.doesNotThrow(() => {
848
+ result = onPaste(wrap(img));
849
+ });
850
+ assert.ok(result?.data?.startsWith("[[attach:"), "token still produced, just not persisted");
851
+ } finally {
852
+ if (saved === undefined) delete process.env.PI_CODING_AGENT_DIR;
853
+ else process.env.PI_CODING_AGENT_DIR = saved;
854
+ }
855
+ });
856
+
857
+ it("inlineTextFiles does not re-inline a prior-session paste token", async () => {
858
+ const h = inlineHarness();
859
+ // Simulate a paste registered in an earlier session: the paste file persists
860
+ // on disk, the registry maps token name → path, the tray is session-local
861
+ // (empty here).
862
+ const priorPaste = path.join(TMP, "paste_1_120000_999.txt");
863
+ writeFileSync(priorPaste, "old paste body\n");
864
+ remember("paste_1_120000_999.txt", priorPaste);
865
+ const result: any = await run(h, "[[attach:paste_1_120000_999.txt]]");
866
+ assert.equal(result.action, "transform");
867
+ assert.match(result.text, /📎 \S*paste_1_120000_999\.txt/);
868
+ assert.ok(!result.text.includes("<file"), "paste stays read-on-demand across restarts");
869
+ });
870
+ });