@openchamber/web 2.0.2 → 2.0.4

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 (257) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-connect-url.js +6 -5
  3. package/bin/lib/commands-tunnel.js +24 -5
  4. package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
  5. package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
  6. package/dist/assets/FilesView-CN34wm_N.js +17 -0
  7. package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
  9. package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
  11. package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
  12. package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
  14. package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
  15. package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
  17. package/dist/assets/PlanView-B7Xgihqk.js +5 -0
  18. package/dist/assets/PluginPane-2C71F8uF.js +3 -0
  19. package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
  20. package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
  21. package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
  23. package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
  25. package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
  26. package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
  27. package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
  29. package/dist/assets/de-DlgBHUAI.js +10 -0
  30. package/dist/assets/es-BC8G41U8.js +16 -0
  31. package/dist/assets/fr-I0z3vVjy.js +14 -0
  32. package/dist/assets/index-CgR5rJq_.js +41 -0
  33. package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
  34. package/dist/assets/index-adyy_sEk.css +1 -0
  35. package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
  36. package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
  37. package/dist/assets/ja-BIElEsY8.js +16 -0
  38. package/dist/assets/ko-DRnnHetA.js +16 -0
  39. package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
  40. package/dist/assets/main-DVX34beR.js +886 -0
  41. package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
  42. package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
  43. package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
  44. package/dist/assets/nl-DzUV-kwp.js +16 -0
  45. package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
  46. package/dist/assets/pl-Bb-cb7k7.js +16 -0
  47. package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
  48. package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
  49. package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
  51. package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
  52. package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
  53. package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
  54. package/dist/assets/tr-DXEDSoYO.js +7 -0
  55. package/dist/assets/uk-C8hN--q_.js +16 -0
  56. package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
  57. package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
  58. package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
  59. package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
  61. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
  62. package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
  63. package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
  64. package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
  65. package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
  66. package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
  67. package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +5 -5
  70. package/dist/mobile.html +5 -5
  71. package/package.json +5 -5
  72. package/server/index.js +82 -4
  73. package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
  74. package/server/lib/agent-tool/runtime.js +13 -4
  75. package/server/lib/agent-tool/runtime.test.js +15 -0
  76. package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
  77. package/server/lib/context-obligatory/runtime.js +2 -1
  78. package/server/lib/context-obligatory/runtime.test.js +76 -30
  79. package/server/lib/dictation/DOCUMENTATION.md +4 -1
  80. package/server/lib/dictation/openai-compatible-session.js +7 -0
  81. package/server/lib/enterprise-mode.d.ts +30 -0
  82. package/server/lib/enterprise-mode.js +253 -0
  83. package/server/lib/enterprise-mode.test.js +247 -0
  84. package/server/lib/event-stream/translate-v2.js +6 -0
  85. package/server/lib/event-stream/translate-v2.test.js +6 -0
  86. package/server/lib/git/DOCUMENTATION.md +2 -1
  87. package/server/lib/git/routes.js +44 -1
  88. package/server/lib/git/routes.test.js +98 -1
  89. package/server/lib/git/service.js +146 -11
  90. package/server/lib/git/service.test.js +195 -0
  91. package/server/lib/github/routes.js +9 -19
  92. package/server/lib/github/routes.test.js +112 -0
  93. package/server/lib/guests/DOCUMENTATION.md +4 -2
  94. package/server/lib/guests/background.test.js +1 -1
  95. package/server/lib/guests/catalog.js +56 -2
  96. package/server/lib/guests/catalog.test.js +24 -1
  97. package/server/lib/guests/clone-network.test.js +52 -0
  98. package/server/lib/guests/clone.js +30 -4
  99. package/server/lib/guests/enterprise.js +68 -0
  100. package/server/lib/guests/enterprise.test.js +106 -0
  101. package/server/lib/guests/grant-scope.js +8 -2
  102. package/server/lib/guests/grant-scope.test.js +9 -0
  103. package/server/lib/guests/html-styles.js +16 -2
  104. package/server/lib/guests/html-styles.test.js +53 -4
  105. package/server/lib/guests/install.js +10 -0
  106. package/server/lib/guests/persist.js +1 -0
  107. package/server/lib/guests/routes.js +40 -5
  108. package/server/lib/guests/updates.js +9 -2
  109. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  110. package/server/lib/notifications/runtime.js +22 -8
  111. package/server/lib/notifications/trigger-runtime.test.js +45 -0
  112. package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
  113. package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
  114. package/server/lib/opencode/DOCUMENTATION.md +13 -9
  115. package/server/lib/opencode/auth-state-runtime.js +2 -2
  116. package/server/lib/opencode/config-paths.test.js +1 -0
  117. package/server/lib/opencode/env-runtime.js +26 -3
  118. package/server/lib/opencode/env-runtime.test.js +57 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/hmr-state-runtime.js +4 -3
  121. package/server/lib/opencode/lifecycle.js +10 -5
  122. package/server/lib/opencode/lifecycle.test.js +6 -2
  123. package/server/lib/opencode/managed-config-file.js +2 -1
  124. package/server/lib/opencode/managed-config-file.test.js +18 -0
  125. package/server/lib/opencode/npm-registry-config.d.ts +1 -0
  126. package/server/lib/opencode/npm-registry-config.js +123 -0
  127. package/server/lib/opencode/npm-registry-config.test.js +167 -0
  128. package/server/lib/opencode/npm-registry.js +5 -6
  129. package/server/lib/opencode/npm-registry.test.js +30 -0
  130. package/server/lib/opencode/openchamber-routes.js +8 -0
  131. package/server/lib/opencode/project-icon-routes.js +2 -2
  132. package/server/lib/opencode/project-icon-routes.test.js +44 -0
  133. package/server/lib/opencode/provider-source-route.test.js +32 -0
  134. package/server/lib/opencode/routes.js +17 -2
  135. package/server/lib/opencode/settings-helpers.js +26 -3
  136. package/server/lib/opencode/settings-helpers.test.js +12 -5
  137. package/server/lib/opencode/settings-registry.json +35 -1
  138. package/server/lib/opencode/settings-runtime.js +1 -0
  139. package/server/lib/opencode/shutdown-runtime.js +2 -0
  140. package/server/lib/opencode/static-routes-runtime.js +9 -1
  141. package/server/lib/opencode/static-routes-runtime.test.js +58 -1
  142. package/server/lib/package-manager.js +4 -1
  143. package/server/lib/package-manager.test.js +24 -0
  144. package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
  145. package/server/lib/permission-auto-accept/modes.js +26 -0
  146. package/server/lib/permission-auto-accept/runtime.js +146 -40
  147. package/server/lib/permission-auto-accept/runtime.test.js +93 -9
  148. package/server/lib/quota/DOCUMENTATION.md +6 -0
  149. package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
  150. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
  151. package/server/lib/relay/DOCUMENTATION.md +1 -1
  152. package/server/lib/relay/service.js +32 -12
  153. package/server/lib/relay/service.test.js +30 -0
  154. package/server/lib/routing/DOCUMENTATION.md +150 -41
  155. package/server/lib/routing/classifier.js +156 -0
  156. package/server/lib/routing/defaults.js +27 -0
  157. package/server/lib/routing/jev.js +5 -17
  158. package/server/lib/routing/routes.http.test.js +9 -0
  159. package/server/lib/routing/routes.js +27 -1
  160. package/server/lib/routing/runtime.js +199 -33
  161. package/server/lib/routing/runtime.test.js +299 -15
  162. package/server/lib/routing/store.js +57 -0
  163. package/server/lib/routing/store.test.js +37 -0
  164. package/server/lib/session-assist/DOCUMENTATION.md +17 -7
  165. package/server/lib/session-assist/context.js +42 -2
  166. package/server/lib/session-assist/context.test.js +38 -1
  167. package/server/lib/session-assist/runtime.js +57 -13
  168. package/server/lib/session-assist/runtime.test.js +45 -0
  169. package/server/lib/session-goal/DOCUMENTATION.md +47 -22
  170. package/server/lib/session-goal/audit.js +112 -0
  171. package/server/lib/session-goal/audit.test.js +58 -0
  172. package/server/lib/session-goal/runtime.js +113 -134
  173. package/server/lib/session-goal/runtime.test.js +146 -13
  174. package/server/lib/session-lineage.js +52 -0
  175. package/server/lib/session-lineage.test.js +45 -0
  176. package/server/lib/session-work/DOCUMENTATION.md +108 -0
  177. package/server/lib/session-work/questions.js +126 -0
  178. package/server/lib/session-work/runtime.js +278 -0
  179. package/server/lib/session-work/runtime.test.js +255 -0
  180. package/server/lib/session-work/state.js +48 -0
  181. package/server/lib/session-work/state.test.js +34 -0
  182. package/server/lib/small-model/DOCUMENTATION.md +14 -7
  183. package/server/lib/small-model/client.js +7 -4
  184. package/server/lib/small-model/index.js +11 -21
  185. package/server/lib/small-model/index.test.js +13 -26
  186. package/server/lib/spaces/DOCUMENTATION.md +79 -25
  187. package/server/lib/spaces/gatekeeper-channel.js +63 -11
  188. package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
  189. package/server/lib/spaces/gatekeeper-program.cjs +64 -13
  190. package/server/lib/spaces/gatekeeper-program.test.js +115 -3
  191. package/server/lib/spaces/host.js +58 -13
  192. package/server/lib/spaces/host.test.js +34 -1
  193. package/server/lib/spaces/idle-stop.js +98 -0
  194. package/server/lib/spaces/idle-stop.test.js +130 -0
  195. package/server/lib/spaces/journey.js +427 -17
  196. package/server/lib/spaces/journey.test.js +592 -5
  197. package/server/lib/spaces/layout.js +27 -6
  198. package/server/lib/spaces/manager.test.js +1 -1
  199. package/server/lib/spaces/places/contract-suite.js +4 -2
  200. package/server/lib/spaces/places/docker-live-support.js +27 -4
  201. package/server/lib/spaces/places/docker.js +32 -5
  202. package/server/lib/spaces/places/docker.test.js +38 -8
  203. package/server/lib/spaces/places/escape-suite.js +32 -0
  204. package/server/lib/spaces/places/fake-docker.js +3 -1
  205. package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
  206. package/server/lib/spaces/places/memory-place.js +3 -3
  207. package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
  208. package/server/lib/spaces/routes.js +49 -1
  209. package/server/lib/spaces/routes.test.js +31 -3
  210. package/server/lib/spaces/space-opencode.js +52 -0
  211. package/server/lib/spaces/space-opencode.test.js +41 -0
  212. package/server/lib/spaces/space-records.js +90 -2
  213. package/server/lib/spaces/space-records.test.js +58 -1
  214. package/server/lib/spaces/space-server.js +13 -1
  215. package/server/lib/spaces/space-server.test.js +13 -0
  216. package/server/lib/spaces/space-setup.js +173 -0
  217. package/server/lib/spaces/space-setup.test.js +174 -0
  218. package/server/lib/tts/DOCUMENTATION.md +3 -0
  219. package/server/lib/tts/base-url.js +8 -0
  220. package/server/lib/tts/routes.js +13 -1
  221. package/server/lib/tts/routes.test.js +26 -0
  222. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  223. package/server/lib/tunnels/routes.js +14 -0
  224. package/server/lib/tunnels/routes.test.js +26 -0
  225. package/server/lib/walkthrough/index.js +11 -7
  226. package/server/lib/walkthrough/jobs.test.js +8 -0
  227. package/server/lib/walkthrough/languages.js +1 -0
  228. package/server/lib/walkthrough/routes.js +7 -1
  229. package/dist/assets/FilesView-0Ie20mEk.js +0 -17
  230. package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
  231. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
  232. package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
  233. package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
  234. package/dist/assets/PluginPane-BEPUWVho.js +0 -3
  235. package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
  236. package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
  237. package/dist/assets/de-CgAJ51z7.js +0 -10
  238. package/dist/assets/es-zGi_ravM.js +0 -16
  239. package/dist/assets/fr-CPfogrWx.js +0 -14
  240. package/dist/assets/index-CHfphYL3.js +0 -41
  241. package/dist/assets/index-DvMJ3w6V.css +0 -1
  242. package/dist/assets/ja-DMk6wd-U.js +0 -16
  243. package/dist/assets/ko-BFpzJ8jc.js +0 -16
  244. package/dist/assets/main-anyZFMIs.js +0 -896
  245. package/dist/assets/markdownCore-CmM47cAE.js +0 -7
  246. package/dist/assets/pl-VdRPcZrB.js +0 -16
  247. package/dist/assets/pt-BR-BRys_lOW.js +0 -16
  248. package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
  249. package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
  250. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
  251. package/dist/assets/tr-CA9ckNnm.js +0 -7
  252. package/dist/assets/uk-byjR-y8D.js +0 -16
  253. package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
  254. package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
  255. package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
  256. package/dist/assets/zh-CN-DRabgxdG.js +0 -16
  257. package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
