@pi-chamber/web 1.0.0 → 1.0.2-rc.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 (78) 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-GUJij-1P.js} +1 -1
  12. package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BZ487Bhh.js} +1 -1
  13. package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-Ci6WdSiS.js} +1 -1
  14. package/dist/assets/{FilesView-DasA5EU2.js → FilesView-DBiWEo71.js} +1 -1
  15. package/dist/assets/{GitView-DU3mOECp.js → GitView-DVyhqN5s.js} +3 -3
  16. package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-BaU7aAUq.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-6NBJLtEr.js} +1 -1
  18. package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-CvptevA2.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-Cqp5FVCP.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-CRVJU16x.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CsFxImPI.js} +1 -1
  22. package/dist/assets/SettingsView-ppaIrPry.js +2 -0
  23. package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-geMUhnxd.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-BLGl2mNt.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-BVeL1IuE.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-9kAZ96se.js} +1 -1
  27. package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BencOwkW.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-C8vH0vcM.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-B6e3cTcl.js} +1 -1
  30. package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-B6w5GMNU.js} +1 -1
  31. package/dist/assets/{index-OveFsNBm.js → index-BifnX1Mp.js} +1 -1
  32. package/dist/assets/{index-DvNeSFO9.js → index-CpSdU-d4.js} +7 -7
  33. package/dist/assets/index-Dwz16owi.css +1 -0
  34. package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-BepQ1JHv.js} +1 -1
  35. package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-CA1KFaTm.js} +1 -1
  36. package/dist/assets/{main-BsDkATRV.js → main-TzeSIx1W.js} +3 -3
  37. package/dist/assets/{main-C393Ywhx.js → main-dhVDQIHu.js} +2 -2
  38. package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BztwD2c9.js} +1 -1
  39. package/dist/assets/{miniChat-CWEerp3c.js → miniChat-smqdx0Y7.js} +2 -2
  40. package/dist/assets/{mobile-YxV9KcxF.js → mobile-BV-WCEiE.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-DKmb9oa7.js} +2 -2
  42. package/dist/assets/renderMobileApp-D3dtjeaE.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-C1EENUlq.js +53 -0
  44. package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-Bm6cRkok.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-Dq7xKVjh.js} +77 -77
  46. package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Bvlo7C3a.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-BY4xtozp.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-CkE242zK.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-Bv6kN79m.js} +2 -2
  50. package/dist/assets/{web-components-B0RFakat.js → web-components-CCiRgoOw.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 +48 -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/package-manager.js +3 -2
  63. package/server/lib/package-manager.test.js +7 -2
  64. package/server/lib/pi/routes.test.js +24 -0
  65. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
  66. package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
  67. package/server/lib/pi/ui-settings-store.js +15 -2
  68. package/server/lib/pi/ui-settings-store.test.js +47 -1
  69. package/server/lib/server/core-routes.js +18 -0
  70. package/server/lib/server/linux-distribution.js +47 -0
  71. package/server/lib/server/linux-distribution.test.js +22 -0
  72. package/server/lib/server/runtime-requirements.js +193 -0
  73. package/server/lib/server/runtime-requirements.test.js +295 -0
  74. package/server/lib/server/tunnel-service.DOCUMENTATION.md +1 -1
  75. package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
  76. package/dist/assets/index-BXX8l7mM.css +0 -1
  77. package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
  78. 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
+ });
@@ -8,6 +8,7 @@ import { withCrossProcessLock } from '../server/cross-process-lock.js';
8
8
  const MAX_SETTINGS_BYTES = 2 * 1024 * 1024;
9
9
  const PORTABLE_SETTINGS_MARKER = '__pichamberSettingsScope';
10
10
  const PORTABLE_SETTINGS_VERSION = 'portable-v1';
11
+ const DOCKER_WORKSPACE = '/home/pichamber/workspaces';
11
12
 
12
13
  // Keep this list explicit. settings.json is intended to be copied between hosts.
13
14
  // Retired keys are intentionally absent so saved values cannot restore retired
@@ -18,14 +19,15 @@ const PORTABLE_SETTINGS_VERSION = 'portable-v1';
18
19
  // userMessageRenderingMode, collapsibleUserMessages, stickyUserHeader,
19
20
  // promptNavigatorEnabled, wideChatLayoutEnabled,
20
21
  // showSplitAssistantMessageActions, directoryShowHidden, gitmojiEnabled,
22
+ // notifyOnSubtasks, notifyOnQuestion, notificationTemplates,
21
23
  // desktopWindowControlsPosition/Style (local). persistChatDraft was local-only
22
24
  // UI state and was never part of the server allowlists.
