@openchamber/web 1.24.0 → 1.24.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 (131) hide show
  1. package/bin/cli.test.js +7 -6
  2. package/bin/lib/cli-http.js +5 -1
  3. package/dist/assets/{CodeMirrorCommentWidgets-C9kV-n7r.js → CodeMirrorCommentWidgets-DvUH815P.js} +1 -1
  4. package/dist/assets/DiffView-DkC3xlRJ.js +4 -0
  5. package/dist/assets/{FilesView-vjJx7VaM.js → FilesView-D0bM9FVB.js} +6 -6
  6. package/dist/assets/GitView-Bxuv3dfP.js +6 -0
  7. package/dist/assets/GuestAttachDialog-B0u3Q5uO.js +1 -0
  8. package/dist/assets/{JsonTreeView-D_4G5X6-.js → JsonTreeView-BBVPFM5K.js} +1 -1
  9. package/dist/assets/{LinearIssuesView-1uKhePfH.js → LinearIssuesView-UI1FcSC8.js} +1 -1
  10. package/dist/assets/{MarkdownImageGallery-Ix7N_2wp.js → MarkdownImageGallery-CUJxH8Le.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-Deel_y5S.js → MarkdownRendererImpl-D5BZOg8X.js} +1 -1
  12. package/dist/assets/{OnboardingScreen-ToIakxb_.js → OnboardingScreen-5Gou9cGD.js} +1 -1
  13. package/dist/assets/{PatchDiff-BjMgezr1.js → PatchDiff-C4rE5k6z.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-53Ghfnlr.js → PierreDiffViewer-ByRVu6ss.js} +1 -1
  15. package/dist/assets/{PlanView-BGAzxDwD.js → PlanView-u2yi5XGJ.js} +4 -4
  16. package/dist/assets/PluginPane-QxjsKYeO.js +3 -0
  17. package/dist/assets/SettingsView-Fo5ZqMaT.js +29 -0
  18. package/dist/assets/SettingsWindow-HVDVANjJ.js +1 -0
  19. package/dist/assets/{SubmoduleDiffSummary--YFqK6Ih.js → SubmoduleDiffSummary-D3hzkybB.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DRWBvdaJ.js → ToolOutputDialog-3J6IRayW.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-BxZJCU28.js → ToolPartDiffPreview-DarxPjSd.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-DCXjBGRf.js → VirtualizedFileDiff-CZgXWHjU.js} +4 -4
  23. package/dist/assets/{WalkthroughView-CfIPvWWa.js → WalkthroughView-wSpED5L4.js} +2 -2
  24. package/dist/assets/{appThemeRegistry-DDROzcUO.js → appThemeRegistry-Cf8KitzT.js} +1 -1
  25. package/dist/assets/commitAndPush-DZnzlhvc.js +1 -0
  26. package/dist/assets/{computeVirtualFileMetrics-DHgQIkUq.js → computeVirtualFileMetrics-VYnT_A2h.js} +1 -1
  27. package/dist/assets/{de-CX_f-T5U.js → de-BM_8EDD3.js} +4 -4
  28. package/dist/assets/{es-BERmWNn_.js → es-CxZjlqpo.js} +3 -3
  29. package/dist/assets/{fr-BjYYE_-z.js → fr-VCixCnMW.js} +4 -4
  30. package/dist/assets/{index-WjufPkIV.js → index-3U4CtS9b.js} +1 -1
  31. package/dist/assets/index-B9Hvzjwl.css +1 -0
  32. package/dist/assets/index-DLHQogv8.js +40 -0
  33. package/dist/assets/{isDiffPlainText-D9faP70y.js → isDiffPlainText-ImDG3Uhg.js} +1 -1
  34. package/dist/assets/{isFilePlainText-6qOcz5Ky.js → isFilePlainText-D_YDVYDb.js} +1 -1
  35. package/dist/assets/{ja-DxqeAk9N.js → ja-CZ5k_GyD.js} +4 -4
  36. package/dist/assets/{ko-Dty1aUod.js → ko-7YM3A1Xh.js} +4 -4
  37. package/dist/assets/{main-Bjcre_GE.js → main-CycplCph.js} +2 -2
  38. package/dist/assets/main-DFYTCx5o.js +896 -0
  39. package/dist/assets/markdownCore-DHvqMxPn.js +5 -0
  40. package/dist/assets/{miniChat-Dz_bPgMc.js → miniChat-DIQKfY2V.js} +2 -2
  41. package/dist/assets/{mobile-BbZPBJrK.js → mobile-BMwz5q-m.js} +2 -2
  42. package/dist/assets/{patchFileDiff-BvU6KOQC.js → patchFileDiff-DDQ6Rq5e.js} +3 -3
  43. package/dist/assets/{pl-CX-_ROkr.js → pl-BcgDO_w5.js} +4 -4
  44. package/dist/assets/{pt-BR-DhRR1arx.js → pt-BR-CU2u_1q5.js} +3 -3
  45. package/dist/assets/renderElectronMiniChatApp-3_d6g6CU.js +2 -0
  46. package/dist/assets/renderMobileApp-D0Y8DtkA.js +25 -0
  47. package/dist/assets/runtimeEndpointReset-DhC3REb2.js +25 -0
  48. package/dist/assets/{scheduledTasksApi-DW3xqMQ8.js → scheduledTasksApi-D8pq6gQz.js} +1 -1
  49. package/dist/assets/{shikiHighlight-DsxD9QEa.js → shikiHighlight-1imXsir9.js} +1 -1
  50. package/dist/assets/{textMateThemeFromAppTheme-Da7ed8qM.js → textMateThemeFromAppTheme-Dgqc63LZ.js} +1 -1
  51. package/dist/assets/tr-DuYhOzNe.js +7 -0
  52. package/dist/assets/{uk-CD21CXFV.js → uk-Cuk7-uvq.js} +3 -3
  53. package/dist/assets/{useAppFontEffects-hfv2s6mZ.js → useAppFontEffects-BItUWdo4.js} +147 -147
  54. package/dist/assets/{useInlineCommentController-BmtfVbo8.js → useInlineCommentController-CkbKsm7m.js} +2 -2
  55. package/dist/assets/useRootScrollLock-vmzxZjWA.js +2 -0
  56. package/dist/assets/{vendor-codemirror-language-data-BPMJpOpT.js → vendor-codemirror-language-data-BDyxuqK4.js} +2 -2
  57. package/dist/assets/{vendor-tanstack-react-virtual-g05Cx3z9.js → vendor-tanstack-react-virtual-ClYN8CzB.js} +1 -1
  58. package/dist/assets/{vendor-tanstack-virtual-core-Dubg10g5.js → vendor-tanstack-virtual-core-BewVQryB.js} +1 -1
  59. package/dist/assets/{web-components-U-hWbgJo.js → web-components-D7FinaeH.js} +1 -1
  60. package/dist/assets/{zh-CN-BWvlPHY-.js → zh-CN-CUWoiRHd.js} +3 -3
  61. package/dist/assets/{zh-TW-CRp5dJU2.js → zh-TW-CQ8EBSBN.js} +3 -3
  62. package/dist/index.html +3 -3
  63. package/dist/mini-chat.html +3 -3
  64. package/dist/mobile.html +3 -3
  65. package/package.json +4 -3
  66. package/server/index.js +26 -7
  67. package/server/lib/changelog/update-notes.js +2 -1
  68. package/server/lib/changelog/update-notes.test.js +19 -0
  69. package/server/lib/event-stream/DOCUMENTATION.md +23 -0
  70. package/server/lib/event-stream/delta-coalescer.js +0 -0
  71. package/server/lib/event-stream/delta-coalescer.test.js +292 -0
  72. package/server/lib/event-stream/global-hub.js +53 -23
  73. package/server/lib/event-stream/global-hub.test.js +160 -0
  74. package/server/lib/event-stream/global-ws-bridge.js +1 -0
  75. package/server/lib/event-stream/index.js +4 -0
  76. package/server/lib/git/DOCUMENTATION.md +17 -4
  77. package/server/lib/git/routes.js +1 -1
  78. package/server/lib/git/serial-refresh.js +93 -0
  79. package/server/lib/git/serial-refresh.test.js +112 -0
  80. package/server/lib/git/service.js +232 -62
  81. package/server/lib/git/service.test.js +273 -0
  82. package/server/lib/github/pr-status.js +5 -5
  83. package/server/lib/github/pr-status.test.js +1 -1
  84. package/server/lib/github/routes.js +4 -4
  85. package/server/lib/guests/DOCUMENTATION.md +5 -3
  86. package/server/lib/guests/background.test.js +83 -0
  87. package/server/lib/guests/catalog.js +20 -9
  88. package/server/lib/guests/catalog.test.js +5 -5
  89. package/server/lib/guests/routes.js +2 -2
  90. package/server/lib/message-queue/DOCUMENTATION.md +6 -0
  91. package/server/lib/message-queue/runtime.js +5 -0
  92. package/server/lib/message-queue/runtime.test.js +32 -1
  93. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  94. package/server/lib/opencode/settings-helpers.js +3 -0
  95. package/server/lib/opencode/settings-registry.json +8 -0
  96. package/server/lib/permission-auto-accept/DOCUMENTATION.md +8 -0
  97. package/server/lib/permission-auto-accept/runtime.js +13 -0
  98. package/server/lib/permission-auto-accept/runtime.test.js +37 -1
  99. package/server/lib/routing/DOCUMENTATION.md +81 -0
  100. package/server/lib/routing/defaults.js +98 -0
  101. package/server/lib/routing/feature-flag.js +11 -0
  102. package/server/lib/routing/history.js +34 -0
  103. package/server/lib/routing/jev.js +98 -0
  104. package/server/lib/routing/routes.http.test.js +100 -0
  105. package/server/lib/routing/routes.js +81 -0
  106. package/server/lib/routing/runtime.js +217 -0
  107. package/server/lib/routing/runtime.test.js +188 -0
  108. package/server/lib/routing/store.js +249 -0
  109. package/server/lib/routing/store.test.js +96 -0
  110. package/server/lib/security/request-security.js +9 -5
  111. package/server/lib/security/request-security.test.js +37 -0
  112. package/server/lib/ui-auth/DOCUMENTATION.md +8 -0
  113. package/server/lib/ui-auth/session-cookie.js +51 -0
  114. package/server/lib/ui-auth/session-cookie.test.js +46 -0
  115. package/server/lib/ui-auth/ui-auth.js +13 -9
  116. package/server/lib/ui-auth/ui-auth.test.js +56 -0
  117. package/dist/assets/DiffView-B7YkbY-u.js +0 -4
  118. package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +0 -1
  119. package/dist/assets/GitView-BLhlMYEY.js +0 -6
  120. package/dist/assets/GuestAttachDialog-B-fwE8r3.js +0 -3
  121. package/dist/assets/SettingsView-n2X-jfBB.js +0 -29
  122. package/dist/assets/SettingsWindow-Bi8LE9XI.js +0 -1
  123. package/dist/assets/index-DpzTz2UH.css +0 -1
  124. package/dist/assets/index-Dy8xgawx.js +0 -40
  125. package/dist/assets/main-BOYSXfYn.js +0 -896
  126. package/dist/assets/markdownCore-DPrwM1rU.js +0 -5
  127. package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +0 -2
  128. package/dist/assets/renderMobileApp-BK1kFlcJ.js +0 -25
  129. package/dist/assets/runtimeEndpointReset-BULHvOwb.js +0 -25
  130. package/dist/assets/tr-cIQtYBpg.js +0 -7
  131. package/dist/assets/useRootScrollLock-Cwc4kSl2.js +0 -1
package/dist/index.html CHANGED
@@ -509,16 +509,16 @@
509
509
  pointer-events: none;
510
510
  }
511
511
  </style>
512
- <script type="module" crossorigin src="/assets/main-Bjcre_GE.js"></script>
512
+ <script type="module" crossorigin src="/assets/main-CycplCph.js"></script>
513
513
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
514
514
  <link rel="modulepreload" crossorigin href="/assets/vendor-zod-fZppILAM.js">
515
515
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
516
516
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BUCujlKS.js">
517
517
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-BAGL70zf.js">
518
518
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-sdk-BJ73u-bH.js">
519
- <link rel="modulepreload" crossorigin href="/assets/index-Dy8xgawx.js">
519
+ <link rel="modulepreload" crossorigin href="/assets/index-DLHQogv8.js">
520
520
  <link rel="modulepreload" crossorigin href="/assets/contextPanelEmbeddedChat-CirXEPJq.js">
521
- <link rel="stylesheet" crossorigin href="/assets/index-DpzTz2UH.css">
521
+ <link rel="stylesheet" crossorigin href="/assets/index-B9Hvzjwl.css">
522
522
  </head>
523
523
  <body class="h-full bg-background text-foreground">
524
524
  <div id="root" class="h-full">
@@ -74,15 +74,15 @@
74
74
  }
