@openchamber/web 1.23.1 → 1.24.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 (187) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-DL0imnlI.js → CodeMirrorCommentWidgets-C9kV-n7r.js} +1 -1
  2. package/dist/assets/DiffView-B7YkbY-u.js +4 -0
  3. package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +1 -0
  4. package/dist/assets/FilesView-vjJx7VaM.js +13 -0
  5. package/dist/assets/GitView-BLhlMYEY.js +6 -0
  6. package/dist/assets/GuestAttachDialog-B-fwE8r3.js +3 -0
  7. package/dist/assets/{JsonTreeView-BPBDPY9B.js → JsonTreeView-D_4G5X6-.js} +1 -1
  8. package/dist/assets/LinearIssuesView-1uKhePfH.js +1 -0
  9. package/dist/assets/{MarkdownImageGallery-BNjimjiI.js → MarkdownImageGallery-Ix7N_2wp.js} +1 -1
  10. package/dist/assets/MarkdownRendererImpl-Deel_y5S.js +12 -0
  11. package/dist/assets/{OnboardingScreen-CWXxIIAH.js → OnboardingScreen-ToIakxb_.js} +1 -1
  12. package/dist/assets/{PatchDiff-B6J3p3br.js → PatchDiff-BjMgezr1.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-BjTRJJ1D.js → PierreDiffViewer-53Ghfnlr.js} +5 -5
  14. package/dist/assets/PlanView-BGAzxDwD.js +5 -0
  15. package/dist/assets/SettingsView-n2X-jfBB.js +29 -0
  16. package/dist/assets/SettingsWindow-Bi8LE9XI.js +1 -0
  17. package/dist/assets/SubmoduleDiffSummary--YFqK6Ih.js +1 -0
  18. package/dist/assets/ToolOutputDialog-DRWBvdaJ.js +15 -0
  19. package/dist/assets/{ToolPartDiffPreview-DRifZ2YH.js → ToolPartDiffPreview-BxZJCU28.js} +2 -2
  20. package/dist/assets/{VirtualizedFileDiff-BOeQtAWV.js → VirtualizedFileDiff-DCXjBGRf.js} +3 -3
  21. package/dist/assets/{WalkthroughView-BD4p0vhD.js → WalkthroughView-CfIPvWWa.js} +2 -2
  22. package/dist/assets/appThemeRegistry-DDROzcUO.js +1 -0
  23. package/dist/assets/{computeVirtualFileMetrics-FZI1j1rE.js → computeVirtualFileMetrics-DHgQIkUq.js} +1 -1
  24. package/dist/assets/de-CX_f-T5U.js +10 -0
  25. package/dist/assets/es-BERmWNn_.js +16 -0
  26. package/dist/assets/fr-BjYYE_-z.js +14 -0
  27. package/dist/assets/index-DpzTz2UH.css +1 -0
  28. package/dist/assets/index-Dy8xgawx.js +40 -0
  29. package/dist/assets/{index-DddhnFNK.js → index-WjufPkIV.js} +1 -1
  30. package/dist/assets/{isDiffPlainText-D4ld2G-2.js → isDiffPlainText-D9faP70y.js} +1 -1
  31. package/dist/assets/{isFilePlainText-BW1Xfw0F.js → isFilePlainText-6qOcz5Ky.js} +1 -1
  32. package/dist/assets/ja-DxqeAk9N.js +16 -0
  33. package/dist/assets/ko-Dty1aUod.js +16 -0
  34. package/dist/assets/main-BOYSXfYn.js +896 -0
  35. package/dist/assets/{main-BBqRX3Po.js → main-Bjcre_GE.js} +2 -2
  36. package/dist/assets/{markdown-shiki.worker-D5fBU-lw.js → markdown-shiki.worker-CahLvHIq.js} +5 -5
  37. package/dist/assets/markdownCore-DPrwM1rU.js +5 -0
  38. package/dist/assets/{miniChat-CygpKLC_.js → miniChat-Dz_bPgMc.js} +2 -2
  39. package/dist/assets/{mobile-CSmUm4vb.js → mobile-BbZPBJrK.js} +2 -2
  40. package/dist/assets/{patchFileDiff-u4JuidC_.js → patchFileDiff-BvU6KOQC.js} +3 -3
  41. package/dist/assets/pl-CX-_ROkr.js +16 -0
  42. package/dist/assets/pt-BR-DhRR1arx.js +16 -0
  43. package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +2 -0
  44. package/dist/assets/renderMobileApp-BK1kFlcJ.js +25 -0
  45. package/dist/assets/runtimeEndpointReset-BULHvOwb.js +25 -0
  46. package/dist/assets/{scheduledTasksApi-Og3jfb4K.js → scheduledTasksApi-DW3xqMQ8.js} +1 -1
  47. package/dist/assets/shikiHighlight-DsxD9QEa.js +1 -0
  48. package/dist/assets/textMateThemeFromAppTheme-Da7ed8qM.js +1 -0
  49. package/dist/assets/tr-cIQtYBpg.js +7 -0
  50. package/dist/assets/uk-CD21CXFV.js +16 -0
  51. package/dist/assets/useAppFontEffects-hfv2s6mZ.js +7333 -0
  52. package/dist/assets/useInlineCommentController-BmtfVbo8.js +2 -0
  53. package/dist/assets/useRootScrollLock-Cwc4kSl2.js +1 -0
  54. package/dist/assets/{vendor-base-ui-BY_5qla_.js → vendor-base-ui-CsXYnR5c.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-D5hG1bL9.js → vendor-codemirror-language-data-BPMJpOpT.js} +2 -2
  56. package/dist/assets/vendor-framer-motion-Bq3iTZ6r.js +1 -0
  57. package/dist/assets/{vendor-motion-dom-D_o3BTI3.js → vendor-motion-dom-DcCgeG69.js} +1 -1
  58. package/dist/assets/{vendor-remixicon-react-Dil0zKKT.js → vendor-remixicon-react-BDmGmFCA.js} +1 -1
  59. package/dist/assets/vendor-strip-json-comments-5dJlOkP1.js +4 -0
  60. package/dist/assets/{vendor-zod-B6551dwG.js → vendor-zod-fZppILAM.js} +4 -4
  61. package/dist/assets/{web-components-DCyJti1c.js → web-components-U-hWbgJo.js} +2 -2
  62. package/dist/assets/zh-CN-BWvlPHY-.js +16 -0
  63. package/dist/assets/zh-TW-CRp5dJU2.js +16 -0
  64. package/dist/index.html +4 -4
  65. package/dist/mini-chat.html +4 -4
  66. package/dist/mobile.html +4 -4
  67. package/package.json +8 -6
  68. package/server/built-in-extensions/registry.json +4 -0
  69. package/server/index.d.ts +2 -0
  70. package/server/index.js +15 -3
  71. package/server/lib/fs/DOCUMENTATION.md +8 -0
  72. package/server/lib/fs/git-process.test.js +77 -0
  73. package/server/lib/fs/routes.js +2 -1
  74. package/server/lib/fs/search.js +2 -1
  75. package/server/lib/git/DOCUMENTATION.md +3 -1
  76. package/server/lib/git/routes.js +16 -3
  77. package/server/lib/git/service.js +112 -8
  78. package/server/lib/git/service.test.js +127 -0
  79. package/server/lib/guests/DOCUMENTATION.md +66 -0
  80. package/server/lib/guests/auth-store.js +184 -0
  81. package/server/lib/guests/auth-store.test.js +112 -0
  82. package/server/lib/guests/builtins.js +34 -0
  83. package/server/lib/guests/builtins.test.js +174 -0
  84. package/server/lib/guests/catalog.js +466 -0
  85. package/server/lib/guests/catalog.test.js +390 -0
  86. package/server/lib/guests/clone.js +297 -0
  87. package/server/lib/guests/extract-zip.js +136 -0
  88. package/server/lib/guests/extract-zip.test.js +109 -0
  89. package/server/lib/guests/files.js +308 -0
  90. package/server/lib/guests/files.test.js +262 -0
  91. package/server/lib/guests/grant-scope.js +81 -0
  92. package/server/lib/guests/grant-scope.test.js +75 -0
  93. package/server/lib/guests/host-session.js +73 -0
  94. package/server/lib/guests/host-session.test.js +30 -0
  95. package/server/lib/guests/html-styles.js +6 -0
  96. package/server/lib/guests/html-styles.test.js +45 -0
  97. package/server/lib/guests/html-tokens.js +73 -0
  98. package/server/lib/guests/html-tokens.test.js +53 -0
  99. package/server/lib/guests/install.js +406 -0
  100. package/server/lib/guests/install.test.js +338 -0
  101. package/server/lib/guests/oauth.js +501 -0
  102. package/server/lib/guests/oauth.test.js +481 -0
  103. package/server/lib/guests/persist.js +336 -0
  104. package/server/lib/guests/persist.test.js +288 -0
  105. package/server/lib/guests/request.js +112 -0
  106. package/server/lib/guests/request.test.js +206 -0
  107. package/server/lib/guests/routes.js +838 -0
  108. package/server/lib/guests/service.js +538 -0
  109. package/server/lib/guests/service.test.js +277 -0
  110. package/server/lib/guests/sockets.js +129 -0
  111. package/server/lib/guests/sockets.test.js +110 -0
  112. package/server/lib/guests/ssh-install.test.js +188 -0
  113. package/server/lib/guests/storage.js +68 -0
  114. package/server/lib/guests/storage.test.js +59 -0
  115. package/server/lib/guests/updates.js +294 -0
  116. package/server/lib/guests/updates.test.js +334 -0
  117. package/server/lib/guests/upload.js +50 -0
  118. package/server/lib/guests/upload.test.js +131 -0
  119. package/server/lib/linear/DOCUMENTATION.md +1 -1
  120. package/server/lib/openchamber-control/DOCUMENTATION.md +6 -0
  121. package/server/lib/openchamber-sessions/routes.js +44 -11
  122. package/server/lib/openchamber-sessions/routes.test.js +47 -0
  123. package/server/lib/opencode/DOCUMENTATION.md +54 -0
  124. package/server/lib/opencode/core-routes.js +39 -1
  125. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  126. package/server/lib/opencode/lifecycle-process.test.js +84 -0
  127. package/server/lib/opencode/lifecycle.js +54 -67
  128. package/server/lib/opencode/openchamber-routes.js +72 -14
  129. package/server/lib/opencode/openchamber-routes.test.js +71 -3
  130. package/server/lib/opencode/settings-helpers.js +5 -0
  131. package/server/lib/opencode/settings-helpers.test.js +13 -1
  132. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  133. package/server/lib/opencode/settings-normalization-runtime.test.js +13 -0
  134. package/server/lib/opencode/settings-registry.json +7 -0
  135. package/server/lib/opencode/shutdown-runtime.js +3 -0
  136. package/server/lib/opencode/shutdown-runtime.test.js +24 -0
  137. package/server/lib/opencode/theme-archive.js +53 -0
  138. package/server/lib/opencode/theme-catalog.js +171 -0
  139. package/server/lib/opencode/theme-catalog.test.js +125 -0
  140. package/server/lib/opencode/theme-import.test.js +144 -0
  141. package/server/lib/opencode/theme-runtime.js +100 -28
  142. package/server/lib/opencode/theme-runtime.test.js +15 -0
  143. package/server/lib/quota/DOCUMENTATION.md +0 -1
  144. package/server/lib/quota/providers/index.js +0 -7
  145. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  146. package/server/lib/terminal/runtime.js +17 -2
  147. package/server/lib/terminal/runtime.test.js +45 -0
  148. package/server/lib/ui-auth/ui-auth.js +43 -8
  149. package/server/lib/ui-auth/ui-auth.test.js +40 -0
  150. package/dist/assets/DiffView-q6z6MFdZ.js +0 -4
  151. package/dist/assets/DirtyBranchSwitchDialog-to6K1rXL.js +0 -1
  152. package/dist/assets/FilesView-uwvKGOeu.js +0 -13
  153. package/dist/assets/GitView-CAqrkFYg.js +0 -6
  154. package/dist/assets/LinearIssuesView-Dq4Nz_DL.js +0 -1
  155. package/dist/assets/MarkdownRendererImpl-BIYG3j5A.js +0 -12
  156. package/dist/assets/PlanView-Cs7Aa22g.js +0 -5
  157. package/dist/assets/SettingsView-DROvkdyX.js +0 -28
  158. package/dist/assets/SettingsWindow-AtPQGcRJ.js +0 -1
  159. package/dist/assets/ToolOutputDialog-DmAZDzlT.js +0 -15
  160. package/dist/assets/appThemeRegistry-BK0dHKa6.js +0 -1
  161. package/dist/assets/de-Byg3syd1.js +0 -10
  162. package/dist/assets/es-B-FGkjnQ.js +0 -16
  163. package/dist/assets/fr-Dvzik_Jj.js +0 -14
  164. package/dist/assets/index-zhgg-SDz.css +0 -1
  165. package/dist/assets/index-zzfsbdBe.js +0 -40
  166. package/dist/assets/ja-CFnftYdc.js +0 -16
  167. package/dist/assets/ko-CgZ13aWV.js +0 -16
  168. package/dist/assets/main-BX3ip8Oc.js +0 -930
  169. package/dist/assets/markdownCore-TRGNObm0.js +0 -5
  170. package/dist/assets/pl-BDk6AWIE.js +0 -16
  171. package/dist/assets/pt-BR-DV5hPNsk.js +0 -16
  172. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  173. package/dist/assets/renderElectronMiniChatApp-Bfh77YcY.js +0 -2
  174. package/dist/assets/renderMobileApp-DsYwHQBL.js +0 -25
  175. package/dist/assets/runtimeEndpointReset-MtnTGkZz.js +0 -41
  176. package/dist/assets/shikiHighlight-CVE7qsu3.js +0 -1
  177. package/dist/assets/tr-BwS5J324.js +0 -7
  178. package/dist/assets/uk-Dp60Q7VN.js +0 -16
  179. package/dist/assets/useAppFontEffects-DQXEYu1N.js +0 -7282
  180. package/dist/assets/useGitComparison-DjFXbxbu.js +0 -1
  181. package/dist/assets/useInlineCommentController-B4Vhtx-T.js +0 -2
  182. package/dist/assets/useRootScrollLock-B32nj08w.js +0 -1
  183. package/dist/assets/vendor-framer-motion-livSKyyV.js +0 -1
  184. package/dist/assets/zh-CN-D1MXOnJ7.js +0 -16
  185. package/dist/assets/zh-TW-MqRc5ECP.js +0 -16
  186. package/server/lib/quota/providers/crof.js +0 -96
  187. package/server/lib/quota/providers/crof.test.js +0 -98