23
25
  const PORTABLE_FIELDS = new Set([
24
26
  'themeId', 'useSystemTheme', 'themeVariant', 'lightThemeId', 'darkThemeId',
25
27
  'splashBgLight', 'splashFgLight', 'splashBgDark', 'splashFgDark',
26
28
  'showDeletionDialog', 'nativeNotificationsEnabled', 'notificationMode',
27
- 'notifyOnSubtasks', 'notifyOnCompletion', 'notifyOnError', 'notifyOnQuestion',
28
- 'notificationTemplates', 'summarizeLastMessage', 'summaryThreshold', 'summaryLength',
29
+ 'notifyOnCompletion', 'notifyOnError',
30
+ 'summarizeLastMessage', 'summaryThreshold', 'summaryLength',
29
31
  'maxLastMessageLength', 'usageAutoRefresh', 'usageRefreshIntervalMs',
30
32
  'usageDisplayMode', 'usageShowPredValues', 'usageDropdownProviders',
31
33
  'usageSelectedModels', 'usageCollapsedFamilies', 'usageExpandedFamilies', 'usageModelGroups',
@@ -103,6 +105,14 @@ const readRecord = async (file, fs) => {
103
105
  }
104
106
  };
105
107
 
108
+ export const createDockerInitialLocalSettings = () => {
109
+ const projectId = `path_${Buffer.from(DOCKER_WORKSPACE).toString('base64url')}`;
110
+ return {
111
+ projects: [{ id: projectId, path: DOCKER_WORKSPACE, label: 'Workspaces' }],
112
+ activeProjectId: projectId,
113
+ };
114
+ };
115
+
106
116
  const writeRecord = async (file, value, fs) => {
107
117
  const serialized = `${JSON.stringify(value, null, 2)}\n`;
108
118
  if (Buffer.byteLength(serialized) > MAX_SETTINGS_BYTES) throw new Error('UI_SETTINGS_INVALID');
@@ -117,6 +127,7 @@ const writeRecord = async (file, value, fs) => {
117
127
  export const createPiUiSettingsStore = ({
118
128
  file = join(resolvePiChamberDataDir(), 'settings.json'),
119
129
  runtimeFile = join(dirname(file), 'runtime-state.json'),
130
+ initialLocalSettings = {},
120
131
  fs = { chmod, mkdir, readFile, rename, writeFile },
121
132
  } = {}) => {
122
133
  let mutation = Promise.resolve();
@@ -127,7 +138,9 @@ export const createPiUiSettingsStore = ({
127
138
  const migrated = portableRoot[PORTABLE_SETTINGS_MARKER] === PORTABLE_SETTINGS_VERSION;
128
139
 
129
140
  if (!migrated) {
141
+ const isFreshStore = Object.keys(portableRoot).length === 0 && Object.keys(runtimeRoot).length === 0;
130
142
  const migratedRuntime = {
143
+ ...(isFreshStore ? selectFields(validateRecord(initialLocalSettings), LOCAL_FIELDS) : {}),
131
144
  ...selectFields(runtimeRoot, LOCAL_FIELDS),
132
145
  ...selectFields(portableRoot, LOCAL_FIELDS),
133
146
  };
@@ -3,7 +3,7 @@ import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
 
6
- import { createPiUiSettingsStore } from './ui-settings-store.js';
6
+ import { createDockerInitialLocalSettings, createPiUiSettingsStore } from './ui-settings-store.js';
7
7
 
8
8
  const makeStore = async () => {
9
9
  const root = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
@@ -22,6 +22,52 @@ describe('Pi UI settings store', () => {
22
22
  await expect(store.read()).rejects.toThrow('UI_SETTINGS_INVALID');
23
23
  });
24
24
 
25
+ it('builds Docker initial settings with a stable path-derived project id', async () => {
26
+ const initialLocalSettings = createDockerInitialLocalSettings();
27
+ expect(initialLocalSettings).toEqual({
28
+ projects: [{
29
+ id: 'path_L2hvbWUvcGljaGFtYmVyL3dvcmtzcGFjZXM',
30
+ path: '/home/pichamber/workspaces',
31
+ label: 'Workspaces',
32
+ }],
33
+ activeProjectId: 'path_L2hvbWUvcGljaGFtYmVyL3dvcmtzcGFjZXM',
34
+ });
35
+
36
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
37
+ const store = createPiUiSettingsStore({
38
+ file: join(root, 'settings.json'),
39
+ runtimeFile: join(root, 'runtime-state.json'),
40
+ initialLocalSettings,
41
+ });
42
+ await expect(store.read()).resolves.toMatchObject(initialLocalSettings);
43
+ });
44
+
45
+ it('seeds initial local settings only for a fresh store', async () => {
46
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
47
+ const file = join(root, 'settings.json');
48
+ const runtimeFile = join(root, 'runtime-state.json');
49
+ const initialLocalSettings = {
50
+ projects: [{ id: 'workspaces', path: '/home/pichamber/workspaces', label: 'Workspaces' }],
51
+ activeProjectId: 'workspaces',
52
+ };
53
+ const store = createPiUiSettingsStore({ file, runtimeFile, initialLocalSettings });
54
+
55
+ await expect(store.read()).resolves.toMatchObject(initialLocalSettings);
56
+ await store.write({ projects: [], activeProjectId: null });
57
+ await expect(store.read()).resolves.toMatchObject({ projects: [], activeProjectId: null });
58
+
59
+ const existingRoot = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
60
+ const existingFile = join(existingRoot, 'settings.json');
61
+ const existingRuntimeFile = join(existingRoot, 'runtime-state.json');
62
+ await writeFile(existingFile, JSON.stringify({ themeId: 'nord' }));
63
+ const existingStore = createPiUiSettingsStore({
64
+ file: existingFile,
65
+ runtimeFile: existingRuntimeFile,
66
+ initialLocalSettings,
67
+ });
68
+ await expect(existingStore.read()).resolves.toEqual({ themeId: 'nord' });
69
+ });
70
+
25
71
  it('migrates a flat settings file into portable and local allowlists', async () => {
26
72
  const { file, runtimeFile, store } = await makeStore();
27
73
  await writeFile(file, JSON.stringify({
@@ -64,6 +64,15 @@ export const registerServerStatusRoutes = (app, dependencies) => {
64
64
  process,
65
65
  pichamberVersion,
66
66
  runtimeName,
67
+ // Server origin metadata, reported verbatim on /health and /api/version
68
+ // so clients can adapt without probing. deploymentKind is 'docker' for
69
+ // the container image and 'host' otherwise; serverPlatform is
70
+ // process.platform ('linux', 'darwin', 'win32'); serverDistribution is
71
+ // the Linux distribution id (e.g. 'debian', 'nixos') or null when
72
+ // unknown or not Linux.
73
+ deploymentKind = 'host',
74
+ serverPlatform = 'unknown',
75
+ serverDistribution = null,
67
76
  serverStartedAt,
68
77
  gracefulShutdown,
69
78
  getHealthSnapshot,
@@ -245,6 +254,9 @@ export const registerServerStatusRoutes = (app, dependencies) => {
245
254
  timestamp: new Date().toISOString(),
246
255
  pichamberVersion,
247
256
  runtime: runtimeName,
257
+ deploymentKind,
258
+ serverPlatform,
259
+ ...(serverDistribution ? { serverDistribution } : {}),
248
260
  compatibility,
249
261
  ...(serverId ? { serverId } : {}),
250
262
  ...getHealthSnapshot(),
@@ -257,6 +269,9 @@ export const registerServerStatusRoutes = (app, dependencies) => {
257
269
  status: 'ok',
258
270
  pichamberVersion,
259
271
  runtime: runtimeName,
272
+ deploymentKind,
273
+ serverPlatform,
274
+ ...(serverDistribution ? { serverDistribution } : {}),
260
275
  startedAt: serverStartedAt,
261
276
  compatibility,
262
277
  ...(serverId ? { serverId } : {}),
@@ -360,6 +375,9 @@ export const registerServerStatusRoutes = (app, dependencies) => {
360
375
  res.json({
361
376
  pichamberVersion,
362
377
  runtime: runtimeName,
378
+ deploymentKind,
379
+ serverPlatform,
380
+ ...(serverDistribution ? { serverDistribution } : {}),
363
381
  pid: process.pid,
364
382
  startedAt: serverStartedAt,
365
383
  port: getServerPort(),
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ const KNOWN_DISTRIBUTIONS = new Set(['ubuntu', 'arch', 'nixos', 'fedora', 'debian', 'centos']);
4
+
5
+ const DISTRIBUTION_ALIASES = new Map([
6
+ ['archlinux', 'arch'],
7
+ ['endeavouros', 'arch'],
8
+ ['manjaro', 'arch'],
9
+ ['pop', 'ubuntu'],
10
+ ['linuxmint', 'ubuntu'],
11
+ ['elementary', 'ubuntu'],
12
+ ['rhel', 'fedora'],
13
+ ['rocky', 'centos'],
14
+ ['almalinux', 'centos'],
15
+ ]);
16
+
17
+ const normalizeDistribution = (value) => {
18
+ const id = String(value || '').trim().toLowerCase();
19
+ return KNOWN_DISTRIBUTIONS.has(id) ? id : DISTRIBUTION_ALIASES.get(id) || null;
20
+ };
21
+
22
+ export const parseLinuxDistribution = (content) => {
23
+ const values = new Map();
24
+ for (const line of String(content || '').split(/\r?\n/)) {
25
+ const match = /^([A-Z_]+)=(.*)$/.exec(line.trim());
26
+ if (!match) continue;
27
+ const raw = match[2].trim();
28
+ values.set(match[1], raw.replace(/^(["'])(.*)\1$/, '$2'));
29
+ }
30
+
31
+ const direct = normalizeDistribution(values.get('ID'));
32
+ if (direct) return direct;
33
+ for (const related of String(values.get('ID_LIKE') || '').split(/\s+/)) {
34
+ const normalized = normalizeDistribution(related);
35
+ if (normalized) return normalized;
36
+ }
37
+ return null;
38
+ };
39
+
40
+ export const detectLinuxDistribution = ({ platform = process.platform, readFile = readFileSync } = {}) => {
41
+ if (platform !== 'linux') return null;
42
+ try {
43
+ return parseLinuxDistribution(readFile('/etc/os-release', 'utf8'));
44
+ } catch {
45
+ return null;
46
+ }
47
+ };