@openchamber/web 1.21.0 → 1.22.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 (180) 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-C2BopIs3.js → CodeMirrorCommentWidgets-CPvfxh0N.js} +1 -1
  8. package/dist/assets/CommitSection-CC5mFzO2.js +1 -0
  9. package/dist/assets/DiffView-6xGdyI0n.js +4 -0
  10. package/dist/assets/FilesView-Bm3vT63N.js +17 -0
  11. package/dist/assets/GitView-B6y1Y69c.js +6 -0
  12. package/dist/assets/{JsonTreeView-osju7J70.js → JsonTreeView-rwHz84MX.js} +1 -1
  13. package/dist/assets/LinearIssuesView-B0UM_Rkx.js +1 -0
  14. package/dist/assets/MarkdownImageGallery-sGilV9Hs.js +1 -0
  15. package/dist/assets/MarkdownRendererImpl--4sRsKBn.js +12 -0
  16. package/dist/assets/OnboardingScreen-CECL_Cms.js +1 -0
  17. package/dist/assets/{PatchDiff-Dan3mADn.js → PatchDiff-BGPl1s-U.js} +1 -1
  18. package/dist/assets/{PierreDiffViewer-CGoI2v0q.js → PierreDiffViewer-Cvz9Z-io.js} +2 -2
  19. package/dist/assets/PlanView-BFMsnHk3.js +5 -0
  20. package/dist/assets/SettingsView-_Gtn5SdT.js +28 -0
  21. package/dist/assets/{SettingsWindow-DXF-MTHG.js → SettingsWindow-C1Qa09YO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-DrCa1JRk.js → ToolOutputDialog-DzQlzMF4.js} +6 -6
  23. package/dist/assets/{ToolPartDiffPreview-B_tfvlNF.js → ToolPartDiffPreview-DfVOfwHy.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-CN_BctrR.js → VirtualizedFileDiff-DT5MDv-u.js} +1 -1
  25. package/dist/assets/WalkthroughView-D8sLH_M8.js +4 -0
  26. package/dist/assets/{computeVirtualFileMetrics-Gi1d5eU1.js → computeVirtualFileMetrics-DmpLWhll.js} +1 -1
  27. package/dist/assets/{contextPanelEmbeddedChat-CpzVNWAv.js → contextPanelEmbeddedChat-BK78t3M_.js} +1 -1
  28. package/dist/assets/de-C3luvSd_.js +9 -0
  29. package/dist/assets/es-CmU4HLv9.js +15 -0
  30. package/dist/assets/fr-Bgyni40l.js +13 -0
  31. package/dist/assets/index-C57jT0Sa.css +1 -0
  32. package/dist/assets/{index-Brm3X9rs.js → index-CWYs7sMK.js} +1 -1
  33. package/dist/assets/index-b0zDkWyg.js +7 -0
  34. package/dist/assets/{isDiffPlainText-pH9kAJQH.js → isDiffPlainText-BO_q5ezD.js} +1 -1
  35. package/dist/assets/{isFilePlainText-CVKy_dgB.js → isFilePlainText-D8qPqUAf.js} +1 -1
  36. package/dist/assets/ja-C1ImKinT.js +15 -0
  37. package/dist/assets/ko-CP7OdxYH.js +15 -0
  38. package/dist/assets/main-D4rd8Hy5.js +928 -0
  39. package/dist/assets/{main-vUCh0VB0.js → main-D7fwjW2z.js} +2 -2
  40. package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
  41. package/dist/assets/markdownCore-BcmkWZPO.js +3 -0
  42. package/dist/assets/{miniChat-BlzGEYgE.js → miniChat-D5rraz-g.js} +2 -2
  43. package/dist/assets/{mobile-CkX6H-IT.js → mobile-Cg_DE3KL.js} +2 -2
  44. package/dist/assets/{patchFileDiff-BCTsE43U.js → patchFileDiff-Bpql0QGw.js} +3 -3
  45. package/dist/assets/pl-DQYSiGYX.js +15 -0
  46. package/dist/assets/pt-BR-DytpsW4M.js +15 -0
  47. package/dist/assets/{renderElectronMiniChatApp-CJYe_KOL.js → renderElectronMiniChatApp-B_Bn7BbN.js} +2 -2
  48. package/dist/assets/renderMobileApp-DLfxMzGJ.js +25 -0
  49. package/dist/assets/runtimeEndpointReset-HlRmXFGW.js +16 -0
  50. package/dist/assets/scheduledTasksApi-BPvxrynl.js +1 -0
  51. package/dist/assets/{shikiHighlight-BgTPSITe.js → shikiHighlight-CFAVs_lu.js} +1 -1
  52. package/dist/assets/tr-aizaUvft.js +6 -0
  53. package/dist/assets/uk-DwnRxJZd.js +15 -0
  54. package/dist/assets/useAppFontEffects-DWXGRUPZ.js +7310 -0
  55. package/dist/assets/{useInlineCommentController-DFFv0hae.js → useInlineCommentController-Cc0OCXr0.js} +2 -2
  56. package/dist/assets/useRootScrollLock-BFZtfciC.js +1 -0
  57. package/dist/assets/{vendor-base-ui-_6j2xOWl.js → vendor-base-ui-BeMD8X_w.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-language-data-DkQX2EBa.js → vendor-codemirror-language-data-BGFszm8n.js} +2 -2
  59. package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
  60. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
  61. package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
  62. package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
  63. package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
  64. package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
  65. package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
  66. package/dist/assets/{web-components-DLnGY4fs.js → web-components-CD-GFayc.js} +4 -4
  67. package/dist/assets/zh-CN-UDNMxm7r.js +15 -0
  68. package/dist/assets/zh-TW-BsswdYL-.js +15 -0
  69. package/dist/index.html +5 -5
  70. package/dist/mini-chat.html +3 -3
  71. package/dist/mobile.html +3 -3
  72. package/dist/site.webmanifest +1 -1
  73. package/dist/sw.js +1 -1
  74. package/package.json +2 -2
  75. package/public/site.webmanifest +1 -1
  76. package/server/index.js +6 -2
  77. package/server/lib/cloudflare-tunnel.js +1 -1
  78. package/server/lib/dictation/DOCUMENTATION.md +19 -6
  79. package/server/lib/dictation/local/model-catalog.js +220 -0
  80. package/server/lib/dictation/local/model-catalog.test.js +42 -0
  81. package/server/lib/dictation/local/sherpa-tts.js +41 -20
  82. package/server/lib/dictation/local/worker-process.js +2 -0
  83. package/server/lib/dictation/runtime.js +4 -0
  84. package/server/lib/dictation/service.js +27 -4
  85. package/server/lib/fs/DOCUMENTATION.md +5 -0
  86. package/server/lib/fs/routes.js +150 -0
  87. package/server/lib/fs/routes.test.js +308 -3
  88. package/server/lib/git/DOCUMENTATION.md +4 -3
  89. package/server/lib/git/service.js +128 -6
  90. package/server/lib/git/service.test.js +191 -1
  91. package/server/lib/linear/DOCUMENTATION.md +97 -0
  92. package/server/lib/linear/OAUTH-BROKER-HANDOFF.md +91 -0
  93. package/server/lib/linear/auth.js +436 -0
  94. package/server/lib/linear/auth.test.js +242 -0
  95. package/server/lib/linear/client.js +191 -0
  96. package/server/lib/linear/index.js +61 -0
  97. package/server/lib/linear/issues.js +499 -0
  98. package/server/lib/linear/issues.test.js +512 -0
  99. package/server/lib/linear/mapping.js +188 -0
  100. package/server/lib/linear/mapping.test.js +147 -0
  101. package/server/lib/linear/oauth.js +345 -0
  102. package/server/lib/linear/oauth.test.js +166 -0
  103. package/server/lib/linear/parse.js +23 -0
  104. package/server/lib/linear/routes.js +432 -0
  105. package/server/lib/linear/routes.test.js +661 -0
  106. package/server/lib/linear/status-runtime.js +64 -0
  107. package/server/lib/linear/status-runtime.test.js +167 -0
  108. package/server/lib/linear/status.js +280 -0
  109. package/server/lib/linear/status.test.js +271 -0
  110. package/server/lib/linear/teams.js +72 -0
  111. package/server/lib/linear/teams.test.js +94 -0
  112. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  113. package/server/lib/markdown-image-grants/routes.js +3 -1
  114. package/server/lib/markdown-image-grants/routes.test.js +14 -0
  115. package/server/lib/openchamber-sessions/routes.js +4 -1
  116. package/server/lib/openchamber-sessions/routes.test.js +23 -0
  117. package/server/lib/opencode/env-runtime.js +17 -1
  118. package/server/lib/opencode/env-runtime.test.js +56 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/lifecycle.js +48 -9
  121. package/server/lib/opencode/lifecycle.test.js +125 -1
  122. package/server/lib/opencode/managed-process-registry.d.ts +13 -0
  123. package/server/lib/opencode/managed-process-registry.js +213 -163
  124. package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
  125. package/server/lib/opencode/project-directory-runtime.js +16 -11
  126. package/server/lib/opencode/project-directory-runtime.test.js +32 -12
  127. package/server/lib/opencode/pwa-manifest-routes.js +1 -1
  128. package/server/lib/opencode/routes-upgrade.test.js +96 -12
  129. package/server/lib/opencode/routes.js +53 -5
  130. package/server/lib/opencode/settings-helpers.js +3 -0
  131. package/server/lib/opencode/settings-helpers.test.js +10 -0
  132. package/server/lib/opencode/static-routes-runtime.js +3 -3
  133. package/server/lib/opencode/theme-runtime.js +1 -1
  134. package/server/lib/opencode/theme-runtime.test.js +129 -0
  135. package/server/lib/projects/project-config.js +33 -5
  136. package/server/lib/projects/project-config.test.js +85 -0
  137. package/server/lib/quota/DOCUMENTATION.md +19 -0
  138. package/server/lib/quota/providers/copilot.js +26 -10
  139. package/server/lib/quota/providers/copilot.test.js +78 -0
  140. package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -0
  141. package/server/lib/small-model/DOCUMENTATION.md +11 -5
  142. package/server/lib/small-model/call.js +64 -20
  143. package/server/lib/small-model/call.test.js +184 -2
  144. package/server/lib/tts/DOCUMENTATION.md +1 -0
  145. package/server/lib/tts/language-detect.js +210 -0
  146. package/server/lib/tts/language-detect.test.js +76 -0
  147. package/server/lib/tts/routes.js +23 -1
  148. package/server/lib/tts/routes.test.js +26 -0
  149. package/server/lib/tunnels/install-help.js +2 -2
  150. package/server/lib/tunnels/install-help.test.js +9 -0
  151. package/server/lib/walkthrough/languages.js +1 -0
  152. package/dist/assets/CommitSection-HJeMUAWb.js +0 -1
  153. package/dist/assets/DiffView-D5cvbEPb.js +0 -4
  154. package/dist/assets/FilesView-DPU8aNPL.js +0 -17
  155. package/dist/assets/GitView-Ct6xWrVH.js +0 -6
  156. package/dist/assets/MarkdownImageGallery-EujHSZ2M.js +0 -1
  157. package/dist/assets/MarkdownRendererImpl-CPzu4kIr.js +0 -12
  158. package/dist/assets/OnboardingScreen-w2VG4fWY.js +0 -1
  159. package/dist/assets/PlanView-Dgg-WTEc.js +0 -4
  160. package/dist/assets/SessionSwitcherDropdown-CJTrc8K7.js +0 -1
  161. package/dist/assets/SettingsView-D9yRuFZw.js +0 -28
  162. package/dist/assets/WalkthroughView-D9Q4lr5x.js +0 -4
  163. package/dist/assets/de-B_LdJwEM.js +0 -9
  164. package/dist/assets/es-CubfsAYV.js +0 -15
  165. package/dist/assets/fr-5qJM0nFS.js +0 -13
  166. package/dist/assets/index-BW82eK5v.css +0 -1
  167. package/dist/assets/index-rlLjZUM5.js +0 -7
  168. package/dist/assets/ja-DJYIBUlH.js +0 -15
  169. package/dist/assets/ko-DcUBkB7y.js +0 -15
  170. package/dist/assets/main-DLBxKIoX.js +0 -926
  171. package/dist/assets/markdownCore-DG6GHLF4.js +0 -3
  172. package/dist/assets/pl-rB6BLcio.js +0 -15
  173. package/dist/assets/pt-BR-DcwtlO-o.js +0 -15
  174. package/dist/assets/renderMobileApp-hQJTnr8B.js +0 -25
  175. package/dist/assets/runtimeEndpointReset-BDh7r8BL.js +0 -15
  176. package/dist/assets/scheduledTasksApi-CAGPh_gZ.js +0 -1
  177. package/dist/assets/uk-INZlFD9A.js +0 -15
  178. package/dist/assets/useAppFontEffects-Cll4gnsh.js +0 -7268
  179. package/dist/assets/zh-CN-Dzda8xa1.js +0 -15
  180. package/dist/assets/zh-TW-Cwn3rNYZ.js +0 -15
