@openchamber/web 1.22.1 → 1.23.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 (205) hide show
  1. package/bin/cli.js +11 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-DbcnxAfY.js} +1 -1
  6. package/dist/assets/DiffView-Dp1tomqK.js +4 -0
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-DE2sKIYv.js} +1 -1
  8. package/dist/assets/FilesView-C_of2nIT.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-CKgUkb5Z.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-Bce2ettZ.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BZVWM2zw.js} +1 -1
  12. package/dist/assets/MarkdownImageGallery-DdROVz29.js +1 -0
  13. package/dist/assets/MarkdownRendererImpl-CenrzmMN.js +12 -0
  14. package/dist/assets/OnboardingScreen-DyqYG_NP.js +1 -0
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CR3RVO5I.js} +1 -1
  16. package/dist/assets/PierreDiffViewer-KihzO94X.js +161 -0
  17. package/dist/assets/PlanView-jcQAfr2A.js +5 -0
  18. package/dist/assets/SettingsView-Buvom5A2.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-CV_hzB5v.js} +1 -1
  20. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  21. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-llKecK_Z.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-ZDMTdCGn.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-ClvqQ4j0.js} +1 -1
  24. package/dist/assets/WalkthroughView-BgpSnSlU.js +4 -0
  25. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-Nm5_wabb.js} +2 -2
  26. package/dist/assets/contextPanelEmbeddedChat-CirXEPJq.js +1 -0
  27. package/dist/assets/de-DTQDjaiv.js +10 -0
  28. package/dist/assets/es-SOCFd_r-.js +16 -0
  29. package/dist/assets/fr-CP6jqIzw.js +14 -0
  30. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  31. package/dist/assets/index-B68h5S5B.css +1 -0
  32. package/dist/assets/index-CRf2xk51.js +39 -0
  33. package/dist/assets/{index-DLiD86ge.js → index-Du9sZhDb.js} +1 -1
  34. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-EQERIius.js} +1 -1
  35. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-BCoVpkQy.js} +1 -1
  36. package/dist/assets/ja-BKfafwsD.js +16 -0
  37. package/dist/assets/ko-BA5xgCYp.js +16 -0
  38. package/dist/assets/main-BNiPEont.js +930 -0
  39. package/dist/assets/{main-DCB4JgVe.js → main-DPf32fO6.js} +2 -2
  40. package/dist/assets/markdownCore-CQ7CAuuV.js +5 -0
  41. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CHqVTsgj.js} +2 -2
  42. package/dist/assets/{mobile-DZV_sfX7.js → mobile-BQmgHA57.js} +2 -2
  43. package/dist/assets/patchFileDiff-C4X_trug.js +13 -0
  44. package/dist/assets/pl-B215pG1Y.js +16 -0
  45. package/dist/assets/pt-BR-Bo2pnlEa.js +16 -0
  46. package/dist/assets/renderElectronMiniChatApp-BUcHPOXW.js +2 -0
  47. package/dist/assets/renderMobileApp-BvTmuRE-.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-C8GAA2kS.js +17 -0
  49. package/dist/assets/scheduledTasksApi-BAScWwt3.js +1 -0
  50. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-BTObuQCR.js} +1 -1
  51. package/dist/assets/surface-BvRzS58U.js +1 -0
  52. package/dist/assets/tr-CUaxHc8X.js +7 -0
  53. package/dist/assets/uk-YTJgyqAZ.js +16 -0
  54. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-theH_IJL.js} +143 -137
  55. package/dist/assets/useGitComparison-B94I6kOI.js +1 -0
  56. package/dist/assets/useInlineCommentController-Bs3PgeA8.js +2 -0
  57. package/dist/assets/useRootScrollLock-hSYwnxZs.js +1 -0
  58. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-DdV8vhHn.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-Cxgr01md.js} +2 -2
  60. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  61. package/dist/assets/vendor-zod-BPAANqvH.js +39 -0
  62. package/dist/assets/{web-components-B6QgbmTo.js → web-components-CaS0ksnZ.js} +1 -1
  63. package/dist/assets/zh-CN-CZ2BxZS6.js +16 -0
  64. package/dist/assets/zh-TW-BsUrPdXz.js +16 -0
  65. package/dist/index.html +5 -43
  66. package/dist/mini-chat.html +4 -4
  67. package/dist/mobile.html +4 -4
  68. package/package.json +3 -4
  69. package/server/index.d.ts +15 -0
  70. package/server/index.js +52 -10
  71. package/server/lib/changelog/update-notes.js +82 -0
  72. package/server/lib/changelog/update-notes.test.js +59 -0
  73. package/server/lib/data-dir-migration.js +40 -0
  74. package/server/lib/data-dir-migration.test.js +59 -0
  75. package/server/lib/event-stream/runtime.test.js +12 -12
  76. package/server/lib/fs/DOCUMENTATION.md +5 -0
  77. package/server/lib/fs/routes.js +63 -21
  78. package/server/lib/fs/routes.test.js +187 -1
  79. package/server/lib/git/DOCUMENTATION.md +29 -5
  80. package/server/lib/git/routes.js +24 -4
  81. package/server/lib/git/service.js +194 -198
  82. package/server/lib/git/service.test.js +440 -25
  83. package/server/lib/inherited-env.js +16 -9
  84. package/server/lib/inherited-env.test.js +8 -9
  85. package/server/lib/message-queue/DOCUMENTATION.md +20 -7
  86. package/server/lib/message-queue/runtime.js +59 -7
  87. package/server/lib/message-queue/runtime.test.js +59 -3
  88. package/server/lib/network-defaults.js +23 -0
  89. package/server/lib/network-defaults.test.js +52 -0
  90. package/server/lib/opencode/DOCUMENTATION.md +25 -5
  91. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  92. package/server/lib/opencode/config-paths.test.js +116 -0
  93. package/server/lib/opencode/feature-routes-runtime.js +4 -0
  94. package/server/lib/opencode/input-history-scope.js +14 -0
  95. package/server/lib/opencode/openchamber-routes.js +64 -4
  96. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  97. package/server/lib/opencode/plugins.js +2 -2
  98. package/server/lib/opencode/providers.js +44 -2
  99. package/server/lib/opencode/providers.test.js +131 -4
  100. package/server/lib/opencode/routes.js +9 -7
  101. package/server/lib/opencode/server-startup-runtime.js +1 -1
  102. package/server/lib/opencode/settings-files.js +214 -0
  103. package/server/lib/opencode/settings-helpers.js +113 -41
  104. package/server/lib/opencode/settings-helpers.test.js +342 -0
  105. package/server/lib/opencode/settings-registry.json +747 -0
  106. package/server/lib/opencode/settings-runtime.js +139 -18
  107. package/server/lib/opencode/settings-runtime.test.js +163 -5
  108. package/server/lib/opencode/shared.js +4 -1
  109. package/server/lib/opencode/skill-routes.js +2 -1
  110. package/server/lib/opencode/snippets.js +1 -2
  111. package/server/lib/package-manager.js +3 -28
  112. package/server/lib/project-context/DOCUMENTATION.md +25 -1
  113. package/server/lib/project-context/routes.http.test.js +18 -0
  114. package/server/lib/project-context/routes.js +15 -0
  115. package/server/lib/project-context/runtime.js +248 -23
  116. package/server/lib/project-context/runtime.test.js +106 -3
  117. package/server/lib/projects/DOCUMENTATION.md +76 -0
  118. package/server/lib/projects/project-config.js +142 -9
  119. package/server/lib/projects/project-id.js +17 -0
  120. package/server/lib/projects/project-setup.js +409 -0
  121. package/server/lib/projects/project-setup.test.js +557 -0
  122. package/server/lib/projects/routes.js +59 -0
  123. package/server/lib/quota/DOCUMENTATION.md +38 -1
  124. package/server/lib/quota/index.js +1 -0
  125. package/server/lib/quota/providers/cline-pass.js +125 -0
  126. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  127. package/server/lib/quota/providers/hyper.js +118 -0
  128. package/server/lib/quota/providers/hyper.test.js +126 -0
  129. package/server/lib/quota/providers/index.js +15 -0
  130. package/server/lib/quota/providers/neuralwatt.js +3 -6
  131. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  132. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  133. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  134. package/server/lib/quota/providers/opencode-go.js +1 -1
  135. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  136. package/server/lib/quota/providers/openrouter.js +119 -24
  137. package/server/lib/quota/providers/openrouter.test.js +330 -0
  138. package/server/lib/quota/utils/auth.js +1 -1
  139. package/server/lib/relay/DOCUMENTATION.md +55 -0
  140. package/server/lib/relay/cross-compat.test.js +26 -0
  141. package/server/lib/relay/downstream-scheduler.js +154 -0
  142. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  143. package/server/lib/relay/e2ee.js +10 -8
  144. package/server/lib/relay/flow-control.test.js +177 -0
  145. package/server/lib/relay/host-client.js +37 -8
  146. package/server/lib/relay/host-client.test.js +9 -1
  147. package/server/lib/relay/tunnel-codec.js +9 -0
  148. package/server/lib/relay/tunnel-host.js +66 -17
  149. package/server/lib/session-assist/runtime.js +6 -10
  150. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  151. package/server/lib/session-goal/runtime.js +80 -20
  152. package/server/lib/session-goal/runtime.test.js +426 -0
  153. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  154. package/server/lib/skills-catalog/install.js +3 -2
  155. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  156. package/server/lib/small-model/call.js +9 -4
  157. package/server/lib/small-model/call.test.js +29 -0
  158. package/server/lib/small-model/index.js +5 -10
  159. package/server/lib/small-model/runtime-providers.js +15 -7
  160. package/server/lib/small-model/runtime-providers.test.js +7 -1
  161. package/server/lib/terminal/DOCUMENTATION.md +14 -10
  162. package/server/lib/terminal/runtime.js +160 -24
  163. package/server/lib/terminal/runtime.test.js +571 -37
  164. package/server/lib/terminal/shells.js +17 -0
  165. package/server/lib/terminal/shells.test.js +32 -1
  166. package/server/lib/walkthrough/DOCUMENTATION.md +33 -14
  167. package/server/lib/walkthrough/model-settings.js +8 -12
  168. package/server/lib/walkthrough/prompt.js +3 -1
  169. package/server/lib/walkthrough/routes.test.js +26 -5
  170. package/server/lib/walkthrough/sources.js +23 -2
  171. package/dist/assets/DiffView-CNnDxRmO.js +0 -4
  172. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  173. package/dist/assets/MarkdownImageGallery-DffjmciG.js +0 -1
  174. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  175. package/dist/assets/OnboardingScreen-CTZe6HZn.js +0 -1
  176. package/dist/assets/PierreDiffViewer-BvwtCxW4.js +0 -157
  177. package/dist/assets/PlanView-C1qvAm7m.js +0 -5
  178. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  179. package/dist/assets/WalkthroughView-D-HFgdmM.js +0 -4
  180. package/dist/assets/contextPanelEmbeddedChat-CV-DwAiX.js +0 -1
  181. package/dist/assets/de-Cv_4FoXm.js +0 -10
  182. package/dist/assets/es-BIWNEbnS.js +0 -16
  183. package/dist/assets/fr-SD3OfMHJ.js +0 -14
  184. package/dist/assets/index-CHUT_bDS.css +0 -1
  185. package/dist/assets/index-DDInLQDd.js +0 -40
  186. package/dist/assets/ja-D7I9HofF.js +0 -16
  187. package/dist/assets/ko-BsVJM_PQ.js +0 -16
  188. package/dist/assets/main-De8Z5w49.js +0 -928
  189. package/dist/assets/markdownCore-BoQVG5-a.js +0 -3
  190. package/dist/assets/patchFileDiff-Chmiz6hq.js +0 -10
  191. package/dist/assets/pl-XR9Bs8Be.js +0 -16
  192. package/dist/assets/pt-BR-Due4be8g.js +0 -16
  193. package/dist/assets/renderElectronMiniChatApp-8tXADjfl.js +0 -2
  194. package/dist/assets/renderMobileApp-Cji7Hma5.js +0 -25
  195. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  196. package/dist/assets/scheduledTasksApi-9e-UX6im.js +0 -1
  197. package/dist/assets/tr-DBJcAv4y.js +0 -7
  198. package/dist/assets/uk-COYh2BaN.js +0 -16
  199. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  200. package/dist/assets/useRootScrollLock-KzOUytpn.js +0 -1
  201. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  202. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  203. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
  204. package/dist/assets/zh-CN-Cjk6lzhc.js +0 -16
  205. package/dist/assets/zh-TW-Dk0dOg03.js +0 -16
