File size: 26,466 Bytes
3201ca6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
/**
 * TODO: Fix flaky WebSocket tests (https://github.com/OpenHands/OpenHands/issues/11944)
 *
 * Several tests in this file are skipped because they fail intermittently in CI
 * but pass locally. The SUSPECTED root cause is that `wsLink.broadcast()` sends messages
 * to ALL connected clients across all tests, causing cross-test contamination
 * when tests run in parallel with Vitest v4.
 */
import { act, renderHook, waitFor } from "@testing-library/react";
import {
  describe,
  it,
  expect,
  beforeAll,
  afterAll,
  afterEach,
  vi,
} from "vitest";
import { ws } from "msw";
import { setupServer } from "msw/node";
import { useWebSocket } from "#/hooks/use-websocket";

describe("useWebSocket", () => {
  // MSW WebSocket mock setup
  const wsLink = ws.link("ws://acme.com/ws");

  const mswServer = setupServer(
    wsLink.addEventListener("connection", ({ client, server }) => {
      // Establish the connection
      server.connect();

      // Send a welcome message to confirm connection
      client.send("Welcome to the WebSocket!");
    }),
  );

  beforeAll(() =>
    mswServer.listen({
      onUnhandledRequest: "warn",
    }),
  );
  afterEach(() => mswServer.resetHandlers());
  afterAll(() => mswServer.close());

  const waitForConnection = async (result: {
    current: {
      isConnected: boolean;
    };
  }) => {
    await waitFor(
      () => {
        expect(result.current.isConnected).toBe(true);
      },
      { timeout: 5000 },
    );
  };

  it("should establish a WebSocket connection", async () => {
    const messages: string[] = [];
    const { result } = renderHook(() =>
      useWebSocket("ws://acme.com/ws", {
        onMessage: (event) => messages.push(event.data),
      }),
    );

    // Initially should not be connected
    expect(result.current.isConnected).toBe(false);

    // Wait for connection to be established
    await waitForConnection(result);

    // Should deliver the welcome message from our mock via onMessage
    await waitFor(() => {
      expect(messages).toContain("Welcome to the WebSocket!");
    });

    // Confirm that the WebSocket connection is established when the hook is used
    expect(result.current.socket).toBeTruthy();
  });

  it("should not retain an unbounded raw message history", async () => {
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static instance: MockWebSocket | null = null;

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instance = this;
        queueMicrotask(() => {
          this.readyState = MockWebSocket.OPEN;
          this.onopen?.(new Event("open"));
        });
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
        this.onclose?.(
          new CloseEvent("close", {
            code: 1000,
            reason: "Normal closure",
            wasClean: true,
          }),
        );
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);

    try {
      const messages: string[] = [];
      const { result, unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", {
          onMessage: (event) => messages.push(event.data),
        }),
      );

      await waitForConnection(result);

      act(() => {
        MockWebSocket.instance?.onmessage?.(
          new MessageEvent("message", { data: "first" }),
        );
        MockWebSocket.instance?.onmessage?.(
          new MessageEvent("message", { data: "second" }),
        );
        MockWebSocket.instance?.onmessage?.(
          new MessageEvent("message", { data: "third" }),
        );
      });

      // Every frame is delivered via onMessage, but the hook retains no raw
      // message history of its own — not even the latest.
      expect(messages).toEqual(["first", "second", "third"]);
      expect("lastMessage" in result.current).toBe(false);
      expect("messages" in result.current).toBe(false);

      unmount();
    } finally {
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instance = null;
    }
  });

  it("should handle connection errors gracefully", async () => {
    // Create a mock that will simulate an error
    const errorLink = ws.link("ws://error-test.com/ws");
    mswServer.use(
      errorLink.addEventListener("connection", ({ client }) => {
        // Simulate an error by closing the connection immediately
        client.close(1006, "Connection failed");
      }),
    );

    const { result } = renderHook(() => useWebSocket("ws://error-test.com/ws"));

    // Initially should not be connected and no error
    expect(result.current.isConnected).toBe(false);
    expect(result.current.error).toBe(null);

    // Wait for the connection to fail
    await waitFor(() => {
      expect(result.current.isConnected).toBe(false);
    });

    // Should have error information (the close event should trigger error state)
    await waitFor(() => {
      expect(result.current.error).not.toBe(null);
    });

    expect(result.current.error).toBeInstanceOf(Error);
    // Should have meaningful error message (could be from onerror or onclose)
    expect(
      result.current.error?.message.includes("WebSocket closed with code 1006"),
    ).toBe(true);

    // Should not crash the application
    expect(result.current.socket).toBeTruthy();
  });

  it.skip("should close the WebSocket connection on unmount", async () => {
    const { result, unmount } = renderHook(() =>
      useWebSocket("ws://acme.com/ws"),
    );

    // Wait for connection to be established
    await waitFor(() => {
      expect(result.current.isConnected).toBe(true);
    });

    // Verify connection is active
    expect(result.current.isConnected).toBe(true);
    expect(result.current.socket).toBeTruthy();

    const closeSpy = vi.spyOn(result.current.socket!, "close");

    // Unmount the component (this should trigger the useEffect cleanup)
    unmount();

    // Verify that WebSocket close was called during cleanup
    expect(closeSpy).toHaveBeenCalledOnce();
  });

  it("should support query parameters in WebSocket URL", async () => {
    // Stub WebSocket deterministically (mirrors the `onClose` test below).
    // The MSW-backed variant was flaky in CI — `wsLink.broadcast()` from
    // other tests leaks across the shared mock server, and this assertion
    // only needs to observe the constructed URL, not a real connection.
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        queueMicrotask(() => {
          this.readyState = MockWebSocket.OPEN;
          this.onopen?.(new Event("open"));
        });
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
        this.onclose?.(
          new CloseEvent("close", {
            code: 1000,
            reason: "Normal closure",
            wasClean: true,
          }),
        );
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);

    try {
      const baseUrl = "ws://acme.com/ws";
      const queryParams = {
        token: "abc123",
        userId: "user456",
        version: "v1",
      };

      const { result, unmount } = renderHook(() =>
        useWebSocket(baseUrl, { queryParams }),
      );

      await waitForConnection(result);

      // Verify that the WebSocket was created with query parameters
      expect(result.current.socket).toBeTruthy();
      expect(result.current.socket!.url).toBe(
        "ws://acme.com/ws?token=abc123&userId=user456&version=v1",
      );

      unmount();
    } finally {
      globalThis.WebSocket = originalWebSocket;
    }
  });

  it("should send the session key before application messages on every connection", async () => {
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static instance: MockWebSocket | null = null;
      static readonly instances: MockWebSocket[] = [];

      readonly url: string;
      readonly sent: string[] = [];
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instance = this;
        MockWebSocket.instances.push(this);
        queueMicrotask(() => {
          this.readyState = MockWebSocket.OPEN;
          this.onopen?.(new Event("open"));
        });
      }

      send(data: string) {
        if (this.readyState !== MockWebSocket.OPEN) {
          throw new DOMException("WebSocket is not open", "InvalidStateError");
        }
        this.sent.push(data);
      }

      close() {
        this.readyState = MockWebSocket.CLOSED;
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);
    const sessionApiKey = `sk-oh-${"a".repeat(64)}`;
    const expectedFrames = [
      JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),
      "application-message",
    ];

    try {
      const { result, unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", {
          sessionApiKey,
          onOpen: () => MockWebSocket.instance?.send("application-message"),
        }),
      );
      const firstSocket = MockWebSocket.instance!;

      expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);
      expect(firstSocket.sent).toEqual([]);
      await waitForConnection(result);

      expect(firstSocket.url).toBe("ws://acme.com/ws");
      expect(firstSocket.sent).toEqual(expectedFrames);

      act(() => {
        result.current.reconnect();
      });

      await waitFor(() => {
        expect(MockWebSocket.instances).toHaveLength(2);
        expect(MockWebSocket.instances[1].sent).toEqual(expectedFrames);
      });

      unmount();
    } finally {
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instance = null;
      MockWebSocket.instances.length = 0;
    }
  });

  // Skipped: flaky in CI - see comment at top of file
  it.skip("should call onOpen handler when WebSocket connection opens", async () => {
    const onOpenSpy = vi.fn();
    const options = { onOpen: onOpenSpy };

    const { result } = renderHook(() =>
      useWebSocket("ws://acme.com/ws", options),
    );

    // Initially should not be connected
    expect(result.current.isConnected).toBe(false);
    expect(onOpenSpy).not.toHaveBeenCalled();

    // Wait for connection to be established
    await waitForConnection(result);

    // onOpen handler should have been called
    expect(onOpenSpy).toHaveBeenCalledOnce();
  });

  it("should call onClose handler when WebSocket connection closes", async () => {
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        queueMicrotask(() => {
          this.readyState = MockWebSocket.OPEN;
          this.onopen?.(new Event("open"));
        });
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
        this.onclose?.(
          new CloseEvent("close", {
            code: 1000,
            reason: "Normal closure",
            wasClean: true,
          }),
        );
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);

    const onCloseSpy = vi.fn();
    const options = { onClose: onCloseSpy };

    try {
      const { result, unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", options),
      );

      await waitForConnection(result);

      act(() => {
        result.current.disconnect();
      });

      await waitFor(() => {
        expect(onCloseSpy).toHaveBeenCalledOnce();
      });

      unmount();
    } finally {
      globalThis.WebSocket = originalWebSocket;
    }
  });

  it.skip("should call onMessage handler when WebSocket receives a message", async () => {
    const onMessageSpy = vi.fn();
    const options = { onMessage: onMessageSpy };

    const { result } = renderHook(() =>
      useWebSocket("ws://acme.com/ws", options),
    );

    // Wait for connection to be established
    await waitFor(() => {
      expect(result.current.isConnected).toBe(true);
    });

    // onMessage handler should have been called for the welcome message
    await waitFor(() => {
      expect(onMessageSpy).toHaveBeenCalledOnce();
    });

    // Send another message from the mock server
    wsLink.broadcast("Hello from server!");

    // onMessage handler should have been called twice now
    await waitFor(() => {
      expect(onMessageSpy).toHaveBeenCalledTimes(2);
    });
  });

  it("should call onError handler when WebSocket encounters an error", async () => {
    const onErrorSpy = vi.fn();
    const options = { onError: onErrorSpy };

    // Create a mock that will simulate an error
    const errorLink = ws.link("ws://error-test.com/ws");
    mswServer.use(
      errorLink.addEventListener("connection", ({ client }) => {
        // Simulate an error by closing the connection immediately
        client.close(1006, "Connection failed");
      }),
    );

    const { result } = renderHook(() =>
      useWebSocket("ws://error-test.com/ws", options),
    );

    // Initially should not be connected and no error
    expect(result.current.isConnected).toBe(false);
    expect(onErrorSpy).not.toHaveBeenCalled();

    // Wait for the connection to fail
    await waitFor(() => {
      expect(result.current.isConnected).toBe(false);
    });

    // Should have error information
    await waitFor(() => {
      expect(result.current.error).not.toBe(null);
    });

    // onError handler should have been called
    expect(onErrorSpy).toHaveBeenCalled();
  });

  it.skip("should provide sendMessage function to send messages to WebSocket", async () => {
    const { result } = renderHook(() => useWebSocket("ws://acme.com/ws"));

    // Wait for connection to be established
    await waitFor(() => {
      expect(result.current.isConnected).toBe(true);
    });

    // Should have a sendMessage function
    expect(result.current.sendMessage).toBeDefined();
    expect(typeof result.current.sendMessage).toBe("function");

    // Mock the WebSocket send method
    const sendSpy = vi.spyOn(result.current.socket!, "send");

    // Send a message
    result.current.sendMessage("Hello WebSocket!");

    // Verify that WebSocket.send was called with the correct message
    expect(sendSpy).toHaveBeenCalledOnce();
    expect(sendSpy).toHaveBeenCalledWith("Hello WebSocket!");
  });

  it("closes a handshake stuck in CONNECTING at the timeout and retries", async () => {
    // Arrange: a socket whose handshake never completes. Closing it while
    // CONNECTING fires error + close(1006), as browsers do.
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static readonly instances: MockWebSocket[] = [];

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instances.push(this);
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
        this.onerror?.(new Event("error"));
        this.onclose?.(
          new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),
        );
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);
    vi.useFakeTimers();
    vi.spyOn(Math, "random").mockReturnValue(0); // deterministic backoff

    try {
      const { unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),
      );
      const firstSocket = MockWebSocket.instances[0];

      // Act/Assert: just before the timeout the handshake is still pending.
      await act(async () => {
        vi.advanceTimersByTime(9_999);
      });
      expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);
      expect(MockWebSocket.instances).toHaveLength(1);

      // At the timeout the stuck socket is closed (releasing the browser's
      // per-host handshake lock)...
      await act(async () => {
        vi.advanceTimersByTime(1);
      });
      expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED);

      // ...and a fresh attempt follows after the first backoff delay.
      await act(async () => {
        vi.advanceTimersByTime(1_000);
      });
      expect(MockWebSocket.instances).toHaveLength(2);

      unmount();
    } finally {
      vi.useRealTimers();
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instances.length = 0;
    }
  });

  it("does not close a socket that finished its handshake in time", async () => {
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static instance: MockWebSocket | null = null;

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instance = this;
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);
    vi.useFakeTimers();

    try {
      const { unmount } = renderHook(() => useWebSocket("ws://acme.com/ws"));
      const socket = MockWebSocket.instance!;
      const closeSpy = vi.spyOn(socket, "close");

      // Act: the handshake completes, then the watchdog window elapses.
      await act(async () => {
        socket.readyState = MockWebSocket.OPEN;
        socket.onopen?.(new Event("open"));
      });
      await act(async () => {
        vi.advanceTimersByTime(60_000);
      });

      // Assert: the cleared watchdog never touched the healthy socket.
      expect(closeSpy).not.toHaveBeenCalled();
      expect(socket.readyState).toBe(MockWebSocket.OPEN);

      unmount();
    } finally {
      vi.useRealTimers();
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instance = null;
    }
  });

  it("spaces reconnect attempts with exponential backoff capped at 30s", async () => {
    // Arrange: every connection attempt fails immediately.
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static readonly instances: MockWebSocket[] = [];

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instances.push(this);
        queueMicrotask(() => {
          this.readyState = MockWebSocket.CLOSED;
          this.onclose?.(
            new CloseEvent("close", {
              code: 1006,
              reason: "",
              wasClean: false,
            }),
          );
        });
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);
    vi.useFakeTimers();
    vi.spyOn(Math, "random").mockReturnValue(0); // strip the jitter

    const expectInstancesAfter = async (
      advanceMs: number,
      expected: number,
    ) => {
      await act(async () => {
        vi.advanceTimersByTime(advanceMs);
      });
      expect(MockWebSocket.instances).toHaveLength(expected);
    };

    try {
      const { unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),
      );
      // Flush the first attempt's immediate failure.
      await act(async () => {});
      expect(MockWebSocket.instances).toHaveLength(1);

      // Act/Assert: retries land at 1s, then 2s, then 4s after each failure.
      await expectInstancesAfter(999, 1);
      await expectInstancesAfter(1, 2);
      await expectInstancesAfter(1_999, 2);
      await expectInstancesAfter(1, 3);
      await expectInstancesAfter(3_999, 3);
      await expectInstancesAfter(1, 4);
      await expectInstancesAfter(7_999, 4);
      await expectInstancesAfter(1, 5);
      await expectInstancesAfter(15_999, 5);
      await expectInstancesAfter(1, 6);

      // The sixth failure would double to 32s; the cap holds it at 30s...
      await expectInstancesAfter(29_999, 6);
      await expectInstancesAfter(1, 7);

      // ...and every failure after that stays at 30s rather than growing.
      await expectInstancesAfter(29_999, 7);
      await expectInstancesAfter(1, 8);

      unmount();
    } finally {
      vi.useRealTimers();
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instances.length = 0;
    }
  });

  it("ignores close/error events from a socket that was replaced", async () => {
    // Arrange: sockets that only emit events when the test fires them, so the
    // old socket's close can land *after* its replacement is open — the race
    // that used to overwrite the new socket's OPEN state.
    class MockWebSocket {
      static readonly CONNECTING = 0;
      static readonly OPEN = 1;
      static readonly CLOSING = 2;
      static readonly CLOSED = 3;
      static readonly instances: MockWebSocket[] = [];

      readonly url: string;
      readyState = MockWebSocket.CONNECTING;
      onopen: ((event: Event) => void) | null = null;
      onmessage: ((event: MessageEvent) => void) | null = null;
      onclose: ((event: CloseEvent) => void) | null = null;
      onerror: ((event: Event) => void) | null = null;

      constructor(url: string) {
        this.url = url;
        MockWebSocket.instances.push(this);
      }

      send() {}

      close() {
        this.readyState = MockWebSocket.CLOSED;
      }

      emitOpen() {
        this.readyState = MockWebSocket.OPEN;
        this.onopen?.(new Event("open"));
      }

      emitFailure() {
        this.onerror?.(new Event("error"));
        this.emitClose();
      }

      emitClose() {
        this.onclose?.(
          new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),
        );
      }
    }

    const originalWebSocket = globalThis.WebSocket;
    vi.stubGlobal("WebSocket", MockWebSocket);

    const onCloseSpy = vi.fn();
    const onErrorSpy = vi.fn();

    try {
      const { result, unmount } = renderHook(() =>
        useWebSocket("ws://acme.com/ws", {
          onClose: onCloseSpy,
          onError: onErrorSpy,
        }),
      );
      const staleSocket = MockWebSocket.instances[0];
      act(() => staleSocket.emitOpen());

      // Act: replace the socket, open the replacement, then let the stale
      // socket's error + close events land late.
      act(() => {
        result.current.reconnect();
      });
      const currentSocket = MockWebSocket.instances[1];
      act(() => currentSocket.emitOpen());
      act(() => staleSocket.emitFailure());

      // Assert: the stale socket's events reach neither handler...
      expect(onCloseSpy).not.toHaveBeenCalled();
      expect(onErrorSpy).not.toHaveBeenCalled();

      // ...while the current socket's close still notifies as before.
      act(() => currentSocket.emitClose());
      expect(onCloseSpy).toHaveBeenCalledOnce();
      expect(onErrorSpy).toHaveBeenCalledOnce();

      unmount();
    } finally {
      globalThis.WebSocket = originalWebSocket;
      MockWebSocket.instances.length = 0;
    }
  });

  it("should not send message when WebSocket is not connected", () => {
    const { result } = renderHook(() => useWebSocket("ws://acme.com/ws"));

    // Initially should not be connected
    expect(result.current.isConnected).toBe(false);
    expect(result.current.sendMessage).toBeDefined();

    // Mock the WebSocket send method (even though socket might be null)
    const sendSpy = vi.fn();
    if (result.current.socket) {
      vi.spyOn(result.current.socket, "send").mockImplementation(sendSpy);
    }

    // Try to send a message when not connected
    result.current.sendMessage("Hello WebSocket!");

    // Verify that WebSocket.send was not called
    expect(sendSpy).not.toHaveBeenCalled();
  });
});