@openchamber/web 1.20.0 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/bin/cli.test.js +35 -0
  2. package/bin/lib/DOCUMENTATION.md +12 -0
  3. package/bin/lib/cli-settings-accessors.js +111 -0
  4. package/bin/lib/cli-settings-accessors.test.js +189 -0
  5. package/bin/lib/cli-startup.js +29 -9
  6. package/bin/lib/commands-connect-url.js +12 -14
  7. package/dist/assets/{CodeMirrorCommentWidgets-C36E738Y.js → CodeMirrorCommentWidgets-BGj8TJxW.js} +1 -1
  8. package/dist/assets/CommitSection-DwGiXyjf.js +1 -0
  9. package/dist/assets/DiffView-Db6bjVv1.js +4 -0
  10. package/dist/assets/FilesView-DQOa7Lgz.js +17 -0
  11. package/dist/assets/GitView-CHzJxTi0.js +6 -0
  12. package/dist/assets/{JsonTreeView-KnXFN2A-.js → JsonTreeView-CggOsLot.js} +1 -1
  13. package/dist/assets/MarkdownImageGallery-DoZpaHev.js +1 -0
  14. package/dist/assets/MarkdownRendererImpl-B5Y5xCOz.js +12 -0
  15. package/dist/assets/OnboardingScreen-C98d69Fp.js +1 -0
  16. package/dist/assets/{PatchDiff-BzVOVog8.js → PatchDiff-DJYMUiXA.js} +1 -1
  17. package/dist/assets/PierreDiffViewer-CY2bx_SB.js +157 -0
  18. package/dist/assets/PlanView-PkiOY_9H.js +5 -0
  19. package/dist/assets/SettingsView-D-K3ELCM.js +28 -0
  20. package/dist/assets/SettingsWindow-oyOm2fHR.js +1 -0
  21. package/dist/assets/{ToolOutputDialog-BB1c--Zr.js → ToolOutputDialog-lKyeQTPL.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-DaOIDISD.js → ToolPartDiffPreview-C7kBQNAA.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-lESMT-2b.js → VirtualizedFileDiff-BP7ebDFF.js} +4 -4
  24. package/dist/assets/{Virtualizer-X_7XPoTH.js → Virtualizer-CZlLSacm.js} +1 -1
  25. package/dist/assets/Virtualizer-D_a8gKmg.js +1 -0
  26. package/dist/assets/{WalkthroughView-CaSYE0lw.js → WalkthroughView-MuJodAHD.js} +2 -2
  27. package/dist/assets/{computeVirtualFileMetrics-DkRR5b75.js → computeVirtualFileMetrics-CZ0xPeaT.js} +2 -2
  28. package/dist/assets/contextPanelEmbeddedChat-C9abMBTb.js +1 -0
  29. package/dist/assets/de-CEoCz3j6.js +9 -0
  30. package/dist/assets/es-DwyXCqaL.js +15 -0
  31. package/dist/assets/fr-CS7Csln9.js +13 -0
  32. package/dist/assets/index-CUKcHnUA.css +1 -0
  33. package/dist/assets/index-CaPAjwXQ.js +1 -0
  34. package/dist/assets/index-DIvDEKE-.js +7 -0
  35. package/dist/assets/{isDiffPlainText-BG53Ixxy.js → isDiffPlainText-ZBvDxhVB.js} +1 -1
  36. package/dist/assets/{isFilePlainText-BbV-39jl.js → isFilePlainText-DiLRrkJr.js} +1 -1
  37. package/dist/assets/ja-vnwqLcx6.js +15 -0
  38. package/dist/assets/ko-CXuSfZv5.js +15 -0
  39. package/dist/assets/main-D5RWr6sJ.js +2 -0
  40. package/dist/assets/main-DLlfDjQ_.js +926 -0
  41. package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
  42. package/dist/assets/markdownCore-CcTcLsQF.js +3 -0
  43. package/dist/assets/{miniChat-ldEghBLB.js → miniChat-CqR3icsk.js} +2 -2
  44. package/dist/assets/mobile-RN_UTTlB.js +2 -0
  45. package/dist/assets/{patchFileDiff-BcFaMtMu.js → patchFileDiff-CjRR5ESs.js} +1 -1
  46. package/dist/assets/pl-BJxry0Mi.js +15 -0
  47. package/dist/assets/pt-BR-DxLmkhdv.js +15 -0
  48. package/dist/assets/renderElectronMiniChatApp-1wC94fQK.js +2 -0
  49. package/dist/assets/renderMobileApp-ltva2Plg.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-D6SmNZaP.js +15 -0
  51. package/dist/assets/scheduledTasksApi-mjMDet_H.js +1 -0
  52. package/dist/assets/{shikiHighlight-DCT2Sq_z.js → shikiHighlight-fGmFkxAM.js} +1 -1
  53. package/dist/assets/tr-5Mk_hQ2Q.js +6 -0
  54. package/dist/assets/uk-ClgQjmlw.js +15 -0
  55. package/dist/assets/{useAppFontEffects-B53Rb6m7.js → useAppFontEffects-KP8_yiGW.js} +176 -184
  56. package/dist/assets/useInlineCommentController-HIjtuhxD.js +2 -0
  57. package/dist/assets/useRootScrollLock-BSiQ5F75.js +1 -0
  58. package/dist/assets/{vendor-base-ui-DsHmyMwp.js → vendor-base-ui-BeMD8X_w.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-data-vch3tJ4c.js → vendor-codemirror-language-data-DrTPkHl4.js} +2 -2
  60. package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
  61. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
  62. package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
  63. package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
  64. package/dist/assets/{vendor-framer-motion-CRSgBxjL.js → vendor-framer-motion-livSKyyV.js} +1 -1
  65. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +1 -0
  66. package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
  67. package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
  68. package/dist/assets/{vendor-motion-dom-DJLgZh4Q.js → vendor-motion-dom-D_o3BTI3.js} +1 -1
  69. package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
  70. package/dist/assets/vendor-zod-BLfBSgBh.js +39 -0
  71. package/dist/assets/{web-components-pcwCTWjC.js → web-components-DOXvU-tB.js} +4 -4
  72. package/dist/assets/zh-CN-Ba6y8H-i.js +15 -0
  73. package/dist/assets/zh-TW-Dv8yyhN1.js +15 -0
  74. package/dist/index.html +7 -7
  75. package/dist/mini-chat.html +5 -5
  76. package/dist/mobile.html +5 -5
  77. package/dist/site.webmanifest +1 -1
  78. package/dist/sw.js +1 -1
  79. package/package.json +4 -4
  80. package/public/site.webmanifest +1 -1
  81. package/server/index.js +10 -2
  82. package/server/lib/client-auth/pairing.js +8 -7
  83. package/server/lib/client-auth/pairing.test.js +5 -1
  84. package/server/lib/client-auth/remote-clients.js +9 -1
  85. package/server/lib/client-auth/remote-clients.test.js +17 -0
  86. package/server/lib/cloudflare-tunnel.js +1 -1
  87. package/server/lib/fs/DOCUMENTATION.md +1 -0
  88. package/server/lib/fs/routes.js +21 -0
  89. package/server/lib/fs/routes.test.js +89 -3
  90. package/server/lib/git/DOCUMENTATION.md +4 -3
  91. package/server/lib/git/service.js +128 -6
  92. package/server/lib/git/service.test.js +191 -1
  93. package/server/lib/github/pr-status.js +10 -1
  94. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  95. package/server/lib/markdown-image-grants/routes.js +3 -1
  96. package/server/lib/markdown-image-grants/routes.test.js +14 -0
  97. package/server/lib/openchamber-sessions/routes.js +4 -1
  98. package/server/lib/openchamber-sessions/routes.test.js +23 -0
  99. package/server/lib/opencode/env-runtime.js +17 -1
  100. package/server/lib/opencode/env-runtime.test.js +56 -0
  101. package/server/lib/opencode/lifecycle.js +48 -9
  102. package/server/lib/opencode/lifecycle.test.js +125 -1
  103. package/server/lib/opencode/managed-process-registry.d.ts +13 -0
  104. package/server/lib/opencode/managed-process-registry.js +213 -163
  105. package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
  106. package/server/lib/opencode/project-directory-runtime.js +16 -11
  107. package/server/lib/opencode/project-directory-runtime.test.js +32 -12
  108. package/server/lib/opencode/pwa-manifest-routes.js +1 -1
  109. package/server/lib/opencode/routes-upgrade.test.js +96 -12
  110. package/server/lib/opencode/routes.js +53 -5
  111. package/server/lib/opencode/settings-helpers.js +3 -0
  112. package/server/lib/opencode/settings-helpers.test.js +10 -0
  113. package/server/lib/opencode/theme-runtime.js +1 -1
  114. package/server/lib/opencode/theme-runtime.test.js +129 -0
  115. package/server/lib/quota/DOCUMENTATION.md +19 -0
  116. package/server/lib/quota/providers/copilot.js +26 -10
  117. package/server/lib/quota/providers/copilot.test.js +78 -0
  118. package/server/lib/quota/providers/index.js +4 -18
  119. package/server/lib/relay/DOCUMENTATION.md +1 -1
  120. package/server/lib/relay/service.js +34 -2
  121. package/server/lib/relay/service.test.js +69 -0
  122. package/server/lib/session-goal/runtime.js +2 -1
  123. package/server/lib/session-goal/runtime.test.js +4 -2
  124. package/server/lib/small-model/DOCUMENTATION.md +11 -5
  125. package/server/lib/small-model/call.js +64 -20
  126. package/server/lib/small-model/call.test.js +184 -2
  127. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  128. package/server/lib/terminal/runtime.js +29 -1
  129. package/server/lib/terminal/runtime.test.js +26 -0
  130. package/server/lib/tunnels/install-help.js +2 -2
  131. package/server/lib/tunnels/install-help.test.js +9 -0
  132. package/server/lib/ui-auth/ui-auth.js +2 -2
  133. package/server/lib/ui-auth/ui-auth.test.js +2 -2
  134. package/server/lib/walkthrough/languages.js +1 -0
  135. package/dist/assets/CommitSection-C-F3AX6D.js +0 -1
  136. package/dist/assets/DiagramEditor-BPECg1jS.js +0 -1
  137. package/dist/assets/DiagramView-D0YNMix8.js +0 -1
  138. package/dist/assets/DiffView-BHWaMYCC.js +0 -4
  139. package/dist/assets/FilesView-NMBCW2Tm.js +0 -14
  140. package/dist/assets/GitView-Rp8P1KEI.js +0 -6
  141. package/dist/assets/MarkdownImageGallery-BMn3mtor.js +0 -1
  142. package/dist/assets/MarkdownRendererImpl-kD6N03pH.js +0 -12
  143. package/dist/assets/OnboardingScreen-CenIeD4v.js +0 -1
  144. package/dist/assets/PierreDiffViewer-Dlby4XqT.js +0 -136
  145. package/dist/assets/PlanView-Czu1KMJa.js +0 -4
  146. package/dist/assets/SessionSwitcherDropdown-IETz58DB.js +0 -1
  147. package/dist/assets/SettingsView-B6vmuf-c.js +0 -28
  148. package/dist/assets/SettingsWindow-CauZpdD3.js +0 -1
  149. package/dist/assets/contextPanelEmbeddedChat-BEARQjgn.js +0 -1
  150. package/dist/assets/de-DFdX3ABv.js +0 -9
  151. package/dist/assets/es-iC-FKvV9.js +0 -15
  152. package/dist/assets/fr-BBbi_1AL.js +0 -13
  153. package/dist/assets/index-BiEgzzkg.js +0 -1
  154. package/dist/assets/index-Cwmuwk3V.js +0 -7
  155. package/dist/assets/index-GNm1wgUH.css +0 -1
  156. package/dist/assets/ja-DQLQJL2J.js +0 -15
  157. package/dist/assets/ko-BeElEB4Y.js +0 -15
  158. package/dist/assets/main-Dpzo18z7.js +0 -2
  159. package/dist/assets/main-WMjtYzJs.js +0 -921
  160. package/dist/assets/markdownCore--tDmyI_v.js +0 -2
  161. package/dist/assets/mobile-Dk-VGreF.js +0 -2
  162. package/dist/assets/pl-CLHt2_vV.js +0 -15
  163. package/dist/assets/pt-BR-C_MPUq7e.js +0 -15
  164. package/dist/assets/renderElectronMiniChatApp-DIgCOmXY.js +0 -2
  165. package/dist/assets/renderMobileApp-CDfHS5rr.js +0 -25
  166. package/dist/assets/runtimeEndpointReset-ovNbaZ-x.js +0 -15
  167. package/dist/assets/scheduledTasksApi-BFSlqgnG.js +0 -1
  168. package/dist/assets/uk-PhsC-c4-.js +0 -15
  169. package/dist/assets/useInlineCommentController-DSfrIBKT.js +0 -2
  170. package/dist/assets/vendor-zod-C9ioTTSo.js +0 -39
  171. package/dist/assets/zh-CN-wF-NOFHM.js +0 -15
  172. package/dist/assets/zh-TW-4m4-A7rT.js +0 -15
  173. package/server/lib/quota/providers/command-code.js +0 -90
  174. package/server/lib/quota/providers/command-code.test.js +0 -85
@@ -164,6 +164,41 @@ ${desktopReturn ? `<a class="return" href="openchamber://focus/mcp-auth">Return
164
164
  return versions.sort((left, right) => compareVersions(right, left))[0];
165
165
  };
166
166
 
167
+ // OpenCode's `/global/upgrade` requires an explicit semver target and rejects
168
+ // a bodyless call, so "update to the latest" has to name the version. The
169
+ // release lookup is the same one the upgrade-status check already uses to
170
+ // decide there is anything to offer.
171
+ const resolveOpenCodeUpgradeTarget = async (requestedTarget) => {
172
+ if (typeof requestedTarget === 'string' && requestedTarget.trim().length > 0) {
173
+ return { resolved: true, target: requestedTarget.trim() };
174
+ }
175
+ try {
176
+ const latest = await fetchLatestOpenCodeVersion();
177
+ if (!latest) {
178
+ return { resolved: false, reason: 'The latest OpenCode version could not be determined.' };
179
+ }
180
+ return { resolved: true, target: latest };
181
+ } catch (error) {
182
+ return {
183
+ resolved: false,
184
+ reason: error instanceof Error ? error.message : 'The latest OpenCode version could not be determined.',
185
+ };
186
+ }
187
+ };
188
+
189
+ // OpenCode reports a rejected upgrade as `{ name, data: { message, kind } }`,
190
+ // which carries no `error` field. Reading only `error` left the user with the
191
+ // bare HTTP status text ("Bad Request") and nothing to act on.
192
+ const readOpenCodeUpgradeErrorMessage = (payload, response) => {
193
+ const candidates = [payload?.error, payload?.data?.message, payload?.message];
194
+ for (const candidate of candidates) {
195
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
196
+ return candidate.trim();
197
+ }
198
+ }
199
+ return response.statusText || 'Failed to upgrade OpenCode';
200
+ };
201
+
167
202
  const pruneExpiredPendingMcpAuthContexts = () => {
168
203
  const now = Date.now();
169
204
  for (const [state, entry] of pendingMcpAuthContextByState.entries()) {
@@ -218,10 +253,23 @@ ${desktopReturn ? `<a class="return" href="openchamber://focus/mcp-auth">Return
218
253
  });
219
254
  }
220
255
 
221
- const target = typeof req.body?.target === 'string' && req.body.target.trim().length > 0
222
- ? req.body.target.trim()
223
- : undefined;
256
+ const requestedTarget = req.body?.target;
257
+ // The target lookup reaches the network, so it runs inside the operation:
258
+ // the in-flight lock is taken synchronously above, and a second click
259
+ // cannot slip past while the release version is being resolved.
224
260
  const upgradeOperation = (async () => {
261
+ const targetResolution = await resolveOpenCodeUpgradeTarget(requestedTarget);
262
+ if (!targetResolution.resolved) {
263
+ return {
264
+ status: 502,
265
+ body: {
266
+ success: false,
267
+ code: 'OPENCODE_UPGRADE_TARGET_UNRESOLVED',
268
+ error: `Could not determine which OpenCode version to install: ${targetResolution.reason}`,
269
+ },
270
+ };
271
+ }
272
+
225
273
  const response = await fetch(buildOpenCodeUrl('/global/upgrade', ''), {
226
274
  method: 'POST',
227
275
  headers: {
@@ -229,7 +277,7 @@ ${desktopReturn ? `<a class="return" href="openchamber://focus/mcp-auth">Return
229
277
  Accept: 'application/json',
230
278
  ...getOpenCodeAuthHeaders(),
231
279
  },
232
- body: JSON.stringify(target ? { target } : {}),
280
+ body: JSON.stringify({ target: targetResolution.target }),
233
281
  });
234
282
  const payload = await response.json().catch(() => null);
235
283
  if (!response.ok) {
@@ -237,7 +285,7 @@ ${desktopReturn ? `<a class="return" href="openchamber://focus/mcp-auth">Return
237
285
  status: response.status,
238
286
  body: {
239
287
  success: false,
240
- error: payload?.error || response.statusText || 'Failed to upgrade OpenCode',
288
+ error: readOpenCodeUpgradeErrorMessage(payload, response),
241
289
  },
242
290
  };
243
291
  }
@@ -616,6 +616,9 @@ export const createSettingsHelpers = (dependencies) => {
616
616
  if (typeof candidate.terminalFontSize === 'number' && Number.isFinite(candidate.terminalFontSize)) {
617
617
  result.terminalFontSize = Math.max(9, Math.min(52, Math.round(candidate.terminalFontSize)));
618
618
  }
619
+ if (typeof candidate.editorFontSize === 'number' && Number.isFinite(candidate.editorFontSize)) {
620
+ result.editorFontSize = Math.max(9, Math.min(32, Math.round(candidate.editorFontSize)));
621
+ }
619
622
  if (typeof candidate.terminalShell === 'string') {
620
623
  const shell = candidate.terminalShell.trim().toLowerCase();
621
624
  if (TERMINAL_SHELL_VALUES.has(shell)) result.terminalShell = shell;
@@ -104,6 +104,16 @@ describe('settings helpers', () => {
104
104
  expect(helpers.sanitizeSettingsUpdate({ collapsibleUserMessages: 'true' })).toEqual({});
105
105
  });
106
106
 
107
+ it('sanitizes and returns the persisted editor font size', () => {
108
+ const helpers = createTestHelpers();
109
+
110
+ expect(helpers.sanitizeSettingsUpdate({ editorFontSize: 20.6 })).toEqual({ editorFontSize: 21 });
111
+ expect(helpers.sanitizeSettingsUpdate({ editorFontSize: 8 })).toEqual({ editorFontSize: 9 });
112
+ expect(helpers.sanitizeSettingsUpdate({ editorFontSize: 33 })).toEqual({ editorFontSize: 32 });
113
+ expect(helpers.sanitizeSettingsUpdate({ editorFontSize: Number.NaN })).toEqual({});
114
+ expect(helpers.formatSettingsResponse({ editorFontSize: 20 })).toMatchObject({ editorFontSize: 20 });
115
+ });
116
+
107
117
  it('accepts messageStreamTransport as a persisted shared setting', () => {
108
118
  const helpers = createTestHelpers();
109
119
 
@@ -116,7 +116,7 @@ export const createThemeRuntime = (dependencies) => {
116
116
  const seen = new Set();
117
117
 
118
118
  for (const entry of entries) {
119
- if (!entry.isFile()) continue;
119
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
120
120
  if (!entry.name.toLowerCase().endsWith('.json')) continue;
121
121
 
122
122
  const filePath = path.join(themesDir, entry.name);
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { createThemeRuntime } from './theme-runtime.js';
4
+
5
+ const validTheme = (id = 'custom-theme') => ({
6
+ metadata: {
7
+ id,
8
+ name: 'Custom Theme',
9
+ variant: 'dark',
10
+ },
11
+ colors: {
12
+ primary: {
13
+ base: '#ffffff',
14
+ foreground: '#000000',
15
+ },
16
+ surface: {
17
+ background: '#000000',
18
+ foreground: '#ffffff',
19
+ muted: '#111111',
20
+ mutedForeground: '#eeeeee',
21
+ elevated: '#222222',
22
+ elevatedForeground: '#dddddd',
23
+ subtle: '#333333',
24
+ },
25
+ interactive: {
26
+ border: '#444444',
27
+ selection: '#555555',
28
+ selectionForeground: '#ffffff',
29
+ focusRing: '#666666',
30
+ hover: '#777777',
31
+ },
32
+ status: {
33
+ error: '#ff0000',
34
+ errorForeground: '#ffffff',
35
+ errorBackground: '#330000',
36
+ errorBorder: '#660000',
37
+ warning: '#ffaa00',
38
+ warningForeground: '#000000',
39
+ warningBackground: '#332200',
40
+ warningBorder: '#664400',
41
+ success: '#00ff00',
42
+ successForeground: '#000000',
43
+ successBackground: '#003300',
44
+ successBorder: '#006600',
45
+ info: '#0000ff',
46
+ infoForeground: '#ffffff',
47
+ infoBackground: '#000033',
48
+ infoBorder: '#000066',
49
+ },
50
+ syntax: {
51
+ base: {
52
+ background: '#000000',
53
+ foreground: '#ffffff',
54
+ keyword: '#ff00ff',
55
+ string: '#00ff00',
56
+ number: '#ffaa00',
57
+ function: '#00ffff',
58
+ variable: '#ffffff',
59
+ type: '#ffff00',
60
+ comment: '#888888',
61
+ operator: '#ffffff',
62
+ },
63
+ highlights: {
64
+ diffAdded: '#003300',
65
+ diffRemoved: '#330000',
66
+ lineNumber: '#888888',
67
+ },
68
+ },
69
+ },
70
+ });
71
+
72
+ const fileEntry = (name, type = 'file') => ({
73
+ name,
74
+ isFile: () => type === 'file',
75
+ isDirectory: () => type === 'directory',
76
+ isSymbolicLink: () => type === 'symlink',
77
+ });
78
+
79
+ const createTestRuntime = ({ entries, files, stats }) => createThemeRuntime({
80
+ fsPromises: {
81
+ readdir: async () => entries,
82
+ stat: async (filePath) => stats[filePath],
83
+ readFile: async (filePath) => files[filePath],
84
+ },
85
+ path: { join: (...parts) => parts.join('/') },
86
+ themesDir: '/themes',
87
+ maxThemeJsonBytes: 512 * 1024,
88
+ logger: { warn: () => {} },
89
+ });
90
+
91
+ describe('theme runtime', () => {
92
+ describe('readCustomThemesFromDisk', () => {
93
+ it('loads valid theme files', async () => {
94
+ const runtime = createTestRuntime({
95
+ entries: [fileEntry('direct.json')],
96
+ files: { '/themes/direct.json': JSON.stringify(validTheme('direct-theme')) },
97
+ stats: { '/themes/direct.json': { isFile: () => true, size: 1024 } },
98
+ });
99
+
100
+ const themes = await runtime.readCustomThemesFromDisk();
101
+
102
+ expect(themes.map((theme) => theme.metadata.id)).toEqual(['direct-theme']);
103
+ });
104
+
105
+ it('loads JSON themes whose directory entry is a symbolic link', async () => {
106
+ const runtime = createTestRuntime({
107
+ entries: [fileEntry('linked.json', 'symlink')],
108
+ files: { '/themes/linked.json': JSON.stringify(validTheme('linked-theme')) },
109
+ stats: { '/themes/linked.json': { isFile: () => true, size: 1024 } },
110
+ });
111
+
112
+ const themes = await runtime.readCustomThemesFromDisk();
113
+
114
+ expect(themes.map((theme) => theme.metadata.id)).toEqual(['linked-theme']);
115
+ });
116
+
117
+ it('skips JSON directories after stat resolution', async () => {
118
+ const runtime = createTestRuntime({
119
+ entries: [fileEntry('directory.json', 'directory')],
120
+ files: { '/themes/directory.json': JSON.stringify(validTheme('directory-theme')) },
121
+ stats: { '/themes/directory.json': { isFile: () => false, size: 1024 } },
122
+ });
123
+
124
+ const themes = await runtime.readCustomThemesFromDisk();
125
+
126
+ expect(themes).toEqual([]);
127
+ });
128
+ });
129
+ });
@@ -97,6 +97,25 @@ In 2025/2026 MiniMax rebranded "Coding Plan" to "Token Plan" alongside the M3 mo
97
97
 
98
98
  The provider computes `usedPercent` from whichever of `used`/`remaining` is present (`used` takes precedence when both exist) rather than assuming one field name. Both `packages/web/server/lib/quota/providers/kimi.js` and `packages/vscode/src/quotaProviders.ts` (`fetchKimiQuota`) must stay in sync — the VS Code extension duplicates this parsing logic rather than importing it.
99
99
 
100
+ ## GitHub Copilot quota semantics
101
+
102
+ GitHub Copilot usage exposes only the `premium_interactions` snapshot as the
103
+ `premium_interactions` window. Shared UI labels that window **AI Credits** and treats it as
104
+ the provider's primary usage marker. Legacy chat-request quota and unlimited
105
+ completion quota are intentionally omitted. Keep
106
+ `packages/web/server/lib/quota/providers/copilot.js` and
107
+ `packages/vscode/src/quotaProviders.ts` in sync.
108
+
109
+ The `/copilot_internal/user` endpoint is undocumented; its quota semantics mirror
110
+ what `microsoft/vscode-copilot-chat` consumes (`CopilotUserQuotaInfo`). Each
111
+ snapshot carries `entitlement`, `remaining`, `unlimited`, and
112
+ `percent_remaining`. Providers must honor these rules:
113
+
114
+ - `unlimited: true` renders a percent-less window with an "Unlimited" value label.
115
+ - Percent math requires a positive `entitlement`; entitlements of `0`, `-1`, or null are unusable.
116
+ - When entitlement/remaining are unusable, fall back to `100 - percent_remaining`.
117
+ - Snapshots other than `premium_interactions` (legacy annual plans) yield zero windows.
118
+
100
119
  ## Notes for contributors
101
120
  - Keep provider IDs stable; clients use them directly.
102
121
  - Avoid adding alias-based dispatch in `fetchQuotaForProvider`; dispatch currently expects exact provider IDs.
@@ -13,14 +13,35 @@ const buildCopilotWindows = (payload) => {
13
13
  const resetAt = toTimestamp(payload?.quota_reset_date);
14
14
  const windows = {};
15
15
 
16
+ // Mirrors the quota semantics of microsoft/vscode-copilot-chat
17
+ // (CopilotUserQuotaInfo): each snapshot carries entitlement, remaining,
18
+ // unlimited, and percent_remaining. Unlimited plans report no usable
19
+ // entitlement; percent_remaining is a server-computed fallback.
16
20
  const addWindow = (label, snapshot) => {
17
21
  if (!snapshot) return;
22
+
23
+ if (snapshot.unlimited === true) {
24
+ windows[label] = toUsageWindow({
25
+ usedPercent: null,
26
+ windowSeconds: null,
27
+ resetAt,
28
+ valueLabel: 'Unlimited'
29
+ });
30
+ return;
31
+ }
32
+
18
33
  const entitlement = toNumber(snapshot.entitlement);
19
34
  const remaining = toNumber(snapshot.remaining);
20
- const usedPercent = entitlement && remaining !== null
21
- ? Math.max(0, 100 - (remaining / entitlement) * 100)
35
+ let usedPercent = entitlement !== null && entitlement > 0 && remaining !== null
36
+ ? Math.min(100, Math.max(0, 100 - (remaining / entitlement) * 100))
22
37
  : null;
23
- const valueLabel = entitlement !== null && remaining !== null
38
+ if (usedPercent === null) {
39
+ const percentRemaining = toNumber(snapshot.percent_remaining);
40
+ if (percentRemaining !== null) {
41
+ usedPercent = Math.min(100, Math.max(0, 100 - percentRemaining));
42
+ }
43
+ }
44
+ const valueLabel = entitlement !== null && entitlement > 0 && remaining !== null
24
45
  ? `${remaining.toFixed(0)} / ${entitlement.toFixed(0)} left`
25
46
  : null;
26
47
  windows[label] = toUsageWindow({
@@ -31,9 +52,7 @@ const buildCopilotWindows = (payload) => {
31
52
  });
32
53
  };
33
54
 
34
- addWindow('chat', quota.chat);
35
- addWindow('completions', quota.completions);
36
- addWindow('premium', quota.premium_interactions);
55
+ addWindow('premium_interactions', quota.premium_interactions);
37
56
 
38
57
  return windows;
39
58
  };
@@ -143,15 +162,12 @@ export const fetchQuotaAddon = async () => {
143
162
  }
144
163
 
145
164
  const payload = await response.json();
146
- const windows = buildCopilotWindows(payload);
147
- const premium = windows.premium ? { premium: windows.premium } : windows;
148
-
149
165
  return buildResult({
150
166
  providerId: providerIdAddon,
151
167
  providerName: providerNameAddon,
152
168
  ok: true,
153
169
  configured: true,
154
- usage: { windows: premium }
170
+ usage: { windows: buildCopilotWindows(payload) }
155
171
  });
156
172
  } catch (error) {
157
173
  return buildResult({
@@ -0,0 +1,78 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('../../opencode/auth.js', () => ({
4
+ readAuthFile: () => ({ 'github-copilot': { access: 'test-token' } }),
5
+ }));
6
+
7
+ import { fetchQuota, fetchQuotaAddon } from './copilot.js';
8
+
9
+ afterEach(() => {
10
+ vi.unstubAllGlobals();
11
+ });
12
+
13
+ const payload = {
14
+ quota_reset_date: '2026-09-01T00:00:00Z',
15
+ quota_snapshots: {
16
+ chat: { entitlement: 100, remaining: 80 },
17
+ completions: { entitlement: 1000, remaining: 900 },
18
+ premium_interactions: { entitlement: 300, remaining: 225 },
19
+ },
20
+ };
21
+
22
+ const mockResponse = (body = payload) => ({
23
+ ok: true,
24
+ status: 200,
25
+ json: async () => body,
26
+ });
27
+
28
+ describe('GitHub Copilot quota provider', () => {
29
+ it.each([
30
+ ['primary provider', fetchQuota],
31
+ ['add-on provider', fetchQuotaAddon],
32
+ ])('exposes only premium interactions for the %s', async (_name, fetchProviderQuota) => {
33
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse()));
34
+
35
+ const result = await fetchProviderQuota();
36
+
37
+ expect(result.ok).toBe(true);
38
+ expect(Object.keys(result.usage.windows)).toEqual(['premium_interactions']);
39
+ expect(result.usage.windows.premium_interactions.usedPercent).toBe(25);
40
+ expect(result.usage.windows.premium_interactions.valueLabel).toBe('225 / 300 left');
41
+ });
42
+
43
+ it.each([
44
+ ['primary provider', fetchQuota],
45
+ ['add-on provider', fetchQuotaAddon],
46
+ ])('reports unlimited plans without a percent for the %s', async (_name, fetchProviderQuota) => {
47
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
48
+ quota_reset_date: '2026-09-01T00:00:00Z',
49
+ quota_snapshots: {
50
+ premium_interactions: { unlimited: true, entitlement: -1, remaining: -1 },
51
+ },
52
+ })));
53
+
54
+ const result = await fetchProviderQuota();
55
+
56
+ expect(result.ok).toBe(true);
57
+ expect(result.usage.windows.premium_interactions.usedPercent).toBeNull();
58
+ expect(result.usage.windows.premium_interactions.valueLabel).toBe('Unlimited');
59
+ });
60
+
61
+ it.each([
62
+ ['primary provider', fetchQuota],
63
+ ['add-on provider', fetchQuotaAddon],
64
+ ])('falls back to percent_remaining when entitlement is unusable for the %s', async (_name, fetchProviderQuota) => {
65
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
66
+ quota_reset_date: '2026-09-01T00:00:00Z',
67
+ quota_snapshots: {
68
+ premium_interactions: { entitlement: 0, remaining: 0, percent_remaining: 75.5 },
69
+ },
70
+ })));
71
+
72
+ const result = await fetchProviderQuota();
73
+
74
+ expect(result.ok).toBe(true);
75
+ expect(result.usage.windows.premium_interactions.usedPercent).toBeCloseTo(24.5);
76
+ expect(result.usage.windows.premium_interactions.valueLabel ?? null).toBeNull();
77
+ });
78
+ });
@@ -9,7 +9,6 @@ import { buildResult } from '../utils/index.js';
9
9
 
10
10
  import * as claude from './claude/index.js';
11
11
  import * as codex from './codex.js';
12
- import * as commandCode from './command-code.js';
13
12
  import * as copilot from './copilot.js';
14
13
  import * as crof from './crof.js';
15
14
  import * as cursor from './cursor.js';
@@ -30,12 +29,6 @@ import * as opencodeGo from './opencode-go.js';
30
29
  import * as xai from './xai.js';
31
30
 
32
31
  const registry = {
33
- 'command-code': {
34
- providerId: commandCode.providerId,
35
- providerName: commandCode.providerName,
36
- isConfigured: commandCode.isConfigured,
37
- fetchQuota: commandCode.fetchQuota
38
- },
39
32
  claude: {
40
33
  providerId: claude.providerId,
41
34
  providerName: claude.providerName,
@@ -160,12 +153,6 @@ const registry = {
160
153
 
161
154
  const pendingFetches = new Map();
162
155
 
163
- const normalizeQuotaProviderId = (providerId) => {
164
- if (typeof providerId !== 'string') return providerId;
165
- return ['command-code', 'commandcode', 'command_code', 'command code'].includes(providerId.trim().toLowerCase())
166
- ? 'command-code'
167
- : providerId;
168
- };
169
156
 
170
157
  export const listConfiguredQuotaProviders = () => {
171
158
  const configured = [];
@@ -210,14 +197,13 @@ const fetchQuotaForProviderUncoalesced = async (providerId) => {
210
197
  };
211
198
 
212
199
  export const fetchQuotaForProvider = (providerId) => {
213
- const normalizedProviderId = normalizeQuotaProviderId(providerId);
214
- const existing = pendingFetches.get(normalizedProviderId);
200
+ const existing = pendingFetches.get(providerId);
215
201
  if (existing) return existing;
216
202
 
217
- const pending = fetchQuotaForProviderUncoalesced(normalizedProviderId).finally(() => {
218
- if (pendingFetches.get(normalizedProviderId) === pending) pendingFetches.delete(normalizedProviderId);
203
+ const pending = fetchQuotaForProviderUncoalesced(providerId).finally(() => {
204
+ if (pendingFetches.get(providerId) === pending) pendingFetches.delete(providerId);
219
205
  });
220
- pendingFetches.set(normalizedProviderId, pending);
206
+ pendingFetches.set(providerId, pending);
221
207
  return pending;
222
208
  };
223
209
 
@@ -23,7 +23,7 @@ Host side (`packages/web/server/lib/relay/`):
23
23
  - `identity.js` — the host's stable identity: the long-lived signing keypair (shared with the push relay, defines the routing id) plus a long-lived encryption keypair (the E2EE trust anchor). Reused across restarts; never rotated implicitly.
24
24
  - `signing-key.js` — storage/derivation of the signing keypair and the routing id, shared with the notifications runtime.
25
25
  - `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect/backoff, and the E2EE responder handshake per connection.
26
- - `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
26
+ - `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. A standby watcher waits a 2-minute grace after the claim frees before taking over, so a cleanly restarting host (app update/relaunch) — which reclaims at boot with no wait — always wins the restart window over a bystander instance. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. Instances created with `allowPassiveHost: false` (dev servers via `OPENCHAMBER_RELAY_HOST=off`, the Electron dev shell via `OPENCHAMBER_ELECTRON_DEV`; `OPENCHAMBER_RELAY_HOST=on` overrides) never start the host passively at all — boot, demand reconcile, and watcher takeover leave them in `standby`; only explicit enable/pairing hosts there. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
27
27
  - `tunnel-host.js` — the per-connection dispatcher: decrypts tunnel frames and forwards HTTP/SSE/WS to the local server over loopback, then streams responses back. Enforces a path allowlist and never injects credentials.
28
28
  - `e2ee.js`, `tunnel-codec.js` — host-side (JS) mirrors of the shared crypto and framing (see "Two implementations" below).
29
29
 
@@ -70,6 +70,11 @@ export const createRelayService = ({
70
70
  // evict each other at the relay worker ("Control replaced") and devices land
71
71
  // on a random instance. Optional: without it, behavior is pre-lock.
72
72
  hostLock = null,
73
+ // When false, this instance never starts the relay host on its own (boot,
74
+ // demand reconcile, or claim-watch takeover) — only an explicit user action
75
+ // (enable, pairing) force-claims. Dev/debug instances set this so they do not
76
+ // capture paired devices from the production instance sharing the data dir.
77
+ allowPassiveHost = true,
73
78
  logger = console,
74
79
  }) => {
75
80
  const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
@@ -80,6 +85,13 @@ export const createRelayService = ({
80
85
  // claimant dies; a running host stands down when another process claims.
81
86
  let claimWatchTimer = null;
82
87
  const CLAIM_WATCH_INTERVAL_MS = 30_000;
88
+ // A standby instance does not grab a freed claim immediately: a clean restart
89
+ // of the previous host (app update, relaunch) releases the claim for a short
90
+ // while, and taking it during that window strands the devices on this —
91
+ // possibly older — instance. The restarting host reclaims at boot without any
92
+ // wait, so it always wins the window.
93
+ const CLAIM_TAKEOVER_GRACE_MS = 120_000;
94
+ let claimFreeSinceMs = null;
83
95
 
84
96
  const readConfig = async () => {
85
97
  const settings = await readSettingsFromDiskMigrated();
@@ -133,8 +145,19 @@ export const createRelayService = ({
133
145
  }
134
146
  return;
135
147
  }
136
- if (status.state === 'standby' && hostLock.tryClaim()) {
137
- logger.warn('[Relay] host claim is free — taking over the relay host');
148
+ if (status.state !== 'standby' || !allowPassiveHost) return;
149
+ if (hostLock.liveClaimantPid() !== null) {
150
+ claimFreeSinceMs = null;
151
+ return;
152
+ }
153
+ if (claimFreeSinceMs === null) {
154
+ claimFreeSinceMs = Date.now();
155
+ return;
156
+ }
157
+ if (Date.now() - claimFreeSinceMs < CLAIM_TAKEOVER_GRACE_MS) return;
158
+ if (hostLock.tryClaim()) {
159
+ claimFreeSinceMs = null;
160
+ logger.warn('[Relay] host claim stayed free — taking over the relay host');
138
161
  await start(relayUrl);
139
162
  }
140
163
  } catch (error) {
@@ -149,10 +172,19 @@ export const createRelayService = ({
149
172
  if (!claimWatchTimer) return;
150
173
  clearInterval(claimWatchTimer);
151
174
  claimWatchTimer = null;
175
+ claimFreeSinceMs = null;
152
176
  };
153
177
 
154
178
  const start = async (relayUrl, { claim = 'try' } = {}) => {
155
179
  if (hostClient) return;
180
+ if (claim !== 'force' && !allowPassiveHost) {
181
+ status = {
182
+ state: 'standby',
183
+ lastError: 'passive relay hosting is disabled on this instance — enable the relay or create a pairing link to host here',
184
+ connectedClients: 0,
185
+ };
186
+ return;
187
+ }
156
188
  if (hostLock) {
157
189
  const claimed = claim === 'force' ? hostLock.forceClaim() : hostLock.tryClaim();
158
190
  if (!claimed) {
@@ -0,0 +1,69 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import crypto from 'node:crypto';
3
+
4
+ import { createRelayService } from './service.js';
5
+
6
+ const makeService = (options = {}) => {
7
+ // In-memory settings store with a pre-seeded relay identity so the service
8
+ // never regenerates a signing key during the test.
9
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
10
+ let settings = {
11
+ relaySigningKey: {
12
+ privateJwk: privateKey.export({ format: 'jwk' }),
13
+ publicJwk: publicKey.export({ format: 'jwk' }),
14
+ },
15
+ privateRelay: { enabled: true, relayUrl: 'wss://relay.example.test/ws' },
16
+ ...options.settings,
17
+ };
18
+ const hostLock = {
19
+ tryClaim: vi.fn(() => true),
20
+ forceClaim: vi.fn(() => true),
21
+ holdsClaim: vi.fn(() => true),
22
+ liveClaimantPid: vi.fn(() => null),
23
+ release: vi.fn(),
24
+ };
25
+ const service = createRelayService({
26
+ crypto,
27
+ readSettingsFromDiskMigrated: async () => settings,
28
+ writeSettingsToDisk: async (next) => { settings = next; },
29
+ readSettingsStrict: async () => settings,
30
+ getLocalPort: () => 0,
31
+ hasRelayDemand: options.hasRelayDemand ?? (async () => true),
32
+ hostLock,
33
+ allowPassiveHost: options.allowPassiveHost,
34
+ logger: { warn: () => {} },
35
+ });
36
+ return { service, hostLock, getSettings: () => settings };
37
+ };
38
+
39
+ describe('relay service passive hosting', () => {
40
+ it('never claims or starts the host passively when passive hosting is disabled', async () => {
41
+ const { service, hostLock } = makeService({ allowPassiveHost: false });
42
+ try {
43
+ await service.startIfEnabled();
44
+ let status = await service.getStatus();
45
+ expect(status.state).toBe('standby');
46
+ expect(hostLock.tryClaim).not.toHaveBeenCalled();
47
+ expect(hostLock.forceClaim).not.toHaveBeenCalled();
48
+
49
+ await service.reconcile();
50
+ status = await service.getStatus();
51
+ expect(status.state).toBe('standby');
52
+ expect(status.lastError).toContain('passive relay hosting is disabled');
53
+ expect(hostLock.tryClaim).not.toHaveBeenCalled();
54
+ } finally {
55
+ service.stop();
56
+ }
57
+ });
58
+
59
+ it('force-claims for an explicit pairing even when passive hosting is disabled', async () => {
60
+ const { service, hostLock } = makeService({ allowPassiveHost: false });
61
+ try {
62
+ const candidate = await service.ensureEnabledForPairing();
63
+ expect(candidate?.type).toBe('relay');
64
+ expect(hostLock.forceClaim).toHaveBeenCalled();
65
+ } finally {
66
+ service.stop();
67
+ }
68
+ });
69
+ });
@@ -249,6 +249,7 @@ export const createSessionGoalRuntime = ({
249
249
  getOpenCodeAuthHeaders,
250
250
  getSmallModelService,
251
251
  emitGoalNotification,
252
+ isEnabled = isSessionGoalEnabled,
252
253
  idleQuietMs = IDLE_QUIET_MS,
253
254
  kickoffQuietMs = KICKOFF_QUIET_MS,
254
255
  maxAutoTurns = MAX_AUTO_TURNS,
@@ -444,7 +445,7 @@ export const createSessionGoalRuntime = ({
444
445
  };
445
446
 
446
447
  const tick = async (sessionId, directory) => {
447
- if (!isSessionGoalEnabled()) return;
448
+ if (!isEnabled()) return;
448
449
 
449
450
  const session = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, { directory })
450
451
  .catch((error) => {