@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
@@ -1,5 +1,8 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
1
3
  import { createUpstreamSseReader } from './upstream-reader.js';
2
4
  import { serializeMessageStreamWsEvent } from './protocol.js';
5
+ import { createDeltaCoalescer, DELTA_COALESCE_WINDOW_MS } from './delta-coalescer.js';
3
6
 
4
7
  // Raised from 512 → 2048 to improve recovery after brief disconnects during
5
8
  // long-running agent sessions where many events accumulate quickly.
@@ -14,6 +17,7 @@ export function createGlobalMessageStreamHub({
14
17
  upstreamReconnectDelayMs,
15
18
  replayLimit = MESSAGE_STREAM_GLOBAL_REPLAY_LIMIT,
16
19
  replayByteLimit = MESSAGE_STREAM_GLOBAL_REPLAY_BYTES,
20
+ deltaCoalesceWindowMs = DELTA_COALESCE_WINDOW_MS,
17
21
  }) {
18
22
  if (!Number.isSafeInteger(replayLimit) || replayLimit < 0 || !Number.isSafeInteger(replayByteLimit) || replayByteLimit < 0) {
19
23
  throw new RangeError('Replay limits must be nonnegative safe integers');
@@ -23,6 +27,15 @@ export function createGlobalMessageStreamHub({
23
27
  const replay = [];
24
28
  let replayBytes = 0;
25
29
  let latestEventId;
30
+ // OpenCode's event stream carries no SSE ids (verified on 1.18.30: not one
31
+ // frame in a full response), and an event without an id never entered the
32
+ // replay buffer, so a reconnecting browser had no cursor and every event in
33
+ // the gap was gone. The replay log is this hub's own, so the hub numbers
34
+ // what upstream leaves unnumbered. The per-process prefix makes a cursor
35
+ // from before a restart miss instead of matching an unrelated sequence
36
+ // number, which reports `replayReset` and sends the client to repair.
37
+ const replayIdPrefix = `oc-${randomUUID().slice(0, 8)}-`;
38
+ let replaySequence = 0;
26
39
 
27
40
  let controller = null;
28
41
  let reader = null;
@@ -52,7 +65,9 @@ export function createGlobalMessageStreamHub({
52
65
  const normalizeEvent = ({ envelope, payload }) => {
53
66
  const directory =
54
67
  typeof envelope?.directory === 'string' && envelope.directory.length > 0 ? envelope.directory : 'global';
55
- const eventId = typeof envelope?.eventId === 'string' && envelope.eventId.length > 0 ? envelope.eventId : undefined;
68
+ const eventId = typeof envelope?.eventId === 'string' && envelope.eventId.length > 0
69
+ ? envelope.eventId
70
+ : `${replayIdPrefix}${String(++replaySequence).padStart(12, '0')}`;
56
71
  let serializedFrame;
57
72
  return {
58
73
  envelope,
@@ -66,6 +81,34 @@ export function createGlobalMessageStreamHub({
66
81
  };
67
82
  };
68
83
 
84
+ // Replay and fan-out see the same committed sequence: an event enters the
85
+ // replay buffer in the same step that delivers it, so a client's cursor
86
+ // always names a frame the buffer can find.
87
+ const commitEvent = (event) => {
88
+ const normalized = normalizeEvent(event);
89
+ latestEventId = normalized.eventId;
90
+ const serializedFrame = normalized.serialize();
91
+ const bytes = Buffer.byteLength(serializedFrame);
92
+ if (bytes > replayByteLimit) {
93
+ // An oversized live event creates a hole: retain only a contiguous
94
+ // suffix after it, never replay an older prefix across the gap.
95
+ replay.length = 0;
96
+ replayBytes = 0;
97
+ } else {
98
+ replay.push({ eventId: normalized.eventId, serializedFrame, bytes });
99
+ replayBytes += bytes;
100
+ while (replay.length > replayLimit || replayBytes > replayByteLimit) {
101
+ replayBytes -= replay.shift().bytes;
102
+ }
103
+ }
104
+
105
+ for (const subscriber of Array.from(eventSubscribers)) {
106
+ notifySubscriber('event', subscriber, normalized);
107
+ }
108
+ };
109
+
110
+ const coalescer = createDeltaCoalescer({ emit: commitEvent, windowMs: deltaCoalesceWindowMs });
111
+
69
112
  const start = () => {
70
113
  if (reader) {
71
114
  return;
@@ -98,28 +141,7 @@ export function createGlobalMessageStreamHub({
98
141
  notifyStatus({ type: 'disconnect', reason });
99
142
  },
100
143
  onEvent(event) {
101
- const normalized = normalizeEvent(event);
102
- if (normalized.eventId) {
103
- latestEventId = normalized.eventId;
104
- const serializedFrame = normalized.serialize();
105
- const bytes = Buffer.byteLength(serializedFrame);
106
- if (bytes > replayByteLimit) {
107
- // An oversized live event creates a hole: retain only a contiguous
108
- // suffix after it, never replay an older prefix across the gap.
109
- replay.length = 0;
110
- replayBytes = 0;
111
- } else {
112
- replay.push({ eventId: normalized.eventId, serializedFrame, bytes });
113
- replayBytes += bytes;
114
- while (replay.length > replayLimit || replayBytes > replayByteLimit) {
115
- replayBytes -= replay.shift().bytes;
116
- }
117
- }
118
- }
119
-
120
- for (const subscriber of Array.from(eventSubscribers)) {
121
- notifySubscriber('event', subscriber, normalized);
122
- }
144
+ coalescer.push(event);
123
145
  },
124
146
  onError(error) {
125
147
  if (controller?.signal.aborted) {
@@ -139,6 +161,8 @@ export function createGlobalMessageStreamHub({
139
161
 
140
162
  const stop = () => {
141
163
  connected = false;
164
+ // Text that already arrived belongs in the retained replay suffix.
165
+ coalescer.flush();
142
166
  reader?.stop();
143
167
  if (controller && !controller.signal.aborted) {
144
168
  controller.abort();
@@ -170,6 +194,12 @@ export function createGlobalMessageStreamHub({
170
194
  statusSubscribers.delete(subscriber);
171
195
  };
172
196
  },
197
+ // A client that becomes ready must not receive text from before it was
198
+ // ready merged into its first live delta, so the bridge commits pending
199
+ // deltas before it reads the replay tail.
200
+ flushPending() {
201
+ coalescer.flush();
202
+ },
173
203
  replayAfter(eventId) {
174
204
  if (!eventId) {
175
205
  return [];
@@ -62,6 +62,166 @@ async function waitForAssertion(assertion) {
62
62
  throw lastError;
63
63
  }
64
64
 
65
+ const deltaBlock = (id, text, partID = 'prt_a') => `id: ${id}\ndata: ${JSON.stringify({
66
+ id, type: 'message.part.delta',
67
+ properties: { sessionID: 'ses_1', messageID: 'msg_1', partID, field: 'text', delta: text },
68
+ })}\n\n`;
69
+
70
+ const createDeltaHub = ({ blocks, deltaCoalesceWindowMs }) => createGlobalMessageStreamHub({
71
+ buildOpenCodeUrl: (pathname) => `http://127.0.0.1:4096${pathname}`,
72
+ getOpenCodeAuthHeaders: () => ({}),
73
+ upstreamReconnectDelayMs: 60_000,
74
+ deltaCoalesceWindowMs,
75
+ fetchImpl: async () => createSseResponse({ blocks }),
76
+ });
77
+
78
+ // What a browser holds after applying frames in order: text per part, and the
79
+ // text each part had when a snapshot barrier passed.
80
+ const applyFrames = (frames) => {
81
+ const text = {};
82
+ const barriers = [];
83
+ for (const frame of frames) {
84
+ const payload = frame.payload;
85
+ if (payload.type === 'message.part.delta') {
86
+ text[payload.properties.partID] = (text[payload.properties.partID] ?? '') + payload.properties.delta;
87
+ } else {
88
+ barriers.push({ id: payload.id, seen: { ...text } });
89
+ }
90
+ }
91
+ return { text, barriers };
92
+ };
93
+
94
+ describe('delta coalescing in the global hub', () => {
95
+ it('delivers the same text in far fewer frames', async () => {
96
+ const words = Array.from({ length: 120 }, (_, index) => `w${index} `);
97
+ const hub = createDeltaHub({ blocks: words.map((word, index) => deltaBlock(`e${String(index).padStart(4, '0')}`, word)) });
98
+ const received = [];
99
+ hub.subscribeEvent((event) => received.push(event));
100
+ try {
101
+ hub.start();
102
+ await waitForAssertion(() => expect(applyFrames(received).text.prt_a).toBe(words.join('')));
103
+ expect(received.length).toBeLessThanOrEqual(3);
104
+ expect(received.at(-1).eventId).toBe('e0119');
105
+ } finally { hub.stop(); }
106
+ });
107
+
108
+ it('resumes from any cursor without losing or repeating text', async () => {
109
+ const blocks = [];
110
+ let id = 0;
111
+ const nextId = () => `e${String(id++).padStart(4, '0')}`;
112
+ for (let index = 0; index < 40; index += 1) blocks.push(deltaBlock(nextId(), `a${index}.`, index % 3 === 0 ? 'prt_b' : 'prt_a'));
113
+ const snapshotId = nextId();
114
+ blocks.push(`id: ${snapshotId}\ndata: ${JSON.stringify({ id: snapshotId, type: 'message.part.updated', properties: { part: { id: 'prt_a', messageID: 'msg_1' } } })}\n\n`);
115
+ for (let index = 0; index < 40; index += 1) blocks.push(deltaBlock(nextId(), `b${index}.`));
116
+
117
+ const hub = createDeltaHub({ blocks });
118
+ const received = [];
119
+ hub.subscribeEvent((event) => received.push(event));
120
+ try {
121
+ hub.start();
122
+ const expectedA = [...Array(40).keys()].filter((index) => index % 3 !== 0).map((index) => `a${index}.`).join('')
123
+ + [...Array(40).keys()].map((index) => `b${index}.`).join('');
124
+ await waitForAssertion(() => expect(applyFrames(received).text.prt_a).toBe(expectedA));
125
+ expect(received.length).toBeLessThan(blocks.length / 4);
126
+
127
+ const complete = applyFrames(received);
128
+ // The snapshot barrier saw exactly the text that arrived before it.
129
+ expect(complete.barriers).toHaveLength(1);
130
+ expect(complete.barriers[0].seen.prt_a).toBe([...Array(40).keys()].filter((index) => index % 3 !== 0).map((index) => `a${index}.`).join(''));
131
+
132
+ // A socket that drops after any frame reconnects with that frame's id.
133
+ for (let cut = 0; cut < received.length; cut += 1) {
134
+ const tail = hub.replayAfter(received[cut].eventId);
135
+ expect(tail).not.toBeNull();
136
+ const replayed = tail.map((entry) => JSON.parse(entry.serializedFrame));
137
+ expect(applyFrames([...received.slice(0, cut + 1), ...replayed])).toEqual(complete);
138
+ }
139
+ } finally { hub.stop(); }
140
+ });
141
+
142
+ // OpenCode 1.18 sends no SSE ids at all. Before the hub numbered such events
143
+ // itself the replay buffer stayed empty and every reconnect lost its gap.
144
+ it('numbers id-less upstream events so a reconnect resumes from any cursor', async () => {
145
+ const idless = (type, properties) => `data: ${JSON.stringify({ type, properties })}\n\n`;
146
+ const blocks = [];
147
+ for (let index = 0; index < 30; index += 1) {
148
+ blocks.push(idless('message.part.delta', { sessionID: 'ses_1', messageID: 'msg_1', partID: 'prt_a', field: 'text', delta: `a${index}.` }));
149
+ }
150
+ blocks.push(idless('message.part.updated', { part: { id: 'prt_a', messageID: 'msg_1' } }));
151
+ for (let index = 0; index < 30; index += 1) {
152
+ blocks.push(idless('message.part.delta', { sessionID: 'ses_1', messageID: 'msg_1', partID: 'prt_a', field: 'text', delta: `b${index}.` }));
153
+ }
154
+
155
+ const hub = createDeltaHub({ blocks });
156
+ const received = [];
157
+ hub.subscribeEvent((event) => received.push(event));
158
+ try {
159
+ hub.start();
160
+ const expected = [...Array(30).keys()].map((index) => `a${index}.`).join('') + [...Array(30).keys()].map((index) => `b${index}.`).join('');
161
+ await waitForAssertion(() => expect(applyFrames(received).text.prt_a).toBe(expected));
162
+
163
+ const ids = received.map((event) => event.eventId);
164
+ expect(ids.every((eventId) => typeof eventId === 'string' && eventId.length > 0)).toBe(true);
165
+ expect(new Set(ids).size).toBe(ids.length);
166
+ expect(ids).toEqual([...ids].sort());
167
+
168
+ const complete = applyFrames(received);
169
+ for (let cut = 0; cut < received.length; cut += 1) {
170
+ const tail = hub.replayAfter(received[cut].eventId);
171
+ expect(tail).not.toBeNull();
172
+ const replayed = tail.map((entry) => JSON.parse(entry.serializedFrame));
173
+ expect(replayed.every((frame) => typeof frame.eventId === 'string')).toBe(true);
174
+ expect(applyFrames([...received.slice(0, cut + 1), ...replayed])).toEqual(complete);
175
+ }
176
+
177
+ // A cursor minted by another server process must miss, never match by
178
+ // sequence number: the bridge then reports replayReset and the client
179
+ // repairs from HTTP instead of trusting a wrong tail.
180
+ const foreign = ids[0].replace(/^oc-[^-]+-/, 'oc-00000000-');
181
+ expect(foreign).not.toBe(ids[0]);
182
+ expect(hub.replayAfter(foreign)).toBeNull();
183
+ } finally { hub.stop(); }
184
+ });
185
+
186
+ it('keeps pending text for replay when the hub stops', async () => {
187
+ const hub = createDeltaHub({
188
+ deltaCoalesceWindowMs: 60_000,
189
+ blocks: ['one ', 'two ', 'three'].map((text, index) => deltaBlock(`e${index}`, text)),
190
+ });
191
+ const received = [];
192
+ hub.subscribeEvent((event) => received.push(event));
193
+ hub.start();
194
+ // The window is a minute, so only the leading delta has been delivered.
195
+ await waitForAssertion(() => expect(received).toHaveLength(1));
196
+ await new Promise((resolve) => setTimeout(resolve, 20));
197
+
198
+ hub.stop();
199
+
200
+ const tail = hub.replayAfter('e0').map((entry) => JSON.parse(entry.serializedFrame));
201
+ expect(applyFrames(tail).text.prt_a).toBe('two three');
202
+ expect(tail.at(-1).eventId).toBe('e2');
203
+ });
204
+
205
+ it('commits pending text on demand, so a client readied later starts after it', async () => {
206
+ const hub = createDeltaHub({
207
+ deltaCoalesceWindowMs: 60_000,
208
+ blocks: ['one ', 'two ', 'three'].map((text, index) => deltaBlock(`e${index}`, text)),
209
+ });
210
+ const received = [];
211
+ hub.subscribeEvent((event) => received.push(event));
212
+ try {
213
+ hub.start();
214
+ await waitForAssertion(() => expect(received).toHaveLength(1));
215
+ await new Promise((resolve) => setTimeout(resolve, 20));
216
+
217
+ hub.flushPending();
218
+
219
+ expect(applyFrames(received).text.prt_a).toBe('one two three');
220
+ expect(hub.replayAfter('e2')).toEqual([]);
221
+ } finally { hub.stop(); }
222
+ });
223
+ });
224
+
65
225
  describe('createGlobalMessageStreamHub', () => {
66
226
  it('continues fanout when an event subscriber throws', async () => {
67
227
  const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
@@ -46,6 +46,7 @@ export function createGlobalMessageStreamWsBridge({
46
46
  return;
47
47
  }
48
48
 
49
+ globalHub.flushPending();
49
50
  const replay = globalHub.replayAfter(requestedLastEventId);
50
51
  const ready = { type: 'ready', scope: 'global' };
51
52
  if (replay === null) ready.replayReset = true;
@@ -7,6 +7,10 @@ export {
7
7
  createGlobalMessageStreamHub,
8
8
  } from './global-hub.js';
9
9
 
10
+ export {
11
+ resolveDeltaCoalesceWindowMs,
12
+ } from './delta-coalescer.js';
13
+
10
14
  export {
11
15
  DEFAULT_UPSTREAM_STALL_TIMEOUT_MS,
12
16
  UPSTREAM_STALL_TIMEOUT_CONCURRENT_MS,
@@ -24,10 +24,11 @@ The following functions are exported and used by the web server:
24
24
  - `getRemoteUrl(directory, remoteName)`: Get URL for a specific remote.
25
25
 
26
26
  ### Status and Diff Operations
27
- - `getStatus(directory)`: Get comprehensive Git status including current branch, tracking, ahead/behind, file changes, diff stats, merge/rebase state.
27
+ - `getStatus(directory, { mode })`: Get comprehensive Git status including current branch, tracking, ahead/behind, file changes, diff stats, merge/rebase state. `mode: 'light'` skips the diff stats. One read runs per directory at a time and at most four run across directories (`serial-refresh.js`): a call made while a read is running waits for one follow-up read that starts after the call, so no caller gets a snapshot older than its request, and every caller that arrives during one read shares that single follow-up at the widest mode any of them asked for. Clients refresh after every completed agent tool call and from several surfaces at once; on a large repository (a status read is a dozen Git processes walking the working tree) this bound is what keeps identical `git status` processes from piling up side by side. Untracked files are listed with `-unormal` and each new directory is then expanded to its files with a bounded `ls-files` listing (`UNTRACKED_DIRECTORY_EXPANSION_LIMIT`, 1000): up to that many files the result equals `-uall`; beyond it the directory stays one `dir/` entry, because `-uall` would walk a forgotten build or dependency directory in full on every read. A nested repository stays a `dir/` entry as before.
28
+ - `getTrackingBranch(directory)`: Upstream of the checked-out branch as `remote/branch` (the same value as `status.tracking`, including an upstream whose remote ref is gone), or `null` when HEAD is detached or unborn or no upstream is configured. Reads refs and config only. Callers that need just the tracking name (GitHub PR status polling, PR creation) use this instead of `getStatus`.
28
29
  - `getDiff(directory, { path, staged, contextLines })`: Get diff output for files or entire working tree with full Git blob identities. Untracked symbolic links are represented as link entries without following their targets.
29
30
  - `getPathDiff(directory, { path, staged, contextLines })`: `getDiff` for one path, returning `{ diff, submodule }`. `submodule` is `null` for ordinary paths. For a gitlink it is `{ headCommit, indexCommit, worktreeCommit, hasTrackedChanges, hasUntrackedFiles, hasConflict }`, because a submodule that only gained untracked files shows as modified in status while its patch is empty. `worktreeCommit` is `null` when the submodule is not checked out. An unmerged gitlink has no single index commit, so it reports `hasConflict: true` with `indexCommit: null`. Exposed as `GET /api/git/diff`.
30
- - Paths come from an earlier status listing and can stop resolving. Per-path operations reject with `error.code`: `path_not_found` when the path is absent from the working tree, index, and HEAD (for example, a file removed after the listing), and `nested_repository` when the path is a directory holding its own `.git` that is not a submodule (status lists it as `dir/`). `GET /api/git/diff` and `GET /api/git/file-diff` answer these with 404 and 422 and a `{ error, code }` body instead of 500. Entry existence is read from `ls-files --stage` and `ls-tree` modes, not `cat-file -e`: a gitlink's commit is not in the parent's object store, and simple-git reports that silent exit 1 as success.
31
+ - Paths come from an earlier status listing and can stop resolving. Per-path operations reject with `error.code`: `path_not_found` when the path is absent from the working tree, index, and HEAD (for example, a file removed after the listing), `nested_repository` when the path is a directory holding its own `.git` that is not a submodule (status lists it as `dir/`), and `untracked_directory` when the path is a directory status kept as one `dir/` entry because it holds more untracked files than the expansion bound. `GET /api/git/diff` and `GET /api/git/file-diff` answer these with 404, 422 and 422 and a `{ error, code }` body instead of 500. Entry existence is read from `ls-files --stage` and `ls-tree` modes, not `cat-file -e`: a gitlink's commit is not in the parent's object store, and simple-git reports that silent exit 1 as success.
31
32
  - `getRangeDiff(directory, { base, head, path, contextLines, includeWorkingTree })`: Compare the merge base of the exact selected refs with `head`. With `includeWorkingTree: true`, compare with the checked-out branch's current files instead, including committed, staged, unstaged, and untracked work in one net diff. This mode rejects a head that is not the checked-out branch. Exposed as `GET /api/git/range-diff`; omit `path` for the whole comparison.
32
33
  - `getRangeFiles(directory, { base, head, includeWorkingTree })`: List changed paths using the same comparison as `getRangeDiff`. A successful empty list means the final files match the merge base, even if staging and working-tree changes cancel each other out.
33
34
  - Both range operations honor refs literally. A local `main` is never replaced with `origin/main`, and an unavailable ref fails rather than choosing a different remote. The UI picker sends qualified refs to distinguish local and remote branches with matching display names.
@@ -83,6 +84,17 @@ bootstrap, tracking is left unset rather than writing `branch.*.remote` /
83
84
  - `removeRemote(directory, options)`: Remove a configured remote (except `origin`).
84
85
  - `deleteRemoteBranch(directory, options)`: Delete a remote branch.
85
86
 
87
+ `push` leaves an unspecified destination to Git, including `branch.<name>.pushRemote`
88
+ and `remote.pushDefault`. Its missing-upstream fallback uses that same destination;
89
+ an explicit remote overrides configuration. `pushed` contains only refs changed by
90
+ the operation, derived from Git's porcelain flags, including first publication,
91
+ fast-forward and forced updates. Each entry's `remote` is the destination remote
92
+ name, not a ref. A successful no-op returns an empty array; rejected pushes throw.
93
+ Commit & Push and Sync share the same fetch/pull/push flow in web, Electron and
94
+ mobile, and never infer publication from an upstream `ahead` count. Fetch follows
95
+ the selected upstream while push routing remains independent. VS Code does not
96
+ mount these Git panels and keeps its separate extension-host Git implementation.
97
+
86
98
  ### Log Operations
87
99
  - `getLog(directory, options)`: Get commit history with stats (supports maxCount, from, to, file filters).
88
100
  - `getCommitFiles(directory, commitHash)`: Get file changes for a specific commit relative to its first parent, or the empty tree for a root commit. NUL-delimited paths preserve whitespace; renamed files return their destination in `path` and source in `previousPath`.
@@ -110,7 +122,7 @@ bootstrap, tracking is left unset rather than writing `branch.*.remote` /
110
122
 
111
123
  The following functions are internal helpers used by exported functions:
112
124
  - `buildSshCommand(sshKeyPath)`: Build SSH command string for git config.
113
- - `buildGitEnv()`: Build Git environment with SSH_AUTH_SOCK resolution.
125
+ - `buildGitEnv()`: Build Git environment with SSH_AUTH_SOCK resolution and `GIT_TERMINAL_PROMPT=0` (unless the server was started with it set): the server has no terminal a user could answer, so a Git command that would ask for a username or password fails instead of waiting forever on a console nobody sees. Credential helpers, including GUI ones, still run before Git would prompt.
114
126
  - `createGit(directory)`: Create simple-git instance with environment.
115
127
  - `normalizeDirectoryPath(value)`: Normalize directory paths (supports ~ expansion).
116
128
  - `cleanBranchName(branch)`: Remove refs/heads/ or refs/ prefixes.
@@ -132,7 +144,7 @@ The following functions are internal helpers used by exported functions:
132
144
  - `upstreamComparison`: Optional comparison against `upstream/<current-branch>`, with `{ remote, branch, ahead, behind }`.
133
145
  - `files`: Array of file objects with `path`, `index`, `working_dir` status codes.
134
146
  - `isClean`: Boolean indicating if working tree is clean.
135
- - `diffStats`: Object mapping file paths to `{ insertions, deletions }`.
147
+ - `diffStats`: Scope-aware per-file line stats, `{ staged, working }`. `staged` is HEAD → index (`git diff --cached --numstat`), `working` is index → working tree (`git diff --numstat`). A partially staged file appears in both maps with its own scope's counts; the two are never summed together. Untracked and working-tree-added files are counted into `working`; files added to the index are counted into `staged`.
136
148
  - `mergeInProgress`: Object with `{ head, message }` if merge in progress.
137
149
  - `rebaseInProgress`: Object with `{ headName, onto }` if rebase in progress.
138
150
 
@@ -168,6 +180,7 @@ The following functions are internal helpers used by exported functions:
168
180
  surface and VS Code does not mount these controls.
169
181
  - Untracked patches from `getDiff` and `getUntrackedDiffs` use `git diff --no-index` with separate stdout, stderr, and process exit status. Exit codes 0 and 1 return stdout only, so line-ending warnings never become patch text or request failures. Other exits and process failures reject the single-file request; the batch keeps an empty entry for the failed path and preserves the other results.
170
182
  - `status.files` exposes both `index` and `working_dir` codes. Shared UI uses these as separate scopes: staged rows are derived from non-empty `index` statuses, while unstaged rows are derived from `working_dir` statuses and untracked files.
183
+ - `status.diffStats` follows the same scopes (`staged`, `working`), so a staged row shows HEAD → index counts and an unstaged row shows index → working-tree counts. A file with edits in both scopes reports each part in its own row instead of one combined total.
171
184
  - A file with both staged and unstaged changes can appear in both UI sections. Staged rows request diffs with `staged: true`; unstaged rows request normal working-tree diffs.
172
185
  - The shared Git panel exposes explicit staging actions. Unstaged rows use `stageFile`, staged rows use `unstageFile`, and commits operate on the current staged index.
173
186
  - `stageFiles` remains supported for callers that need to stage a selected unstaged subset as part of commit. In that mode the server temporarily unstages unrelated index entries, stages `stageFiles`, commits from the index, then restores temporarily unstaged entries.
@@ -12,7 +12,7 @@ export function registerGitRoutes(app, { emitWorktreeChanged } = {}) {
12
12
 
13
13
  // A path from an earlier status listing that no longer resolves is a stale
14
14
  // row or a nested repository, not a server fault.
15
- const GIT_PATH_ERROR_STATUS = new Map([['path_not_found', 404], ['nested_repository', 422]]);
15
+ const GIT_PATH_ERROR_STATUS = new Map([['path_not_found', 404], ['nested_repository', 422], ['untracked_directory', 422]]);
16
16
  const sendGitPathError = (res, error) => {
17
17
  const status = GIT_PATH_ERROR_STATUS.get(error?.code);
18
18
  if (!status) return false;
@@ -0,0 +1,93 @@
1
+ // Runs one refresh per key at a time and bounds how many keys refresh at once.
2
+ //
3
+ // A request that arrives while a refresh for its key is running does not join
4
+ // that run: the run may have read the working tree before the change the
5
+ // caller just made. Instead the request waits for one follow-up run that starts
6
+ // after the current one finishes, so every caller receives a result at least as
7
+ // fresh as its own arrival. All requests that arrive during one run share the
8
+ // same follow-up, which caps the work per key at "one running, one pending"
9
+ // no matter how many callers ask.
10
+
11
+ export function createSerialRefresh({ maxConcurrent = Number.POSITIVE_INFINITY } = {}) {
12
+ const runs = new Map();
13
+ let running = 0;
14
+ const waiting = [];
15
+
16
+ const acquire = () => new Promise((resolve) => {
17
+ if (running < maxConcurrent) {
18
+ running += 1;
19
+ resolve();
20
+ return;
21
+ }
22
+ waiting.push(resolve);
23
+ });
24
+
25
+ const release = () => {
26
+ const next = waiting.shift();
27
+ if (next) {
28
+ next();
29
+ return;
30
+ }
31
+ running -= 1;
32
+ };
33
+
34
+ const start = (key, requests, execute, deferred) => {
35
+ const run = { follower: null };
36
+ runs.set(key, run);
37
+ const promise = (async () => {
38
+ await acquire();
39
+ try {
40
+ return await execute(requests);
41
+ } finally {
42
+ release();
43
+ }
44
+ })();
45
+ if (deferred) {
46
+ promise.then(deferred.resolve, deferred.reject);
47
+ }
48
+ promise
49
+ .catch(() => undefined)
50
+ .then(() => {
51
+ if (runs.get(key) !== run) return;
52
+ if (run.follower) {
53
+ const follower = run.follower;
54
+ start(key, follower.requests, follower.execute, follower);
55
+ return;
56
+ }
57
+ runs.delete(key);
58
+ });
59
+ return promise;
60
+ };
61
+
62
+ return {
63
+ /**
64
+ * @template TRequest, TResult
65
+ * @param {string} key
66
+ * @param {TRequest} request
67
+ * @param {(requests: TRequest[]) => Promise<TResult>} execute receives every
68
+ * request the run answers, so it can widen the work to satisfy all of them
69
+ * @returns {Promise<TResult>}
70
+ */
71
+ run(key, request, execute) {
72
+ const current = runs.get(key);
73
+ if (!current) {
74
+ return start(key, [request], execute);
75
+ }
76
+ if (!current.follower) {
77
+ let resolve;
78
+ let reject;
79
+ const promise = new Promise((res, rej) => {
80
+ resolve = res;
81
+ reject = rej;
82
+ });
83
+ current.follower = { requests: [], execute, promise, resolve, reject };
84
+ }
85
+ current.follower.requests.push(request);
86
+ return current.follower.promise;
87
+ },
88
+ /** Keys with a running or pending refresh. Exposed for tests. */
89
+ get activeKeys() {
90
+ return Array.from(runs.keys());
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,112 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createSerialRefresh } from './serial-refresh.js';
3
+
4
+ const createGate = () => {
5
+ let release;
6
+ const opened = new Promise((resolve) => {
7
+ release = resolve;
8
+ });
9
+ return { opened, release };
10
+ };
11
+
12
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
13
+
14
+ describe('createSerialRefresh', () => {
15
+ it('runs one refresh per key and answers later callers with one follow-up run', async () => {
16
+ const refresh = createSerialRefresh();
17
+ const gates = [createGate(), createGate()];
18
+ const executions = [];
19
+ const execute = async (requests) => {
20
+ const index = executions.length;
21
+ executions.push(requests);
22
+ await gates[index].opened;
23
+ return `run-${index}`;
24
+ };
25
+
26
+ const first = refresh.run('repo', 'a', execute);
27
+ await flush();
28
+ const second = refresh.run('repo', 'b', execute);
29
+ const third = refresh.run('repo', 'c', execute);
30
+ await flush();
31
+
32
+ expect(executions).toEqual([['a']]);
33
+
34
+ gates[0].release();
35
+ await expect(first).resolves.toBe('run-0');
36
+ await flush();
37
+ expect(executions).toEqual([['a'], ['b', 'c']]);
38
+
39
+ gates[1].release();
40
+ await expect(second).resolves.toBe('run-1');
41
+ await expect(third).resolves.toBe('run-1');
42
+ await flush();
43
+ expect(refresh.activeKeys).toEqual([]);
44
+ });
45
+
46
+ it('never serves a caller from a run that started before it asked', async () => {
47
+ const refresh = createSerialRefresh();
48
+ const gate = createGate();
49
+ let reads = 0;
50
+ const execute = async () => {
51
+ reads += 1;
52
+ const value = reads;
53
+ if (value === 1) await gate.opened;
54
+ return value;
55
+ };
56
+
57
+ const early = refresh.run('repo', null, execute);
58
+ await flush();
59
+ const late = refresh.run('repo', null, execute);
60
+ gate.release();
61
+
62
+ await expect(early).resolves.toBe(1);
63
+ await expect(late).resolves.toBe(2);
64
+ });
65
+
66
+ it('keeps keys independent and bounds how many run at once', async () => {
67
+ const refresh = createSerialRefresh({ maxConcurrent: 2 });
68
+ const gates = new Map();
69
+ const started = [];
70
+ const execute = (key) => async () => {
71
+ started.push(key);
72
+ const gate = createGate();
73
+ gates.set(key, gate);
74
+ await gate.opened;
75
+ return key;
76
+ };
77
+
78
+ const runs = ['a', 'b', 'c'].map((key) => refresh.run(key, null, execute(key)));
79
+ await flush();
80
+ expect(started).toEqual(['a', 'b']);
81
+
82
+ gates.get('a').release();
83
+ await flush();
84
+ expect(started).toEqual(['a', 'b', 'c']);
85
+
86
+ gates.get('b').release();
87
+ gates.get('c').release();
88
+ await expect(Promise.all(runs)).resolves.toEqual(['a', 'b', 'c']);
89
+ });
90
+
91
+ it('propagates a failed run to its callers and still runs the follow-up', async () => {
92
+ const refresh = createSerialRefresh();
93
+ const gate = createGate();
94
+ let calls = 0;
95
+ const execute = async () => {
96
+ calls += 1;
97
+ if (calls === 1) {
98
+ await gate.opened;
99
+ throw new Error('first failed');
100
+ }
101
+ return 'ok';
102
+ };
103
+
104
+ const first = refresh.run('repo', null, execute);
105
+ await flush();
106
+ const second = refresh.run('repo', null, execute);
107
+ gate.release();
108
+
109
+ await expect(first).rejects.toThrow('first failed');
110
+ await expect(second).resolves.toBe('ok');
111
+ });
112
+ });