@openchamber/web 1.23.0 → 1.23.2

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 (154) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-DbcnxAfY.js → CodeMirrorCommentWidgets-DdNGwbBw.js} +1 -1
  2. package/dist/assets/DiffView-GYriC0Wk.js +4 -0
  3. package/dist/assets/{DirtyBranchSwitchDialog-DE2sKIYv.js → DirtyBranchSwitchDialog-Bv0C99hc.js} +1 -1
  4. package/dist/assets/FilesView-2Lin13wx.js +13 -0
  5. package/dist/assets/{GitView-CKgUkb5Z.js → GitView-9wKba3UO.js} +4 -4
  6. package/dist/assets/{JsonTreeView-Bce2ettZ.js → JsonTreeView-Chzx5Y6N.js} +1 -1
  7. package/dist/assets/{LinearIssuesView-BZVWM2zw.js → LinearIssuesView-DXS9QJiR.js} +1 -1
  8. package/dist/assets/{MarkdownImageGallery-DdROVz29.js → MarkdownImageGallery-CugnrZ6f.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-CenrzmMN.js → MarkdownRendererImpl-CaMyct2Q.js} +4 -4
  10. package/dist/assets/{OnboardingScreen-DyqYG_NP.js → OnboardingScreen-hH9xcTjA.js} +1 -1
  11. package/dist/assets/{PatchDiff-CR3RVO5I.js → PatchDiff-DRgNYc9l.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-KihzO94X.js → PierreDiffViewer-ZT2CKuzJ.js} +1 -1
  13. package/dist/assets/PlanView-DiTBm2BD.js +5 -0
  14. package/dist/assets/SettingsView-CN8VeM99.js +28 -0
  15. package/dist/assets/{SettingsWindow-CV_hzB5v.js → SettingsWindow-DisOghhD.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-llKecK_Z.js → ToolOutputDialog-BqiKydxR.js} +6 -6
  17. package/dist/assets/{ToolPartDiffPreview-ZDMTdCGn.js → ToolPartDiffPreview-oWxWCu-4.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-ClvqQ4j0.js → VirtualizedFileDiff-CiyrAq_I.js} +4 -4
  19. package/dist/assets/WalkthroughView-CKTevaea.js +4 -0
  20. package/dist/assets/{computeVirtualFileMetrics-Nm5_wabb.js → computeVirtualFileMetrics-SUWoTyPe.js} +2 -2
  21. package/dist/assets/de-DQWC94VK.js +10 -0
  22. package/dist/assets/es-DixFUD3m.js +16 -0
  23. package/dist/assets/{fr-CP6jqIzw.js → fr-D6u8tvfA.js} +4 -4
  24. package/dist/assets/index-BvpFzhLs.js +40 -0
  25. package/dist/assets/{index-Du9sZhDb.js → index-C4jJ3Ur5.js} +1 -1
  26. package/dist/assets/index-n5p3SnES.css +1 -0
  27. package/dist/assets/{isDiffPlainText-EQERIius.js → isDiffPlainText-DfG0cZxr.js} +1 -1
  28. package/dist/assets/{isFilePlainText-BCoVpkQy.js → isFilePlainText-CyNivOCU.js} +1 -1
  29. package/dist/assets/ja-4u4pCorB.js +16 -0
  30. package/dist/assets/ko-C27-LW_b.js +16 -0
  31. package/dist/assets/{main-DPf32fO6.js → main-B8cGozKr.js} +2 -2
  32. package/dist/assets/main-tEA-fFPg.js +930 -0
  33. package/dist/assets/markdownCore-kyGrWGsn.js +5 -0
  34. package/dist/assets/{miniChat-CHqVTsgj.js → miniChat-Cay99IxR.js} +2 -2
  35. package/dist/assets/{mobile-BQmgHA57.js → mobile-Zfhix7nz.js} +2 -2
  36. package/dist/assets/patchFileDiff-CJ5AN9Ql.js +13 -0
  37. package/dist/assets/{pl-B215pG1Y.js → pl-FtCjsNdW.js} +4 -4
  38. package/dist/assets/pt-BR-CLosVawq.js +16 -0
  39. package/dist/assets/renderElectronMiniChatApp-CuHOGlF4.js +2 -0
  40. package/dist/assets/renderMobileApp-C4X_KUH8.js +25 -0
  41. package/dist/assets/runtimeEndpointReset-CMg-KUx3.js +41 -0
  42. package/dist/assets/scheduledTasksApi-CGFV4Pap.js +1 -0
  43. package/dist/assets/{shikiHighlight-BTObuQCR.js → shikiHighlight-DdKWYWrV.js} +1 -1
  44. package/dist/assets/surface-B6n7wJtt.js +1 -0
  45. package/dist/assets/tr-D2j6wUez.js +7 -0
  46. package/dist/assets/uk-C6IzmwM_.js +16 -0
  47. package/dist/assets/{useAppFontEffects-theH_IJL.js → useAppFontEffects-DgCHy6Mr.js} +134 -136
  48. package/dist/assets/useGitComparison-BIaI0WZI.js +1 -0
  49. package/dist/assets/{useInlineCommentController-Bs3PgeA8.js → useInlineCommentController-2wcCtpM3.js} +2 -2
  50. package/dist/assets/{useRootScrollLock-hSYwnxZs.js → useRootScrollLock-CbWA03xR.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-DdV8vhHn.js → vendor-base-ui-BY_5qla_.js} +1 -1
  52. package/dist/assets/{vendor-codemirror-language-data-Cxgr01md.js → vendor-codemirror-language-data-ES33GhKK.js} +2 -2
  53. package/dist/assets/{vendor-remixicon-react-Dil0zKKT.js → vendor-remixicon-react-BDmGmFCA.js} +1 -1
  54. package/dist/assets/{vendor-zod-BPAANqvH.js → vendor-zod-B6551dwG.js} +2 -2
  55. package/dist/assets/{web-components-CaS0ksnZ.js → web-components-CJZwV5BE.js} +1 -1
  56. package/dist/assets/zh-CN-Wl6tIDz1.js +16 -0
  57. package/dist/assets/zh-TW-hgphoWSN.js +16 -0
  58. package/dist/index.html +4 -4
  59. package/dist/mini-chat.html +4 -4
  60. package/dist/mobile.html +4 -4
  61. package/package.json +2 -2
  62. package/server/index.js +3 -13
  63. package/server/lib/agent-memory/runtime.js +7 -2
  64. package/server/lib/agent-memory/runtime.test.js +22 -0
  65. package/server/lib/event-stream/DOCUMENTATION.md +3 -0
  66. package/server/lib/event-stream/global-hub.js +29 -4
  67. package/server/lib/event-stream/global-hub.test.js +22 -0
  68. package/server/lib/event-stream/global-ws-bridge.js +15 -18
  69. package/server/lib/event-stream/protocol.js +21 -7
  70. package/server/lib/event-stream/runtime.js +9 -6
  71. package/server/lib/event-stream/runtime.test.js +60 -0
  72. package/server/lib/git/DOCUMENTATION.md +10 -1
  73. package/server/lib/git/routes.js +21 -8
  74. package/server/lib/git/routes.test.js +78 -0
  75. package/server/lib/git/service.js +159 -4
  76. package/server/lib/git/service.test.js +74 -0
  77. package/server/lib/github/DOCUMENTATION.md +5 -0
  78. package/server/lib/github/routes.js +2 -2
  79. package/server/lib/message-queue/DOCUMENTATION.md +7 -0
  80. package/server/lib/message-queue/runtime.js +13 -0
  81. package/server/lib/message-queue/runtime.test.js +31 -1
  82. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  83. package/server/lib/notifications/emitter-runtime.js +4 -3
  84. package/server/lib/opencode/DOCUMENTATION.md +32 -4
  85. package/server/lib/opencode/env-runtime.js +5 -1
  86. package/server/lib/opencode/env-runtime.test.js +72 -0
  87. package/server/lib/opencode/feature-routes-runtime.js +15 -1
  88. package/server/lib/opencode/lifecycle.js +4 -3
  89. package/server/lib/opencode/lifecycle.test.js +29 -0
  90. package/server/lib/opencode/managed-plugin-config.js +1 -1
  91. package/server/lib/opencode/openchamber-routes.js +72 -14
  92. package/server/lib/opencode/openchamber-routes.test.js +71 -3
  93. package/server/lib/opencode/proxy.js +33 -0
  94. package/server/lib/opencode/settings-helpers.js +8 -0
  95. package/server/lib/opencode/settings-helpers.test.js +24 -2
  96. package/server/lib/opencode/settings-registry.json +6 -0
  97. package/server/lib/opencode/settings-runtime.js +36 -9
  98. package/server/lib/opencode/settings-runtime.test.js +158 -2
  99. package/server/lib/project-context/DOCUMENTATION.md +13 -3
  100. package/server/lib/project-context/runtime.js +8 -2
  101. package/server/lib/project-context/runtime.test.js +54 -0
  102. package/server/lib/projects/DOCUMENTATION.md +2 -1
  103. package/server/lib/projects/project-config.js +38 -9
  104. package/server/lib/projects/project-config.test.js +97 -0
  105. package/server/lib/projects/project-id.js +26 -0
  106. package/server/lib/relay/DOCUMENTATION.md +20 -0
  107. package/server/lib/relay/host-client.js +7 -0
  108. package/server/lib/relay/host-client.test.js +14 -0
  109. package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
  110. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
  111. package/server/lib/scheduled-tasks/runtime.js +12 -2
  112. package/server/lib/scheduled-tasks/runtime.test.js +53 -0
  113. package/server/lib/session-assist/DOCUMENTATION.md +131 -66
  114. package/server/lib/session-assist/context.js +127 -0
  115. package/server/lib/session-assist/context.test.js +132 -0
  116. package/server/lib/session-assist/prompt.js +54 -0
  117. package/server/lib/session-assist/runtime.js +111 -257
  118. package/server/lib/session-assist/runtime.test.js +203 -0
  119. package/server/lib/walkthrough/DOCUMENTATION.md +15 -5
  120. package/server/lib/walkthrough/pr-source.test.js +21 -0
  121. package/server/lib/walkthrough/pull-request.js +7 -4
  122. package/server/lib/walkthrough/pull-request.test.js +16 -0
  123. package/server/lib/walkthrough/routes.js +19 -0
  124. package/server/lib/walkthrough/routes.test.js +26 -0
  125. package/server/lib/walkthrough/sources.js +13 -2
  126. package/server/opencode-worktree-readiness.test.js +130 -0
  127. package/dist/assets/DiffView-Dp1tomqK.js +0 -4
  128. package/dist/assets/FilesView-C_of2nIT.js +0 -17
  129. package/dist/assets/PlanView-jcQAfr2A.js +0 -5
  130. package/dist/assets/SettingsView-Buvom5A2.js +0 -28
  131. package/dist/assets/WalkthroughView-BgpSnSlU.js +0 -4
  132. package/dist/assets/de-DTQDjaiv.js +0 -10
  133. package/dist/assets/es-SOCFd_r-.js +0 -16
  134. package/dist/assets/index-B68h5S5B.css +0 -1
  135. package/dist/assets/index-CRf2xk51.js +0 -39
  136. package/dist/assets/ja-BKfafwsD.js +0 -16
  137. package/dist/assets/ko-BA5xgCYp.js +0 -16
  138. package/dist/assets/main-BNiPEont.js +0 -930
  139. package/dist/assets/markdownCore-CQ7CAuuV.js +0 -5
  140. package/dist/assets/patchFileDiff-C4X_trug.js +0 -13
  141. package/dist/assets/pt-BR-Bo2pnlEa.js +0 -16
  142. package/dist/assets/renderElectronMiniChatApp-BUcHPOXW.js +0 -2
  143. package/dist/assets/renderMobileApp-BvTmuRE-.js +0 -25
  144. package/dist/assets/runtimeEndpointReset-C8GAA2kS.js +0 -17
  145. package/dist/assets/scheduledTasksApi-BAScWwt3.js +0 -1
  146. package/dist/assets/surface-BvRzS58U.js +0 -1
  147. package/dist/assets/tr-CUaxHc8X.js +0 -7
  148. package/dist/assets/uk-YTJgyqAZ.js +0 -16
  149. package/dist/assets/useGitComparison-B94I6kOI.js +0 -1
  150. package/dist/assets/zh-CN-CZ2BxZS6.js +0 -16
  151. package/dist/assets/zh-TW-BsUrPdXz.js +0 -16
  152. package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
  153. package/server/lib/mcp-reconnect/runtime.js +0 -122
  154. package/server/lib/mcp-reconnect/runtime.test.js +0 -140
@@ -1,3 +1,11 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ // The longest stem `<stem>.json` may have and still leave room, inside the
4
+ // 255-byte file name limit, for the atomic-write `.tmp-<pid>-<ms>-<random>`
5
+ // suffix and the `.json.lock` sibling. Ids are ASCII, so characters are bytes.
6
+ const MAX_PROJECT_CONFIG_FILE_STEM_LENGTH = 200;
7
+ const HASHED_PROJECT_CONFIG_FILE_STEM_PREFIX = 'path_sha256_';
8
+
1
9
  const normalizeProjectPathForId = (value) => {
2
10
  if (typeof value !== 'string') return '';
3
11
  return value.replace(/\\/g, '/').replace(/\/+$/g, '') || value;
@@ -28,3 +36,21 @@ export const projectPathFromId = (projectId) => {
28
36
  return '';
29
37
  }
30
38
  };
39
+
40
+ /**
41
+ * The stem of everything a project owns in the projects dir: the per-user
42
+ * config file `<projectsDir>/<stem>.json` and the sibling folder
43
+ * `<projectsDir>/<stem>/` (context, plans, memory). It is the id itself while
44
+ * that fits a file name. A `path_<base64url>` id grows with the checkout path,
45
+ * so a deeply nested project would otherwise get a name the filesystem
46
+ * rejects (ENAMETOOLONG); such an id maps to a fixed-length digest instead.
47
+ * The digest keeps the `path_` prefix so the orphan recovery in
48
+ * `opencode/settings-runtime.js` never mistakes the file for a leftover of the
49
+ * random-id era. The VS Code extension host applies the same rule
50
+ * (`packages/vscode/src/bridge-project-setup-runtime.ts`); keep the two in sync.
51
+ */
52
+ export const projectConfigFileStemOf = (projectId) => {
53
+ if (projectId.length <= MAX_PROJECT_CONFIG_FILE_STEM_LENGTH) return projectId;
54
+ const digest = crypto.createHash('sha256').update(projectId, 'utf8').digest('hex');
55
+ return `${HASHED_PROJECT_CONFIG_FILE_STEM_PREFIX}${digest}`;
56
+ };
@@ -97,6 +97,26 @@ It does not replace a physical iOS/LTE check.
97
97
 
98
98
  ## Authentication model
99
99
 
100
+ ### Self-reported app diagnostics
101
+
102
+ Host-control, host-data and client upgrades include optional `appId`,
103
+ `appVersion` and `platform` query parameters. OpenChamber sends `openchamber`,
104
+ the local package version and the local runtime. Client platforms use the
105
+ existing presence values: `desktop` for Electron, `vscode`, `ios`, `android`
106
+ and `web` for browsers, including hosted mobile. Hosts use
107
+ `OPENCHAMBER_RUNTIME`, defaulting to `web`, so SSH hosts report `ssh-remote`.
108
+ These labels describe the connecting process, not its remote target.
109
+
110
+ These fields are diagnostics only, outside the signed auth payload. Older
111
+ relays ignore them and older apps remain connectable. The hosted relay groups
112
+ missing or invalid fields as `unknown`. Its analytics count host-control and
113
+ client connections separately, including reconnects, and show labels as
114
+ self-reported, never as verified app identity. Host-data sockets are excluded.
115
+ App diagnostics are written on connection, without per-app traffic counters.
116
+ No credentials, device names or application contents are added to diagnostics.
117
+
118
+ ### Access checks
119
+
100
120
  - The tunnel is **transport only**. The OpenChamber server still authenticates every tunneled request exactly as it authenticates a direct remote client. The relay path grants reachability, not authorization.
101
121
  - Clients carry their normal credential. HTTP and SSE requests authenticate with the client's bearer token (a header). **WebSocket upgrades cannot send headers**, so they authenticate with a short-lived URL-scoped token minted beforehand and passed as a query parameter. This asymmetry is important when adding new WebSocket features (see the skill).
102
122
  - The host authenticates itself to the relay with a signed handshake using its long-lived signing key.
@@ -4,6 +4,7 @@
4
4
  // dispatcher. Spec: .opencode/plans/private-relay/01-protocol-spec.md (Layer 1).
5
5
 
6
6
  import { WebSocket } from 'ws';
7
+ import { createRequire } from 'node:module';
7
8
 
8
9
  import { RELAY_PROTOCOL_VERSION, RelayCloseCode, createHostHandshake } from './e2ee.js';
9
10
  import { createOutboundFrameBatcher, decodeFrameBatch, decodeTunnelFrame, decodeDeliveryAck, encodeFrameBatch, TunnelFrameType } from './tunnel-codec.js';
@@ -50,6 +51,8 @@ const resolveBatchWindowMs = (option) => {
50
51
  * }} options
51
52
  */
52
53
  export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, onStatus, logger = console, batchWindowMs, batch, flowControl }) => {
54
+ const { version } = createRequire(import.meta.url)('../../../package.json');
55
+ const platform = process.env.OPENCHAMBER_RUNTIME || 'web';
53
56
  const resolveLocalPort = typeof getLocalPort === 'function' ? getLocalPort : () => localPort;
54
57
  const localBatch = batch !== false;
55
58
  const resolvedBatchWindowMs = resolveBatchWindowMs(batchWindowMs);
@@ -82,6 +85,10 @@ export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, on
82
85
  url.searchParams.set('v', String(RELAY_PROTOCOL_VERSION));
83
86
  url.searchParams.set('role', role);
84
87
  url.searchParams.set('serverId', identity.serverId);
88
+ // Self-reported diagnostics, not part of relay authentication.
89
+ url.searchParams.set('appId', 'openchamber');
90
+ url.searchParams.set('appVersion', version);
91
+ url.searchParams.set('platform', platform);
85
92
  if (connectionId) url.searchParams.set('connectionId', connectionId);
86
93
  const auth = identity.signRelayAuth(role, connectionId ?? null);
87
94
  url.searchParams.set('ts', String(auth.ts));
@@ -39,11 +39,17 @@ const startFakeRelay = () => {
39
39
  clients: new Map(), // connectionId -> ws
40
40
  buffered: new Map(), // connectionId -> [[data, isBinary]] awaiting host-data
41
41
  relayFrames: [], // observed forwarded frames (for plaintext assertions)
42
+ apps: new Map(),
42
43
  };
43
44
 
44
45
  wss.on('connection', (ws, req) => {
45
46
  const url = new URL(req.url, 'http://localhost');
46
47
  const role = url.searchParams.get('role');
48
+ state.apps.set(role, {
49
+ appId: url.searchParams.get('appId'),
50
+ appVersion: url.searchParams.get('appVersion'),
51
+ platform: url.searchParams.get('platform'),
52
+ });
47
53
  const connectionId = url.searchParams.get('connectionId');
48
54
 
49
55
  if (role === 'host-control') {
@@ -101,6 +107,7 @@ const startFakeRelay = () => {
101
107
  // A socket a failed test left open would hold server.close() until
102
108
  // the hook timeout; drop them so a failure is reported once.
103
109
  for (const client of wss.clients) client.terminate();
110
+ server.closeAllConnections();
104
111
  wss.close();
105
112
  server.close(() => r());
106
113
  }),
@@ -286,6 +293,13 @@ describe('relay host-client integration', () => {
286
293
  });
287
294
 
288
295
  expect(result.status).toBe(200);
296
+ for (const role of ['host-control', 'host-data']) {
297
+ expect(relay.state.apps.get(role)).toEqual({
298
+ appId: 'openchamber',
299
+ appVersion: expect.stringMatching(/^\d+\.\d+\.\d+/),
300
+ platform: process.env.OPENCHAMBER_RUNTIME || 'web',
301
+ });
302
+ }
289
303
  expect(result.body.ok).toBe(true);
290
304
  expect(result.body.relayConn).toBe('conn-test-1');
291
305
  expect(result.body.origin).toBe(`http://127.0.0.1:${origin.port}`);
@@ -25,6 +25,12 @@ in shared project config under the project write lock:
25
25
  from the winner's persisted `nextRunAt`.
26
26
  - Project config writes also take a cross-process `.json.lock` file so the
27
27
  read-modify-write is serialized across processes, not only within one process.
28
+ - `syncAllProjects` (startup and every full resync) syncs each registered
29
+ project on its own: a project whose config cannot be read or written (a
30
+ broken file, a lock timeout) is logged with its id and skipped, and every
31
+ other project's tasks are still scheduled. Only `listProjects` failing
32
+ aborts the sync as a whole. `syncProject` for one project still throws, so
33
+ a route for that project reports the failure.
28
34
  - The sharing processes may run different OpenChamber versions. Normalization
29
35
  keeps only the fields a build knows, so every writer persists tasks it did
30
36
  not change verbatim from disk and swaps only `state` onto a task whose state
@@ -63,7 +69,9 @@ in shared project config under the project write lock:
63
69
  - Claiming always writes `nextRunAt` (including `undefined`) so a past once-slot
64
70
  is cleared when there is no following occurrence.
65
71
 
66
- Manual `runNow` does not claim a schedule occurrence.
72
+ Manual `runNow` does not claim a schedule occurrence. It also runs paused
73
+ (`enabled: false`) tasks — that is the point of the button — while scheduled
74
+ dispatches still skip disabled tasks, and completion never re-arms a paused task.
67
75
 
68
76
  ## Files
69
77
 
@@ -485,4 +485,32 @@ describe('issue 2710: daily scheduled task double execution at the configured ti
485
485
 
486
486
  runtime.stop();
487
487
  });
488
+
489
+ it('manual runNow runs a paused task but does not schedule future runs', async () => {
490
+ vi.setSystemTime(UTC(2026, 0, 1, 14, 0, 0));
491
+ const task = { ...makeTask({ kind: 'daily', times: ['15:00'] }), enabled: false };
492
+ const projectConfigRuntime = createSharedProjectConfigRuntime(task);
493
+
494
+ const runtime = createScheduledTasksRuntime(createRuntimeDeps(projectConfigRuntime));
495
+ await runtime.start();
496
+
497
+ // The scheduler must not fire a disabled task on its own.
498
+ await vi.advanceTimersByTimeAsync(HOUR + 3_000);
499
+ expect(sdk.sessionCreates.length).toBe(0);
500
+
501
+ const manual = await runtime.runNow('p1', 'task-1');
502
+ expect(manual.ok).toBe(true);
503
+ expect(manual.sessionID).toBeTruthy();
504
+ expect(sdk.sessionCreates.length).toBe(1);
505
+ expect(runtime.getStatus().runningScheduledTasksCount).toBe(0);
506
+
507
+ // Completion records state but leaves the task paused with no next run.
508
+ const tasks = await projectConfigRuntime.listScheduledTasks('p1');
509
+ expect(tasks[0].enabled).toBe(false);
510
+ expect(tasks[0].state.lastStatus).toBe('success');
511
+ expect(tasks[0].state.lastSessionId).toBe('sess-1');
512
+ expect(tasks[0].state.nextRunAt).toBeUndefined();
513
+
514
+ runtime.stop();
515
+ });
488
516
  });
@@ -426,7 +426,16 @@ export const createScheduledTasksRuntime = (deps) => {
426
426
  }
427
427
 
428
428
  for (const projectID of activeProjectIDs) {
429
- await syncProject(projectID);
429
+ try {
430
+ await syncProject(projectID);
431
+ } catch (error) {
432
+ // One project's config being unusable (a broken file, a lock timeout)
433
+ // must not keep every other project's tasks from being scheduled.
434
+ logger.warn?.('[ScheduledTasks] failed to sync project', {
435
+ projectID,
436
+ error: error?.message ?? String(error),
437
+ });
438
+ }
430
439
  }
431
440
  };
432
441
 
@@ -676,7 +685,8 @@ export const createScheduledTasksRuntime = (deps) => {
676
685
  const runTask = async (projectID, taskID, reason, scheduledFor) => {
677
686
  const taskMap = tasksByProject.get(projectID);
678
687
  const task = taskMap?.get(taskID);
679
- if (!task || !task.enabled) {
688
+ // Manual runNow runs paused tasks too; only scheduled dispatches skip them.
689
+ if (!task || (reason !== 'manual' && !task.enabled)) {
680
690
  return { ok: false, skipped: true };
681
691
  }
682
692
 
@@ -206,3 +206,56 @@ Run daily.
206
206
  }
207
207
  });
208
208
  });
209
+
210
+ describe('scheduled-tasks runtime syncAllProjects', () => {
211
+ it('keeps scheduling the other projects when one project cannot be synced', async () => {
212
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'oc-runtime-sync-all-'));
213
+ try {
214
+ const brokenPath = path.join(tempRoot, 'broken');
215
+ const healthyPath = path.join(tempRoot, 'healthy');
216
+ await mkdir(path.join(healthyPath, '.agents', 'loops'), { recursive: true });
217
+ await mkdir(brokenPath, { recursive: true });
218
+ await writeFile(path.join(healthyPath, '.agents', 'loops', 'daily.md'), `---
219
+ name: daily
220
+ schedule: "0 9 * * *"
221
+ enabled: true
222
+ model: openai/gpt-5
223
+ ---
224
+ Run daily.
225
+ `, 'utf8');
226
+
227
+ const projectConfigRuntime = createProjectConfigRuntime({
228
+ fsPromises: await import('fs/promises'),
229
+ path,
230
+ projectsDirPath: path.join(tempRoot, 'config'),
231
+ createTaskID: () => 'task-fixed-id',
232
+ });
233
+ await mkdir(path.join(tempRoot, 'config'), { recursive: true });
234
+ await writeFile(projectConfigRuntime.resolveProjectConfigPath('broken'), '{ not json', 'utf8');
235
+
236
+ const warnings = [];
237
+ const runtime = createScheduledTasksRuntime({
238
+ buildOpenCodeUrl: () => 'http://localhost',
239
+ getOpenCodeAuthHeaders: () => ({}),
240
+ waitForOpenCodeReady: async () => {},
241
+ projectConfigRuntime,
242
+ listProjects: async () => [
243
+ { id: 'broken', path: brokenPath },
244
+ { id: 'healthy', path: healthyPath },
245
+ ],
246
+ logger: { warn: (...args) => warnings.push(args) },
247
+ });
248
+
249
+ await expect(runtime.start()).resolves.toBeUndefined();
250
+
251
+ expect(runtime.getStatus().enabledScheduledTasksCount).toBe(1);
252
+ const healthyTasks = await projectConfigRuntime.listScheduledTasks('healthy');
253
+ expect(healthyTasks.map((task) => task.id)).toEqual(['loop:project:daily']);
254
+ expect(warnings).toHaveLength(1);
255
+ expect(warnings[0][1]).toMatchObject({ projectID: 'broken' });
256
+ runtime.stop();
257
+ } finally {
258
+ await rm(tempRoot, { recursive: true, force: true });
259
+ }
260
+ });
261
+ });
@@ -1,66 +1,131 @@
1
- # Session Assist
2
-
3
- Server-side watcher that generates a short recap of the agent's last reply
4
- and one suggested user follow-up with the small model
5
- (`lib/small-model`), storing both on the session's metadata under
6
- `metadata.openchamber.assist`.
7
-
8
- ## Flow
9
-
10
- 1. `createSessionAssistRuntime` is a consumer of the server's global SSE
11
- fan-out (`index.js` → `onPayload`), riding the same upstream connection as
12
- notifications. Purely event-driven — dormant sessions never generate
13
- anything, there is no backfill and no session scanning.
14
- 2. `session.status: idle` arms a 60-second per-session timer; any `busy`/
15
- `retry` status or a user `message.updated` clears it (the "1 minute of
16
- quiet" rule).
17
- 3. On fire: fetch the session (skip sub-agent sessions with `parentID`),
18
- take the LAST exchange only — the final assistant reply plus the user
19
- message it answered (assistant `parentID` → user id) — and call
20
- `generateSmallModelText` with the
21
- session's own provider/model taken from the last assistant message — so
22
- the utility call spends the same subscription as the conversation.
23
- `restrictToPreferredProvider` forbids the resolver's global fallback:
24
- conversation content never goes to a provider the user didn't pick for
25
- the session, unless the small model was chosen explicitly (settings
26
- override or opencode config). A resolver 404 is silently skipped.
27
- 4. The requested JSON fields (`recap`, `suggestion`, or both) are clamped and
28
- PATCHed onto the session metadata together with `forMessageID` (the last
29
- assistant message id) and `generatedAt`. Before writing, the session tail is
30
- re-checked (a stale result is dropped) and the metadata is merged from a
31
- fresh session read so concurrent metadata writes made during generation are
32
- preserved.
33
-
34
- ## Settings gate
35
-
36
- `sessionRecapEnabled` and `sessionSuggestionEnabled` in OpenChamber settings
37
- (Settings → Chat, default on) are hard generation switches checked at fire
38
- time. When both are off, no small-model calls run and nothing is written. When
39
- one is on, the runtime still makes at most one small-model call and asks only
40
- for that field. The UI also hides disabled payload types immediately.
41
-
42
- ## Freshness contract (no clearing writes)
43
-
44
- Clients do not need the payload to be deleted: they render it only while
45
- `assist.forMessageID` still equals the session's last assistant message id
46
- (and the session is idle). Any new message invalidates the payload
47
- everywhere instantly and offline; the next idle cycle overwrites it.
48
-
49
- ## UI consumers (packages/ui)
50
-
51
- - `lib/sessionAssistMetadata.ts` — payload parsing.
52
- - `hooks/useSessionAssist.ts` — freshness gating + the 1-minute quiet window
53
- for the recap (single timeout to the boundary, no polling).
54
- - `components/chat/SessionRecapSpacer.tsx` — renders the recap inside the
55
- fixed-height reserved gap under the last message (height never changes).
56
- - `components/chat/SessionSuggestionChip.tsx` — one tappable suggestion chip
57
- near the composer (desktop chips row + above the mobile pill); hidden as
58
- soon as the composer has any content. Tap fills the input, never sends.
59
-
60
- ## Limitations
61
-
62
- - The watcher lives in the web server, so VS Code (extension-only, no web
63
- server) does not generate assists; it still renders payloads produced by a
64
- web/desktop instance of the same OpenCode server via `session.updated`.
65
- - Metadata payloads ride every `session.updated` event — keep the clamps
66
- (`RECAP_CHAR_LIMIT`, `SUGGESTION_CHAR_LIMIT`) small.
1
+ # Session assist
2
+
3
+ The server generates a short reminder of recent work and an optional next user
4
+ message with Small Model. Results live in `metadata.openchamber.assist` with
5
+ `recap`, `suggestion`, `forMessageID`, and `generatedAt`. The payload shape is
6
+ unchanged; an empty suggestion is a successful outcome.
7
+
8
+ ## Ownership
9
+
10
+ - `runtime.js` owns idle timers, cancellation, provider selection, SDK reads,
11
+ freshness checks, settings gates, and metadata writes.
12
+ - `context.js` reads bounded history and constructs human turns. It removes
13
+ tool payloads and injected prompts before retaining message text.
14
+ - `prompt.js` owns the generation instructions and total input budget.
15
+ - `../small-model/DOCUMENTATION.md` owns provider/auth resolution, generation,
16
+ output limits, and overflow behavior.
17
+
18
+ ## What the model receives
19
+
20
+ Read backward through the official SDK in pages of 50 messages until three
21
+ human turns are covered, history ends, or eight pages have been read. A failed
22
+ page or repeated cursor aborts generation; it is not treated as complete history.
23
+ At the page limit, use fewer available human turns. If the latest answer's human
24
+ request has not been found, skip generation rather than invent its context.
25
+
26
+ Three turns retain the substance behind short commit confirmations without
27
+ bringing an entire old task back into the prompt. This was compared against
28
+ one, five, ten, and full-history contexts on long maintainer sessions. There
29
+ is no full-history cache and no assumed provider prefix-cache behavior.
30
+
31
+ The latest record must be a completed, successful, non-summary assistant answer
32
+ with visible text. Child, archived, and reverted sessions are skipped. A new
33
+ prompt clears the revert boundary before its next idle event.
34
+
35
+ Human turns follow chronological message intervals. OpenCode can insert
36
+ synthetic continuation users during compaction, so a final answer's `parentID`
37
+ need not point directly at the original human request. These continuations stay
38
+ within their human turn; compaction summaries are excluded. An interrupted
39
+ request remains context with its last visible progress explicitly labeled as
40
+ unfinished, rather than being dropped or called a final answer.
41
+ An answer must still reference that human user or one of its continuation
42
+ users; a late answer for an older request cannot be assigned to a newer request.
43
+
44
+ ### Attached context and language
45
+
46
+ The persisted attachment contract is owned by
47
+ `packages/ui/src/lib/messages/contextParts.ts`. Its user-facing Markdown
48
+ formatter is `packages/ui/src/lib/messages/messageMarkdown.ts`.
49
+
50
+ The server projects those persisted parts into model context without importing
51
+ the UI runtime: code comments, file/chat quotes, browser annotations, PR comments,
52
+ checks, terminal selections, and linked GitHub/Linear items remain attached to
53
+ the user turn even when their transport part is synthetic. The OpenCode
54
+ `opencodeComment` mirror is also accepted. Unrecognized synthetic prompts and
55
+ ignored parts are excluded. Malformed attached text fails the generation.
56
+
57
+ Quoted material and the user's own comment are separate blocks. The user's
58
+ authored text is also supplied separately for language selection. Quoted source,
59
+ logs, assistant replies, and injected memory instructions do not choose the
60
+ language. A language-neutral final acknowledgment can use recent authored text.
61
+ The existing Cyrillic/CJK mismatch guard uses that authored sample per field;
62
+ it is not a complete language detector, and it is skipped if no sample exists.
63
+
64
+ ### Input bounds
65
+
66
+ User text is bounded to 8,000 characters and each assistant answer to 16,000.
67
+ Attached quote bodies have their own 4,000-character limit so a large quote
68
+ does not consume the user's comment. Excerpts preserve both ends with an
69
+ explicit omission marker, including the conclusion of a long final report.
70
+
71
+ The complete user prompt is limited to 32,000 characters and the resolved small
72
+ model's input allowance, reserving space for the system prompt. Under pressure,
73
+ drop older whole turns first. If the latest pair itself is too large, excerpt
74
+ both its user request and answer rather than discarding either side. If even
75
+ the minimum prompt cannot fit, skip generation. `onOverflow: 'error'` prevents
76
+ the Small Model service from silently cutting off the instructions. Expected
77
+ context/output-budget failures are quiet and do not write metadata.
78
+
79
+ OpenCode message pages still contain complete tool payloads on the wire. A
80
+ single long turn can therefore require substantial I/O even though its retained
81
+ model context is small. Page/count bounds are not a network-byte quota.
82
+
83
+ ## Generation and lifecycle
84
+
85
+ 1. The server's existing global event fan-out calls `processPayload`. An idle
86
+ event arms the 60-second quiet window. No history scan or startup backfill runs.
87
+ 2. Busy/retry events and newly created user messages clear pending work and
88
+ abort in-flight reads/generation. Re-emitted old user updates do not cancel it.
89
+ 3. One generation runs per session. If a newer quiet window expires while an
90
+ old canceled request is still settling, retain that pending run and start it
91
+ after the old one finishes. Later activity cancels the pending run as well.
92
+ 4. Resolve the small model using the last answer's provider/model and the
93
+ existing explicit settings/config overrides. `restrictToPreferredProvider`
94
+ prevents an implicit cross-provider fallback. Production does not pin the
95
+ experimental model. Generation accepts an abort signal and a 120-second limit.
96
+ 5. Recap describes the substantive work and its current result, including the
97
+ work behind a closing commit or acknowledgment. Suggestion is independent:
98
+ only unfinished requested agent work should produce a sendable user message.
99
+ Completed work, optional offers, or a decision/action belonging to the user
100
+ should return an empty suggestion. This is model judgment, not authorization
101
+ enforcement or a guarantee that every generated field is factually correct.
102
+ 6. Re-read the latest message and fresh session before writing. A moved tail,
103
+ canceled run, changed endpoint/directory, archive, revert, or failed fresh
104
+ read discards the result. Never merge from the old pre-generation metadata.
105
+ 7. Re-check settings, clamp the enabled fields, and merge into fresh metadata.
106
+ The OpenCode update endpoint has no compare-and-set operation; another
107
+ writer after the final read is not guarded atomically.
108
+
109
+ Stopping the runtime clears pending timers/runs and aborts in-flight operations.
110
+ No failed session blocks another session.
111
+
112
+ ## Settings and consumers
113
+
114
+ `sessionRecapEnabled` and `sessionSuggestionEnabled` default on and are checked
115
+ before work and before writing. With both off there are no reads, model calls,
116
+ or writes. With one on, the shared recent context is still available, but only
117
+ that field is requested. An empty suggestion does not erase a valid recap.
118
+
119
+ Clients render an assist only while its `forMessageID` is the last message and
120
+ the session is idle. A new message invalidates it without clearing writes.
121
+
122
+ - `packages/ui/src/lib/sessionAssistMetadata.ts` parses the payload.
123
+ - `packages/ui/src/hooks/useSessionAssist.ts` owns freshness/settings gating.
124
+ - `SessionRecapSpacer` shows the reminder in the reserved gap under the reply.
125
+ - `SessionSuggestionChip` fills the composer; it never sends automatically.
126
+
127
+ Web, Electron, hosted mobile, and Capacitor use the server watcher. VS Code's
128
+ extension-only runtime does not generate assists; shared UI can render payloads
129
+ produced by a server. The background watcher cannot use the browser's message
130
+ store when the UI is closed. Manual AI rename uses that store through
131
+ `SessionMessageLoader`; these are intentionally different retrieval lifecycles.
@@ -0,0 +1,127 @@
1
+ const TURN_LIMIT = 3;
2
+ const PAGE_SIZE = 50;
3
+ const MAX_PAGES = 8;
4
+ const USER_CHAR_LIMIT = 8_000;
5
+ const ANSWER_CHAR_LIMIT = 16_000;
6
+
7
+ // Mirrors the persisted context contract owned by UI lib/messages/contextParts.ts.
8
+ // Read only the fields needed for model context; malformed attached text fails
9
+ // this generation instead of silently dropping the user's comment.
10
+ const QUOTE_FIELDS = new Map([
11
+ ['code-comment', 'code'], ['file-quote', 'quote'], ['chat-quote', 'quote'],
12
+ ['browser-annotation', 'prompt'], ['pr-comment', 'body'], ['pr-check', 'output'],
13
+ ['terminal', 'output'],
14
+ ]);
15
+ const LINK_KINDS = new Set(['github-issue', 'github-pr', 'linear-issue']);
16
+
17
+ export function excerpt(text, limit) {
18
+ if (text.length <= limit) return text;
19
+ const marker = '\n[Content omitted]\n';
20
+ if (limit <= marker.length) return text.slice(0, Math.max(0, limit));
21
+ const head = Math.ceil((limit - marker.length) / 2);
22
+ const tail = limit - marker.length - head;
23
+ return text.slice(0, head) + marker + (tail > 0 ? text.slice(-tail) : '');
24
+ }
25
+
26
+ function attachedText(part) {
27
+ const context = part.metadata?.openchamberContext;
28
+ if (QUOTE_FIELDS.has(context?.kind)) {
29
+ const source = (context[QUOTE_FIELDS.get(context.kind)] ?? '').trim();
30
+ const authored = (context.text ?? '').trim();
31
+ const label = excerpt((context.fileLabel ?? context.label ?? context.pageUrl ?? context.terminalLabel ?? '').trim(), 300);
32
+ const location = Number.isInteger(context.startLine) ? `, lines ${context.startLine}-${context.endLine ?? context.startLine}` : '';
33
+ const quote = excerpt(source, 4_000).split('\n').map((line) => `> ${line}`).join('\n');
34
+ return { text: `Attached ${context.kind}${label ? ` (${label}${location})` : ''}:\n${quote}\n\nUser comment:\n${excerpt(authored, USER_CHAR_LIMIT)}`, authored };
35
+ }
36
+ if (LINK_KINDS.has(context?.kind)) return { text: excerpt(part.text, USER_CHAR_LIMIT), authored: '' };
37
+ const comment = part.metadata?.opencodeComment;
38
+ if (comment) {
39
+ const authored = comment.comment.trim();
40
+ const source = (comment.preview ?? '').trim();
41
+ const label = excerpt((comment.path ?? '').trim(), 300);
42
+ return { text: `Attached file context (${label}):\n${excerpt(source, 4_000)}\n\nUser comment:\n${excerpt(authored, USER_CHAR_LIMIT)}`, authored };
43
+ }
44
+ return null;
45
+ }
46
+
47
+ /** SDK message records are chronological; tool payloads never enter this view. */
48
+ function readMessage({ info, parts }) {
49
+ const blocks = [];
50
+ const authored = [];
51
+ for (const part of parts) {
52
+ if (part.type !== 'text' || part.ignored) continue;
53
+ const attached = info.role === 'user' ? attachedText(part) : null;
54
+ if (attached) {
55
+ blocks.push(attached.text);
56
+ authored.push(attached.authored);
57
+ } else if (!part.synthetic) {
58
+ blocks.push(part.text);
59
+ if (info.role === 'user') {
60
+ // Legacy terminal selections are source material, not a language sample.
61
+ authored.push(part.text.replace(/\n*<terminal_context>\n[\s\S]*?\n<\/terminal_context>\s*$/, ''));
62
+ }
63
+ }
64
+ }
65
+ return {
66
+ id: info.id, role: info.role, parentID: info.parentID,
67
+ providerID: info.providerID, modelID: info.modelID,
68
+ complete: info.role === 'assistant' && info.finish === 'stop' && Boolean(info.time?.completed) && !info.error && !info.summary,
69
+ summary: Boolean(info.summary),
70
+ text: excerpt(blocks.join('\n\n').trim(), info.role === 'user' ? USER_CHAR_LIMIT : ANSWER_CHAR_LIMIT),
71
+ authored: excerpt(authored.filter(Boolean).join('\n\n').trim(), USER_CHAR_LIMIT),
72
+ };
73
+ }
74
+
75
+ function collectTurns(messages) {
76
+ const turns = [];
77
+ let active = null;
78
+ let parents = new Set();
79
+ for (const message of messages) {
80
+ if (message.role === 'user' && message.text) {
81
+ active = { user: message, assistant: null, complete: false };
82
+ parents = new Set([message.id]);
83
+ turns.push(active);
84
+ } else if (active && message.role === 'user') {
85
+ parents.add(message.id);
86
+ } else if (active && message.role === 'assistant' && parents.has(message.parentID) && !message.summary) {
87
+ // Compaction's synthetic continuation users belong to the same human
88
+ // turn. Parent IDs alone would lose its eventual final answer.
89
+ if (message.text) active.assistant = message;
90
+ active.complete = message.complete && Boolean(message.text);
91
+ }
92
+ }
93
+ return turns.slice(-TURN_LIMIT);
94
+ }
95
+
96
+ /** Failure is thrown; null means no eligible final answer within bounded history. */
97
+ export async function loadAssistContext({ readPage, signal }) {
98
+ let messages = [];
99
+ let before;
100
+ const cursors = new Set();
101
+ const ids = new Set();
102
+ for (let pageNumber = 0; pageNumber < MAX_PAGES; pageNumber++) {
103
+ signal.throwIfAborted();
104
+ const page = await readPage({ limit: PAGE_SIZE, before });
105
+ signal.throwIfAborted();
106
+ if (!Array.isArray(page.data)) throw new Error('Session message page is unavailable');
107
+ const older = [];
108
+ for (const record of page.data) {
109
+ if (ids.has(record.info.id)) continue;
110
+ ids.add(record.info.id);
111
+ older.push(readMessage(record));
112
+ }
113
+ messages = older.concat(messages);
114
+ const last = messages.at(-1);
115
+ if (!last?.complete || !last.text) return null;
116
+ const turns = collectTurns(messages);
117
+ const cursor = page.response.headers.get('x-next-cursor');
118
+ if (turns.length === TURN_LIMIT || !cursor || pageNumber === MAX_PAGES - 1) {
119
+ if (!turns.at(-1)?.complete || turns.at(-1).assistant.id !== last.id) return null;
120
+ return { turns, last };
121
+ }
122
+ if (cursors.has(cursor)) throw new Error('Session message pagination made no progress');
123
+ cursors.add(cursor);
124
+ before = cursor;
125
+ }
126
+ return null;
127
+ }