75
75
  </style>
76
76
 
77
- <script type="module" crossorigin src="/assets/miniChat-Dz_bPgMc.js"></script>
77
+ <script type="module" crossorigin src="/assets/miniChat-DIQKfY2V.js"></script>
78
78
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
79
79
  <link rel="modulepreload" crossorigin href="/assets/vendor-zod-fZppILAM.js">
80
80
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
81
81
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BUCujlKS.js">
82
82
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-BAGL70zf.js">
83
83
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-sdk-BJ73u-bH.js">
84
- <link rel="modulepreload" crossorigin href="/assets/index-Dy8xgawx.js">
85
- <link rel="stylesheet" crossorigin href="/assets/index-DpzTz2UH.css">
84
+ <link rel="modulepreload" crossorigin href="/assets/index-DLHQogv8.js">
85
+ <link rel="stylesheet" crossorigin href="/assets/index-B9Hvzjwl.css">
86
86
  </head>
87
87
  <body class="h-full bg-background text-foreground">
88
88
  <div id="root" class="h-full">
package/dist/mobile.html CHANGED
@@ -63,15 +63,15 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-BbZPBJrK.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-BMwz5q-m.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/vendor-zod-fZppILAM.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
70
70
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BUCujlKS.js">
71
71
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-BAGL70zf.js">
72
72
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-sdk-BJ73u-bH.js">
73
- <link rel="modulepreload" crossorigin href="/assets/index-Dy8xgawx.js">
74
- <link rel="stylesheet" crossorigin href="/assets/index-DpzTz2UH.css">
73
+ <link rel="modulepreload" crossorigin href="/assets/index-DLHQogv8.js">
74
+ <link rel="stylesheet" crossorigin href="/assets/index-B9Hvzjwl.css">
75
75
  </head>
76
76
  <body class="h-full bg-background text-foreground">
77
77
  <div id="root" class="h-full"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openchamber/web",
3
- "version": "1.24.0",
3
+ "version": "1.24.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./server/index.js",
@@ -26,7 +26,7 @@
26
26
  "dependencies": {
27
27
  "@clack/prompts": "^1.1.0",
28
28
  "@octokit/rest": "^22.0.1",
29
- "@openchamber/sdk": "1.23.1",
29
+ "@openchamber/sdk": "1.24.1",
30
30
  "@opencode-ai/sdk": "1.18.31",
31
31
  "@simplewebauthn/server": "13.3.1",
32
32
  "bun-pty": "^0.4.5",
@@ -45,7 +45,8 @@
45
45
  "simple-git": "^3.36.0",
46
46
  "web-push": "^3.6.7",
47
47
  "ws": "^8.18.3",
48
- "yaml": "^2.8.1"
48
+ "yaml": "^2.8.1",
49
+ "zod": "^4.3.6"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@base-ui/react": "^1.4.0",
package/server/index.js CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  createGlobalUiEventBroadcaster,
44
44
  createGlobalMessageStreamHub,
45
45
  createMessageStreamWsRuntime,
46
+ resolveDeltaCoalesceWindowMs,
46
47
  DEFAULT_UPSTREAM_STALL_TIMEOUT_MS,
47
48
  UPSTREAM_STALL_TIMEOUT_CONCURRENT_MS,
48
49
  } from './lib/event-stream/index.js';
@@ -92,6 +93,7 @@ import { createApnsRuntime } from './lib/notifications/apns-runtime.js';
92
93
  import { createNotificationTemplateRuntime } from './lib/notifications/template-runtime.js';
93
94
  import { createPermissionAutoAcceptRuntime } from './lib/permission-auto-accept/runtime.js';
94
95
  import { createMessageQueueRuntime } from './lib/message-queue/runtime.js';
96
+ import { createRoutingRuntime } from './lib/routing/runtime.js';
95
97
  import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
96
98
  import { stopAllGuestServices } from './lib/guests/service.js';
97
99
  import { createProjectConfigRuntime } from './lib/projects/project-config.js';
@@ -892,6 +894,25 @@ const globalMessageStreamHub = createGlobalMessageStreamHub({
892
894
  buildOpenCodeUrl,
893
895
  getOpenCodeAuthHeaders,
894
896
  upstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
897
+ deltaCoalesceWindowMs: resolveDeltaCoalesceWindowMs(),
898
+ });
899
+
900
+ // OpenChamber-owned events for the UI control stream (SSE) plus the WS fan-out.
901
+ // OpenCode's /global/event proxy cannot carry them.
902
+ const broadcastOpenChamberUiEvent = createGlobalUiEventBroadcaster({
903
+ sseClients: uiOpenChamberEventClients,
904
+ wsClients: uiNotificationWsClients,
905
+ writeSseEvent,
906
+ });
907
+
908
+ // Jev model routing and the permission safety net. Dark unless
909
+ // OPENCHAMBER_ROUTING_ENABLE is set; every failure keeps the user's own model
910
+ // or the auto-accept reply it was asked about.
911
+ const routingRuntime = createRoutingRuntime({
912
+ dataDir: OPENCHAMBER_DATA_DIR,
913
+ buildOpenCodeUrl,
914
+ getOpenCodeAuthHeaders,
915
+ broadcastGlobalUiEvent: broadcastOpenChamberUiEvent,
895
916
  });
896
917
 
897
918
  const permissionAutoAcceptRuntime = createPermissionAutoAcceptRuntime({
@@ -901,6 +922,8 @@ const permissionAutoAcceptRuntime = createPermissionAutoAcceptRuntime({
901
922
  readSettingsFromDiskMigrated,
902
923
  persistSettings,
903
924
  broadcastGlobalUiEvent,
925
+ evaluatePermission: (permission, directory) => routingRuntime.evaluatePermission(permission, directory),
926
+ onPermissionReplied: (permissionId) => routingRuntime.forgetPermission(permissionId),
904
927
  });
905
928
  permissionAutoAcceptRuntime.start();
906
929
  notificationTriggerRuntime.setGetIsSessionAutoAccepting(
@@ -914,13 +937,8 @@ const messageQueueRuntime = createMessageQueueRuntime({
914
937
  buildOpenCodeUrl,
915
938
  getOpenCodeAuthHeaders,
916
939
  sessionKnowledgeRuntime,
917
- // OpenCode's /global/event SSE proxy cannot carry OpenChamber-owned events.
918
- // Use the shared control stream for SSE clients and the existing WS fan-out.
919
- broadcastGlobalUiEvent: createGlobalUiEventBroadcaster({
920
- sseClients: uiOpenChamberEventClients,
921
- wsClients: uiNotificationWsClients,
922
- writeSseEvent,
923
- }),
940
+ broadcastGlobalUiEvent: broadcastOpenChamberUiEvent,
941
+ resolvePromptBody: (body, target) => routingRuntime.resolvePromptBody(body, target),
924
942
  onPromptSent: (sessionId) => sessionRuntime.markUserMessageSent(sessionId),
925
943
  dataDir: OPENCHAMBER_DATA_DIR,
926
944
  });
@@ -1980,6 +1998,7 @@ async function main(options = {}) {
1980
1998
  writeSseEvent,
1981
1999
  permissionAutoAcceptRuntime,
1982
2000
  messageQueueRuntime,
2001
+ routingRuntime,
1983
2002
  });
1984
2003
 
1985
2004
  const startupPipelineResult = await startupPipelineRuntime.run({
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // The repo publishes `changelog/index.json` on `main`: one object per release,
4
4
  // newest first, with the app notes grouped as New / Improvements / Fixes /
5
- // Misc. This module fetches it and renders the releases between the installed
5
+ // SDK / Misc. This module fetches it and renders the releases between the installed
6
6
  // version (exclusive) and the offered one (inclusive) as the Markdown the
7
7
  // dialog already understands: a `## [x.y.z] - YYYY-MM-DD` header per release,
8
8
  // the release title in bold, the intro, then the groups.
@@ -16,6 +16,7 @@ const GROUPS = [
16
16
  ['new', 'New'],
17
17
  ['improvements', 'Improvements'],
18
18
  ['fixes', 'Fixes'],
19
+ ['sdk', 'SDK'],
19
20
  ['misc', 'Misc'],
20
21
  ];
21
22
 
@@ -37,6 +37,25 @@ A short intro.
37
37
  - Faster.`);
38
38
  });
39
39
 
40
+ it('shows SDK notes between Fixes and Misc and omits an empty SDK group', () => {
41
+ const withSdk = [{
42
+ ...index[0],
43
+ app: { ...index[0].app, sdk: ['Actions: background execution.'], misc: ['Packaging update.'] },
44
+ }];
45
+ expect(renderUpdateNotes(withSdk, '1.2.2', '1.2.3', compare)).toContain(`### Fixes
46
+
47
+ - Chat: no freeze.
48
+
49
+ ### SDK
50
+
51
+ - Actions: background execution.
52
+
53
+ ### Misc
54
+
55
+ - Packaging update.`);
56
+ expect(renderUpdateNotes([{ ...index[0], app: { sdk: [] } }], '1.2.2', '1.2.3', compare)).not.toContain('### SDK');
57
+ });
58
+
40
59
  it('returns null when nothing lies in the range or the payload is not an index', () => {
41
60
  expect(renderUpdateNotes(index, '1.2.3', '1.2.3', compare)).toBe(null);
42
61
  expect(renderUpdateNotes({ entries: [] }, '1.0.0', '9.9.9', compare)).toBe(null);
@@ -6,6 +6,7 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
6
6
  ## Entrypoints and structure
7
7
  - `packages/web/server/lib/event-stream/index.js`: public entrypoint re-exporting protocol and runtime helpers.
8
8
  - `packages/web/server/lib/event-stream/global-hub.js`: shared global upstream SSE hub for server-side subscribers and browser WS fan-out.
9
+ - `packages/web/server/lib/event-stream/delta-coalescer.js`: merges consecutive `message.part.delta` events before replay and fan-out. Pure, with injectable clock and timers.
9
10
  - `packages/web/server/lib/event-stream/global-ws-bridge.js`: browser-facing global WS bridge that subscribes clients to the shared global hub.
10
11
  - `packages/web/server/lib/event-stream/directory-ws-bridge.js`: browser-facing per-directory WS bridge that owns one scoped upstream reader per connection.
11
12
  - `packages/web/server/lib/event-stream/protocol.js`: path constants, SSE envelope parsing, and WebSocket frame serialization helpers.
@@ -31,6 +32,9 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
31
32
  - `createGlobalUiEventBroadcaster({ sseClients, wsClients, writeSseEvent })`: returns a broadcaster that fans out the same synthetic UI event to SSE and WS clients.
32
33
  - `createMessageStreamWsRuntime(...)`: mounts the message-stream WS server, upgrade handler, and SSE-to-WS bridge onto the web HTTP server.
33
34
 
35
+ ### Coalescing helpers
36
+ - `resolveDeltaCoalesceWindowMs(env)`: reads `OPENCHAMBER_EVENT_DELTA_COALESCE_MS`. Unset means 50ms, `0` turns coalescing off, and anything that is not a whole number from 0 to 1000 keeps the default with a warning.
37
+
34
38
  ### Upstream reader helpers
35
39
  - `DEFAULT_UPSTREAM_STALL_TIMEOUT_MS`: default idle timeout before an attached upstream SSE fetch is aborted for reconnect.
36
40
  - `DEFAULT_UPSTREAM_RECONNECT_DELAY_MS`: default delay between upstream reconnect attempts.
@@ -42,6 +46,7 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
42
46
  - The web server creates one shared global message-stream hub. OpenCode watcher side effects and global WS clients subscribe to that hub, so there is one upstream `/global/event` SSE reader for both server-side processing and browser fan-out.
43
47
  - The global hub keeps a bounded replay buffer keyed by SSE `eventId` so reconnecting browser clients can receive buffered events after their requested `Last-Event-ID`.
44
48
  - Replay retains at most 2,048 events and 8 MiB of UTF-8 wire frames. It stores encoded frames rather than retaining parsed payloads as well. Encoding is shared with live WS fanout. An oversized event still reaches live clients in full, but clears the retained suffix so replay cannot cross its gap. A missing replay cursor returns `null`, distinct from a complete empty tail; the bridge sends `ready` with `replayReset: true` and no partial replay. The client retires its cursor and requests authoritative repair, including during the early-boot reconnect grace period. A stopped hub retains its bounded suffix for clients reconnecting after the last socket closed.
49
+ - The hub numbers every event that arrives without an SSE id (`oc-<process>-<sequence>`). OpenCode 1.18 sends no ids at all, and an event without an id used to skip the replay buffer, so reconnecting clients had no cursor and lost whatever fell into the gap. The process prefix makes a cursor from before a server restart miss, which reports `replayReset`, instead of matching an unrelated sequence number.
45
50
  - Directory WS clients still attach one upstream `/event?directory=...` SSE reader per connection because directory streams are scoped.
46
51
  - If an upstream SSE stream stalls after the browser WS is already ready, the reader aborts that upstream fetch and reconnects upstream with `Last-Event-ID`, keeping the browser WS alive when recovery is fast.
47
52
  - When the shared global upstream reconnects after it was previously ready, the global WS bridge sends a fresh `ready` frame to already-ready browser clients. The browser treats this as a reconnect edge and can run scoped state repair without requiring the browser WS to close.
@@ -52,6 +57,23 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
52
57
  - The reusable upstream reader centralizes SSE fetch/parsing/reconnect behavior for the WS runtime and OpenCode watcher. Additional event consumers should move to it only with parity tests for their lifecycle and error semantics.
53
58
  - Browser transport concerns live in the WS bridge modules; server-side global stream ownership lives in `global-hub.js`.
54
59
 
60
+ ## Delta coalescing
61
+ OpenCode publishes one `message.part.delta` per token fragment. A 5.7 KB answer measured 3,402 delta events of 1.7 characters each, 97% of all frames and 1.3 MB on the wire. The hub merges them before replay and fan-out, which cut that stream to 483 frames and 197 KB with identical text. Replay holds merged frames too, so its 2,048 entries cover about seven times more streaming time.
62
+
63
+ Merging is lossless because of three rules. Change one only with the randomized test in `delta-coalescer.test.js` still passing.
64
+
65
+ - Every event that is not a well-formed delta is a barrier. All pending text is emitted before it, so a delta never crosses a part snapshot or a status change.
66
+ - Deltas of different part fields commute, so several stay pending at once. They are emitted in the order their latest fragment arrived, which keeps event ids in upstream order.
67
+ - A merged event carries the id of its last fragment. A client cursor is the id of the last frame it received, so it always names a boundary between merged events.
68
+
69
+ Pending text is bounded by time (the 50ms window), by size (64 KiB), and by part fields (64). Reaching a bound emits early. Nothing is dropped. The first delta after a quiet spell is emitted at once, so time to first text does not grow.
70
+
71
+ The hub commits pending text when it stops, so it reaches the retained replay suffix, and the global bridge commits it before it marks a socket ready. A client readied later therefore receives exactly the events that arrived after it was ready, as it did before coalescing, and a reconnecting client receives the committed text through replay.
72
+
73
+ Verified against a live server by dropping the socket every 150ms to 3s during a stream and resuming from the cursor: the reconstructed text matched byte for byte with no duplicate ids. Server-side hub subscribers receive merged events as well. None of them reads individual deltas.
74
+
75
+ The directory WS bridge and the SSE proxy (`/api/global/event`, used by Capacitor) still forward unmerged events.
76
+
55
77
  ## Notes for contributors
56
78
  - Keep protocol helpers pure and small so they can be unit tested without spinning up a server.
57
79
  - Keep `runtime.js` focused on WebSocket upgrade and endpoint dispatch. Put global browser-client lifecycle in `global-ws-bridge.js`, directory stream lifecycle in `directory-ws-bridge.js`, and upstream stream sharing in `global-hub.js`.
@@ -59,6 +81,7 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
59
81
  - Keep global replay bounded; do not turn it into an unbounded event log.
60
82
 
61
83
  ## Testing
84
+ - Run `bunx vitest run server/lib/event-stream` from `packages/web` for the whole module, including `delta-coalescer.test.js` and the resume-from-any-cursor cases in `global-hub.test.js`.
62
85
  - Run `bun test packages/web/server/lib/event-stream/protocol.test.js`
63
86
  - Run `bun test packages/web/server/lib/event-stream/upstream-reader.test.js`
64
87
  - Run `bun test packages/web/server/lib/event-stream/runtime.test.js`
@@ -0,0 +1,292 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { createDeltaCoalescer, DELTA_COALESCE_WINDOW_MS, resolveDeltaCoalesceWindowMs } from './delta-coalescer.js';
4
+
5
+ let nextId = 0;
6
+
7
+ const delta = (partID, text, { messageID = 'msg_1', field = 'text', directory = '/repo', sessionID = 'ses_1' } = {}) => {
8
+ nextId += 1;
9
+ const id = String(nextId).padStart(6, '0');
10
+ const payload = { id, type: 'message.part.delta', properties: { sessionID, messageID, partID, field, delta: text } };
11
+ return { envelope: { eventId: id, directory, payload }, payload };
12
+ };
13
+
14
+ const other = (type, properties = {}) => {
15
+ nextId += 1;
16
+ const id = String(nextId).padStart(6, '0');
17
+ const payload = { id, type, properties };
18
+ return { envelope: { eventId: id, directory: '/repo', payload }, payload };
19
+ };
20
+
21
+ // A clock and timer queue the test advances by hand, so every assertion about
22
+ // the window is exact instead of racing a real timeout.
23
+ const createHarness = (options = {}) => {
24
+ let time = 1_000_000;
25
+ let timers = [];
26
+ let timerSeq = 0;
27
+ const emitted = [];
28
+ const coalescer = createDeltaCoalescer({
29
+ emit: (event) => emitted.push(event),
30
+ now: () => time,
31
+ setTimer: (callback, delay) => {
32
+ timerSeq += 1;
33
+ timers.push({ id: timerSeq, at: time + delay, callback });
34
+ return timerSeq;
35
+ },
36
+ clearTimer: (id) => {
37
+ timers = timers.filter((timer) => timer.id !== id);
38
+ },
39
+ ...options,
40
+ });
41
+ const advance = (ms) => {
42
+ const target = time + ms;
43
+ for (;;) {
44
+ const due = timers.filter((timer) => timer.at <= target).sort((left, right) => left.at - right.at)[0];
45
+ if (!due) break;
46
+ timers = timers.filter((timer) => timer !== due);
47
+ time = due.at;
48
+ due.callback();
49
+ }
50
+ time = target;
51
+ };
52
+ return { coalescer, emitted, advance, pendingTimers: () => timers.length };
53
+ };
54
+
55
+ const isDelta = (event) => event.payload.type === 'message.part.delta';
56
+ const keyOf = (event) => `${event.payload.properties.messageID}:${event.payload.properties.partID}:${event.payload.properties.field}`;
57
+
58
+ const textByKey = (events) => {
59
+ const text = new Map();
60
+ for (const event of events) {
61
+ if (!isDelta(event)) continue;
62
+ text.set(keyOf(event), (text.get(keyOf(event)) ?? '') + event.payload.properties.delta);
63
+ }
64
+ return text;
65
+ };
66
+
67
+ describe('delta coalescer', () => {
68
+ it('emits the first delta after a quiet spell at once and unchanged', () => {
69
+ const { coalescer, emitted } = createHarness();
70
+ const first = delta('prt_a', 'He');
71
+
72
+ coalescer.push(first);
73
+
74
+ expect(emitted).toEqual([first]);
75
+ expect(emitted[0]).toBe(first);
76
+ });
77
+
78
+ it('merges following deltas for one part field and carries the last fragment id', () => {
79
+ const { coalescer, emitted, advance, pendingTimers } = createHarness();
80
+ const fragments = [delta('prt_a', 'He'), delta('prt_a', 'll'), delta('prt_a', 'o,'), delta('prt_a', ' wor'), delta('prt_a', 'ld')];
81
+
82
+ for (const fragment of fragments) coalescer.push(fragment);
83
+ expect(emitted).toHaveLength(1);
84
+ advance(50);
85
+
86
+ expect(emitted).toHaveLength(2);
87
+ expect(emitted[1].payload.properties).toEqual({ sessionID: 'ses_1', messageID: 'msg_1', partID: 'prt_a', field: 'text', delta: 'llo, world' });
88
+ expect(emitted[1].envelope.eventId).toBe(fragments[4].envelope.eventId);
89
+ expect(emitted[1].payload.id).toBe(fragments[4].payload.id);
90
+ expect(emitted[1].envelope.payload).toBe(emitted[1].payload);
91
+ expect(pendingTimers()).toBe(0);
92
+ // Upstream objects are never mutated: other hub subscribers may hold them.
93
+ expect(fragments.map((fragment) => fragment.payload.properties.delta)).toEqual(['He', 'll', 'o,', ' wor', 'ld']);
94
+ });
95
+
96
+ it('never holds text longer than the window', () => {
97
+ const { coalescer, emitted, advance } = createHarness();
98
+ coalescer.push(delta('prt_a', 'a'));
99
+ coalescer.push(delta('prt_a', 'b'));
100
+
101
+ advance(49);
102
+ expect(emitted).toHaveLength(1);
103
+ advance(1);
104
+ expect(emitted).toHaveLength(2);
105
+ });
106
+
107
+ it('treats every other event as a barrier, so a delta never crosses a part snapshot', () => {
108
+ const { coalescer, emitted, advance } = createHarness();
109
+ const snapshot = other('message.part.updated', { part: { id: 'prt_a', messageID: 'msg_1', text: 'abc' } });
110
+
111
+ coalescer.push(delta('prt_a', 'a'));
112
+ coalescer.push(delta('prt_a', 'b'));
113
+ coalescer.push(delta('prt_a', 'c'));
114
+ coalescer.push(snapshot);
115
+ coalescer.push(delta('prt_a', 'd'));
116
+ coalescer.push(delta('prt_a', 'e'));
117
+ advance(50);
118
+
119
+ expect(emitted.map((event) => (isDelta(event) ? event.payload.properties.delta : event.payload.type)))
120
+ .toEqual(['a', 'bc', 'message.part.updated', 'de']);
121
+ expect(emitted[2]).toBe(snapshot);
122
+ });
123
+
124
+ it('keeps several part fields pending at once and emits them in upstream id order', () => {
125
+ const { coalescer, emitted, advance } = createHarness();
126
+ coalescer.push(delta('prt_lead', '.'));
127
+
128
+ coalescer.push(delta('prt_a', 'a1'));
129
+ coalescer.push(delta('prt_b', 'b1', { messageID: 'msg_2', sessionID: 'ses_2' }));
130
+ coalescer.push(delta('prt_a', 'a2'));
131
+ const lastB = delta('prt_b', 'b2', { messageID: 'msg_2', sessionID: 'ses_2' });
132
+ coalescer.push(lastB);
133
+ advance(50);
134
+
135
+ const merged = emitted.slice(1);
136
+ expect(merged.map((event) => event.payload.properties.delta)).toEqual(['a1a2', 'b1b2']);
137
+ expect(merged[1].envelope.eventId).toBe(lastB.envelope.eventId);
138
+ const ids = emitted.map((event) => event.envelope.eventId);
139
+ expect(ids).toEqual([...ids].sort());
140
+ });
141
+
142
+ it('does not merge the same part across directories, sessions, messages, or fields', () => {
143
+ const { coalescer, emitted, advance } = createHarness();
144
+ coalescer.push(delta('prt_lead', '.'));
145
+
146
+ coalescer.push(delta('prt_a', '1'));
147
+ coalescer.push(delta('prt_a', '2', { directory: '/other' }));
148
+ coalescer.push(delta('prt_a', '3', { messageID: 'msg_2' }));
149
+ coalescer.push(delta('prt_a', '4', { field: 'reasoning' }));
150
+ coalescer.push(delta('prt_a', '5', { sessionID: 'ses_2' }));
151
+ advance(50);
152
+
153
+ expect(emitted.slice(1).map((event) => event.payload.properties.delta)).toEqual(['1', '2', '3', '4', '5']);
154
+ });
155
+
156
+ it('bounds pending text by characters and by part fields, emitting early instead of dropping', () => {
157
+ const { coalescer, emitted } = createHarness({ maxPendingChars: 10, maxPendingKeys: 3 });
158
+ coalescer.push(delta('prt_lead', '.'));
159
+
160
+ let peakChars = 0;
161
+ for (let index = 0; index < 40; index += 1) {
162
+ coalescer.push(delta('prt_a', 'xyz'));
163
+ peakChars = Math.max(peakChars, coalescer.pendingSize().chars);
164
+ }
165
+ expect(peakChars).toBeLessThan(10 + 3);
166
+ expect(textByKey(emitted).get('msg_1:prt_a:text')).toBe('xyz'.repeat(40));
167
+
168
+ let peakKeys = 0;
169
+ for (let index = 0; index < 20; index += 1) {
170
+ coalescer.push(delta(`prt_k${index}`, 'k'));
171
+ peakKeys = Math.max(peakKeys, coalescer.pendingSize().keys);
172
+ }
173
+ expect(peakKeys).toBeLessThanOrEqual(3);
174
+ coalescer.flush();
175
+ expect(emitted.filter((event) => event.payload.properties.delta === 'k')).toHaveLength(20);
176
+ });
177
+
178
+ it('flushes on demand and leaves nothing pending', () => {
179
+ const { coalescer, emitted, pendingTimers } = createHarness();
180
+ coalescer.push(delta('prt_a', 'a'));
181
+ coalescer.push(delta('prt_a', 'b'));
182
+
183
+ coalescer.flush();
184
+
185
+ expect(emitted.map((event) => event.payload.properties.delta)).toEqual(['a', 'b']);
186
+ expect(coalescer.pendingSize()).toEqual({ keys: 0, chars: 0 });
187
+ expect(pendingTimers()).toBe(0);
188
+ });
189
+
190
+ it('passes a malformed delta through as a barrier instead of guessing', () => {
191
+ const { coalescer, emitted } = createHarness();
192
+ const malformed = other('message.part.delta', { messageID: 'msg_1', partID: 'prt_a', field: 'text', delta: 42 });
193
+
194
+ coalescer.push(delta('prt_a', 'a'));
195
+ coalescer.push(delta('prt_a', 'b'));
196
+ coalescer.push(malformed);
197
+
198
+ expect(emitted.map((event) => event.payload.properties.delta)).toEqual(['a', 'b', 42]);
199
+ expect(emitted[2]).toBe(malformed);
200
+ });
201
+
202
+ it('is a pass-through when the window is zero', () => {
203
+ const { coalescer, emitted } = createHarness({ windowMs: 0 });
204
+ const events = [delta('prt_a', 'a'), delta('prt_a', 'b'), delta('prt_a', 'c')];
205
+
206
+ for (const event of events) coalescer.push(event);
207
+
208
+ expect(emitted).toEqual(events);
209
+ });
210
+
211
+ // The properties that make coalescing safe, checked over arbitrary streams
212
+ // rather than the handful of shapes someone thought of.
213
+ it('loses, duplicates, and reorders nothing across randomized streams', () => {
214
+ let seed = 0x5eed;
215
+ const random = () => {
216
+ seed = (seed * 1664525 + 1013904223) % 4294967296;
217
+ return seed / 4294967296;
218
+ };
219
+
220
+ for (let round = 0; round < 40; round += 1) {
221
+ const { coalescer, emitted, advance } = createHarness({ maxPendingChars: 200, maxPendingKeys: 4 });
222
+ const raw = [];
223
+ const partCount = 1 + Math.floor(random() * 6);
224
+ for (let index = 0; index < 600; index += 1) {
225
+ const roll = random();
226
+ let event;
227
+ if (roll < 0.9) {
228
+ const part = Math.floor(random() * partCount);
229
+ event = delta(`prt_${part}`, `${index}|`.repeat(1 + Math.floor(random() * 3)), { messageID: `msg_${part % 2}` });
230
+ } else if (roll < 0.95) {
231
+ event = other('message.part.updated', { part: { id: `prt_${Math.floor(random() * partCount)}`, messageID: 'msg_0' } });
232
+ } else {
233
+ event = other('session.status', { sessionID: 'ses_1', status: { type: 'busy' } });
234
+ }
235
+ raw.push(event);
236
+ coalescer.push(event);
237
+ if (random() < 0.3) advance(Math.floor(random() * 80));
238
+ }
239
+ advance(1_000);
240
+
241
+ // Nothing lost or duplicated: every part field ends with the same text.
242
+ expect(textByKey(emitted)).toEqual(textByKey(raw));
243
+
244
+ // Every other event is delivered once, as the same object, in order.
245
+ expect(emitted.filter((event) => !isDelta(event))).toEqual(raw.filter((event) => !isDelta(event)));
246
+
247
+ // Barrier: the text delivered before each barrier is exactly the text
248
+ // that arrived before it.
249
+ for (const barrier of raw.filter((event) => !isDelta(event))) {
250
+ expect(textByKey(emitted.slice(0, emitted.indexOf(barrier)))).toEqual(textByKey(raw.slice(0, raw.indexOf(barrier))));
251
+ }
252
+
253
+ // Replay cursors: ids stay unique and in upstream order.
254
+ const ids = emitted.map((event) => event.envelope.eventId);
255
+ expect(new Set(ids).size).toBe(ids.length);
256
+ expect(ids).toEqual([...ids].sort());
257
+
258
+ expect(coalescer.pendingSize()).toEqual({ keys: 0, chars: 0 });
259
+ }
260
+ });
261
+
262
+ it('collapses a dense single-part stream to a few frames per window', () => {
263
+ const { coalescer, emitted, advance } = createHarness();
264
+
265
+ // 150 fragments a second for two seconds, the rate measured from OpenCode.
266
+ for (let index = 0; index < 300; index += 1) {
267
+ coalescer.push(delta('prt_a', 'ab'));
268
+ advance(index % 3 === 2 ? 8 : 6);
269
+ }
270
+ advance(50);
271
+
272
+ expect(textByKey(emitted).get('msg_1:prt_a:text')).toBe('ab'.repeat(300));
273
+ expect(emitted.length).toBeLessThanOrEqual(45);
274
+ });
275
+ });
276
+
277
+ describe('resolveDeltaCoalesceWindowMs', () => {
278
+ it('uses the default when unset and accepts zero as off', () => {
279
+ expect(resolveDeltaCoalesceWindowMs({})).toBe(DELTA_COALESCE_WINDOW_MS);
280
+ expect(resolveDeltaCoalesceWindowMs({ OPENCHAMBER_EVENT_DELTA_COALESCE_MS: ' ' })).toBe(DELTA_COALESCE_WINDOW_MS);
281
+ expect(resolveDeltaCoalesceWindowMs({ OPENCHAMBER_EVENT_DELTA_COALESCE_MS: '0' })).toBe(0);
282
+ expect(resolveDeltaCoalesceWindowMs({ OPENCHAMBER_EVENT_DELTA_COALESCE_MS: '25' })).toBe(25);
283
+ });
284
+
285
+ it('keeps the default and says so for anything that is not 0-1000 whole milliseconds', () => {
286
+ for (const value of ['-1', '1001', '12.5', 'fast', 'NaN', '1e9']) {
287
+ const warnings = [];
288
+ expect(resolveDeltaCoalesceWindowMs({ OPENCHAMBER_EVENT_DELTA_COALESCE_MS: value }, (message) => warnings.push(message))).toBe(DELTA_COALESCE_WINDOW_MS);
289
+ expect(warnings).toHaveLength(1);
290
+ }
291
+ });
292
+ });