@@ -0,0 +1,173 @@
1
+ // The project's worktree setup commands, run inside a space after its code arrived (DESIGN.md,
2
+ // "Code in and out"; STAGES.md, stage 5d-4). They are the commands OpenChamber runs for a new
3
+ // worktree on the host, chosen by the client the same way, the shared ones only after the user
4
+ // trusted them; here they run in the space, as the space user, one after the other, and stop at
5
+ // the first that fails, as the host's `&&` chain does.
6
+ //
7
+ // A run is one process's memory while it goes: which command runs now. The record keeps what
8
+ // the user must still see after a restart of the host: that a run began, that it finished, or
9
+ // which command failed with the end of its output. A record that says a run began, with no run
10
+ // in this process, is a run the host did not live to see end, and is listed as interrupted.
11
+ //
12
+ // Everything a command prints comes from the project's code and the agent's space: it is text
13
+ // to show, kept short, with the terminal's control sequences taken out, and never anything else.
14
+
15
+ import { z } from 'zod';
16
+
17
+ import { SpaceError } from './errors.js';
18
+ import { IMAGE_BASH, IMAGE_SH, IMAGE_TIMEOUT } from './layout.js';
19
+
20
+ // The host's own limits, `project-setup.js`: 50 shared commands and 50 personal ones, merged.
21
+ export const MAX_SETUP_COMMANDS = 100;
22
+ export const MAX_SETUP_COMMAND_LENGTH = 4000;
23
+
24
+ /** The commands of a run, as the client resolved them: blank ones are dropped. */
25
+ export const setupCommandsSchema = z.array(z.string().max(MAX_SETUP_COMMAND_LENGTH))
26
+ .max(MAX_SETUP_COMMANDS)
27
+ .transform((commands) => commands.filter((command) => command.trim() !== ''));
28
+
29
+ // One command may run this long inside; `timeout` then ends it and everything it started, which
30
+ // a kill of the host's `docker exec` would not. The host waits a minute longer for the answer.
31
+ const COMMAND_TIME_LIMIT_SECONDS = 3600;
32
+ const COMMAND_KILL_AFTER_SECONDS = 10;
33
+ const HOST_WAIT_MS = (COMMAND_TIME_LIMIT_SECONDS + 60) * 1000;
34
+ // `timeout` answers this code when the time limit ended the command.
35
+ const TIMED_OUT_EXIT_CODE = 124;
36
+ // How much of the output the host reads, and how much of its end it keeps for the user.
37
+ const OUTPUT_WINDOW_BYTES = 256 * 1024;
38
+ export const MAX_KEPT_OUTPUT_LINES = 200;
39
+ export const MAX_KEPT_OUTPUT_CHARACTERS = 32 * 1024;
40
+
41
+ // Runs in the space's project, with the space's own environment, so a command finds what the
42
+ // agent finds: the corridor's proxy variables and the space's PATH. The script uses only shell
43
+ // builtins and absolute paths, so no PATH decides what the host runs; the user's command gets
44
+ // the space's PATH. Its error output joins the rest, in the order it was printed.
45
+ const RUN_SCRIPT = `cd -- "$1" || exit 1; exec ${IMAGE_BASH} -c "$2" 2>&1`;
46
+
47
+ /** `$ROOT_PROJECT_PATH` and its older name, as the host's worktrees substitute them: here, the project inside the space. */
48
+ const substituteProjectPath = (command, projectPath) => command
49
+ .replace(/\$\{?ROOT_PROJECT_PATH\}?/g, projectPath)
50
+ .replace(/\$\{?ROOT_WORKTREE_PATH\}?/g, projectPath);
51
+
52
+ // Whole sequences first: operating-system commands with their text, such as a link, up to their
53
+ // end; colour and cursor sequences; any other escape. Then every control character but a tab and a
54
+ // line break, the one-byte controls of the C1 range, and the marks that turn text direction.
55
+ // eslint-disable-next-line no-control-regex
56
+ const TERMINAL_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-_]?|[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
57
+
58
+ /**
59
+ * The end of a command's output as the user reads it: a line that a progress bar rewrote with
60
+ * carriage returns is what it said last, the terminal's sequences are gone, and at most the last
61
+ * 200 lines and 32 KiB are kept.
62
+ */
63
+ export const keptOutputOf = (text) => {
64
+ const lines = String(text)
65
+ .split('\n')
66
+ .map((line) => line.split('\r').filter((part) => part !== '').at(-1) ?? '')
67
+ .map((line) => line.replace(TERMINAL_SEQUENCE, ''));
68
+ while (lines.length > 0 && lines.at(-1).trim() === '') lines.pop();
69
+ const kept = lines.slice(-MAX_KEPT_OUTPUT_LINES).join('\n');
70
+ return kept.length > MAX_KEPT_OUTPUT_CHARACTERS ? kept.slice(-MAX_KEPT_OUTPUT_CHARACTERS) : kept;
71
+ };
72
+
73
+ /**
74
+ * `exec` is the place's; `records` the host's records of spaces; `announce(spaceId)` tells the
75
+ * clients that a space's setup moved on, so they read the list again.
76
+ */
77
+ export function createSpaceSetup({ exec, records, announce = () => {}, logger = console, now = () => new Date() }) {
78
+ // The runs under way, by space id: which command of how many.
79
+ const runs = new Map();
80
+
81
+ const remember = (spaceId, setup) => {
82
+ // A record that is gone, with its space, or unreadable keeps nothing; the run still ends.
83
+ try {
84
+ records.update(spaceId, { setup });
85
+ } catch (error) {
86
+ logger.warn?.(`[spaces] the setup of space ${spaceId} could not be remembered: ${error?.code ?? error?.message ?? error}`);
87
+ }
88
+ };
89
+
90
+ /** One command in the space. Resolves `{ exitCode, timedOut, output }`; a failure of the place is the command's failure. */
91
+ const runOne = async (spaceId, projectPath, command) => {
92
+ const began = now().getTime();
93
+ // 124 is also what a command of the project's own may answer, `timeout 30 curl` among them:
94
+ // it counts as the hour only when the hour has passed.
95
+ const hourPassed = () => now().getTime() - began >= COMMAND_TIME_LIMIT_SECONDS * 1000;
96
+ const argv = [
97
+ IMAGE_TIMEOUT, '-k', String(COMMAND_KILL_AFTER_SECONDS), String(COMMAND_TIME_LIMIT_SECONDS),
98
+ IMAGE_SH, '-c', RUN_SCRIPT, 'openchamber-setup', projectPath, substituteProjectPath(command, projectPath),
99
+ ];
100
+ try {
101
+ // `killTree`, so a host that quits takes its `docker exec` along; the command inside then
102
+ // runs to its end or its time limit, and the host lists the run as interrupted.
103
+ const result = await exec(spaceId, argv, { timeoutMs: HOST_WAIT_MS, maxOutputBytes: OUTPUT_WINDOW_BYTES, keepTail: true, killTree: true });
104
+ return {
105
+ exitCode: result.code,
106
+ timedOut: result.code === TIMED_OUT_EXIT_CODE && hourPassed(),
107
+ // The runtime's own complaint, a container that stopped among them, comes on stderr.
108
+ output: keptOutputOf([result.stdout, result.stderr].filter((part) => part !== '').join('\n')),
109
+ };
110
+ } catch (error) {
111
+ return {
112
+ exitCode: null,
113
+ timedOut: error instanceof SpaceError && error.code === 'command_timeout',
114
+ output: keptOutputOf(error?.message ?? String(error)),
115
+ };
116
+ }
117
+ };
118
+
119
+ const runAll = async (spaceId, projectPath, commands) => {
120
+ const run = runs.get(spaceId);
121
+ try {
122
+ for (const [index, command] of commands.entries()) {
123
+ run.index = index;
124
+ run.command = command;
125
+ if (index > 0) announce(spaceId);
126
+ const outcome = await runOne(spaceId, projectPath, command);
127
+ if (outcome.exitCode !== 0) {
128
+ remember(spaceId, { state: 'failed', total: commands.length, index, command, ...outcome, finishedAt: now().toISOString() });
129
+ logger.warn?.(`[spaces] setup command ${index + 1} of ${commands.length} failed in space ${spaceId}: exit ${outcome.exitCode}${outcome.timedOut ? ', timed out' : ''}`);
130
+ return;
131
+ }
132
+ }
133
+ remember(spaceId, { state: 'done', total: commands.length, finishedAt: now().toISOString() });
134
+ } finally {
135
+ runs.delete(spaceId);
136
+ announce(spaceId);
137
+ }
138
+ };
139
+
140
+ /**
141
+ * Starts the commands in the background and answers at once. One run per space at a time.
142
+ * `projectPath` is the project inside the space, where they run.
143
+ */
144
+ const start = (spaceId, { projectPath, commands }) => {
145
+ if (runs.has(spaceId)) throw new SpaceError('space_setup_running', 'The setup commands of this space are still running. Wait for them to finish.');
146
+ if (commands.length === 0) throw new SpaceError('invalid_setup_commands', 'There are no setup commands to run.');
147
+ runs.set(spaceId, { index: 0, total: commands.length, command: commands[0] });
148
+ remember(spaceId, { state: 'running', total: commands.length, startedAt: now().toISOString() });
149
+ announce(spaceId);
150
+ void runAll(spaceId, projectPath, commands);
151
+ };
152
+
153
+ const isRunning = (spaceId) => runs.has(spaceId);
154
+
155
+ /**
156
+ * The setup as the list carries it, from this process's run while one goes and from the record
157
+ * otherwise. The output is not here: the list is read often, and the output only when asked.
158
+ */
159
+ const describe = (spaceId, record) => {
160
+ const run = runs.get(spaceId);
161
+ if (run) return { state: 'running', index: run.index, total: run.total, command: run.command };
162
+ const kept = record?.setup ?? null;
163
+ if (kept === null) return null;
164
+ if (kept.state === 'running') return { state: 'interrupted', total: kept.total };
165
+ if (kept.state === 'done') return { state: 'done', total: kept.total };
166
+ return { state: 'failed', index: kept.index, total: kept.total, command: kept.command, exitCode: kept.exitCode, timedOut: kept.timedOut };
167
+ };
168
+
169
+ /** The end of the failed command's output, or null when no command failed. */
170
+ const outputOf = (record) => (record?.setup?.state === 'failed' ? record.setup.output : null);
171
+
172
+ return { start, isRunning, describe, outputOf };
173
+ }
@@ -0,0 +1,174 @@
1
+ // The setup commands inside a space, over a stand-in `exec` that answers per command and real
2
+ // records in a temporary folder. What is under test is the order, where they run, what a failure
3
+ // keeps for the user, and what the list says while a run goes and after the host lost it.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+
9
+ import { afterEach, describe, expect, it } from 'vitest';
10
+
11
+ import { SpaceError } from './errors.js';
12
+ import { IMAGE_BASH, IMAGE_SH, IMAGE_TIMEOUT } from './layout.js';
13
+ import { createSpaceRecords } from './space-records.js';
14
+ import { MAX_KEPT_OUTPUT_CHARACTERS, MAX_KEPT_OUTPUT_LINES, createSpaceSetup, keptOutputOf, setupCommandsSchema } from './space-setup.js';
15
+
16
+ const ID = 'abcdef012345';
17
+ const PROJECT_PATH = `/spaces/${ID}/project`;
18
+ const quiet = { warn: () => {} };
19
+ const folders = [];
20
+ const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
21
+ const until = async (check, timeoutMs = 3_000) => {
22
+ const deadline = Date.now() + timeoutMs;
23
+ while (!check() && Date.now() < deadline) await sleep(5);
24
+ return check();
25
+ };
26
+
27
+ afterEach(() => {
28
+ for (const folder of folders.splice(0)) fs.rmSync(folder, { recursive: true, force: true });
29
+ });
30
+
31
+ /** A setup over records in a fresh folder and an `exec` that answers each command from `answers`. */
32
+ const setupWith = (answers = {}) => {
33
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-setup-'));
34
+ folders.push(dataDir);
35
+ const records = createSpaceRecords({ dataDir, logger: quiet });
36
+ records.write(ID, { network: { mode: 'allowlist', domains: [] }, spacePath: PROJECT_PATH });
37
+ const calls = [];
38
+ const announced = [];
39
+ const held = new Map();
40
+ const exec = async (spaceId, argv, options) => {
41
+ const command = argv.at(-1);
42
+ calls.push({ spaceId, argv, options });
43
+ if (held.has(command)) await held.get(command).promise;
44
+ const answer = answers[command] ?? { code: 0, stdout: '', stderr: '' };
45
+ if (answer instanceof Error) throw answer;
46
+ return answer;
47
+ };
48
+ /** Makes the named command wait until the test lets it go. */
49
+ const hold = (command) => {
50
+ let release = () => {};
51
+ const promise = new Promise((resolve) => { release = resolve; });
52
+ held.set(command, { promise, release });
53
+ return release;
54
+ };
55
+ // The clock stands still unless a test moves it.
56
+ const clock = { at: Date.parse('2026-09-28T10:00:00.000Z') };
57
+ const exec2 = async (spaceId, argv, options) => {
58
+ const answer = await exec(spaceId, argv, options);
59
+ if (answers.advanceMs) clock.at += answers.advanceMs;
60
+ return answer;
61
+ };
62
+ const setup = createSpaceSetup({ exec: exec2, records, announce: (spaceId) => announced.push(spaceId), logger: quiet, now: () => new Date(clock.at) });
63
+ return { setup, records, calls, announced, hold };
64
+ };
65
+
66
+ describe('setup commands inside a space', () => {
67
+ it('runs each command in the project inside, one after the other, under a time limit, and remembers that they finished', async () => {
68
+ const { setup, records, calls, announced } = setupWith();
69
+ setup.start(ID, { projectPath: PROJECT_PATH, commands: ['npm ci', 'cp "$ROOT_PROJECT_PATH/.env.example" ${ROOT_WORKTREE_PATH}/.env'] });
70
+ expect(await until(() => !setup.isRunning(ID))).toBe(true);
71
+
72
+ expect(calls.map((call) => call.argv)).toEqual([
73
+ [IMAGE_TIMEOUT, '-k', '10', '3600', IMAGE_SH, '-c', `cd -- "$1" || exit 1; exec ${IMAGE_BASH} -c "$2" 2>&1`, 'openchamber-setup', PROJECT_PATH, 'npm ci'],
74
+ [IMAGE_TIMEOUT, '-k', '10', '3600', IMAGE_SH, '-c', `cd -- "$1" || exit 1; exec ${IMAGE_BASH} -c "$2" 2>&1`, 'openchamber-setup', PROJECT_PATH, `cp "${PROJECT_PATH}/.env.example" ${PROJECT_PATH}/.env`],
75
+ ]);
76
+ // The host waits past the time limit inside, reads a window of the output, and a quit takes its `docker exec` along.
77
+ expect(calls[0].options).toEqual({ timeoutMs: 3_660_000, maxOutputBytes: 256 * 1024, keepTail: true, killTree: true });
78
+ expect(calls.every((call) => call.spaceId === ID && call.options.target === undefined)).toBe(true);
79
+ expect(records.read(ID).record.setup).toEqual({ state: 'done', total: 2, finishedAt: '2026-09-28T10:00:00.000Z' });
80
+ expect(setup.describe(ID, records.read(ID).record)).toEqual({ state: 'done', total: 2 });
81
+ expect(setup.outputOf(records.read(ID).record)).toBeNull();
82
+ // Began, the second command, and the end.
83
+ expect(announced).toEqual([ID, ID, ID]);
84
+ });
85
+
86
+ it('says which command runs while a run goes, and refuses a second run until it ends', async () => {
87
+ const { setup, records, hold } = setupWith();
88
+ const release = hold('npm ci');
89
+ setup.start(ID, { projectPath: PROJECT_PATH, commands: ['npm ci', 'npm run build'] });
90
+ expect(setup.describe(ID, records.read(ID).record)).toEqual({ state: 'running', index: 0, total: 2, command: 'npm ci' });
91
+ expect(records.read(ID).record.setup).toEqual({ state: 'running', total: 2, startedAt: '2026-09-28T10:00:00.000Z' });
92
+ expect(() => setup.start(ID, { projectPath: PROJECT_PATH, commands: ['true'] })).toThrow(expect.objectContaining({ code: 'space_setup_running' }));
93
+ release();
94
+ expect(await until(() => !setup.isRunning(ID))).toBe(true);
95
+ expect(() => setup.start(ID, { projectPath: PROJECT_PATH, commands: [] })).toThrow(expect.objectContaining({ code: 'invalid_setup_commands' }));
96
+ });
97
+
98
+ it('stops at the first command that fails and keeps which one, how, and the end of what it printed', async () => {
99
+ const printed = `${'\u001b[31mnpm ERR!\u001b[0m 403 Forbidden\n'}fetch 10%\rfetch 50%\rfetch 100%\n`;
100
+ const { setup, records, calls } = setupWith({ 'npm ci': { code: 1, stdout: printed, stderr: '' } });
101
+ setup.start(ID, { projectPath: PROJECT_PATH, commands: ['echo ok', 'npm ci', 'npm run build'] });
102
+ expect(await until(() => !setup.isRunning(ID))).toBe(true);
103
+ expect(calls).toHaveLength(2);
104
+ const { record } = records.read(ID);
105
+ expect(record.setup).toEqual({ state: 'failed', total: 3, index: 1, command: 'npm ci', exitCode: 1, timedOut: false, output: 'npm ERR! 403 Forbidden\nfetch 100%', finishedAt: '2026-09-28T10:00:00.000Z' });
106
+ expect(setup.describe(ID, record)).toEqual({ state: 'failed', index: 1, total: 3, command: 'npm ci', exitCode: 1, timedOut: false });
107
+ expect(setup.outputOf(record)).toBe('npm ERR! 403 Forbidden\nfetch 100%');
108
+ });
109
+
110
+ it('counts the time limit inside and a place that failed as the command failing', async () => {
111
+ const limited = setupWith({ 'sleep 9999': { code: 124, stdout: '', stderr: '' }, advanceMs: 3_600_000 });
112
+ limited.setup.start(ID, { projectPath: PROJECT_PATH, commands: ['sleep 9999'] });
113
+ expect(await until(() => !limited.setup.isRunning(ID))).toBe(true);
114
+ expect(limited.records.read(ID).record.setup).toMatchObject({ exitCode: 124, timedOut: true });
115
+
116
+ // A command's own 124 before the hour is its own failure, not the limit.
117
+ const own = setupWith({ 'timeout 30 curl https://example.com': { code: 124, stdout: '', stderr: '' }, advanceMs: 30_000 });
118
+ own.setup.start(ID, { projectPath: PROJECT_PATH, commands: ['timeout 30 curl https://example.com'] });
119
+ expect(await until(() => !own.setup.isRunning(ID))).toBe(true);
120
+ expect(own.records.read(ID).record.setup).toMatchObject({ exitCode: 124, timedOut: false });
121
+
122
+ const gone = setupWith({ 'npm ci': new SpaceError('space_not_running', 'Space abcdef012345 is stopped.') });
123
+ gone.setup.start(ID, { projectPath: PROJECT_PATH, commands: ['npm ci'] });
124
+ expect(await until(() => !gone.setup.isRunning(ID))).toBe(true);
125
+ expect(gone.records.read(ID).record.setup).toMatchObject({ exitCode: null, timedOut: false, output: 'Space abcdef012345 is stopped.' });
126
+
127
+ const hostWait = setupWith({ 'npm ci': new SpaceError('command_timeout', 'docker exec ran too long') });
128
+ hostWait.setup.start(ID, { projectPath: PROJECT_PATH, commands: ['npm ci'] });
129
+ expect(await until(() => !hostWait.setup.isRunning(ID))).toBe(true);
130
+ expect(hostWait.records.read(ID).record.setup).toMatchObject({ exitCode: null, timedOut: true });
131
+ });
132
+
133
+ it('lists a run the record says began, with no run in this process, as interrupted', () => {
134
+ const { setup, records } = setupWith();
135
+ records.update(ID, { setup: { state: 'running', total: 3, startedAt: '2026-09-28T09:00:00.000Z' } });
136
+ expect(setup.describe(ID, records.read(ID).record)).toEqual({ state: 'interrupted', total: 3 });
137
+ expect(setup.describe(ID, null)).toBeNull();
138
+ });
139
+
140
+ it('keeps a run going when its record is gone, the space removed meanwhile', async () => {
141
+ const { setup, records, hold } = setupWith({ 'npm ci': { code: 2, stdout: 'x', stderr: '' } });
142
+ const release = hold('npm ci');
143
+ setup.start(ID, { projectPath: PROJECT_PATH, commands: ['npm ci'] });
144
+ records.remove(ID);
145
+ release();
146
+ expect(await until(() => !setup.isRunning(ID))).toBe(true);
147
+ expect(records.read(ID)).toEqual({ status: 'missing', record: null });
148
+ });
149
+ });
150
+
151
+ describe('what the user reads of a command', () => {
152
+ it('keeps the last lines as a terminal last showed them, without its control sequences', () => {
153
+ expect(keptOutputOf('a\r\nb\u0007\u001b[2Kc\n\n')).toBe('a\nbc');
154
+ const many = Array.from({ length: 500 }, (_, index) => `line ${index}`).join('\n');
155
+ const kept = keptOutputOf(many).split('\n');
156
+ expect(kept).toHaveLength(MAX_KEPT_OUTPUT_LINES);
157
+ expect(kept.at(-1)).toBe('line 499');
158
+ expect(keptOutputOf('y'.repeat(100_000))).toHaveLength(MAX_KEPT_OUTPUT_CHARACTERS);
159
+ // A link's whole sequence goes, its address with it; so do the one-byte controls and the direction marks.
160
+ expect(keptOutputOf('see \u001b]8;;https://evil.example/\u0007here\u001b]8;;\u0007 done')).toBe('see here done');
161
+ expect(keptOutputOf('a\u001b]0;title\u001b\\b')).toBe('ab');
162
+ expect(keptOutputOf('x\u009b31my\u0085')).toBe('x31my');
163
+ expect(keptOutputOf('file\u202egnp.exe \u2066z\u2069')).toBe('filegnp.exe z');
164
+ });
165
+
166
+ it('takes the list of commands as the host keeps it, without blank ones', () => {
167
+ expect(setupCommandsSchema.parse(['npm ci', ' ', ''])).toEqual(['npm ci']);
168
+ // 50 shared and 50 personal, as the host keeps them.
169
+ expect(setupCommandsSchema.safeParse(Array.from({ length: 100 }, () => 'true')).success).toBe(true);
170
+ expect(setupCommandsSchema.safeParse(Array.from({ length: 101 }, () => 'true')).success).toBe(false);
171
+ expect(setupCommandsSchema.safeParse(['x'.repeat(4001)]).success).toBe(false);
172
+ expect(setupCommandsSchema.safeParse('npm ci').success).toBe(false);
173
+ });
174
+ });
@@ -81,6 +81,9 @@ Returns object with:
81
81
  ### `generateSpeechBuffer`
82
82
  Returns Buffer containing MP3 audio data.
83
83
 
84
+ ## Enterprise mode
85
+ With enterprise mode on (`../enterprise-mode.js`), speech and transcription stay on this machine: `normalizeCustomOpenAIBaseURL` refuses any non-local host whatever `OPENCHAMBER_ALLOW_REMOTE_OPENAI_COMPAT_URLS` or the desktop runtime would allow, `/api/tts/speak` without a custom server (OpenAI's cloud) and `/api/voice/token` answer 403, and `/api/tts/status` reports `available: false, enterpriseMode: true` so Settings can say why. macOS `say` and the local dictation models are unaffected.
86
+
84
87
  ## API key resolution
85
88
  OpenAI API keys are resolved in order:
86
89
  1. Environment variable `OPENAI_API_KEY`.
@@ -1,3 +1,5 @@
1
+ import { isEnterpriseMode } from '../enterprise-mode.js';
2
+
1
3
  const LOCAL_BASE_URL_HOSTS = new Set([
2
4
  'localhost',
3
5
  '127.0.0.1',
@@ -47,6 +49,12 @@ export const normalizeCustomOpenAIBaseURL = (value) => {
47
49
  return { error: 'Custom server URL must not include credentials' };
48
50
  }
49
51
 
52
+ // Speech and transcription carry conversation content, so enterprise mode
53
+ // keeps them on this machine whatever else allows a remote host.
54
+ if (isEnterpriseMode() && !isAllowedLocalHost(parsed.hostname)) {
55
+ return { error: 'In enterprise mode a custom speech server has to run on this machine.' };
56
+ }
57
+
50
58
  const isDesktop = (process.env.OPENCHAMBER_RUNTIME || '').trim().toLowerCase() === 'desktop';
51
59
  const envFlagRaw = process.env.OPENCHAMBER_ALLOW_REMOTE_OPENAI_COMPAT_URLS;
52
60
  const hasExplicitFlag = typeof envFlagRaw === 'string' && envFlagRaw.trim().length > 0;
@@ -3,6 +3,7 @@ import { normalizeCustomOpenAIBaseURL } from './base-url.js';
3
3
  import { summarizeText, sanitizeForTTS, sanitizeForNote } from '../text/summarization.js';
4
4
 
5
5
  import { detectTextLanguage, languageOfLocale, pickVoiceForLanguage } from './language-detect.js';
6
+ import { ENTERPRISE_MODE_ERROR, isEnterpriseMode } from '../enterprise-mode.js';
6
7
 
7
8
  export function registerTtsRoutes(app, { sayTTSCapability }) {
8
9
  let ttsModulePromise = null;
@@ -18,6 +19,9 @@ export function registerTtsRoutes(app, { sayTTSCapability }) {
18
19
  contentType: req.headers['content-type'] || null,
19
20
  });
20
21
  try {
22
+ if (isEnterpriseMode()) {
23
+ return res.status(403).json({ allowed: false, error: ENTERPRISE_MODE_ERROR });
24
+ }
21
25
  const openaiApiKey = process.env.OPENAI_API_KEY;
22
26
  console.log('[Voice] OpenAI API Key present:', !!openaiApiKey);
23
27
 
@@ -60,6 +64,12 @@ export function registerTtsRoutes(app, { sayTTSCapability }) {
60
64
  return res.status(400).json({ error: 'Text is required' });
61
65
  }
62
66
 
67
+ // Without a custom server this is OpenAI's cloud; a custom one has
68
+ // already been held to this machine by the URL check above.
69
+ if (isEnterpriseMode() && !normalizedBaseURL) {
70
+ return res.status(403).json({ error: ENTERPRISE_MODE_ERROR });
71
+ }
72
+
63
73
  // Dynamically import the TTS service (ESM)
64
74
  const { ttsService } = await getTtsModule();
65
75
 
@@ -135,8 +145,10 @@ export function registerTtsRoutes(app, { sayTTSCapability }) {
135
145
  app.get('/api/tts/status', async (_req, res) => {
136
146
  try {
137
147
  const { ttsService } = await getTtsModule();
148
+ const enterpriseMode = isEnterpriseMode();
138
149
  res.json({
139
- available: ttsService.isAvailable(),
150
+ available: !enterpriseMode && ttsService.isAvailable(),
151
+ enterpriseMode,
140
152
  voices: [
141
153
  'alloy', 'ash', 'ballad', 'coral', 'echo', 'fable',
142
154
  'nova', 'onyx', 'sage', 'shimmer', 'verse', 'marin', 'cedar'
@@ -59,6 +59,20 @@ describe('tts routes', () => {
59
59
  }
60
60
  });
61
61
 
62
+ it('refuses OpenAI cloud speech in enterprise mode and says so in the status', async () => {
63
+ process.env.OPENCHAMBER_ENTERPRISE_MODE = 'true';
64
+ try {
65
+ const app = createApp();
66
+ const status = await request(app).get('/api/tts/status');
67
+ expect(status.body).toMatchObject({ available: false, enterpriseMode: true });
68
+ const speak = await request(app).post('/api/tts/speak').send({ text: 'The migration is done', apiKey: 'sk-test' });
69
+ expect(speak.status).toBe(403);
70
+ expect((await request(app).post('/api/voice/token').send({})).status).toBe(403);
71
+ } finally {
72
+ delete process.env.OPENCHAMBER_ENTERPRISE_MODE;
73
+ }
74
+ });
75
+
62
76
  it('returns local note fallback while model summarization is retired', async () => {
63
77
  const response = await request(createApp())
64
78
  .post('/api/text/summarize')
@@ -157,6 +171,18 @@ describe('normalizeCustomOpenAIBaseURL', () => {
157
171
  expect(result.value).toBe('https://my-server.com/v1');
158
172
  });
159
173
 
174
+ it('keeps custom servers on this machine in enterprise mode, whatever else allows remote', () => {
175
+ process.env.OPENCHAMBER_RUNTIME = 'desktop';
176
+ process.env.OPENCHAMBER_ALLOW_REMOTE_OPENAI_COMPAT_URLS = 'true';
177
+ process.env.OPENCHAMBER_ENTERPRISE_MODE = '1';
178
+ try {
179
+ expect(normalizeCustomOpenAIBaseURL('https://my-tts-server.example.com/v1').error).toMatch(/enterprise mode/);
180
+ expect(normalizeCustomOpenAIBaseURL('http://127.0.0.1:8880/v1').value).toBe('http://127.0.0.1:8880/v1');
181
+ } finally {
182
+ delete process.env.OPENCHAMBER_ENTERPRISE_MODE;
183
+ }
184
+ });
185
+
160
186
  it('denies remote URLs on desktop when env var is explicitly false', () => {
161
187
  process.env.OPENCHAMBER_RUNTIME = 'desktop';
162
188
  process.env.OPENCHAMBER_ALLOW_REMOTE_OPENAI_COMPAT_URLS = 'false';
@@ -5,6 +5,8 @@ This module contains tunnel provider orchestration for OpenChamber, including pr
5
5
 
6
6
  Public tunnels require a UI password on the running server. The shared tunnel start operation enforces this for startup tunnels and HTTP requests; the HTTP route rejects passwordless starts before touching an existing tunnel.
7
7
 
8
+ In enterprise mode (`../enterprise-mode.js`) no tunnel starts at all: a tunnel provider terminates TLS at its edge and sees plain text. The same shared start operation refuses first (so `--tunnel` at startup fails too), the HTTP route answers 403 `enterprise_mode` ahead of the password check, and an inactive status reports `enterpriseMode` so Settings shows why.
9
+
8
10
  ## Entrypoints and structure
9
11
  - `packages/web/server/lib/tunnels/index.js`: tunnel service orchestration.
10
12
  - `packages/web/server/lib/tunnels/executable-search.js`: cross-platform executable discovery, including Windows Store app aliases.
@@ -1,3 +1,9 @@
1
+ import { isEnterpriseMode } from '../enterprise-mode.js';
2
+
3
+ // Tunnel providers terminate TLS at their edge and see every request in plain
4
+ // text, so enterprise mode refuses them outright.
5
+ const TUNNEL_BLOCKED_ERROR = 'External tunnels are not available in enterprise mode. Pair devices on your network or through your own relay instead.';
6
+
1
7
  export const createTunnelRoutesRuntime = (dependencies) => {
2
8
  const {
3
9
  crypto,
@@ -75,6 +81,10 @@ export const createTunnelRoutesRuntime = (dependencies) => {
75
81
  selectedPresetId,
76
82
  selectedPresetName,
77
83
  }) => {
84
+ // Every tunnel start passes here: the Settings button and `--tunnel` at startup.
85
+ if (isEnterpriseMode()) {
86
+ throw Object.assign(new Error(TUNNEL_BLOCKED_ERROR), { code: 'enterprise_mode' });
87
+ }
78
88
  if (!hasUiPassword) {
79
89
  throw new Error('A UI password is required before starting a public tunnel. Restart OpenChamber with --ui-password.');
80
90
  }
@@ -355,6 +365,7 @@ export const createTunnelRoutesRuntime = (dependencies) => {
355
365
  if (!publicUrl) {
356
366
  return res.json({
357
367
  active: false,
368
+ enterpriseMode: isEnterpriseMode(),
358
369
  url: null,
359
370
  mode: normalizedMode,
360
371
  provider,
@@ -449,6 +460,9 @@ export const createTunnelRoutesRuntime = (dependencies) => {
449
460
  });
450
461
 
451
462
  app.post('/api/openchamber/tunnel/start', async (_req, res) => {
463
+ if (isEnterpriseMode()) {
464
+ return res.status(403).json({ ok: false, code: 'enterprise_mode', error: TUNNEL_BLOCKED_ERROR });
465
+ }
452
466
  if (!hasUiPassword) {
453
467
  return res.status(403).json({ ok: false, code: 'ui_password_required', error: 'A UI password is required before starting a public tunnel. Restart OpenChamber with --ui-password.' });
454
468
  }
@@ -46,6 +46,32 @@ describe('public tunnel password requirement', () => {
46
46
  expect(getStarts()).toBe(0);
47
47
  });
48
48
 
49
+ it('refuses every tunnel in enterprise mode, password or not', async () => {
50
+ process.env.OPENCHAMBER_ENTERPRISE_MODE = '1';
51
+ try {
52
+ const { runtime, getStarts } = createRuntime(true);
53
+ await expect(runtime.startTunnelWithNormalizedRequest({ provider: 'cloudflare', mode: 'quick' }))
54
+ .rejects.toThrow('enterprise mode');
55
+ const routes = new Map();
56
+ runtime.registerRoutes({
57
+ get: (path, handler) => routes.set(`GET ${path}`, handler),
58
+ post: (path, handler) => routes.set(`POST ${path}`, handler),
59
+ put: (path, handler) => routes.set(`PUT ${path}`, handler),
60
+ });
61
+ let status = 200;
62
+ let body;
63
+ await routes.get('POST /api/openchamber/tunnel/start')({ body: {} }, {
64
+ status(code) { status = code; return this; },
65
+ json(payload) { body = payload; return this; },
66
+ });
67
+ expect(status).toBe(403);
68
+ expect(body.code).toBe('enterprise_mode');
69
+ expect(getStarts()).toBe(0);
70
+ } finally {
71
+ delete process.env.OPENCHAMBER_ENTERPRISE_MODE;
72
+ }
73
+ });
74
+
49
75
  it('allows a password-protected runtime to start a tunnel', async () => {
50
76
  const { runtime, getStarts } = createRuntime(true);
51
77
  const result = await runtime.startTunnelWithNormalizedRequest({ provider: 'cloudflare', mode: 'quick' });
@@ -165,10 +165,14 @@ const modelLabel = (model) => `${model.providerID}/${model.modelID}`;
165
165
  * saved setting, which in turn outranks the small-model chain — the user picking
166
166
  * a roomier model for a risky change is the most specific intent there is.
167
167
  */
168
- const resolveModel = (directory, explicitModel) => describeSmallModel({
168
+ // `providerID` is the provider in the user's composer: without a model of its
169
+ // own choosing, the walkthrough stays on it rather than on whichever provider
170
+ // happens to be connected.
171
+ const resolveModel = (directory, explicitModel, providerID) => describeSmallModel({
169
172
  directory,
170
173
  outputReserveTokens: walkthroughOutputTokens,
171
174
  overrideModel: explicitModel || readWalkthroughModelOverride(),
175
+ preferredProviderID: providerID || undefined,
172
176
  });
173
177
 
174
178
  export const __testing = { generationTimeoutMs, walkthroughOutputTokens };
@@ -233,7 +237,7 @@ const serializeHunks = (files) => files.flatMap((file) => file.hunks.map((hunk)
233
237
  * Read the last walkthrough for a source, resolved against the current diff.
234
238
  * Never generates and never spends tokens.
235
239
  */
236
- export async function getWalkthrough({ directory, source: rawSource, model: explicitModel, language: rawLanguage }, deps = {}) {
240
+ export async function getWalkthrough({ directory, source: rawSource, model: explicitModel, providerID, language: rawLanguage }, deps = {}) {
237
241
  const source = parseSource(rawSource);
238
242
  const repoRoot = await getRepositoryRoot(directory);
239
243
  const key = sourceKey(source);
@@ -245,7 +249,7 @@ export async function getWalkthrough({ directory, source: rawSource, model: expl
245
249
  // the whole git pipeline twice.
246
250
  const [built, model] = await Promise.all([
247
251
  loadCurrentDiff(directory, source, deps),
248
- resolveModel(directory, explicitModel).catch(() => null),
252
+ resolveModel(directory, explicitModel, providerID).catch(() => null),
249
253
  ]);
250
254
  const { files } = built;
251
255
  const hunkIndex = indexHunks(files);
@@ -368,7 +372,7 @@ function computeReadiness({ model, digest, files, fileCount, hunkCount, generate
368
372
  * which also means returning to a previous state of the working tree costs
369
373
  * nothing.
370
374
  */
371
- export async function generateWalkthrough({ directory, source: rawSource, force = false, model: explicitModel, language: rawLanguage }, deps = {}) {
375
+ export async function generateWalkthrough({ directory, source: rawSource, force = false, model: explicitModel, providerID, language: rawLanguage }, deps = {}) {
372
376
  const source = parseSource(rawSource);
373
377
  const repoRoot = await getRepositoryRoot(directory);
374
378
  const key = sourceKey(source);
@@ -380,7 +384,7 @@ export async function generateWalkthrough({ directory, source: rawSource, force
380
384
  if (existing) return existing.promise;
381
385
 
382
386
  const controller = new AbortController();
383
- const promise = runGeneration({ directory, source, repoRoot, key, force, explicitModel, language, signal: controller.signal }, deps)
387
+ const promise = runGeneration({ directory, source, repoRoot, key, force, explicitModel, providerID, language, signal: controller.signal }, deps)
384
388
  .finally(() => {
385
389
  if (jobs.get(jobKey(repoRoot, key))?.controller === controller) {
386
390
  jobs.delete(jobKey(repoRoot, key));
@@ -391,9 +395,9 @@ export async function generateWalkthrough({ directory, source: rawSource, force
391
395
  return promise;
392
396
  }
393
397
 
394
- async function runGeneration({ directory, source, repoRoot, key, force, explicitModel, language, signal }, deps) {
398
+ async function runGeneration({ directory, source, repoRoot, key, force, explicitModel, providerID, language, signal }, deps) {
395
399
 
396
- const model = await resolveModel(directory, explicitModel);
400
+ const model = await resolveModel(directory, explicitModel, providerID);
397
401
  if (!model) {
398
402
  throw fail('No model is available — sign in to a provider first', 404, { code: 'no-model' });
399
403
  }
@@ -83,6 +83,14 @@ describe('generation jobs', () => {
83
83
  fs.rmSync(TEMP_DATA_DIR, { recursive: true, force: true });
84
84
  });
85
85
 
86
+ it('resolves the model on the composer provider it was given', async () => {
87
+ generateSmallModelText.mockResolvedValue({ text: RESPONSE });
88
+
89
+ await generateWalkthrough({ directory: '/repo', source: SOURCE, providerID: 'anthropic' });
90
+
91
+ expect(describeSmallModel.mock.calls.at(-1)[0]).toMatchObject({ directory: '/repo', preferredProviderID: 'anthropic' });
92
+ });
93
+
86
94
  it('runs a second request against the same job instead of paying twice', async () => {
87
95
  let release;
88
96
  generateSmallModelText.mockImplementation(() => new Promise((resolve) => {
@@ -19,6 +19,7 @@ const LANGUAGE_NAMES = {
19
19
  en: 'English',
20
20
  de: 'German',
21
21
  fr: 'French',
22
+ nl: 'Dutch',
22
23
  'zh-CN': 'Simplified Chinese',
23
24
  'zh-TW': 'Traditional Chinese',
24
25
  uk: 'Ukrainian',