Skip to content

fix(client): start the wsLink subscription when onConnectionStateChange throws on the first state - #7899

Merged
KATT merged 2 commits into
mainfrom
cursor/wslink-initial-connstate-throw-3334
Nov 4, 2026
Merged

KATT merged 2 commits into
mainfrom
cursor/wslink-initial-connstate-throw-3334

Conversation

@KATT

@KATT KATT commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #7896, for the second Minor follow-up in CodeRabbit's review there ("Isolate the initial connectionState delivery in wsLink"). No issue.

Stack (bottom to top): this PR, then #7900.

Why

  • wsLink subscribes to client.connectionState, a behaviorSubject that sends the current state inside subscribe. If the subscription's onConnectionStateChange throws there, the request is never sent, a lazy connection never opens, and the error comes out of .subscribe(...).
  • fix(client): keep wsClient reconnecting when onConnectionStateChange throws #7896 guarded every later state; this first delivery was the one gap.

What

  • callUserCallback() moves, unchanged, to wsClient/utils.ts, and wsLink sends the first state through it. A throw still shows up as an uncaught exception, and the request is still sent.
  • No public API change.

Links

None

Alternatives considered

Testing

On main (06528e2), the new lazy and eager tests in websockets.reconnectErrors.test.ts fail: the connection never opens, or the request is never sent.

AI model

Claude Opus 5.5

Open in Web Open in Cursor 

Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

Summary by CodeRabbit

  • Bug Fixes
    • WebSocket subscriptions now continue initializing when a connection-state callback throws, so they can reach the pending state and deliver data.
    • Errors thrown by connection-state callbacks are reported asynchronously, without being routed to the subscription’s onError handler.
    • Verified the behavior for both lazy and eager WebSocket connections.

cursoragent and others added 2 commits November 4, 2026 14:09
… throws on the first state

Co-authored-by: Alex / KATT <[email protected]>
…e throws on the first state

Co-authored-by: Alex / KATT <[email protected]>
@KATT
KATT requested a review from a team as a code owner November 4, 2026 14:30
@vercel

vercel Bot commented Nov 4, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
examples-next-minimal-starter Ready Ready Preview Nov 4, 2026 2:30pm UTC
examples-todomvc Ready Ready Preview Nov 4, 2026 2:30pm UTC
next-prisma-starter Ready Ready Preview Nov 4, 2026 2:30pm UTC
next-prisma-websockets-starter Ready Ready Preview Nov 4, 2026 2:30pm UTC
tanstack-start-sse-chat Ready Ready Preview Nov 4, 2026 2:30pm UTC
trpc-next-app-dir Ready Ready Preview Nov 4, 2026 2:30pm UTC
www Ready Ready Preview Nov 4, 2026 2:30pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The WebSocket client now imports a shared callback error helper. wsLink uses the helper for connection-state notifications received during subscription setup. Tests cover lazy and eager clients when the initial callback throws.

Changes: WebSocket connection-state callbacks

Layer / File(s) Summary
Share callback error handling
packages/client/src/links/wsLink/wsClient/utils.ts, packages/client/src/links/wsLink/wsClient/wsClient.ts
The client exports callUserCallback from utils.ts. wsClient.ts imports it instead of defining a local helper.
Protect the initial state notification
packages/client/src/links/wsLink/wsLink.ts, packages/tests/server/websockets.reconnectErrors.test.ts
wsLink applies callUserCallback to connection-state notifications received during subscription setup and forwards later notifications directly. Lazy and eager tests verify that a thrown initial callback does not prevent subscription startup or data delivery.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Possibly related PRs

  • trpc/trpc#7900: Changes observer notification to catch callback errors and rethrow them asynchronously.
  • trpc/trpc#7891: Adds callUserCallback for WebSocket event handling and asynchronous error rethrowing.
  • trpc/trpc#7896: Addresses the onConnectionStateChange exception path and introduces callUserCallback.

Suggested reviewers: nick-lucas, hmatthieu

Merge Risk: Minimal · up to 8e7e2

No actionable merge-blocking risk was identified. The change allows subscriptions to start despite an initial connection-state callback exception and is mergeable after normal checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main fix: ensuring the wsLink subscription starts when the initial onConnectionStateChange callback throws.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 4 files.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 06528e2 and 8e7e286.

Files selected for processing: 4
  • packages/client/src/links/wsLink/wsClient/utils.ts
  • packages/client/src/links/wsLink/wsClient/wsClient.ts
  • packages/client/src/links/wsLink/wsLink.ts
  • packages/tests/server/websockets.reconnectErrors.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@pkg-pr-new

pkg-pr-new Bot commented Nov 4, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/@trpc/client@7899

@trpc/next

npm i https://pkg.pr.new/@trpc/next@7899

@trpc/openapi

npm i https://pkg.pr.new/@trpc/openapi@7899

@trpc/react-query

