@pi-chamber/web 1.0.0 → 1.0.1

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/README.md +3 -1
  2. package/bin/cli.js +7 -32
  3. package/bin/dev-server.js +185 -0
  4. package/bin/dev-server.test.js +252 -0
  5. package/bin/lib/DOCUMENTATION.md +19 -0
  6. package/bin/lib/cli-startup.js +9 -1
  7. package/bin/lib/cli-startup.test.js +30 -0
  8. package/bin/lib/commands-serve.js +9 -5
  9. package/bin/lib/server-runtime.js +6 -0
  10. package/bin/lib/server-runtime.test.js +313 -0
  11. package/dist/assets/{DiagramView-CbSxUe1D.js → DiagramView-COHSzZ9Z.js} +1 -1
  12. package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BA4LWExp.js} +1 -1
  13. package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
  14. package/dist/assets/{FilesView-DasA5EU2.js → FilesView-CIx6Bq8l.js} +1 -1
  15. package/dist/assets/{GitView-DU3mOECp.js → GitView-3Hgk_pVS.js} +3 -3
  16. package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-CVLGj7jk.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-CWeQW9_O.js} +1 -1
  18. package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-367QPDDL.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
  22. package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
  23. package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-CN0wm-Fv.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-Bkh0DWJn.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-CFToyUp4.js} +1 -1
  27. package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BXBoS1M4.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-BpbB2xiE.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
  30. package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
  31. package/dist/assets/{index-OveFsNBm.js → index-CVZfC79h.js} +1 -1
  32. package/dist/assets/{index-BXX8l7mM.css → index-Ci9OMaKW.css} +1 -1
  33. package/dist/assets/{index-DvNeSFO9.js → index-DyeT2dc_.js} +7 -7
  34. package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-dBQiDlRy.js} +1 -1
  35. package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-DWMzO-Ms.js} +1 -1
  36. package/dist/assets/{main-BsDkATRV.js → main-DkXvFwTR.js} +3 -3
  37. package/dist/assets/{main-C393Ywhx.js → main-DukaBOy3.js} +2 -2
  38. package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BH61OrJ2.js} +1 -1
  39. package/dist/assets/{miniChat-CWEerp3c.js → miniChat-B1uBoxSn.js} +2 -2
  40. package/dist/assets/{mobile-YxV9KcxF.js → mobile-DV_RYy3x.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-CA6co_Lh.js} +2 -2
  42. package/dist/assets/renderMobileApp-CyhFZ_4g.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-CVoKFaRw.js +53 -0
  44. package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-CxbVCK7k.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-HCEusnq7.js} +77 -77
  46. package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-DLA7kskG.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
  50. package/dist/assets/{web-components-B0RFakat.js → web-components-C7g3Hi85.js} +1 -1
  51. package/dist/index.html +4 -4
  52. package/dist/mini-chat.html +3 -3
  53. package/dist/mobile.html +3 -3
  54. package/package.json +8 -3
  55. package/server/index.js +40 -6
  56. package/server/lib/notifications/DOCUMENTATION.md +39 -0
  57. package/server/lib/notifications/delivery-runtime.js +314 -0
  58. package/server/lib/notifications/delivery-runtime.test.js +85 -0
  59. package/server/lib/notifications/pi-notification-watcher.js +154 -0
  60. package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
  61. package/server/lib/notifications/routes.js +74 -0
  62. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
  63. package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
  64. package/server/lib/pi/ui-settings-store.js +3 -2
  65. package/server/lib/server/runtime-requirements.js +193 -0
  66. package/server/lib/server/runtime-requirements.test.js +295 -0
  67. package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
  68. package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
  69. package/dist/assets/runtimeEndpointReset-DHARMv9w.js +0 -53
