@wherever-dev/client 0.7.0 → 0.8.0

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.
@@ -0,0 +1,482 @@
1
+ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
2
+ import {WhereverClient} from '../src/client.js';
3
+ import {makeWSFactory} from './harness.js';
4
+
5
+ // Bug: on mobile, picking a file backgrounds the page and the socket is often
6
+ // lost within seconds. uploadFileViaWebSocket fired its frame and forgot it:
7
+ // - started while the socket was (re)connecting, send() returned false and the
8
+ // frame was silently dropped, so the promise never settled;
9
+ // - a frame sent on a socket that then died never got its reply, and nothing
10
+ // rejected or retried it.
11
+ // Either way the composer's "uploading" chip spun forever and Send stayed
12
+ // disabled. An upload must survive a reconnect and must always settle.
13
+ //
14
+ // These cover the LEGACY one-frame protocol: every socket here announces no
15
+ // `upload.v1` capability (see chunked-upload.test.ts for the chunked one).
16
+
17
+ // A byte source whose bytes base64-encode back to `b64` (4 base64 chars = 3
18
+ // bytes, so the legacy frame's `data` is exactly `b64`).
19
+ function src(b64: string) {
20
+ const bytes = Uint8Array.from(atob(b64), (ch) => ch.charCodeAt(0));
21
+ return {size: bytes.length, read: async (o: number, l: number) => bytes.slice(o, o + l)};
22
+ }
23
+
24
+ // Let the async byte-source read (and the send after it) run.
25
+ async function flush() {
26
+ for (let i = 0; i < 20; i++) await Promise.resolve();
27
+ }
28
+
29
+ describe('WebSocket upload is independent of the socket it started on', () => {
30
+ let ws: ReturnType<typeof makeWSFactory>;
31
+ let client: WhereverClient;
32
+
33
+ beforeEach(() => {
34
+ vi.useFakeTimers();
35
+ ws = makeWSFactory();
36
+ client = new WhereverClient({
37
+ host: 'localhost',
38
+ port: 1234,
39
+ secure: false,
40
+ WebSocketCtor: ws.ctor,
41
+ });
42
+ client.connect();
43
+ });
44
+
45
+ afterEach(() => {
46
+ client.disconnect(true);
47
+ vi.useRealTimers();
48
+ });
49
+
50
+ function joinSession() {
51
+ client.joinSession('/tmp/project/session.jsonl');
52
+ ws.last().receive({
53
+ type: 'session_created',
54
+ sessionId: 'sid-1',
55
+ sessionFile: '/tmp/project/session.jsonl',
56
+ cwd: '/tmp/project',
57
+ model: 'fake:model',
58
+ });
59
+ ws.last().receive({
60
+ type: 'message_history',
61
+ sessionId: 'sid-1',
62
+ messages: [],
63
+ totalCount: 0,
64
+ offset: 0,
65
+ });
66
+ }
67
+
68
+ function dropAndReconnect() {
69
+ const first = ws.last();
70
+ first.close();
71
+ vi.advanceTimersByTime(5000);
72
+ const second = ws.last();
73
+ expect(second).not.toBe(first);
74
+ second.open();
75
+ connected(second);
76
+ return second;
77
+ }
78
+
79
+ // A server without upload.v1: uploads on this socket use the legacy frame.
80
+ function connected(sock: ReturnType<typeof ws.last>) {
81
+ sock.receive({type: 'connected', clientId: 'c1', serverVersion: 'x'});
82
+ }
83
+
84
+ it('an upload started while the socket is down is sent once reconnected and rejoined', async () => {
85
+ ws.last().open();
86
+ connected(ws.last());
87
+ joinSession();
88
+ ws.last().close(); // dropped; the reconnect is pending
89
+ const p = client.uploadFileViaWebSocket('sid-1', 'a.png', src('AAAA'));
90
+ vi.advanceTimersByTime(5000);
91
+ const next = ws.last();
92
+ // Still CONNECTING: nothing could be sent.
93
+ expect(next.lastSentOfType('file_upload')).toBeUndefined();
94
+
95
+ next.open();
96
+ connected(next);
97
+ next.receive({
98
+ type: 'session_created',
99
+ sessionId: 'sid-1',
100
+ sessionFile: '/tmp/project/session.jsonl',
101
+ cwd: '/tmp/project',
102
+ model: 'fake:model',
103
+ });
104
+ await flush();
105
+ const frame = next.lastSentOfType('file_upload');
106
+ expect(frame).toMatchObject({sessionId: 'sid-1', filename: 'a.png', data: 'AAAA'});
107
+
108
+ next.receive({
109
+ type: 'file_uploaded',
110
+ uploadId: frame.uploadId,
111
+ sessionId: 'sid-1',
112
+ filename: 'a.png',
113
+ savedPath: '/up/1_a.png',
114
+ });
115
+ await expect(p).resolves.toEqual({savedPath: '/up/1_a.png', filename: 'a.png'});
116
+ expect(client.pendingUploadCount()).toBe(0);
117
+ });
118
+
119
+ it('an upload whose socket dies is re-sent only AFTER the rejoin is answered', async () => {
120
+ ws.last().open();
121
+ connected(ws.last());
122
+ joinSession();
123
+ const p = client.uploadFileViaWebSocket('sid-1', 'b.pdf', src('BBBB'));
124
+ await flush();
125
+ const sent = ws.last().lastSentOfType('file_upload');
126
+ expect(sent).toBeTruthy();
127
+
128
+ // The socket drops (app switch / file picker) before the server replied.
129
+ const second = dropAndReconnect();
130
+
131
+ // session_load goes first; the upload is held: a fresh server socket has
132
+ // no write verdict (readOnly) until it answers the rejoin.
133
+ expect(second.lastSentOfType('session_load')).toBeTruthy();
134
+ expect(second.lastSentOfType('file_upload')).toBeUndefined();
135
+
136
+ second.receive({
137
+ type: 'session_created',
138
+ sessionId: 'sid-1',
139
+ sessionFile: '/tmp/project/session.jsonl',
140
+ cwd: '/tmp/project',
141
+ model: 'fake:model',
142
+ });
143
+ const resent = second.lastSentOfType('file_upload');
144
+ expect(resent).toMatchObject({uploadId: sent.uploadId, data: 'BBBB'});
145
+
146
+ second.receive({
147
+ type: 'file_uploaded',
148
+ uploadId: sent.uploadId,
149
+ sessionId: 'sid-1',
150
+ filename: 'b.pdf',
151
+ savedPath: '/up/2_b.pdf',
152
+ });
153
+ await expect(p).resolves.toMatchObject({savedPath: '/up/2_b.pdf'});
154
+ });
155
+
156
+ it('an upload started mid-rejoin waits for session_created', async () => {
157
+ ws.last().open();
158
+ connected(ws.last());
159
+ joinSession();
160
+ const second = dropAndReconnect();
161
+ void client.uploadFileViaWebSocket('sid-1', 'f.png', src('FFFF')).catch(() => {});
162
+ await flush();
163
+ expect(second.lastSentOfType('file_upload')).toBeUndefined();
164
+ second.receive({
165
+ type: 'session_created',
166
+ sessionId: 'sid-1',
167
+ sessionFile: '/tmp/project/session.jsonl',
168
+ cwd: '/tmp/project',
169
+ model: 'fake:model',
170
+ });
171
+ await flush();
172
+ expect(second.lastSentOfType('file_upload')).toMatchObject({data: 'FFFF'});
173
+ });
174
+
175
+ it('a reconnect with no session to rejoin fails parked uploads', async () => {
176
+ ws.last().open();
177
+ connected(ws.last());
178
+ const p = client.uploadFileViaWebSocket('sid-1', 'g.png', src('GGGG'));
179
+ const settled = expect(p).rejects.toThrow(/session was closed/);
180
+ dropAndReconnect();
181
+ await settled;
182
+ });
183
+
184
+ it('a sent upload is not timed out while in transmission', async () => {
185
+ ws.last().open();
186
+ connected(ws.last());
187
+ joinSession();
188
+ const p = client.uploadFileViaWebSocket('sid-1', 'h.mp4', src('HHHH'));
189
+ await flush();
190
+ let settled = false;
191
+ p.then(
192
+ () => (settled = true),
193
+ () => (settled = true),
194
+ );
195
+ // A healthy (if slow) socket keeps receiving frames, so the liveness
196
+ // watchdog leaves it alone; only the upload timeout is under test.
197
+ for (let t = 0; t < 30 * 60_000; t += 20_000) {
198
+ ws.last().receive({type: 'pong', timestamp: t});
199
+ vi.advanceTimersByTime(20_000);
200
+ }
201
+ return Promise.resolve().then(() => {
202
+ expect(settled).toBe(false);
203
+ expect(client.pendingUploadCount()).toBe(1);
204
+ });
205
+ });
206
+
207
+ it('aborting drops a parked upload so it is never sent', async () => {
208
+ const controller = new AbortController();
209
+ const p = client.uploadFileViaWebSocket('sid-1', 'i.png', src('IIII'), {
210
+ signal: controller.signal,
211
+ });
212
+ const settled = expect(p).rejects.toThrow(/cancelled/);
213
+ controller.abort();
214
+ await settled;
215
+ expect(client.pendingUploadCount()).toBe(0);
216
+ ws.last().open();
217
+ connected(ws.last());
218
+ expect(ws.last().lastSentOfType('file_upload')).toBeUndefined();
219
+ });
220
+
221
+ it('a server error rejects the upload', async () => {
222
+ ws.last().open();
223
+ connected(ws.last());
224
+ const p = client.uploadFileViaWebSocket('sid-1', 'c.txt', src('CCCC'));
225
+ await flush();
226
+ const sent = ws.last().lastSentOfType('file_upload');
227
+ ws.last().receive({
228
+ type: 'file_upload_error',
229
+ uploadId: sent.uploadId,
230
+ sessionId: 'sid-1',
231
+ error: 'nope',
232
+ });
233
+ await expect(p).rejects.toThrow('nope');
234
+ expect(client.pendingUploadCount()).toBe(0);
235
+ });
236
+
237
+ it('an upload that never gets a connection eventually rejects (never hangs)', async () => {
238
+ const p = client.uploadFileViaWebSocket('sid-1', 'd.png', src('DDDD'));
239
+ const settled = expect(p).rejects.toThrow(/timed out/);
240
+ vi.advanceTimersByTime(10 * 60_000 + 1);
241
+ await settled;
242
+ expect(client.pendingUploadCount()).toBe(0);
243
+ });
244
+
245
+ it('an explicit full disconnect rejects pending uploads', async () => {
246
+ const p = client.uploadFileViaWebSocket('sid-1', 'e.png', src('EEEE'));
247
+ const settled = expect(p).rejects.toThrow(/Disconnected/);
248
+ client.disconnect(true);
249
+ await settled;
250
+ expect(client.pendingUploadCount()).toBe(0);
251
+ });
252
+
253
+ it('a failed rejoin (session_error) fails held uploads and stops holding', async () => {
254
+ ws.last().open();
255
+ connected(ws.last());
256
+ joinSession();
257
+ const p = client.uploadFileViaWebSocket('sid-1', 'j.png', src('JJJJ'));
258
+ await flush();
259
+ const second = dropAndReconnect();
260
+ const settled = expect(p).rejects.toThrow(/Could not rejoin/);
261
+ second.receive({type: 'session_error', error: 'Session not found'});
262
+ await settled;
263
+ expect(client.pendingUploadCount()).toBe(0);
264
+ // No longer holding: a new upload goes straight out.
265
+ void client.uploadFileViaWebSocket('sid-1', 'k.png', src('KKKK')).catch(() => {});
266
+ await flush();
267
+ expect(second.lastSentOfType('file_upload')).toMatchObject({data: 'KKKK'});
268
+ });
269
+
270
+ it('a rejoin that times out (load watchdog) fails held uploads', async () => {
271
+ ws.last().open();
272
+ connected(ws.last());
273
+ joinSession();
274
+ const p = client.uploadFileViaWebSocket('sid-1', 'l.png', src('LLLL'));
275
+ await flush();
276
+ dropAndReconnect();
277
+ const settled = expect(p).rejects.toThrow(/Could not rejoin/);
278
+ vi.advanceTimersByTime(13_000); // past LOAD_WATCHDOG_MS
279
+ await settled;
280
+ });
281
+
282
+ it('switching session mid-hold fails the parked upload instead of releasing it to the new session', async () => {
283
+ ws.last().open();
284
+ connected(ws.last());
285
+ joinSession();
286
+ const p = client.uploadFileViaWebSocket('sid-1', 'm.png', src('MMMM'));
287
+ await flush();
288
+ const second = dropAndReconnect();
289
+ const settled = expect(p).rejects.toThrow(/session changed/);
290
+ client.switchSession('/tmp/other/session.jsonl');
291
+ await settled;
292
+ second.receive({
293
+ type: 'session_created',
294
+ sessionId: 'sid-2',
295
+ sessionFile: '/tmp/other/session.jsonl',
296
+ cwd: '/tmp/other',
297
+ model: 'fake:model',
298
+ });
299
+ expect(second.lastSentOfType('file_upload')).toBeUndefined();
300
+ });
301
+
302
+ it('a rejoin answered for a DIFFERENT session releases only matching uploads', async () => {
303
+ ws.last().open();
304
+ connected(ws.last());
305
+ joinSession();
306
+ const p = client.uploadFileViaWebSocket('sid-1', 'n.png', src('NNNN'));
307
+ await flush();
308
+ const second = dropAndReconnect();
309
+ const settled = expect(p).rejects.toThrow(/session changed/);
310
+ second.receive({
311
+ type: 'session_created',
312
+ sessionId: 'sid-1-other-id',
313
+ sessionFile: '/tmp/project/session.jsonl',
314
+ cwd: '/tmp/project',
315
+ model: 'fake:model',
316
+ });
317
+ await settled;
318
+ expect(second.lastSentOfType('file_upload')).toBeUndefined();
319
+ });
320
+
321
+ it('suspend with an upload on the wire re-arms its timer and re-sends after resume', async () => {
322
+ ws.last().open();
323
+ connected(ws.last());
324
+ joinSession();
325
+ const p = client.uploadFileViaWebSocket('sid-1', 'o.png', src('OOOO'));
326
+ await flush();
327
+ const first = ws.last();
328
+ const sent = first.lastSentOfType('file_upload');
329
+ client.suspend();
330
+ client.resume();
331
+ const second = ws.last();
332
+ expect(second).not.toBe(first);
333
+ second.open();
334
+ connected(second);
335
+ second.receive({
336
+ type: 'session_created',
337
+ sessionId: 'sid-1',
338
+ sessionFile: '/tmp/project/session.jsonl',
339
+ cwd: '/tmp/project',
340
+ model: 'fake:model',
341
+ });
342
+ const resent = second.lastSentOfType('file_upload');
343
+ expect(resent).toMatchObject({uploadId: sent.uploadId});
344
+ second.receive({
345
+ type: 'file_uploaded',
346
+ uploadId: sent.uploadId,
347
+ sessionId: 'sid-1',
348
+ filename: 'o.png',
349
+ savedPath: '/up/o.png',
350
+ });
351
+ await expect(p).resolves.toMatchObject({savedPath: '/up/o.png'});
352
+ });
353
+
354
+ it('suspend while an upload is on the wire, never resumed: it eventually times out', async () => {
355
+ ws.last().open();
356
+ connected(ws.last());
357
+ joinSession();
358
+ const p = client.uploadFileViaWebSocket('sid-1', 'q.png', src('QQQQ'));
359
+ await flush();
360
+ const settled = expect(p).rejects.toThrow(/timed out/);
361
+ client.suspend();
362
+ vi.advanceTimersByTime(10 * 60_000 + 1);
363
+ await settled;
364
+ });
365
+
366
+ it('the waiting deadline is NOT restarted by repeated failed reconnect attempts', async () => {
367
+ ws.last().open();
368
+ connected(ws.last());
369
+ joinSession();
370
+ ws.last().close(); // server goes away
371
+ const p = client.uploadFileViaWebSocket('sid-1', 'r.png', src('RRRR'));
372
+ const settled = expect(p).rejects.toThrow(/timed out/);
373
+ // Every reconnect attempt opens a socket that immediately fails.
374
+ for (let t = 0; t < 11 * 60_000; t += 5_000) {
375
+ vi.advanceTimersByTime(5_000);
376
+ const sock = ws.last();
377
+ if (sock.readyState === 0) sock.close();
378
+ }
379
+ await settled;
380
+ });
381
+
382
+ it('an upload that loses its socket on every send gives up after MAX_UPLOAD_SENDS', async () => {
383
+ ws.last().open();
384
+ connected(ws.last());
385
+ joinSession();
386
+ const p = client.uploadFileViaWebSocket('sid-1', 's.png', src('SSSS'));
387
+ await flush();
388
+ const settled = expect(p).rejects.toThrow(/dropped during the transfer/);
389
+ for (let i = 0; i < 3; i++) {
390
+ const sock = dropAndReconnect();
391
+ sock.receive({
392
+ type: 'session_created',
393
+ sessionId: 'sid-1',
394
+ sessionFile: '/tmp/project/session.jsonl',
395
+ cwd: '/tmp/project',
396
+ model: 'fake:model',
397
+ });
398
+ }
399
+ await settled;
400
+ expect(client.pendingUploadCount()).toBe(0);
401
+ });
402
+
403
+ it('refuses a file too large for the server frame limit before reading it', async () => {
404
+ ws.last().open();
405
+ connected(ws.last());
406
+ let reads = 0;
407
+ const huge = {
408
+ size: 72 * 1024 * 1024 + 1,
409
+ read: async () => {
410
+ reads++;
411
+ return new Uint8Array(0);
412
+ },
413
+ };
414
+ await expect(client.uploadFileViaWebSocket('sid-1', 'big.mp4', huge)).rejects.toThrow(
415
+ /too large/,
416
+ );
417
+ expect(reads).toBe(0);
418
+ expect(ws.last().lastSentOfType('file_upload')).toBeUndefined();
419
+ });
420
+
421
+ it('the base64 size backstop refuses a source that yields more bytes than its size', async () => {
422
+ ws.last().open();
423
+ connected(ws.last());
424
+ // Claims 3 bytes, delivers enough for more than 96 MiB of base64.
425
+ const liar = {
426
+ size: 3,
427
+ read: async () => new Uint8Array(72 * 1024 * 1024 + 3),
428
+ };
429
+ await expect(client.uploadFileViaWebSocket('sid-1', 'liar.bin', liar)).rejects.toThrow(
430
+ /too large/,
431
+ );
432
+ expect(ws.last().lastSentOfType('file_upload')).toBeUndefined();
433
+ });
434
+
435
+ it('a session_error tagged with a session id does not fail held uploads', async () => {
436
+ ws.last().open();
437
+ connected(ws.last());
438
+ joinSession();
439
+ void client.uploadFileViaWebSocket('sid-1', 't.png', src('TTTT')).catch(() => {});
440
+ await flush();
441
+ const second = dropAndReconnect();
442
+ second.receive({type: 'session_error', sessionId: 'some-other', error: 'fork failed'});
443
+ expect(client.pendingUploadCount()).toBe(1);
444
+ second.receive({
445
+ type: 'session_created',
446
+ sessionId: 'sid-1',
447
+ sessionFile: '/tmp/project/session.jsonl',
448
+ cwd: '/tmp/project',
449
+ model: 'fake:model',
450
+ });
451
+ expect(second.lastSentOfType('file_upload')).toMatchObject({data: 'TTTT'});
452
+ });
453
+
454
+ it('an upload lost twice and answered on the third send resolves (cap boundary)', async () => {
455
+ ws.last().open();
456
+ connected(ws.last());
457
+ joinSession();
458
+ const p = client.uploadFileViaWebSocket('sid-1', 'u.png', src('UUUU'));
459
+ await flush();
460
+ let sock = ws.last();
461
+ for (let i = 0; i < 2; i++) {
462
+ sock = dropAndReconnect();
463
+ sock.receive({
464
+ type: 'session_created',
465
+ sessionId: 'sid-1',
466
+ sessionFile: '/tmp/project/session.jsonl',
467
+ cwd: '/tmp/project',
468
+ model: 'fake:model',
469
+ });
470
+ }
471
+ const sent = sock.lastSentOfType('file_upload');
472
+ expect(sent).toBeTruthy();
473
+ sock.receive({
474
+ type: 'file_uploaded',
475
+ uploadId: sent.uploadId,
476
+ sessionId: 'sid-1',
477
+ filename: 'u.png',
478
+ savedPath: '/up/u.png',
479
+ });
480
+ await expect(p).resolves.toMatchObject({savedPath: '/up/u.png'});
481
+ });
482
+ });