Skip to content

fix(websocket): attach stream listeners before the socket opens - #1189

Merged
EhabY merged 1 commit into
mainfrom
fix/ws-listeners-before-open
Nov 12, 2026
Merged

EhabY merged 1 commit into
mainfrom
fix/ws-listeners-before-open

Conversation

@EhabY

@EhabY EhabY commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Streams now return before their socket opens, so every listener is attached before any event can fire. ws emits frames that arrive with the handshake on a process.nextTick, ahead of any awaited continuation, so awaiting open before subscribing dropped the first message on every connect and reconnect: agent metadata, the workspace watch, and log backlogs. The same timing kept the ReconnectingWebSocket open handler from ever running, so watchers never reached CONNECTED and their backoff never reset on open. Both are fixed.

OneWayWebSocket exposes opened and closed promises. Log streams attach all listeners up front and then await socket.opened, so they still reject on a failed handshake without printing anything, while errors after open (even ones arriving with the handshake) are reported. The tasks panel subscribes via stream.closed.then(...), which cannot miss an early close. ReconnectingWebSocket.connect() now numbers its attempts, so a restart while a factory is pending always connects the latest attempt and closes superseded sockets, and a disconnect() during a certificate refresh is no longer undone when the refresh succeeds. The SSE fallback only served servers older than 2.22 (#620), so it is removed now that 2.29.0 is the minimum (#1186), together with the eventsource dependency and the logger's protocol parameter.

Closes #1141.

Plan and decision log

Problem (verified)

  • With the repo's ws, a listener attached a few awaits after open dropped 20/20 messages; attached before open, 0/20.
  • eventsource 5.1.5 had the same gap: 20/20 dropped after 3+ promise hops.
  • Every awaited layer added a gap: waiting for open, then the factory, then ReconnectingWebSocket.connect(), then create(), then the caller's await client.watchX() before addEventListener.
  • A close that arrives with the handshake (a finished build: backlog, then close) was lost too, and the tasks panel refreshes on that close.
  • The ReconnectingWebSocket open listener was attached after open had fired. The test fake hid this because its factory resolved before fireOpen().

Options considered

  • A. Pause the socket on open, resume on setImmediate (about 5 lines). Rejected: it depends on every caller subscribing within the same await chain, which is an ordering assumption rather than a guarantee.
  • A2. Hold events until the first consumer subscribes. Deterministic, but it adds a step to the stream interface, and a consumer that never subscribes leaves the socket paused.
  • B. Attach listeners before open (chosen). This is the browser WebSocket contract, what coder/site does (watchAgentMetadata returns new OneWayWebSocket(...)), what partysocket/reconnecting-websocket do, and how matter.js fixed this exact ws bug.

Ordering guarantee

  • The socket is constructed inside a promise continuation (after await createHttpAgent), and listeners are attached in the same microtask chain (ReconnectingWebSocket right after the factory, callers right after await client.watchX()). I/O callbacks and process.nextTick work scheduled from a microtask run only after that chain drains, so no event can precede its listener.

Decisions

  • Factories resolve once async setup (header command, HTTP agent) is done and the socket is constructed; nothing awaits I/O before listeners attach. await client.watchX() now means "initialized", not "connected"; no caller relied on "connected".
  • Lifecycle as opened/closed promises on OneWayWebSocket, created in the constructor, rather than onClose callbacks or open-flag tracking. A promise settles once and late subscribers still see it, which mirrors WebSocketStream.
  • Log stream error listener is attached before the await and gated on a synchronous open flag. Attaching it after await socket.opened missed protocol errors in bytes delivered with the handshake (verified against a raw server: the error line was missing before, present now).
  • Connect attempts are numbered. Before, a reconnect() while a factory was pending raced: the older socket could open first and get the newer one cancelled, or be overwritten and leaked. Stale factory results are closed and stale rejections ignored. This predates the PR, but the faster factories made the window more visible.
  • Before open, ReconnectingWebSocket routes error and close through handleConnectionError (401, certificate refresh, unrecoverable codes, retry) without forwarding them to consumers. That keeps the behavior consumers saw before, and an error followed by a close gives a single retry. Only the certificate path awaits; it now re-checks for DISCONNECTED after the refresh (raised in review).
  • SSE fallback: dead code with the 2.29.0 floor, so it was deleted after fix!: set the minimum supported Coder version to 2.29.0 #1186 merged, along with EventStreamLogger's "WS" | "SSE" parameter.
  • UnidirectionalStream is kept: OneWayWebSocket and ReconnectingWebSocket both implement it, and consumers and test fakes depend only on the interface.
  • Tests kept minimal: one real-server regression test through CoderApi (message on connect, then on reconnect; state reaches CONNECTED), one ReconnectingWebSocket test where a superseded factory resolves late, and one where disconnect() runs during a certificate refresh; all fail on the old code. The existing handshake-rejection test now goes through streamBuildLogs and also checks that nothing is printed after a failed handshake.

Validation

  • pnpm typecheck, pnpm lint, pnpm format:check and pnpm build pass; the build no longer bundles eventsource.
  • pnpm test: 3163 passed, 6 skipped.
  • Throwaway real-server checks (not committed): finished build (backlog then close), 403 rejects with no output, 401 disconnects without retry or consumer events, dispose/logout during the handshake, refused connection then reconnect, protocol error sent with the handshake.
  • Not run: integration tests and a live deployment.

Generated by Coder Agents on behalf of @EhabY.

@EhabY
EhabY force-pushed the fix/ws-listeners-before-open branch from 5e3228b to 3da7eb4 Compare November 12, 2026 15:29
@EhabY
EhabY marked this pull request as ready for review November 12, 2026 16:06
@EhabY
EhabY force-pushed the fix/ws-listeners-before-open branch from 3da7eb4 to cb77fe0 Compare November 12, 2026 16:19
@EhabY
EhabY requested a review from jeremyruppel November 12, 2026 16:32
Comment thread src/websocket/oneWayWebSocket.ts Resolved
Comment thread src/websocket/reconnectingWebSocket.ts Resolved
Comment thread test/unit/api/coderApi.streams.test.ts Resolved
@EhabY
EhabY force-pushed the fix/ws-listeners-before-open branch from cb77fe0 to 326b989 Compare November 12, 2026 18:08
@EhabY
EhabY requested a review from jeremyruppel November 12, 2026 18:14

@jeremyruppel jeremyruppel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@EhabY
EhabY merged commit 98ae74d into main Nov 12, 2026
22 of 24 checks passed
@EhabY
EhabY deleted the fix/ws-listeners-before-open branch November 12, 2026 23:11
@EhabY EhabY mentioned this pull request Nov 13, 2026
EhabY added a commit that referenced this pull request Nov 13, 2026
streamBuildLogs awaits socket.opened and chains socket.closed since the
OneWayWebSocket change in #1189. The awaitBuild tests mocked the socket
without either, so streamBuildLogs threw, awaitBuild logged "Could not
stream the build logs" and never closed the socket.

Move the tasks panel's open socket mock to testHelpers as
createMockOneWaySocket and use it for every build log socket.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ReconnectingWebSocket drops messages the server sends right after the handshake

2 participants