@firstpick/pi-package-webui 0.8.5 → 0.8.7

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 (110) hide show
  1. package/README.md +18 -584
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,238 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { updateStatePaths } from "./journal.mjs";
6
+
7
+ const POINTER_SCHEMA = 1;
8
+ const RESTORE_SCHEMA = 1;
9
+ const MAX_RESTORE_TABS = 256;
10
+ const MAX_RESTORE_BYTES = 2 * 1024 * 1024;
11
+
12
+ function inside(root, candidate) {
13
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
14
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
15
+ }
16
+
17
+ export function managedRuntimePaths(agentDir) {
18
+ const root = updateStatePaths(agentDir).root;
19
+ return Object.freeze({
20
+ root,
21
+ runtimesDir: path.join(root, "runtimes"),
22
+ tempDir: path.join(root, "tmp"),
23
+ currentPointer: path.join(root, "current.json"),
24
+ previousPointer: path.join(root, "previous.json"),
25
+ });
26
+ }
27
+
28
+ async function privateJson(file, value) {
29
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
30
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
31
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
32
+ await chmod(temporary, 0o600).catch(() => undefined);
33
+ try { await rename(temporary, file); } finally { await rm(temporary, { force: true }).catch(() => undefined); }
34
+ await chmod(file, 0o600).catch(() => undefined);
35
+ }
36
+
37
+ export async function readRuntimePointer(agentDir, name = "current") {
38
+ if (!new Set(["current", "previous"]).has(name)) throw new TypeError("pointer name must be current or previous");
39
+ const paths = managedRuntimePaths(agentDir);
40
+ const file = name === "current" ? paths.currentPointer : paths.previousPointer;
41
+ let pointer;
42
+ try { pointer = JSON.parse(await readFile(file, "utf8")); } catch (error) {
43
+ if (error?.code === "ENOENT") return null;
44
+ return null;
45
+ }
46
+ const runtimeRoot = typeof pointer?.runtimeRoot === "string" ? path.resolve(pointer.runtimeRoot) : "";
47
+ const serverEntry = typeof pointer?.serverEntry === "string" ? path.resolve(pointer.serverEntry) : "";
48
+ if (pointer?.schemaVersion !== POINTER_SCHEMA || !runtimeRoot || !serverEntry || !inside(paths.runtimesDir, runtimeRoot) || !inside(runtimeRoot, serverEntry)) return null;
49
+ try {
50
+ if (!(await stat(runtimeRoot)).isDirectory() || !(await stat(serverEntry)).isFile()) return null;
51
+ const [canonicalRuntimesDir, canonicalRuntimeRoot, canonicalServerEntry] = await Promise.all([
52
+ realpath(paths.runtimesDir),
53
+ realpath(runtimeRoot),
54
+ realpath(serverEntry),
55
+ ]);
56
+ if (!inside(canonicalRuntimesDir, canonicalRuntimeRoot) || !inside(canonicalRuntimeRoot, canonicalServerEntry)) return null;
57
+ return Object.freeze({ ...pointer, runtimeRoot: canonicalRuntimeRoot, serverEntry: canonicalServerEntry });
58
+ } catch { return null; }
59
+ }
60
+
61
+ export async function writeRuntimePointer(agentDir, name, pointer) {
62
+ if (!new Set(["current", "previous"]).has(name)) throw new TypeError("pointer name must be current or previous");
63
+ const paths = managedRuntimePaths(agentDir);
64
+ const runtimeRoot = path.resolve(String(pointer?.runtimeRoot || ""));
65
+ const serverEntry = path.resolve(String(pointer?.serverEntry || ""));
66
+ if (!inside(paths.runtimesDir, runtimeRoot) || !inside(runtimeRoot, serverEntry)) throw Object.assign(new Error("Managed runtime pointer escapes the private runtime root."), { code: "UPDATE_POINTER_ESCAPE" });
67
+ let canonicalRuntimesDir;
68
+ let canonicalRuntimeRoot;
69
+ let canonicalServerEntry;
70
+ try {
71
+ [canonicalRuntimesDir, canonicalRuntimeRoot, canonicalServerEntry] = await Promise.all([
72
+ realpath(paths.runtimesDir),
73
+ realpath(runtimeRoot),
74
+ realpath(serverEntry),
75
+ ]);
76
+ } catch {
77
+ throw Object.assign(new Error("Managed runtime pointer target is incomplete."), { code: "UPDATE_POINTER_INCOMPLETE" });
78
+ }
79
+ if (!inside(canonicalRuntimesDir, canonicalRuntimeRoot) || !inside(canonicalRuntimeRoot, canonicalServerEntry)) {
80
+ throw Object.assign(new Error("Managed runtime pointer resolves outside the private runtime root."), { code: "UPDATE_POINTER_ESCAPE" });
81
+ }
82
+ const record = { schemaVersion: POINTER_SCHEMA, runtimeRoot: canonicalRuntimeRoot, serverEntry: canonicalServerEntry, version: String(pointer.version || ""), activatedAt: pointer.activatedAt || new Date().toISOString() };
83
+ await privateJson(name === "current" ? paths.currentPointer : paths.previousPointer, record);
84
+ return Object.freeze(record);
85
+ }
86
+
87
+ export async function switchRuntimePointer(agentDir, candidate) {
88
+ const current = await readRuntimePointer(agentDir, "current");
89
+ if (current) await writeRuntimePointer(agentDir, "previous", current);
90
+ const next = await writeRuntimePointer(agentDir, "current", candidate);
91
+ return Object.freeze({ current: next, previous: current });
92
+ }
93
+
94
+ export async function rollbackRuntimePointer(agentDir) {
95
+ const paths = managedRuntimePaths(agentDir);
96
+ const previous = await readRuntimePointer(agentDir, "previous");
97
+ const current = await readRuntimePointer(agentDir, "current");
98
+ if (!previous) {
99
+ await rm(paths.currentPointer, { force: true });
100
+ if (current) await writeRuntimePointer(agentDir, "previous", current);
101
+ return Object.freeze({ current: null, previous: current, bootstrapFallback: true });
102
+ }
103
+ await writeRuntimePointer(agentDir, "current", previous);
104
+ if (current) await writeRuntimePointer(agentDir, "previous", current);
105
+ return Object.freeze({ current: previous, previous: current, bootstrapFallback: false });
106
+ }
107
+
108
+ function normalizeRestoreTab(item, seen) {
109
+ if (!item || typeof item !== "object") return null;
110
+ const text = (value, max) => typeof value === "string" && value.trim() ? value.trim().slice(0, max) : undefined;
111
+ const rawId = text(item.id, 128);
112
+ const id = rawId && /^[A-Za-z0-9._:-]+$/.test(rawId) && !seen.has(rawId) ? rawId : undefined;
113
+ if (id) seen.add(id);
114
+ const tab = { id, title: text(item.title, 160), titleSource: text(item.titleSource, 32), cwd: text(item.cwd, 4096), sessionFile: text(item.sessionFile, 4096), conversationStarted: item.conversationStarted === true };
115
+ if (Number.isInteger(item.index) && item.index > 0) tab.index = item.index;
116
+ return tab;
117
+ }
118
+
119
+ export async function createRestoreFile(agentDir, tabs, { now = () => new Date() } = {}) {
120
+ const paths = managedRuntimePaths(agentDir);
121
+ const seen = new Set();
122
+ const normalized = (Array.isArray(tabs) ? tabs : []).map((item) => normalizeRestoreTab(item, seen)).filter(Boolean).slice(0, MAX_RESTORE_TABS);
123
+ const payload = { schemaVersion: RESTORE_SCHEMA, createdAt: now().toISOString(), tabs: normalized };
124
+ const encoded = `${JSON.stringify(payload)}\n`;
125
+ if (Buffer.byteLength(encoded) > MAX_RESTORE_BYTES) throw Object.assign(new Error("Restore descriptor file exceeds the private handoff limit."), { code: "RESTORE_FILE_TOO_LARGE" });
126
+ await mkdir(paths.tempDir, { recursive: true, mode: 0o700 });
127
+ const file = path.join(paths.tempDir, `restore-${randomUUID()}.json`);
128
+ const handle = await open(file, "wx", 0o600);
129
+ try { await handle.writeFile(encoded, "utf8"); await handle.sync(); } finally { await handle.close(); }
130
+ return Object.freeze({ file, count: normalized.length });
131
+ }
132
+
133
+ export async function readRestoreFileOnce(file, agentDir) {
134
+ if (!file) return [];
135
+ const paths = managedRuntimePaths(agentDir);
136
+ const resolved = path.resolve(file);
137
+ if (!inside(paths.tempDir, resolved)) throw Object.assign(new Error("Restore descriptor path is outside the private temp root."), { code: "RESTORE_FILE_ESCAPE" });
138
+ let raw;
139
+ try {
140
+ const info = await stat(resolved);
141
+ if (!info.isFile() || info.size > MAX_RESTORE_BYTES) throw new Error("Restore descriptor is not a bounded file.");
142
+ raw = await readFile(resolved, "utf8");
143
+ } finally {
144
+ await rm(resolved, { force: true }).catch(() => undefined);
145
+ }
146
+ const parsed = JSON.parse(raw);
147
+ if (parsed?.schemaVersion !== RESTORE_SCHEMA || !Array.isArray(parsed.tabs) || parsed.tabs.length > MAX_RESTORE_TABS) throw new Error("Restore descriptor schema is invalid.");
148
+ const seen = new Set();
149
+ return parsed.tabs.map((item) => normalizeRestoreTab(item, seen)).filter(Boolean);
150
+ }
151
+
152
+ export async function sweepRestoreFiles(agentDir, { olderThanMs = 24 * 60 * 60_000, now = Date.now() } = {}) {
153
+ const { tempDir } = managedRuntimePaths(agentDir);
154
+ let entries = [];
155
+ try { entries = await readdir(tempDir); } catch (error) { if (error?.code === "ENOENT") return 0; throw error; }
156
+ let removed = 0;
157
+ for (const name of entries.filter((entry) => /^restore-[a-f0-9-]+\.json$/i.test(entry))) {
158
+ const file = path.join(tempDir, name);
159
+ try { if (now - (await stat(file)).mtimeMs > olderThanMs) { await rm(file, { force: true }); removed += 1; } } catch {}
160
+ }
161
+ return removed;
162
+ }
163
+
164
+ export async function listenWithRetry(server, { port, host, attempts = 40, initialDelayMs = 250 } = {}) {
165
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
166
+ try {
167
+ await new Promise((resolve, reject) => {
168
+ const onError = (error) => { server.off("listening", onListening); reject(error); };
169
+ const onListening = () => { server.off("error", onError); resolve(); };
170
+ server.once("error", onError); server.once("listening", onListening); server.listen(port, host);
171
+ });
172
+ return attempt + 1;
173
+ } catch (error) {
174
+ if (error?.code !== "EADDRINUSE" || attempt === attempts - 1) throw error;
175
+ await new Promise((resolve) => setTimeout(resolve, initialDelayMs));
176
+ }
177
+ }
178
+ throw new Error("Listener retry exhausted.");
179
+ }
180
+
181
+ export async function probeCandidateRuntime(serverEntry, { expectedVersion, expectedPiVersion, timeoutMs = 20_000, spawnImpl = spawn } = {}) {
182
+ return new Promise((resolve) => {
183
+ const child = spawnImpl(process.execPath, [serverEntry, "--candidate-probe"], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: { ...process.env, PI_WEBUI_CANDIDATE_PROBE: "1" } });
184
+ let stdout = "", stderr = "", settled = false;
185
+ const finish = (result) => { if (settled) return; settled = true; clearTimeout(timer); resolve(Object.freeze(result)); };
186
+ child.stdout?.on("data", (chunk) => { stdout = (stdout + chunk).slice(-16_000); });
187
+ child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk).slice(-16_000); });
188
+ child.once("error", (error) => finish({ ok: false, error: String(error.message || error), stdout, stderr }));
189
+ child.once("close", (code) => {
190
+ let data = null;
191
+ try { data = JSON.parse(stdout.trim().split(/\r?\n/).at(-1)); } catch {}
192
+ const ok = code === 0
193
+ && data?.ok === true
194
+ && (!expectedVersion || data.version === expectedVersion)
195
+ && (!expectedPiVersion || data.piVersion === expectedPiVersion);
196
+ finish({ ok, code, data, stdout, stderr, error: ok ? "" : "Candidate probe did not verify the expected Web UI runtime." });
197
+ });
198
+ const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch {} finish({ ok: false, timedOut: true, stdout, stderr, error: "Candidate probe timed out." }); }, timeoutMs);
199
+ timer.unref?.();
200
+ });
201
+ }
202
+
203
+ export async function collectManagedRuntimes(agentDir, { protectedRoots = [], keepHealthyForMs = 7 * 24 * 60 * 60_000, now = Date.now() } = {}) {
204
+ const paths = managedRuntimePaths(agentDir);
205
+ const statePaths = updateStatePaths(agentDir);
206
+ const current = await readRuntimePointer(agentDir, "current");
207
+ const previous = await readRuntimePointer(agentDir, "previous");
208
+ const protectedSet = new Set([current?.runtimeRoot, previous?.runtimeRoot, ...protectedRoots].filter(Boolean).map((item) => path.resolve(item)));
209
+ try {
210
+ for (const name of await readdir(statePaths.updatesDir)) {
211
+ if (!name.endsWith(".json")) continue;
212
+ try {
213
+ const journal = JSON.parse(await readFile(path.join(statePaths.updatesDir, name), "utf8"));
214
+ for (const target of journal?.plan?.targets || []) {
215
+ const runtimeRoot = target?.metadata?.runtimeRoot;
216
+ if (runtimeRoot && inside(paths.runtimesDir, runtimeRoot)) protectedSet.add(path.resolve(runtimeRoot));
217
+ }
218
+ } catch {}
219
+ }
220
+ } catch (error) { if (error?.code !== "ENOENT") throw error; }
221
+ let entries = [];
222
+ try { entries = await readdir(paths.runtimesDir, { withFileTypes: true }); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
223
+ const removed = [];
224
+ for (const entry of entries) {
225
+ if (!entry.isDirectory()) continue;
226
+ const root = path.join(paths.runtimesDir, entry.name);
227
+ if (protectedSet.has(path.resolve(root))) continue;
228
+ try {
229
+ const info = await stat(root);
230
+ if (now - info.mtimeMs < keepHealthyForMs) continue;
231
+ await rm(root, { recursive: true, force: true });
232
+ removed.push(root);
233
+ } catch {}
234
+ }
235
+ return removed;
236
+ }
237
+
238
+ export const UPDATE_RESTORE_LIMIT = MAX_RESTORE_TABS;
@@ -0,0 +1,52 @@
1
+ function version(value) {
2
+ return String(value ?? "").trim().replace(/^v/i, "");
3
+ }
4
+
5
+ function receipt(target, status, detail = {}) {
6
+ return Object.freeze({
7
+ targetId: String(target?.id || detail.targetId || ""),
8
+ kind: String(target?.kind || detail.kind || "package"),
9
+ status,
10
+ beforeVersion: version(detail.beforeVersion ?? target?.currentVersion),
11
+ expectedVersion: version(detail.expectedVersion ?? target?.targetVersion),
12
+ afterVersion: version(detail.afterVersion),
13
+ message: String(detail.message || ""),
14
+ command: detail.command || null,
15
+ });
16
+ }
17
+
18
+ /** Exit zero is insufficient: identity, exact promised version, and a change are mandatory. */
19
+ export function verifyTargetResult(target, { beforeIdentity, afterIdentity, beforeVersion, afterVersion, command } = {}) {
20
+ const before = version(beforeVersion ?? target?.currentVersion);
21
+ const after = version(afterVersion);
22
+ const expected = version(target?.targetVersion);
23
+ if (beforeIdentity?.canonicalId && afterIdentity?.canonicalId && beforeIdentity.canonicalId !== afterIdentity.canonicalId) {
24
+ return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "Runtime identity changed during verification." });
25
+ }
26
+ if (!after) return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "The updated version could not be read." });
27
+ if (after === before) return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "The command completed without changing the installed version." });
28
+ if (!expected || after !== expected) {
29
+ return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: `Expected exact version ${expected || "unknown"}, found ${after}.` });
30
+ }
31
+ return receipt(target, "success", { beforeVersion: before, afterVersion: after, command, message: `Verified ${after}.` });
32
+ }
33
+
34
+ export function failedTargetReceipt(target, message, detail = {}) {
35
+ return receipt(target, "failed", { ...detail, message });
36
+ }
37
+
38
+ export function rolledBackTargetReceipt(target, message, detail = {}) {
39
+ return receipt(target, "rolled-back", { ...detail, message });
40
+ }
41
+
42
+ export function reduceUpdateReceipts(receipts = []) {
43
+ const ordered = Object.freeze(receipts.map((item) => Object.freeze({ ...item })));
44
+ const successes = ordered.filter((item) => item.status === "success").length;
45
+ const rolledBack = ordered.filter((item) => item.status === "rolled-back").length;
46
+ const failures = ordered.length - successes - rolledBack;
47
+ let outcome = "failed";
48
+ if (ordered.length > 0 && successes === ordered.length) outcome = "success";
49
+ else if (successes > 0) outcome = "partial";
50
+ else if (rolledBack > 0 && failures === 0) outcome = "rolled-back";
51
+ return Object.freeze({ outcome, receipts: ordered, counts: Object.freeze({ success: successes, failed: failures, rolledBack }) });
52
+ }
@@ -1,20 +1,32 @@
1
- export function piUpdateHelpSupportsAll(output) {
2
- return /(?:^|[^A-Za-z0-9_-])--all(?:$|[^A-Za-z0-9_-])/.test(String(output || ""));
3
- }
1
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
4
2
 
5
- export function piUpdateCommandSteps({ all = false, supportsAll = false } = {}) {
6
- if (!all) return [{ label: "Pi CLI", args: ["update", "--self"] }];
7
- if (supportsAll) return [{ label: "Pi CLI and configured packages", args: ["update", "--all"] }];
3
+ export function exactPackageSpec(packageName, version) {
4
+ const name = String(packageName || "").trim();
5
+ const exact = String(version || "").trim().replace(/^v/i, "");
6
+ if (!name || !EXACT_VERSION.test(exact)) throw new TypeError("packageName and an exact version are required");
7
+ return `${name}@${exact}`;
8
+ }
8
9
 
9
- // Explicit flags remain compatible with Pi releases that predate `--all`.
10
+ export function exactNpmInstallArgs({ installRoot, packageName, version, registry } = {}) {
11
+ const root = String(installRoot || "").trim();
12
+ const registryUrl = new URL(String(registry || ""));
13
+ if (!root) throw new TypeError("installRoot is required");
14
+ if (!/^https?:$/.test(registryUrl.protocol) || registryUrl.username || registryUrl.password || registryUrl.hash) {
15
+ throw new TypeError("registry must be a credential-free HTTP(S) URL");
16
+ }
10
17
  return [
11
- { label: "Pi CLI", args: ["update", "--self"] },
12
- { label: "configured Pi packages", args: ["update", "--extensions"] },
18
+ "install", "--prefix", root, "--ignore-scripts", "--no-save", "--package-lock=false",
19
+ "--registry", registryUrl.href, exactPackageSpec(packageName, version),
13
20
  ];
14
21
  }
15
22
 
16
- export function piUpdateCommandText(options = {}) {
17
- return piUpdateCommandSteps(options)
18
- .map((step) => `pi ${step.args.join(" ")}`)
19
- .join(" && ");
23
+ export function updatePlanConfirmationText(plan) {
24
+ if (!plan?.transactionId || !/^[a-f0-9]{64}$/.test(String(plan.digest || ""))) throw new TypeError("persisted update plan is required");
25
+ const targets = (plan.targets || []).map((target) => `${target.id} ${target.currentVersion} → ${target.targetVersion}`);
26
+ const refusals = (plan.refusals || []).map((item) => `${item.id}: ${item.guidance}`);
27
+ return [
28
+ targets.length ? `Exact targets: ${targets.join(" · ")}` : "No automatic targets were accepted.",
29
+ refusals.length ? `Refused: ${refusals.join(" · ")}` : "",
30
+ `Plan digest: ${plan.digest}`,
31
+ ].filter(Boolean).join("\n");
20
32
  }
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
5
6
 
6
7
  export const WEBUI_WORKSPACES_VERSION = 1;
7
8
  export const WEBUI_WORKSPACE_LIMIT = 20;
@@ -152,13 +153,28 @@ export async function listWebuiWorkspaces(storageFile = webuiWorkspacesFile(), o
152
153
  return document.workspaces.slice().reverse().map(workspaceMetadata).filter(Boolean);
153
154
  }
154
155
 
156
+ async function renameWithWindowsRetry(source, target) {
157
+ let lastError;
158
+ for (let attempt = 0; attempt < 12; attempt += 1) {
159
+ try {
160
+ await rename(source, target);
161
+ return;
162
+ } catch (error) {
163
+ lastError = error;
164
+ if (process.platform !== "win32" || !["EACCES", "EBUSY", "EPERM"].includes(error?.code)) throw error;
165
+ await delay(25 * (attempt + 1));
166
+ }
167
+ }
168
+ throw lastError;
169
+ }
170
+
155
171
  async function writeWorkspaceDocument(document, storageFile) {
156
172
  const normalized = normalizeWebuiWorkspaces(document);
157
173
  await mkdir(path.dirname(storageFile), { recursive: true });
158
174
  const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
159
175
  try {
160
176
  await writeFile(temporaryFile, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
161
- await rename(temporaryFile, storageFile);
177
+ await renameWithWindowsRetry(temporaryFile, storageFile);
162
178
  } catch (error) {
163
179
  await rm(temporaryFile, { force: true }).catch(() => {});
164
180
  throw error;