npm i https://pkg.pr.new/@trpc/react-query@7899

@trpc/server

npm i https://pkg.pr.new/@trpc/server@7899

@trpc/tanstack-react-query

npm i https://pkg.pr.new/@trpc/tanstack-react-query@7899

@trpc/upgrade

npm i https://pkg.pr.new/@trpc/upgrade@7899

commit: 8e7e286

@trpc-bot trpc-bot 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.

🤖 Approved; Alex reviewed stack #7901.

@KATT
KATT added this pull request to the merge queue Nov 4, 2026
Merged via the queue into main with commit 50372ac Nov 4, 2026
54 of 55 checks passed
@KATT
KATT deleted the cursor/wslink-initial-connstate-throw-3334 branch November 4, 2026 17:18
meefs pushed a commit to meefs/trpc that referenced this pull request Nov 4, 2026
…ows (trpc#7900)

<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
Follow-up to trpc#7896, for the first Minor follow-up in [CodeRabbit's
review
there](trpc#7896 (review))
("Deliver each connection state to later subscribers when one callback
throws"). No issue.

**Stack (bottom to top):** 1. trpc#7899 `fix(client): start the wsLink
subscription when onConnectionStateChange throws on the first state`
(`cursor/wslink-initial-connstate-throw-3334` → `main`); 2. this PR,
`fix(server)` (`cursor/observable-subject-isolate-throws-3334` →
`cursor/wslink-initial-connstate-throw-3334`).

## Why

- `behaviorSubject.next()` calls each subscriber in a loop. If one
throws, the loop stops, so the subscribers after it never get that
value.
- `wsClient.connectionState` is a `behaviorSubject`. When one
subscription's `onConnectionStateChange` throws, later subscriptions on
the same client miss that state (`pending`, or the reconnect's
`connecting`).
- trpc#7896's `callUserCallback()` keeps the client's reconnect loop
running, but it can't restore delivery to the other subscribers.

## What

- `behaviorSubject.next()` calls each subscriber through a new private
`callObserver()` helper in `behaviorSubject.ts`. It isn't exported.
- The helper rethrows any error in a `setTimeout`, like the client's
`callUserCallback()`, so the error still shows up as an uncaught
exception.
- Every subscriber gets the value, and each error is rethrown
separately.
- Order is unchanged, and so is the handling of subscribers that
unsubscribe during the loop.
- `behaviorSubject.next()` no longer throws synchronously. Its doc
comment says so.
- Unchanged:
- **`share()`**, which has the same loop. It's left out of this PR by
choice (see Alternatives).
- **Delivery on subscribe.** A `behaviorSubject` still sends the current
value to a new subscriber inside `subscribe()`, and a throw there still
comes out of that subscriber's own `subscribe()` call. trpc#7899 guards
`wsLink`'s use of it.
- **`map`, `tap` and `distinctUntilChanged`,** which each call one
observer.

### User-visible changes

Only `packages/client` creates `behaviorSubject`s. I checked each one,
and confirmed the link cases with a throwaway probe: a real server,
`createTRPCClient`, and a callback that throws once.

- **`wsClient.connectionState` with several subscribers** (several
`wsLink` subscriptions, or direct
`wsClient.connectionState.subscribe(...)`): when one throws, the others
now still get that state. Before, they missed it. The error was already
rethrown asynchronously by `wsClient`.
- **`httpSubscriptionLink` and `localLink`** each create one
`behaviorSubject` per subscription, with the link as its only
subscriber. If `onConnectionStateChange` throws on a later state
(`pending`, the retry's `connecting`, or the final `idle`), the error is
now rethrown asynchronously and the subscription keeps going. Before,
the throw escaped into the link and ended the subscription:
  - It called `onError` with a `TRPCClientError`.
  - With `localLink`, its own `onError` option also fired.
- **Unchanged for those two links:**
- A throw on the first `connecting` state, which is sent during
`subscribe()`.
- Throws in `onData`, `onStarted`, `onStopped`, `onComplete` and
`onError`. These don't go through the `behaviorSubject`.
- **`WsConnection.wsObservable`** is internal, and its one subscriber
doesn't throw, so nothing visible changes.

### `callUserCallback` around `connectionState.next` in `wsClient`

- With this PR, `connectionState.next()` can't throw, so those wrappers
no longer catch anything.
- I kept them. `@trpc/client`'s peer dependency on `@trpc/server` is an
exact version, but package managers only warn on a mismatch. With an
older `@trpc/server`, removing them would bring back the reconnect bugs
trpc#7896 fixed. They cost nothing, and keeping them keeps this PR to
`@trpc/server`.
- trpc#7899's first-delivery guard in `wsLink` is still needed. That
delivery happens inside `connectionState.subscribe()`, not `next()`, and
this PR doesn't change it.

## Links

- None. No docs or example changes.
- trpc#7896 and [CodeRabbit's
review](trpc#7896 (review)).

## Alternatives considered

- **Also fix `share()`.** It has the same stop-at-first-throw loop for
`next`, `error` and `complete`. `TRPCUntypedClient` runs every request
through it, so changing it would change how every throwing subscription
callback (`onData` etc.) behaves on every link. It's left out by choice,
to keep this fix to `behaviorSubject`. It could be a separate change.
- **Fix it only in `wsClient`**, by keeping its own subscriber list or
wrapping each `wsLink` delivery. That would leave `behaviorSubject`'s
loop as it is for its other users.
- **Deliver to everyone, then rethrow the first error synchronously**
(or an `AggregateError`). That keeps a sync throw out of `next()`, and
trpc#7896's callers would still need their guards.
- **Swallow the errors.** That would hide the user's bug.
- **Also isolate `behaviorSubject`'s subscribe-time delivery.** Only the
subscribing caller is involved, and it can handle its own throw. Left as
is.

## Testing

- New tests, written first, with no existing test changed (`git diff
origin/main -- '*.test.ts'` only adds lines):
- `packages/tests/server/websockets.reconnectErrors.test.ts` has a new
`describe`, "a throwing connection state subscriber does not stop the
others". Both tests use `createTRPCClient` + `wsLink` + `createWSClient`
against a real server, and force a reconnect with
`destroyConnections()`.
- **Two `wsLink` subscriptions, the first throwing on every state after
its first:** the second gets `connecting, pending, connecting, pending`,
the same states as the first. The 4 errors are reported as uncaught
exceptions.
- **Two direct `wsClient.connectionState` subscribers, the first
throwing:** the second gets `idle, connecting, pending, connecting,
pending`.
- `behaviorSubject.test.ts`: `next()` still reaches later subscribers,
and each subscriber's error is rethrown in its own timer (fake timers).
- Regression check (`wsLink` subscriptions): on trpc#7899 (8e7e286) plus
only the test commit, the test fails with `expected [ 'connecting' ] to
deeply equal [ 'connecting', 'pending' ]` at
`expect(secondStates.map((state) => state.state)).toEqual(['connecting',
'pending'])`. The second subscription never sees `pending`.
- Regression check (`connectionState` subscribers): on the same base,
the test fails with `expected [ 'idle' ] to deeply equal [ 'idle',
'connecting', 'pending' ]`.
- Regression check (unit): on the same base, the 2 `behaviorSubject`
tests fail with `expected [Function] to not throw an error but 'Error:
observer failed' was thrown` (and `'Error: first failed'`).
- The same 4 tests fail the same way on `main` (06528e2) plus only
these test additions.
- With the fix, the 2 files (15 tests) pass, 10 of 10 runs.
- Full suite (`pnpm vitest --watch false`): 214 files, 1636 tests pass.
- `@trpc/react-query` and `@trpc/tanstack-react-query` projects: 70
files, 363 tests pass.
- `tsc --noEmit` for `packages/client`, `server`, `tests`, `react-query`
and `tanstack-react-query` is clean. `oxlint` and `oxfmt --check` on the
3 changed files are clean.

## AI model

Claude Opus 5.5
<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a
href="https://cursor.com/agents/bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

<!-- codesmith:footer -->
---
<a
href="https://backend.blacksmith.sh/track/enable-autofix?expires=1796394694&installation_model_id=443568&pr_number=7900&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7900&signature=66ee6a111bd2d011705a0c419a3ede8becd7fe05de3d13153d6984cf0614d065"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img
alt="Autofix with [code]smith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark-3x.png"
width="190" height="28"></picture></a>
<sup><a
href="https://app.blacksmith.sh/trpc/codesmith/trpc/pr/7900?autoLogin=true&ref=codesmith_pr_footer">Open
in [code]smith</a> · Need help on this PR? Tag
<code>@codesmith-bot</code> with what you need.</sup>

<!-- codesmith:autofix:disabled -->
<!-- /codesmith:footer -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed observable notifications so an error from one subscriber no
longer prevents other subscribers from receiving updates.
* Subscriber errors are reported asynchronously, including when multiple
subscribers throw.
* Fixed WebSocket reconnect state notifications so later subscribers
continue receiving connection updates when an earlier subscriber throws.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor Agent <[email protected]>
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Nov 5, 2026

This branch was successfully deployed

5 active deployments
Preview – www — 8e7e2867 Deployed Nov 4, 2026 by vercel[bot]
Preview – examples-todomvc — 8e7e2867 Deployed Nov 4, 2026 by vercel[bot]
Preview – trpc-next-app-dir — 8e7e2867 Deployed Nov 4, 2026 by vercel[bot]
Preview – next-prisma-starter — 8e7e2867 Deployed Nov 4, 2026 by vercel[bot]
Preview – examples-next-minimal-starter — 8e7e2867 Deployed Nov 4, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants