Fix websocket reconnect race

studio-mac · ~/src/signal-bus

live

Codex · gpt-5.3-codex

The websocket client sometimes double-opens after a flaky reconnect. Fix the race and add a regression test.

I'll trace connect() vs onclose and serialize reconnects behind a generation token so a stale socket can't reopen after a newer handshake.

Readsrc/ws/client.ts
async function connect() {
  socket = new WebSocket(url)
  socket.onclose = () => setTimeout(connect, backoff())
}
Editsrc/ws/client.ts
+ let gen = 0
async function connect() {
+ const my = ++gen
+ socket?.close()
socket = new WebSocket(url)
- socket.onclose = () => setTimeout(connect, backoff())
+ socket.onclose = () => {
+ if (my === gen) setTimeout(connect, backoff())
+ }
}
Bashpnpm test src/ws/client.test.ts

$ pnpm test src/ws/client.test.ts