Skip to content

JS: resume the session socket after a drop, and say where it is - #2822

Open
oliverlaz wants to merge 1 commit into
mainfrom
oliver/sdk-js-session-reconnect
Open

oliverlaz wants to merge 1 commit into
mainfrom
oliver/sdk-js-session-reconnect

Conversation

@oliverlaz

Copy link
Copy Markdown
Member

Why

When a session's socket dropped (a network blink, a laptop asleep, a router redeploy closing with 1012, a node relay ending with 1011), the JS SDK ended the session for good: live went false, approvals were cleared, running tools were aborted. Between "connected" and "dead" a page had nothing to show.

The router already resumes (resumable=true, cursor, request_id, resumed.complete), and since #2811 it sends an app-level healthcheck frame, which is the only way page JS can notice a half-open socket (the browser never shows it WebSocket pings). This PR uses both: the same Session carries on through a drop, and says where it is.

How it works

 [connecting] ── dial ok ──► [connected] ◄──────── dial ok (+ resumed) ────────┐
     │ first dial fails           │ drop: error, 1006, 1011, 1012, silent     │
     ▼                            ▼                                            │
 [disconnected]      [reconnecting{attempt, retryAt, since, cause}] ── dial ──┤
                            │  ▲   failed dial → look the session up          │
               onLine=false │  │   online / tab visible / reconnect() ────────┘
                            ▼  │
                     [offline{since, cause}]
 disconnected.reason: closed · ended · refused · gave_up · unwatched
  • Backoff 500 ms → 30 s, half of it random, for 5 minutes (the router's hold on a text session nobody watches). The waits start over only after a connection lasted 10 s, so an accept-then-drop link isn't dialled twice a second.
  • Every dial, the first included, gives up after dialTimeoutMs (10 s). After a failed dial, GET /sessions/{id} decides: 404 or not live → ended, 401/403 → refused, anything else keeps trying. That lookup is bounded the same way.
  • healthcheck=true: a socket that reads nothing for 2.5 of the router's intervals is dropped with SocketSilentError and dialled again. Each socket is watched only from its own first healthcheck, so a router without them keeps its quiet sockets. A check that fires late (busy event loop, sleep, frozen tab) lets the waiting reads run first before deciding.
  • Tool answers are kept until the router says the call settled, and sent again on the socket that comes back. say, interrupt and close go over HTTP while the socket is away (or quiet); close stops the dialling even when the router couldn't be told.
  • resumed{complete:false} resets state and approvals, and AgentChat re-reads the channel. A call the router took down with it (1012) ends rather than come back without the agent.

Changes

  • src/reconnect.ts (new): ConnectionState, SocketConnection store, ReconnectOptions / RECONNECT_DEFAULTS, backoff, network source, healthcheck Watchdog.
  • src/session.ts: the resume loop, session.connection, session.reconnect(), the answer ledger, HTTP fallbacks, healthcheck handling.
  • src/sessions.ts: reconnect reaches the session from create, resume and fork, and is not sent in the request body.
  • src/dispatch.ts: dispatch.connection, shared backoff helpers.
  • src/agent-chat.ts: state.connection, re-read after an incomplete resume. src/react.ts: useConnection.
  • src/errors.ts, src/socket.ts: SocketClosedError.code, SocketSilentError.
  • README.md: "Staying connected". .claude/skills/sdk/notes/2026-11-30-session-socket-resume.md: what the other SDKs should port.

API change: session.say() and session.interrupt() return Promise<void> instead of void, so the HTTP fallback can report a failure. Source-compatible for callers that ignore the result.

Validation

  • npm run typecheck, npm run build, npm test (923 tests) and the generated-types check pass on top of current main.
  • tests/reconnect.test.ts runs against the real HTTP/WS TestRouter; each new test was mutation-checked (it fails with the behaviour it guards removed). Among them: resume with cursor and request id, 1011/1012 resume and 1000/left end, ended/refused lookups, giving up and reconnect(), flapping backoff, offline/online, a hung first dial and a hung lookup, a socket silent past its healthchecks, a socket watched only from its own healthcheck, short and long stalls, quiet close() over HTTP, and the reconnect options passing through.
  • Live, against a local router built from Send a healthcheck a browser can read on the session events socket #2811 through a fault-injecting TCP proxy: 20 scenarios — reset mid-reply, blackhole, host down, Wi-Fi off/on, flapping, tool result while away and after return, slow link, router SIGKILL / graceful restart / SIGSTOP freeze, close during an outage, outage past the window then sessions.resume, busy event loop, laptop sleep, WebSocket-only outage, stop button while away, idle-killing load balancer, retry-now, first open into a dead network. The last full run covered 17 of 20 with 56 checks passing and none failing (stopped at the load balancer); the remaining three passed in the run before. The harness found the reconnect pass-through and stall bugs fixed here; it isn't committed.

A session's socket that drops (a network blink, a laptop asleep, a router
restart) is dialled again with resumable=true, cursor and request_id, and
the router sends what was missed. live, events(), the stores and pending
approvals carry on through it.

- session.connection (and dispatch.connection, AgentChat state.connection,
  useConnection) says connecting, connected (resumed), reconnecting
  (attempt, retryAt, cause), offline or disconnected (closed, ended,
  refused, gave_up, unwatched).
- Backoff 500 ms to 30 s with jitter, for 5 minutes; each dial, the first
  included, gives up after dialTimeoutMs. A refused dial looks the session
  up: one ended or not ours stops the dialling.
- healthcheck=true: a socket that reads nothing for 2.5 of the router's
  intervals is taken for dead (SocketSilentError), watched from its own
  first healthcheck so a router without them keeps its quiet sockets. A
  late check reads what waited behind a stall before deciding.
- Tool answers are kept until the router says the call settled, and sent
  again on the socket that comes back. say, interrupt and close go over
  HTTP while the socket is away; close stops the dialling even when the
  router could not be told.
- A call the router took off on its way down (1012) ends rather than come
  back in writing without the agent.
- reconnect options now reach the session from sessions.create, resume and
  fork, and are no longer sent to the router.

Checked against a local router through a fault proxy: resets, blackholes,
refused dials, flapping, Wi-Fi off and on, latency, idle-killing balancers,
router crash, restart and freeze, stalls and laptop sleep.
@getstream-metis

Copy link
Copy Markdown

👋 Hi Oliver, want a second pair of eyes on this?

I'm Jeffery, Stream's review agent. I look for bugs, regressions, missing tests and slow paths, and I only post findings I've checked against the code.

  • Review this PR

Or comment /jeffery review. I'll stay quiet unless you ask.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant