@openchamber/web 1.17.0 → 1.17.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 (63) hide show
  1. package/README.md +3 -0
  2. package/dist/assets/{DiagramView-CRjw8BGO.js → DiagramView-CI2JhNxs.js} +1 -1
  3. package/dist/assets/{MarkdownRendererImpl-BjjFniUt.js → MarkdownRendererImpl-Bq-wtyiF.js} +3 -3
  4. package/dist/assets/{OnboardingScreen-JuiKjRTI.js → OnboardingScreen-B6BqjJ0l.js} +1 -1
  5. package/dist/assets/{SessionSwitcherDropdown-S2EvRz-E.js → SessionSwitcherDropdown-DepVWyeA.js} +1 -1
  6. package/dist/assets/{SettingsWindow-PzqMjCEx.js → SettingsWindow-Xj4Uy_Fr.js} +1 -1
  7. package/dist/assets/{document-attachments-DZf4VoiD.js → document-attachments-C5tUWELq.js} +1 -1
  8. package/dist/assets/{es-CErIcckI.js → es-DSTFcl6A.js} +1 -1
  9. package/dist/assets/{fr-z5ORYrou.js → fr-CEeK5ifb.js} +1 -1
  10. package/dist/assets/index-DUBtXIPQ.css +1 -0
  11. package/dist/assets/{index-DMCrPMIW.js → index-Dld5wFqI.js} +3 -3
  12. package/dist/assets/{ja-ecPbYMn0.js → ja-pu3u7ZOY.js} +1 -1
  13. package/dist/assets/{ko-CASkpaQH.js → ko-CStr_CJ-.js} +1 -1
  14. package/dist/assets/{main-BTLr2DyB.js → main-DBG0rE6P.js} +36 -36
  15. package/dist/assets/{main-DQ-uX_zf.js → main-Xc2GeALp.js} +2 -2
  16. package/dist/assets/{markdownCore-C4XTgyYU.js → markdownCore-Bn8Ywh-t.js} +2 -2
  17. package/dist/assets/miniChat-D5FFElbH.js +2 -0
  18. package/dist/assets/mobile-B4K4IpE7.js +2 -0
  19. package/dist/assets/{pl-BYtGQyDI.js → pl-nD08d1Bo.js} +1 -1
  20. package/dist/assets/{pt-BR-D8dONk68.js → pt-BR-DqcoQ-nE.js} +1 -1
  21. package/dist/assets/{renderElectronMiniChatApp-Cbdusroc.js → renderElectronMiniChatApp-B-rksap7.js} +2 -2
  22. package/dist/assets/renderMobileApp-U-jxDI_G.js +16 -0
  23. package/dist/assets/runtimeEndpointReset-fpfBYOyW.js +174 -0
  24. package/dist/assets/{uk-C8z1P8tg.js → uk-DkX7DsWk.js} +1 -1
  25. package/dist/assets/{useAppFontEffects-DrLhDSC3.js → useAppFontEffects-CZdEKvZ8.js} +129 -127
  26. package/dist/assets/{vendor-.bun-DvcSrJLa.js → vendor-.bun-BzW0Lgld.js} +1 -1
  27. package/dist/assets/{zh-CN-BwJPtjKq.js → zh-CN-DlqHNM1o.js} +1 -1
  28. package/dist/assets/{zh-TW-C7FpgD-Y.js → zh-TW-DeKAHBhV.js} +1 -1
  29. package/dist/index.html +4 -4
  30. package/dist/mini-chat.html +4 -4
  31. package/dist/mobile.html +4 -4
  32. package/package.json +2 -2
  33. package/server/index.js +31 -2
  34. package/server/lib/openchamber-sessions/routes.js +30 -30
  35. package/server/lib/openchamber-sessions/routes.test.js +38 -0
  36. package/server/lib/opencode/DOCUMENTATION.md +7 -2
  37. package/server/lib/opencode/env-runtime.js +18 -0
  38. package/server/lib/opencode/env-runtime.test.js +12 -0
  39. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  40. package/server/lib/opencode/lifecycle.js +18 -6
  41. package/server/lib/opencode/lifecycle.test.js +67 -1
  42. package/server/lib/opencode/proxy.js +32 -2
  43. package/server/lib/opencode/routes-upgrade.test.js +113 -0
  44. package/server/lib/opencode/routes.js +69 -36
  45. package/server/lib/opencode/server-utils-runtime.js +2 -0
  46. package/server/lib/opencode/settings-helpers.js +3 -0
  47. package/server/lib/opencode/settings-helpers.test.js +8 -0
  48. package/server/lib/opencode/upgrade-capability.js +36 -0
  49. package/server/lib/opencode/upgrade-capability.test.js +57 -0
  50. package/server/lib/quota/providers/codex.js +18 -0
  51. package/server/lib/quota/providers/codex.test.js +28 -0
  52. package/server/lib/scheduled-tasks/runtime.js +44 -18
  53. package/server/lib/scheduled-tasks/runtime.test.js +12 -1
  54. package/server/lib/session-goal/DOCUMENTATION.md +12 -3
  55. package/server/lib/system-prompt/DOCUMENTATION.md +36 -0
  56. package/server/lib/system-prompt/runtime.js +68 -0
  57. package/server/lib/system-prompt/runtime.test.js +76 -0
  58. package/server/opencode-proxy.test.js +49 -0
  59. package/dist/assets/index-Csh1A7Eh.css +0 -1
  60. package/dist/assets/miniChat-ComIlrTa.js +0 -2
  61. package/dist/assets/mobile-DUYXEkKA.js +0 -2
  62. package/dist/assets/renderMobileApp-m9MPmIZT.js +0 -16
  63. package/dist/assets/runtimeEndpointReset-B0yQKPe0.js +0 -174
package/server/index.js CHANGED
@@ -69,6 +69,7 @@ import { createServerUtilsRuntime } from './lib/opencode/server-utils-runtime.js
69
69
  import { createStaticRoutesRuntime } from './lib/opencode/static-routes-runtime.js';
70
70
  import { createSettingsRuntime } from './lib/opencode/settings-runtime.js';
71
71
  import { createOpenCodeResolutionRuntime } from './lib/opencode/opencode-resolution-runtime.js';
72
+ import { resolveOpenCodeUpgradeCapability } from './lib/opencode/upgrade-capability.js';
72
73
  import { createBootstrapRuntime } from './lib/opencode/bootstrap-runtime.js';
73
74
  import { createSessionRuntime } from './lib/opencode/session-runtime.js';
74
75
  import { createOpenCodeWatcherRuntime } from './lib/opencode/watcher.js';
@@ -96,6 +97,7 @@ import { attachRealtimeProxy } from './lib/realtime-proxy.js';
96
97
  import { createRelayService } from './lib/relay/service.js';
97
98
  import { createRelayHostLock } from './lib/relay/host-lock.js';
98
99
  import { createAgentToolRuntime } from './lib/agent-tool/runtime.js';
100
+ import { createSystemPromptRuntime } from './lib/system-prompt/runtime.js';
99
101
  import { createOpenChamberSessionService } from './lib/openchamber-sessions/routes.js';
100
102
  import { createScheduledTaskService } from './lib/scheduled-tasks/service.js';
101
103
  import { createOpenChamberControlService } from './lib/openchamber-control/service.js';
@@ -269,6 +271,7 @@ const readCustomThemesFromDisk = (...args) => themeRuntime.readCustomThemesFromD
269
271
 
270
272
  let notificationTemplateRuntime = null;
271
273
  let agentToolRuntime = null;
274
+ let systemPromptRuntime = null;
272
275
 
273
276
  const createTimeoutSignal = (...args) => notificationTemplateRuntime.createTimeoutSignal(...args);
274
277
  const formatProjectLabel = (...args) => notificationTemplateRuntime.formatProjectLabel(...args);
@@ -664,6 +667,7 @@ const getLoginShellEnvSnapshot = (...args) => openCodeEnvRuntime.getLoginShellEn
664
667
  const ensureOpencodeCliEnv = (...args) => openCodeEnvRuntime.ensureOpencodeCliEnv(...args);
665
668
  const applyOpencodeBinaryFromSettings = (...args) => openCodeEnvRuntime.applyOpencodeBinaryFromSettings(...args);
666
669
  const resolveOpencodeCliPath = (...args) => openCodeEnvRuntime.resolveOpencodeCliPath(...args);
670
+ const isBundledOpenCodeCliPath = (...args) => openCodeEnvRuntime.isBundledOpenCodeCliPath(...args);
667
671
  const isExecutable = (...args) => openCodeEnvRuntime.isExecutable(...args);
668
672
  const searchPathFor = (...args) => openCodeEnvRuntime.searchPathFor(...args);
669
673
  const resolveGitBinaryForSpawn = (...args) => openCodeEnvRuntime.resolveGitBinaryForSpawn(...args);
@@ -891,6 +895,7 @@ const serverUtilsRuntime = createServerUtilsRuntime({
891
895
  getOpenCodeAuthHeaders,
892
896
  buildOpenCodeUrl,
893
897
  ensureOpenCodeApiPrefix,
898
+ getUpstreamStallTimeoutMs,
894
899
  getUiNotificationClients: () => uiNotificationClients,
895
900
  getOpenCodePort: () => openCodePort,
896
901
  setOpenCodePortState: (value) => {
@@ -1056,11 +1061,29 @@ const openCodeLifecycleRuntime = createOpenCodeLifecycleRuntime({
1056
1061
  getActiveSessionCount,
1057
1062
  getManagedOpenCodeEnv: async () => {
1058
1063
  const settings = await readSettingsFromDiskMigrated().catch(() => null);
1059
- if (settings?.agentControlToolEnabled === false) return {};
1060
- return agentToolRuntime?.prepareManagedOpenCodeEnv() || {};
1064
+ const managedEnv = settings?.agentControlToolEnabled === false
1065
+ ? {}
1066
+ : await (agentToolRuntime?.prepareManagedOpenCodeEnv() || {});
1067
+ if (settings?.optimizeSystemPrompt !== true) return managedEnv;
1068
+
1069
+ const configContent = managedEnv.OPENCODE_CONFIG_CONTENT ?? process.env.OPENCODE_CONFIG_CONTENT;
1070
+ const systemPromptEnv = await systemPromptRuntime.prepareManagedOpenCodeEnv(configContent);
1071
+ return { ...managedEnv, ...systemPromptEnv };
1061
1072
  },
1062
1073
  });
1063
1074
 
1075
+ const getOpenCodeUpgradeCapability = () => {
1076
+ const activeBinary = lastOpenCodeLaunchDiagnostics?.sourceBinary
1077
+ || lastOpenCodeLaunchDiagnostics?.binary
1078
+ || resolvedOpencodeBinary;
1079
+ return resolveOpenCodeUpgradeCapability({
1080
+ isExternal: isExternalOpenCode,
1081
+ hasManagedProcess: Boolean(openCodeProcess),
1082
+ activeBinary,
1083
+ isBundledBinary: isBundledOpenCodeCliPath,
1084
+ });
1085
+ };
1086
+
1064
1087
  const restartOpenCode = (...args) => openCodeLifecycleRuntime.restartOpenCode(...args);
1065
1088
  const waitForOpenCodeReady = (...args) => openCodeLifecycleRuntime.waitForOpenCodeReady(...args);
1066
1089
  const waitForAgentPresence = (...args) => openCodeLifecycleRuntime.waitForAgentPresence(...args);
@@ -1240,6 +1263,11 @@ async function main(options = {}) {
1240
1263
  return typeof address === 'object' && address ? address.port : null;
1241
1264
  },
1242
1265
  });
1266
+ systemPromptRuntime = createSystemPromptRuntime({
1267
+ fsPromises,
1268
+ path,
1269
+ dataDir: OPENCHAMBER_DATA_DIR,
1270
+ });
1243
1271
 
1244
1272
  // Pairing transports advertised to the create-device dialog. LAN reachability is
1245
1273
  // derived from the SERVER's actual bind (a wildcard bind → the machine's LAN IP;
@@ -1586,6 +1614,7 @@ async function main(options = {}) {
1586
1614
  readCustomThemesFromDisk,
1587
1615
  refreshOpenCodeAfterConfigChange,
1588
1616
  getOpenCodeResolutionSnapshot,
1617
+ getOpenCodeUpgradeCapability,
1589
1618
  formatSettingsResponse,
1590
1619
  readSettingsFromDisk,
1591
1620
  readSettingsFromDiskMigrated,
@@ -2,7 +2,7 @@ import express from 'express';
2
2
  import { createOpencodeClient } from '@opencode-ai/sdk/v2';
3
3
  import { createWorktree } from '../git/index.js';
4
4
  import { expandSnippets } from '../opencode/snippets.js';
5
- import { parseScheduledCommandPrompt } from '../scheduled-tasks/runtime.js';
5
+ import { expandCommandGoalObjective, parseScheduledCommandPrompt } from '../scheduled-tasks/runtime.js';
6
6
  import { buildGoalIntroText, createSessionGoal } from '../session-goal/create.js';
7
7
  import { OpenChamberControlError, asControlError } from '../openchamber-control/error.js';
8
8
 
@@ -369,13 +369,27 @@ export const createOpenChamberSessionService = (dependencies) => {
369
369
  }
370
370
 
371
371
  const expandedPrompt = expandSnippets(prompt, directory);
372
+ const parsedCommand = parseScheduledCommandPrompt(prompt);
373
+ let resolvedCommand = null;
374
+ if (parsedCommand) {
375
+ try {
376
+ const response = await client.command.list({ directory });
377
+ const commands = Array.isArray(response?.data) ? response.data : [];
378
+ const command = commands.find((candidate) => candidate?.name === parsedCommand.command);
379
+ if (command) resolvedCommand = { ...parsedCommand, template: command.template };
380
+ } catch {
381
+ }
382
+ }
372
383
  if (goalInput.enabled) {
384
+ const commandObjective = resolvedCommand
385
+ ? expandCommandGoalObjective(resolvedCommand.template, resolvedCommand.arguments)
386
+ : null;
373
387
  await (createSessionGoalOverride || createSessionGoal)({
374
388
  baseUrl,
375
389
  authHeaders,
376
390
  sessionID,
377
391
  directory,
378
- objective: expandedPrompt,
392
+ objective: commandObjective ?? expandedPrompt,
379
393
  tokenBudget: goalInput.tokenBudget,
380
394
  providerID: model.providerID,
381
395
  modelID: model.modelID,
@@ -388,35 +402,21 @@ export const createOpenChamberSessionService = (dependencies) => {
388
402
  return error;
389
403
  };
390
404
 
391
- let dispatchedAsCommand = false;
392
- const parsedCommand = parseScheduledCommandPrompt(prompt);
393
- if (parsedCommand) {
394
- let commandExists = false;
405
+ if (resolvedCommand) {
395
406
  try {
396
- const response = await client.command.list({ directory });
397
- const commands = Array.isArray(response?.data) ? response.data : [];
398
- commandExists = commands.some((command) => command?.name === parsedCommand.command);
399
- } catch {
400
- }
401
- if (commandExists) {
402
- try {
403
- await client.session.command({
404
- sessionID,
405
- directory,
406
- command: parsedCommand.command,
407
- arguments: parsedCommand.arguments,
408
- ...(agent ? { agent } : {}),
409
- model: `${model.providerID}/${model.modelID}`,
410
- ...(variant ? { variant } : {}),
411
- });
412
- } catch (error) {
413
- throw markGoalPartial(error);
414
- }
415
- dispatchedAsCommand = true;
407
+ await client.session.command({
408
+ sessionID,
409
+ directory,
410
+ command: resolvedCommand.command,
411
+ arguments: resolvedCommand.arguments,
412
+ ...(agent ? { agent } : {}),
413
+ model: `${model.providerID}/${model.modelID}`,
414
+ ...(variant ? { variant } : {}),
415
+ });
416
+ } catch (error) {
417
+ throw markGoalPartial(error);
416
418
  }
417
- }
418
-
419
- if (!dispatchedAsCommand) {
419
+ } else {
420
420
  try {
421
421
  await runPromptAsync({
422
422
  baseUrl,
@@ -440,7 +440,7 @@ export const createOpenChamberSessionService = (dependencies) => {
440
440
  }
441
441
  }
442
442
 
443
- return { model, agent, variant, promptDispatched: true, dispatchedAsCommand };
443
+ return { model, agent, variant, promptDispatched: true, dispatchedAsCommand: Boolean(resolvedCommand) };
444
444
  };
445
445
 
446
446
  const create = async (payload = {}) => {
@@ -361,6 +361,44 @@ describe('openchamber session routes', () => {
361
361
  }
362
362
  });
363
363
 
364
+ it('uses the expanded slash-command template as the goal objective before command dispatch', async () => {
365
+ const originalFetch = globalThis.fetch;
366
+ const createSessionGoal = vi.fn(async () => undefined);
367
+ commandListMock.mockResolvedValue({
368
+ data: [{
369
+ name: 'issue--to-pr',
370
+ template: 'Take $ARGUMENTS from issue through a verified pull request. Confirm the PR covers $ARGUMENTS.',
371
+ }],
372
+ });
373
+ globalThis.fetch = vi.fn();
374
+ try {
375
+ const { app } = createApp({ createSessionGoal });
376
+ const response = await request(app)
377
+ .post('/api/openchamber/sessions/ses_source/send')
378
+ .send({
379
+ directory: '/repo/app',
380
+ prompt: '/issue--to-pr LIN-123',
381
+ model: 'openai/gpt-5.5',
382
+ agent: 'build',
383
+ goal: true,
384
+ })
385
+ .expect(200);
386
+
387
+ expect(createSessionGoal).toHaveBeenCalledWith(expect.objectContaining({
388
+ objective: 'Take LIN-123 from issue through a verified pull request. Confirm the PR covers LIN-123.',
389
+ }));
390
+ expect(sessionCommandMock).toHaveBeenCalledWith(expect.objectContaining({
391
+ command: 'issue--to-pr',
392
+ arguments: 'LIN-123',
393
+ }));
394
+ expect(createSessionGoal.mock.invocationCallOrder[0]).toBeLessThan(sessionCommandMock.mock.invocationCallOrder[0]);
395
+ expect(response.body).toMatchObject({ goalEnabled: true, dispatchedAsCommand: true });
396
+ expect(globalThis.fetch).not.toHaveBeenCalled();
397
+ } finally {
398
+ globalThis.fetch = originalFetch;
399
+ }
400
+ });
401
+
364
402
  it('reuses the previous session selection when send omits model, agent, and variant', async () => {
365
403
  const originalFetch = globalThis.fetch;
366
404
  const fetchMock = vi.fn(async () => ({ ok: true, text: async () => '' }));
@@ -26,9 +26,11 @@ This module provides OpenCode server integration utilities for the web server ru
26
26
  - `packages/web/server/lib/opencode/static-routes-runtime.js`: static asset/SPA fallback route registration and manifest route wiring.
27
27
  - `packages/web/server/lib/opencode/feature-routes-runtime.js`: feature route composition runtime for dynamic import-backed config/skill/provider route registration.
28
28
  - `packages/web/server/lib/opencode/opencode-resolution-runtime.js`: OpenCode binary resolution snapshot runtime for settings routes and diagnostics.
29
+ - `packages/web/server/lib/opencode/upgrade-capability.js`: authoritative upgrade ownership policy for the active OpenCode runtime. Bundled, external, and unresolved runtimes fail closed; only managed non-bundled runtimes delegate upgrades to OpenCode.
29
30
  - `packages/web/server/lib/opencode/tunnel-wiring-runtime.js`: tunnel service/routes composition runtime and active-port wiring for main server startup.
30
31
  - `packages/web/server/lib/opencode/startup-pipeline-runtime.js`: server startup tail orchestration runtime for terminal/proxy/static/start-listen flow.
31
32
  - `packages/web/server/lib/agent-tool/runtime.js`: managed OpenCode custom-tool materialization, environment injection, loopback authentication, and fixed CLI action dispatch.
33
+ - `packages/web/server/lib/system-prompt/runtime.js`: opt-in managed OpenCode system-prompt optimizer materialization and plugin injection.
32
34
  - `packages/web/server/lib/opencode/server-utils-runtime.js`: shared server runtime utilities for OpenCode proxy wiring, OpenCode port/readiness helpers, and snapshot fetchers.
33
35
  - `packages/web/server/lib/opencode/openchamber-routes.js`: OpenChamber update and models metadata route registration.
34
36
  - `packages/web/server/lib/opencode/pwa-manifest-routes.js`: PWA manifest route registration with recent-session shortcut resolution and short-lived caching.
@@ -75,8 +77,8 @@ This module provides OpenCode server integration utilities for the web server ru
75
77
  - `GET /api/config/settings`
76
78
  - `PUT /api/config/settings`
77
79
  - `GET /api/config/opencode-resolution`
78
- - `POST /api/opencode/upgrade` (proxies OpenCode upgrade, then restarts managed OpenCode so the new binary is active)
79
- - `GET /api/opencode/upgrade-status`
80
+ - `POST /api/opencode/upgrade` (enforces the active runtime's upgrade capability, serializes supported OpenCode upgrades, then restarts managed OpenCode so the new binary is active)
81
+ - `GET /api/opencode/upgrade-status` (returns version availability plus the authoritative `upgrade.supported`, `upgrade.manager`, and `upgrade.reason` capability)
80
82
  - `POST /api/opencode/directory`
81
83
  - `GET /api/provider/:providerId/source`
82
84
  - `DELETE /api/provider/:providerId/auth`
@@ -119,6 +121,8 @@ runtime. PATH and `OPENCODE_SERVER_PASSWORD` remain lifecycle-owned and cannot
119
121
  be replaced by injected values. External OpenCode processes receive no
120
122
  OpenChamber tool injection.
121
123
 
124
+ Transport-triggered health checks share the periodic monitor's failure accounting interval. Rapid WS reconnect callbacks therefore cannot exhaust the managed-process restart threshold using one cached unhealthy result; an exited managed process still restarts immediately.
125
+
122
126
  ## Public exports (env-runtime.js)
123
127
  - `createOpenCodeEnvRuntime(dependencies)`: creates runtime that owns OpenCode CLI environment and binary discovery state.
124
128
  - OpenCode CLI resolution order is persisted settings, environment overrides, bundled Desktop CLI when available, PATH, known install locations, then platform shell discovery.
@@ -349,6 +353,7 @@ an authoritative loopback callback URL even when OpenChamber binds port `0`.
349
353
  - `registerOpenCodeProxy(app, dependencies)`: registers OpenCode proxy routes and middleware.
350
354
  - Owns:
351
355
  - SSE forwarders: `GET /api/global/event`, `GET /api/event`
356
+ - Downstream heartbeats keep clients and intermediaries alive, while a separate upstream-only stall watchdog closes the downstream response when OpenCode stops producing bytes so clients reconnect instead of trusting synthetic heartbeats indefinitely. Each watchdog reset uses the current load-aware timeout, matching the shared event transport.
352
357
  - Session message forwarder: `POST /api/session/:sessionId/message`
353
358
  - Generic `/api/*` forwarding with hop-by-hop header filtering
354
359
  - Windows `/session` merge fallback path behavior
@@ -301,6 +301,23 @@ export const createOpenCodeEnvRuntime = (deps) => {
301
301
  return null;
302
302
  };
303
303
 
304
+ const canonicalExecutablePath = (candidate) => {
305
+ if (typeof candidate !== 'string' || !candidate.trim()) return null;
306
+ try {
307
+ return fs.realpathSync.native(candidate.trim());
308
+ } catch {
309
+ return path.resolve(candidate.trim());
310
+ }
311
+ };
312
+
313
+ const isBundledOpenCodeCliPath = (candidate) => {
314
+ const canonicalCandidate = canonicalExecutablePath(candidate);
315
+ if (!canonicalCandidate) return false;
316
+ return bundledOpenCodeCliCandidates().some((bundledCandidate) => (
317
+ canonicalExecutablePath(bundledCandidate) === canonicalCandidate
318
+ ));
319
+ };
320
+
304
321
  const bundledOpenCodeCliFallback = () => {
305
322
  const bundled = resolveBundledOpenCodeCliPath();
306
323
  if (!bundled) return null;
@@ -1164,6 +1181,7 @@ export const createOpenCodeEnvRuntime = (deps) => {
1164
1181
  applyOpencodeBinaryFromSettings,
1165
1182
  getLoginShellEnvSnapshot,
1166
1183
  resolveOpencodeCliPath,
1184
+ isBundledOpenCodeCliPath,
1167
1185
  resolveManagedOpenCodeLaunchSpec,
1168
1186
  isExecutable,
1169
1187
  searchPathFor,
@@ -183,6 +183,18 @@ describe('OpenCode env runtime', () => {
183
183
  expect(state.resolvedOpencodeBinarySource).toBe('bundled');
184
184
  });
185
185
 
186
+ it('recognizes the bundled CLI by canonical path', () => {
187
+ const bundledDir = createTempDir('openchamber-bundled-opencode-');
188
+ const bundledBinary = path.join(bundledDir, process.platform === 'win32' ? 'opencode.exe' : 'opencode');
189
+ fs.writeFileSync(bundledBinary, '#!/bin/sh\nexit 0\n');
190
+ if (process.platform !== 'win32') fs.chmodSync(bundledBinary, 0o755);
191
+ process.env.OPENCHAMBER_BUNDLED_OPENCODE_CLI_DIR = bundledDir;
192
+ const { runtime } = createRuntime({});
193
+
194
+ expect(runtime.isBundledOpenCodeCliPath(bundledBinary)).toBe(true);
195
+ expect(runtime.isBundledOpenCodeCliPath(path.join(bundledDir, 'other'))).toBe(false);
196
+ });
197
+
186
198
  it('keeps explicit OpenCode binary ahead of bundled CLI', () => {
187
199
  const bundledDir = createTempDir('openchamber-bundled-opencode-');
188
200
  const bundledBinary = path.join(bundledDir, process.platform === 'win32' ? 'opencode.exe' : 'opencode');
@@ -86,6 +86,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
86
86
  readCustomThemesFromDisk,
87
87
  refreshOpenCodeAfterConfigChange,
88
88
  getOpenCodeResolutionSnapshot,
89
+ getOpenCodeUpgradeCapability,
89
90
  formatSettingsResponse,
90
91
  readSettingsFromDisk,
91
92
  readSettingsFromDiskMigrated,
@@ -121,6 +122,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
121
122
  crypto,
122
123
  clientReloadDelayMs,
123
124
  getOpenCodeResolutionSnapshot,
125
+ getOpenCodeUpgradeCapability,
124
126
  formatSettingsResponse,
125
127
  readSettingsFromDisk,
126
128
  readSettingsFromDiskMigrated,
@@ -40,6 +40,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
40
40
  getManagedOpenCodeShellEnvSnapshot,
41
41
  getManagedOpenCodeEnv = async () => ({}),
42
42
  getActiveSessionCount = () => 0,
43
+ now = Date.now,
43
44
  } = deps;
44
45
 
45
46
  const killProcessOnPort = (port) => {
@@ -240,6 +241,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
240
241
 
241
242
  const createManagedOpenCodeServerProcess = async ({ hostname, port, timeout, cwd, env: processEnv, shellEnvKeysCount = 0 }) => {
242
243
  let binary = (process.env.OPENCODE_BINARY || 'opencode').trim() || 'opencode';
244
+ const sourceBinary = binary;
243
245
  let args = ['serve', '--hostname', hostname, '--port', String(port)];
244
246
  let launchWrapperType = null;
245
247
 
@@ -263,6 +265,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
263
265
  const pathEntryCount = pathValue ? pathValue.split(process.platform === 'win32' ? ';' : ':').filter(Boolean).length : 0;
264
266
  state.lastOpenCodeLaunchDiagnostics = {
265
267
  launchedAt: new Date().toISOString(),
268
+ sourceBinary,
266
269
  binary,
267
270
  args,
268
271
  cwd,
@@ -871,18 +874,21 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
871
874
  const STALE_BUSY_GRACE_MS = 2 * 60 * 1000;
872
875
  let lastUnhealthyWithBusySessionsAt = 0;
873
876
  let consecutiveHealthFailures = 0;
877
+ let lastCountedHealthFailureAt = 0;
874
878
  let healthProbePromise = null;
875
879
  let healthCheckCyclePromise = null;
876
880
  let lastHealthProbeResult = null;
881
+ let healthFailureCountIntervalMs = 15_000;
877
882
 
878
883
  const resetHealthFailureState = () => {
879
884
  consecutiveHealthFailures = 0;
880
885
  lastUnhealthyWithBusySessionsAt = 0;
886
+ lastCountedHealthFailureAt = 0;
881
887
  };
882
888
 
883
889
  const probeOpenCodeHealth = async () => {
884
- const now = Date.now();
885
- if (lastHealthProbeResult && now - lastHealthProbeResult.at < HEALTH_CHECK_RESULT_CACHE_MS) {
890
+ const checkedAt = now();
891
+ if (lastHealthProbeResult && checkedAt - lastHealthProbeResult.at < HEALTH_CHECK_RESULT_CACHE_MS) {
886
892
  return lastHealthProbeResult.healthy;
887
893
  }
888
894
 
@@ -892,7 +898,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
892
898
 
893
899
  healthProbePromise = isOpenCodeProcessHealthy()
894
900
  .then((healthy) => {
895
- lastHealthProbeResult = { at: Date.now(), healthy };
901
+ lastHealthProbeResult = { at: now(), healthy };
896
902
  return healthy;
897
903
  })
898
904
  .finally(() => {
@@ -909,13 +915,13 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
909
915
  return false;
910
916
  }
911
917
 
912
- const now = Date.now();
918
+ const checkedAt = now();
913
919
  if (!lastUnhealthyWithBusySessionsAt) {
914
- lastUnhealthyWithBusySessionsAt = now;
920
+ lastUnhealthyWithBusySessionsAt = checkedAt;
915
921
  return true;
916
922
  }
917
923
 
918
- if (now - lastUnhealthyWithBusySessionsAt >= STALE_BUSY_GRACE_MS) {
924
+ if (checkedAt - lastUnhealthyWithBusySessionsAt >= STALE_BUSY_GRACE_MS) {
919
925
  console.warn(
920
926
  `[lifecycle] OpenCode unhealthy with ${activeCount} busy session(s) for > 2 min — forcing restart`
921
927
  );
@@ -940,6 +946,11 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
940
946
  await restartOpenCode();
941
947
  return;
942
948
  }
949
+ const checkedAt = now();
950
+ if (lastCountedHealthFailureAt && checkedAt - lastCountedHealthFailureAt < healthFailureCountIntervalMs) {
951
+ return;
952
+ }
953
+ lastCountedHealthFailureAt = checkedAt;
943
954
  consecutiveHealthFailures += 1;
944
955
  console.warn(
945
956
  `[lifecycle] ${source} health check failed (${consecutiveHealthFailures}/${HEALTH_CHECK_MAX_CONSECUTIVE_FAILURES})`
@@ -974,6 +985,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
974
985
  }
975
986
 
976
987
  const effectiveIntervalMs = HEALTH_CHECK_INTERVAL_OVERRIDE_MS || healthCheckIntervalMs;
988
+ healthFailureCountIntervalMs = effectiveIntervalMs;
977
989
 
978
990
  state.healthCheckInterval = setInterval(async () => {
979
991
  try {
@@ -12,9 +12,11 @@ const { createOpenCodeLifecycleRuntime } = await import('./lifecycle.js');
12
12
 
13
13
  const originalOpencodeBinary = process.env.OPENCODE_BINARY;
14
14
  const originalPath = process.env.PATH;
15
+ const originalFetch = globalThis.fetch;
15
16
 
16
17
  afterEach(() => {
17
18
  spawnMock.mockReset();
19
+ globalThis.fetch = originalFetch;
18
20
  if (typeof originalOpencodeBinary === 'string') {
19
21
  process.env.OPENCODE_BINARY = originalOpencodeBinary;
20
22
  } else {
@@ -43,7 +45,7 @@ const createMockChild = () => {
43
45
  return child;
44
46
  };
45
47
 
46
- const createRuntime = (overrides = {}) => {
48
+ const createRuntime = (overrides = {}, stateOverrides = {}) => {
47
49
  const state = {
48
50
  openCodeWorkingDirectory: '/tmp/project',
49
51
  openCodeProcess: null,
@@ -65,6 +67,7 @@ const createRuntime = (overrides = {}) => {
65
67
  resolvedWslBinary: null,
66
68
  resolvedWslOpencodePath: null,
67
69
  resolvedWslDistro: null,
70
+ ...stateOverrides,
68
71
  };
69
72
 
70
73
  return createOpenCodeLifecycleRuntime({
@@ -105,6 +108,69 @@ const createRuntime = (overrides = {}) => {
105
108
  };
106
109
 
107
110
  describe('OpenCode lifecycle', () => {
111
+ it('does not count rapid transport-triggered checks as independent health failures', async () => {
112
+ const close = vi.fn(async () => {});
113
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
114
+ let now = 1;
115
+ globalThis.fetch = vi.fn(async () => ({
116
+ ok: false,
117
+ json: async () => null,
118
+ }));
119
+ const runtime = createRuntime({ now: () => now }, {
120
+ openCodePort: 45678,
121
+ openCodeProcess: {
122
+ pid: null,
123
+ exitCode: null,
124
+ signalCode: null,
125
+ close,
126
+ },
127
+ isOpenCodeReady: true,
128
+ });
129
+
130
+ for (let attempt = 0; attempt < 25; attempt += 1) {
131
+ await runtime.triggerHealthCheck();
132
+ }
133
+
134
+ expect(close).not.toHaveBeenCalled();
135
+ expect(warn).toHaveBeenCalledTimes(1);
136
+
137
+ now += 15_000;
138
+ await runtime.triggerHealthCheck();
139
+
140
+ expect(warn).toHaveBeenCalledTimes(2);
141
+ expect(warn).toHaveBeenLastCalledWith(expect.stringContaining('(2/20)'));
142
+ warn.mockRestore();
143
+ });
144
+
145
+ it('restarts an exited managed process without waiting for the failure interval', async () => {
146
+ const close = vi.fn(async () => {});
147
+ const replacement = createMockChild();
148
+ globalThis.fetch = vi.fn(async () => ({
149
+ ok: false,
150
+ json: async () => null,
151
+ }));
152
+ spawnMock.mockImplementationOnce(() => {
153
+ queueMicrotask(() => {
154
+ replacement.stdout.emit('data', 'opencode server listening on http://127.0.0.1:45678\n');
155
+ });
156
+ return replacement;
157
+ });
158
+ const runtime = createRuntime({}, {
159
+ openCodePort: 45678,
160
+ openCodeProcess: {
161
+ pid: null,
162
+ exitCode: 1,
163
+ signalCode: null,
164
+ close,
165
+ },
166
+ });
167
+
168
+ await runtime.triggerHealthCheck();
169
+
170
+ expect(close).toHaveBeenCalledTimes(1);
171
+ expect(spawnMock).toHaveBeenCalledTimes(1);
172
+ });
173
+
108
174
  it('launches managed OpenCode with the managed PATH', async () => {
109
175
  delete process.env.OPENCODE_BINARY;
110
176
  const child = createMockChild();
@@ -6,6 +6,9 @@ import {
6
6
  shouldForwardProxyResponseHeader,
7
7
  } from '../../proxy-headers.js';
8
8
  import { createRealpathCache } from '../path-realpath-cache.js';
9
+ import { DEFAULT_UPSTREAM_STALL_TIMEOUT_MS } from '../event-stream/upstream-reader.js';
10
+
11
+ const DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 20_000;
9
12
 
10
13
  export const createDirectoryQueryCanonicalizer = ({ realpath, ...cacheOptions } = {}) => {
11
14
  const realpathCache = createRealpathCache({ fallbackOnError: true, realpath, ...cacheOptions });
@@ -186,6 +189,9 @@ export const registerOpenCodeProxy = (app, deps) => {
186
189
  getOpenCodeAuthHeaders,
187
190
  buildOpenCodeUrl,
188
191
  ensureOpenCodeApiPrefix,
192
+ SSE_HEARTBEAT_INTERVAL_MS = DEFAULT_SSE_HEARTBEAT_INTERVAL_MS,
193
+ SSE_UPSTREAM_STALL_TIMEOUT_MS = DEFAULT_UPSTREAM_STALL_TIMEOUT_MS,
194
+ getSseUpstreamStallTimeoutMs = () => SSE_UPSTREAM_STALL_TIMEOUT_MS,
189
195
  } = deps;
190
196
 
191
197
  if (app.get('opencodeProxyConfigured')) {
@@ -340,6 +346,8 @@ export const registerOpenCodeProxy = (app, deps) => {
340
346
  let upstream = null;
341
347
  let reader = null;
342
348
  let heartbeatTimer = null;
349
+ let upstreamStallTimer = null;
350
+ let didUpstreamStall = false;
343
351
  let writeQueue = Promise.resolve(true);
344
352
  const sseBoundary = createSseBoundaryTracker();
345
353
 
@@ -392,8 +400,6 @@ export const registerOpenCodeProxy = (app, deps) => {
392
400
  res.socket.setNoDelay(true);
393
401
  }
394
402
 
395
- const SSE_HEARTBEAT_INTERVAL_MS = 20_000;
396
-
397
403
  const scheduleHeartbeat = () => {
398
404
  heartbeatTimer = setTimeout(async () => {
399
405
  if (abortController.signal.aborted || res.writableEnded || res.destroyed) {
@@ -410,6 +416,20 @@ export const registerOpenCodeProxy = (app, deps) => {
410
416
  }, SSE_HEARTBEAT_INTERVAL_MS);
411
417
  };
412
418
 
419
+ const clearUpstreamStallTimer = () => {
420
+ clearTimeout(upstreamStallTimer);
421
+ upstreamStallTimer = null;
422
+ };
423
+
424
+ const resetUpstreamStallTimer = () => {
425
+ clearUpstreamStallTimer();
426
+ upstreamStallTimer = setTimeout(() => {
427
+ didUpstreamStall = true;
428
+ abortController.abort();
429
+ }, getSseUpstreamStallTimeoutMs());
430
+ upstreamStallTimer.unref?.();
431
+ };
432
+
413
433
  const enqueueSseWrite = (value) => {
414
434
  writeQueue = writeQueue
415
435
  .catch(() => false)
@@ -423,6 +443,7 @@ export const registerOpenCodeProxy = (app, deps) => {
423
443
  };
424
444
 
425
445
  scheduleHeartbeat();
446
+ resetUpstreamStallTimer();
426
447
 
427
448
  reader = upstream.body.getReader();
428
449
  while (!abortController.signal.aborted) {
@@ -431,6 +452,7 @@ export const registerOpenCodeProxy = (app, deps) => {
431
452
  break;
432
453
  }
433
454
  if (value && value.length > 0) {
455
+ resetUpstreamStallTimer();
434
456
  sseBoundary.observe(value);
435
457
  const canContinue = await enqueueSseWrite(value);
436
458
  if (!canContinue) {
@@ -442,6 +464,10 @@ export const registerOpenCodeProxy = (app, deps) => {
442
464
  res.end();
443
465
  } catch (error) {
444
466
  if (isAbortError(error)) {
467
+ if (didUpstreamStall && !res.writableEnded && !res.destroyed) {
468
+ await writeQueue.catch(() => false);
469
+ res.end();
470
+ }
445
471
  return;
446
472
  }
447
473
  console.error('[proxy] OpenCode SSE proxy error:', error?.message ?? error);
@@ -455,6 +481,10 @@ export const registerOpenCodeProxy = (app, deps) => {
455
481
  clearTimeout(heartbeatTimer);
456
482
  heartbeatTimer = null;
457
483
  }
484
+ if (upstreamStallTimer) {
485
+ clearTimeout(upstreamStallTimer);
486
+ upstreamStallTimer = null;
487
+ }
458
488
  req.off('close', closeUpstream);
459
489
  try {
460
490
  if (reader) {