@@ -95,13 +95,19 @@ persisted "sending" flag would strand a message forever.
95
95
  the tick re-arms with backoff.
96
96
  5. The head is marked in flight (broadcast), then sent:
97
97
  - text starting with `/` that names a command in OpenCode's `/command`
98
- list (skills included) goes to `POST /session/:id/command` with the
99
- captured model, agent, variant, and file parts;
98
+ list (skills included) and carries no captured context goes to
99
+ `POST /session/:id/command` with the captured model, agent, variant, and
100
+ file parts. That route accepts file parts only, so a command queued
101
+ **with** context takes the prompt route instead, the same rule the
102
+ composer applies: the command's template is expanded with its arguments
103
+ (`$ARGUMENTS`, `$1..$N`, or appended), a skill keeps its `/name args` text
104
+ and gets an explicit "the user invoked this skill" synthetic part after
105
+ the context;
100
106
  - otherwise `POST /session/:id/prompt_async` with the parts in the same
101
- order a UI send uses: text, files, the captured context, pending project
102
- knowledge (`sessionKnowledgeRuntime.resolvePendingForSession`, synthetic,
103
- recorded as delivered only after the prompt is accepted), then the agent
104
- mention. The command path sends files and captured context as `parts`.
107
+ order a UI send uses: text, files, the captured context, the skill
108
+ invocation when there is one, pending project knowledge
109
+ (`sessionKnowledgeRuntime.resolvePendingForSession`, synthetic, recorded
110
+ as delivered only after the prompt is accepted), then the agent mention.
105
111
  Success removes the item, persists, broadcasts, and marks the user
