@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
package/README.md CHANGED
@@ -4,7 +4,9 @@ PiChamber server and browser UI for the [Pi coding agent](https://pi.dev). It se
4
4
 
5
5
  ## Requirements
6
6
 
7
- Node.js 22 or newer, or Bun.
7
+ Server needs Node.js 22.19 or newer (24 recommended) or Bun 1.4 or newer (1.4.2 recommended).
8
+
9
+ Background `pichamber serve` picks Node first with Bun fallback. Foreground `serve --foreground` runs in the current runtime with no PATH lookup. Startup services reuse the pinned runtime from `startup enable`. Docker images launch from pinned Bun 1.4.2. Update a Docker deployment by pulling a new image and recreating the container; `pichamber update` is disabled inside the image. The desktop app runs its bundled Node in-process. The mobile app connects to an existing server.
8
10
 
9
11
  ## Install
10
12
 
package/bin/cli.js CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
- import { spawnSync } from 'child_process';
6
5
  import { fileURLToPath, pathToFileURL } from 'url';
7
6
  import { isModuleCliExecution } from './cli-entry.js';
8
7
  import { EXIT_CODE, TunnelCliError } from './lib/cli-errors.js';
@@ -60,6 +59,10 @@ import {
60
59
  isPiChamberCmdline,
61
60
  getOpenchamberProcessState,
62
61
  } from './lib/cli-process.js';
62
+ import {
63
+ getBunBinary,
64
+ resolveServerExecutable as sharedResolveServerExecutable,
65
+ } from './lib/server-runtime.js';
63
66
  import {
64
67
  intro as clackIntro, outro as clackOutro, cancel as clackCancel,
65
68
  isJsonMode,
@@ -107,37 +110,10 @@ function importFromFilePath(filePath) {
107
110
  return import(pathToFileURL(filePath).href);
108
111
  }
109
112
 
110
- function getBunBinary() {
111
- if (typeof process.env.BUN_BINARY === 'string' && process.env.BUN_BINARY.trim().length > 0) {
112
- return process.env.BUN_BINARY.trim();
113
- }
114
- if (typeof process.env.BUN_INSTALL === 'string' && process.env.BUN_INSTALL.trim().length > 0) {
115
- return path.join(process.env.BUN_INSTALL.trim(), 'bin', 'bun');
116
- }
117
- return 'bun';
118
- }
119
-
120
113
  const BUN_BIN = getBunBinary();
121
114
 
122
- function isBunRuntime() {
123
- return typeof globalThis.Bun !== 'undefined';
124
- }
125
-
126
- function isBunInstalled() {
127
- try {
128
- const result = spawnSync(BUN_BIN, ['--version'], {
129
- stdio: 'ignore',
130
- env: process.env,
131
- windowsHide: true,
132
- });
133
- return result.status === 0;
134
- } catch {
135
- return false;
136
- }
137
- }
138
-
139
- function getPreferredServerRuntime() {
140
- return isBunInstalled() ? 'bun' : 'node';
115
+ function resolveServerExecutable() {
116
+ return sharedResolveServerExecutable({ bunBin: BUN_BIN });
141
117
  }
142
118
 
143
119
  const commands = {
@@ -160,8 +136,7 @@ const commands = {
160
136
 
161
137
  commands.serve = createServeCommand({
162
138
  serverPath: path.join(__dirname, '..', 'server', 'index.js'),
163
- bunBin: BUN_BIN,
164
- getPreferredServerRuntime,
139
+ resolveServerExecutable,
165
140
  setForegroundServerActive(value) { foregroundServerActive = value; },
166
141
  setForegroundShutdown(handler) { foregroundShutdown = handler; },
167
142
  });
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isModuleCliExecution } from './cli-entry.js';
7
+ import { resolveServerExecutable } from './lib/server-runtime.js';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+ const DEV_SERVER_PATH = path.join(__dirname, '..', 'server', 'index.js');
12
+
13
+ // Conventional shell exit codes for signal termination (128 + signal number).
14
+ // Matches scripts/dev-web-*.mjs precedent (SIGINT 130, SIGTERM 143, SIGHUP 129).
15
+ export const SIGNAL_EXIT_CODES = {
16
+ SIGHUP: 129,
17
+ SIGINT: 130,
18
+ SIGQUIT: 131,
19
+ SIGUSR1: 138,
20
+ SIGUSR2: 140,
21
+ SIGTERM: 143,
22
+ };
23
+
24
+ const BASE_LIFECYCLE_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
25
+ const USR_LIFECYCLE_SIGNALS = ['SIGUSR1', 'SIGUSR2'];
26
+
27
+ function getLifecycleSignals(processRef) {
28
+ const platform = processRef?.platform ?? process.platform;
29
+ if (platform === 'win32') return [...BASE_LIFECYCLE_SIGNALS];
30
+ return [...BASE_LIFECYCLE_SIGNALS, ...USR_LIFECYCLE_SIGNALS];
31
+ }
32
+
33
+ export function resolveSignalExitCode(signal) {
34
+ return SIGNAL_EXIT_CODES[signal] ?? 1;
35
+ }
36
+
37
+ export function forwardSignalToChild(child, signal) {
38
+ if (!child || typeof child.kill !== 'function') return false;
39
+ if (child.exitCode !== null && child.exitCode !== undefined) return false;
40
+ if (child.signalCode !== null && child.signalCode !== undefined) return false;
41
+ try {
42
+ child.kill(signal);
43
+ return true;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ function buildDevServerCommand(resolved, serverPath = DEV_SERVER_PATH, serverArgs = []) {
50
+ return { executable: resolved.executable, args: [serverPath, ...serverArgs] };
51
+ }
52
+
53
+ function resolveDevServerCommand({
54
+ resolveFn = resolveServerExecutable,
55
+ serverPath = DEV_SERVER_PATH,
56
+ serverArgs = [],
57
+ } = {}) {
58
+ const resolved = resolveFn();
59
+ return {
60
+ runtime: resolved.runtime,
61
+ executable: resolved.executable,
62
+ args: [serverPath, ...serverArgs],
63
+ };
64
+ }
65
+
66
+ function startDevServerChild({
67
+ spawnFn = spawn,
68
+ resolveFn = resolveServerExecutable,
69
+ serverPath = DEV_SERVER_PATH,
70
+ serverArgs = [],
71
+ env = process.env,
72
+ } = {}) {
73
+ const command = resolveDevServerCommand({ resolveFn, serverPath, serverArgs });
74
+ const child = spawnFn(command.executable, command.args, { stdio: 'inherit', env });
75
+ return { command, child };
76
+ }
77
+
78
+ // Single-child lifecycle: forward parent signals to the direct backend child
79
+ // and propagate the backend exit. Direct child.kill only — no process-tree
80
+ // framework. The backend owns its detached Pi session daemon via authenticated
81
+ // IPC (supervisor stop), so killing the whole tree would terminate a daemon
82
+ // that is intentionally detached. The backend handles SIGINT/SIGTERM
83
+ // gracefully; SIGUSR2/SIGHUP/SIGQUIT terminate with default semantics.
84
+ //
85
+ // SIGINT process-group double delivery: Ctrl+C in a terminal delivers SIGINT
86
+ // to the whole foreground group, so launcher and backend both receive it.
87
+ // Forwarding is idempotent (second kill is a harmless no-op when the backend
88
+ // already exited) and the launcher waits for the backend exit instead of
89
+ // exiting immediately, so the backend is never orphaned. The launcher's own
90
+ // signal code takes precedence over the backend's exit code to preserve
91
+ // Ctrl+C (130) semantics even when the backend exits 0 after graceful
92
+ // shutdown.
93
+ //
94
+ // Nodemon restart (dev:server:watch): nodemon's default signal is SIGUSR2. It
95
+ // kills its whole subtree (launcher and backend) with SIGUSR2 via psTree, so
96
+ // the backend usually already received SIGUSR2 directly. Forwarding is a
97
+ // redundant backup for missed delivery; the launcher then exits 140 after the
98
+ // backend exits, letting nodemon restart.
99
+ export function attachDevServerLifecycle({
100
+ child,
101
+ command,
102
+ processRef = process,
103
+ exitFn = (code) => process.exit(code),
104
+ logger = console,
105
+ } = {}) {
106
+ if (!child || typeof child.on !== 'function') {
107
+ throw new Error('attachDevServerLifecycle requires a child process with .on()');
108
+ }
109
+ let settled = false;
110
+ let pendingSignalCode = null;
111
+ const executableLabel = command?.executable ?? 'dev server';
112
+ const exitOnce = (code) => {
113
+ if (settled) return;
114
+ settled = true;
115
+ exitFn(code);
116
+ };
117
+
118
+ child.on('error', (error) => {
119
+ logger.error(
120
+ `Error: failed to start dev server with ${executableLabel}: ${error instanceof Error ? error.message : String(error)}`,
121
+ );
122
+ exitOnce(1);
123
+ });
124
+
125
+ child.on('exit', (code, signal) => {
126
+ if (pendingSignalCode !== null) {
127
+ exitOnce(pendingSignalCode);
128
+ return;
129
+ }
130
+ if (signal) {
131
+ exitOnce(resolveSignalExitCode(signal));
132
+ return;
133
+ }
134
+ exitOnce(typeof code === 'number' ? code : 1);
135
+ });
136
+
137
+ for (const signal of getLifecycleSignals(processRef)) {
138
+ try {
139
+ processRef.on(signal, () => {
140
+ if (settled) return;
141
+ if (pendingSignalCode === null) {
142
+ pendingSignalCode = resolveSignalExitCode(signal);
143
+ }
144
+ forwardSignalToChild(child, signal);
145
+ });
146
+ } catch {
147
+ // Unsupported signal on this platform (e.g. SIGUSR2 on Windows).
148
+ }
149
+ }
150
+
151
+ return {
152
+ getPendingSignalCode: () => pendingSignalCode,
153
+ isSettled: () => settled,
154
+ };
155
+ }
156
+
157
+ async function main({
158
+ processRef = process,
159
+ exitFn = (code) => process.exit(code),
160
+ spawnFn = spawn,
161
+ resolveFn = resolveServerExecutable,
162
+ serverArgs = process.argv.slice(2),
163
+ logger = console,
164
+ env = processRef?.env ?? process.env,
165
+ } = {}) {
166
+ let started;
167
+ try {
168
+ started = startDevServerChild({ spawnFn, resolveFn, serverArgs, env });
169
+ } catch (error) {
170
+ logger.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
171
+ exitFn(1);
172
+ return;
173
+ }
174
+ const { command, child } = started;
175
+ logger.log(`[pichamber] dev server runtime: ${command.runtime} (${command.executable})`);
176
+ attachDevServerLifecycle({ child, command, processRef, exitFn, logger });
177
+ }
178
+
179
+ const isDevServerExecution = isModuleCliExecution(process.argv[1], import.meta.url, fs.realpathSync);
180
+
181
+ if (isDevServerExecution) {
182
+ await main();
183
+ }
184
+
185
+ export { DEV_SERVER_PATH, buildDevServerCommand, resolveDevServerCommand, startDevServerChild };
@@ -0,0 +1,252 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { EventEmitter } from 'node:events';
3
+ import {
4
+ attachDevServerLifecycle,
5
+ buildDevServerCommand,
6
+ forwardSignalToChild,
7
+ resolveDevServerCommand,
8
+ resolveSignalExitCode,
9
+ startDevServerChild,
10
+ } from './dev-server.js';
11
+
12
+ function createMockChild() {
13
+ const child = new EventEmitter();
14
+ child.pid = 4242;
15
+ child.exitCode = null;
16
+ child.signalCode = null;
17
+ child.killCalls = [];
18
+ child.kill = (signal) => {
19
+ child.killCalls.push(signal ?? 'SIGTERM');
20
+ return true;
21
+ };
22
+ return child;
23
+ }
24
+
25
+ function createMockProcess() {
26
+ const proc = new EventEmitter();
27
+ proc.platform = 'linux';
28
+ proc.env = { PICHAMBER_SERVER_PROFILE_KIND: 'dev' };
29
+ return proc;
30
+ }
31
+
32
+ function createSilentLogger() {
33
+ return { log: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() };
34
+ }
35
+
36
+ describe('dev server runtime', () => {
37
+ it('builds the server command from the resolved executable', () => {
38
+ const command = buildDevServerCommand(
39
+ { runtime: 'node', executable: '/mock/node' },
40
+ '/app/server/index.js',
41
+ ['--port', '3001'],
42
+ );
43
+ expect(command).toEqual({
44
+ executable: '/mock/node',
45
+ args: ['/app/server/index.js', '--port', '3001'],
46
+ });
47
+ });
48
+
49
+ it('resolves the runtime once per start', () => {
50
+ let resolveCalls = 0;
51
+ const command = resolveDevServerCommand({
52
+ resolveFn: () => {
53
+ resolveCalls += 1;
54
+ return { runtime: 'bun', executable: '/mock/bun' };
55
+ },
56
+ serverPath: '/app/server/index.js',
57
+ serverArgs: ['--port', '3001'],
58
+ });
59
+ expect(resolveCalls).toBe(1);
60
+ expect(command).toEqual({
61
+ runtime: 'bun',
62
+ executable: '/mock/bun',
63
+ args: ['/app/server/index.js', '--port', '3001'],
64
+ });
65
+ });
66
+
67
+ it('spawns once with the resolved executable and server args', () => {
68
+ let resolveCalls = 0;
69
+ const spawned = [];
70
+ const { command, child } = startDevServerChild({
71
+ resolveFn: () => {
72
+ resolveCalls += 1;
73
+ return { runtime: 'node', executable: '/mock/node' };
74
+ },
75
+ spawnFn: (executable, args, options) => {
76
+ spawned.push({ executable, args, options });
77
+ return { pid: 4242, on() {}, kill() {} };
78
+ },
79
+ serverPath: '/app/server/index.js',
80
+ serverArgs: ['--port', '3001'],
81
+ env: { PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
82
+ });
83
+ expect(resolveCalls).toBe(1);
84
+ expect(spawned).toHaveLength(1);
85
+ expect(spawned[0].executable).toBe('/mock/node');
86
+ expect(spawned[0].args).toEqual(['/app/server/index.js', '--port', '3001']);
87
+ expect(spawned[0].options.env.PICHAMBER_SERVER_PROFILE_KIND).toBe('dev');
88
+ expect(command.executable).toBe('/mock/node');
89
+ expect(child.pid).toBe(4242);
90
+ });
91
+ });
92
+
93
+ describe('dev server signal exit codes', () => {
94
+ it('uses conventional 128+signal codes', () => {
95
+ expect(resolveSignalExitCode('SIGINT')).toBe(130);
96
+ expect(resolveSignalExitCode('SIGTERM')).toBe(143);
97
+ expect(resolveSignalExitCode('SIGHUP')).toBe(129);
98
+ expect(resolveSignalExitCode('SIGQUIT')).toBe(131);
99
+ expect(resolveSignalExitCode('SIGUSR2')).toBe(140);
100
+ });
101
+
102
+ it('does not forward when the child already exited', () => {
103
+ const exited = createMockChild();
104
+ exited.exitCode = 0;
105
+ expect(forwardSignalToChild(exited, 'SIGINT')).toBe(false);
106
+ expect(exited.killCalls).toHaveLength(0);
107
+ });
108
+
109
+ it('tolerates a kill failure without throwing', () => {
110
+ const child = createMockChild();
111
+ child.kill = () => { throw new Error('ESRCH'); };
112
+ expect(forwardSignalToChild(child, 'SIGTERM')).toBe(false);
113
+ });
114
+ });
115
+
116
+ describe('dev server lifecycle (isolated fixtures, never the prod server)', () => {
117
+ it('propagates a nonzero child exit code', () => {
118
+ const child = createMockChild();
119
+ const proc = createMockProcess();
120
+ const exitCodes = [];
121
+ attachDevServerLifecycle({
122
+ child,
123
+ command: { runtime: 'node', executable: '/mock/node' },
124
+ processRef: proc,
125
+ exitFn: (code) => { exitCodes.push(code); },
126
+ logger: createSilentLogger(),
127
+ });
128
+ child.emit('exit', 3, null);
129
+ expect(exitCodes).toEqual([3]);
130
+ });
131
+
132
+ it('maps a child signal exit to the conventional code', () => {
133
+ const child = createMockChild();
134
+ const proc = createMockProcess();
135
+ const exitCodes = [];
136
+ attachDevServerLifecycle({
137
+ child,
138
+ command: { runtime: 'node', executable: '/mock/node' },
139
+ processRef: proc,
140
+ exitFn: (code) => { exitCodes.push(code); },
141
+ logger: createSilentLogger(),
142
+ });
143
+ child.emit('exit', null, 'SIGTERM');
144
+ expect(exitCodes).toEqual([143]);
145
+ });
146
+
147
+ it('fails explicitly when the resolver has no supported runtime', () => {
148
+ expect(() => startDevServerChild({
149
+ resolveFn: () => { throw new Error('No supported server runtime found. Install Node.js 22.19.0 or newer, or Bun 1.4.0 or newer.'); },
150
+ spawnFn: () => { throw new Error('should not spawn without a runtime'); },
151
+ serverPath: '/tmp/fake-dev-server-index.js',
152
+ serverArgs: ['--port', '3902'],
153
+ })).toThrow('No supported server runtime');
154
+ });
155
+
156
+ it('fails explicitly when spawn throws synchronously', () => {
157
+ expect(() => startDevServerChild({
158
+ resolveFn: () => ({ runtime: 'node', executable: '/mock/node' }),
159
+ spawnFn: () => { throw new Error('spawn ENOENT'); },
160
+ serverPath: '/tmp/fake-dev-server-index.js',
161
+ serverArgs: ['--port', '3902'],
162
+ })).toThrow('spawn ENOENT');
163
+ });
164
+
165
+ it('exits 1 once on async spawn error even if exit follows', () => {
166
+ const child = createMockChild();
167
+ const proc = createMockProcess();
168
+ const exitCodes = [];
169
+ const logger = createSilentLogger();
170
+ attachDevServerLifecycle({
171
+ child,
172
+ command: { runtime: 'node', executable: '/mock/node' },
173
+ processRef: proc,
174
+ exitFn: (code) => { exitCodes.push(code); },
175
+ logger,
176
+ });
177
+ child.emit('error', new Error('spawn ENOENT'));
178
+ child.emit('exit', 1, null);
179
+ expect(exitCodes).toEqual([1]);
180
+ expect(logger.error).toHaveBeenCalledTimes(1);
181
+ });
182
+
183
+ it('forwards SIGINT and preserves 130 even when the backend exits 0 (process-group double delivery)', () => {
184
+ const child = createMockChild();
185
+ const proc = createMockProcess();
186
+ const exitCodes = [];
187
+ attachDevServerLifecycle({
188
+ child,
189
+ command: { runtime: 'node', executable: '/mock/node' },
190
+ processRef: proc,
191
+ exitFn: (code) => { exitCodes.push(code); },
192
+ logger: createSilentLogger(),
193
+ });
194
+ proc.emit('SIGINT');
195
+ expect(child.killCalls).toEqual(['SIGINT']);
196
+ // Backend also received SIGINT directly from the terminal group and shut
197
+ // down gracefully with code 0; the launcher still reports 130.
198
+ child.emit('exit', 0, null);
199
+ expect(exitCodes).toEqual([130]);
200
+ });
201
+
202
+ it('forwards SIGTERM and exits 143 after backend cleanup', () => {
203
+ const child = createMockChild();
204
+ const proc = createMockProcess();
205
+ const exitCodes = [];
206
+ attachDevServerLifecycle({
207
+ child,
208
+ command: { runtime: 'bun', executable: '/mock/bun' },
209
+ processRef: proc,
210
+ exitFn: (code) => { exitCodes.push(code); },
211
+ logger: createSilentLogger(),
212
+ });
213
+ proc.emit('SIGTERM');
214
+ expect(child.killCalls).toEqual(['SIGTERM']);
215
+ child.emit('exit', null, 'SIGTERM');
216
+ expect(exitCodes).toEqual([143]);
217
+ });
218
+
219
+ it('forwards SIGUSR2 for nodemon restart and exits 140', () => {
220
+ const child = createMockChild();
221
+ const proc = createMockProcess();
222
+ const exitCodes = [];
223
+ attachDevServerLifecycle({
224
+ child,
225
+ command: { runtime: 'bun', executable: '/mock/bun' },
226
+ processRef: proc,
227
+ exitFn: (code) => { exitCodes.push(code); },
228
+ logger: createSilentLogger(),
229
+ });
230
+ proc.emit('SIGUSR2');
231
+ expect(child.killCalls).toEqual(['SIGUSR2']);
232
+ child.emit('exit', null, 'SIGUSR2');
233
+ expect(exitCodes).toEqual([140]);
234
+ });
235
+
236
+ it('handles repeated SIGINT idempotently with a single exit', () => {
237
+ const child = createMockChild();
238
+ const proc = createMockProcess();
239
+ const exitCodes = [];
240
+ attachDevServerLifecycle({
241
+ child,
242
+ command: { runtime: 'node', executable: '/mock/node' },
243
+ processRef: proc,
244
+ exitFn: (code) => { exitCodes.push(code); },
245
+ logger: createSilentLogger(),
246
+ });
247
+ proc.emit('SIGINT');
248
+ proc.emit('SIGINT');
249
+ child.emit('exit', 0, null);
250
+ expect(exitCodes).toEqual([130]);
251
+ });
252
+ });
@@ -13,6 +13,25 @@ This directory contains non-entrypoint PiChamber CLI implementation. `../cli.js`
13
13
  - `pichamber version` and `pichamber --version`: print the installed package version; `--json` returns the same value as JSON.
14
14
  - `commands-update.js`: package update and restart coordination. Interactive updates review the old and target versions, selected server channel, and restart impact before installation; `--yes` skips confirmation. The host-local default channel is `stable`; `--channel stable|rc` overrides it for one run, and RC subscribers receive the highest available version across stable and numbered RC releases. Updates only a writable global install owned by the running CLI. Deployment preflight reports stable reason codes and instructions for containers, source checkouts, custom systemd units, ownership mismatches, and unsupported installs before changing files. Package-manager output is suppressed for `--quiet`/`--json`; results distinguish the previous, installed, and latest versions and report partial restart failures with a non-zero CLI exit. An update requested from the managed PiChamber systemd service, including its browser terminal, moves into a transient systemd unit before replacing the package and restarting `pichamber.service`. Update jobs persist non-secret progress, channel, and an exact registry-validated target version in the PiChamber run directory so clients can resume status polling after restart without a moving dist-tag changing the installation target. Installation must verify that exact version before any managed service or instance restart. Terminal job state is persisted before JSON, quiet, or interactive output, and status reads mark dead workers or workers that miss the startup grace period as failed.
15
15
  - `commands-tunnel.js`: tunnel lifecycle and profile management. Interactive tunnel setup ends with a review and confirmation; fully specified flag and profile runs remain direct. Auto-started servers never write nested output into the parent command's `--quiet` or `--json` result.
16
+ - `server-runtime.js`: thin bridge over `../../server/lib/server/runtime-requirements.js`. `dev-server.js` uses the same helper for dev servers.
17
+
18
+ ## Server runtime
19
+
20
+ Server needs Node.js 22.19 or newer (24 recommended) or Bun 1.4 or newer (1.4.2 recommended). `runtime-requirements.js` owns version rules and probing. `server-runtime.js` only re-exports it.
21
+
22
+ Background `serve` picks Node first. It reuses the current executable when the CLI runs on supported Node, else probes `node` on PATH, else uses the configured Bun binary. Each probe runs `bin --version` with a 5s timeout. Only stable `X.Y.Z` counts. Prerelease and build metadata fail. Old Bun that emulates a new Node version still fails on its Bun version.
23
+
24
+ `BUN_BINARY` beats `BUN_INSTALL/bin/bun` beats `bun` on PATH. A configured value is validated and fails when unsupported instead of falling through. Without config, a supported current Bun works even off PATH before PATH is probed.
25
+
26
+ Foreground `serve --foreground`, `startup enable`, and `startWebUiServer` validate the current executable only. They never probe PATH and never switch runtimes. The `startWebUiServer` gate covers direct CLI and Electron in-process startup. `startup enable` validates before it writes any service file and pins `process.execPath`, not the package manager.
27
+
28
+ Dev `dev:server` and `dev:server:watch` use the same Node-first order through `../dev-server.js`. Builds and package management stay on Bun. Docker images launch from pinned Bun 1.4.2, but background selection still prefers supported Node when present. Docker deployments report `DOCKER_DEPLOYMENT` and must pull a new image then recreate the container.
29
+
30
+ Upgrade note: if your system still runs Bun 1.3.14, update Bun before you restart a Bun-pinned service. The source `packageManager` pin does not replace the installed binary. Node 22.0 through 22.18 is unsupported. No session migration is needed.
31
+
32
+ Smoke: `bun run test:runtime` at the root runs `vitest run server/lib/pi/session-daemon/pi-runtime-smoke.test.js` in `packages/web`. It defaults to `process.execPath` (Vitest runs under Node). Set `PICHAMBER_TEST_RUNTIME` to an absolute server binary to run the same probes under another runtime. The file checks the bundled SDK import with pinned version parity, bundled `bin.pi --help`, credential-free `rpc get_state` to success, and a credential-free foreground `serve --foreground --api-only` that polls `/api/pi/runtime` to ready and checks parent and daemon `execPath`. It is not provider E2E. Children run with isolated dirs, an allowlisted env, and bounded timeouts.
33
+
34
+ PR checks and release call the reusable `runtime-smoke.yml` workflow on Linux across Node 22.19, Node 24, Bun 1.4.0, and Bun 1.4.2.
16
35
 
17
36
  ## Rules
18
37
 
@@ -6,6 +6,7 @@ import { DEFAULT_PORT } from './cli-args.js';
6
6
  import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
7
7
  import { getDataDir } from './cli-paths.js';
8
8
  import { assertAuthenticatedNetworkExposure, hasUiPasswordConfigured, resolveServeUiPassword } from './cli-network.js';
9
+ import { assertCurrentRuntimeSupported as defaultAssertCurrentRuntimeSupported } from './server-runtime.js';
9
10
 
10
11
  const STARTUP_SERVICE_ID = 'dev.pichamber.web';
11
12
 
@@ -364,7 +365,14 @@ function getStartupStatus() {
364
365
  };
365
366
  }
366
367
 
367
- function enableStartupService(options = {}) {
368
+ function enableStartupService(options = {}, deps = {}) {
369
+ const assertCurrentRuntime = typeof deps.assertCurrentRuntime === 'function'
370
+ ? deps.assertCurrentRuntime
371
+ : defaultAssertCurrentRuntimeSupported;
372
+ // Startup services reuse the current executable (`process.execPath`) inline
373
+ // under the service manager. Validate the current runtime before
374
+ // persisting any service files so an unsupported runtime never enables.
375
+ assertCurrentRuntime();
368
376
  const paths = getStartupServicePaths();
369
377
  if (!paths.servicePath) {
370
378
  throw new TunnelCliError(`Startup integration is not supported on ${paths.platform}.`, EXIT_CODE.USAGE_ERROR);
@@ -32,6 +32,36 @@ describe('systemd startup activation', () => {
32
32
  });
33
33
  });
34
34
 
35
+ describe('startup runtime validation', () => {
36
+ it('rejects enable on unsupported current runtime before persisting', async () => {
37
+ const { enableStartupService } = await import('./cli-startup.js');
38
+ const assertCurrentRuntime = () => {
39
+ throw new Error('Unsupported server runtime: Node.js v20.19.0 is not supported. Install Node.js 22.19.0 or newer, or Bun 1.4.0 or newer.');
40
+ };
41
+ expect(() => enableStartupService(
42
+ { port: 3000, host: '127.0.0.1' },
43
+ { assertCurrentRuntime },
44
+ )).toThrow(/Unsupported server runtime/);
45
+ });
46
+
47
+ it('rejects old Bun enable even when emulated Node looks new', async () => {
48
+ const { assertCurrentRuntimeSupported } = await import('./server-runtime.js');
49
+ expect(() => assertCurrentRuntimeSupported({
50
+ isBun: true,
51
+ nodeVersion: 'v26.3.0',
52
+ bunVersion: '1.3.14',
53
+ execPath: '/mock/old-bun',
54
+ })).toThrow(/Bun 1\.3\.14/);
55
+ });
56
+
57
+ it('keeps status usable on old runtimes (no current validation)', async () => {
58
+ const { getStartupStatus } = await import('./cli-startup.js');
59
+ // Status never validates the current runtime so help/status/stop stay
60
+ // usable when serve/startup enable would fail.
61
+ expect(() => getStartupStatus()).not.toThrow(/Unsupported server runtime/);
62
+ });
63
+ });
64
+
35
65
  describe('startup service paths', () => {
36
66
  const originalPlatform = process.platform;
37
67
  const originalGetuid = process.getuid;
@@ -9,6 +9,7 @@ import { ensureLogsDir, getLogFilePath } from './cli-paths.js';
9
9
  import { rotateLogFile } from './cli-log-files.js';
10
10
  import { discoverPiChamberInstanceOnPort, isDesktopRuntimeForPort } from './cli-lifecycle.js';
11
11
  import { getPidFilePath, getInstanceFilePath, writePidFile, writeInstanceOptions, removePidFile, removeInstanceFile, isProcessRunning, terminateProcessTree } from './cli-process.js';
12
+ import { resolveServerExecutable as defaultResolveServerExecutable, assertCurrentRuntimeSupported as defaultAssertCurrentRuntimeSupported } from './server-runtime.js';
12
13
  import { isNetworkExposedBindHost } from '../../server/lib/security/bind-host.js';
13
14
  import {
14
15
  intro as clackIntro,
@@ -171,8 +172,9 @@ async function collectInteractiveServeOptions(options, prompts = servePromptApi)
171
172
 
172
173
  function createServeCommand({
173
174
  serverPath,
174
- bunBin,
175
- getPreferredServerRuntime,
175
+ resolveServerExecutable = defaultResolveServerExecutable,
176
+ assertCurrentRuntime = defaultAssertCurrentRuntimeSupported,
177
+ spawnFn = spawn,
176
178
  setForegroundServerActive,
177
179
  setForegroundShutdown,
178
180
  }) {
@@ -254,8 +256,10 @@ async function serveCommand(options) {
254
256
  }
255
257
  }
256
258
 
257
- const preferredRuntime = getPreferredServerRuntime();
258
- const runtimeBin = preferredRuntime === 'bun' ? bunBin : process.execPath;
259
+ // Foreground validates its own executable without probing or switching.
260
+ const runtimeBin = options.foreground
261
+ ? assertCurrentRuntime().executable
262
+ : resolveServerExecutable().executable;
259
263
 
260
264
  ensureLogsDir();
261
265
  const initialLogPort = targetPort === 0 ? 'auto' : String(targetPort);
@@ -439,7 +443,7 @@ async function serveCommand(options) {
439
443
 
440
444
  const serveSpin = showOutput ? createSpinner(options) : null;
441
445
 
442
- const child = spawn(runtimeBin, serverArgs, {
446
+ const child = spawnFn(runtimeBin, serverArgs, {
443
447
  detached: true,
444
448
  windowsHide: true,
445
449
  stdio: ['ignore', logFd, logFd, 'ipc'],
@@ -0,0 +1,6 @@
1
+ export {
2
+ getBunBinary,
3
+ isSupportedNodeVersion,
4
+ resolveServerExecutable,
5
+ assertCurrentRuntimeSupported,
6
+ } from '../../server/lib/server/runtime-requirements.js';