File size: 21,087 Bytes
a080db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/**

 * @fileoverview End-to-end reconnect test for `Runtime` transcript delivery.

 *

 * Reproduces the "captions freeze after a hostile network drop" investigation

 * at the SDK seam: a consumer registers `onTranscript` ONCE (as the island

 * runtime's `ensureCloudResultsWired` does), the socket then drops, several

 * reconnect attempts FAIL, and finally one succeeds. The test asserts that the

 * originally-registered `onTranscript` STILL fires on the recovered session —

 * i.e. the handler is not silently dropped when the socket churns — and that the

 * recovery `connection.init` carried the live subscription set (so the cloud

 * seeds the new session non-empty and actually transcribes).

 *

 * This guards the client contract end-to-end. The actual on-device wedge was

 * server-side (a dead Soniox provider never recreated on a same-pod reconnect —

 * see runtime/.../providers/soniox.ts self-heal), but the SDK's handler survival

 * + init-carries-subscriptions is the load-bearing client invariant and must not

 * regress.

 */
import { describe, test, expect } from "bun:test";
import nacl from "tweetnacl";

import { Runtime } from "./runtime";
import { Connection, type ConnectionDeps } from "./connection";
import { RuntimeEmitter } from "./emitter";
import { Subscriptions } from "./subscriptions";
import { Camera } from "./camera";
import { Maps } from "./maps";
import { Tts } from "./tts";
import { UdpAudio } from "./audio-udp";
import type { WebSocketLike, UdpSocketLike } from "../../transports";
import type { HttpClient } from "../../http";
import { noopLogger } from "../../logger";
import { systemTimers, type CloudClientTimers } from "../../timers";
import {
  PROTOCOL_MAJOR,
  UDP_LIVENESS_PROBE_PREFIX,
  type ConnectionInit,
  type ConnectionAck,
  type AudioSubscription,
} from "@mentra/cloud-protocol";

/** A scriptable WebSocket the test drives by hand (peer = the test). */
class FakeSocket implements WebSocketLike {
  sent: string[] = [];
  sentBinary: Uint8Array[] = [];
  openCb: (() => void) | null = null;
  messageCb: ((data: string) => void) | null = null;
  closeCb: ((info: { code: number; reason: string }) => void) | null = null;
  errorCb: ((err: unknown) => void) | null = null;

  send(data: string): void {
    this.sent.push(data);
  }
  sendBinary(data: Uint8Array): void {
    this.sentBinary.push(data);
  }
  close(): void {}
  onOpen(cb: () => void): void {
    this.openCb = cb;
  }
  onMessage(cb: (data: string) => void): void {
    this.messageCb = cb;
  }
  onClose(cb: (info: { code: number; reason: string }) => void): void {
    this.closeCb = cb;
  }
  onError(cb: (err: unknown) => void): void {
    this.errorCb = cb;
  }

  /** Drive a full successful handshake: open, receive init, send ack back. */
  handshake(ack: ConnectionAck): void {
    this.openCb?.();
    this.messageCb?.(
      JSON.stringify({
        v: PROTOCOL_MAJOR,
        type: "connection.ack",
        timestamp: Date.now(),
        payload: ack,
      }),
    );
  }

  /** Push a (schema-valid) transcript frame down to the client. */
  pushTranscript(text: string, language = "en"): void {
    this.messageCb?.(
      JSON.stringify({
        v: PROTOCOL_MAJOR,
        type: "stream.transcript",
        timestamp: Date.now(),
        payload: {
          userId: "user-1",
          subscription: { kind: "transcription", language: { mode: "auto" } },
          text,
          isFinal: true,
          startMs: 0,
          endMs: 1000,
          resolvedLanguage: language,
          languageDetected: false,
          tokens: [],
          provider: "test",
          timestamp: Date.now(),
        },
      }),
    );
  }

  /** The decoded `connection.init` this socket received (the last init sent). */
  readInit(): ConnectionInit {
    const raw = this.sent.find((s) => s.includes("connection.init"));
    if (!raw) throw new Error("no connection.init sent on this socket");
    return JSON.parse(raw).payload as ConnectionInit;
  }
}

const ACK: ConnectionAck = { sessionId: "sess-1", negotiatedVersion: "2.0.0" };
const ACK_WITH_AUDIO: ConnectionAck = {
  sessionId: "sess-udp",
  negotiatedVersion: "2.0.0",
  audio: {
    sessionTag: 42,
    udp: { host: "127.0.0.1", port: 8000 },
    encryption: {
      algorithm: "xsalsa20-poly1305",
      key: Buffer.alloc(32).toString("base64"),
    },
  },
};

function readProbeId(packet: Uint8Array): string {
  const key = new Uint8Array(Buffer.from(ACK_WITH_AUDIO.audio!.encryption.key, "base64"));
  const plaintext = nacl.secretbox.open(packet.subarray(30), packet.subarray(6, 30), key);
  expect(plaintext).not.toBeNull();
  const probe = new TextDecoder().decode(plaintext!);
  expect(probe.startsWith(UDP_LIVENESS_PROBE_PREFIX)).toBe(true);
  return probe.slice(UDP_LIVENESS_PROBE_PREFIX.length);
}

function acknowledgeUdpProbe(socket: FakeSocket, probeId: string): void {
  socket.messageCb?.(JSON.stringify({
    v: PROTOCOL_MAJOR,
    type: "audio.udp_liveness_ack",
    timestamp: Date.now(),
    payload: {
      sessionId: ACK_WITH_AUDIO.sessionId,
      sessionTag: ACK_WITH_AUDIO.audio?.sessionTag,
      probeId,
      receivedAt: Date.now(),
    },
  }));
}

const FAST_RECONNECT = { baseMs: 3, maxMs: 10, jitter: false };

function wait(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

/** Poll until `cond()` is true or `timeoutMs` elapses (robust to backoff jitter). */
async function waitUntil(cond: () => boolean, timeoutMs = 500): Promise<void> {
  const deadline = Date.now() + timeoutMs;
  while (!cond() && Date.now() < deadline) {
    await wait(2);
  }
}

/** A no-op HttpClient — subscription writes resolve without a real server. */
function fakeHttp(): HttpClient {
  return {
    get: async () => undefined as never,
    head: async () => new Response(null, { status: 200, headers: { "content-type": "audio/mpeg" } }),
    post: async () => undefined as never,
    postForm: async () => undefined as never,
    put: async () => undefined as never,
    delete: async () => undefined as never,
    url: (path: string) => `https://runtime.test${path}`,
  };
}

function fakeTts(): Tts {
  return new Tts({ http: fakeHttp() });
}

function fakeUdp(): UdpSocketLike {
  return {
    send: () => {},
    onMessage: () => {},
    close: () => {},
  };
}

function recordingUdp(sent: Uint8Array[]): UdpSocketLike {
  return {
    send: (bytes) => {
      sent.push(bytes);
    },
    onMessage: () => {},
    close: () => {},
  };
}

describe("Runtime transcript delivery survives a multi-attempt reconnect", () => {
  test("initial and reconnected sessions use WS until their own UDP probe is acknowledged", async () => {
    const socket = new FakeSocket();
    const udpSent: Uint8Array[] = [];
    let created = 0;
    const ws = (_url: string): WebSocketLike => {
      created += 1;
      return socket;
    };

    const emitter = new RuntimeEmitter();
    const subscriptions = new Subscriptions({ http: fakeHttp() });
    const connection = new Connection({
      ws,
      url: "wss://example.test/ws",
      getToken: async () => "tok",
      initPayload: () => ({
        protocolVersion: "2.0.0",
        audio: {
          codec: "lc3",
          sampleRate: 16000,
          initialSubscriptions: subscriptions.currentSet(),
        },
      }),
      reconnect: FAST_RECONNECT,
      logger: noopLogger,
    });
    const runtime = new Runtime({
      connection,
      emitter,
      subscriptions,
      camera: new Camera({ http: fakeHttp() }),
      maps: new Maps({ http: fakeHttp() }),
      tts: fakeTts(),
      audio: new UdpAudio({ udp: () => recordingUdp(udpSent) }),
      logger: noopLogger,
      forceRefreshToken: async () => "tok",
    });

    const statuses: Array<ReturnType<typeof runtime.getStatus>> = [];
    runtime.onStatusChanged((status) => {
      statuses.push(status);
    });

    expect(runtime.getStatus()).toEqual({ status: "disconnected", audioTransport: "none" });

    const connectedPromise = runtime.connect();
    await waitUntil(() => created === 1);
    expect(runtime.getStatus()).toEqual({ status: "connecting", audioTransport: "none" });

    socket.handshake(ACK_WITH_AUDIO);
    await connectedPromise;
    expect(runtime.getStatus()).toEqual({ status: "connected", audioTransport: "ws" });
    const firstProbeId = readProbeId(udpSent.at(-1)!);
    acknowledgeUdpProbe(socket, firstProbeId);
    expect(runtime.getStatus().audioTransport).toBe("udp");

    socket.closeCb?.({ code: 1006, reason: "network lost" });
    await waitUntil(() => runtime.getStatus().status === "reconnecting");
    expect(runtime.getStatus()).toEqual({ status: "reconnecting", audioTransport: "none" });
    await waitUntil(() => created === 2);
    socket.handshake(ACK_WITH_AUDIO);
    await waitUntil(() => runtime.getStatus().status === "connected");
    expect(runtime.getStatus().audioTransport).toBe("ws");
    acknowledgeUdpProbe(socket, firstProbeId);
    expect(runtime.getStatus().audioTransport).toBe("ws");
    runtime.sendAudioFrame(new Uint8Array([1, 2, 3]));
    expect(socket.sentBinary).toHaveLength(1);
    acknowledgeUdpProbe(socket, readProbeId(udpSent.at(-1)!));
    expect(runtime.getStatus().audioTransport).toBe("udp");

    runtime.close();
    expect(runtime.getStatus()).toEqual({ status: "disconnected", audioTransport: "none" });
    expect(statuses).toContainEqual({ status: "connected", audioTransport: "ws" });
    expect(statuses).toContainEqual({ status: "reconnecting", audioTransport: "none" });
  });

  test("refreshes a dead UDP route and requires an ack from the replacement before leaving WS", async () => {
    const socket = new FakeSocket();
    let created = 0;
    const ws = (_url: string): WebSocketLike => {
      created += 1;
      return socket;
    };
    const udpSent: Uint8Array[] = [];
    const acknowledge = (probeId: string): void => acknowledgeUdpProbe(socket, probeId);
    const udpSockets: { closed: boolean }[] = [];
    const scheduledIntervals: number[] = [];
    const timers: CloudClientTimers = {
      ...systemTimers,
      setInterval(callback, intervalMs) {
        scheduledIntervals.push(intervalMs);
        return systemTimers.setInterval(callback, intervalMs);
      },
    };

    const emitter = new RuntimeEmitter();
    const subscriptions = new Subscriptions({ http: fakeHttp() });
    const connection = new Connection({
      ws,
      url: "wss://example.test/ws",
      getToken: async () => "tok",
      initPayload: () => ({
        protocolVersion: "2.0.0",
        audio: {
          codec: "lc3",
          sampleRate: 16000,
          initialSubscriptions: subscriptions.currentSet(),
        },
      }),
      reconnect: FAST_RECONNECT,
      logger: noopLogger,
    });
    const runtime = new Runtime({
      connection,
      emitter,
      subscriptions,
      camera: new Camera({ http: fakeHttp() }),
      maps: new Maps({ http: fakeHttp() }),
      tts: fakeTts(),
      audio: new UdpAudio({
        udp: () => {
          const state = { closed: false };
          udpSockets.push(state);
          return {
            ...recordingUdp(udpSent),
            close: () => { state.closed = true; },
          };
        },
      }),
      timers,
      logger: noopLogger,
      forceRefreshToken: async () => "tok",
    });

    const connectedPromise = runtime.connect();
    await waitUntil(() => created === 1);
    socket.handshake(ACK_WITH_AUDIO);
    await connectedPromise;

    // A failed initial DNS/connect/send produces no UDP ack. Audio must use WS
    // immediately, including before the first liveness timeout replaces it.
    expect(runtime.getStatus()).toEqual({ status: "connected", audioTransport: "ws" });
    const probesBeforeAudio = udpSent.length;
    runtime.sendAudioFrame(new Uint8Array([10, 11, 12]));
    expect(socket.sentBinary.length).toBe(1);
    expect(udpSent.length).toBe(probesBeforeAudio);
    expect(scheduledIntervals).toEqual([1_000]);
    expect(udpSockets).toEqual([{ closed: false }]);
    await waitUntil(() => udpSent.length >= 3, 2_500);
    const oldProbeId = readProbeId(udpSent.at(-1)!);
    expect(runtime.getStatus().audioTransport).toBe("ws");
    await waitUntil(() => udpSockets.length === 2, 2_000);
    expect(runtime.getStatus()).toEqual({ status: "connected", audioTransport: "ws" });

    expect(udpSockets).toEqual([{ closed: true }, { closed: false }]);
    const countAfterTimeout = udpSent.length;
    // The replacement gets another complete liveness window, not a reset on
    // each one-second probe tick. Audio continues on WS until UDP is proven.
    await waitUntil(() => udpSent.length > countAfterTimeout, 1_500);
    expect(udpSockets).toHaveLength(2);
    runtime.sendAudioFrame(new Uint8Array([1, 2, 3]));
    expect(socket.sentBinary.length).toBe(2);

    // Same-session acks from the closed socket (or unknown probes) cannot move
    // audio away from working WS while the replacement may still be failing.
    acknowledge(oldProbeId);
    acknowledge("unknown-probe");
    expect(runtime.getStatus().audioTransport).toBe("ws");
    runtime.sendAudioFrame(new Uint8Array([7, 8, 9]));
    expect(socket.sentBinary.length).toBe(3);
    acknowledge(readProbeId(udpSent.at(-1)!));

    await waitUntil(() => runtime.getStatus().audioTransport === "udp");
    const wsFramesBeforeUdpSend = socket.sentBinary.length;
    const udpFramesBeforeRealAudio = udpSent.length;
    runtime.sendAudioFrame(new Uint8Array([4, 5, 6]));

    expect(runtime.getStatus()).toEqual({ status: "connected", audioTransport: "udp" });
    expect(socket.sentBinary.length).toBe(wsFramesBeforeUdpSend);
    expect(udpSent.length).toBeGreaterThan(udpFramesBeforeRealAudio);
    expect(udpSockets).toHaveLength(2);
    runtime.close();
    expect(udpSockets.every((entry) => entry.closed)).toBe(true);
  });

  test("connected event fires once on a normal initial open", async () => {
    const socket = new FakeSocket();
    let created = 0;
    const ws = (_url: string): WebSocketLike => {
      created += 1;
      return socket;
    };

    const emitter = new RuntimeEmitter();
    const subscriptions = new Subscriptions({ http: fakeHttp() });
    const connection = new Connection({
      ws,
      url: "wss://example.test/ws",
      getToken: async () => "tok",
      initPayload: () => ({
        protocolVersion: "2.0.0",
        audio: {
          codec: "lc3",
          sampleRate: 16000,
          initialSubscriptions: subscriptions.currentSet(),
        },
      }),
      reconnect: FAST_RECONNECT,
      logger: noopLogger,
    });
    const runtime = new Runtime({
      connection,
      emitter,
      subscriptions,
      camera: new Camera({ http: fakeHttp() }),
      maps: new Maps({ http: fakeHttp() }),
      tts: fakeTts(),
      audio: new UdpAudio({ udp: fakeUdp }),
      logger: noopLogger,
      forceRefreshToken: async () => "tok",
    });

    let connected = 0;
    runtime.onConnected(() => {
      connected += 1;
    });

    const connectedPromise = runtime.connect();
    await waitUntil(() => created === 1);
    socket.handshake(ACK);
    await connectedPromise;

    expect(connected).toBe(1);
    runtime.close();
  });

  test("connected event fires when the first successful open is a retry after initial failure", async () => {
    const retrySocket = new FakeSocket();
    let created = 0;
    const ws = (_url: string): WebSocketLike => {
      created += 1;
      return retrySocket;
    };

    let tokenCalls = 0;
    const emitter = new RuntimeEmitter();
    const subscriptions = new Subscriptions({ http: fakeHttp() });
    const connection = new Connection({
      ws,
      url: "wss://example.test/ws",
      getToken: async () => {
        tokenCalls += 1;
        if (tokenCalls === 1) {
          throw new Error("cloud unavailable during initial app boot");
        }
        return "tok";
      },
      initPayload: () => ({
        protocolVersion: "2.0.0",
        audio: {
          codec: "lc3",
          sampleRate: 16000,
          initialSubscriptions: subscriptions.currentSet(),
        },
      }),
      reconnect: FAST_RECONNECT,
      logger: noopLogger,
    });
    const runtime = new Runtime({
      connection,
      emitter,
      subscriptions,
      camera: new Camera({ http: fakeHttp() }),
      maps: new Maps({ http: fakeHttp() }),
      tts: fakeTts(),
      audio: new UdpAudio({ udp: fakeUdp }),
      logger: noopLogger,
      forceRefreshToken: async () => "tok",
    });

    let connected = 0;
    runtime.onConnected(() => {
      connected += 1;
    });

    await runtime.connect().catch(() => undefined);
    expect(created).toBe(0);
    expect(connected).toBe(0);

    await waitUntil(() => created >= 1);
    retrySocket.handshake(ACK);
    await waitUntil(() => connected === 1);

    expect(connected).toBe(1);
    runtime.close();
  });

  test("onTranscript registered once still fires after drop → N failed retries → reconnect", async () => {
    // Socket #1 = initial session. #2, #3 = failed reconnect attempts. #4 = the
    // eventual successful reconnect.
    const sockets = [new FakeSocket(), new FakeSocket(), new FakeSocket(), new FakeSocket()];
    let created = 0;
    const ws = (_url: string): WebSocketLike => {
      const s = sockets[created] ?? new FakeSocket();
      created += 1;
      return s;
    };

    const emitter = new RuntimeEmitter();
    const subscriptions = new Subscriptions({ http: fakeHttp() });
    const connDeps: ConnectionDeps = {
      ws,
      url: "wss://example.test/ws",
      getToken: async () => "tok",
      initPayload: () => ({
        protocolVersion: "2.0.0",
        audio: {
          codec: "lc3",
          sampleRate: 16000,
          initialSubscriptions: subscriptions.currentSet(),
        },
      }),
      reconnect: FAST_RECONNECT,
      logger: noopLogger,
    };
    const connection = new Connection(connDeps);
    const runtime = new Runtime({
      connection,
      emitter,
      subscriptions,
      camera: new Camera({ http: fakeHttp() }),
      maps: new Maps({ http: fakeHttp() }),
      tts: fakeTts(),
      audio: new UdpAudio({ udp: fakeUdp }),
      logger: noopLogger,
      forceRefreshToken: async () => "tok",
    });

    // Register the transcript consumer ONCE, the way the island runtime does.
    const received: string[] = [];
    runtime.onTranscript((d) => received.push(d.text));

    // Connect the initial session.
    const connectPromise = runtime.connect();
    await wait(5);
    sockets[0]!.handshake(ACK);
    await connectPromise;

    // Apply a live subscription set (so the reconnect init carries it).
    const subs: AudioSubscription[] = [{ kind: "transcription", language: { mode: "auto" } }];
    await runtime.setSubscriptions(subs);

    // Transcripts flow on the original session.
    sockets[0]!.pushTranscript("before drop");
    expect(received).toEqual(["before drop"]);

    // HOSTILE DROP: the socket closes; the reconnect loop kicks in.
    sockets[0]!.closeCb?.({ code: 1006, reason: "network lost" });

    // Two reconnect attempts FAIL (each opens then immediately closes without an
    // ack), simulating the cloud being briefly unreachable. Poll for each
    // attempt's socket so backoff timing can't make the test flaky.
    await waitUntil(() => created >= 2);
    expect(created).toBeGreaterThanOrEqual(2);
    sockets[1]!.closeCb?.({ code: 1006, reason: "still down" });

    await waitUntil(() => created >= 3);
    sockets[2]!.closeCb?.({ code: 1006, reason: "still down" });

    // The next attempt SUCCEEDS.
    await waitUntil(() => created >= 4);
    expect(created).toBeGreaterThanOrEqual(4);
    const recoverySocket = sockets[3]!;
    recoverySocket.handshake({ sessionId: "sess-2", negotiatedVersion: "2.0.0" });
    await wait(5);

    // The recovery handshake must have carried the LIVE subscription set, so the
    // cloud seeds the new session non-empty (initialSubCount > 0 on the server).
    expect(recoverySocket.readInit().audio?.initialSubscriptions).toEqual(subs);

    // THE ASSERTION THAT REPRODUCES THE WEDGE: the originally-registered
    // onTranscript must STILL fire on the recovered session. If a reconnect
    // dropped the handler, this transcript would never be recorded.
    recoverySocket.pushTranscript("after reconnect");
    expect(received).toEqual(["before drop", "after reconnect"]);

    runtime.close();
  });
});