106
112
  message sent for notifications. Failure keeps the item, backs off
107
113
  2 s → 60 s (doubling per consecutive failure of that item), and re-arms.
@@ -134,7 +140,14 @@ allowlists.
134
140
 
135
141
  Every mutation broadcasts `openchamber:message-queue.updated` with
136
142
  `{ revision, session }` to all connected clients (SSE and WS), so several
137
- devices on one server see one queue.
143
+ devices on one server see one queue. SSE uses the shared control stream at
144
+ `/api/openchamber/events`; `/api/global/event` carries no OpenChamber events.
145
+ The UI subscribes independently of its OpenCode transport and re-reads the
146
+ snapshot whenever either stream reconnects. The session in that payload always names
147
+ its `directory`, including the broadcast that removes the last item: the UI
148
+ keys its projection by directory, and a broadcast without one left the
149
+ delivered message on screen (a session's directory is remembered until the
150
+ session is deleted or evicted).
138
151
 
139
152
  Limits: 20 items per session, 50 sessions (oldest evicted, never one with an
140
153
  item in flight), 200k characters of content; attachment payloads are bounded
@@ -220,6 +220,10 @@ export function createMessageQueueRuntime({
220
220
  const failures = new Map(); // sessionId → { itemId, failures, nextAttemptAt }
221
221
  const abortedAt = new Map(); // sessionId → timestamp
222
222
  const holds = new Map(); // sessionId → expiresAt
223
+ // sessionId → directory, kept after the queue empties: the UI keys its
224
+ // projection by directory, so the broadcast that removes the last item must
225
+ // still name it or the client cannot tell which queue just finished.
226
+ const directories = new Map();
223
227
 
224
228
  // --- persistence ---------------------------------------------------------
225
229
 
@@ -302,7 +306,7 @@ export function createMessageQueueRuntime({
302
306
  const queue = queues.get(sessionId);
303
307
  return {
304
308
  sessionId,
305
- directory: queue?.directory ?? '',
309
+ directory: queue?.directory ?? directories.get(sessionId) ?? '',
306
310
  items: (queue?.items ?? []).map(toPublicItem),
307
311
  sendingId: sending.get(sessionId) ?? null,
308
312
  };
@@ -329,6 +333,7 @@ export function createMessageQueueRuntime({
329
333
  };
330
334
 
331
335
  const setQueueItems = (sessionId, directory, items) => {
336
+ directories.set(sessionId, directory);
332
337
  if (items.length === 0) {
333
338
  queues.delete(sessionId);
334
339
  return;
@@ -385,8 +390,36 @@ export function createMessageQueueRuntime({
385
390
  const name = head.slice(1);
386
391
  if (!name) return null;
387
392
  const commands = asList(await openCodeFetch('/command', { directory })) ?? [];
388
- if (!commands.some((command) => asRecord(command)?.name === name)) return null;
389
- return { name, arguments: tail.join(' ') };
393
+ const match = commands.map(asRecord).find((command) => command?.name === name);
394
+ if (!match) return null;
395
+ return {
396
+ name,
397
+ arguments: tail.join(' '),
398
+ isSkill: match.source === 'skill',
399
+ template: asNonEmptyString(match.template),
400
+ };
401
+ };
402
+
403
+ /**
404
+ * The prompt a slash command stands for, expanded the way OpenCode expands
405
+ * it: `$ARGUMENTS` takes the whole argument string, `$1..$N` take quoted or
406
+ * bare words with the last position absorbing the rest, and a template with
407
+ * no placeholder gets the arguments appended. Twin of the UI's
408
+ * `expandSlashCommandGoalObjective` in `packages/ui/src/sync/session-ui-store.ts`.
409
+ */
410
+ const expandCommandTemplate = (template, argumentsText) => {
411
+ if (template.includes('$ARGUMENTS')) return template.replaceAll('$ARGUMENTS', argumentsText);
412
+ const positions = [...template.matchAll(/\$(\d+)/g)].map((match) => Number(match[1]));
413
+ if (positions.length > 0) {
414
+ const parsed = [...argumentsText.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)]
415
+ .map((match) => match[1] ?? match[2] ?? match[3] ?? '');
416
+ const last = Math.max(...positions);
417
+ return template.replace(/\$(\d+)/g, (_match, value) => {
418
+ const position = Number(value);
419
+ return position === last ? parsed.slice(position - 1).join(' ') : (parsed[position - 1] ?? '');
420
+ });
421
+ }
422
+ return argumentsText ? `${template}\n\n${argumentsText}` : template;
390
423
  };
391
424
 
392
425
  const toFilePart = (attachment) => ({
@@ -412,16 +445,31 @@ export function createMessageQueueRuntime({
412
445
  const { providerID, modelID, agent, variant } = item.sendConfig;
413
446
  const fileParts = item.attachments.map(toFilePart);
414
447
  const contextParts = item.context.flatMap(toContextParts);
448
+ // OpenCode's command route takes file parts only, so a command queued
449
+ // with captured context cannot go through it. Same rule as the composer:
450
+ // without context the command route keeps its semantics; with context the
451
+ // prompt route carries the expanded template (or the skill invocation as an
452
+ // explicit instruction) together with the context.
415
453
  const command = await resolveSlashCommand(item.text, directory);
416
- if (command) {
454
+ if (command && contextParts.length === 0) {
417
455
  const body = { command: command.name, arguments: command.arguments, model: `${providerID}/${modelID}` };
418
456
  if (agent) body.agent = agent;
419
457
  if (variant) body.variant = variant;
420
- const extraParts = [...fileParts, ...contextParts];
421
- if (extraParts.length > 0) body.parts = extraParts;
458
+ if (fileParts.length > 0) body.parts = fileParts;
422
459
  await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/command`, { directory, method: 'POST', body });
423
460
  return;
424
461
  }
462
+ let text = item.text;
463
+ const commandParts = [];
464
+ if (command?.isSkill) {
465
+ commandParts.push({
466
+ type: 'text',
467
+ text: `The user explicitly invoked the ${command.name} skill. Use the corresponding skill tool to handle this request.`,
468
+ synthetic: true,
469
+ });
470
+ } else if (command?.template) {
471
+ text = expandCommandTemplate(command.template, command.arguments);
472
+ }
425
473
 
426
474
  // Standing project context rides the prompt exactly as a UI send would
427
475
  // attach it; a failed lookup sends without it rather than not at all.
@@ -432,9 +480,10 @@ export function createMessageQueueRuntime({
432
480
  // Same order as a UI send: the user's text and files, the context queued
433
481
  // with them, then the standing context, then the mentioned agent.
434
482
  const parts = [];
435
- if (item.text.trim()) parts.push({ type: 'text', text: item.text });
483
+ if (text.trim()) parts.push({ type: 'text', text });
436
484
  parts.push(...fileParts);
437
485
  parts.push(...contextParts);
486
+ parts.push(...commandParts);
438
487
  if (knowledge.text) parts.push({ type: 'text', text: knowledge.text, synthetic: true });
439
488
  if (item.agentMention) parts.push({ type: 'agent', name: item.agentMention });
440
489
  const body = { model: { providerID, modelID } };
@@ -564,6 +613,7 @@ export function createMessageQueueRuntime({
564
613
  const existing = queues.get(sessionId);
565
614
  const items = [...(existing?.items ?? []), item].slice(-MAX_ITEMS_PER_SESSION);
566
615
  queues.set(sessionId, { directory, items });
616
+ directories.set(sessionId, directory);
567
617
  if (queues.size > MAX_SESSIONS) {
568
618
  const oldest = Array.from(queues.entries())
569
619
  .filter(([id]) => id !== sessionId && !sending.has(id))
@@ -573,6 +623,7 @@ export function createMessageQueueRuntime({
573
623
  queues.delete(staleId);
574
624
  clearTimer(staleId);
575
625
  broadcast(staleId);
626
+ directories.delete(staleId);
576
627
  }
577
628
  }
578
629
  const result = commit(sessionId);
@@ -675,6 +726,7 @@ export function createMessageQueueRuntime({
675
726
  clearTimer(deletedSessionId);
676
727
  failures.delete(deletedSessionId);
677
728
  commit(deletedSessionId);
729
+ directories.delete(deletedSessionId);
678
730
  return;
679
731
  }
680
732
 
@@ -315,6 +315,21 @@ describe('message queue runtime', () => {
315
315
  expect(runtime.snapshot().sessions).toEqual([]);
316
316
  });
317
317
 
318
+ it('names the directory in the broadcast that empties a queue', async () => {
319
+ // The UI keys its projection by directory; without it the client cannot
320
+ // tell which queue just delivered its last message and keeps showing it.
321
+ const { runtime, emit, broadcasts, openCode } = createRuntime();
322
+ runtime.start();
323
+ await runtime.enqueue(SESSION, DIRECTORY, item());
324
+ openCode.state.statuses = {};
325
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
326
+ await settle();
327
+
328
+ expect(openCode.state.sent).toHaveLength(1);
329
+ expect(runtime.snapshot().sessions).toEqual([]);
330
+ expect(broadcasts.at(-1).properties.session).toEqual({ sessionId: SESSION, directory: DIRECTORY, items: [], sendingId: null });
331
+ });
332
+
318
333
  it('reorders only with a complete permutation', async () => {
319
334
  const { runtime } = createRuntime();
320
335
  runtime.start();
@@ -377,19 +392,60 @@ describe('message queue runtime', () => {
377
392
  ]);
378
393
  });
379
394
 
380
- it('sends captured context with a slash command too', async () => {
395
+ it('keeps files on the command route, which is all that route accepts', async () => {
381
396
  const { runtime, openCode, emit } = createRuntime();
382
397
  runtime.start();
383
398
  openCode.state.commands = [{ name: 'review' }];
384
399
  await runtime.enqueue(SESSION, DIRECTORY, item({
385
400
  content: '/review',
386
401
  text: '/review',
387
- context: [{ kind: 'synthetic', text: 'focus on tests' }],
402
+ attachments: [{ id: 'a', filename: 'f.txt', mimeType: 'text/plain', size: 1, source: 'local', dataUrl: 'data:text/plain,hi' }],
388
403
  }));
389
404
  emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
390
405
  await settle();
391
406
  expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/command`);
392
- expect(openCode.state.sent[0].body.parts).toEqual([{ type: 'text', text: 'focus on tests', synthetic: true }]);
407
+ expect(openCode.state.sent[0].body.parts).toEqual([{ type: 'file', mime: 'text/plain', filename: 'f.txt', url: 'data:text/plain,hi' }]);
408
+ });
409
+
410
+ it('sends a command queued with context as its expanded prompt, context included', async () => {
411
+ // The command route rejects text parts, so a command with captured
412
+ // context takes the prompt route with the template expanded, exactly as
413
+ // the composer does.
414
+ const { runtime, openCode, emit } = createRuntime();
415
+ runtime.start();
416
+ openCode.state.commands = [{ name: 'review', source: 'command', template: 'Review $1 with focus on $2' }];
417
+ const metadata = { openchamberContext: { kind: 'chat-quote', quote: 'q', text: 'why?' } };
418
+ await runtime.enqueue(SESSION, DIRECTORY, item({
419
+ content: '/review src "error handling"',
420
+ text: '/review src "error handling"',
421
+ context: [{ kind: 'context', text: 'quoted', metadata }],
422
+ }));
423
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
424
+ await settle();
425
+ expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/prompt_async`);
426
+ expect(openCode.state.sent[0].body.parts).toEqual([
427
+ { type: 'text', text: 'Review src with focus on error handling' },
428
+ { type: 'text', text: 'quoted', synthetic: true, metadata },
429
+ ]);
430
+ });
431
+
432
+ it('sends a skill queued with context as an explicit invocation, context included', async () => {
433
+ const { runtime, openCode, emit } = createRuntime();
434
+ runtime.start();
435
+ openCode.state.commands = [{ name: 'grill', source: 'skill', template: 'skill body' }];
436
+ await runtime.enqueue(SESSION, DIRECTORY, item({
437
+ content: '/grill auth',
438
+ text: '/grill auth',
439
+ context: [{ kind: 'synthetic', text: 'focus on tests' }],
440
+ }));
441
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
442
+ await settle();
443
+ expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/prompt_async`);
444
+ expect(openCode.state.sent[0].body.parts).toEqual([
445
+ { type: 'text', text: '/grill auth' },
446
+ { type: 'text', text: 'focus on tests', synthetic: true },
447
+ { type: 'text', text: 'The user explicitly invoked the grill skill. Use the corresponding skill tool to handle this request.', synthetic: true },
448
+ ]);
393
449
  });
394
450
 
395
451
  it('keeps captured context out of snapshots and broadcasts, and hands it back on take', async () => {
@@ -0,0 +1,23 @@
1
+ import net from 'node:net';
2
+
3
+ // Node caps each happy-eyeballs connect attempt at 250ms by default
4
+ // (autoSelectFamilyAttemptTimeout). TCP handshakes to provider endpoints that are
5
+ // geographically distant routinely take 300-1500ms, so fetch() from a Node process
6
+ // aborts every attempt (ETIMEDOUT) and surfaces "fetch failed" even though the host
7
+ // is reachable — e.g. the z.ai quota endpoint from an IPv4-only egress (#3399).
8
+ //
9
+ // Every Node process entrypoint that performs provider fetches raises the
10
+ // per-attempt cap. Family autoselection itself stays enabled, so the IPv6→IPv4
11
+ // fallback and ::1/localhost servers keep working; disabling it instead breaks
12
+ // local MCP servers. Runtimes without the setter (Bun's fetch path, older Node)
13
+ // are a no-op.
14
+ export const CONNECT_ATTEMPT_TIMEOUT_MS = 5_000;
15
+
16
+ export const applyConnectAttemptTimeout = (netModule = net) => {
17
+ try {
18
+ netModule.setDefaultAutoSelectFamilyAttemptTimeout(CONNECT_ATTEMPT_TIMEOUT_MS);
19
+ return true;
20
+ } catch {
21
+ return false;
22
+ }
23
+ };
@@ -0,0 +1,52 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import net from 'node:net';
3
+ import { spawnSync } from 'node:child_process';
4
+
5
+ import { applyConnectAttemptTimeout, CONNECT_ATTEMPT_TIMEOUT_MS } from './network-defaults.js';
6
+
7
+ describe('applyConnectAttemptTimeout', () => {
8
+ it('initializes the server entrypoint in a fresh Node process', () => {
9
+ const serverUrl = new URL('../index.js', import.meta.url).href;
10
+ const result = spawnSync('node', ['--input-type=module', '--eval', `
11
+ import net from 'node:net';
12
+ import assert from 'node:assert/strict';
13
+ const family = net.getDefaultAutoSelectFamily();
14
+ net.setDefaultAutoSelectFamilyAttemptTimeout(250);
15
+ await import(${JSON.stringify(serverUrl)});
16
+ assert.equal(net.getDefaultAutoSelectFamilyAttemptTimeout(), 5000);
17
+ assert.equal(net.getDefaultAutoSelectFamily(), family);
18
+ process.exit(0);
19
+ `], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
20
+ expect(result.status, result.stderr).toBe(0);
21
+ });
22
+
23
+ it('raises the per-attempt connect timeout on runtimes that expose the setter', () => {
24
+ const previous = net.getDefaultAutoSelectFamilyAttemptTimeout();
25
+ try {
26
+ expect(applyConnectAttemptTimeout()).toBe(true);
27
+ expect(net.getDefaultAutoSelectFamilyAttemptTimeout()).toBe(CONNECT_ATTEMPT_TIMEOUT_MS);
28
+ } finally {
29
+ net.setDefaultAutoSelectFamilyAttemptTimeout(previous);
30
+ }
31
+ });
32
+
33
+ it('is a no-op on runtimes without the setter', () => {
34
+ expect(applyConnectAttemptTimeout({})).toBe(false);
35
+ });
36
+
37
+ it('survives a throwing setter', () => {
38
+ const setDefaultAutoSelectFamilyAttemptTimeout = vi.fn(() => {
39
+ throw new Error('not supported');
40
+ });
41
+ expect(applyConnectAttemptTimeout({ setDefaultAutoSelectFamilyAttemptTimeout })).toBe(false);
42
+ });
43
+
44
+ it('leaves family autoselection itself untouched', () => {
45
+ const setDefaultAutoSelectFamily = vi.fn();
46
+ const setDefaultAutoSelectFamilyAttemptTimeout = vi.fn();
47
+ applyConnectAttemptTimeout({ setDefaultAutoSelectFamily, setDefaultAutoSelectFamilyAttemptTimeout });
48
+ expect(setDefaultAutoSelectFamilyAttemptTimeout).toHaveBeenCalledTimes(1);
49
+ expect(setDefaultAutoSelectFamilyAttemptTimeout).toHaveBeenCalledWith(CONNECT_ATTEMPT_TIMEOUT_MS);
50
+ expect(setDefaultAutoSelectFamily).not.toHaveBeenCalled();
51
+ });
52
+ });
@@ -63,12 +63,12 @@ This module provides OpenCode server integration utilities for the web server ru
63
63
 
64
64
  ## Public exports (providers.js)
65
65
  - `getProviderSources(providerId, workingDirectory)`: Resolves which OpenCode config layers define a provider.
66
- - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom OpenAI-compatible provider block (`npm`, `name`, `options.baseURL`, `models`, optional `env`/`headers`) into the user/project/custom config layer. Does not store API keys. Requires `config.env` or `options.hasStoredAuth` (auth already written via OpenCode `auth.set`). Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
67
- - `validateCustomProviderConfig(providerId, config, options?)`: Structural validation for custom provider payloads (id format, http(s) base URL, models, credentials via `env` or `hasStoredAuth`).
66
+ - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom provider block (`npm`, `name`, `options.baseURL`, `models`, optional `env`/`headers`) into the user/project/custom config layer. The adapter may be OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages. Existing provider, option, and retained-model fields not managed by the form are preserved; omitted models, headers, and env credentials remain explicit removals. Updating a legacy `providers` entry migrates it to the canonical `provider` key. Does not store API keys. Requires `config.env` or `options.hasStoredAuth` (auth already written via OpenCode `auth.set`). Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
67
+ - `validateCustomProviderConfig(providerId, config, options?)`: Structural validation for custom provider payloads (id format, adapter allowlist `@ai-sdk/openai-compatible`/`@ai-sdk/openai`/`@ai-sdk/anthropic`, http(s) base URL, models, credentials via `env` or `hasStoredAuth`).
68
68
  - `removeProviderConfig(providerId, workingDirectory, scope?)`: Removes a provider block from the selected config layer.
69
69
 
70
70
  ## Public exports (shared.js)
71
- - `OPENCODE_CONFIG_DIR`, `AGENT_DIR`, `COMMAND_DIR`, `SKILL_DIR`, `CONFIG_FILE`: Path constants. `OPENCODE_CONFIG` is resolved at call time for the custom config layer path.
71
+ - `OPENCODE_CONFIG_DIR`, `AGENT_DIR`, `COMMAND_DIR`, `SKILL_DIR`, `CONFIG_FILE`: Path constants rooted at `$XDG_CONFIG_HOME/opencode` when `XDG_CONFIG_HOME` is non-empty, otherwise `~/.config/opencode`. These constants are evaluated when the module loads; no files are migrated. `OPENCODE_CONFIG` remains a separate explicit config-file path and is resolved at call time for the custom config layer; it does not replace the global config directory.
72
72
  - `AGENT_SCOPE`, `COMMAND_SCOPE`, `SKILL_SCOPE`: Scope constants with USER and PROJECT values.
73
73
  - `ensureDirs()`: Creates required OpenCode directories.
74
74
  - `parseMdFile(filePath)`, `writeMdFile(filePath, frontmatter, body)`: Markdown file operations with YAML frontmatter.
@@ -212,7 +212,12 @@ Managed health failures are classified as `timeout`, `connection_refused`, `conn
212
212
  - `persistSettings(changes)`
213
213
  - Persistent permission auto-accept policy is stored under `permissionAutoAccept`; execution ownership lives in `lib/permission-auto-accept/`.
214
214
  - Queued follow-up messages live in `<data-dir>/message-queue.json`, not in settings; execution ownership lives in `lib/message-queue/`.
215
- - Shared sidebar preferences are stored as validated top-level fields: `sidebarProjectDisplayMode`, `sidebarSessionGroupingMode`, `sidebarProjectSortOrder`, and `sidebarShowRecentSection`. Device-local picker selection and sticky-header state do not enter `settings.json`.
215
+ - Shared sidebar preferences are stored as validated top-level fields: `sidebarProjectDisplayMode`, `sidebarSessionGroupingMode`, `sidebarProjectSortOrder`, and `sidebarShowRecentSection`. Device-local picker selection and sticky-header state do not enter either settings file.
216
+ - Two files (`settings-files.js`): `settings.json` holds instance facts and any legacy or unknown keys; `preferences.json` beside it holds every key the generated registry snapshot (`settings-registry.json`) marks `profile`, as `{ version: 1, fields: { key: { value, updatedAt, surfaces? } } }`. Keys the snapshot marks `perSurface` are stored per surface kind: `GET`/`PUT /api/config/settings` read the client's kind from the `surface` query parameter (`settingsSurfaceOf`; the legacy `x-openchamber-surface` header is still honoured, but a header forces a CORS preflight that cross-origin shells and older instances refuse, so clients must not send one) (`web`, `desktop`, `vscode`, `mobile`; anything else means base), `persistSettings(changes, { surface })` writes a changed per-surface key under `surfaces[surface]` and never touches its base, and `readSettingsFromDisk({ surface })` resolves that kind's value first, the base otherwise. Callers without a surface (migrations, the seed, server-side feature writers) read and write the base. `readSettingsFromDisk()` returns the merged document and seeds `preferences.json` once from an existing `settings.json` (which it leaves intact). An existing `preferences.json` that fails to parse is a failure, not an empty profile: it is never seeded or overwritten, the merged read serves the instance part, and `persistSettings` drops profile keys with a warning until the file is fixed or removed. `writeSettingsToDisk(document)` splits by scope and writes `settings.json` as the instance part plus a copy of the profile's base values (`legacySettingsDocumentOf`): a build from before the split reads only that file, so a rollback keeps the user's preferences, while current builds ignore the copy because `preferences.json` wins in the merge; device keys are dropped from writes. Modules that read one profile key off the disk on a hot path use `readMergedSettingsSync`.
217
+
218
+ ## Public exports (settings-files.js)
219
+ - `parsePreferencesDocument(raw)`, `serializePreferencesDocument(fields)`, `flattenPreferences(fields)`, `buildPreferencesFields(previousFields, document, now)`, `instancePartOf(document)`, `seedPreferencesFrom(document, now)`, `readMergedSettingsSync({ fs, path, settingsFilePath })`, `getSettingsScope(key)`, `isProfileSettingsKey(key)`, `isDeviceSettingsKey(key)`, `preferencesFilePathFor(settingsFilePath, path)`.
220
+ - The VS Code extension host writes the same two files with the same shape (`packages/vscode/src/settings-files.ts`); format changes go to both.
216
221
 
217
222
  ## Public exports (settings-helpers.js)
218
223
  - `createSettingsHelpers(dependencies)`: creates settings helper runtime for settings request/response shaping.
@@ -363,9 +368,20 @@ before starting managed OpenCode. The managed custom tool therefore receives
363
368
  an authoritative loopback callback URL even when OpenChamber binds port `0`.
364
369
 
365
370
  ## Public exports (openchamber-routes.js)
371
+ Browser completion checks use `appType=web&updateStatus=true` to stay on the
372
+ Desktop Host's native updater. A rejected native restart is retained in the
373
+ server process and returned to these polls as `DESKTOP_UPDATE_RESTART_FAILED`;
374
+ ordinary availability checks remain usable so a browser reload can offer a
375
+ retry. Starting another installation clears the previous restart error.
376
+ The shared UI's `lib/web-update.ts` parses install/check responses and waits
377
+ for the installed native target version, rather than treating absence of a
378
+ newer release as installation success. Poll requests have individual deadlines
379
+ within a ten-minute overall deadline.
380
+
366
381
  - `registerOpenChamberRoutes(app, dependencies)`: registers OpenChamber endpoints:
367
382
  - `GET /api/openchamber/update-check`
368
383
  - `POST /api/openchamber/update-install`
384
+ - Desktop-managed hosts delegate authenticated Web update requests to the Electron main process, which checks, downloads, and applies the update through `electron-updater` before restarting the host.
369
385
  - Foreground servers running under a systemd user unit queue installation in
370
386
  a separate transient unit and restart the configured service afterwards.
371
387
  `OPENCHAMBER_SYSTEMD_UNIT` overrides the default `openchamber.service`.
@@ -421,7 +437,7 @@ an authoritative loopback callback URL even when OpenChamber binds port `0`.
421
437
 
422
438
  ## Storage and configuration
423
439
  - Provider auth: `~/.local/share/opencode/auth.json`.
424
- - User config: `~/.config/opencode/opencode.json`.
440
+ - User config: `$XDG_CONFIG_HOME/opencode/opencode.json`, falling back to `~/.config/opencode/opencode.json` when unset or blank.
425
441
  - Project config: `<workingDirectory>/.opencode/opencode.json` or `opencode.json`.
426
442
  - Custom config: `OPENCODE_CONFIG` env var path.
427
443
  - Rate limit config: `OPENCHAMBER_RATE_LIMIT_MAX_ATTEMPTS`, `OPENCHAMBER_RATE_LIMIT_NO_IP_MAX_ATTEMPTS` env vars.
@@ -433,3 +449,7 @@ an authoritative loopback callback URL even when OpenChamber binds port `0`.
433
449
  - Config merging follows priority: custom > project > user.
434
450
  - UI auth uses scrypt for password hashing with constant-time comparison.
435
451
  - Tunnel auth treats `host.docker.internal` as local-only when the socket remote IP is private/loopback.
452
+
453
+ The behavior `GET /api/behavior/agents-md` response includes `path`, the effective
454
+ server-side filename, whether or not the file exists. Settings displays this
455
+ path without deriving a directory from the browser environment.
@@ -63,6 +63,7 @@ export const createBootstrapRuntime = (dependencies) => {
63
63
  getCachedZenModels,
64
64
  setAutoAcceptSession,
65
65
  agentToolRuntime,
66
+ desktopUpdater,
66
67
  } = options;
67
68
 
68
69
  const uiAuthController = createUiAuth({
@@ -153,6 +154,7 @@ export const createBootstrapRuntime = (dependencies) => {
153
154
  readSettingsFromDiskMigrated,
154
155
  fetchFreeZenModels,
155
156
  getCachedZenModels,
157
+ desktopUpdater,
156
158
  });
157
159
 
158
160
  return {
@@ -0,0 +1,116 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ const originalXdgConfigHome = process.env.XDG_CONFIG_HOME;
7
+ const originalOpenCodeConfig = process.env.OPENCODE_CONFIG;
8
+
9
+ afterEach(() => {
10
+ if (originalXdgConfigHome === undefined) delete process.env.XDG_CONFIG_HOME;
11
+ else process.env.XDG_CONFIG_HOME = originalXdgConfigHome;
12
+ if (originalOpenCodeConfig === undefined) delete process.env.OPENCODE_CONFIG;
13
+ else process.env.OPENCODE_CONFIG = originalOpenCodeConfig;
14
+ vi.resetModules();
15
+ });
16
+
17
+ async function loadOpenCodeModules() {
18
+ vi.resetModules();
19
+ return Promise.all([
20
+ import('./shared.js'),
21
+ import('./agents.js'),
22
+ import('./commands.js'),
23
+ import('./skills.js'),
24
+ import('./snippets.js'),
25
+ import('./plugins.js'),
26
+ import('./routes.js'),
27
+ ]);
28
+ }
29
+
30
+ describe('OpenCode global config paths', () => {
31
+ it('derives all shared constants from a non-empty XDG_CONFIG_HOME', async () => {
32
+ const xdgConfigHome = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-xdg-'));
33
+ process.env.XDG_CONFIG_HOME = xdgConfigHome;
34
+
35
+ const [{ OPENCODE_CONFIG_DIR, AGENT_DIR, COMMAND_DIR, SKILL_DIR, CONFIG_FILE }] = await loadOpenCodeModules();
36
+ const configDir = path.join(xdgConfigHome, 'opencode');
37
+ expect(OPENCODE_CONFIG_DIR).toBe(configDir);
38
+ expect(AGENT_DIR).toBe(path.join(configDir, 'agents'));
39
+ expect(COMMAND_DIR).toBe(path.join(configDir, 'commands'));
40
+ expect(SKILL_DIR).toBe(path.join(configDir, 'skills'));
41
+ expect(CONFIG_FILE).toBe(path.join(configDir, 'config.json'));
42
+
43
+ fs.rmSync(xdgConfigHome, { recursive: true, force: true });
44
+ });
45
+
46
+ it.each([undefined, ' '])('falls back to ~/.config/opencode when XDG_CONFIG_HOME is %s', async (xdgConfigHome) => {
47
+ if (xdgConfigHome === undefined) delete process.env.XDG_CONFIG_HOME;
48
+ else process.env.XDG_CONFIG_HOME = xdgConfigHome;
49
+
50
+ const [{ OPENCODE_CONFIG_DIR }] = await loadOpenCodeModules();
51
+ expect(OPENCODE_CONFIG_DIR).toBe(path.join(os.homedir(), '.config', 'opencode'));
52
+ });
53
+
54
+ it('keeps global CRUD below XDG_CONFIG_HOME while project files stay in the project', async () => {
55
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-config-paths-'));
56
+ const xdgConfigHome = path.join(root, 'xdg');
57
+ const projectDir = path.join(root, 'project');
58
+ process.env.XDG_CONFIG_HOME = xdgConfigHome;
59
+ delete process.env.OPENCODE_CONFIG;
60
+
61
+ const [, agents, commands, skills, snippets, plugins] = await loadOpenCodeModules();
62
+ agents.createAgent('global-agent', { description: 'Global', prompt: 'Global prompt' }, projectDir, 'user');
63
+ commands.createCommand('global-command', { description: 'Global', template: 'Global template' }, projectDir, 'user');
64
+ skills.createSkill('global-skill', { description: 'Global', instructions: 'Global instructions' }, projectDir, 'user');
65
+ snippets.createSnippet('global-snippet', { content: 'Global snippet' }, projectDir, 'global');
66
+ plugins.createPluginEntry({ spec: 'global-plugin', scope: 'user' }, projectDir);
67
+
68
+ const configDir = path.join(xdgConfigHome, 'opencode');
69
+ expect(fs.existsSync(path.join(configDir, 'agents', 'global-agent.md'))).toBe(true);
70
+ expect(fs.existsSync(path.join(configDir, 'commands', 'global-command.md'))).toBe(true);
71
+ expect(fs.existsSync(path.join(configDir, 'skills', 'global-skill', 'SKILL.md'))).toBe(true);
72
+ expect(fs.existsSync(path.join(configDir, 'snippet', 'global-snippet.md'))).toBe(true);
73
+ expect(JSON.parse(fs.readFileSync(path.join(configDir, 'config.json'), 'utf8')).plugin).toEqual(['global-plugin']);
74
+
75
+ agents.createAgent('project-agent', { description: 'Project', prompt: 'Project prompt' }, projectDir, 'project');
76
+ commands.createCommand('project-command', { description: 'Project', template: 'Project template' }, projectDir, 'project');
77
+ skills.createSkill('project-skill', { description: 'Project', instructions: 'Project instructions' }, projectDir, 'project');
78
+
79
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'agents', 'project-agent.md'))).toBe(true);
80
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'commands', 'project-command.md'))).toBe(true);
81
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'skills', 'project-skill', 'SKILL.md'))).toBe(true);
82
+
83
+ fs.rmSync(root, { recursive: true, force: true });
84
+ });
85
+
86
+ it('writes global AGENTS.md below XDG_CONFIG_HOME', async () => {
87
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-agents-md-'));
88
+ process.env.XDG_CONFIG_HOME = path.join(root, 'xdg');
89
+ delete process.env.OPENCODE_CONFIG;
90
+
91
+ const [, , , , , , routes] = await loadOpenCodeModules();
92
+ const handlers = new Map();
93
+ const app = {
94
+ get(route, ...callbacks) { handlers.set(`GET ${route}`, callbacks.at(-1)); },
95
+ put(route, ...callbacks) { handlers.set(`PUT ${route}`, callbacks.at(-1)); },
96
+ post() {},
97
+ delete() {},
98
+ };
99
+ routes.registerOpenCodeRoutes(app, {});
100
+
101
+ const response = { json: vi.fn(), status: vi.fn(() => response) };
102
+ await handlers.get('GET /api/behavior/agents-md')({}, response);
103
+ expect(response.json).toHaveBeenLastCalledWith({
104
+ content: '', exists: false, path: path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'),
105
+ });
106
+
107
+ await handlers.get('PUT /api/behavior/agents-md')({ body: { content: 'Global behavior' } }, response);
108
+
109
+ expect(fs.readFileSync(path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'), 'utf8')).toBe('Global behavior');
110
+ await handlers.get('GET /api/behavior/agents-md')({}, response);
111
+ expect(response.json).toHaveBeenLastCalledWith({
112
+ content: 'Global behavior', exists: true, path: path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'),
113
+ });
114
+ fs.rmSync(root, { recursive: true, force: true });
115
+ });
116
+ });
@@ -10,6 +10,7 @@ import { registerDevServerRoutes } from '../dev-servers/routes.js';
10
10
  import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
11
11
  import { registerSessionFoldersRoutes } from '../session-folders/routes.js';
12
12
  import { registerProjectContextRoutes } from '../project-context/routes.js';
13
+ import { registerProjectSetupRoutes } from '../projects/routes.js';
13
14
  import { registerAgentMemoryRoutes } from '../agent-memory/routes.js';
14
15
  import { registerSessionKnowledgeRoutes } from '../session-knowledge/routes.js';
15
16
  import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
@@ -98,6 +99,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
98
99
  createFsSearchRuntime,
99
100
  openchamberDataDir,
100
101
  openchamberUserConfigRoot,
102
+ managedChatsRoot,
101
103
  normalizeDirectoryPath,
102
104
  resolveProjectDirectory,
103
105
  resolveOptionalProjectDirectory,
@@ -313,6 +315,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
313
315
  openchamberDataDir,
314
316
  });
315
317
  registerProjectContextRoutes(app, { projectContextRuntime });
318
+ registerProjectSetupRoutes(app, { projectConfigRuntime });
316
319
  registerAgentMemoryRoutes(app, { agentMemoryRuntime, isAgentMemoryEnabled });
317
320
  registerSessionKnowledgeRoutes(app, { sessionKnowledgeRuntime });
318
321
 
@@ -332,6 +335,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
332
335
  buildAugmentedPath,
333
336
  resolveGitBinaryForSpawn,
334
337
  openchamberUserConfigRoot,
338
+ managedChatsRoot,
335
339
  });
336
340
  };
337
341
 
@@ -0,0 +1,14 @@
1
+ export const DEFAULT_INPUT_HISTORY_SCOPE = 'session';
2
+ export const DEFAULT_INPUT_HISTORY_LIMIT = 40;
3
+ const MIN_INPUT_HISTORY_LIMIT = 1;
4
+ const MAX_INPUT_HISTORY_LIMIT = 100;
5
+
6
+ export const isInputHistoryScope = (value) => (
7
+ value === 'global' || value === 'session'
8
+ );
9
+
10
+ export const isInputHistoryLimit = (value) => (
11
+ Number.isInteger(value)
12
+ && value >= MIN_INPUT_HISTORY_LIMIT
13
+ && value <= MAX_INPUT_HISTORY_LIMIT
14
+ );