ceulen 0.10.1 → 0.11.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 (41) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +56 -1
  3. package/extensions/lib/plan-bridge.ts +18 -0
  4. package/extensions/lib/registry.ts +14 -0
  5. package/extensions/modules/a2a/index.ts +4 -2
  6. package/extensions/modules/attachments/configPanel.ts +91 -0
  7. package/extensions/modules/attachments/index.ts +274 -0
  8. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  9. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  10. package/extensions/modules/attachments/lib/paths.ts +74 -0
  11. package/extensions/modules/attachments/lib/registry.ts +70 -0
  12. package/extensions/modules/attachments/lib/settings.ts +99 -0
  13. package/extensions/modules/attachments/lib/tray.ts +74 -0
  14. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  15. package/extensions/modules/attachments/test/index.test.ts +870 -0
  16. package/extensions/modules/attachments/test/module.test.ts +53 -0
  17. package/extensions/modules/composer/test/module.test.ts +2 -2
  18. package/extensions/modules/config/index.ts +3 -0
  19. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  20. package/extensions/modules/cron/configPanel.ts +103 -0
  21. package/extensions/modules/cron/index.ts +638 -0
  22. package/extensions/modules/cron/lib/jobs.ts +201 -0
  23. package/extensions/modules/cron/lib/schedule.ts +161 -0
  24. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  25. package/extensions/modules/cron/test/index.test.ts +859 -0
  26. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  27. package/extensions/modules/munin/index.ts +3 -1
  28. package/extensions/modules/permission/index.ts +567 -0
  29. package/extensions/modules/permission/test/permission.test.ts +789 -0
  30. package/extensions/modules/plan/index.ts +5 -0
  31. package/extensions/modules/repair/index.ts +134 -3
  32. package/extensions/modules/repair/test/freshness.test.ts +169 -0
  33. package/extensions/modules/subagent/index.ts +38 -5
  34. package/extensions/modules/subagent/lib/runner.ts +348 -12
  35. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  36. package/extensions/modules/usage/index.ts +193 -71
  37. package/extensions/modules/usage/test/context.test.ts +160 -120
  38. package/extensions/modules/web/index.ts +3 -1
  39. package/extensions/modules/web/test/a11y.test.ts +1 -1
  40. package/package.json +2 -2
  41. package/skills/cron/SKILL.md +58 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Read file paths (not bytes) from the OS clipboard.
