@openchamber/web 1.23.2 → 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 (179) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-DdNGwbBw.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-Chzx5Y6N.js → JsonTreeView-D_4G5X6-.js} +1 -1
  8. package/dist/assets/LinearIssuesView-1uKhePfH.js +1 -0
  9. package/dist/assets/{MarkdownImageGallery-CugnrZ6f.js → MarkdownImageGallery-Ix7N_2wp.js} +1 -1
  10. package/dist/assets/MarkdownRendererImpl-Deel_y5S.js +12 -0
  11. package/dist/assets/{OnboardingScreen-hH9xcTjA.js → OnboardingScreen-ToIakxb_.js} +1 -1
  12. package/dist/assets/{PatchDiff-DRgNYc9l.js → PatchDiff-BjMgezr1.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-ZT2CKuzJ.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-oWxWCu-4.js → ToolPartDiffPreview-BxZJCU28.js} +2 -2
  20. package/dist/assets/{VirtualizedFileDiff-CiyrAq_I.js → VirtualizedFileDiff-DCXjBGRf.js} +3 -3
  21. package/dist/assets/{WalkthroughView-CKTevaea.js → WalkthroughView-CfIPvWWa.js} +2 -2
  22. package/dist/assets/appThemeRegistry-DDROzcUO.js +1 -0
  23. package/dist/assets/{computeVirtualFileMetrics-SUWoTyPe.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-C4jJ3Ur5.js → index-WjufPkIV.js} +1 -1
  30. package/dist/assets/{isDiffPlainText-DfG0cZxr.js → isDiffPlainText-D9faP70y.js} +1 -1
  31. package/dist/assets/{isFilePlainText-CyNivOCU.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-B8cGozKr.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-kyGrWGsn.js → markdownCore-DPrwM1rU.js} +5 -5
  38. package/dist/assets/{miniChat-Cay99IxR.js → miniChat-Dz_bPgMc.js} +2 -2
  39. package/dist/assets/{mobile-Zfhix7nz.js → mobile-BbZPBJrK.js} +2 -2
  40. package/dist/assets/{patchFileDiff-CJ5AN9Ql.js → patchFileDiff-BvU6KOQC.js} +3 -3
  41. package/dist/assets/pl-CX-_ROkr.js +16 -0
  42. package/dist/assets/{pt-BR-CLosVawq.js → pt-BR-DhRR1arx.js} +4 -4
  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-CGFV4Pap.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-DgCHy6Mr.js → useAppFontEffects-hfv2s6mZ.js} +198 -147
  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-ES33GhKK.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-strip-json-comments-5dJlOkP1.js +4 -0
  59. package/dist/assets/{vendor-zod-B6551dwG.js → vendor-zod-fZppILAM.js} +4 -4
  60. package/dist/assets/{web-components-CJZwV5BE.js → web-components-U-hWbgJo.js} +2 -2
  61. package/dist/assets/zh-CN-BWvlPHY-.js +16 -0
  62. package/dist/assets/zh-TW-CRp5dJU2.js +16 -0
  63. package/dist/index.html +4 -4
  64. package/dist/mini-chat.html +4 -4
  65. package/dist/mobile.html +4 -4
  66. package/package.json +7 -5
  67. package/server/built-in-extensions/registry.json +4 -0
  68. package/server/index.d.ts +2 -0
  69. package/server/index.js +15 -3
  70. package/server/lib/fs/DOCUMENTATION.md +8 -0
  71. package/server/lib/fs/git-process.test.js +77 -0
  72. package/server/lib/fs/routes.js +2 -1
  73. package/server/lib/fs/search.js +2 -1
  74. package/server/lib/git/DOCUMENTATION.md +3 -1
  75. package/server/lib/git/routes.js +16 -3
  76. package/server/lib/git/service.js +112 -8
  77. package/server/lib/git/service.test.js +127 -0
  78. package/server/lib/guests/DOCUMENTATION.md +66 -0
  79. package/server/lib/guests/auth-store.js +184 -0
  80. package/server/lib/guests/auth-store.test.js +112 -0
  81. package/server/lib/guests/builtins.js +34 -0
  82. package/server/lib/guests/builtins.test.js +174 -0
  83. package/server/lib/guests/catalog.js +466 -0
  84. package/server/lib/guests/catalog.test.js +390 -0
  85. package/server/lib/guests/clone.js +297 -0
  86. package/server/lib/guests/extract-zip.js +136 -0
  87. package/server/lib/guests/extract-zip.test.js +109 -0
  88. package/server/lib/guests/files.js +308 -0
  89. package/server/lib/guests/files.test.js +262 -0
  90. package/server/lib/guests/grant-scope.js +81 -0
  91. package/server/lib/guests/grant-scope.test.js +75 -0
  92. package/server/lib/guests/host-session.js +73 -0
  93. package/server/lib/guests/host-session.test.js +30 -0
  94. package/server/lib/guests/html-styles.js +6 -0
  95. package/server/lib/guests/html-styles.test.js +45 -0
  96. package/server/lib/guests/html-tokens.js +73 -0
  97. package/server/lib/guests/html-tokens.test.js +53 -0
  98. package/server/lib/guests/install.js +406 -0
  99. package/server/lib/guests/install.test.js +338 -0
  100. package/server/lib/guests/oauth.js +501 -0
  101. package/server/lib/guests/oauth.test.js +481 -0
  102. package/server/lib/guests/persist.js +336 -0
  103. package/server/lib/guests/persist.test.js +288 -0
  104. package/server/lib/guests/request.js +112 -0
  105. package/server/lib/guests/request.test.js +206 -0
  106. package/server/lib/guests/routes.js +838 -0
  107. package/server/lib/guests/service.js +538 -0
  108. package/server/lib/guests/service.test.js +277 -0
  109. package/server/lib/guests/sockets.js +129 -0
  110. package/server/lib/guests/sockets.test.js +110 -0
  111. package/server/lib/guests/ssh-install.test.js +188 -0
  112. package/server/lib/guests/storage.js +68 -0
  113. package/server/lib/guests/storage.test.js +59 -0
  114. package/server/lib/guests/updates.js +294 -0
  115. package/server/lib/guests/updates.test.js +334 -0
  116. package/server/lib/guests/upload.js +50 -0
  117. package/server/lib/guests/upload.test.js +131 -0
  118. package/server/lib/linear/DOCUMENTATION.md +1 -1
  119. package/server/lib/openchamber-control/DOCUMENTATION.md +6 -0
  120. package/server/lib/openchamber-sessions/routes.js +44 -11
  121. package/server/lib/openchamber-sessions/routes.test.js +47 -0
  122. package/server/lib/opencode/DOCUMENTATION.md +40 -0
  123. package/server/lib/opencode/core-routes.js +39 -1
  124. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  125. package/server/lib/opencode/lifecycle-process.test.js +84 -0
  126. package/server/lib/opencode/lifecycle.js +54 -67
  127. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  128. package/server/lib/opencode/settings-normalization-runtime.test.js +13 -0
  129. package/server/lib/opencode/settings-registry.json +4 -0
  130. package/server/lib/opencode/shutdown-runtime.js +3 -0
  131. package/server/lib/opencode/shutdown-runtime.test.js +24 -0
  132. package/server/lib/opencode/theme-archive.js +53 -0
  133. package/server/lib/opencode/theme-catalog.js +171 -0
  134. package/server/lib/opencode/theme-catalog.test.js +125 -0
  135. package/server/lib/opencode/theme-import.test.js +144 -0
  136. package/server/lib/opencode/theme-runtime.js +100 -28
  137. package/server/lib/opencode/theme-runtime.test.js +15 -0
  138. package/server/lib/quota/DOCUMENTATION.md +0 -1
  139. package/server/lib/quota/providers/index.js +0 -7
  140. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  141. package/server/lib/terminal/runtime.js +17 -2
  142. package/server/lib/terminal/runtime.test.js +45 -0
  143. package/server/lib/ui-auth/ui-auth.js +43 -8
  144. package/server/lib/ui-auth/ui-auth.test.js +40 -0
  145. package/dist/assets/DiffView-GYriC0Wk.js +0 -4
  146. package/dist/assets/DirtyBranchSwitchDialog-Bv0C99hc.js +0 -1
  147. package/dist/assets/FilesView-2Lin13wx.js +0 -13
  148. package/dist/assets/GitView-9wKba3UO.js +0 -6
  149. package/dist/assets/LinearIssuesView-DXS9QJiR.js +0 -1
  150. package/dist/assets/MarkdownRendererImpl-CaMyct2Q.js +0 -12
  151. package/dist/assets/PlanView-DiTBm2BD.js +0 -5
  152. package/dist/assets/SettingsView-CN8VeM99.js +0 -28
  153. package/dist/assets/SettingsWindow-DisOghhD.js +0 -1
  154. package/dist/assets/ToolOutputDialog-BqiKydxR.js +0 -15
  155. package/dist/assets/appThemeRegistry-BK0dHKa6.js +0 -1
  156. package/dist/assets/de-DQWC94VK.js +0 -10
  157. package/dist/assets/es-DixFUD3m.js +0 -16
  158. package/dist/assets/fr-D6u8tvfA.js +0 -14
  159. package/dist/assets/index-BvpFzhLs.js +0 -40
  160. package/dist/assets/index-n5p3SnES.css +0 -1
  161. package/dist/assets/ja-4u4pCorB.js +0 -16
  162. package/dist/assets/ko-C27-LW_b.js +0 -16
  163. package/dist/assets/main-tEA-fFPg.js +0 -930
  164. package/dist/assets/pl-FtCjsNdW.js +0 -16
  165. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  166. package/dist/assets/renderElectronMiniChatApp-CuHOGlF4.js +0 -2
  167. package/dist/assets/renderMobileApp-C4X_KUH8.js +0 -25
  168. package/dist/assets/runtimeEndpointReset-CMg-KUx3.js +0 -41
  169. package/dist/assets/shikiHighlight-DdKWYWrV.js +0 -1
  170. package/dist/assets/tr-D2j6wUez.js +0 -7
  171. package/dist/assets/uk-C6IzmwM_.js +0 -16
  172. package/dist/assets/useGitComparison-BIaI0WZI.js +0 -1
  173. package/dist/assets/useInlineCommentController-2wcCtpM3.js +0 -2
  174. package/dist/assets/useRootScrollLock-CbWA03xR.js +0 -1
  175. package/dist/assets/vendor-framer-motion-livSKyyV.js +0 -1
  176. package/dist/assets/zh-CN-Wl6tIDz1.js +0 -16
  177. package/dist/assets/zh-TW-hgphoWSN.js +0 -16
  178. package/server/lib/quota/providers/crof.js +0 -96
  179. package/server/lib/quota/providers/crof.test.js +0 -98
