Repository navigation
feat: implement socket recovery mechanism and enhance reconnection logic - #714
Conversation
There was a problem hiding this comment.
Important
The recovery loop is the right shape, but two details keep it from doing what it says: the backoff counter is cleared before the reconnect is known to have worked, and the forced attempt on tab visibility cannot preempt a pending backoff timer.
Reviewed changes
- Handshake recovery in
socket-client.ts—connect_errorandvisibilitychangenow driverecover(), which refreshes the session and reconnects behind a single pending timer with capped exponential backoff;disconnectSocket()tears the timer/listener/counter down andreconnectSocketIfDown()is exported. - Token-refresh reconnect in
_authenticated.tsx— when a refreshed token arrives while the socket is down, the layout now callsreconnectSocketIfDown()instead of doing nothing. - Reconnect reconciliation in the realtime hooks —
useGlobalAgentRealtimeanduseProjectRealtimeinvalidate["conversation-event-window"](plus["global-chat", "conversations"]for global chat) after a reconnect, since events emitted while the socket was away are never replayed; the project hook does it on the rejoin ack, matching its existing ordering. - Test — one vitest case covers refresh-then-reconnect after
connect_error.
deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Both findings from the previous review are addressed in 10a822c, and the recovery loop now behaves as described.
Reviewed changes
- Backoff reset moved to
connect—recoveryAttemptnow zeroes from aconnectlistener instead of immediately beforecurrent.connect(), so a refresh that keeps succeeding while the handshake keeps failing grows the delay to the 30s cap instead of pinning at 1s. - Forced recovery preempts a pending timer —
recoverNow()clears any outstanding backoff timer and schedules a 0ms attempt without incrementingrecoveryAttempt, so a tab returning to visibility (or a token refresh) no longer waits out a long backoff. - Recovery tests — added cases for repeated handshake failures (1s → 2s), reset on
connect, and forced preemption, alongside the existing refresh-then-reconnect case. The suite (29 tests), the project realtime hook suite, and biome all pass locally.
deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
mountedDown in useGlobalAgentRealtime is always false in production: it is computed after connectSocket() has already called socket.connect(), which re-subscribes the socket (Socket.active === !!subs).
Reviewed changes
- Gated handshake recovery on
socket.active, so only a refused handshake drives the refresh-and-reconnect loop while transport failures stay in Socket.IO's own retry loop. - Stopped the recovery loop on a 401/403 from
/auth/refreshviaisAuthRejection. - Added a single-flight
recoveringSocketguard so a visibility change or token refresh cannot start a second refresh while one is in flight. - Added a mounted-down check to
useGlobalAgentRealtimeand a dedicated hook test suite. - Extended
socket-clientcoverage with transient pass-through, auth-rejection stop, backoff on other refresh failures, in-flight dedupe, still-reconnecting no-op, visibility recovery and teardown cases.
ℹ️ The auth-rejection comment promises a login redirect that does not happen
socket-client.ts:175-177 says the HTTP client's 401 handling "takes the user to login", but api-client.ts:91-101 explicitly excludes /auth/refresh from that path, so a rejected refresh just stops recovery and leaves the user on the page with a dead socket. If stopping is intended, say the session is treated as over; if the user should be sent to login, that needs an explicit handler here or in a shared session-expired path.
Technical details
# `isAuthRejection` comment vs. actual 401 handling
## Affected sites
- `apps/web/src/lib/socket-client.ts:175-177` — comment claims the HTTP client redirects to login on 401
- `apps/web/src/lib/api-client.ts:91-101` — `/auth/refresh` is in the `isAuthEndpoint` list, so it is rejected without the 401 refresh/redirect path
- `apps/web/src/lib/auth-api.ts:134-151` — `getMe` maps 401 to `null`; the `_authenticated` `beforeLoad` redirect only runs on navigation
## Required outcome
- The comment accurately describes what happens after a rejected refresh, or an explicit session-expired redirect is added.…improving connection handling
There was a problem hiding this comment.
✅ No new issues found.
Both previous findings are now resolved: the mountedDown ordering bug is fixed, and the earlier backoff/forced-preemption threads stay addressed. The delta is a targeted correction to the prior review feedback, and the hook suites pass.
Reviewed changes
- Read the socket state before reconnecting in
useGlobalAgentRealtime:getSocket()is now called beforeconnectSocket(), somountedDownreflects the pre-connect state instead of always seeing a re-subscribed (active === true) socket. - Made the hook test mock faithful to production: the mocked
connectSocket()now setsactivetotrue, and the mounted-down test asserts that transition.
deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Problem
After a browser tab sat idle for a long time, sending a message in a conversation left it "thinking" forever: the agent replied, but nothing appeared until the page was reloaded.
Conversation events reach the browser only over the Socket.IO connection (no polling fallback). The realtime server ties each socket to the access token it connected with, and disconnects it at token expiry. A background tab can miss the earlier
reauthmessage, so the client's reconnect after the server disconnect used the expired cookie. The server's auth middleware refused that handshake, which surfaces asconnect_error, and Socket.IO does not auto-reconnect after that. The client had noconnect_errorhandler. Sending a message did refresh the cookie via the 401 path, but theonTokenRefreshedlistener only reconnected a socket that was still connected, so the dead socket stayed dead.Changes
socket-client.ts: handleconnect_errorby refreshing the session and reconnecting, with exponential backoff (1s up to 30s). Also check the connection when the tab becomes visible again. ExportreconnectSocketIfDown()._authenticated.tsx: when the token is refreshed and the socket is down, reconnect it (previously only a connected socket was handled).use-global-agent-realtime.ts,use-project-realtime.ts: after a reconnect, invalidate the conversation event windows (and the global chat conversations list) so events missed while the socket was away are fetched.socket-client.test.ts: test thatconnect_errortriggers a session refresh and a reconnect.Testing
tsc -b, biome and the related vitest suites (hooks + socket-client) pass.