@openchamber/web 1.22.1 → 1.23.0

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 (205) hide show
  1. package/bin/cli.js +11 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-DbcnxAfY.js} +1 -1
  6. package/dist/assets/DiffView-Dp1tomqK.js +4 -0
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-DE2sKIYv.js} +1 -1
  8. package/dist/assets/FilesView-C_of2nIT.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-CKgUkb5Z.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-Bce2ettZ.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BZVWM2zw.js} +1 -1
  12. package/dist/assets/MarkdownImageGallery-DdROVz29.js +1 -0
  13. package/dist/assets/MarkdownRendererImpl-CenrzmMN.js +12 -0
  14. package/dist/assets/OnboardingScreen-DyqYG_NP.js +1 -0
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CR3RVO5I.js} +1 -1
  16. package/dist/assets/PierreDiffViewer-KihzO94X.js +161 -0
  17. package/dist/assets/PlanView-jcQAfr2A.js +5 -0
  18. package/dist/assets/SettingsView-Buvom5A2.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-CV_hzB5v.js} +1 -1
  20. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  21. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-llKecK_Z.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-ZDMTdCGn.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-ClvqQ4j0.js} +1 -1
  24. package/dist/assets/WalkthroughView-BgpSnSlU.js +4 -0
  25. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-Nm5_wabb.js} +2 -2
  26. package/dist/assets/contextPanelEmbeddedChat-CirXEPJq.js +1 -0
  27. package/dist/assets/de-DTQDjaiv.js +10 -0
  28. package/dist/assets/es-SOCFd_r-.js +16 -0
  29. package/dist/assets/fr-CP6jqIzw.js +14 -0
  30. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  31. package/dist/assets/index-B68h5S5B.css +1 -0
  32. package/dist/assets/index-CRf2xk51.js +39 -0
  33. package/dist/assets/{index-DLiD86ge.js → index-Du9sZhDb.js} +1 -1
  34. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-EQERIius.js} +1 -1
  35. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-BCoVpkQy.js} +1 -1
  36. package/dist/assets/ja-BKfafwsD.js +16 -0
  37. package/dist/assets/ko-BA5xgCYp.js +16 -0
  38. package/dist/assets/main-BNiPEont.js +930 -0
  39. package/dist/assets/{main-DCB4JgVe.js → main-DPf32fO6.js} +2 -2
  40. package/dist/assets/markdownCore-CQ7CAuuV.js +5 -0
  41. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CHqVTsgj.js} +2 -2
  42. package/dist/assets/{mobile-DZV_sfX7.js → mobile-BQmgHA57.js} +2 -2
  43. package/dist/assets/patchFileDiff-C4X_trug.js +13 -0
  44. package/dist/assets/pl-B215pG1Y.js +16 -0
  45. package/dist/assets/pt-BR-Bo2pnlEa.js +16 -0
  46. package/dist/assets/renderElectronMiniChatApp-BUcHPOXW.js +2 -0
  47. package/dist/assets/renderMobileApp-BvTmuRE-.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-C8GAA2kS.js +17 -0
  49. package/dist/assets/scheduledTasksApi-BAScWwt3.js +1 -0
  50. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-BTObuQCR.js} +1 -1
  51. package/dist/assets/surface-BvRzS58U.js +1 -0
  52. package/dist/assets/tr-CUaxHc8X.js +7 -0
  53. package/dist/assets/uk-YTJgyqAZ.js +16 -0
  54. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-theH_IJL.js} +143 -137
  55. package/dist/assets/useGitComparison-B94I6kOI.js +1 -0
  56. package/dist/assets/useInlineCommentController-Bs3PgeA8.js +2 -0
  57. package/dist/assets/useRootScrollLock-hSYwnxZs.js +1 -0
  58. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-DdV8vhHn.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-Cxgr01md.js} +2 -2
  60. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  61. package/dist/assets/vendor-zod-BPAANqvH.js +39 -0
  62. package/dist/assets/{web-components-B6QgbmTo.js → web-components-CaS0ksnZ.js} +1 -1
  63. package/dist/assets/zh-CN-CZ2BxZS6.js +16 -0
  64. package/dist/assets/zh-TW-BsUrPdXz.js +16 -0
  65. package/dist/index.html +5 -43
  66. package/dist/mini-chat.html +4 -4
  67. package/dist/mobile.html +4 -4
  68. package/package.json +3 -4
  69. package/server/index.d.ts +15 -0
  70. package/server/index.js +52 -10
  71. package/server/lib/changelog/update-notes.js +82 -0
  72. package/server/lib/changelog/update-notes.test.js +59 -0
  73. package/server/lib/data-dir-migration.js +40 -0
  74. package/server/lib/data-dir-migration.test.js +59 -0
  75. package/server/lib/event-stream/runtime.test.js +12 -12
  76. package/server/lib/fs/DOCUMENTATION.md +5 -0
  77. package/server/lib/fs/routes.js +63 -21
  78. package/server/lib/fs/routes.test.js +187 -1
  79. package/server/lib/git/DOCUMENTATION.md +29 -5
  80. package/server/lib/git/routes.js +24 -4
  81. package/server/lib/git/service.js +194 -198
  82. package/server/lib/git/service.test.js +440 -25
  83. package/server/lib/inherited-env.js +16 -9
  84. package/server/lib/inherited-env.test.js +8 -9
  85. package/server/lib/message-queue/DOCUMENTATION.md +20 -7
  86. package/server/lib/message-queue/runtime.js +59 -7
  87. package/server/lib/message-queue/runtime.test.js +59 -3
  88. package/server/lib/network-defaults.js +23 -0
  89. package/server/lib/network-defaults.test.js +52 -0
  90. package/server/lib/opencode/DOCUMENTATION.md +25 -5
  91. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  92. package/server/lib/opencode/config-paths.test.js +116 -0
  93. package/server/lib/opencode/feature-routes-runtime.js +4 -0
  94. package/server/lib/opencode/input-history-scope.js +14 -0
  95. package/server/lib/opencode/openchamber-routes.js +64 -4
  96. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  97. package/server/lib/opencode/plugins.js +2 -2
  98. package/server/lib/opencode/providers.js +44 -2
  99. package/server/lib/opencode/providers.test.js +131 -4
  100. package/server/lib/opencode/routes.js +9 -7
  101. package/server/lib/opencode/server-startup-runtime.js +1 -1
  102. package/server/lib/opencode/settings-files.js +214 -0
  103. package/server/lib/opencode/settings-helpers.js +113 -41
  104. package/server/lib/opencode/settings-helpers.test.js +342 -0
  105. package/server/lib/opencode/settings-registry.json +747 -0
  106. package/server/lib/opencode/settings-runtime.js +139 -18
  107. package/server/lib/opencode/settings-runtime.test.js +163 -5
  108. package/server/lib/opencode/shared.js +4 -1
  109. package/server/lib/opencode/skill-routes.js +2 -1
  110. package/server/lib/opencode/snippets.js +1 -2
  111. package/server/lib/package-manager.js +3 -28
  112. package/server/lib/project-context/DOCUMENTATION.md +25 -1
  113. package/server/lib/project-context/routes.http.test.js +18 -0
  114. package/server/lib/project-context/routes.js +15 -0
  115. package/server/lib/project-context/runtime.js +248 -23
  116. package/server/lib/project-context/runtime.test.js +106 -3
  117. package/server/lib/projects/DOCUMENTATION.md +76 -0
  118. package/server/lib/projects/project-config.js +142 -9
  119. package/server/lib/projects/project-id.js +17 -0
  120. package/server/lib/projects/project-setup.js +409 -0
  121. package/server/lib/projects/project-setup.test.js +557 -0
  122. package/server/lib/projects/routes.js +59 -0
  123. package/server/lib/quota/DOCUMENTATION.md +38 -1
  124. package/server/lib/quota/index.js +1 -0
  125. package/server/lib/quota/providers/cline-pass.js +125 -0
  126. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  127. package/server/lib/quota/providers/hyper.js +118 -0
  128. package/server/lib/quota/providers/hyper.test.js +126 -0
  129. package/server/lib/quota/providers/index.js +15 -0
  130. package/server/lib/quota/providers/neuralwatt.js +3 -6
  131. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  132. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  133. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  134. package/server/lib/quota/providers/opencode-go.js +1 -1
  135. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  136. package/server/lib/quota/providers/openrouter.js +119 -24
  137. package/server/lib/quota/providers/openrouter.test.js +330 -0
  138. package/server/lib/quota/utils/auth.js +1 -1
  139. package/server/lib/relay/DOCUMENTATION.md +55 -0
  140. package/server/lib/relay/cross-compat.test.js +26 -0
  141. package/server/lib/relay/downstream-scheduler.js +154 -0
  142. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  143. package/server/lib/relay/e2ee.js +10 -8
  144. package/server/lib/relay/flow-control.test.js +177 -0
  145. package/server/lib/relay/host-client.js +37 -8
  146. package/server/lib/relay/host-client.test.js +9 -1
  147. package/server/lib/relay/tunnel-codec.js +9 -0
  148. package/server/lib/relay/tunnel-host.js +66 -17
  149. package/server/lib/session-assist/runtime.js +6 -10
  150. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  151. package/server/lib/session-goal/runtime.js +80 -20
  152. package/server/lib/session-goal/runtime.test.js +426 -0
  153. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  154. package/server/lib/skills-catalog/install.js +3 -2
  155. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  156. package/server/lib/small-model/call.js +9 -4
  157. package/server/lib/small-model/call.test.js +29 -0
  158. package/server/lib/small-model/index.js +5 -10
  159. package/server/lib/small-model/runtime-providers.js +15 -7
  160. package/server/lib/small-model/runtime-providers.test.js +7 -1
  161. package/server/lib/terminal/DOCUMENTATION.md +14 -10
  162. package/server/lib/terminal/runtime.js +160 -24
  163. package/server/lib/terminal/runtime.test.js +571 -37
  164. package/server/lib/terminal/shells.js +17 -0
  165. package/server/lib/terminal/shells.test.js +32 -1
  166. package/server/lib/walkthrough/DOCUMENTATION.md +33 -14
  167. package/server/lib/walkthrough/model-settings.js +8 -12
  168. package/server/lib/walkthrough/prompt.js +3 -1
  169. package/server/lib/walkthrough/routes.test.js +26 -5
  170. package/server/lib/walkthrough/sources.js +23 -2
  171. package/dist/assets/DiffView-CNnDxRmO.js +0 -4
  172. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  173. package/dist/assets/MarkdownImageGallery-DffjmciG.js +0 -1
  174. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  175. package/dist/assets/OnboardingScreen-CTZe6HZn.js +0 -1
  176. package/dist/assets/PierreDiffViewer-BvwtCxW4.js +0 -157
  177. package/dist/assets/PlanView-C1qvAm7m.js +0 -5
  178. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  179. package/dist/assets/WalkthroughView-D-HFgdmM.js +0 -4
  180. package/dist/assets/contextPanelEmbeddedChat-CV-DwAiX.js +0 -1
  181. package/dist/assets/de-Cv_4FoXm.js +0 -10
  182. package/dist/assets/es-BIWNEbnS.js +0 -16
  183. package/dist/assets/fr-SD3OfMHJ.js +0 -14
  184. package/dist/assets/index-CHUT_bDS.css +0 -1
  185. package/dist/assets/index-DDInLQDd.js +0 -40
  186. package/dist/assets/ja-D7I9HofF.js +0 -16
  187. package/dist/assets/ko-BsVJM_PQ.js +0 -16
  188. package/dist/assets/main-De8Z5w49.js +0 -928
  189. package/dist/assets/markdownCore-BoQVG5-a.js +0 -3
  190. package/dist/assets/patchFileDiff-Chmiz6hq.js +0 -10
  191. package/dist/assets/pl-XR9Bs8Be.js +0 -16
  192. package/dist/assets/pt-BR-Due4be8g.js +0 -16
  193. package/dist/assets/renderElectronMiniChatApp-8tXADjfl.js +0 -2
  194. package/dist/assets/renderMobileApp-Cji7Hma5.js +0 -25
  195. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  196. package/dist/assets/scheduledTasksApi-9e-UX6im.js +0 -1
  197. package/dist/assets/tr-DBJcAv4y.js +0 -7
  198. package/dist/assets/uk-COYh2BaN.js +0 -16
  199. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  200. package/dist/assets/useRootScrollLock-KzOUytpn.js +0 -1
  201. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  202. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  203. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
  204. package/dist/assets/zh-CN-Cjk6lzhc.js +0 -16
  205. package/dist/assets/zh-TW-Dk0dOg03.js +0 -16