@@ -109,6 +109,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
109
109
  reapManagedOrphanedProcesses = reapOrphanedProcesses,
110
110
  getWarmupDirectories = async () => [],
111
111
  onOpenCodeRestarted = null,
112
+ managedStartupTimeoutMs = 30_000,
112
113
  now = Date.now,
113
114
  } = deps;
114
115
 
@@ -287,7 +288,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
287
288
  }
288
289
 
289
290
  const pid = child.pid;
290
- if (!pid || hasChildProcessExited(child)) {
291
+ if (!pid || (process.platform === 'win32' && hasChildProcessExited(child))) {
291
292
  await waitForChildProcessClose(child, 250);
292
293
  return;
293
294
  }
@@ -301,34 +302,14 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
301
302
  }
302
303
 
303
304
  try {
304
- child.kill(signal);
305
+ if (!hasChildProcessExited(child)) child.kill(signal);
305
306
  } catch {
306
307
  }
307
308
  };
308
309
 
309
310
  if (process.platform === 'win32') {
310
- try {
311
- child.kill();
312
- } catch {
313
- }
314
-
315
- if (await waitForChildProcessClose(child, 800)) {
316
- return;
317
- }
318
-
319
- try {
320
- spawnSync('taskkill', ['/pid', String(pid), '/t'], {
321
- stdio: 'ignore',
322
- timeout: 3000,
323
- windowsHide: true,
324
- });
325
- } catch {
326
- }
327
-
328
- if (await waitForChildProcessClose(child, 1500)) {
329
- return;
330
- }
331
-
311
+ // Windows child.kill() terminates only the parent. Kill the owned tree
312
+ // while its parent still exists, otherwise /T cannot find its children.
332
313
  try {
333
314
  spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], {
334
315
  stdio: 'ignore',
@@ -343,11 +324,9 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
343
324
  }
344
325
 
345
326
  signalProcessTree('SIGTERM');
346
-
347
- if (await waitForChildProcessClose(child, 2500)) {
348
- return;
349
- }
350
-
327
+ await waitForChildProcessClose(child, 2500);
328
+ // Parent exit does not prove group exit. Tools can ignore SIGTERM and keep
329
+ // running after their server has exited and closed its own stdio.
351
330
  signalProcessTree('SIGKILL');
352
331
 
353
332
  await waitForChildProcessClose(child, 1000);
@@ -452,7 +431,29 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
452
431
  child.on('exit', recordManagedProcessExit);
453
432
  child.on('close', recordManagedProcessExit);
454
433
 
455
- const url = await new Promise((resolve, reject) => {
434
+ // Ownership starts at spawn, including processes that never become ready.
435
+ const registration = registerManagedProcess({
436
+ pid: child.pid,
437
+ ownerPid: process.pid,
438
+ port,
439
+ binary,
440
+ runtime: process.env.OPENCHAMBER_RUNTIME || 'web',
441
+ });
442
+
443
+ let closePromise = null;
444
+ const serverProcess = {
445
+ url: null,
446
+ pid: child.pid || null,
447
+ get exitCode() { return observedExitCode ?? child.exitCode; },
448
+ get signalCode() { return observedSignalCode ?? child.signalCode; },
449
+ get stderrTail() { return getManagedProcessSnapshot().stderrTail; },
450
+ close() {
451
+ if (!closePromise) closePromise = registration.then(() => closeManagedOpenCodeChild(child));
452
+ return closePromise;
453
+ },
454
+ };
455
+
456
+ const readiness = new Promise((resolve, reject) => {
456
457
  let stdout = '';
457
458
  let stderr = '';
458
459
  let done = false;
@@ -507,37 +508,21 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
507
508
  child.stderr?.on('data', onStderr);
508
509
  child.on('exit', onExit);
509
510
  child.on('error', onError);
511
+ }).catch(async (error) => {
512
+ await serverProcess.close();
513
+ if (state.openCodeProcess === serverProcess) {
514
+ state.openCodeProcess = null;
515
+ syncToHmrState();
516
+ }
517
+ throw error;
510
518
  });
511
519
 
512
- // Record this child so a future run can reap it if we crash before teardown.
513
- // The web-server lifecycle runs in-process inside multiple hosts, so tag the
514
- // actual host (Electron sets OPENCHAMBER_RUNTIME='desktop'; the standalone
515
- // web CLI leaves it unset → 'web'; SSH remote → 'ssh-remote') rather than a
516
- // hardcoded label, matching the server's existing runtimeName convention.
517
- await registerManagedProcess({
518
- pid: child.pid,
519
- ownerPid: process.pid,
520
- port,
521
- binary,
522
- runtime: process.env.OPENCHAMBER_RUNTIME || 'web',
523
- });
524
-
525
- return {
526
- url,
527
- pid: child.pid || null,
528
- get exitCode() {
529
- return observedExitCode ?? child.exitCode;
530
- },
531
- get signalCode() {
532
- return observedSignalCode ?? child.signalCode;
533
- },
534
- get stderrTail() {
535
- return getManagedProcessSnapshot().stderrTail;
536
- },
537
- async close() {
538
- await closeManagedOpenCodeChild(child);
539
- },
540
- };
520
+ // Shutdown must be able to close an in-flight startup, not only a ready server.
521
+ state.openCodeProcess = serverProcess;
522
+ syncToHmrState();
523
+ serverProcess.url = await readiness;
524
+ await registration;
525
+ return serverProcess;
541
526
  };
542
527
 
543
528
  const resolveManagedOpenCodePort = async (requestedPort, hostname = '127.0.0.1') => {
@@ -719,12 +704,14 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
719
704
  });
720
705
  phaseStartedAt = performance.now();
721
706
 
707
+ let serverInstance;
722
708
  try {
723
- const serverInstance = await createManagedOpenCodeServerProcess({
709
+ if (state.isShuttingDown) throw new Error('OpenCode startup cancelled during shutdown');
710
+ serverInstance = await createManagedOpenCodeServerProcess({
724
711
  resolvedBinary,
725
712
  hostname: env.ENV_CONFIGURED_OPENCODE_HOSTNAME,
726
713
  port: spawnPort,
727
- timeout: 30000,
714
+ timeout: managedStartupTimeoutMs,
728
715
  cwd: state.openCodeWorkingDirectory,
729
716
  shellEnvKeysCount: Object.keys(shellEnv).length,
730
717
  env: stripAppImageArgv0Leak(applyProviderEnvAliases({
@@ -750,7 +737,9 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
750
737
  const port = parseInt(url.port, 10);
751
738
  const prefix = normalizeApiPrefix(url.pathname);
752
739
 
753
- if (await waitForReady(serverInstance.url, 10000)) {
740
+ const ready = await waitForReady(serverInstance.url, 10000);
741
+ if (state.isShuttingDown) throw new Error('OpenCode startup cancelled during shutdown');
742
+ if (ready) {
754
743
  setOpenCodePort(port);
755
744
  setDetectedOpenCodeApiPrefix(prefix);
756
745
 
@@ -768,12 +757,10 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
768
757
  return serverInstance;
769
758
  }
770
759
 
771
- try {
772
- await serverInstance.close();
773
- } catch {
774
- }
775
760
  throw new Error('Server started but health check failed (timeout)');
776
761
  } catch (error) {
762
+ await serverInstance?.close();
763
+ if (serverInstance && state.openCodeProcess === serverInstance) state.openCodeProcess = null;
777
764
  const message = error instanceof Error ? error.message : String(error);
778
765
  state.lastOpenCodeError = message;
779
766
  state.openCodePort = null;
@@ -795,7 +782,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
795
782
  return await startOpenCodeOnce(attempt);
796
783
  } catch (error) {
797
784
  lastError = error;
798
- if (error?.code === 'OPENCODE_BINARY_INVALID') {
785
+ if (state.isShuttingDown || error?.code === 'OPENCODE_BINARY_INVALID') {
799
786
  break;
800
787
  }
801
788
  if (attempt >= START_OPEN_CODE_MAX_ATTEMPTS) {
@@ -16,6 +16,43 @@ function quotePosixShell(value) {
16
16
  return `'${String(value).replace(/'/g, "'\\''")}'`;
17
17
  }
18
18
 
19
+ /**
20
+ * `echo` in batch treats `& | < > ( ) ^` as syntax and `%var%` as expansion,
21
+ * so a line of the log preamble is escaped before it becomes an `echo`.
22
+ */
23
+ const escapeBatchEchoLine = (line) => {
24
+ if (!line) return 'echo.';
25
+ return `echo ${line.replace(/%/g, '%%').replace(/[&|<>()^]/g, '^$&')}`;
26
+ };
27
+
28
+ /**
29
+ * The Windows update runs as a batch file, one command per line, so the
30
+ * `if ... else` block and the multi-line log preamble keep their structure.
31
+ */
32
+ const buildWindowsUpdateScript = ({ logPreamble, updateCmd, restartCmd }) => [
33
+ '@echo off',
34
+ ...logPreamble.split('\n').map(escapeBatchEchoLine),
35
+ // `timeout` refuses redirected stdin, which is what a detached child has;
36
+ // a ping to loopback waits about two seconds without a console.
37
+ 'ping -n 3 127.0.0.1 >nul',
38
+ // npm, pnpm and yarn are .cmd shims on Windows. Without `call`, a batch
39
+ // file hands control to them for good and the restart below never runs.
40
+ // Read from a file, cmd expands `%x%` and drops a lone `%`, so a `%` in a
41
+ // host or UI password would change the restart command. Doubling keeps it.
42
+ `call ${updateCmd.replace(/%/g, '%%')}`,
43
+ 'if %ERRORLEVEL% EQU 0 (',
44
+ ' echo Update successful, restarting OpenChamber...',
45
+ ` ${restartCmd ? restartCmd.replace(/%/g, '%%') : 'echo Service manager will restart OpenChamber.'}`,
46
+ ') else (',
47
+ ' echo Update failed',
48
+ ')',
49
+ // The restart command carries the server's own flags, `--ui-password`
50
+ // included, so the file does not outlive the run. Deleting the running
51
+ // batch file on its last line is safe: cmd has already read it.
52
+ 'del "%~f0"',
53
+ '',
54
+ ].join('\r\n');
55
+
19
56
  export const registerOpenChamberRoutes = (app, dependencies) => {
20
57
  const {
21
58
  fs,
@@ -300,6 +337,26 @@ export const registerOpenChamberRoutes = (app, dependencies) => {
300
337
  `logPath=${updateLogPath}`,
301
338
  ].join('\n');
302
339
 
340
+ const shell = isWindows ? (process.env.ComSpec || 'cmd.exe') : 'sh';
341
+ const shellFlag = isWindows ? '/c' : '-c';
342
+ // cmd.exe /c takes one command line: a newline inside it ends the
343
+ // command, so a multi-line script passed as the argument ran nothing
344
+ // and exited 0, and the server shut itself down believing the update
345
+ // was under way (#3084). Batch runs from a file instead, written before
346
+ // the client is told to expect a restart.
347
+ const windowsScriptPath = path.join(openchamberDataDir, 'update-install.cmd');
348
+ if (isWindows) {
349
+ try {
350
+ fs.mkdirSync(path.dirname(windowsScriptPath), { recursive: true });
351
+ fs.writeFileSync(windowsScriptPath, buildWindowsUpdateScript({ logPreamble, updateCmd, restartCmd }), 'utf8');
352
+ } catch (scriptError) {
353
+ console.error('Failed to write the update script, update not started:', scriptError);
354
+ return res.status(500).json({
355
+ error: `Could not write the update script at ${windowsScriptPath}: ${scriptError instanceof Error ? scriptError.message : String(scriptError)}`,
356
+ });
357
+ }
358
+ }
359
+
303
360
  res.json({
304
361
  success: true,
305
362
  message: 'Update starting, server will restart shortly',
@@ -314,21 +371,8 @@ export const registerOpenChamberRoutes = (app, dependencies) => {
314
371
  console.log(`Running: ${updateCmd}`);
315
372
  console.log(logPreamble);
316
373
 
317
- const shell = isWindows ? (process.env.ComSpec || 'cmd.exe') : 'sh';
318
- const shellFlag = isWindows ? '/c' : '-c';
319
374
  const script = isWindows
320
- ? `
321
- echo ${quoteCmd(logPreamble)}
322
- timeout /t 2 /nobreak >nul
323
- ${updateCmd}
324
- if %ERRORLEVEL% EQU 0 (
325
- echo Update successful, restarting OpenChamber...
326
- ${restartCmd || 'echo Service manager will restart OpenChamber.'}
327
- ) else (
328
- echo Update failed
329
- exit /b 1
330
- )
331
- `
375
+ ? windowsScriptPath
332
376
  : `
333
377
  printf '%s\n' ${quotePosix(logPreamble)}
334
378
  sleep 2
@@ -350,10 +394,24 @@ export const registerOpenChamberRoutes = (app, dependencies) => {
350
394
  console.warn('Failed to open update log file, continuing without log capture:', logError);
351
395
  }
352
396
 
397
+ if (isWindows) {
398
+ // On Windows the detached child inherits this process's listening
399
+ // socket, and keeps the port for as long as the batch runs. The
400
+ // restart inside that batch then fails with "port already in use",
401
+ // and the update ends with no server. Closing the listener first
402
+ // leaves nothing to inherit; the process exits right after anyway.
403
+ try {
404
+ server.close();
405
+ } catch (closeError) {
406
+ console.warn('Failed to close the listener before the update script:', closeError);
407
+ }
408
+ }
409
+
353
410
  const child = spawnChild(shell, [shellFlag, script], {
354
411
  detached: true,
355
412
  stdio: logFd !== null ? ['ignore', logFd, logFd] : 'ignore',
356
413
  env: process.env,
414
+ windowsHide: true,
357
415
  });
358
416
  child.unref();
359
417
 
@@ -18,11 +18,15 @@ const childProcess = await import('child_process');
18
18
  const packageManager = await import('../package-manager.js');
19
19
  const { registerOpenChamberRoutes } = await import('./openchamber-routes.js');
20
20
 
21
- const createApp = ({ environment = {}, storedOptions = {}, desktopUpdater } = {}) => {
21
+ const createApp = ({ environment = {}, storedOptions = {}, desktopUpdater, platform = 'linux', execPath = '/usr/bin/node' } = {}) => {
22
22
  const app = express();
23
23
  const dependencies = {
24
24
  fs: {
25
25
  existsSync: vi.fn(() => false),
26
+ mkdirSync: vi.fn(),
27
+ writeFileSync: vi.fn(),
28
+ openSync: vi.fn(() => 7),
29
+ closeSync: vi.fn(),
26
30
  promises: {
27
31
  readFile: vi.fn(async () => JSON.stringify({
28
32
  launchMode: 'foreground',
@@ -34,11 +38,13 @@ const createApp = ({ environment = {}, storedOptions = {}, desktopUpdater } = {}
34
38
  path,
35
39
  process: {
36
40
  env: environment,
37
- platform: 'linux',
38
- execPath: '/usr/bin/node',
41
+ platform,
42
+ execPath,
43
+ exit: vi.fn(),
39
44
  },
40
45
  server: {
41
46
  address: () => ({ port: 7897 }),
47
+ close: vi.fn(),
42
48
  },
43
49
  __dirname: '/opt/openchamber/server',
44
50
  openchamberDataDir: '/tmp/openchamber',
@@ -266,3 +272,65 @@ describe('OpenChamber foreground update route', () => {
266
272
  });
267
273
  });
268
274
  });
275
+
276
+ describe('OpenChamber web update route on Windows', () => {
277
+ it('runs the install-and-restart script from a batch file instead of a cmd.exe /c argument', async () => {
278
+ const { app, dependencies } = createApp({
279
+ platform: 'win32',
280
+ execPath: 'C:\\Program Files\\nodejs\\node.exe',
281
+ environment: { ComSpec: 'C:\\Windows\\system32\\cmd.exe' },
282
+ storedOptions: { launchMode: 'daemon', port: 7897, uiPassword: 'pa%ss' },
283
+ });
284
+ childProcess.spawn.mockReturnValue({ unref: vi.fn() });
285
+ vi.spyOn(console, 'log').mockImplementation(() => {});
286
+
287
+ await request(app).post('/api/openchamber/update-install').expect(200);
288
+ await new Promise((resolve) => setTimeout(resolve, 1300));
289
+
290
+ const scriptPath = path.join('/tmp/openchamber', 'update-install.cmd');
291
+ expect(dependencies.fs.writeFileSync).toHaveBeenCalledWith(scriptPath, expect.any(String), 'utf8');
292
+ const script = dependencies.fs.writeFileSync.mock.calls[0][1];
293
+ const lines = script.split('\r\n');
294
+ expect(lines[0]).toBe('@echo off');
295
+ // Every preamble line is an echo; none is left to run as a command.
296
+ expect(lines.filter((line) => line.startsWith('currentVersion=') || line.startsWith('restartCommand='))).toEqual([]);
297
+ expect(lines).toContain('echo packageManager=npm');
298
+ expect(lines).toContain('echo restartCommand=^("C:\\Program Files\\nodejs\\node.exe" "/opt/openchamber/bin/cli.js" serve --port 7897 --ui-password "pa%%ss"^) ^|^| ^(openchamber serve --port 7897 --ui-password "pa%%ss"^)');
299
+ // A .cmd shim (npm, pnpm, yarn) must be `call`ed or the script ends there.
300
+ expect(lines).toContain('call npm install -g @openchamber/web@latest');
301
+ expect(lines).toContain('ping -n 3 127.0.0.1 >nul');
302
+ expect(lines.some((line) => line.startsWith('timeout '))).toBe(false);
303
+ expect(lines).toContain('if %ERRORLEVEL% EQU 0 (');
304
+ expect(lines.at(-2)).toBe('del "%~f0"');
305
+ // A `%` in the password survives batch expansion only when doubled.
306
+ expect(lines).toContain(' ("C:\\Program Files\\nodejs\\node.exe" "/opt/openchamber/bin/cli.js" serve --port 7897 --ui-password "pa%%ss") || (openchamber serve --port 7897 --ui-password "pa%%ss")');
307
+
308
+ expect(childProcess.spawn).toHaveBeenCalledWith(
309
+ 'C:\\Windows\\system32\\cmd.exe',
310
+ ['/c', scriptPath],
311
+ expect.objectContaining({ detached: true, windowsHide: true }),
312
+ );
313
+ // The listener is closed before the batch is spawned, so the detached
314
+ // child cannot inherit the socket and hold the port against the restart.
315
+ expect(dependencies.server.close).toHaveBeenCalledOnce();
316
+ expect(dependencies.server.close.mock.invocationCallOrder[0]).toBeLessThan(childProcess.spawn.mock.invocationCallOrder[0]);
317
+ expect(dependencies.process.exit).toHaveBeenCalledWith(0);
318
+ });
319
+
320
+ it('answers 500 and keeps the server up when the batch file cannot be written', async () => {
321
+ const { app, dependencies } = createApp({ platform: 'win32', storedOptions: { launchMode: 'daemon', port: 7897 } });
322
+ dependencies.fs.writeFileSync.mockImplementation(() => { throw new Error('EACCES'); });
323
+ vi.spyOn(console, 'log').mockImplementation(() => {});
324
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {});
325
+
326
+ const response = await request(app).post('/api/openchamber/update-install').expect(500);
327
+ await new Promise((resolve) => setTimeout(resolve, 1300));
328
+
329
+ expect(response.body.error).toContain('update-install.cmd');
330
+ expect(response.body.error).toContain('EACCES');
331
+ expect(childProcess.spawn).not.toHaveBeenCalled();
332
+ expect(dependencies.process.exit).not.toHaveBeenCalled();
333
+ expect(logError).toHaveBeenCalledOnce();
334
+ });
335
+ });
336
+
@@ -233,6 +233,11 @@ export const createSettingsHelpers = (dependencies) => {
233
233
  if (typeof candidate.workStatusHiddenSectionsExplicit === 'boolean') {
234
234
  result.workStatusHiddenSectionsExplicit = candidate.workStatusHiddenSectionsExplicit;
235
235
  }
236
+ if (Array.isArray(candidate.workStatusSectionOrder)) {
237
+ result.workStatusSectionOrder = [
238
+ ...new Set(candidate.workStatusSectionOrder.filter((entry) => typeof entry === 'string' && entry.length > 0)),
239
+ ];
240
+ }
236
241
  if (typeof candidate.desktopLanAccessEnabled === 'boolean') {
237
242
  result.desktopLanAccessEnabled = candidate.desktopLanAccessEnabled;
238
243
  }
@@ -69,6 +69,18 @@ const createTestHelpersWithRealSanitizers = () => {
69
69
  };
70
70
 
71
71
  describe('settings helpers', () => {
72
+ it('round-trips section order and preserves it across unrelated writes', () => {
73
+ const helpers = createTestHelpers();
74
+ const changes = helpers.sanitizeSettingsUpdate({ workStatusSectionOrder: ['mcp', 'session', 'mcp', null, ''] });
75
+ expect(changes.workStatusSectionOrder).toEqual(['mcp', 'session']);
76
+ const saved = helpers.mergePersistedSettings({}, changes);
77
+ const reloaded = helpers.formatSettingsResponse(JSON.parse(JSON.stringify(saved)));
78
+ expect(reloaded.workStatusSectionOrder).toEqual(['mcp', 'session']);
79
+ const next = helpers.mergePersistedSettings(reloaded, helpers.sanitizeSettingsUpdate({ workStatusPanelEnabled: false }));
80
+ expect(helpers.formatSettingsResponse(next).workStatusSectionOrder).toEqual(['mcp', 'session']);
81
+ expect(helpers.sanitizeSettingsUpdate({ workStatusSectionOrder: 'bad' }).workStatusSectionOrder).toBeUndefined();
82
+ expect(helpers.sanitizeSettingsUpdate({ workStatusSectionOrder: [] }).workStatusSectionOrder).toEqual([]);
83
+ });
72
84
  it('round-trips telemetry opt-in with the hidden list and preserves it across unrelated writes', () => {
73
85
  const helpers = createTestHelpers();
74
86
  const legacy = helpers.sanitizeSettingsUpdate({ workStatusHiddenSections: [] });
@@ -762,7 +774,7 @@ describe('settings registry gate', () => {
762
774
  managedRemoteTunnelHostname: 'x.example', managedRemoteTunnelToken: 'token', managedRemoteTunnelPresets: [{ id: 'a', name: 'A', hostname: 'a.example' }],
763
775
  managedRemoteTunnelSelectedPresetId: 'a', managedRemoteTunnelPresetTokens: { a: 'token' },
764
776
  sidebarProjectDisplayMode: 'all', sidebarSessionGroupingMode: 'flat', sidebarProjectSortOrder: 'manual', sidebarShowRecentSection: true,
765
- workStatusPanelEnabled: true, workStatusHiddenSections: ['mcp'], workStatusHiddenSectionsExplicit: true,
777
+ workStatusPanelEnabled: true, workStatusHiddenSections: ['mcp'], workStatusHiddenSectionsExplicit: true, workStatusSectionOrder: ['mcp', 'session'],
766
778
  showReasoningTraces: true, streamingAutoFollowEnabled: true, collapsibleThinkingBlocks: true, showTextJustificationActivity: true,
767
779
  chatRenderMode: 'live', activityRenderMode: 'summary', mermaidRenderingMode: 'svg', userMessageRenderingMode: 'markdown', collapsibleUserMessages: true,
768
780
  stickyUserHeader: true, promptNavigatorEnabled: true, wideChatLayoutEnabled: true, showSplitAssistantMessageActions: true, showToolFileIcons: true,
@@ -154,6 +154,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
154
154
  : null;
155
155
  const iconBackground = normalizeIconBackground(candidate.iconBackground);
156
156
  const color = typeof candidate.color === 'string' ? candidate.color.trim() : '';
157
+ const defaultAgent = typeof candidate.defaultAgent === 'string' ? candidate.defaultAgent.trim() : '';
157
158
  const defaultModel = typeof candidate.defaultModel === 'string' ? candidate.defaultModel.trim() : '';
158
159
  const defaultVariant = typeof candidate.defaultVariant === 'string' ? candidate.defaultVariant.trim() : '';
159
160
  const addedAt = Number.isFinite(candidate.addedAt) ? Number(candidate.addedAt) : null;
@@ -175,6 +176,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
175
176
  ...(icon ? { icon } : {}),
176
177
  ...(iconBackground ? { iconBackground } : {}),
177
178
  ...(color ? { color } : {}),
179
+ ...(defaultAgent ? { defaultAgent } : {}),
178
180
  ...(defaultModel && defaultModel.includes('/') ? { defaultModel } : {}),
179
181
  // A variant is meaningless without the model it belongs to.
180
182
  ...(defaultModel && defaultModel.includes('/') && defaultVariant ? { defaultVariant } : {}),
@@ -122,6 +122,19 @@ describe('settings normalization runtime - symlink resolution', () => {
122
122
  expect(result[1].defaultVariant).toBe(undefined);
123
123
  });
124
124
 
125
+ it('keeps a project default agent', () => {
126
+ const runtime = createTestRuntime({
127
+ realpathSync: (p) => p,
128
+ path: { resolve: (p) => p, sep: '/', dirname: (p) => p.split('/').slice(0, -1).join('/') || '/' },
129
+ });
130
+
131
+ const result = runtime.sanitizeProjects([
132
+ { id: 'proj1', path: '/a', defaultAgent: 'plan' },
133
+ ]);
134
+
135
+ expect(result[0].defaultAgent).toBe('plan');
136
+ });
137
+
125
138
  it('deduplicates projects that resolve to the same realpath', () => {
126
139
  const runtime = createTestRuntime({
127
140
  realpathSync: (p) => p.startsWith('/symlink') ? '/real/project' : p,
@@ -217,6 +217,9 @@
217
217
  "sidebarShowRecentSection": {
218
218
  "scope": "profile"
219
219
  },
220
+ "workStatusSectionOrder": {
221
+ "scope": "profile"
222
+ },
220
223
  "workStatusPanelEnabled": {
221
224
  "scope": "profile"
222
225
  },
@@ -605,6 +608,10 @@
605
608
  "scope": "device",
606
609
  "local": true
607
610
  },
611
+ "contextEditorVisible": {
612
+ "scope": "device",
613
+ "local": true
614
+ },
608
615
  "contextEditorTreeWidth": {
609
616
  "scope": "device",
610
617
  "local": true
@@ -108,6 +108,9 @@ export const createGracefulShutdownRuntime = (dependencies) => {
108
108
  console.log('HTTP server closed');
109
109
  resolve();
110
110
  });
111
+ // The backend has stopped. Active SSE/HTTP clients must not keep
112
+ // Desktop waiting for the outer shutdown deadline.
113
+ server.closeAllConnections?.();
111
114
  }),
112
115
  new Promise((resolve) => {
113
116
  closeTimeout = setTimeout(() => {
@@ -1,4 +1,5 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import http from 'node:http';
2
3
 
3
4
  import { createGracefulShutdownRuntime } from './shutdown-runtime.js';
4
5
 
@@ -55,4 +56,27 @@ describe('graceful shutdown runtime', () => {
55
56
  expect(warnSpy).not.toHaveBeenCalledWith('Server close timeout reached, forcing shutdown');
56
57
  expect(vi.getTimerCount()).toBe(0);
57
58
  });
59
+
60
+ it('closes an active HTTP stream instead of waiting for the shutdown deadline', async () => {
61
+ const server = http.createServer((_request, response) => {
62
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
63
+ response.write('data: fixture\n\n');
64
+ });
65
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
66
+ const request = http.get(`http://127.0.0.1:${server.address().port}`);
67
+ request.on('error', () => {});
68
+ const response = await new Promise((resolve) => request.once('response', resolve));
69
+ response.resume();
70
+ const closed = new Promise((resolve) => response.once('close', resolve));
71
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
72
+ try {
73
+ await createRuntime(server).gracefulShutdown({ exitProcess: false });
74
+ expect(warning).not.toHaveBeenCalledWith('Server close timeout reached, forcing shutdown');
75
+ await closed;
76
+ } finally {
77
+ request.destroy();
78
+ server.closeAllConnections();
79
+ await new Promise((resolve) => server.close(resolve));
80
+ }
81
+ });
58
82
  });
@@ -0,0 +1,53 @@
1
+ import { inflateRaw } from 'node:zlib';
2
+ import { promisify } from 'node:util';
3
+
4
+ const inflate = promisify(inflateRaw);
5
+ const MAX_FILE_BYTES = 512 * 1024;
6
+
7
+ // Read only selected JSON entries in memory. Nothing from a VSIX is executed or
8
+ // extracted onto the host filesystem.
9
+ export function openThemeArchive(bytes) {
10
+ let end = bytes.length - 22;
11
+ const lower = Math.max(0, end - 65535);
12
+ while (end >= lower && (bytes.readUInt32LE(end) !== 0x06054b50 || end + 22 + bytes.readUInt16LE(end + 20) !== bytes.length)) end--;
13
+ if (end < lower) throw new Error('Invalid VSIX directory');
14
+ const count = bytes.readUInt16LE(end + 10);
15
+ const directorySize = bytes.readUInt32LE(end + 12);
16
+ let cursor = bytes.readUInt32LE(end + 16);
17
+ if (count > 5000 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6)
18
+ || bytes.readUInt16LE(end + 8) !== count || cursor + directorySize !== end) throw new Error('Unsupported VSIX directory');
19
+ const entries = new Map();
20
+ let totalSize = 0;
21
+ for (let index = 0; index < count; index++) {
22
+ if (cursor + 46 > end || bytes.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid VSIX entry');
23
+ const flags = bytes.readUInt16LE(cursor + 8);
24
+ const method = bytes.readUInt16LE(cursor + 10);
25
+ const compressed = bytes.readUInt32LE(cursor + 20);
26
+ const size = bytes.readUInt32LE(cursor + 24);
27
+ const nameLength = bytes.readUInt16LE(cursor + 28);
28
+ const next = cursor + 46 + nameLength + bytes.readUInt16LE(cursor + 30) + bytes.readUInt16LE(cursor + 32);
29
+ const offset = bytes.readUInt32LE(cursor + 42);
30
+ if (next > end || nameLength > 1024 || flags & 1 || ![0, 8].includes(method)) throw new Error('Unsupported VSIX entry');
31
+ const name = bytes.toString('utf8', cursor + 46, cursor + 46 + nameLength);
32
+ const parts = name.replace(/\/$/, '').split('/');
33
+ if (parts.some((part) => !part || part === '.' || part === '..') || /[\\\0:]/.test(name) || entries.has(name)) throw new Error('Unsafe VSIX path');
34
+ totalSize += size;
35
+ if (totalSize > 100 * 1024 * 1024) throw new Error('VSIX contents too large');
36
+ entries.set(name, { offset, compressed, size, method });
37
+ cursor = next;
38
+ }
39
+ if (cursor !== end) throw new Error('Invalid VSIX directory size');
40
+ return async (name) => {
41
+ const entry = entries.get(name);
42
+ if (!entry || entry.size > MAX_FILE_BYTES) throw new Error('Theme file missing or too large');
43
+ const { offset, compressed, size, method } = entry;
44
+ if (offset + 30 > bytes.length || bytes.readUInt32LE(offset) !== 0x04034b50 || bytes.readUInt16LE(offset + 8) !== method) throw new Error('Invalid VSIX file');
45
+ const nameLength = bytes.readUInt16LE(offset + 26);
46
+ const start = offset + 30 + nameLength + bytes.readUInt16LE(offset + 28);
47
+ if (start + compressed > bytes.length || bytes.toString('utf8', offset + 30, offset + 30 + nameLength) !== name) throw new Error('Invalid VSIX file bounds');
48
+ const data = bytes.subarray(start, start + compressed);
49
+ const result = method === 0 ? data : await inflate(data, { maxOutputLength: MAX_FILE_BYTES });
50
+ if (result.length !== size) throw new Error('Invalid VSIX file size');
51
+ return result.toString('utf8');
52
+ };
53
+ }