Skip to content

feat: implement socket recovery mechanism and enhance reconnection logic - #714

Merged
pikann merged 4 commits into
masterfrom
feature/implement-socket-recovery-mechanism
Nov 8, 2026
Merged

pikann merged 4 commits into
masterfrom
feature/implement-socket-recovery-mechanism

Conversation

@pikann

@pikann pikann commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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 reauth message, so the client's reconnect after the server disconnect used the expired cookie. The server's auth middleware refused that handshake, which surfaces as connect_error, and Socket.IO does not auto-reconnect after that. The client had no connect_error handler. Sending a message did refresh the cookie via the 401 path, but the onTokenRefreshed listener only reconnected a socket that was still connected, so the dead socket stayed dead.

Changes

  • socket-client.ts: handle connect_error by refreshing the session and reconnecting, with exponential backoff (1s up to 30s). Also check the connection when the tab becomes visible again. Export reconnectSocketIfDown().
  • _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 that connect_error triggers a session refresh and a reconnect.

Testing

  • tsc -b, biome and the related vitest suites (hooks + socket-client) pass.
  • Not yet verified in a real browser. To check: leave a tab idle past the access token lifetime, then send a message; the reply should appear without a reload.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_error and visibilitychange now drive recover(), which refreshes the session and reconnects behind a single pending timer with capped exponential backoff; disconnectSocket() tears the timer/listener/counter down and reconnectSocketIfDown() is exported.
  • Token-refresh reconnect in _authenticated.tsx — when a refreshed token arrives while the socket is down, the layout now calls reconnectSocketIfDown() instead of doing nothing.
  • Reconnect reconciliation in the realtime hooks — useGlobalAgentRealtime and useProjectRealtime invalidate ["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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread apps/web/src/lib/socket-client.ts Resolved
Comment thread apps/web/src/lib/socket-client.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 — recoveryAttempt now zeroes from a connect listener instead of immediately before current.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 incrementing recoveryAttempt, 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.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/refresh via isAuthRejection.
  • Added a single-flight recoveringSocket guard so a visibility change or token refresh cannot start a second refresh while one is in flight.
  • Added a mounted-down check to useGlobalAgentRealtime and a dedicated hook test suite.
  • Extended socket-client coverage 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 before connectSocket(), so mountedDown reflects 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 sets active to true, and the mounted-down test asserts that transition.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit 30f9d95 into master Nov 8, 2026
2 checks passed
@pikann
pikann deleted the feature/implement-socket-recovery-mechanism branch November 8, 2026 15:21
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.

1 participant