@pi-chamber/web 0.9.6 → 0.9.7
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.
- package/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BvrCkm_z.js} +1 -1
- package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-DGa9u43J.js} +1 -1
- package/dist/assets/{FilesView-B_BF39ef.js → FilesView-CNHu4RnC.js} +4 -4
- package/dist/assets/{GitView-LFEpCasf.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DGT31A3z.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-BjniCdZ5.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-CsAu9rOt.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-Dh58uD3I.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-CH3EqGJI.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-HzTrVvbB.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-lj4gpGsO.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-BTZutbn-.js} +2 -2
- package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-DWuadqra.js → web-components-CYngz9Ml.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- package/server/lib/pi/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +76 -25
- package/server/lib/pi/routes.test.js +48 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon.js +55 -6
- package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
- package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +3 -1
- package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
- package/dist/assets/index-BpmGBboM.css +0 -1
- package/dist/assets/index-DZnzXhTs.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
- package/dist/assets/useSwitcherItems-CazJ6Yox.js +0 -1
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
7
|
+
createPiEventStreamRegistry,
|
|
8
|
+
openPiEventStream,
|
|
9
|
+
} from './event-stream.js';
|
|
10
|
+
import { registerPiRuntimeRoutes } from './routes.js';
|
|
11
|
+
|
|
12
|
+
const flush = async () => {
|
|
13
|
+
for (let i = 0; i < 10; i++) await Promise.resolve();
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const createFakeReq = () => {
|
|
17
|
+
const listeners = {};
|
|
18
|
+
return {
|
|
19
|
+
once: (event, handler) => {
|
|
20
|
+
(listeners[event] ??= []).push(handler);
|
|
21
|
+
},
|
|
22
|
+
off: (event, handler) => {
|
|
23
|
+
listeners[event] = (listeners[event] ?? []).filter((candidate) => candidate !== handler);
|
|
24
|
+
},
|
|
25
|
+
emit: (event) => {
|
|
26
|
+
for (const handler of [...(listeners[event] ?? [])]) handler();
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Fake response with deterministic backpressure: every write is buffered
|
|
33
|
+
* forever (the client never reads), so `writableLength` grows monotonically
|
|
34
|
+
* and `write()` returns false once past `highWater`.
|
|
35
|
+
*/
|
|
36
|
+
/**
|
|
37
|
+
* Fake response with deterministic backpressure: every write is buffered
|
|
38
|
+
* forever (the client never reads), so `writableLength` grows monotonically.
|
|
39
|
+
* With `highWaterMark`, `write()` buffers the chunk and then returns false
|
|
40
|
+
* once past the mark (like a real socket), and `'drain'` only fires if a test
|
|
41
|
+
* emits it — so a never-draining client is fully deterministic.
|
|
42
|
+
*/
|
|
43
|
+
const createFakeRes = ({ highWaterMark } = {}) => {
|
|
44
|
+
const state = { chunks: [], destroyed: false, writableEnded: false, endCount: 0, bytes: 0, closeEmitted: false };
|
|
45
|
+
const listeners = {};
|
|
46
|
+
const res = {
|
|
47
|
+
get destroyed() {
|
|
48
|
+
return state.destroyed;
|
|
49
|
+
},
|
|
50
|
+
get writableEnded() {
|
|
51
|
+
return state.writableEnded;
|
|
52
|
+
},
|
|
53
|
+
get writableLength() {
|
|
54
|
+
return state.bytes;
|
|
55
|
+
},
|
|
56
|
+
write(chunk) {
|
|
57
|
+
if (state.destroyed || state.writableEnded) return false;
|
|
58
|
+
state.chunks.push(chunk);
|
|
59
|
+
state.bytes += Buffer.byteLength(chunk);
|
|
60
|
+
return highWaterMark === undefined || state.bytes < highWaterMark;
|
|
61
|
+
},
|
|
62
|
+
end() {
|
|
63
|
+
state.endCount += 1;
|
|
64
|
+
state.writableEnded = true;
|
|
65
|
+
},
|
|
66
|
+
destroy() {
|
|
67
|
+
state.destroyed = true;
|
|
68
|
+
if (!state.closeEmitted) {
|
|
69
|
+
state.closeEmitted = true;
|
|
70
|
+
res.emit('close');
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
on(event, handler) {
|
|
74
|
+
(listeners[event] ??= []).push(handler);
|
|
75
|
+
},
|
|
76
|
+
once(event, handler) {
|
|
77
|
+
(listeners[event] ??= []).push(handler);
|
|
78
|
+
},
|
|
79
|
+
off(event, handler) {
|
|
80
|
+
listeners[event] = (listeners[event] ?? []).filter((candidate) => candidate !== handler);
|
|
81
|
+
},
|
|
82
|
+
emit(event, ...args) {
|
|
83
|
+
for (const handler of [...(listeners[event] ?? [])]) handler(...args);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
res.__state = state;
|
|
87
|
+
return res;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const frame = (sequence, padding = '') => ({
|
|
91
|
+
protocolVersion: 1,
|
|
92
|
+
kind: 'event',
|
|
93
|
+
event: 'session.updated',
|
|
94
|
+
sequence,
|
|
95
|
+
payload: { sessionId: 's', directory: '/workspace', title: `t${sequence}${padding}` },
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const writtenData = (res) => res.__state.chunks
|
|
99
|
+
.filter((chunk) => chunk.startsWith('data: '))
|
|
100
|
+
.map((chunk) => JSON.parse(chunk.slice('data: '.length)).payload.title);
|
|
101
|
+
|
|
102
|
+
describe('Pi event stream lifecycle', () => {
|
|
103
|
+
beforeEach(() => {
|
|
104
|
+
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
afterEach(() => {
|
|
108
|
+
vi.useRealTimers();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('closes a late subscription exactly once when the client disconnects while subscribe is pending', async () => {
|
|
112
|
+
let resolveSubscribe;
|
|
113
|
+
let closeCalls = 0;
|
|
114
|
+
const req = createFakeReq();
|
|
115
|
+
const res = createFakeRes();
|
|
116
|
+
openPiEventStream({
|
|
117
|
+
req,
|
|
118
|
+
res,
|
|
119
|
+
projectFrame: (value) => value,
|
|
120
|
+
subscribe: () => new Promise((resolve) => {
|
|
121
|
+
resolveSubscribe = resolve;
|
|
122
|
+
}),
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Client leaves before the subscription opens.
|
|
126
|
+
req.emit('close');
|
|
127
|
+
resolveSubscribe(() => {
|
|
128
|
+
closeCalls += 1;
|
|
129
|
+
});
|
|
130
|
+
await flush();
|
|
131
|
+
|
|
132
|
+
expect(closeCalls).toBe(1);
|
|
133
|
+
expect(res.__state.chunks).toEqual([]);
|
|
134
|
+
expect(res.__state.endCount).toBe(0);
|
|
135
|
+
// No heartbeat is attached to the dead response.
|
|
136
|
+
vi.advanceTimersByTime(60_000);
|
|
137
|
+
expect(res.__state.chunks).toEqual([]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('closes a late subscription exactly once on shutdown while subscribe is pending', async () => {
|
|
141
|
+
const registry = createPiEventStreamRegistry();
|
|
142
|
+
let resolveSubscribe;
|
|
143
|
+
let closeCalls = 0;
|
|
144
|
+
const req = createFakeReq();
|
|
145
|
+
const res = createFakeRes();
|
|
146
|
+
openPiEventStream({
|
|
147
|
+
req,
|
|
148
|
+
res,
|
|
149
|
+
registry,
|
|
150
|
+
projectFrame: (value) => value,
|
|
151
|
+
subscribe: () => new Promise((resolve) => {
|
|
152
|
+
resolveSubscribe = resolve;
|
|
153
|
+
}),
|
|
154
|
+
});
|
|
155
|
+
expect(registry.size).toBe(1);
|
|
156
|
+
|
|
157
|
+
registry.closeAll();
|
|
158
|
+
registry.closeAll();
|
|
159
|
+
resolveSubscribe(() => {
|
|
160
|
+
closeCalls += 1;
|
|
161
|
+
});
|
|
162
|
+
await flush();
|
|
163
|
+
|
|
164
|
+
expect(closeCalls).toBe(1);
|
|
165
|
+
expect(registry.size).toBe(0);
|
|
166
|
+
expect(res.__state.chunks).toEqual([]);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('ends an active connection once on shutdown and is idempotent across close events', async () => {
|
|
170
|
+
const registry = createPiEventStreamRegistry();
|
|
171
|
+
let closeCalls = 0;
|
|
172
|
+
const req = createFakeReq();
|
|
173
|
+
const res = createFakeRes();
|
|
174
|
+
openPiEventStream({
|
|
175
|
+
req,
|
|
176
|
+
res,
|
|
177
|
+
registry,
|
|
178
|
+
heartbeatMs: 5,
|
|
179
|
+
projectFrame: (value) => value,
|
|
180
|
+
subscribe: async () => () => {
|
|
181
|
+
closeCalls += 1;
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
await flush();
|
|
185
|
+
expect(res.__state.chunks.filter((chunk) => chunk.startsWith('event: heartbeat'))).toHaveLength(1);
|
|
186
|
+
|
|
187
|
+
registry.closeAll();
|
|
188
|
+
req.emit('close');
|
|
189
|
+
await flush();
|
|
190
|
+
|
|
191
|
+
expect(closeCalls).toBe(1);
|
|
192
|
+
expect(res.__state.endCount).toBe(1);
|
|
193
|
+
expect(registry.size).toBe(0);
|
|
194
|
+
const after = res.__state.chunks.length;
|
|
195
|
+
vi.advanceTimersByTime(60_000);
|
|
196
|
+
expect(res.__state.chunks).toHaveLength(after);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('sends named heartbeats on a healthy connection and never on a dead response', async () => {
|
|
200
|
+
const req = createFakeReq();
|
|
201
|
+
const res = createFakeRes();
|
|
202
|
+
openPiEventStream({
|
|
203
|
+
req,
|
|
204
|
+
res,
|
|
205
|
+
heartbeatMs: 10,
|
|
206
|
+
projectFrame: (value) => value,
|
|
207
|
+
subscribe: async () => () => {},
|
|
208
|
+
});
|
|
209
|
+
await flush();
|
|
210
|
+
|
|
211
|
+
expect(res.__state.chunks[0]).toBe('event: heartbeat\ndata: {}\n\n');
|
|
212
|
+
vi.advanceTimersByTime(30);
|
|
213
|
+
const heartbeats = res.__state.chunks.filter((chunk) => chunk.startsWith('event: heartbeat'));
|
|
214
|
+
expect(heartbeats.length).toBeGreaterThanOrEqual(2);
|
|
215
|
+
|
|
216
|
+
// Response dies: no heartbeat write, no late write, no throw.
|
|
217
|
+
res.destroy();
|
|
218
|
+
const before = res.__state.chunks.length;
|
|
219
|
+
vi.advanceTimersByTime(100);
|
|
220
|
+
expect(res.__state.chunks).toHaveLength(before);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it('skips late daemon events after cleanup without throwing', async () => {
|
|
224
|
+
let push;
|
|
225
|
+
const req = createFakeReq();
|
|
226
|
+
const res = createFakeRes();
|
|
227
|
+
openPiEventStream({
|
|
228
|
+
req,
|
|
229
|
+
res,
|
|
230
|
+
projectFrame: (value) => value,
|
|
231
|
+
subscribe: async ({ onEvent }) => {
|
|
232
|
+
push = onEvent;
|
|
233
|
+
return () => {};
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
await flush();
|
|
237
|
+
push(frame(1));
|
|
238
|
+
expect(writtenData(res)).toEqual(['t1']);
|
|
239
|
+
|
|
240
|
+
req.emit('close');
|
|
241
|
+
push(frame(2));
|
|
242
|
+
expect(writtenData(res)).toEqual(['t1']);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('aborts the provided signal when the client disconnects', async () => {
|
|
246
|
+
let captured;
|
|
247
|
+
const req = createFakeReq();
|
|
248
|
+
const res = createFakeRes();
|
|
249
|
+
openPiEventStream({
|
|
250
|
+
req,
|
|
251
|
+
res,
|
|
252
|
+
projectFrame: (value) => value,
|
|
253
|
+
subscribe: async (handlers) => {
|
|
254
|
+
captured = handlers;
|
|
255
|
+
return () => {};
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
await flush();
|
|
259
|
+
expect(captured.signal.aborted).toBe(false);
|
|
260
|
+
|
|
261
|
+
req.emit('close');
|
|
262
|
+
expect(captured.signal.aborted).toBe(true);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it('ends once on daemon error and stays idempotent when close events follow', async () => {
|
|
266
|
+
let fail;
|
|
267
|
+
let closeCalls = 0;
|
|
268
|
+
const req = createFakeReq();
|
|
269
|
+
const res = createFakeRes();
|
|
270
|
+
openPiEventStream({
|
|
271
|
+
req,
|
|
272
|
+
res,
|
|
273
|
+
heartbeatMs: 5,
|
|
274
|
+
projectFrame: (value) => value,
|
|
275
|
+
subscribe: async ({ onError }) => {
|
|
276
|
+
fail = onError;
|
|
277
|
+
return () => {
|
|
278
|
+
closeCalls += 1;
|
|
279
|
+
};
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
await flush();
|
|
283
|
+
fail();
|
|
284
|
+
req.emit('close');
|
|
285
|
+
await flush();
|
|
286
|
+
|
|
287
|
+
expect(closeCalls).toBe(1);
|
|
288
|
+
expect(res.__state.endCount).toBe(1);
|
|
289
|
+
vi.advanceTimersByTime(60_000);
|
|
290
|
+
expect(res.__state.chunks.filter((chunk) => chunk.startsWith('event: heartbeat'))).toHaveLength(1);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('disconnects a slow client at the byte bound without dropping any buffered event', async () => {
|
|
294
|
+
let push;
|
|
295
|
+
let closeCalls = 0;
|
|
296
|
+
const req = createFakeReq();
|
|
297
|
+
const res = createFakeRes();
|
|
298
|
+
const bound = 1024;
|
|
299
|
+
openPiEventStream({
|
|
300
|
+
req,
|
|
301
|
+
res,
|
|
302
|
+
maxBufferedBytes: bound,
|
|
303
|
+
projectFrame: (value) => value,
|
|
304
|
+
subscribe: async ({ onEvent }) => {
|
|
305
|
+
push = onEvent;
|
|
306
|
+
return () => {
|
|
307
|
+
closeCalls += 1;
|
|
308
|
+
};
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
await flush();
|
|
312
|
+
|
|
313
|
+
// Replay overload: a long synchronous burst.
|
|
314
|
+
for (let sequence = 1; sequence <= 500; sequence++) push(frame(sequence));
|
|
315
|
+
await flush();
|
|
316
|
+
|
|
317
|
+
expect(closeCalls).toBe(1);
|
|
318
|
+
expect(res.__state.endCount).toBe(1);
|
|
319
|
+
// Every event written before the bound survived, in order: the slow client
|
|
320
|
+
// gets a recoverable disconnect, not a dropped event.
|
|
321
|
+
const titles = writtenData(res);
|
|
322
|
+
expect(titles).toEqual(titles.map((_, index) => `t${index + 1}`));
|
|
323
|
+
expect(titles.length).toBeGreaterThan(0);
|
|
324
|
+
expect(titles.length).toBeLessThan(500);
|
|
325
|
+
expect(res.__state.bytes).toBeLessThan(bound * 2);
|
|
326
|
+
// Frames emitted after the disconnect are not written.
|
|
327
|
+
push(frame(501));
|
|
328
|
+
expect(writtenData(res)).toEqual(titles);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it('never writes an oversized frame that would overshoot the byte bound', async () => {
|
|
332
|
+
let push;
|
|
333
|
+
const req = createFakeReq();
|
|
334
|
+
const res = createFakeRes();
|
|
335
|
+
openPiEventStream({
|
|
336
|
+
req,
|
|
337
|
+
res,
|
|
338
|
+
maxBufferedBytes: 100,
|
|
339
|
+
projectFrame: (value) => value,
|
|
340
|
+
subscribe: async ({ onEvent }) => {
|
|
341
|
+
push = onEvent;
|
|
342
|
+
return () => {};
|
|
343
|
+
},
|
|
344
|
+
});
|
|
345
|
+
await flush();
|
|
346
|
+
|
|
347
|
+
// The initial heartbeat (28 bytes) fits; this frame (~400 bytes) would
|
|
348
|
+
// overshoot the 100-byte bound, so it must be dropped BEFORE the write
|
|
349
|
+
// and the stream ended instead of writing one huge overshoot.
|
|
350
|
+
push(frame(1, 'x'.repeat(380)));
|
|
351
|
+
await flush();
|
|
352
|
+
|
|
353
|
+
expect(writtenData(res)).toEqual([]);
|
|
354
|
+
expect(res.__state.chunks).toEqual(['event: heartbeat\ndata: {}\n\n']);
|
|
355
|
+
expect(res.__state.writableEnded).toBe(true);
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
it('destroys a stalled socket after the bounded terminate deadline so shutdown cannot hang', async () => {
|
|
359
|
+
let push;
|
|
360
|
+
let closeCalls = 0;
|
|
361
|
+
const req = createFakeReq();
|
|
362
|
+
const res = createFakeRes();
|
|
363
|
+
openPiEventStream({
|
|
364
|
+
req,
|
|
365
|
+
res,
|
|
366
|
+
maxBufferedBytes: 1024,
|
|
367
|
+
terminateTimeoutMs: 100,
|
|
368
|
+
projectFrame: (value) => value,
|
|
369
|
+
subscribe: async ({ onEvent }) => {
|
|
370
|
+
push = onEvent;
|
|
371
|
+
return () => {
|
|
372
|
+
closeCalls += 1;
|
|
373
|
+
};
|
|
374
|
+
},
|
|
375
|
+
});
|
|
376
|
+
await flush();
|
|
377
|
+
|
|
378
|
+
for (let sequence = 1; sequence <= 100; sequence++) push(frame(sequence));
|
|
379
|
+
await flush();
|
|
380
|
+
|
|
381
|
+
// The bound crossed: res.end() ran, but a stalled client never reads, so
|
|
382
|
+
// end() alone cannot release the socket.
|
|
383
|
+
expect(closeCalls).toBe(1);
|
|
384
|
+
expect(res.__state.endCount).toBe(1);
|
|
385
|
+
expect(res.__state.writableEnded).toBe(true);
|
|
386
|
+
expect(res.__state.destroyed).toBe(false);
|
|
387
|
+
|
|
388
|
+
// The terminate deadline bounds the wait and destroys the socket.
|
|
389
|
+
vi.advanceTimersByTime(99);
|
|
390
|
+
expect(res.__state.destroyed).toBe(false);
|
|
391
|
+
vi.advanceTimersByTime(1);
|
|
392
|
+
expect(res.__state.destroyed).toBe(true);
|
|
393
|
+
expect(closeCalls).toBe(1);
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
it('ends a quiet client whose socket never drains after the bounded drain deadline', async () => {
|
|
397
|
+
let push;
|
|
398
|
+
let closeCalls = 0;
|
|
399
|
+
const req = createFakeReq();
|
|
400
|
+
const res = createFakeRes({ highWaterMark: 64 });
|
|
401
|
+
openPiEventStream({
|
|
402
|
+
req,
|
|
403
|
+
res,
|
|
404
|
+
drainTimeoutMs: 100,
|
|
405
|
+
terminateTimeoutMs: 100,
|
|
406
|
+
projectFrame: (value) => value,
|
|
407
|
+
subscribe: async ({ onEvent }) => {
|
|
408
|
+
push = onEvent;
|
|
409
|
+
return () => {
|
|
410
|
+
closeCalls += 1;
|
|
411
|
+
};
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
await flush();
|
|
415
|
+
|
|
416
|
+
// One frame fills the socket buffer (write returned false) and then the
|
|
417
|
+
// client goes quiet: the byte bound is never crossed, but the connection
|
|
418
|
+
// must still be released by the drain deadline.
|
|
419
|
+
push(frame(1));
|
|
420
|
+
await flush();
|
|
421
|
+
expect(res.__state.writableEnded).toBe(false);
|
|
422
|
+
|
|
423
|
+
vi.advanceTimersByTime(99);
|
|
424
|
+
expect(res.__state.writableEnded).toBe(false);
|
|
425
|
+
vi.advanceTimersByTime(1);
|
|
426
|
+
expect(closeCalls).toBe(1);
|
|
427
|
+
expect(res.__state.endCount).toBe(1);
|
|
428
|
+
// The terminate deadline then releases the stalled socket itself.
|
|
429
|
+
vi.advanceTimersByTime(100);
|
|
430
|
+
expect(res.__state.destroyed).toBe(true);
|
|
431
|
+
// No late frame is written after teardown.
|
|
432
|
+
push(frame(2));
|
|
433
|
+
expect(writtenData(res)).toEqual(['t1']);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it('clears the drain deadline when the socket drains in time and keeps streaming', async () => {
|
|
437
|
+
let push;
|
|
438
|
+
const req = createFakeReq();
|
|
439
|
+
const res = createFakeRes({ highWaterMark: 64 });
|
|
440
|
+
openPiEventStream({
|
|
441
|
+
req,
|
|
442
|
+
res,
|
|
443
|
+
drainTimeoutMs: 100,
|
|
444
|
+
terminateTimeoutMs: 100,
|
|
445
|
+
projectFrame: (value) => value,
|
|
446
|
+
subscribe: async ({ onEvent }) => {
|
|
447
|
+
push = onEvent;
|
|
448
|
+
return () => {};
|
|
449
|
+
},
|
|
450
|
+
});
|
|
451
|
+
await flush();
|
|
452
|
+
|
|
453
|
+
push(frame(1));
|
|
454
|
+
await flush();
|
|
455
|
+
// The socket drains before the deadline: the connection stays open.
|
|
456
|
+
res.emit('drain');
|
|
457
|
+
vi.advanceTimersByTime(200);
|
|
458
|
+
expect(res.__state.writableEnded).toBe(false);
|
|
459
|
+
expect(res.__state.destroyed).toBe(false);
|
|
460
|
+
|
|
461
|
+
// Streaming continues normally after the drain.
|
|
462
|
+
push(frame(2));
|
|
463
|
+
expect(writtenData(res)).toEqual(['t1', 't2']);
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
it('swallows a late response error after cleanup instead of crashing', async () => {
|
|
467
|
+
let push;
|
|
468
|
+
const req = createFakeReq();
|
|
469
|
+
const res = createFakeRes();
|
|
470
|
+
openPiEventStream({
|
|
471
|
+
req,
|
|
472
|
+
res,
|
|
473
|
+
projectFrame: (value) => value,
|
|
474
|
+
subscribe: async ({ onEvent }) => {
|
|
475
|
+
push = onEvent;
|
|
476
|
+
return () => {};
|
|
477
|
+
},
|
|
478
|
+
});
|
|
479
|
+
await flush();
|
|
480
|
+
push(frame(1));
|
|
481
|
+
req.emit('close');
|
|
482
|
+
|
|
483
|
+
// Teardown completed while data was still in flight: a late response
|
|
484
|
+
// error must not surface as an unhandled 'error' event.
|
|
485
|
+
expect(() => {
|
|
486
|
+
res.emit('error', new Error('late socket error'));
|
|
487
|
+
res.emit('error', new Error('second late error'));
|
|
488
|
+
}).not.toThrow();
|
|
489
|
+
expect(writtenData(res)).toEqual(['t1']);
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
it('keeps a healthy client independent of a slow one and preserves order', async () => {
|
|
493
|
+
const senders = [];
|
|
494
|
+
const subscribe = async ({ onEvent }) => {
|
|
495
|
+
senders.push(onEvent);
|
|
496
|
+
return () => {};
|
|
497
|
+
};
|
|
498
|
+
const slowReq = createFakeReq();
|
|
499
|
+
const slowRes = createFakeRes();
|
|
500
|
+
openPiEventStream({
|
|
501
|
+
req: slowReq,
|
|
502
|
+
res: slowRes,
|
|
503
|
+
maxBufferedBytes: 512,
|
|
504
|
+
projectFrame: (value) => value,
|
|
505
|
+
subscribe,
|
|
506
|
+
});
|
|
507
|
+
const healthyReq = createFakeReq();
|
|
508
|
+
const healthyRes = createFakeRes();
|
|
509
|
+
openPiEventStream({
|
|
510
|
+
req: healthyReq,
|
|
511
|
+
res: healthyRes,
|
|
512
|
+
maxBufferedBytes: DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
513
|
+
projectFrame: (value) => value,
|
|
514
|
+
subscribe,
|
|
515
|
+
});
|
|
516
|
+
await flush();
|
|
517
|
+
|
|
518
|
+
for (const send of senders) {
|
|
519
|
+
for (let sequence = 1; sequence <= 50; sequence++) send(frame(sequence));
|
|
520
|
+
}
|
|
521
|
+
await flush();
|
|
522
|
+
|
|
523
|
+
// The slow client was disconnected mid-burst with a preserved prefix.
|
|
524
|
+
expect(slowRes.__state.writableEnded).toBe(true);
|
|
525
|
+
const slowTitles = writtenData(slowRes);
|
|
526
|
+
expect(slowTitles).toEqual(slowTitles.map((_, index) => `t${index + 1}`));
|
|
527
|
+
expect(slowTitles.length).toBeLessThan(50);
|
|
528
|
+
|
|
529
|
+
// The healthy client received the whole burst in order.
|
|
530
|
+
expect(writtenData(healthyRes)).toEqual(Array.from({ length: 50 }, (_, index) => `t${index + 1}`));
|
|
531
|
+
|
|
532
|
+
// Later events still reach only the healthy client.
|
|
533
|
+
for (const send of senders) {
|
|
534
|
+
for (let sequence = 51; sequence <= 60; sequence++) send(frame(sequence));
|
|
535
|
+
}
|
|
536
|
+
await flush();
|
|
537
|
+
expect(writtenData(healthyRes)).toHaveLength(60);
|
|
538
|
+
expect(writtenData(slowRes)).toEqual(slowTitles);
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
it('delivers a full replay overload in order to a healthy client with the default bound', async () => {
|
|
542
|
+
let push;
|
|
543
|
+
const req = createFakeReq();
|
|
544
|
+
const res = createFakeRes();
|
|
545
|
+
openPiEventStream({
|
|
546
|
+
req,
|
|
547
|
+
res,
|
|
548
|
+
projectFrame: (value) => value,
|
|
549
|
+
subscribe: async ({ onEvent }) => {
|
|
550
|
+
push = onEvent;
|
|
551
|
+
return () => {};
|
|
552
|
+
},
|
|
553
|
+
});
|
|
554
|
+
await flush();
|
|
555
|
+
|
|
556
|
+
for (let sequence = 1; sequence <= 2000; sequence++) push(frame(sequence, 'x'.repeat(50)));
|
|
557
|
+
await flush();
|
|
558
|
+
|
|
559
|
+
expect(res.__state.writableEnded).toBe(false);
|
|
560
|
+
expect(writtenData(res)).toEqual(Array.from({ length: 2000 }, (_, index) => `t${index + 1}${'x'.repeat(50)}`));
|
|
561
|
+
});
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
describe('Pi event stream route', () => {
|
|
565
|
+
let server;
|
|
566
|
+
|
|
567
|
+
const listen = (app) => new Promise((resolve, reject) => {
|
|
568
|
+
const created = app.listen(0, '127.0.0.1', () => resolve(created));
|
|
569
|
+
const connections = new Set();
|
|
570
|
+
created.on('connection', (socket) => {
|
|
571
|
+
connections.add(socket);
|
|
572
|
+
socket.once('close', () => connections.delete(socket));
|
|
573
|
+
});
|
|
574
|
+
created.__testConnections = connections;
|
|
575
|
+
created.once('error', reject);
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
const close = async () => {
|
|
579
|
+
if (!server) return;
|
|
580
|
+
// SSE deliberately keeps a response open; destroy test sockets so teardown
|
|
581
|
+
// cannot hang forever.
|
|
582
|
+
for (const socket of server.__testConnections ?? []) socket.destroy();
|
|
583
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
584
|
+
server = undefined;
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
afterEach(close);
|
|
588
|
+
|
|
589
|
+
it('cleans up the subscription when the client disconnects before subscribe resolves', async () => {
|
|
590
|
+
let resolveSubscribe;
|
|
591
|
+
let closeCalls = 0;
|
|
592
|
+
const runtime = {
|
|
593
|
+
subscribe: () => new Promise((resolve) => {
|
|
594
|
+
resolveSubscribe = () => resolve(() => {
|
|
595
|
+
closeCalls += 1;
|
|
596
|
+
});
|
|
597
|
+
}),
|
|
598
|
+
};
|
|
599
|
+
const app = express();
|
|
600
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
|
|
601
|
+
server = await listen(app);
|
|
602
|
+
|
|
603
|
+
const controller = new AbortController();
|
|
604
|
+
// Abort either rejects fetch (before headers) or fails the body read
|
|
605
|
+
// (after headers); normalize the outcome so nothing is left unhandled.
|
|
606
|
+
const clientOutcome = fetch(`http://127.0.0.1:${server.address().port}/api/pi/events`, { signal: controller.signal })
|
|
607
|
+
.then((response) => response.text())
|
|
608
|
+
.catch(() => 'aborted');
|
|
609
|
+
await vi.waitFor(() => expect(resolveSubscribe).toBeDefined());
|
|
610
|
+
const [clientSocket] = server.__testConnections;
|
|
611
|
+
expect(clientSocket).toBeDefined();
|
|
612
|
+
controller.abort();
|
|
613
|
+
// Wait for this request's socket, not all server connections: Node's fetch
|
|
614
|
+
// pool can open an idle replacement socket after aborting the request.
|
|
615
|
+
await vi.waitFor(() => expect(clientSocket.destroyed).toBe(true));
|
|
616
|
+
resolveSubscribe();
|
|
617
|
+
await vi.waitFor(() => expect(closeCalls).toBe(1));
|
|
618
|
+
await clientOutcome;
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
it('enforces the byte bound before writing so no frame overshoots it', async () => {
|
|
622
|
+
const runtime = {
|
|
623
|
+
subscribe: async ({ onEvent }) => {
|
|
624
|
+
for (let sequence = 1; sequence <= 20; sequence++) {
|
|
625
|
+
onEvent({
|
|
626
|
+
protocolVersion: 1,
|
|
627
|
+
kind: 'event',
|
|
628
|
+
event: 'session.updated',
|
|
629
|
+
sequence,
|
|
630
|
+
payload: { sessionId: 's', directory: '/workspace', title: `t${sequence}` },
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
return () => {};
|
|
634
|
+
},
|
|
635
|
+
};
|
|
636
|
+
const app = express();
|
|
637
|
+
registerPiRuntimeRoutes(app, {
|
|
638
|
+
getPiSessionDaemonRuntime: () => runtime,
|
|
639
|
+
eventStreamMaxBufferedBytes: 1,
|
|
640
|
+
});
|
|
641
|
+
server = await listen(app);
|
|
642
|
+
|
|
643
|
+
// Every frame (even the heartbeat) would overshoot the one-byte bound, so
|
|
644
|
+
// the bound is enforced before any write: the response ends with zero
|
|
645
|
+
// bytes written and the client reconnects for replay — no one-frame
|
|
646
|
+
// overshoot, no silently dropped middle frame.
|
|
647
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events`);
|
|
648
|
+
const text = await response.text();
|
|
649
|
+
expect(text).toBe('');
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
/** A raw HTTP client that sends the request and then never reads a byte. */
|
|
653
|
+
const stalledClient = (port) => {
|
|
654
|
+
const client = net.connect(port, '127.0.0.1');
|
|
655
|
+
client.on('connect', () => {
|
|
656
|
+
client.write('GET /events HTTP/1.1\r\nHost: localhost\r\n\r\n');
|
|
657
|
+
client.pause();
|
|
658
|
+
});
|
|
659
|
+
client.on('error', () => {});
|
|
660
|
+
return client;
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
/** Await server.close() with a bounded guard so a regression fails instead of hanging. */
|
|
664
|
+
const closeWithin = (ms = 3_000) => new Promise((resolve) => {
|
|
665
|
+
const guard = setTimeout(() => resolve(false), ms);
|
|
666
|
+
server.close(() => {
|
|
667
|
+
clearTimeout(guard);
|
|
668
|
+
resolve(true);
|
|
669
|
+
});
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
it('releases a stalled reader via the bounded terminate deadline so server shutdown completes', async () => {
|
|
673
|
+
const registry = createPiEventStreamRegistry();
|
|
674
|
+
let resRef;
|
|
675
|
+
const app = express();
|
|
676
|
+
app.get('/events', (req, res) => {
|
|
677
|
+
resRef = res;
|
|
678
|
+
res.writeHead(200, {
|
|
679
|
+
'content-type': 'text/event-stream',
|
|
680
|
+
'cache-control': 'no-cache',
|
|
681
|
+
connection: 'keep-alive',
|
|
682
|
+
});
|
|
683
|
+
res.flushHeaders?.();
|
|
684
|
+
openPiEventStream({
|
|
685
|
+
req,
|
|
686
|
+
res,
|
|
687
|
+
registry,
|
|
688
|
+
heartbeatMs: 15_000,
|
|
689
|
+
maxBufferedBytes: 64 * 1024,
|
|
690
|
+
// The drain shortcut stays out of the way: the byte bound does the
|
|
691
|
+
// ending here, and only the terminate deadline can release the
|
|
692
|
+
// socket afterwards.
|
|
693
|
+
drainTimeoutMs: 60_000,
|
|
694
|
+
terminateTimeoutMs: 150,
|
|
695
|
+
projectFrame: (value) => value,
|
|
696
|
+
subscribe: async ({ onEvent }) => {
|
|
697
|
+
// ~215KB against a never-reading client: crosses the 64KB bound.
|
|
698
|
+
for (let i = 1; i <= 1000; i++) onEvent(frame(i, 'y'.repeat(180)));
|
|
699
|
+
return () => {};
|
|
700
|
+
},
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
server = await listen(app);
|
|
704
|
+
|
|
705
|
+
const client = stalledClient(server.address().port);
|
|
706
|
+
await vi.waitFor(
|
|
707
|
+
() => {
|
|
708
|
+
expect(resRef).toBeDefined();
|
|
709
|
+
expect(resRef.writableEnded).toBe(true);
|
|
710
|
+
},
|
|
711
|
+
{ timeout: 5_000 },
|
|
712
|
+
);
|
|
713
|
+
|
|
714
|
+
// res.end() only queues the FIN behind the unflushable backlog: without
|
|
715
|
+
// the bounded destroy, server.close() hangs forever. With it, shutdown
|
|
716
|
+
// completes promptly and the socket is destroyed.
|
|
717
|
+
expect(await closeWithin()).toBe(true);
|
|
718
|
+
expect(resRef.destroyed).toBe(true);
|
|
719
|
+
expect(registry.size).toBe(0);
|
|
720
|
+
client.destroy();
|
|
721
|
+
});
|
|
722
|
+
|
|
723
|
+
it('releases a stalled reader after shutdown closeAll without crossing the byte bound', async () => {
|
|
724
|
+
const registry = createPiEventStreamRegistry();
|
|
725
|
+
let resRef;
|
|
726
|
+
const app = express();
|
|
727
|
+
app.get('/events', (req, res) => {
|
|
728
|
+
resRef = res;
|
|
729
|
+
res.writeHead(200, {
|
|
730
|
+
'content-type': 'text/event-stream',
|
|
731
|
+
'cache-control': 'no-cache',
|
|
732
|
+
connection: 'keep-alive',
|
|
733
|
+
});
|
|
734
|
+
res.flushHeaders?.();
|
|
735
|
+
openPiEventStream({
|
|
736
|
+
req,
|
|
737
|
+
res,
|
|
738
|
+
registry,
|
|
739
|
+
heartbeatMs: 15_000,
|
|
740
|
+
// The default-sized bound is never crossed; shutdown must release
|
|
741
|
+
// the stalled reader anyway.
|
|
742
|
+
maxBufferedBytes: DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
743
|
+
drainTimeoutMs: 60_000,
|
|
744
|
+
terminateTimeoutMs: 150,
|
|
745
|
+
projectFrame: (value) => value,
|
|
746
|
+
subscribe: async ({ onEvent }) => {
|
|
747
|
+
// Buffer some data behind the stalled socket without ending.
|
|
748
|
+
for (let i = 1; i <= 500; i++) onEvent(frame(i, 'y'.repeat(180)));
|
|
749
|
+
return () => {};
|
|
750
|
+
},
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
server = await listen(app);
|
|
754
|
+
|
|
755
|
+
const client = stalledClient(server.address().port);
|
|
756
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
757
|
+
expect(resRef).toBeDefined();
|
|
758
|
+
expect(resRef.writableEnded).toBe(false);
|
|
759
|
+
|
|
760
|
+
registry.closeAll();
|
|
761
|
+
expect(resRef.writableEnded).toBe(true);
|
|
762
|
+
|
|
763
|
+
expect(await closeWithin()).toBe(true);
|
|
764
|
+
expect(resRef.destroyed).toBe(true);
|
|
765
|
+
client.destroy();
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
it('preserves the unavailable-daemon 503 mapping', async () => {
|
|
769
|
+
const app = express();
|
|
770
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => undefined });
|
|
771
|
+
server = await listen(app);
|
|
772
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events`);
|
|
773
|
+
expect(response.status).toBe(503);
|
|
774
|
+
await expect(response.json()).resolves.toEqual({ error: { code: 'DAEMON_UNAVAILABLE' } });
|
|
775
|
+
});
|
|
776
|
+
});
|