@@ -2,14 +2,14 @@
2
2
 
3
3
  ## Ownership
4
4
 
5
- `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
5
+ `runtime.js` owns terminal identity, PTY processes, launch mode, session purpose, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families, resolves the persisted shell ID, and builds the per-shell argv for interactive versus command launches. Clients own tab arrangement. Interactive terminals use stable IDs; project actions keep a stable UI tab and allocate a fresh terminal ID for each command execution. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
6
6
 
7
7
  ## Protocol
8
8
 
9
9
  `/api/terminal/ws` is the only terminal data transport. It uses v3 binary JSON control frames and is opened through `openRuntimeWebSocket`, preserving direct, Electron proxy, URL-token authentication, and private-relay routing.
10
10
 
11
11
  - `attach` registers a connection for one terminal. One socket may attach to many terminals.
12
- - Every attach and reconnect begins with an authoritative `snapshot` containing bounded history and the current sequence.
12
+ - Every attach and reconnect begins with an authoritative `snapshot` containing bounded history, the current sequence, and the PTY `cols`/`rows` the history was drawn for. The client replays the history at that size before fitting its viewport; replaying shell output at another width leaves stray fragments that the shell's own SIGWINCH redraw never clears.
13
13
  - A current socket that closes or errors before its initial `open` invalidates its URL-scoped auth token before retrying, so retries mint a fresh token instead of backing off against a rejected upgrade. Hidden or offline clients wait 60 seconds and wake promptly on visibility/online recovery.
14
14
  - `output`, `exit`, and `restarted` carry monotonically increasing per-terminal sequences. Output carries raw live bytes plus replay-safe bytes with terminal query exchanges removed.
15
15
  - Attach registers before capturing the snapshot, buffers concurrent events, drops events represented by the snapshot sequence, then enters live delivery.
@@ -19,21 +19,25 @@
19
19
 
20
20
  HTTP remains the authenticated command plane for create, resize, appearance updates, restart, close, and force-kill. There is no SSE output or HTTP input compatibility path.
21
21
 
22
- `GET /api/terminal/sessions` enumerates live sessions (optionally filtered by resolved `cwd`) so clients can adopt terminals their local tab projection does not know about — another device, a new browser tab, or cleared storage. `POST /api/terminal/touch` refreshes `lastActivity` for the listed session ids; open clients call it periodically so background tabs, which hold no WebSocket attachment, are not idle-reaped while a client still shows them.
22
+ `GET /api/terminal/sessions` enumerates live sessions (optionally filtered by resolved `cwd`) so clients can adopt terminals their local tab projection does not know about — another device, a new browser tab, or cleared storage. Listings include the effective launch mode and the normalized purpose, but never the command text. `POST /api/terminal/touch` refreshes `lastActivity` for the listed session ids; open clients call it periodically so background tabs, which hold no WebSocket attachment, are not idle-reaped while a client still shows them.
23
23
 
24
24
  ## PTY Lifecycle
25
25
 
26
26
  - IDs are client-provided or generated with `randomUUID()`.
27
- - Concurrent creates for one ID are single-flight only when working directory and shell preference match. Existing IDs cannot be reused for another working directory.
27
+ - Create defaults to interactive mode. Command mode requires a non-empty trimmed command no longer than the terminal input limit and launches the shell so the PTY exits when that command exits. Each session also carries a normalized purpose. Omitted purpose means `{ type: 'terminal' }`. Project actions use `{ type: 'project-action', actionId, executionId }`, and the server validates both IDs as non-empty bounded strings. Create responses and attach snapshots echo the effective mode and purpose.
28
+ - Concurrent creates for one ID are single-flight only when working directory, shell preference, login mode, launch mode, and session purpose match. Command-mode creates must also match the command text, unless the purpose is a project action that is already running for the same resolved `(cwd, actionId)` pair. In that case the runtime returns the existing session and its existing execution identity, even when another client requested a different session ID. Existing IDs cannot be reused for another working directory or another purpose.
28
29
  - Dimensions are bounded to 1-1000 columns and 1-500 rows; input is capped at 64 KiB.
29
30
  - A client may create before its renderer has mounted. It derives an initial size from the container and font metrics (falling back to 80x24 when unavailable), then sends a resize once Ghostty reports its final dimensions. This allows shell startup and renderer initialization to overlap.
30
- - PTY children explicitly clear `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup.
31
- - PTY children also strip AppImage `ARGV0` (and other host-private shell vars such as `ELECTRON_RUN_AS_NODE`, `BASH_ENV`, `ENV`, `BASH_XTRACEFD`). An exported `ARGV0` makes zsh rewrite argv[0] for every external command, which breaks Python venv detection and other argv[0]/$0 consumers while leaving `/proc/self/exe` correct. On Linux, PTY spawn is wrapped with `env -u ARGV0` because `bun-pty` merges the native OS environ and would otherwise reintroduce `ARGV0` after a JS-only delete.
32
- - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Preference changes affect new sessions and explicit restarts, not running PTYs.
33
- - PTY data and exit callbacks enter one FIFO queue. Stale callbacks from replaced processes are ignored.
31
+ - PTY children never inherit `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup, and an inherited value (even empty) makes Node CLIs such as opencode print `Failed to parse IPC channel number` on exit.
32
+ - PTY children also strip AppImage `ARGV0` (and other host-private shell vars such as `ELECTRON_RUN_AS_NODE`, `BASH_ENV`, `ENV`, `BASH_XTRACEFD`). An exported `ARGV0` makes zsh rewrite argv[0] for every external command, which breaks Python venv detection and other argv[0]/$0 consumers while leaving `/proc/self/exe` correct. On POSIX, PTY spawn is wrapped with `env -u ARGV0 -u NODE_CHANNEL_FD` (`resolvePosixPtyLaunch`) because `bun-pty` merges the native OS environ and would otherwise reintroduce both after a JS-only delete.
33
+ - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Interactive shells still launch as before. Command-mode launches reuse the same environment and login support, but switch argv by shell family: POSIX and Fish use interactive `-c`, Nushell uses `-c`, PowerShell uses `-Command`, and cmd uses `/d /s /c`. Preference changes affect new sessions and explicit restarts, not running PTYs.
34
+ - PTY data and exit callbacks enter one FIFO queue. The runtime wires those listeners in the same synchronous turn that receives the PTY object. `node-pty` and `bun-pty` both expose the PTY before dispatching registered callbacks. If a backend emitted exit before listener registration, this layer could not recover it, so the wiring stays adjacent to PTY creation.
34
35
  - Scrollback is retained on the server and capped at 512 KiB with UTF-8-safe trimming. Device-status, device-attribute, cursor-position reply, and color-query exchanges are removed from replay history with incomplete control sequences carried across PTY chunks; live output remains byte-for-byte unchanged.
35
- - Exited sessions remain attachable until explicit close or idle cleanup.
36
- - Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID.
36
+ - Exited sessions remain attachable until explicit close, idle cleanup, or a successful replacement of the same project action. Creating a replacement retires only exited records for the same resolved directory and action, after the new PTY starts. Failed creation preserves the old record and output. These replaced records do not exhaust the terminal capacity limit.
37
+ - Deduplicated create responses may describe another client's execution. Cancellation cleanup closes only the terminal ID allocated for the cancelled request; it never closes an adopted peer execution.
38
+ - Create and restart validate the working directory with a real `stat` and answer HTTP 400 `Invalid working directory` when it is not a directory. When the path does not exist at all (`ENOENT`/`ENOTDIR`, a worktree deleted outside OpenChamber) the body also carries `code: "TERMINAL_CWD_MISSING"`. The client shows the failure without moving the session. The runtime never substitutes a parent directory on its own.
39
+ - Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID. Command-mode sessions reject restart with HTTP 400 instead of silently turning into interactive shells with stale action metadata.
40
+ - A delete that arrives while create is still pending leaves a cancellation tombstone. When the PTY arrives, the runtime terminates it immediately, never inserts the session into the live map, and returns a create error while the delete still succeeds.
37
41
  - Close uses SIGTERM with bounded SIGKILL escalation. Force-kill, idle cleanup, and runtime shutdown terminate process groups immediately where supported. Removal explicitly sends a fatal scoped closure and evicts client projections even when a PTY backend fails to emit `onExit`; attached terminals are not considered idle.
38
42
 
39
43
  ## Security And Relay
@@ -9,15 +9,77 @@ import {
9
9
  } from './terminal-ws-protocol.js';
10
10
  import { sanitizeTerminalHistoryChunk } from './history.js';
11
11
  import { consumeTerminalThemeQueries, terminalThemeModeReport } from './theme-response.js';
12
- import { createTerminalShellResolver, getTerminalShellLoginArgs, normalizeTerminalShell } from './shells.js';
13
- import { stripAppImageArgv0Leak, resolveLinuxPtyLaunch } from '../inherited-env.js';
12
+ import { buildTerminalShellLaunch, createTerminalShellResolver, normalizeTerminalShell } from './shells.js';
13
+ import { stripAppImageArgv0Leak, resolvePosixPtyLaunch } from '../inherited-env.js';
14
14
 
15
15
  const MAX_SESSIONS = 20;
16
16
  const MAX_HISTORY_BYTES = 512 * 1024;
17
17
  const MAX_INPUT_CHARS = 65_536;
18
18
  const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
19
19
  const TERMINATION_GRACE_MS = 1000;
20
+ const INTERACTIVE_TERMINAL_MODE = 'interactive';
21
+ const COMMAND_TERMINAL_MODE = 'command';
22
+ // Error code the create/restart routes attach when the requested cwd no longer
23
+ // exists. Mirrored by `TERMINAL_CWD_MISSING_CODE` in packages/ui/src/lib/terminalApi.ts.
24
+ const TERMINAL_CWD_MISSING_CODE = 'TERMINAL_CWD_MISSING';
25
+ const TERMINAL_PURPOSE = Object.freeze({ type: 'terminal' });
26
+ const MAX_PURPOSE_ID_CHARS = 128;
27
+ const OBJECT_TAG = '[object Object]';
20
28
  const validateSize = (value, max) => Number.isInteger(value) && value >= 1 && value <= max;
29
+ const isString = (value) => String(value) === value;
30
+ const isObjectRecord = (value) => value != null && !Array.isArray(value) && Object.prototype.toString.call(value) === OBJECT_TAG;
31
+ const normalizeCreateMode = ({ mode, command }) => {
32
+ const normalizedMode = mode == null ? INTERACTIVE_TERMINAL_MODE : mode;
33
+ if (normalizedMode !== INTERACTIVE_TERMINAL_MODE && normalizedMode !== COMMAND_TERMINAL_MODE) throw new Error('Invalid terminal mode');
34
+ if (normalizedMode === INTERACTIVE_TERMINAL_MODE) {
35
+ if (command != null) throw new Error('Interactive terminal create does not accept a command');
36
+ return { mode: INTERACTIVE_TERMINAL_MODE, command: null };
37
+ }
38
+ if (!isString(command) || !command.trim()) throw new Error('Terminal command is required');
39
+ const trimmedCommand = command.trim();
40
+ if (trimmedCommand.length > MAX_INPUT_CHARS) throw new Error('Terminal command exceeds the input limit');
41
+ return { mode: COMMAND_TERMINAL_MODE, command: trimmedCommand };
42
+ };
43
+ const normalizePurposeId = (value, errorMessage) => {
44
+ if (!isString(value) || !value.trim()) throw new Error(errorMessage);
45
+ const normalized = value.trim();
46
+ if (normalized.length > MAX_PURPOSE_ID_CHARS) throw new Error(errorMessage);
47
+ return normalized;
48
+ };
49
+ const normalizeTerminalPurpose = (value) => {
50
+ if (value == null) return TERMINAL_PURPOSE;
51
+ if (!isObjectRecord(value)) throw new Error('Invalid terminal purpose');
52
+ if (value.type === 'terminal') return TERMINAL_PURPOSE;
53
+ if (value.type !== 'project-action') throw new Error('Invalid terminal purpose');
54
+ return {
55
+ type: 'project-action',
56
+ actionId: normalizePurposeId(value.actionId, 'Terminal project action id is required'),
57
+ executionId: normalizePurposeId(value.executionId, 'Terminal execution id is required'),
58
+ };
59
+ };
60
+ const getSessionPurpose = (session) => session.purpose ?? TERMINAL_PURPOSE;
61
+ const isPurposeActionMatch = (left, right) => {
62
+ if (left.type !== right.type) return false;
63
+ return left.type !== 'project-action' || left.actionId === right.actionId;
64
+ };
65
+ const findRunningActionSession = (sessions, resolvedCwd, purpose, path) => {
66
+ if (purpose.type !== 'project-action') return null;
67
+ for (const session of sessions.values()) {
68
+ if (session.status !== 'running') continue;
69
+ if (path.resolve(session.cwd) !== resolvedCwd) continue;
70
+ const sessionPurpose = getSessionPurpose(session);
71
+ if (sessionPurpose.type === 'project-action' && sessionPurpose.actionId === purpose.actionId) return session;
72
+ }
73
+ return null;
74
+ };
75
+ const findPendingActionCreate = (pendingSessionCreates, resolvedCwd, purpose) => {
76
+ if (purpose.type !== 'project-action') return null;
77
+ for (const pending of pendingSessionCreates.values()) {
78
+ if (pending.cancelled || pending.cwd !== resolvedCwd) continue;
79
+ if (pending.purpose?.type === 'project-action' && pending.purpose.actionId === purpose.actionId) return pending;
80
+ }
81
+ return null;
82
+ };
21
83
  const trimHistory = (history) => {
22
84
  const bytes = Buffer.from(history);
23
85
  if (bytes.byteLength <= MAX_HISTORY_BYTES) return history;
@@ -54,25 +116,26 @@ export function createTerminalRuntime({
54
116
  return ptyProviderPromise;
55
117
  };
56
118
 
57
- const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell }) => {
119
+ const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell, mode, command }) => {
58
120
  const provider = await getPtyProvider();
59
121
  const resolvedShell = await shellResolver.resolve(shell);
60
122
  let lastError = null;
61
123
  for (const executable of resolvedShell.executables) {
62
- const args = loginShell ? getTerminalShellLoginArgs(executable) : [];
63
- if (!args) throw new Error(`Terminal shell "${resolvedShell.id}" does not support login mode`);
64
124
  try {
65
125
  const env = { ...process.env, PATH: buildAugmentedPath(), TERM: 'xterm-256color', COLORTERM: 'truecolor', COLORFGBG: themeMode === 'light' ? '0;15' : '15;0' };
66
- // The daemon's IPC fd is closed inside the PTY. An explicit override is
67
- // required because bun-pty also inherits Bun's native process environment.
68
- env.NODE_CHANNEL_FD = '';
126
+ // The daemon's IPC fd is closed inside the PTY; an inherited NODE_CHANNEL_FD
127
+ // (even an empty one) makes Node CLIs warn about an unparsable IPC channel.
128
+ delete env.NODE_CHANNEL_FD;
69
129
  delete env.BASH_XTRACEFD; delete env.BASH_ENV; delete env.ENV; delete env.ELECTRON_RUN_AS_NODE;
70
130
  // AppImage exports ARGV0; zsh would otherwise rewrite argv[0] for every command (#2588).
71
- // bun-pty also merges the native OS environ, so wrap with `env -u ARGV0` on Linux.
72
131
  stripAppImageArgv0Leak(env);
73
- const launch = resolveLinuxPtyLaunch(executable, args);
74
- const options = { name: 'xterm-256color', cwd, cols, rows, env, ...(process.platform === 'win32' ? { useConpty: true } : {}) };
75
- return { process: provider.spawn(launch.executable, launch.args, options), backend: provider.backend, shell: resolvedShell.id, loginShell };
132
+ const shellLaunch = buildTerminalShellLaunch(executable, { mode, command, loginShell });
133
+ // bun-pty merges the native OS environ back in, so the POSIX launch is
134
+ // wrapped with `env -u` for the variables deleted above.
135
+ const launch = resolvePosixPtyLaunch(shellLaunch.executable, shellLaunch.args);
136
+ const options = { name: 'xterm-256color', cwd, cols, rows, env };
137
+ if (process.platform === 'win32') options.useConpty = true;
138
+ return { process: await provider.spawn(launch.executable, launch.args, options), backend: provider.backend, shell: resolvedShell.id, loginShell };
76
139
  } catch (error) { lastError = error; }
77
140
  }
78
141
  throw lastError ?? new Error('No executable shell found');
@@ -122,7 +185,12 @@ export function createTerminalRuntime({
122
185
 
123
186
  const snapshot = (session) => ({
124
187
  t: 'snapshot', v: 3, s: session.id, q: session.sequence, history: session.history,
188
+ // The PTY size the history was drawn for: a client replays history at this
189
+ // size before fitting its own viewport, so shell output wrapped for one
190
+ // width never gets re-laid-out at another.
191
+ cols: session.cols, rows: session.rows,
125
192
  status: session.status, exitCode: session.exitCode, signal: session.signal,
193
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE, purpose: getSessionPurpose(session),
126
194
  runtime, ptyBackend: session.backend,
127
195
  });
128
196
 
@@ -175,11 +243,18 @@ export function createTerminalRuntime({
175
243
  ptyProcess.onExit(({ exitCode, signal }) => { session.eventQueue.push({ type: 'exit', process: ptyProcess, exitCode, signal }); drainEvents(session); });
176
244
  };
177
245
 
246
+ // A working directory that no longer exists (a deleted worktree) is the one
247
+ // rejection the client can recover from by moving the session to its
248
+ // project, so the response names it. Every other rejection stays generic.
249
+ const invalidWorkingDirectory = (code) => Object.assign(new Error('Invalid working directory'), code ? { code } : {});
178
250
  const validateCwd = async (cwd) => {
179
251
  if (typeof cwd !== 'string' || !cwd.trim()) throw new Error('cwd is required');
180
- const stats = await fs.promises.stat(cwd).catch(() => null);
181
- if (!stats?.isDirectory()) throw new Error('Invalid working directory');
252
+ let stats;
253
+ try { stats = await fs.promises.stat(cwd); }
254
+ catch (error) { throw invalidWorkingDirectory(error?.code === 'ENOENT' || error?.code === 'ENOTDIR' ? TERMINAL_CWD_MISSING_CODE : undefined); }
255
+ if (!stats?.isDirectory()) throw invalidWorkingDirectory();
182
256
  };
257
+ const errorBody = (error, fallback) => ({ error: error?.message || fallback, ...(typeof error?.code === 'string' ? { code: error.code } : {}) });
183
258
 
184
259
  const applyAppearance = (session, { themeMode, terminalBackground, terminalForeground }) => {
185
260
  const previous = [session.themeMode, session.terminalBackground, session.terminalForeground];
@@ -192,48 +267,87 @@ export function createTerminalRuntime({
192
267
  }
193
268
  };
194
269
 
195
- const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell }, clear = true) => {
270
+ const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell, mode = INTERACTIVE_TERMINAL_MODE, command = null, purpose = TERMINAL_PURPOSE }, clear = true) => {
196
271
  await validateCwd(cwd);
197
- const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell });
272
+ const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell, mode, command });
198
273
  if (clear) { session.history = ''; session.pendingHistoryControlSequence = ''; session.pendingThemeControlSequence = ''; session.themeModeEnabled = false; }
199
274
  session.cwd = cwd; session.cols = cols; session.rows = rows; session.process = spawned.process;
200
275
  session.backend = spawned.backend; session.shell = spawned.shell; session.loginShell = spawned.loginShell; session.status = 'running'; session.exitCode = null; session.signal = null;
276
+ session.mode = mode; session.command = mode === COMMAND_TERMINAL_MODE ? command : null;
277
+ session.purpose = purpose;
201
278
  session.themeMode = themeMode === 'light' ? 'light' : 'dark'; session.terminalBackground = terminalBackground; session.terminalForeground = terminalForeground;
202
279
  session.lastActivity = Date.now(); session.eventQueue.length = 0;
203
280
  wire(session, spawned.process);
281
+ return spawned.process;
204
282
  };
205
283
 
206
- const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false }) => {
284
+ const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false, mode, command, purpose }) => {
207
285
  if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
208
286
  if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
209
287
  const normalizedShell = normalizeTerminalShell(shell);
210
288
  if (!normalizedShell) throw new Error('Invalid terminal shell');
289
+ const launchMode = normalizeCreateMode({ mode, command });
290
+ const normalizedPurpose = normalizeTerminalPurpose(purpose);
211
291
  const id = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : randomUUID();
212
292
  if (id.length > 128) throw new Error('Invalid terminal session id');
213
293
  const existing = sessions.get(id);
214
294
  const resolvedCwd = path.resolve(cwd);
215
295
  if (existing?.status === 'running') {
216
296
  if (path.resolve(existing.cwd) !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
297
+ if (!isPurposeActionMatch(getSessionPurpose(existing), normalizedPurpose)) throw new Error('Terminal session is already running with a different purpose');
298
+ if (normalizedPurpose.type === 'project-action') { applyAppearance(existing, { themeMode, terminalBackground, terminalForeground }); return existing; }
299
+ if ((existing.mode ?? INTERACTIVE_TERMINAL_MODE) !== launchMode.mode) throw new Error('Terminal session is already running with a different mode');
300
+ if (launchMode.mode === COMMAND_TERMINAL_MODE && existing.command !== launchMode.command) throw new Error('Terminal session is already running with a different command');
217
301
  applyAppearance(existing, { themeMode, terminalBackground, terminalForeground });
218
302
  return existing;
219
303
  }
304
+ const runningActionSession = findRunningActionSession(sessions, resolvedCwd, normalizedPurpose, path);
305
+ if (runningActionSession) {
306
+ applyAppearance(runningActionSession, { themeMode, terminalBackground, terminalForeground });
307
+ return runningActionSession;
308
+ }
220
309
  const pending = pendingSessionCreates.get(id);
221
310
  if (pending) {
222
311
  if (pending.cwd !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
312
+ if (!isPurposeActionMatch(pending.purpose, normalizedPurpose)) throw new Error('Terminal session is already being created with a different purpose');
313
+ if (normalizedPurpose.type === 'project-action') return pending.promise;
223
314
  if (pending.shell !== normalizedShell) throw new Error('Terminal session is already being created with a different shell');
224
315
  if (pending.loginShell !== loginShell) throw new Error('Terminal session is already being created with a different login mode');
316
+ if (pending.mode !== launchMode.mode) throw new Error('Terminal session is already being created with a different mode');
317
+ if (launchMode.mode === COMMAND_TERMINAL_MODE && pending.command !== launchMode.command) throw new Error('Terminal session is already being created with a different command');
225
318
  const session = await pending.promise;
226
319
  applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
227
320
  return session;
228
321
  }
229
- if (!existing && sessions.size + pendingSessionCreates.size >= MAX_SESSIONS) throw new Error('Maximum terminal sessions reached');
322
+ const pendingActionCreate = findPendingActionCreate(pendingSessionCreates, resolvedCwd, normalizedPurpose);
323
+ if (pendingActionCreate) {
324
+ const session = await pendingActionCreate.promise;
325
+ applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
326
+ return session;
327
+ }
328
+ const superseded = normalizedPurpose.type === 'project-action'
329
+ ? [...sessions.values()].filter((session) => session.id !== id && session.status === 'exited'
330
+ && path.resolve(session.cwd) === resolvedCwd && isPurposeActionMatch(getSessionPurpose(session), normalizedPurpose))
331
+ : [];
332
+ if (!existing && sessions.size - superseded.length + pendingSessionCreates.size >= MAX_SESSIONS) throw new Error('Maximum terminal sessions reached');
333
+ const pendingEntry = { cwd: resolvedCwd, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose, cancelled: false, promise: null };
230
334
  const creation = (async () => {
231
335
  const session = existing ?? { id, sequence: 0, history: '', pendingHistoryControlSequence: '', pendingThemeControlSequence: '', eventQueue: [], draining: false, createdAt: Date.now() };
232
- await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell });
336
+ const ptyProcess = await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose });
337
+ if (pendingEntry.cancelled) {
338
+ session.process = null;
339
+ await terminateProcess(ptyProcess, true);
340
+ throw new Error('Terminal session was closed during creation');
341
+ }
342
+ for (const previous of superseded) {
343
+ if (sessions.get(previous.id) !== previous || previous.status !== 'exited') continue;
344
+ sessions.delete(previous.id);
345
+ closeAttachments(previous.id, 'SUPERSEDED', 'Terminal replaced by a new action run');
346
+ }
233
347
  sessions.set(id, session);
234
348
  return session;
235
349
  })();
236
- const pendingEntry = { cwd: resolvedCwd, shell: normalizedShell, loginShell, promise: creation };
350
+ pendingEntry.promise = creation;
237
351
  pendingSessionCreates.set(id, pendingEntry);
238
352
  try { return await creation; }
239
353
  finally { if (pendingSessionCreates.get(id) === pendingEntry) pendingSessionCreates.delete(id); }
@@ -331,6 +445,8 @@ export function createTerminalRuntime({
331
445
  cwd: session.cwd,
332
446
  status: session.status,
333
447
  createdAt: Number.isInteger(session.createdAt) ? session.createdAt : null,
448
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
449
+ purpose: getSessionPurpose(session),
334
450
  });
335
451
  }
336
452
  res.json({ sessions: list });
@@ -349,8 +465,18 @@ export function createTerminalRuntime({
349
465
  res.json({ touched });
350
466
  });
351
467
  app.post('/api/terminal/create', async (req, res) => {
352
- try { const session = await createSession(req.body ?? {}); res.json({ sessionId: session.id, cols: session.cols, rows: session.rows, status: session.status }); }
353
- catch (error) { res.status(error?.message === 'Maximum terminal sessions reached' ? 429 : 400).json({ error: error?.message || 'Failed to create terminal session' }); }
468
+ try {
469
+ const session = await createSession(req.body ?? {});
470
+ res.json({
471
+ sessionId: session.id,
472
+ cols: session.cols,
473
+ rows: session.rows,
474
+ status: session.status,
475
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
476
+ purpose: getSessionPurpose(session),
477
+ });
478
+ }
479
+ catch (error) { res.status(error?.message === 'Maximum terminal sessions reached' ? 429 : 400).json(errorBody(error, 'Failed to create terminal session')); }
354
480
  });
355
481
  app.post('/api/terminal/:sessionId/resize', (req, res) => {
356
482
  const session = sessions.get(req.params.sessionId);
@@ -369,6 +495,7 @@ export function createTerminalRuntime({
369
495
  app.post('/api/terminal/:sessionId/restart', async (req, res) => {
370
496
  const session = sessions.get(req.params.sessionId);
371
497
  if (!session) return res.status(404).json({ error: 'Terminal session not found' });
498
+ if ((session.mode ?? INTERACTIVE_TERMINAL_MODE) === COMMAND_TERMINAL_MODE) return res.status(400).json({ error: 'Command-mode terminal sessions cannot be restarted' });
372
499
  const cwd = req.body?.cwd ?? session.cwd;
373
500
  const cols = req.body?.cols ?? session.cols;
374
501
  const rows = req.body?.rows ?? session.rows;
@@ -393,12 +520,21 @@ export function createTerminalRuntime({
393
520
  try {
394
521
  await restart;
395
522
  res.json({ sessionId: session.id, cols, rows, status: session.status });
396
- } catch (error) { res.status(400).json({ error: error?.message || 'Failed to restart terminal' }); }
523
+ } catch (error) { res.status(400).json(errorBody(error, 'Failed to restart terminal')); }
397
524
  finally { if (pendingSessionRestarts.get(session.id) === restart) pendingSessionRestarts.delete(session.id); }
398
525
  });
399
526
  app.delete('/api/terminal/:sessionId', async (req, res) => {
400
527
  const session = sessions.get(req.params.sessionId);
401
- if (!session) return res.status(404).json({ error: 'Terminal session not found' });
528
+ if (!session) {
529
+ const pending = pendingSessionCreates.get(req.params.sessionId);
530
+ if (!pending) return res.status(404).json({ error: 'Terminal session not found' });
531
+ pending.cancelled = true;
532
+ try { await pending.promise; }
533
+ catch (error) {
534
+ if (error?.message !== 'Terminal session was closed during creation') throw error;
535
+ }
536
+ return res.json({ success: true });
537
+ }
402
538
  sessions.delete(session.id);
403
539
  closeAttachments(session.id, 'CLOSED', 'Terminal closed');
404
540
  await terminateProcess(session.process);