@@ -0,0 +1,466 @@
1
+ // Portable real-subprocess smoke for the pinned Pi SDK and foreground backend.
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createServer } from 'node:net';
4
+ import { mkdtemp, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { afterEach, describe, expect, it } from 'vitest';
9
+ import { createPiSessionDaemonSupervisor } from './supervisor.js';
10
+
11
+ const HELP_TIMEOUT_MS = 20_000;
12
+ const RPC_TIMEOUT_MS = 20_000;
13
+ const BACKEND_READY_TIMEOUT_MS = 30_000;
14
+ const BACKEND_POLL_MS = 250;
15
+ const MAX_BUFFER_BYTES = 2 * 1024 * 1024;
16
+
17
+ const roots = [];
18
+ const children = [];
19
+
20
+ const closePromises = new WeakMap();
21
+
22
+ const ensureCloseTracking = (child) => {
23
+ let tracked = closePromises.get(child);
24
+ if (!tracked) {
25
+ tracked = new Promise((resolve, reject) => {
26
+ child.once('close', (code, signal) => resolve({ code, signal }));
27
+ child.once('error', reject);
28
+ });
29
+ tracked.catch(() => {});
30
+ closePromises.set(child, tracked);
31
+ }
32
+ return tracked;
33
+ };
34
+
35
+ // Truly observe `close`, never resolve early on `exitCode` and never resolve
36
+ // on timeout. Timeouts reject so cleanup cannot swallow a hung child.
37
+ const waitForClose = async (child, ms) => {
38
+ const closePromise = ensureCloseTracking(child);
39
+ let timer;
40
+ const timeoutPromise = new Promise((_, reject) => {
41
+ timer = setTimeout(() => {
42
+ reject(new Error(`Child process did not close within ${ms}ms (exitCode=${child.exitCode}, signal=${child.signalCode}).`));
43
+ }, ms);
44
+ timer.unref?.();
45
+ });
46
+ try {
47
+ await Promise.race([closePromise, timeoutPromise]);
48
+ } finally {
49
+ clearTimeout(timer);
50
+ }
51
+ };
52
+
53
+ // Signal only a directly-spawned child handle. Never resolve a PID from a
54
+ // log file or state sidecar into `process.kill`; stale PIDs must not be
55
+ // signaled. Only ESRCH (already dead) is ignored.
56
+ const signalOwnChild = (child, signal) => {
57
+ try {
58
+ child.kill(signal);
59
+ } catch (error) {
60
+ if (error?.code === 'ESRCH') return;
61
+ throw error;
62
+ }
63
+ };
64
+
65
+ const withTimeout = async (promise, ms, label) => {
66
+ let timer;
67
+ const timeout = new Promise((_, reject) => {
68
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms.`)), ms);
69
+ timer.unref?.();
70
+ });
71
+ try {
72
+ return await Promise.race([promise, timeout]);
73
+ } finally {
74
+ clearTimeout(timer);
75
+ }
76
+ };
77
+
78
+ const untrack = (child) => {
79
+ const index = children.indexOf(child);
80
+ if (index !== -1) children.splice(index, 1);
81
+ };
82
+
83
+ afterEach(async () => {
84
+ const pending = children.splice(0);
85
+ for (const child of pending) {
86
+ ensureCloseTracking(child);
87
+ signalOwnChild(child, 'SIGTERM');
88
+ }
89
+ for (const child of pending) {
90
+ try {
91
+ await waitForClose(child, 5_000);
92
+ } catch {
93
+ signalOwnChild(child, 'SIGKILL');
94
+ await waitForClose(child, 5_000);
95
+ }
96
+ }
97
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
98
+ });
99
+
100
+ const resolveTestRuntime = () => {
101
+ const override = typeof process.env.PICHAMBER_TEST_RUNTIME === 'string'
102
+ ? process.env.PICHAMBER_TEST_RUNTIME.trim()
103
+ : '';
104
+ if (override.length === 0) return process.execPath;
105
+ if (!isAbsolute(override)) throw new Error('PICHAMBER_TEST_RUNTIME must be an absolute path.');
106
+ return override;
107
+ };
108
+
109
+ const resolvePiCli = async () => {
110
+ const sdkUrl = import.meta.resolve('@earendil-works/pi-coding-agent');
111
+ let dir = dirname(fileURLToPath(sdkUrl));
112
+ for (let depth = 0; depth < 6; depth += 1) {
113
+ try {
114
+ const raw = await readFile(join(dir, 'package.json'), 'utf8');
115
+ const parsed = JSON.parse(raw);
116
+ if (parsed?.name === '@earendil-works/pi-coding-agent') {
117
+ const bin = typeof parsed.bin === 'string' ? parsed.bin : parsed?.bin?.pi;
118
+ if (typeof bin !== 'string' || bin.length === 0) throw new Error('Installed Pi package.json has no bin.pi entry.');
119
+ const cliPath = resolve(dir, bin);
120
+ await stat(cliPath);
121
+ return { cliPath, packageJson: parsed };
122
+ }
123
+ } catch (error) {
124
+ if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR' && !(error instanceof SyntaxError)) throw error;
125
+ }
126
+ const parent = dirname(dir);
127
+ if (parent === dir) break;
128
+ dir = parent;
129
+ }
130
+ throw new Error('Could not locate @earendil-works/pi-coding-agent package.json.');
131
+ };
132
+
133
+ const readPinnedPiVersion = async () => {
134
+ const raw = await readFile(new URL('../../../../package.json', import.meta.url), 'utf8');
135
+ const dep = JSON.parse(raw).dependencies?.['@earendil-works/pi-coding-agent'];
136
+ if (typeof dep !== 'string' || dep.length === 0) throw new Error('Pinned Pi dependency is missing.');
137
+ // The Pi SDK is pinned exactly (no ^/~); return the exact string so version
138
+ // parity asserts exact equality instead of stripping a range prefix.
139
+ return dep;
140
+ };
141
+
142
+ const makeIsolatedRoot = async (prefix) => {
143
+ const root = await mkdtemp(join(tmpdir(), prefix));
144
+ roots.push(root);
145
+ const layout = {
146
+ root,
147
+ cwd: join(root, 'cwd'),
148
+ home: join(root, 'home'),
149
+ agentDir: join(root, 'agent'),
150
+ sessionDir: join(root, 'sessions'),
151
+ xdgRuntime: join(root, 'xdg-runtime'),
152
+ xdgConfig: join(root, 'xdg-config'),
153
+ xdgData: join(root, 'xdg-data'),
154
+ xdgCache: join(root, 'xdg-cache'),
155
+ tmp: join(root, 'tmp'),
156
+ };
157
+ await Promise.all([layout.cwd, layout.home, layout.agentDir, layout.sessionDir,
158
+ layout.xdgRuntime, layout.xdgConfig, layout.xdgData, layout.xdgCache, layout.tmp]
159
+ .map((dir) => mkdir(dir, { recursive: true })));
160
+ return layout;
161
+ };
162
+
163
+ const buildIsolatedEnv = ({ runtime, layout, extra = {} }) => {
164
+ const runtimeDir = dirname(runtime);
165
+ const isWindows = process.platform === 'win32';
166
+ const env = {
167
+ PATH: isWindows && typeof process.env.PATH === 'string' && process.env.PATH.length > 0
168
+ ? `${runtimeDir}${delimiter}${process.env.PATH}`
169
+ : runtimeDir,
170
+ HOME: layout.home,
171
+ USERPROFILE: layout.home,
172
+ TMPDIR: layout.tmp,
173
+ TEMP: layout.tmp,
174
+ TMP: layout.tmp,
175
+ XDG_RUNTIME_DIR: layout.xdgRuntime,
176
+ XDG_CONFIG_HOME: layout.xdgConfig,
177
+ XDG_DATA_HOME: layout.xdgData,
178
+ XDG_CACHE_HOME: layout.xdgCache,
179
+ PI_CODING_AGENT_DIR: layout.agentDir,
180
+ PI_CODING_AGENT_SESSION_DIR: layout.sessionDir,
181
+ PI_OFFLINE: '1',
182
+ PI_SKIP_VERSION_CHECK: '1',
183
+ PI_TELEMETRY: '0',
184
+ NO_COLOR: '1',
185
+ TERM: 'dumb',
186
+ ...extra,
187
+ };
188
+ if (isWindows) {
189
+ if (typeof process.env.SystemRoot === 'string' && process.env.SystemRoot.length > 0) env.SystemRoot = process.env.SystemRoot;
190
+ if (typeof process.env.SystemDrive === 'string' && process.env.SystemDrive.length > 0) env.SystemDrive = process.env.SystemDrive;
191
+ if (typeof process.env.PATHEXT === 'string' && process.env.PATHEXT.length > 0) env.PATHEXT = process.env.PATHEXT;
192
+ }
193
+ return env;
194
+ };
195
+
196
+ const allocateLoopbackPort = async () => {
197
+ const server = createServer();
198
+ await new Promise((done, fail) => {
199
+ server.once('error', fail);
200
+ server.listen(0, '127.0.0.1', done);
201
+ });
202
+ const address = server.address();
203
+ const port = typeof address === 'object' && address ? address.port : 0;
204
+ await new Promise((done) => server.close(done));
205
+ if (!Number.isInteger(port) || port <= 0) throw new Error('Could not allocate a loopback port.');
206
+ return port;
207
+ };
208
+
209
+ const realExec = async (value) => {
210
+ try { return await realpath(value); } catch { return value; }
211
+ };
212
+
213
+ const normalizeArgv = (value) => String(value ?? '').replace(/\\/g, '/');
214
+
215
+ // Verified leftover-daemon shutdown using only the isolated root. Never
216
+ // resolves a PID from a log file into `process.kill`. Uses the owning
217
+ // supervisor's authenticated IPC (`runtime.shutdown` after identity checks)
218
+ // and only touches files under the isolated `dataDir`/runtime dir. Bounded;
219
+ // on failure the caller must preserve the isolated root (no state delete).
220
+ const stopIsolatedDaemon = async ({ layout, dataDir, daemonAgentDir, port }) => {
221
+ const webPkg = JSON.parse(await readFile(new URL('../../../../package.json', import.meta.url), 'utf8'));
222
+ const version = typeof webPkg?.version === 'string' && webPkg.version.length > 0 ? webPkg.version : 'unknown';
223
+ const env = {
224
+ PICHAMBER_DATA_DIR: dataDir,
225
+ PICHAMBER_PI_AGENT_DIR: daemonAgentDir,
226
+ XDG_RUNTIME_DIR: layout.xdgRuntime,
227
+ };
228
+ if (process.platform === 'win32') {
229
+ if (typeof process.env.SystemRoot === 'string' && process.env.SystemRoot.length > 0) env.SystemRoot = process.env.SystemRoot;
230
+ if (typeof process.env.SystemDrive === 'string' && process.env.SystemDrive.length > 0) env.SystemDrive = process.env.SystemDrive;
231
+ if (typeof process.env.PATHEXT === 'string' && process.env.PATHEXT.length > 0) env.PATHEXT = process.env.PATHEXT;
232
+ }
233
+ const supervisor = createPiSessionDaemonSupervisor({ env, cwd: layout.cwd, dataDir, port, version });
234
+ try {
235
+ await stat(supervisor.paths.stateFile);
236
+ } catch (error) {
237
+ if (error?.code === 'ENOENT') return { cleaned: true, reason: 'no-state' };
238
+ throw error;
239
+ }
240
+ try {
241
+ await withTimeout(supervisor.stop(), 15_000, 'Isolated daemon stop');
242
+ return { cleaned: true, reason: 'stopped' };
243
+ } catch (error) {
244
+ // A new supervisor has a fresh instance id, so `stop` safely refuses with
245
+ // OWNERSHIP_MISMATCH when the leftover daemon is still owned by the dead
246
+ // backend. Claim (only succeeds when the recorded owner PID is dead) then
247
+ // stop as the new owner. Any other error propagates without deleting state.
248
+ if (error?.code !== 'DAEMON_OWNERSHIP_MISMATCH') throw error;
249
+ await withTimeout(supervisor.start(), 20_000, 'Isolated daemon claim');
250
+ await withTimeout(supervisor.stop(), 15_000, 'Isolated daemon stop after claim');
251
+ return { cleaned: true, reason: 'claimed-stopped' };
252
+ }
253
+ };
254
+
255
+ describe('portable Pi runtime smoke', () => {
256
+ it('imports the Pi SDK in the selected runtime with pinned version parity', async () => {
257
+ const runtime = resolveTestRuntime();
258
+ const sdkUrl = import.meta.resolve('@earendil-works/pi-coding-agent');
259
+ const pinned = await readPinnedPiVersion();
260
+ const layout = await makeIsolatedRoot('pichamber-pi-sdk-');
261
+ const probe = join(layout.root, 'sdk-probe.mjs');
262
+ await writeFile(probe, [
263
+ `import * as PiSdk from ${JSON.stringify(sdkUrl)};`,
264
+ 'process.stdout.write(JSON.stringify({ version: PiSdk.VERSION,',
265
+ ' createAgentSession: typeof PiSdk.createAgentSession,',
266
+ ' SessionManager: typeof PiSdk.SessionManager,',
267
+ ' ModelRuntime: typeof PiSdk.ModelRuntime }));',
268
+ '',
269
+ ].join('\n'));
270
+ const result = spawnSync(runtime, [probe], {
271
+ cwd: layout.cwd,
272
+ env: buildIsolatedEnv({ runtime, layout }),
273
+ timeout: HELP_TIMEOUT_MS,
274
+ maxBuffer: MAX_BUFFER_BYTES,
275
+ windowsHide: true,
276
+ encoding: 'utf8',
277
+ });
278
+ expect(result.error).toBeUndefined();
279
+ expect(result.status).toBe(0);
280
+ expect(String(result.stderr ?? '')).toBe('');
281
+ const out = JSON.parse(String(result.stdout ?? ''));
282
+ expect(out.createAgentSession).toBe('function');
283
+ expect(out.SessionManager).toBe('function');
284
+ expect(out.ModelRuntime).toBe('function');
285
+ expect(out.version).toBe(pinned);
286
+ const { packageJson } = await resolvePiCli();
287
+ expect(out.version).toBe(packageJson.version);
288
+ }, 30_000);
289
+
290
+ it('resolves the installed Pi CLI through package.json bin.pi', async () => {
291
+ const { cliPath, packageJson } = await resolvePiCli();
292
+ expect(isAbsolute(cliPath)).toBe(true);
293
+ expect(cliPath).toContain('cli.js');
294
+ expect(typeof (packageJson.bin?.pi ?? packageJson.bin)).toBe('string');
295
+ });
296
+
297
+ it('runs bin.pi --help to success with EOF in an isolated subprocess', async () => {
298
+ const runtime = resolveTestRuntime();
299
+ const { cliPath } = await resolvePiCli();
300
+ const layout = await makeIsolatedRoot('pichamber-pi-help-');
301
+ const result = spawnSync(runtime, [cliPath, '--help'], {
302
+ cwd: layout.cwd,
303
+ env: buildIsolatedEnv({ runtime, layout }),
304
+ timeout: HELP_TIMEOUT_MS,
305
+ maxBuffer: MAX_BUFFER_BYTES,
306
+ windowsHide: true,
307
+ encoding: 'utf8',
308
+ });
309
+ expect(result.error).toBeUndefined();
310
+ expect(result.status).toBe(0);
311
+ expect(result.stdout).toContain('Usage:');
312
+ expect(result.stdout).toContain('--mode');
313
+ expect(result.stdout).toContain('rpc');
314
+ expect(String(result.stderr ?? '')).toBe('');
315
+ }, 30_000);
316
+
317
+ it('runs bin.pi rpc get_state with id runtime-smoke to success', async () => {
318
+ const runtime = resolveTestRuntime();
319
+ const { cliPath } = await resolvePiCli();
320
+ const layout = await makeIsolatedRoot('pichamber-pi-rpc-');
321
+ const result = spawnSync(runtime, [cliPath, '--mode', 'rpc', '--no-session', '--offline'], {
322
+ cwd: layout.cwd,
323
+ env: buildIsolatedEnv({ runtime, layout }),
324
+ input: `${JSON.stringify({ type: 'get_state', id: 'runtime-smoke' })}\n`,
325
+ timeout: RPC_TIMEOUT_MS,
326
+ maxBuffer: MAX_BUFFER_BYTES,
327
+ windowsHide: true,
328
+ encoding: 'utf8',
329
+ });
330
+ expect(result.error).toBeUndefined();
331
+ expect(result.status).toBe(0);
332
+ expect(String(result.stderr ?? '')).toBe('');
333
+ const frames = String(result.stdout ?? '')
334
+ .split('\n')
335
+ .map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
336
+ .filter((line) => line.length > 0)
337
+ .map((line) => JSON.parse(line));
338
+ const response = frames.find((frame) => frame?.id === 'runtime-smoke');
339
+ expect(response).toMatchObject({ type: 'response', command: 'get_state', success: true, id: 'runtime-smoke' });
340
+ expect(response?.data).toMatchObject({ isStreaming: false });
341
+ }, 30_000);
342
+
343
+ it('starts a credential-free foreground backend on the selected runtime', async () => {
344
+ const runtime = resolveTestRuntime();
345
+ const pichamberCli = fileURLToPath(new URL('../../../../bin/cli.js', import.meta.url));
346
+ await stat(pichamberCli);
347
+ const layout = await makeIsolatedRoot('pichamber-backend-smoke-');
348
+ const dataDir = join(layout.root, 'data');
349
+ const daemonAgentDir = join(layout.root, 'daemon-agent');
350
+ await mkdir(dataDir, { recursive: true });
351
+ await mkdir(daemonAgentDir, { recursive: true });
352
+ const port = await allocateLoopbackPort();
353
+ const probeFile = join(layout.root, 'runtime-probe.mjs');
354
+ const probeLog = join(layout.root, 'runtime-probe.log');
355
+ await writeFile(probeFile, [
356
+ "import fs from 'node:fs';",
357
+ 'const out = process.env.PICHAMBER_RUNTIME_PROBE_FILE;',
358
+ 'if (out) {',
359
+ ' const line = JSON.stringify({ pid: process.pid, execPath: process.execPath, argv1: process.argv[1] ?? null }) + "\\n";',
360
+ ' fs.appendFileSync(out, line);',
361
+ '}',
362
+ '',
363
+ ].join('\n'));
364
+ const probeUrl = pathToFileURL(probeFile).href;
365
+ const env = buildIsolatedEnv({
366
+ runtime,
367
+ layout,
368
+ extra: {
369
+ PICHAMBER_DATA_DIR: dataDir,
370
+ PICHAMBER_PI_AGENT_DIR: daemonAgentDir,
371
+ PICHAMBER_RUNTIME_PROBE_FILE: probeLog,
372
+ NODE_OPTIONS: `--import ${probeUrl}`,
373
+ BUN_OPTIONS: `--import ${probeUrl}`,
374
+ },
375
+ });
376
+ if (process.platform !== 'win32') env.PATH = '';
377
+ const child = spawn(runtime, [
378
+ '--import', probeFile,
379
+ pichamberCli, 'serve',
380
+ '--foreground',
381
+ '--port', String(port),
382
+ '--host', '127.0.0.1',
383
+ '--api-only',
384
+ ], {
385
+ cwd: layout.cwd,
386
+ env,
387
+ windowsHide: true,
388
+ stdio: ['ignore', 'pipe', 'pipe'],
389
+ });
390
+ children.push(child);
391
+ ensureCloseTracking(child);
392
+ let serverOutput = '';
393
+ let spawnError = null;
394
+ child.once('error', (error) => { spawnError = error; });
395
+ child.stdout?.setEncoding('utf8');
396
+ child.stderr?.setEncoding('utf8');
397
+ const onData = (chunk) => {
398
+ serverOutput += chunk;
399
+ if (serverOutput.length > MAX_BUFFER_BYTES) {
400
+ try {
401
+ signalOwnChild(child, 'SIGKILL');
402
+ } catch (error) {
403
+ if (error?.code !== 'ESRCH') spawnError ??= error;
404
+ }
405
+ }
406
+ };
407
+ child.stdout?.on('data', onData);
408
+ child.stderr?.on('data', onData);
409
+
410
+ const deadline = Date.now() + BACKEND_READY_TIMEOUT_MS;
411
+ let runtimeJson = null;
412
+ let lastError = null;
413
+ while (Date.now() < deadline) {
414
+ if (child.exitCode !== null || child.signalCode !== null || spawnError) {
415
+ throw new Error(`Foreground backend exited early (code ${child.exitCode ?? child.signalCode ?? spawnError?.message}). Output: ${serverOutput.slice(0, 2000)}`);
416
+ }
417
+ try {
418
+ const response = await fetch(`http://127.0.0.1:${port}/api/pi/runtime`, { signal: AbortSignal.timeout(5_000) });
419
+ const text = await response.text();
420
+ if (response.status === 200) {
421
+ runtimeJson = JSON.parse(text);
422
+ break;
423
+ }
424
+ lastError = new Error(`Unexpected /api/pi/runtime status ${response.status}: ${text.slice(0, 500)}`);
425
+ } catch (error) {
426
+ lastError = error;
427
+ }
428
+ await new Promise((done) => setTimeout(done, BACKEND_POLL_MS));
429
+ }
430
+ try {
431
+ expect(runtimeJson).toMatchObject({ state: 'ready', protocolVersion: 1 });
432
+ expect(runtimeJson.capabilities).toEqual(expect.arrayContaining(['sessions.list']));
433
+ expect(JSON.stringify(runtimeJson)).not.toContain(dataDir);
434
+ expect(JSON.stringify(runtimeJson)).not.toContain('credential');
435
+ const probeText = await readFile(probeLog, 'utf8');
436
+ const records = probeText.split('\n').filter((line) => line.length > 0).map((line) => JSON.parse(line));
437
+ const parent = records.find((record) => normalizeArgv(record.argv1).endsWith('bin/cli.js'));
438
+ const daemon = records.find((record) => normalizeArgv(record.argv1).endsWith('daemon-process.js'));
439
+ expect(parent).toBeDefined();
440
+ expect(daemon).toBeDefined();
441
+ const expectedExec = await realExec(runtime);
442
+ expect(await realExec(parent.execPath)).toBe(expectedExec);
443
+ expect(await realExec(daemon.execPath)).toBe(expectedExec);
444
+ } finally {
445
+ try {
446
+ signalOwnChild(child, 'SIGTERM');
447
+ try {
448
+ await waitForClose(child, 20_000);
449
+ } catch {
450
+ signalOwnChild(child, 'SIGKILL');
451
+ await waitForClose(child, 5_000);
452
+ }
453
+ await stopIsolatedDaemon({ layout, dataDir, daemonAgentDir, port });
454
+ await waitForClose(child, 5_000);
455
+ } catch (error) {
456
+ // Preserve the isolated root when verified cleanup cannot complete;
457
+ // deleting live daemon state would orphan or corrupt the leftover.
458
+ const rootIndex = roots.indexOf(layout.root);
459
+ if (rootIndex !== -1) roots.splice(rootIndex, 1);
460
+ throw error;
461
+ }
462
+ untrack(child);
463
+ }
464
+ if (!runtimeJson) throw lastError ?? new Error('Foreground backend never reported /api/pi/runtime ready.');
465
+ }, 60_000);
466
+ });
@@ -18,14 +18,15 @@ const PORTABLE_SETTINGS_VERSION = 'portable-v1';
18
18
  // userMessageRenderingMode, collapsibleUserMessages, stickyUserHeader,