@@ -1,3 +1,29 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+
4
+ const color = z.string().regex(/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i);
5
+ const role = z.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/).max(64);
6
+ const importedThemeSchema = z.object({
7
+ metadata: z.object({
8
+ name: z.string().trim().min(1).max(160),
9
+ author: z.string().max(160).optional(),
10
+ variant: z.enum(['light', 'dark']),
11
+ description: z.string().max(1024).default(''),
12
+ version: z.string().max(40).default('1.0.0'),
13
+ tags: z.array(z.string().max(40)).max(16).default([]),
14
+ }),
15
+ colors: z.record(role, z.record(role, z.union([color, z.record(role, color)]))),
16
+ });
17
+ const fileErrorSchema = z.object({ code: z.string() });
18
+
19
+ export class ThemeImportStorageError extends Error {
20
+ constructor(code, status) {
21
+ super(code);
22
+ this.code = code;
23
+ this.status = status;
24
+ }
25
+ }
26
+
1
27
  export const createThemeRuntime = (dependencies) => {
2
28
  const {
3
29
  fsPromises,
@@ -34,46 +60,24 @@ export const createThemeRuntime = (dependencies) => {
34
60
  const status = colors.status;
35
61
  const syntax = colors.syntax;
36
62
  const syntaxBase = syntax && typeof syntax === 'object' ? syntax.base : null;
37
- const syntaxHighlights = syntax && typeof syntax === 'object' ? syntax.highlights : null;
38
63
 
39
- if (!primary || !surface || !interactive || !status || !syntaxBase || !syntaxHighlights) {
64
+ if (!primary || !surface || !interactive || !status || !syntaxBase) {
40
65
  return null;
41
66
  }
42
67
 
43
- // Minimal fields required by CSSVariableGenerator and diff/syntax rendering.
68
+ // Authored inputs only. The UI resolves optional roles before rendering.
44
69
  const required = [
45
70
  primary.base,
46
- primary.foreground,
47
71
  surface.background,
48
72
  surface.foreground,
49
73
  surface.muted,
50
74
  surface.mutedForeground,
51
75
  surface.elevated,
52
- surface.elevatedForeground,
53
- surface.subtle,
54
76
  interactive.border,
55
- interactive.selection,
56
- interactive.selectionForeground,
57
- interactive.focusRing,
58
- interactive.hover,
59
77
  status.error,
60
- status.errorForeground,
61
- status.errorBackground,
62
- status.errorBorder,
63
78
  status.warning,
64
- status.warningForeground,
65
- status.warningBackground,
66
- status.warningBorder,
67
79
  status.success,
68
- status.successForeground,
69
- status.successBackground,
70
- status.successBorder,
71
80
  status.info,
72
- status.infoForeground,
73
- status.infoBackground,
74
- status.infoBorder,
75
- syntaxBase.background,
76
- syntaxBase.foreground,
77
81
  syntaxBase.keyword,
78
82
  syntaxBase.string,
79
83
  syntaxBase.number,
@@ -82,9 +86,6 @@ export const createThemeRuntime = (dependencies) => {
82
86
  syntaxBase.type,
83
87
  syntaxBase.comment,
84
88
  syntaxBase.operator,
85
- syntaxHighlights.diffAdded,
86
- syntaxHighlights.diffRemoved,
87
- syntaxHighlights.lineNumber,
88
89
  ];
89
90
 
90
91
  if (!required.every(isValidThemeColor)) {
@@ -156,12 +157,83 @@ export const createThemeRuntime = (dependencies) => {
156
157
  return [];
157
158
  }
158
159
  logger.warn('[themes] Failed to list custom themes dir:', error);
159
- return [];
160
+ throw error;
161
+ }
162
+ };
163
+
164
+ const saveImportedTheme = async (raw) => {
165
+ const parsed = importedThemeSchema.safeParse(raw);
166
+ if (!parsed.success) throw new ThemeImportStorageError('invalid', 400);
167
+ const normalized = normalizeThemeJson({ ...parsed.data, metadata: { ...parsed.data.metadata, id: 'import' } });
168
+ if (!normalized) throw new ThemeImportStorageError('invalid', 400);
169
+ // The client supplies colors, never a filename or an overwrite target.
170
+ // Identical imports have the same ID, including retries after a lost reply.
171
+ const digest = createHash('sha256').update(JSON.stringify(parsed.data)).digest('hex').slice(0, 24);
172
+ const theme = { ...normalized, metadata: { ...normalized.metadata, id: `imported-vscode-${digest}` } };
173
+ const contents = `${JSON.stringify(theme, null, 2)}\n`;
174
+ if (Buffer.byteLength(contents, 'utf8') > maxThemeJsonBytes) throw new ThemeImportStorageError('size', 413);
175
+ await fsPromises.mkdir(themesDir, { recursive: true });
176
+ const target = path.join(themesDir, `${theme.metadata.id}.json`);
177
+ const temporary = path.join(themesDir, `${randomUUID()}.tmp`);
178
+ try {
179
+ await fsPromises.writeFile(temporary, contents, { flag: 'wx', mode: 0o600 });
180
+ try {
181
+ // Link publishes the complete file atomically and cannot overwrite an
182
+ // existing theme, even if another import finishes at the same time.
183
+ await fsPromises.link(temporary, target);
184
+ } catch (error) {
185
+ const parsedError = fileErrorSchema.safeParse(error);
186
+ if (!parsedError.success || parsedError.data.code !== 'EEXIST') throw error;
187
+ if (await fsPromises.readFile(target, 'utf8') !== contents) throw new ThemeImportStorageError('conflict', 409);
188
+ }
189
+ return theme;
190
+ } finally {
191
+ await fsPromises.unlink(temporary).catch((error) => {
192
+ const parsedError = fileErrorSchema.safeParse(error);
193
+ if (!parsedError.success || parsedError.data.code !== 'ENOENT') logger.warn('[themes] Failed to clean import temporary file');
194
+ });
160
195
  }
161
196
  };
162
197
 
163
198
  return {
164
199
  normalizeThemeJson,
165
200
  readCustomThemesFromDisk,
201
+ saveImportedTheme,
202
+ async deleteImportedTheme(id) {
203
+ if (!z.string().trim().min(1).max(256).safeParse(id).success) throw new ThemeImportStorageError('invalid', 400);
204
+ const matches = [];
205
+ let readFailure;
206
+ let entries;
207
+ try { entries = await fsPromises.readdir(themesDir, { withFileTypes: true }); }
208
+ catch (error) {
209
+ if (fileErrorSchema.safeParse(error).data?.code === 'ENOENT') return;
210
+ throw error;
211
+ }
212
+ for (const entry of entries) {
213
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
214
+ const target = path.join(themesDir, entry.name);
215
+ let text;
216
+ try {
217
+ const stat = await fsPromises.lstat(target);
218
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > maxThemeJsonBytes) continue;
219
+ text = await fsPromises.readFile(target, 'utf8');
220
+ } catch (error) {
221
+ if (fileErrorSchema.safeParse(error).data?.code !== 'ENOENT') readFailure = error;
222
+ continue;
223
+ }
224
+ let theme;
225
+ try { theme = normalizeThemeJson(JSON.parse(text)); }
226
+ catch { continue; }
227
+ if (theme?.metadata.id === id) matches.push(target);
228
+ }
229
+ // IDs identify themes, not filenames. Refuse ambiguous matches rather
230
+ // than deleting an arbitrary sibling or constructing a path from the ID.
231
+ if (matches.length > 1) throw new ThemeImportStorageError('conflict', 409);
232
+ if (!matches.length) {
233
+ if (readFailure) throw readFailure;
234
+ return;
235
+ }
236
+ await fsPromises.unlink(matches[0]);
237
+ },
166
238
  };
167
239
  };
@@ -90,6 +90,21 @@ const createTestRuntime = ({ entries, files, stats }) => createThemeRuntime({
90
90
 
91
91
  describe('theme runtime', () => {
92
92
  describe('readCustomThemesFromDisk', () => {
93
+ it('loads compact authored roles without requiring derived colors', async () => {
94
+ const theme = validTheme('compact');
95
+ theme.colors.primary = { base: '#ffffff' };
96
+ theme.colors.interactive = { border: '#444444' };
97
+ theme.colors.status = { error: '#ff0000', warning: '#ffaa00', success: '#00ff00', info: '#0000ff' };
98
+ delete theme.colors.syntax.highlights;
99
+ delete theme.colors.syntax.base.background;
100
+ delete theme.colors.syntax.base.foreground;
101
+ const runtime = createTestRuntime({
102
+ entries: [fileEntry('compact.json'), fileEntry('bad.json')],
103
+ files: { '/themes/compact.json': JSON.stringify(theme), '/themes/bad.json': '{broken' },
104
+ stats: { '/themes/compact.json': { isFile: () => true, size: 1024 }, '/themes/bad.json': { isFile: () => true, size: 10 } },
105
+ });
106
+ expect((await runtime.readCustomThemesFromDisk()).map((item) => item.metadata.id)).toEqual(['compact']);
107
+ });
93
108
  it('loads valid theme files', async () => {
94
109
  const runtime = createTestRuntime({
95
110
  entries: [fileEntry('direct.json')],
@@ -27,7 +27,6 @@ These provider IDs are currently dispatchable via `fetchQuotaForProvider(provide
27
27
  | `codex` | Codex | `providers/codex.js` | `openai`, `codex`, `chatgpt` |
28
28
  | `command-code` | Command Code | `providers/command-code.js` | `command-code` OAuth/API credential in OpenCode `auth.json`, or `COMMAND_CODE_API_KEY` |
29
29
  | `cursor` | Cursor | `providers/cursor.js` | Environment/token files, OpenChamber-managed credentials, or explicit one-time Cursor import |
30
- | `crof` | CrofAI | `providers/crof.js` | `crof` (API key under `key` or `token`) |
31
30
  | `deepseek` | DeepSeek | `providers/deepseek.js` | `deepseek` (API key under `key` or `token`) |
32
31
  | `exe-dev` | exe.dev | `providers/exe-dev.js` | Usage API token stored under `~/.config/openchamber/quota/` |
33
32
  | `google` | Google | `providers/google/index.js` | `google`, `google.oauth`, Antigravity accounts file |
@@ -11,7 +11,6 @@ import * as claude from './claude/index.js';
11
11
  import * as clinePass from './cline-pass.js';
12
12
  import * as codex from './codex.js';
13
13
  import * as copilot from './copilot.js';
14
- import * as crof from './crof.js';
15
14
  import * as cursor from './cursor.js';
16
15
  import * as deepseek from './deepseek.js';
17
16
  import * as exeDev from './exe-dev.js';
@@ -50,12 +49,6 @@ const registry = {
50
49
  isConfigured: codex.isConfigured,
51
50
  fetchQuota: codex.fetchQuota
52
51
  },
53
- crof: {
54
- providerId: crof.providerId,
55
- providerName: crof.providerName,
56
- isConfigured: crof.isConfigured,
57
- fetchQuota: crof.fetchQuota
58
- },
59
52
  cursor: {
60
53
  providerId: cursor.providerId,
61
54
  providerName: cursor.providerName,
@@ -37,8 +37,10 @@ HTTP remains the authenticated command plane for create, resize, appearance upda
37
37
  - Deduplicated create responses may describe another client's execution. Cancellation cleanup closes only the terminal ID allocated for the cancelled request; it never closes an adopted peer execution.
38
38
  - Create and restart validate the working directory with a real `stat` and answer HTTP 400 `Invalid working directory` when it is not a directory. When the path does not exist at all (`ENOENT`/`ENOTDIR`, a worktree deleted outside OpenChamber) the body also carries `code: "TERMINAL_CWD_MISSING"`. The client shows the failure without moving the session. The runtime never substitutes a parent directory on its own.
39
39
  - Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID. Command-mode sessions reject restart with HTTP 400 instead of silently turning into interactive shells with stale action metadata.
40
+ - A restart rechecks session ownership before and after PTY creation. Close, force-kill, idle removal, or shutdown can invalidate it while spawn is pending. A late replacement is terminated instead of being attached to a retired session.
40
41
  - A delete that arrives while create is still pending leaves a cancellation tombstone. When the PTY arrives, the runtime terminates it immediately, never inserts the session into the live map, and returns a create error while the delete still succeeds.
41
42
  - Close uses SIGTERM with bounded SIGKILL escalation. Force-kill, idle cleanup, and runtime shutdown terminate process groups immediately where supported. Removal explicitly sends a fatal scoped closure and evicts client projections even when a PTY backend fails to emit `onExit`; attached terminals are not considered idle.
43
+ - Shutdown is single-flight, rejects new creates, cancels pending creates, and waits for pending creates and restarts before clearing live sessions. A PTY that arrives during shutdown follows the same cancellation cleanup as a pending create that was explicitly closed.
42
44
 
43
45
  ## Security And Relay
44
46
 
@@ -100,6 +100,7 @@ export function createTerminalRuntime({
100
100
  const pendingTerminations = new Set();
101
101
  const runtime = typeof globalThis.Bun === 'undefined' ? 'node' : 'bun';
102
102
  let ptyProviderPromise = null;
103
+ let shutdownPromise = null;
103
104
  let wsServer = new WebSocketServer({ noServer: true, maxPayload: TERMINAL_WS_MAX_PAYLOAD_BYTES });
104
105
  const shellResolver = createTerminalShellResolver({ fs, path, searchPathFor, isExecutable, buildAugmentedPath });
105
106
 
@@ -282,6 +283,7 @@ export function createTerminalRuntime({
282
283
  };
283
284
 
284
285
  const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false, mode, command, purpose }) => {
286
+ if (shutdownPromise) throw new Error('Terminal runtime is shutting down');
285
287
  if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
286
288
  if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
287
289
  const normalizedShell = normalizeTerminalShell(shell);
@@ -507,10 +509,15 @@ export function createTerminalRuntime({
507
509
  const previousRestart = pendingSessionRestarts.get(session.id) ?? Promise.resolve();
508
510
  const restart = previousRestart.catch(() => {}).then(async () => {
509
511
  await validateCwd(cwd);
512
+ if (shutdownPromise || sessions.get(session.id) !== session) throw new Error('Terminal session was closed during restart');
510
513
  if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
511
514
  if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
512
515
  const oldProcess = session.process;
513
516
  const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell });
517
+ if (shutdownPromise || sessions.get(session.id) !== session) {
518
+ await terminateProcess(spawned.process, true);
519
+ throw new Error('Terminal session was closed during restart');
520
+ }
514
521
  session.process = spawned.process; session.backend = spawned.backend; session.shell = spawned.shell; session.loginShell = spawned.loginShell; session.cwd = cwd; session.cols = cols; session.rows = rows;
515
522
  session.history = ''; session.pendingHistoryControlSequence = ''; session.pendingThemeControlSequence = ''; session.themeModeEnabled = false; session.status = 'running'; session.exitCode = null; session.signal = null; session.eventQueue.length = 0;
516
523
  session.themeMode = themeMode === 'light' ? 'light' : 'dark'; session.terminalBackground = terminalBackground; session.terminalForeground = terminalForeground;
@@ -560,9 +567,13 @@ export function createTerminalRuntime({
560
567
  }
561
568
  }, 5 * 60 * 1000);
562
569
 
563
- const shutdown = async () => {
570
+ const stop = async () => {
564
571
  server.off('upgrade', upgradeHandler); clearInterval(idleSweep);
565
- await Promise.allSettled([...pendingSessionRestarts.values()]);
572
+ for (const pending of pendingSessionCreates.values()) pending.cancelled = true;
573
+ await Promise.allSettled([
574
+ ...[...pendingSessionCreates.values()].map((pending) => pending.promise),
575
+ ...pendingSessionRestarts.values(),
576
+ ]);
566
577
  for (const session of sessions.values()) void terminateProcess(session.process, true);
567
578
  sessions.clear();
568
579
  await Promise.allSettled([...pendingTerminations]);
@@ -574,5 +585,9 @@ export function createTerminalRuntime({
574
585
  ]);
575
586
  wsServer = null;
576
587
  };
588
+ const shutdown = () => {
589
+ if (!shutdownPromise) shutdownPromise = stop();
590
+ return shutdownPromise;
591
+ };
577
592
  return { shutdown };
578
593
  }
@@ -210,6 +210,51 @@ describe('terminal runtime', () => {
210
210
  } finally { await harness.runtime.shutdown(); }
211
211
  });
212
212
 
213
+ it('reaps a pending create during shutdown and rejects later creates', async () => {
214
+ const gate = deferred();
215
+ const harness = createHarness({ spawnDeferred: gate });
216
+ const create = harness.routes.post.get('/api/terminal/create');
217
+ const response = createResponse();
218
+ const creation = create({ body: { sessionId: 'pending', cwd: '/repo' } }, response);
219
+ const closing = harness.runtime.shutdown();
220
+ gate.resolve();
221
+ await Promise.all([creation, closing]);
222
+ expect(harness.processes).toHaveLength(1);
223
+ expect(harness.processes[0].killed).toBe(true);
224
+ expect(response.statusCode).toBe(400);
225
+ const later = createResponse();
226
+ await create({ body: { sessionId: 'later', cwd: '/repo' } }, later);
227
+ expect(later.statusCode).toBe(400);
228
+ expect(harness.processes).toHaveLength(1);
229
+ await harness.runtime.shutdown();
230
+ });
231
+
232
+ for (const removal of ['close', 'force-kill']) {
233
+ it(`reaps a replacement PTY when ${removal} wins a pending restart`, async () => {
234
+ const gate = { promise: Promise.resolve() };
235
+ const harness = createHarness({ spawnDeferred: gate });
236
+ try {
237
+ await harness.routes.post.get('/api/terminal/create')({ body: { sessionId: 'terminal', cwd: '/repo' } }, createResponse());
238
+ const replacement = deferred();
239
+ gate.promise = replacement.promise;
240
+ const response = createResponse();
241
+ const restarting = harness.routes.post.get('/api/terminal/:sessionId/restart')({ params: { sessionId: 'terminal' }, body: {} }, response);
242
+ await new Promise((resolve) => setImmediate(resolve));
243
+ const removed = createResponse();
244
+ if (removal === 'close') {
245
+ await harness.routes.delete.get('/api/terminal/:sessionId')({ params: { sessionId: 'terminal' } }, removed);
246
+ } else {
247
+ harness.routes.post.get('/api/terminal/force-kill')({ body: { sessionId: 'terminal' } }, removed);
248
+ }
249
+ replacement.resolve();
250
+ await restarting;
251
+ expect(harness.processes).toHaveLength(2);
252
+ expect(harness.processes.every((child) => child.killed)).toBe(true);
253
+ expect(response.statusCode).toBe(400);
254
+ } finally { await harness.runtime.shutdown(); }
255
+ });
256
+ }
257
+
213
258
  it('retains completed output when the replacement command fails to start', async () => {
214
259
  let available = true;
215
260
  const harness = createHarness({ fs: { promises: { stat: async () => ({ isDirectory: () => available }) } } });
@@ -291,6 +291,25 @@ const isWebSocketUpgrade = (req) => {
291
291
  return String(upgradeValue || '').toLowerCase() === 'websocket';
292
292
  };
293
293
 
294
+ const GUEST_URL_AUTH_SCOPE = /^guest:([a-z][a-z0-9-]*)$/;
295
+
296
+ /**
297
+ * A URL token scope narrows where the token is accepted. `guest:<id>` is
298
+ * minted for a guest iframe and only opens that guest's own package files:
299
+ * the iframe URL is readable by the guest's script, so the token must be
300
+ * worthless anywhere else.
301
+ * @returns {{ kind: 'guest', id: string } | null | undefined} `undefined` when the value is not a scope
302
+ */
303
+ const parseUrlAuthScope = (value) => {
304
+ const raw = Array.isArray(value) ? value[0] : value;
305
+ if (raw === undefined || raw === null || raw === '') return null;
306
+ if (typeof raw !== 'string') return undefined;
307
+ const match = raw.trim().match(GUEST_URL_AUTH_SCOPE);
308
+ return match ? { kind: 'guest', id: match[1] } : undefined;
309
+ };
310
+
311
+ const isGuestScopedPath = (pathname, guestId) => pathname.startsWith(`/api/guests/${guestId}/`);
312
+
294
313
  const isUrlAuthReadableHttpPath = (pathname) => {
295
314
  return pathname === '/api/event'
296
315
  || pathname === '/api/global/event'
@@ -301,7 +320,9 @@ const isUrlAuthReadableHttpPath = (pathname) => {
301
320
  || pathname === '/api/fs/serve'
302
321
  || pathname.startsWith('/api/fs/serve/')
303
322
  || pathname.startsWith('/api/preview/proxy/')
304
- || /^\/api\/projects\/[^/]+\/icon$/.test(pathname);
323
+ || /^\/api\/projects\/[^/]+\/icon$/.test(pathname)
324
+ || pathname === '/api/guests'
325
+ || /^\/api\/guests\/[a-z][a-z0-9-]*\//.test(pathname);
305
326
  };
306
327
 
307
328
  const isUrlAuthWebSocketPath = (pathname) => {
@@ -314,9 +335,12 @@ const isUrlAuthWebSocketPath = (pathname) => {
314
335
  || pathname.startsWith('/api/preview/proxy/');
315
336
  };
316
337
 
317
- const canUseUrlAuthTokenForRequest = (req) => {
338
+ const canUseUrlAuthTokenForRequest = (req, scope = null) => {
318
339
  const method = typeof req?.method === 'string' ? req.method.toUpperCase() : 'GET';
319
340
  const pathname = getRequestPathname(req);
341
+ if (scope?.kind === 'guest') {
342
+ return !isWebSocketUpgrade(req) && method === 'GET' && isGuestScopedPath(pathname, scope.id);
343
+ }
320
344
  if (isWebSocketUpgrade(req)) {
321
345
  return isUrlAuthWebSocketPath(pathname);
322
346
  }
@@ -425,16 +449,15 @@ export const createUiAuth = ({
425
449
  }
426
450
  };
427
451
 
428
- const issueUrlAuthTokenForSession = (sessionToken) => {
452
+ const issueUrlAuthTokenForSession = (sessionToken, scope = null) => {
429
453
  sweepUrlAuthTokens();
430
454
  const token = `${URL_AUTH_TOKEN_PREFIX}${crypto.randomBytes(24).toString('base64url')}`;
431
455
  const expiresAt = Date.now() + URL_AUTH_TOKEN_TTL_MS;
432
- urlAuthTokens.set(token, { sessionToken, expiresAt });
456
+ urlAuthTokens.set(token, { sessionToken, expiresAt, scope });
433
457
  return { token, expiresAt };
434
458
  };
435
459
 
436
460
  const authenticateUrlAuthToken = (req) => {
437
- if (!canUseUrlAuthTokenForRequest(req)) return null;
438
461
  const token = getUrlAuthTokenFromRequest(req);
439
462
  if (!token || !token.startsWith(URL_AUTH_TOKEN_PREFIX)) return null;
440
463
  const entry = urlAuthTokens.get(token);
@@ -442,9 +465,13 @@ export const createUiAuth = ({
442
465
  urlAuthTokens.delete(token);
443
466
  return null;
444
467
  }
468
+ if (!canUseUrlAuthTokenForRequest(req, entry.scope)) return null;
445
469
  return { ok: true, sessionToken: entry.sessionToken || 'url:authenticated' };
446
470
  };
447
471
 
472
+ /** Scope requested on `POST /auth/url-token`: `?scope=guest:<id>` or `{ scope }` in the body. */
473
+ const readRequestedUrlAuthScope = (req) => parseUrlAuthScope(req?.body?.scope ?? req?.query?.scope);
474
+
448
475
  const authenticateClientRequest = async (req, { allowUrlToken = true } = {}) => {
449
476
  if (allowUrlToken) {
450
477
  const urlAuth = authenticateUrlAuthToken(req);
@@ -566,17 +593,21 @@ export const createUiAuth = ({
566
593
  res.status(400).json({ error: 'UI password not configured' });
567
594
  },
568
595
  handleUrlAuthToken: async (req, res) => {
596
+ const scope = readRequestedUrlAuthScope(req);
597
+ if (scope === undefined) {
598
+ return res.status(400).json({ error: 'Unknown URL token scope' });
599
+ }
569
600
  const clientAuth = await authenticateClientRequest(req, { allowUrlToken: false });
570
601
  if (clientAuth) {
571
602
  res.setHeader('Cache-Control', 'no-store');
572
- return res.json(issueUrlAuthTokenForSession(clientSessionToken(clientAuth)));
603
+ return res.json(issueUrlAuthTokenForSession(clientSessionToken(clientAuth), scope));
573
604
  }
574
605
  if (requireClientAuth) {
575
606
  return res.status(401).json({ error: 'Client authentication required', locked: true, clientAuthRequired: true });
576
607
  }
577
608
  const sessionToken = await ensureSessionToken(req, res);
578
609
  res.setHeader('Cache-Control', 'no-store');
579
- return res.json(issueUrlAuthTokenForSession(sessionToken));
610
+ return res.json(issueUrlAuthTokenForSession(sessionToken, scope));
580
611
  },
581
612
  handlePasskeyStatus: (_req, res) => {
582
613
  res.json({ enabled: false, hasPasskeys: false, passkeyCount: 0, rpID: null });
@@ -799,13 +830,17 @@ export const createUiAuth = ({
799
830
  };
800
831
 
801
832
  const handleUrlAuthToken = async (req, res) => {
833
+ const scope = readRequestedUrlAuthScope(req);
834
+ if (scope === undefined) {
835
+ return res.status(400).json({ error: 'Unknown URL token scope' });
836
+ }
802
837
  const sessionToken = await resolveAuthenticatedSessionToken(req, { allowUrlToken: false });
803
838
  if (!sessionToken) {
804
839
  clearSessionCookie(req, res);
805
840
  return respondUnauthorized(req, res);
806
841
  }
807
842
  res.setHeader('Cache-Control', 'no-store');
808
- return res.json(issueUrlAuthTokenForSession(sessionToken));
843
+ return res.json(issueUrlAuthTokenForSession(sessionToken, scope));
809
844
  };
810
845
 
811
846
  const handleSessionCreate = async (req, res) => {
@@ -213,6 +213,46 @@ describe('ui auth client credential seam', () => {
213
213
  });
214
214
  expect(mountedServeCalled).toBe(true);
215
215
 
216
+ const guestReq = { method: 'GET', path: '/api/guests/hello/panel/index.html', url: `/api/guests/hello/panel/index.html?oc_url_token=${encodeURIComponent(urlToken)}`, headers: {} };
217
+ const guestRes = createResponse();
218
+ let guestCalled = false;
219
+ await auth.requireAuth(guestReq, guestRes, () => {
220
+ guestCalled = true;
221
+ });
222
+ expect(guestCalled).toBe(true);
223
+
224
+ // A guest-scoped token opens only that guest's files. It is the token a
225
+ // sandboxed guest page can read from its own URL, so it must fail on every
226
+ // system path and on another guest's files.
227
+ const guestMintReq = { method: 'POST', path: '/auth/url-token', query: { scope: 'guest:hello' }, headers: { authorization: 'Bearer client-token', accept: 'application/json' } };
228
+ const guestMintRes = createResponse();
229
+ await auth.handleUrlAuthToken(guestMintReq, guestMintRes);
230
+ const guestToken = guestMintRes.body.token;
231
+ expect(typeof guestToken).toBe('string');
232
+ const guestScopedReq = { method: 'GET', path: '/api/guests/hello/panel/main.js', url: `/api/guests/hello/panel/main.js?oc_url_token=${encodeURIComponent(guestToken)}`, headers: {} };
233
+ let guestScopedCalled = false;
234
+ await auth.requireAuth(guestScopedReq, createResponse(), () => {
235
+ guestScopedCalled = true;
236
+ });
237
+ expect(guestScopedCalled).toBe(true);
238
+ for (const forbidden of [
239
+ { method: 'GET', path: '/api/fs/raw', url: `/api/fs/raw?path=%2Ftmp%2Fimage.png&oc_url_token=${encodeURIComponent(guestToken)}` },
240
+ { method: 'GET', path: '/api/event', url: `/api/event?oc_url_token=${encodeURIComponent(guestToken)}` },
241
+ { method: 'GET', path: '/api/guests/other/panel/main.js', url: `/api/guests/other/panel/main.js?oc_url_token=${encodeURIComponent(guestToken)}` },
242
+ { method: 'GET', path: '/api/guests', url: `/api/guests?oc_url_token=${encodeURIComponent(guestToken)}` },
243
+ ]) {
244
+ const forbiddenRes = createResponse();
245
+ let forbiddenCalled = false;
246
+ await auth.requireAuth({ ...forbidden, headers: {} }, forbiddenRes, () => {
247
+ forbiddenCalled = true;
248
+ });
249
+ expect(forbiddenCalled).toBe(false);
250
+ expect(forbiddenRes.statusCode).toBe(401);
251
+ }
252
+ const badScopeRes = createResponse();
253
+ await auth.handleUrlAuthToken({ ...guestMintReq, query: { scope: 'admin' } }, badScopeRes);
254
+ expect(badScopeRes.statusCode).toBe(400);
255
+
216
256
  const dictationWsReq = {
217
257
  method: 'GET',
218
258
  path: '/api/dictation/ws',