3
+ *
4
+ * Each platform exposes copied files as file URLs / file lists:
5
+ * - macOS: «class furl» via osascript (Finder "Copy")
6
+ * - Windows: FileDropList via PowerShell (Explorer "Copy")
7
+ * - Linux: text/uri-list (xclip / wl-paste), gnome-copied-files fallback
8
+ *
9
+ * Missing tools or an empty (file-less) clipboard yield [] — never throws.
10
+ */
11
+
12
+ import { execFile } from "node:child_process";
13
+ import { fileURLToPath } from "node:url";
14
+ import { promisify } from "node:util";
15
+
16
+ const run = promisify(execFile);
17
+
18
+ export async function readClipboardFilePaths(): Promise<string[]> {
19
+ try {
20
+ if (process.platform === "darwin") return await readMac();
21
+ if (process.platform === "win32") return await readWindows();
22
+ return await readLinux();
23
+ } catch {
24
+ return [];
25
+ }
26
+ }
27
+
28
+ async function readMac(): Promise<string[]> {
29
+ // ponytail: single file only; AppleScript repeat-loop if multi-file copies matter
30
+ const { stdout } = await run("osascript", ["-e", 'POSIX path of (the clipboard as «class furl»)'], { timeout: 3000 });
31
+ return [stdout.trim()].filter(Boolean);
32
+ }
33
+
34
+ async function readWindows(): Promise<string[]> {
35
+ const { stdout } = await run(
36
+ "powershell",
37
+ // Newline-join, not ';': a filename containing ';' survives the split.
38
+ ["-NoProfile", "-STA", "-Command", '(Get-Clipboard -Format FileDropList) -join "`n"'],
39
+ { timeout: 5000 },
40
+ );
41
+ return stdout.split(/\r?\n/).map((p) => p.trim()).filter(Boolean);
42
+ }
43
+
44
+ async function readLinux(): Promise<string[]> {
45
+ const isWayland = Boolean(process.env.WAYLAND_DISPLAY) || process.env.XDG_SESSION_TYPE === "wayland";
46
+ const targets: Array<{ cmd: string; args: string[] }> = isWayland
47
+ ? [
48
+ { cmd: "wl-paste", args: ["--type", "text/uri-list"] },
49
+ { cmd: "wl-paste", args: ["--type", "x-special/gnome-copied-files"] },
50
+ ]
51
+ : [
52
+ { cmd: "xclip", args: ["-selection", "clipboard", "-t", "text/uri-list", "-o"] },
53
+ { cmd: "xclip", args: ["-selection", "clipboard", "-t", "x-special/gnome-copied-files", "-o"] },
54
+ ];
55
+ for (const t of targets) {
56
+ try {
57
+ const { stdout } = await run(t.cmd, t.args, { timeout: 2000 });
58
+ const paths = parseUriList(stdout);
59
+ if (paths.length) return paths;
60
+ } catch {
61
+ /* try next target */
62
+ }
63
+ }
64
+ return [];
65
+ }
66
+
67
+ /** Parse `file:///a%20b` lines (uri-list) or `copy\nfile:///...` (gnome-copied-files). */
68
+ export function parseUriList(raw: string): string[] {
69
+ const out: string[] = [];
70
+ for (const line of raw.split(/\r?\n/)) {
71
+ const trimmed = line.trim();
72
+ if (!trimmed.startsWith("file:///") && !trimmed.startsWith("file://localhost/")) continue;
73
+ try {
74
+ out.push(fileURLToPath(trimmed));
75
+ } catch {
76
+ /* skip malformed uri */
77
+ }
78
+ }
79
+ return out;
80
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Collapsed large text pastes (Hermes-style): the pasted payload is written to
3
+ * <agentDir>/pastes/paste_<n>_<HHMMSS>_<pid>.txt and the editor receives an
4
+ * [[attach:name]] token. Unlike Hermes — which re-inlines the full content at
5
+ * submit — the token resolves to a 📎 path, so the paste stays isolated from
6
+ * the chat text and the model reads it on demand.
7
+ */
8
+
9
+ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ // ponytail: oldest-evicted cap; Hermes keeps paste files forever, we don't
14
+ const KEEP = 50;
15
+
16
+ /** Matches paste filenames across modules (inline-suppression, sweep). */
17
+ export const PASTE_NAME_RE = /^paste_\d+_\d{6}_\d+\.txt$/;
18
+
19
+ export function pastesDir(): string {
20
+ const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
21
+ return join(dir, "pastes");
22
+ }
23
+
24
+ let counter = 0;
25
+
26
+ /** Write a paste file, sweep old ones beyond `keep`, return its absolute path. */
27
+ export function savePaste(content: string, keep = KEEP): string {
28
+ const dir = pastesDir();
29
+ mkdirSync(dir, { recursive: true });
30
+ const time = new Date().toTimeString().slice(0, 8).replace(/:/g, "");
31
+ // pid suffix: counter is per-process and the timestamp has 1s resolution —
32
+ // two pi sessions sharing the agent dir could otherwise collide and overwrite.
33
+ const path = join(dir, `paste_${++counter}_${time}_${process.pid}.txt`);
34
+ writeFileSync(path, content, { mode: 0o600 });
35
+ try {
36
+ const files = readdirSync(dir)
37
+ .filter((f) => PASTE_NAME_RE.test(f))
38
+ .map((f) => ({ f, m: statSync(join(dir, f)).mtimeMs }))
39
+ .sort((a, b) => a.m - b.m);
40
+ for (const { f } of files.slice(0, Math.max(0, files.length - keep))) unlinkSync(join(dir, f));
41
+ } catch {
42
+ /* best-effort sweep */
43
+ }
44
+ return path;
45
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * File-path extraction from submitted input text.
3
+ *
4
+ * Conservative by design: images match any existing path with an image
5
+ * extension; text files must be absolute paths (drag-drop and clipboard
6
+ * always produce absolute paths — prose mentions like "see main.rs" never
7
+ * match).
8
+ */
9
+
10
+ import { statSync } from "node:fs";
11
+ // Token may contain backslash-escaped spaces ("with\ space.png" — the form
12
+ // terminals paste on file drops); the escaped form is unescaped before fs access.
13
+ const IMAGE_RE = /[^\s"']+(?:\\ [^\s"']+)*\.(?:png|jpe?g|webp|gif)\b/gi;
14
+ /**
15
+ * Absolute-path token regex: slash segments whose chars may include
16
+ * backslash-escaped spaces (terminal drop form), or Windows drive-letter
17
+ * paths (`C:\Users\x` / `C:/Users/x`) with the same escaped-space charset and
18
+ * backslash as an NTFS separator. isFile() gates every match, so POSIX never
19
+ * false-positives on `C:\…` text and Windows lets the real fs decide.
20
+ */
21
+ export const ABSOLUTE_PATH_RE =
22
+ /(?:\/(?:[\w.@+-]|\\ )+)+|(?:[A-Za-z]:[\\/](?:[\w.@+-]|\\ )+(?:[\\/](?:[\w.@+-]|\\ )+)*)/g;
23
+
24
+ /** A matched absolute-path token: unescaped path plus its literal span in the text. */
25
+ export interface AbsolutePathSpan {
26
+ path: string;
27
+ /** Start of the literal match (incl. any `\ ` escapes) in the source text. */
28
+ start: number;
29
+ /** End of the literal match. */
30
+ end: number;
31
+ }
32
+
33
+ /** All distinct existing-file image paths referenced in text (order-preserving). */
34
+ export function extractImagePaths(text: string): string[] {
35
+ const seen = new Set<string>();
36
+ const out: string[] = [];
37
+ for (const match of text.matchAll(IMAGE_RE)) {
38
+ const p = unescape(match[0]);
39
+ if (seen.has(p)) continue;
40
+ if (!isFile(p)) continue;
41
+ seen.add(p);
42
+ out.push(p);
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Existing absolute non-image path tokens with their literal text spans.
49
+ * One greedy regex pass yields disjoint matches, so a span can never be the
50
+ * prefix of another (e.g. /a/b inside /a/b.c); replacement can therefore use
51
+ * the spans directly, right-to-left.
52
+ */
53
+ export function absolutePathSpans(text: string): AbsolutePathSpan[] {
54
+ const out: AbsolutePathSpan[] = [];
55
+ for (const match of text.matchAll(ABSOLUTE_PATH_RE)) {
56
+ const p = unescape(match[0]);
57
+ if (/\.(?:png|jpe?g|webp|gif)$/i.test(p)) continue; // images are handled separately
58
+ if (!isFile(p)) continue;
59
+ out.push({ path: p, start: match.index, end: match.index + match[0].length });
60
+ }
61
+ return out;
62
+ }
63
+
64
+ function unescape(p: string): string {
65
+ return p.replace(/\\ /g, " ");
66
+ }
67
+
68
+ export function isFile(p: string): boolean {
69
+ try {
70
+ return statSync(p).isFile();
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Persistent token→path registry: survives session restarts so an
3
+ * [[attach:file.ts]] token pasted/referenced in a LATER session still
4
+ * resolves to the dropped file's absolute path.
5
+ *
6
+ * Stored at <agentDir>/pi-attachments.json (non-secret: names + paths only),
7
+ * capped at REGISTRY_MAX entries (oldest evicted).
8
+ */
9
+
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { dirname, join } from "node:path";
13
+
14
+ const REGISTRY_MAX = 200;
15
+
16
+ export function registryPath(): string {
17
+ const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
18
+ return join(dir, "pi-attachments.json");
19
+ }
20
+
21
+ type Registry = Record<string, string>; // name → absolute path
22
+
23
+ function load(): Registry {
24
+ const p = registryPath();
25
+ if (!existsSync(p)) return {};
26
+ try {
27
+ const j = JSON.parse(readFileSync(p, "utf-8"));
28
+ return j && typeof j === "object" ? j : {};
29
+ } catch {
30
+ return {};
31
+ }
32
+ }
33
+
34
+ function save(reg: Registry): void {
35
+ // Evict oldest (first-inserted) entries beyond the cap.
36
+ const keys = Object.keys(reg);
37
+ if (keys.length > REGISTRY_MAX) {
38
+ for (const k of keys.slice(0, keys.length - REGISTRY_MAX)) delete reg[k];
39
+ }
40
+ // Atomic write (tmp + rename): a crash mid-write never leaves a truncated
41
+ // registry, and a fresh PI_CODING_AGENT_DIR gets created on first save.
42
+ const p = registryPath();
43
+ mkdirSync(dirname(p), { recursive: true });
44
+ writeFileSync(`${p}.tmp`, JSON.stringify(reg, null, 2));
45
+ renameSync(`${p}.tmp`, p);
46
+ }
47
+
48
+ export function remember(name: string, path: string): void {
49
+ // Best-effort persistence: pi-tui invokes terminal-input listeners without
50
+ // try/catch, so an unwritable agent dir (EACCES/ENOSPC/ENOTDIR) would crash
51
+ // pi on a plain file drag-drop. Degrade gracefully like lookup() does.
52
+ try {
53
+ const reg = load();
54
+ delete reg[name]; // re-insert at the end (most recent)
55
+ reg[name] = path;
56
+ save(reg);
57
+ } catch {
58
+ /* keep session-local tray only */
59
+ }
60
+ }
61
+
62
+ export function lookup(name: string): string | undefined {
63
+ const path = load()[name];
64
+ if (!path) return undefined;
65
+ try {
66
+ return statSync(path).isFile() ? path : undefined;
67
+ } catch {
68
+ return undefined; // stale token — file deleted or volume gone
69
+ }
70
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Settings from the `attachments` key of Pi's settings.json
3
+ * (~/.pi/agent/settings.json, or PI_CODING_AGENT_DIR). Non-secret only.
4
+ */
5
+
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ export interface AttachmentsSettings {
11
+ /**
12
+ * When true, text-file attachments are inlined as <file> blocks (Claude Code
13
+ * @file style — content dumped into context, re-read every turn).
14
+ * When false (default), they resolve to a 📎 path the model reads on demand.
15
+ */
16
+ inlineTextFiles: boolean;
17
+ /** Max bytes for text-file inlining (inlineTextFiles mode only). Default 100_000. */
18
+ maxInlineBytes: number;
19
+ /** Keybinding for paste-file-from-clipboard. Default "alt+shift+v". */
20
+ pasteFileShortcut: string;
21
+ /** Pastes with ≥ this many lines collapse to a paste file + token. 0 disables. Default 10. */
22
+ pasteCollapseLines: number;
23
+ /** Pastes with ≥ this many chars collapse even below the line threshold. 0 disables. Default 2000. */
24
+ pasteCollapseChars: number;
25
+ }
26
+
27
+ export const DEFAULTS: AttachmentsSettings = {
28
+ inlineTextFiles: false,
29
+ maxInlineBytes: 100_000,
30
+ pasteFileShortcut: "alt+shift+v",
31
+ pasteCollapseLines: 10,
32
+ pasteCollapseChars: 2000,
33
+ };
34
+
35
+ /** Read-modify-write `attachments.*` keys into the GLOBAL settings.json
36
+ * (merge, never clobber; atomic tmp+rename; a corrupt file refuses to clobber).
37
+ * Only the given patch keys are written. Returns the written path.
38
+ * Exported for tests + the /config save path. */
39
+ export function writeAttachmentsSection(patch: Partial<AttachmentsSettings>): string {
40
+ const file = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "settings.json");
41
+ let settings: Record<string, unknown>;
42
+ try {
43
+ settings = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>) : {};
44
+ } catch {
45
+ throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
46
+ }
47
+ const s = (settings.attachments ?? {}) as Record<string, unknown>;
48
+ Object.assign(s, patch);
49
+ settings.attachments = s;
50
+ mkdirSync(join(file, ".."), { recursive: true });
51
+ const tmp = file + ".tmp";
52
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
53
+ renameSync(tmp, file);
54
+ return file;
55
+ }
56
+
57
+ export function loadSettings(): AttachmentsSettings {
58
+ const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
59
+ const p = join(dir, "settings.json");
60
+ if (!existsSync(p)) return { ...DEFAULTS };
61
+ try {
62
+ const raw = JSON.parse(readFileSync(p, "utf-8"))?.attachments ?? {};
63
+ return {
64
+ inlineTextFiles: typeof raw.inlineTextFiles === "boolean" ? raw.inlineTextFiles : DEFAULTS.inlineTextFiles,
65
+ maxInlineBytes: typeof raw.maxInlineBytes === "number" && raw.maxInlineBytes > 0 ? raw.maxInlineBytes : DEFAULTS.maxInlineBytes,
66
+ pasteFileShortcut: typeof raw.pasteFileShortcut === "string" && raw.pasteFileShortcut ? raw.pasteFileShortcut : DEFAULTS.pasteFileShortcut,
67
+ pasteCollapseLines: typeof raw.pasteCollapseLines === "number" && raw.pasteCollapseLines >= 0 ? raw.pasteCollapseLines : DEFAULTS.pasteCollapseLines,
68
+ pasteCollapseChars: typeof raw.pasteCollapseChars === "number" && raw.pasteCollapseChars >= 0 ? raw.pasteCollapseChars : DEFAULTS.pasteCollapseChars,
69
+ };
70
+ } catch {
71
+ return { ...DEFAULTS };
72
+ }
73
+ }
74
+
75
+ /* Runtime mirror of pi-tui's KeyId grammar: modifier(+modifier)*+base.
76
+ * A value outside this grammar registers fine but never matches a key event
77
+ * (the TUI compares against parsed KeyIds) — a silent no-op for the user. */
78
+ const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
79
+ // Lowercase entries — pi-tui lowercases the whole KeyId, so "pageUp" is
80
+ // parsed/compared as "pageup".
81
+ const SPECIAL_KEYS = new Set([
82
+ "escape", "esc", "enter", "return", "tab", "space", "backspace", "delete", "insert", "clear",
83
+ "home", "end", "pageup", "pagedown", "up", "down", "left", "right",
84
+ ...Array.from({ length: 12 }, (_, i) => `f${i + 1}`),
85
+ ]);
86
+ const SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(""));
87
+
88
+ /** True when `s` is a valid pi-tui KeyId (e.g. "alt+shift+v", "ctrl+enter", "f2").
89
+ * Matches pi-tui's parseKeyId exactly: case-insensitive (lowercases the whole
90
+ * id) and duplicate-modifier tolerant (parts.includes), so "Ctrl+Shift+V" and
91
+ * even "ctrl+ctrl+v" are real shortcuts — the validator must not warn about
92
+ * shortcuts pi-tui actually accepts. */
93
+ export function isValidShortcut(s: string): boolean {
94
+ if (typeof s !== "string" || s.length === 0) return false;
95
+ const parts = s.toLowerCase().split("+");
96
+ const base = parts.pop()!;
97
+ const isBase = /^[a-z0-9]$/.test(base) || SPECIAL_KEYS.has(base) || SYMBOL_KEYS.has(base);
98
+ return isBase && parts.every((m) => MODIFIERS.has(m));
99
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Pending-attachment tray: holds files queued by drag-drop paste / clipboard
3
+ * paste until submit. The tray renders as a single chip line above the editor;
4
+ * on submit the input hook swaps the [[attach:name]] tokens for real content.
5
+ */
6
+
7
+ import { basename } from "node:path";
8
+
9
+ export interface PendingAttachment {
10
+ /** [[attach:name]] token inserted into the editor text (filename-based). */
11
+ token: string;
12
+ path: string;
13
+ /** Display name used inside the token (unique across the tray). */
14
+ name: string;
15
+ /** Optional detail appended to the 📎 chip at submit (e.g. paste line count). */
16
+ hint?: string;
17
+ }
18
+
19
+ export class AttachmentTray {
20
+ private items: PendingAttachment[] = [];
21
+
22
+ add(path: string, hint?: string): PendingAttachment {
23
+ const name = this.uniqueName(basename(path));
24
+ const item: PendingAttachment = { token: `[[attach:${name}]]`, path, name };
25
+ if (hint) item.hint = hint;
26
+ this.items.push(item);
27
+ return item;
28
+ }
29
+
30
+ /** Resolve tokens still present in submitted text; returns kept items in order. */
31
+ resolve(text: string): PendingAttachment[] {
32
+ return this.items.filter((i) => text.includes(i.token));
33
+ }
34
+
35
+ /** Replace every live [[attach:name]] token in text with the real path (for the input hook). */
36
+ expand(text: string): string {
37
+ let out = text;
38
+ for (const i of this.items) {
39
+ if (out.includes(i.token)) out = out.split(i.token).join(i.path);
40
+ }
41
+ return out;
42
+ }
43
+
44
+ /** Drop items whose tokens are gone from the editor (user deleted them). */
45
+ prune(editorText: string): void {
46
+ this.items = this.items.filter((i) => editorText.includes(i.token));
47
+ }
48
+
49
+ clear(): void {
50
+ this.items = [];
51
+ }
52
+
53
+ get size(): number {
54
+ return this.items.length;
55
+ }
56
+
57
+ /** Single chip line: 📎 demo.jpeg · C601079.pdf */
58
+ render(): string[] {
59
+ if (this.items.length === 0) return [];
60
+ return [`📎 ${this.items.map((i) => i.name).join(" · ")}`];
61
+ }
62
+
63
+ /** First basename is used as-is; duplicates get -2, -3… before the extension. */
64
+ private uniqueName(base: string): string {
65
+ if (!this.items.some((i) => i.name === base)) return base;
66
+ const dot = base.lastIndexOf(".");
67
+ const stem = dot > 0 ? base.slice(0, dot) : base;
68
+ const ext = dot > 0 ? base.slice(dot) : "";
69
+ for (let n = 2; ; n++) {
70
+ const candidate = `${stem}-${n}${ext}`;
71
+ if (!this.items.some((i) => i.name === candidate)) return candidate;
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,122 @@
1
+ // attachments' /config contribution: row keys + Files tab, save routing
2
+ // (only attachments.* edits persist, working copy driven via row.set()),
3
+ // and the corrupt-file guard.
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { after, beforeEach, describe, it } from "node:test";
9
+ import { applyRows } from "../../../lib/panel.js";
10
+ import { attachmentsConfig, buildAttachmentsGroups } from "../configPanel.js";
11
+ import { DEFAULTS, loadSettings } from "../lib/settings.js";
12
+
13
+ const realAgentDir = process.env.PI_CODING_AGENT_DIR;
14
+ let AGENT: string;
15
+
16
+ beforeEach(() => {
17
+ AGENT = mkdtempSync(join(tmpdir(), "ceulen-att-cfg-"));
18
+ process.env.PI_CODING_AGENT_DIR = AGENT;
19
+ });
20
+
21
+ after(() => {
22
+ if (realAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
23
+ else process.env.PI_CODING_AGENT_DIR = realAgentDir;
24
+ });
25
+
26
+ const fakeCtx = (notified: string[] = []): any => ({
27
+ cwd: AGENT,
28
+ ui: { notify: (message: string) => { notified.push(message); } },
29
+ });
30
+
31
+ describe("attachments config panel", () => {
32
+ it("rows: the five attachments keys on the Files tab", () => {
33
+ const groups = buildAttachmentsGroups({ ...DEFAULTS });
34
+ assert.equal(groups.length, 1);
35
+ const group = groups[0];
36
+ assert.equal(group.tab, "Files");
37
+ assert.equal(group.label, "Attachments");
38
+ assert.deepEqual(
39
+ group.rows.map((r) => r.key),
40
+ [
41
+ "attachments.inlineTextFiles",
42
+ "attachments.maxInlineBytes",
43
+ "attachments.pasteFileShortcut",
44
+ "attachments.pasteCollapseLines",
45
+ "attachments.pasteCollapseChars",
46
+ ],
47
+ );
48
+ assert.equal(group.rows[0].kind, "toggle");
49
+ // The shortcut row carries the load-bound restart warning.
50
+ assert.match(group.rows[2].warning ?? "", /restart/i);
51
+ });
52
+
53
+ it("applyRows round-trips a working copy", () => {
54
+ const cfg = { ...DEFAULTS };
55
+ const groups = buildAttachmentsGroups(cfg);
56
+ const byKey = new Map(groups[0].rows.map((r) => [r.key, r]));
57
+ byKey.get("attachments.inlineTextFiles")!.set(true);
58
+ byKey.get("attachments.maxInlineBytes")!.set(5_000);
59
+ byKey.get("attachments.pasteCollapseLines")!.set(0);
60
+ applyRows(cfg, groups);
61
+ assert.equal(cfg.inlineTextFiles, true);
62
+ assert.equal(cfg.maxInlineBytes, 5_000);
63
+ assert.equal(cfg.pasteCollapseLines, 0);
64
+ assert.equal(cfg.pasteCollapseChars, DEFAULTS.pasteCollapseChars, "untouched field stays default");
65
+ });
66
+
67
+ it("save persists edited keys to the GLOBAL attachments section (rows driven first)", async () => {
68
+ mkdirSync(AGENT, { recursive: true });
69
+ writeFileSync(join(AGENT, "settings.json"), JSON.stringify({ attachments: { pasteCollapseChars: 999 } }));
70
+ const config = attachmentsConfig();
71
+ // Drive the factory's OWN working copy through the row setters — a save
72
+ // without set() would persist the fresh-from-disk defaults, not the edit.
73
+ const byKey = new Map(config.groups()[0].rows.map((r) => [r.key, r]));
74
+ byKey.get("attachments.inlineTextFiles")!.set(true);
75
+ byKey.get("attachments.maxInlineBytes")!.set(5_000);
76
+ await config.save(new Set(["attachments.inlineTextFiles", "attachments.maxInlineBytes"]), fakeCtx());
77
+ const raw = JSON.parse(readFileSync(join(AGENT, "settings.json"), "utf8"));
78
+ assert.equal(raw.attachments.inlineTextFiles, true);
79
+ assert.equal(raw.attachments.maxInlineBytes, 5_000);
80
+ assert.equal(raw.attachments.pasteCollapseChars, 999, "unrelated sibling key untouched");
81
+ });
82
+
83
+ it("save no-ops when no owned key was edited", async () => {
84
+ const config = attachmentsConfig();
85
+ const before = readSettingsIfExists();
86
+ await config.save(new Set(["plan.savePlans"]), fakeCtx());
87
+ assert.equal(readSettingsIfExists(), before, "file untouched");
88
+ });
89
+
90
+ it("loadSettings round-trips a written section", () => {
91
+ mkdirSync(AGENT, { recursive: true });
92
+ writeFileSync(
93
+ join(AGENT, "settings.json"),
94
+ JSON.stringify({ attachments: { inlineTextFiles: true, pasteCollapseLines: 42 } }),
95
+ );
96
+ const s = loadSettings();
97
+ assert.equal(s.inlineTextFiles, true);
98
+ assert.equal(s.pasteCollapseLines, 42);
99
+ assert.equal(s.pasteFileShortcut, DEFAULTS.pasteFileShortcut, "unset field falls back");
100
+ });
101
+
102
+ it("corrupt settings.json refuses to clobber on save", async () => {
103
+ mkdirSync(AGENT, { recursive: true });
104
+ writeFileSync(join(AGENT, "settings.json"), "{not json");
105
+ const config = attachmentsConfig();
106
+ const byKey = new Map(config.groups()[0].rows.map((r) => [r.key, r]));
107
+ byKey.get("attachments.inlineTextFiles")!.set(true);
108
+ const notified: string[] = [];
109
+ await config.save(new Set(["attachments.inlineTextFiles"]), fakeCtx(notified));
110
+ assert.equal(notified.length, 1);
111
+ assert.match(notified[0], /failed|not valid JSON/i);
112
+ assert.equal(readFileSync(join(AGENT, "settings.json"), "utf8"), "{not json", "corrupt file untouched");
113
+ });
114
+ });
115
+
116
+ function readSettingsIfExists(): string | undefined {
117
+ try {
118
+ return readFileSync(join(AGENT, "settings.json"), "utf8");
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ }