diff --git a/apps/mobile/src/lib/nativeWebSocket.test.ts b/apps/mobile/src/lib/nativeWebSocket.test.ts index 6c2c9b543f..f4fa9a0724 100644 --- a/apps/mobile/src/lib/nativeWebSocket.test.ts +++ b/apps/mobile/src/lib/nativeWebSocket.test.ts @@ -163,4 +163,19 @@ describe("nativeWebSocketConstructor", () => { expect(closeCalls[0]!.args).toEqual([id, 4000, "bye"]); expect(socket.readyState).toBe(2); }); + + it("ignores a native open that lands after close", async () => { + const socket = await openSocket(); + const id = connectionIdOf(socket); + const opened = vi.fn(); + socket.addEventListener("open", opened); + + // Effect closes while still CONNECTING (open timeout or scope teardown); + // the in-flight native connect can still report success afterwards. + socket.close(1000, ""); + mocks.emit("onOpen", { id }); + + expect(opened).not.toHaveBeenCalled(); + expect(socket.readyState).toBe(2); + }); }); diff --git a/apps/mobile/src/lib/nativeWebSocket.ts b/apps/mobile/src/lib/nativeWebSocket.ts index db73076b6a..e6d7509a48 100644 --- a/apps/mobile/src/lib/nativeWebSocket.ts +++ b/apps/mobile/src/lib/nativeWebSocket.ts @@ -150,6 +150,14 @@ class NativeWebSocket { } handleOpen(): void { + // `close()` during CONNECTING (an Effect open-timeout or scope teardown) + // leaves a native connect in flight, so its `didOpen` can still land. Only + // a socket that is still connecting may transition to OPEN; otherwise the + // close would be silently undone and open handlers would fire on a socket + // the caller already gave up on. + if (this.readyState !== NativeWebSocket.CONNECTING) { + return; + } this.readyState = NativeWebSocket.OPEN; this.dispatch("open", { type: "open" }); }