19
19
  // promptNavigatorEnabled, wideChatLayoutEnabled,
20
20
  // showSplitAssistantMessageActions, directoryShowHidden, gitmojiEnabled,
21
+ // notifyOnSubtasks, notifyOnQuestion, notificationTemplates,
21
22
  // desktopWindowControlsPosition/Style (local). persistChatDraft was local-only
22
23
  // UI state and was never part of the server allowlists.
23
24
  const PORTABLE_FIELDS = new Set([
24
25
  'themeId', 'useSystemTheme', 'themeVariant', 'lightThemeId', 'darkThemeId',
25
26
  'splashBgLight', 'splashFgLight', 'splashBgDark', 'splashFgDark',
26
27
  'showDeletionDialog', 'nativeNotificationsEnabled', 'notificationMode',
27
- 'notifyOnSubtasks', 'notifyOnCompletion', 'notifyOnError', 'notifyOnQuestion',
28
- 'notificationTemplates', 'summarizeLastMessage', 'summaryThreshold', 'summaryLength',
28
+ 'notifyOnCompletion', 'notifyOnError',
29
+ 'summarizeLastMessage', 'summaryThreshold', 'summaryLength',
29
30
  'maxLastMessageLength', 'usageAutoRefresh', 'usageRefreshIntervalMs',
30
31
  'usageDisplayMode', 'usageShowPredValues', 'usageDropdownProviders',
31
32
  'usageSelectedModels', 'usageCollapsedFamilies', 'usageExpandedFamilies', 'usageModelGroups',
@@ -0,0 +1,193 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+
4
+ const MIN_NODE_VERSION = { major: 22, minor: 19, patch: 0 };
5
+ const MIN_BUN_VERSION = { major: 1, minor: 4, patch: 0 };
6
+ const MIN_NODE_VERSION_STRING = '22.19.0';
7
+ const MIN_BUN_VERSION_STRING = '1.4.0';
8
+ const RUNTIME_PROBE_TIMEOUT_MS = 5000;
9
+ export const NO_SUPPORTED_RUNTIME_MESSAGE =
10
+ `No supported server runtime found. Install Node.js ${MIN_NODE_VERSION_STRING} or newer, or Bun ${MIN_BUN_VERSION_STRING} or newer.`;
11
+ const NODE_PROBE_BIN = 'node';
12
+
13
+ export function getBunBinary(env = process.env) {
14
+ if (env && typeof env.BUN_BINARY === 'string' && env.BUN_BINARY.trim().length > 0) {
15
+ return env.BUN_BINARY.trim();
16
+ }
17
+ if (env && typeof env.BUN_INSTALL === 'string' && env.BUN_INSTALL.trim().length > 0) {
18
+ return path.join(env.BUN_INSTALL.trim(), 'bin', 'bun');
19
+ }
20
+ return 'bun';
21
+ }
22
+
23
+ function hasExplicitBunOverride(env = process.env) {
24
+ if (!env || typeof env !== 'object') return false;
25
+ return (typeof env.BUN_BINARY === 'string' && env.BUN_BINARY.trim().length > 0)
26
+ || (typeof env.BUN_INSTALL === 'string' && env.BUN_INSTALL.trim().length > 0);
27
+ }
28
+
29
+ function isBunRuntime(host = globalThis) {
30
+ return typeof host?.Bun !== 'undefined';
31
+ }
32
+
33
+ function compareVersion(parsed, minimum) {
34
+ if (parsed.major !== minimum.major) return parsed.major - minimum.major;
35
+ if (parsed.minor !== minimum.minor) return parsed.minor - minimum.minor;
36
+ return parsed.patch - minimum.patch;
37
+ }
38
+
39
+ // Strict stable parser: accepts only `X.Y.Z` with an optional leading `v`.
40
+ // Rejects empty, truncated, prerelease (`-rc.1`, `-canary`), and build
41
+ // metadata (`+build`) shapes so old/malformed/prerelease runtimes fail.
42
+ function parseStableVersion(value) {
43
+ if (typeof value !== 'string') return null;
44
+ const trimmed = value.trim();
45
+ if (trimmed.length === 0) return null;
46
+ const match = trimmed.match(/^v?(\d+)\.(\d+)\.(\d+)$/);
47
+ if (!match) return null;
48
+ const major = Number.parseInt(match[1], 10);
49
+ const minor = Number.parseInt(match[2], 10);
50
+ const patch = Number.parseInt(match[3], 10);
51
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) return null;
52
+ return { major, minor, patch };
53
+ }
54
+
55
+ export function isSupportedNodeVersion(value) {
56
+ const parsed = parseStableVersion(value);
57
+ if (!parsed) return false;
58
+ return compareVersion(parsed, MIN_NODE_VERSION) >= 0;
59
+ }
60
+
61
+ export function isSupportedBunVersion(value) {
62
+ const parsed = parseStableVersion(value);
63
+ if (!parsed) return false;
64
+ return compareVersion(parsed, MIN_BUN_VERSION) >= 0;
65
+ }
66
+
67
+ function probeVersionOutput(bin, spawnSyncFn = spawnSync, timeoutMs = RUNTIME_PROBE_TIMEOUT_MS) {
68
+ if (typeof bin !== 'string' || bin.trim().length === 0) return null;
69
+ const runner = typeof spawnSyncFn === 'function' ? spawnSyncFn : spawnSync;
70
+ try {
71
+ const result = runner(bin.trim(), ['--version'], {
72
+ encoding: 'utf8',
73
+ stdio: 'pipe',
74
+ windowsHide: true,
75
+ timeout: timeoutMs,
76
+ });
77
+ if (!result || result.error || result.status !== 0) return null;
78
+ const output = typeof result.stdout === 'string' ? result.stdout.trim() : '';
79
+ return output.length > 0 ? output : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function resolveProbeTimeout(options = {}) {
86
+ const candidate = options.probeTimeoutMs ?? options.timeoutMs ?? RUNTIME_PROBE_TIMEOUT_MS;
87
+ return Number.isFinite(candidate) && candidate > 0 ? candidate : RUNTIME_PROBE_TIMEOUT_MS;
88
+ }
89
+
90
+ function getCurrentNodeExecutable(options = {}) {
91
+ const isBun = options.isBun ?? isBunRuntime(options.globalRef ?? globalThis);
92
+ if (isBun) return null;
93
+ const nodeVersion = options.nodeVersion ?? process.version;
94
+ if (!isSupportedNodeVersion(nodeVersion)) return null;
95
+ const execPath = options.execPath ?? process.execPath;
96
+ if (typeof execPath !== 'string' || execPath.trim().length === 0) return null;
97
+ return execPath;
98
+ }
99
+
100
+ function getCurrentBunExecutable(options = {}) {
101
+ const globalRef = options.globalRef ?? globalThis;
102
+ const isBun = options.isBun ?? isBunRuntime(globalRef);
103
+ if (!isBun) return null;
104
+ const bunVersion = options.bunVersion ?? globalRef?.Bun?.version;
105
+ if (!isSupportedBunVersion(bunVersion)) return null;
106
+ const execPath = options.execPath ?? process.execPath;
107
+ if (typeof execPath !== 'string' || execPath.trim().length === 0) return null;
108
+ return execPath;
109
+ }
110
+
111
+ function findSupportedNodeExecutable(options = {}) {
112
+ const current = getCurrentNodeExecutable(options);
113
+ if (current) return current;
114
+ const nodeBin = options.nodeBin ?? NODE_PROBE_BIN;
115
+ const spawnSyncFn = options.spawnSyncFn ?? spawnSync;
116
+ // Bounded: probe errors (ENOENT, timeout, non-zero) return null so
117
+ // resolution falls through to Bun instead of throwing.
118
+ const probedVersion = probeVersionOutput(nodeBin, spawnSyncFn, resolveProbeTimeout(options));
119
+ if (probedVersion && isSupportedNodeVersion(probedVersion)) return nodeBin;
120
+ return null;
121
+ }
122
+
123
+ function isBunInstalled(options = {}) {
124
+ const bunBin = options.bunBin ?? getBunBinary(options.env ?? process.env);
125
+ const spawnSyncFn = options.spawnSyncFn ?? spawnSync;
126
+ const probedVersion = probeVersionOutput(bunBin, spawnSyncFn, resolveProbeTimeout(options));
127
+ if (!probedVersion) return false;
128
+ return isSupportedBunVersion(probedVersion);
129
+ }
130
+
131
+ function getCurrentRuntime(options = {}) {
132
+ const globalRef = options.globalRef ?? globalThis;
133
+ const isBun = options.isBun ?? isBunRuntime(globalRef);
134
+ const execPath = options.execPath ?? process.execPath;
135
+ const nodeVersion = options.nodeVersion ?? process.version;
136
+ const bunVersion = options.bunVersion ?? globalRef?.Bun?.version;
137
+ if (isBun) {
138
+ return { kind: 'bun', isBun: true, bunVersion, nodeVersion, execPath };
139
+ }
140
+ return { kind: 'node', isBun: false, nodeVersion, bunVersion: undefined, execPath };
141
+ }
142
+
143
+ export function resolveServerExecutable(options = {}) {
144
+ const nodeExecutable = findSupportedNodeExecutable(options);
145
+ if (nodeExecutable) return { runtime: 'node', executable: nodeExecutable };
146
+ const env = options.env ?? process.env;
147
+ const bunBin = options.bunBin ?? getBunBinary(env);
148
+ if (hasExplicitBunOverride(env)) {
149
+ if (isBunInstalled({ ...options, bunBin })) return { runtime: 'bun', executable: bunBin };
150
+ throw new Error(NO_SUPPORTED_RUNTIME_MESSAGE);
151
+ }
152
+ // No explicit override: prefer the current supported Bun executable before
153
+ // probing PATH. bin/cli.js always passes a default BUN_BIN (`bun`) even
154
+ // without overrides, so an explicit options.bunBin must not shadow a
155
+ // supported off-PATH current Bun here. Explicit BUN_BINARY/BUN_INSTALL
156
+ // already returned above.
157
+ const currentBun = getCurrentBunExecutable(options);
158
+ if (currentBun) return { runtime: 'bun', executable: currentBun };
159
+ if (isBunInstalled({ ...options, bunBin })) return { runtime: 'bun', executable: bunBin };
160
+ throw new Error(NO_SUPPORTED_RUNTIME_MESSAGE);
161
+ }
162
+
163
+ // Explicit foreground, startup enable, and in-process server startup validate
164
+ // only the current executable. They never probe PATH and never silently
165
+ // switch runtimes, so a supported absolute Bun exec works with an empty PATH
166
+ // and an old/malformed/prerelease current runtime fails deterministically.
167
+ export function assertCurrentRuntimeSupported(options = {}) {
168
+ const current = getCurrentRuntime(options);
169
+ const execPath = typeof current.execPath === 'string' ? current.execPath.trim() : '';
170
+ if (execPath.length === 0) {
171
+ throw new Error(`${NO_SUPPORTED_RUNTIME_MESSAGE} (missing runtime executable)`);
172
+ }
173
+ if (current.kind === 'bun') {
174
+ if (isSupportedBunVersion(current.bunVersion)) {
175
+ return { runtime: 'bun', executable: execPath };
176
+ }
177
+ const actual = typeof current.bunVersion === 'string' && current.bunVersion.trim().length > 0
178
+ ? current.bunVersion.trim()
179
+ : 'unknown';
180
+ throw new Error(
181
+ `Unsupported server runtime: Bun ${actual} is not supported. Install Bun ${MIN_BUN_VERSION_STRING} or newer, or Node.js ${MIN_NODE_VERSION_STRING} or newer.`,
182
+ );
183
+ }
184
+ if (isSupportedNodeVersion(current.nodeVersion)) {
185
+ return { runtime: 'node', executable: execPath };
186
+ }
187
+ const actual = typeof current.nodeVersion === 'string' && current.nodeVersion.trim().length > 0
188
+ ? current.nodeVersion.trim()
189
+ : 'unknown';
190
+ throw new Error(
191
+ `Unsupported server runtime: Node.js ${actual} is not supported. Install Node.js ${MIN_NODE_VERSION_STRING} or newer, or Bun ${MIN_BUN_VERSION_STRING} or newer.`,
192
+ );
193
+ }