@@ -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
 
@@ -47,20 +47,20 @@ export const createStaticRoutesRuntime = (dependencies) => {
47
47
  normalizePwaOrientation,
48
48
  });
49
49
 
50
- app.get(/^(?!\/api|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (_req, res) => {
50
+ app.get(/^(?!\/api|\/linear|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (_req, res) => {
51
51
  res.sendFile(path.join(distPath, 'index.html'));
52
52
  });
53
53
  return;
54
54
  }
55
55
 
56
56
  console.warn(`Warning: ${distPath} not found, static files will not be served`);
57
- app.get(/^(?!\/api|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (_req, res) => {
57
+ app.get(/^(?!\/api|\/linear|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (_req, res) => {
58
58
  res.status(404).send('Static files not found. Please build the application first.');
59
59
  });
60
60
  };
61
61
 
62
62
  const registerApiOnlyFallbackRoutes = (app) => {
63
- app.get(/^(?!\/api|\/auth|\/health|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (req, res) => {
63
+ app.get(/^(?!\/api|\/auth|\/health|\/linear|.*\.(js|css|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|map)).*$/, (req, res) => {
64
64
  const command = 'openchamber connect-url --help';
65
65
  res.status(200).format({
66
66
  html: () => {
@@ -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
+ });
@@ -499,11 +499,20 @@ export const createProjectConfigRuntime = (deps) => {
499
499
  }
500
500
  };
501
501
 
502
+ // Normalized tasks for reading, plus the raw on-disk record of each one for
503
+ // writing back. Normalization only keeps the fields THIS build knows, so a
504
+ // write that re-serialized normalized tasks would strip every field added
505
+ // by a newer build (or a newer UI) the moment an older server touched the
506
+ // file — a goal or auto-accept setting silently lost after a task ran.
507
+ // Writers therefore persist untouched tasks from `rawTasksByID` verbatim and
508
+ // only serialize a normalized task where the task itself was deliberately
509
+ // replaced.
502
510
  const readProjectConfigFromDisk = async (projectID) => {
503
511
  const parsed = await readRawProjectConfigFromDisk(projectID);
504
512
  const tasksRaw = Array.isArray(parsed.scheduledTasks) ? parsed.scheduledTasks : [];
505
513
  const now = Date.now();
506
514
  const scheduledTasks = [];
515
+ const rawTasksByID = new Map();
507
516
  for (const task of tasksRaw) {
508
517
  try {
509
518
  const normalized = normalizeTaskForStorage(task, {
@@ -514,15 +523,31 @@ export const createProjectConfigRuntime = (deps) => {
514
523
  refreshUpdatedAt: false,
515
524
  });
516
525
  scheduledTasks.push(normalized);
526
+ rawTasksByID.set(normalized.id, task);
517
527
  } catch {
518
528
  }
519
529
  }
520
530
  return {
521
531
  version: PROJECT_CONFIG_VERSION,
522
532
  scheduledTasks,
533
+ rawTasksByID,
523
534
  };
524
535
  };
525
536
 
537
+ // The list to write: tasks this write replaced go out normalized; every
538
+ // other task goes out exactly as stored, fields unknown to this build
539
+ // included. A state-only update counts as untouched — only its `state` is
540
+ // swapped onto the stored record. Callers keep working with (and returning)
541
+ // the normalized tasks; only the bytes on disk differ.
542
+ const toStoredTasks = (config, tasks, { replacedIDs = new Set(), stateUpdatedID = null } = {}) => (
543
+ tasks.map((task) => {
544
+ if (replacedIDs.has(task.id)) return task;
545
+ const stored = config.rawTasksByID.get(task.id);
546
+ if (!stored) return task;
547
+ return task.id === stateUpdatedID ? { ...stored, state: task.state } : stored;
548
+ })
549
+ );
550
+
526
551
  const writeProjectConfigToDisk = async (projectID, config) => {
527
552
  const filePath = resolveProjectConfigPath(projectID);
528
553
  const parentDirectory = path.dirname(filePath);
@@ -607,7 +632,7 @@ export const createProjectConfigRuntime = (deps) => {
607
632
 
608
633
  const nextConfig = {
609
634
  version: PROJECT_CONFIG_VERSION,
610
- scheduledTasks: nextTasks,
635
+ scheduledTasks: toStoredTasks(current, nextTasks, { replacedIDs: new Set([normalizedTask.id]) }),
611
636
  };
612
637
  await writeProjectConfigToDisk(projectID, nextConfig);
613
638
 
@@ -633,7 +658,7 @@ export const createProjectConfigRuntime = (deps) => {
633
658
  if (deleted) {
634
659
  await writeProjectConfigToDisk(projectID, {
635
660
  version: PROJECT_CONFIG_VERSION,
636
- scheduledTasks: nextTasks,
661
+ scheduledTasks: toStoredTasks(current, nextTasks),
637
662
  });
638
663
  }
639
664
 
@@ -676,7 +701,7 @@ export const createProjectConfigRuntime = (deps) => {
676
701
 
677
702
  await writeProjectConfigToDisk(projectID, {
678
703
  version: PROJECT_CONFIG_VERSION,
679
- scheduledTasks: nextTasks,
704
+ scheduledTasks: toStoredTasks(current, nextTasks, { stateUpdatedID: nextTask.id }),
680
705
  });
681
706
 
682
707
  return {
@@ -737,7 +762,7 @@ export const createProjectConfigRuntime = (deps) => {
737
762
 
738
763
  await writeProjectConfigToDisk(projectID, {
739
764
  version: PROJECT_CONFIG_VERSION,
740
- scheduledTasks: nextTasks,
765
+ scheduledTasks: toStoredTasks(current, nextTasks, { stateUpdatedID: nextTask.id }),
741
766
  });
742
767
 
743
768
  return {
@@ -797,6 +822,7 @@ export const createProjectConfigRuntime = (deps) => {
797
822
 
798
823
  const consumedLoopPaths = new Set();
799
824
  const nextTasks = [];
825
+ const replacedIDs = new Set();
800
826
  for (const task of tasks) {
801
827
  if (task.loopFile && !activeLoopFilePaths.has(task.loopFile)) {
802
828
  // The driving loop file was removed (or renamed) — unschedule.
@@ -828,6 +854,7 @@ export const createProjectConfigRuntime = (deps) => {
828
854
  },
829
855
  );
830
856
  nextTasks.push(adopted);
857
+ replacedIDs.add(adopted.id);
831
858
  pendingLoops.delete(loop.definition.name);
832
859
  if (task.loopFile) {
833
860
  consumedLoopPaths.add(task.loopFile);
@@ -863,6 +890,7 @@ export const createProjectConfigRuntime = (deps) => {
863
890
  },
864
891
  );
865
892
  nextTasks.push(created);
893
+ replacedIDs.add(created.id);
866
894
  } catch (error) {
867
895
  console.warn(`[scheduled-tasks] skipped loop ${loop.filePath}:`, error?.message ?? error);
868
896
  }
@@ -870,7 +898,7 @@ export const createProjectConfigRuntime = (deps) => {
870
898
 
871
899
  await writeProjectConfigToDisk(projectID, {
872
900
  version: PROJECT_CONFIG_VERSION,
873
- scheduledTasks: nextTasks,
901
+ scheduledTasks: toStoredTasks(current, nextTasks, { replacedIDs }),
874
902
  });
875
903
 
876
904
  return nextTasks;
@@ -14,6 +14,7 @@ const createRuntime = async () => {
14
14
  });
15
15
  return {
16
16
  runtime,
17
+ tempRoot,
17
18
  cleanup: async () => {
18
19
  await rm(tempRoot, { recursive: true, force: true });
19
20
  },
@@ -472,6 +473,90 @@ describe('project-config loop reconciliation', () => {
472
473
  }
473
474
  });
474
475
 
476
+ describe('fields this build does not know', () => {
477
+ // Simulates a config written by a newer build (or a newer UI): the task
478
+ // carries execution and state fields normalization here has never heard of.
479
+ const seedForeignTask = async (runtime, tempRoot) => {
480
+ const created = await runtime.upsertScheduledTask('project-test', {
481
+ name: 'Nightly digest',
482
+ enabled: true,
483
+ schedule: { kind: 'daily', time: '09:30', timezone: 'UTC' },
484
+ execution: { prompt: 'Summarize', providerID: 'openai', modelID: 'gpt-4.1', goalEnabled: true },
485
+ });
486
+ const filePath = path.join(tempRoot, 'project-test.json');
487
+ const stored = JSON.parse(await readFile(filePath, 'utf8'));
488
+ stored.scheduledTasks[0].execution.futureExecutionField = 'keep me';
489
+ stored.scheduledTasks[0].state.futureStateField = 42;
490
+ stored.scheduledTasks[0].futureTopLevelField = true;
491
+ await writeFile(filePath, JSON.stringify(stored, null, 2), 'utf8');
492
+ return { id: created.task.id, filePath };
493
+ };
494
+
495
+ const readStoredTask = async (filePath, id) => {
496
+ const stored = JSON.parse(await readFile(filePath, 'utf8'));
497
+ return stored.scheduledTasks.find((task) => task.id === id);
498
+ };
499
+
500
+ it('survive a state update after a run, and the claim update', async () => {
501
+ const { runtime, tempRoot, cleanup } = await createRuntime();
502
+ try {
503
+ const { id, filePath } = await seedForeignTask(runtime, tempRoot);
504
+
505
+ await runtime.updateScheduledTaskState('project-test', id, { lastStatus: 'success', lastRunAt: 1000 });
506
+ let stored = await readStoredTask(filePath, id);
507
+ expect(stored.execution.futureExecutionField).toBe('keep me');
508
+ expect(stored.execution.goalEnabled).toBe(true);
509
+ expect(stored.futureTopLevelField).toBe(true);
510
+ expect(stored.state.lastStatus).toBe('success');
511
+
512
+ await runtime.updateScheduledTaskStateIf('project-test', id, () => true, { lastScheduledFor: 5000 });
513
+ stored = await readStoredTask(filePath, id);
514
+ expect(stored.execution.futureExecutionField).toBe('keep me');
515
+ expect(stored.state.lastScheduledFor).toBe(5000);
516
+ } finally {
517
+ await cleanup();
518
+ }
519
+ });
520
+
521
+ it('survive writes that replace or delete a different task, and a loop sync', async () => {
522
+ const { runtime, tempRoot, cleanup } = await createRuntime();
523
+ try {
524
+ const { id, filePath } = await seedForeignTask(runtime, tempRoot);
525
+
526
+ const other = await runtime.upsertScheduledTask('project-test', {
527
+ id: 'other-task',
528
+ name: 'Other',
529
+ enabled: true,
530
+ schedule: { kind: 'daily', time: '10:00', timezone: 'UTC' },
531
+ execution: { prompt: 'Other', providerID: 'openai', modelID: 'gpt-4.1' },
532
+ });
533
+ expect((await readStoredTask(filePath, id)).execution.futureExecutionField).toBe('keep me');
534
+
535
+ await runtime.deleteScheduledTask('project-test', other.task.id);
536
+ expect((await readStoredTask(filePath, id)).execution.futureExecutionField).toBe('keep me');
537
+
538
+ await runtime.reconcileLoopTasks('project-test', []);
539
+ expect((await readStoredTask(filePath, id)).execution.futureExecutionField).toBe('keep me');
540
+ } finally {
541
+ await cleanup();
542
+ }
543
+ });
544
+
545
+ it('are dropped only when the task itself is deliberately saved', async () => {
546
+ const { runtime, tempRoot, cleanup } = await createRuntime();
547
+ try {
548
+ const { id, filePath } = await seedForeignTask(runtime, tempRoot);
549
+ const [task] = await runtime.listScheduledTasks('project-test');
550
+ await runtime.upsertScheduledTask('project-test', { ...task, name: 'Renamed' });
551
+ const stored = await readStoredTask(filePath, id);
552
+ expect(stored.name).toBe('Renamed');
553
+ expect(stored.execution.futureExecutionField).toBeUndefined();
554
+ } finally {
555
+ await cleanup();
556
+ }
557
+ });
558
+ });
559
+
475
560
  it('conditionally updates state only when the predicate passes (occurrence claim)', async () => {
476
561
  const { runtime, cleanup } = await createRuntime();
477
562
  try {
@@ -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
+ });