@pi-chamber/web 0.9.9 → 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 +72 -67
  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-YPcSEyVl.js → DiagramView-COHSzZ9Z.js} +1 -1
  12. package/dist/assets/{DiffView-IrM_w65M.js → DiffView-BA4LWExp.js} +1 -1
  13. package/dist/assets/{FileSaveConflictDialog-CtDwDmHo.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
  14. package/dist/assets/{FilesView-EUL5SZDG.js → FilesView-CIx6Bq8l.js} +1 -1
  15. package/dist/assets/{GitView-7K4eJ1V3.js → GitView-3Hgk_pVS.js} +3 -3
  16. package/dist/assets/{JsonTreeView-Qz0QeRmI.js → JsonTreeView-CVLGj7jk.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-CsJfFWDC.js → MarkdownRendererImpl-CWeQW9_O.js} +2 -2
  18. package/dist/assets/{PatchDiff-DNhojsLA.js → PatchDiff-367QPDDL.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-l1fTUann.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-CUyTFUnd.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-CY3rTilj.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
  22. package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
  23. package/dist/assets/{SettingsWindow-9FD4QY3p.js → SettingsWindow-CN0wm-Fv.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-0uj3Kf5J.js → ToolOutputDialog-Bkh0DWJn.js} +3 -3
  25. package/dist/assets/{ToolPartDiffPreview-B29vAjqI.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-B1Jii7gu.js → VirtualizedFileDiff-CFToyUp4.js} +4 -4
  27. package/dist/assets/{collapsible-B6bVtxgp.js → collapsible-BXBoS1M4.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-B6RnDAuP.js → computeVirtualFileMetrics-BpbB2xiE.js} +2 -2
  29. package/dist/assets/{contextFileOpenGuard-DIpJPFxL.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
  30. package/dist/assets/{gitStatusPredicates-lhIrHyDw.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
  31. package/dist/assets/{index-BUxQG4Eq.js → index-CVZfC79h.js} +1 -1
  32. package/dist/assets/{index-BXgR2dKM.css → index-Ci9OMaKW.css} +1 -1
  33. package/dist/assets/{index-BOtRfXre.js → index-DyeT2dc_.js} +7 -7
  34. package/dist/assets/{isDiffPlainText-r5sF6_KV.js → isDiffPlainText-dBQiDlRy.js} +1 -1
  35. package/dist/assets/{isFilePlainText-B4e2b2Bv.js → isFilePlainText-DWMzO-Ms.js} +1 -1
  36. package/dist/assets/{main-DSfSGm2f.js → main-DkXvFwTR.js} +3 -3
  37. package/dist/assets/{main-DMYsDuaV.js → main-DukaBOy3.js} +2 -2
  38. package/dist/assets/{markdownCore-0ygaCYcc.js → markdownCore-BH61OrJ2.js} +1 -1
  39. package/dist/assets/{miniChat-DUMRG1q5.js → miniChat-B1uBoxSn.js} +2 -2
  40. package/dist/assets/{mobile-DUcoCNyj.js → mobile-DV_RYy3x.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-BNmJJQdl.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-CPm7KWaN.js → runtimeSurface-CxbVCK7k.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-CDmJGQlK.js → useAppFontEffects-HCEusnq7.js} +86 -86
  46. package/dist/assets/{useFilesViewSearch-DDMI---4.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-i8sRCEtS.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-BT_toOh9.js → useSwitcherItems-DLA7kskG.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-D09wcguI.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
  50. package/dist/assets/{web-components-Cb0vnR_a.js → web-components-C7g3Hi85.js} +3 -3
  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-Cm4cKNof.js +0 -2
  68. package/dist/assets/renderMobileApp-DnhfWGEW.js +0 -11
  69. package/dist/assets/runtimeEndpointReset-B0SWG9Uo.js +0 -53
package/README.md CHANGED
@@ -1,81 +1,86 @@
1
1
  # @pi-chamber/web
2
2
 
3
- PiChamber's web server and browser UI for the Pi coding-agent runtime.
3
+ PiChamber server and browser UI for the [Pi coding agent](https://pi.dev). It serves the browser workspace and authenticated Pi routes, and owns its per-profile Pi session daemon.
4
4
 
5
- ## Run
5
+ ## Requirements
6
6
 
7
- ```bash
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. The desktop app runs its bundled Node in-process. The mobile app connects to an existing server.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ bun add -g @pi-chamber/web
15
+ ```
16
+
17
+ Other package managers:
18
+
19
+ ```sh
20
+ npm install -g @pi-chamber/web
21
+ pnpm add -g @pi-chamber/web
22
+ yarn global add @pi-chamber/web
23
+ ```
24
+
25
+ Run without installing:
26
+
27
+ ```sh
28
+ bunx @pi-chamber/web serve
29
+ npx @pi-chamber/web serve
30
+ pnpm dlx @pi-chamber/web serve
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ In an interactive terminal:
36
+
37
+ ```sh
8
38
  pichamber serve
9
39
  ```
10
40
 
11
- In an interactive terminal, `pichamber serve` guides you through access, port,
12
- authentication, browser UI versus API-only content, and background versus
13
- foreground process mode. It shows a review before starting. The server starts
14
- warming the local Pi session daemon as soon as HTTP is listening, serves the
15
- browser UI, and exposes authenticated Pi routes under `/api/pi/*`. HTTP
16
- readiness does not wait for Pi provider/model initialization; early Pi requests
17
- share the supervisor's in-flight startup.
41
+ The command walks through access, port, authentication, browser UI versus API-only, and background versus foreground mode, then shows a review before starting. Open the printed URL. Bare `pichamber` starts with default settings without the wizard.
18
42
 
19
43
  For scripts and non-interactive shells, pass the setup flags explicitly:
20
44
 
21
- ```bash
22
- pichamber serve --port 3000 --ui-password <password>
23
- pichamber serve --port 8080 --lan --ui-password <password>
24
- pichamber serve --port 3000 --api-only --ui-password <password>
25
- pichamber connect-url --port 3000 --qr
26
- pichamber stop --port 3000
45
+ ```sh
46
+ pichamber serve --port 3000 --ui-password "choose-a-strong-password"
47
+ pichamber serve --port 3000 --lan --ui-password "choose-a-strong-password"
48
+ pichamber serve --port 3000 --api-only --ui-password "choose-a-strong-password"
27
49
  ```
28
50
 
29
- `--quiet` and `--json` never prompt. Use `pichamber stop --force` when a broad
30
- stop should skip confirmation, and `pichamber logs --no-follow` for a one-time
31
- log tail. Use `pichamber update --yes` to update without the interactive review.
32
-
33
- Use `--api-only` for a host intended to be paired from a PiChamber desktop or mobile client. LAN-bound servers require a UI password unless the explicit unsafe-development override is set.
34
-
35
- See the [CLI guide](../docs/content/docs/cli.mdx) for guided startup, updates,
36
- tunnels, logs, pairing, and machine-readable output.
37
-
38
- ## Runtime contract
39
-
40
- - Pi session state and actions are served only through `/api/pi/*`. Session detail responses carry a bounded transcript tail; older history is available from `GET /api/pi/sessions/:sessionId/messages` with the opaque before-cursor returned by the previous page.
41
- - `POST /api/pi/attachments` accepts raw `application/octet-stream` bodies with bounded `X-PiChamber-Filename` and `X-PiChamber-Mime` metadata. It returns opaque attachment metadata plus `expiresAt`; filesystem paths remain private. The legacy base64 JSON body remains available for persisted clients. `DELETE /api/pi/attachments/:id` removes an unused upload. Prompt routes accept at most 20 attachment IDs and retire accepted uploads from the active 32-upload map while retaining their files until the one-hour expiry.
42
- - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, `/api/pi/update-install`, and `/api/pi/update-install/:jobId`. Starting an update returns a persisted job ID; clients poll that job on the originating server across its restart, and concurrent requests reuse the active job. Polling stops if the client switches servers. Lost authentication leaves the outcome unknown until the client reauthenticates. For older servers without update jobs, fallback version polling reports version-check errors instead of treating them as successful updates. Status reads fail abandoned jobs after a bounded startup grace period or when the recorded worker exits. The settings route merges portable preferences from `settings.json` with host and device values from `runtime-state.json`; writes split fields through explicit allowlists. Electron and server update-channel subscriptions are separate host-local fields, each accepts only `stable` or `rc`, and each defaults to `stable`. The server RC channel compares `latest` and `rc` and selects the higher version; update jobs pin the selected version so restart or a moving dist-tag cannot change their target. Pi-owned resource, trust, and provider-catalog changes are saved without interrupting active sessions and report deferred runtime activation when an idle edge is required. A flat legacy file migrates on first access. A scoped portable file never contributes paths, project registrations, device values, or secrets. Removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
43
- - Final-only speech-to-text uses authenticated `/api/stt/*` routes and `/api/stt/ws`. Local model inference runs in a forked worker, while remote provider credentials remain in server configuration.
44
- - Browser and paired clients authenticate with UI sessions or scoped client credentials.
45
- - `connect-url` creates a one-time pairing link; credentials are not written to URLs or logs.
46
- - The server owns its per-profile Pi daemon lifecycle (installed web, development web, and desktop use separate namespaces) and stops only its own daemon during shutdown.
47
-
48
- ## SDK updates
49
-
50
- This release pins Pi SDK `0.85.1`, including an updated bundled OpenCode model
51
- catalog. Existing Pi sessions, credentials, settings, and custom models stay in
52
- place; no manual migration or cache deletion is needed. Custom model additions
53
- and overrides still apply to the updated catalog. If a saved default points to a
54
- removed model, select an available replacement; the upgrade does not rewrite
55
- your saved defaults or chat history.
56
-
57
- The normal update command restarts managed background instances. Linux servers
58
- configured by `pichamber startup enable` run updates in a transient systemd unit,
59
- so terminal and in-app updates survive the server restart and report status after
60
- clients reconnect. Foreground instances must be stopped and started manually.
61
- Desktop users must relaunch the updated app. Hosted and mobile clients use their
62
- connected server's SDK, so updating only the client does not update its model
63
- catalog. When a trusted hosted update response does not provide release notes,
64
- the server reads the selected version's GitHub release body, then falls back to
65
- `CHANGELOG.md` from that version tag. This keeps stable and RC notes tied to the
66
- package version chosen from the npm registry.
67
-
68
- ## Development
69
-
70
- ```bash
71
- bun run --cwd packages/web build
72
- bun run --cwd packages/web type-check
73
- bun run --cwd packages/web test
74
- ```
51
+ ## Commands
52
+
53
+ Run `pichamber --help` for the current flags.
54
+
55
+ | Command | What it does |
56
+ | --- | --- |
57
+ | `serve` | Start the server (guided setup in interactive terminals, with a review before starting) |
58
+ | `status` | Show running instances |
59
+ | `logs` | Tail logs (`--no-follow` for a one-time tail) |
60
+ | `stop` / `restart` | Stop or restart instances (broad stops confirm when more than one is affected; `--force` skips) |
61
+ | `startup` | Run at login or boot (`enable` is guided; `status` / `disable` to inspect or remove) |
62
+ | `tunnel` | Expose the server via Cloudflare Tunnel (`start` is guided; profiles cover repeatable runs) |
63
+ | `connect-url` | Create a one-time pairing link for another client (`--qr` in interactive terminals; starts the server if needed) |
64
+ | `update` | Install updates (reviews before changing anything; `--yes` skips confirmation, `--channel stable\|rc` overrides once) |
65
+ | `version` | Print the installed version |
66
+
67
+ ## Scripts and automation
68
+
69
+ `--quiet` and `--json` never prompt, and non-interactive shells never prompt either. Supply required values as flags. `--json` emits JSON only; `--quiet` keeps one concise result line.
70
+
71
+ ## Security
72
+
73
+ Servers reachable beyond this machine require a UI password. Pass `--ui-password` (omit the value to generate one) or set `PICHAMBER_UI_PASSWORD`. Prefer `--lan` only on a trusted network.
74
+
75
+ ## Docs
76
+
77
+ Full guides live in the PiChamber repository:
78
+
79
+ - [Install](https://github.com/RyderAsKing/PiChamber/blob/main/packages/docs/content/docs/install.mdx)
80
+ - [Quick start](https://github.com/RyderAsKing/PiChamber/blob/main/packages/docs/content/docs/quickstart.mdx)
81
+ - [CLI guide](https://github.com/RyderAsKing/PiChamber/blob/main/packages/docs/content/docs/cli.mdx)
82
+ - [Releases](https://github.com/RyderAsKing/PiChamber/releases/latest)
75
83
 
76
- Build flags:
84
+ ## License
77
85
 
78
- - `VITE_REACT_COMPILER=1` re-enables the `babel-plugin-react-compiler` pass for
79
- release builds. It is opt-in because the pass costs ~25s of the ~52s
80
- production build; the default build ships without compiler memoization.
81
- - `VITE_ENABLE_REACT_SCAN=1` injects the react-scan dev script into the page.
86
+ MIT. See [LICENSE](https://github.com/RyderAsKing/PiChamber/blob/main/LICENSE).
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
+ });