refactor(web): decompose useSessionSocket into focused layers
Summary
useSessionSocket was a 500+ line hook owning transport, authentication, reconnection, replay, event normalization, token accumulation, presence, artifacts, session projection, pagination, and SWR invalidation all at once. The protocol is inherently complex; its concentration in one hook was not.
This splits it into focused layers with the public API unchanged — no consumer (session/[id]/page.tsx, session-header.tsx) is touched, and the existing 17-test hook suite passes unmodified as a regression proof.
Layers
| Module | Owns |
|---|---|
hooks/use-session-transport.ts |
the wire: token fetch/auth, connect + subscribe handshake, message schema validation, close-code handling (4001/4002), exponential-backoff reconnect, keepalive pings, send |
lib/session-socket/event-log.ts |
the displayable event log and its one invariant: token events carry cumulative text, so show exactly one final token per message — collapseReplayTokenEvents (replay path) and the pure step function ingestLiveSandboxEvent(pending, event) → { pending, append } (live path), plus timestamp defaulting |
lib/session-socket/artifact-metadata.ts |
wire→UI artifact mapping: metadata field narrowing and PR display-status derivation |
lib/session-socket/reducer.ts |
pure view projection: session state, events, participants, artifacts, replay flag, pagination cursor, session_branch multi-repo routing, sandbox access-state clearing, step cost accumulation |
lib/session-socket/swr-revalidation.ts |
which SWR caches (sidebar session list, child list) a server message invalidates — pure key derivation; the composing hook is the single place that calls mutate |
useSessionSocket itself shrinks to ~200 lines of composition: it routes sandbox_events through the token buffer (kept in a ref so high-frequency token frames still don't re-render), dispatches everything else to the reducer, and applies the derived revalidation keys.
Each module is named for the domain concept it owns rather than a pattern ("adapters"/"cache"), so the file name answers what's inside.
Behavior preserved
- Streamed token text is still buffered in a ref and only rendered on
execution_complete/stop — no new render per token frame. - Reconnect backoff, close-code semantics, subscribe-retry in
sendPrompt, optimisticisProcessing, and PR-gated sidebar revalidation are unchanged (existing hook tests cover these paths).
One intentional deletion: currentParticipantRef was written in two places but never read — dead state, removed rather than carried over.
New tests (+56)
event-log.test.ts— replay collapsing, token buffering/flush semantics, timestamp defaultingartifact-metadata.test.ts— metadata narrowing and PR-state derivationreducer.test.ts— subscribe hydration/resync, cost accumulation guards, history paging, presence, sandbox access-state clearing matrix, multi-reposession_branchroutingswr-revalidation.test.ts— the full revalidation surfaceuse-session-transport.test.tsx— handshake, message validation, 401/4001/4002 handling, backoff timing, attempt exhaustion, keepalive
Test plan
- [x]
npm test -w @open-inspect/web— 764 passed (69 files), including the pre-existinguse-session-socket.test.tsxuntouched - [x]
npm run typecheck - [x]
npm run lint
Summary by CodeRabbit
-
New Features
- More reliable real-time session connectivity with improved authentication handling, reconnection behavior, and keepalive.
- Streamed assistant output and replayed tokens now render more consistently, with correct history, presence, participants, and artifact updates.
- Artifacts now show richer, validated metadata (including pull-request state) and better preview handling.
- Session-related views refresh automatically when relevant session activity occurs.
-
Bug Fixes
- Fixed edge cases around interrupted executions, reconnect timing, late socket events, token replay/collapsing, and history/pagination state.
[!WARNING]
Review limit reached
@ColeMurray, you've reached your PR review limit, so we couldn't start this review.Next review available in: 14 minutes
Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. You're only billed for reviews past your plan's rate limits ($0.25/file).
How can I continue?
After more reviews become available, a review can be triggered using the
@coderabbitai reviewcommand as a PR comment. Alternatively, push new commits to this PR.To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.
How do review limits work?
CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.
For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.
Please refer docs for additional details.
Review details
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
52da77e9-6fdc-4504-bd2e-d22db8a9524e📥 Commits
Reviewing files that changed from the base of the PR and between f9b1ba5bd32d6277e37d4fa05848180dc1e40372 and 5bba3450da3985f81c79d212e9021a7692d5763b.
📒 Files selected for processing (1)
packages/web/src/hooks/use-session-transport.ts
📝 Walkthrough
Walkthrough
The session socket client now uses a dedicated WebSocket transport hook, reducer-based state projection, event and artifact adapters, and targeted SWR cache revalidation. Tests cover transport lifecycle, event processing, reducer behavior, artifact metadata, and cache invalidation.
Changes
Session socket refactor
| Layer / File(s) | Summary |
|---|---|
WebSocket transport and lifecycle packages/web/src/hooks/use-session-transport.ts, packages/web/src/hooks/use-session-transport.test.tsx |
Adds token-based subscription, validated message forwarding, keepalive pings, close-code handling, reconnect backoff, manual reconnect, and transport lifecycle tests. |
Session event and artifact adapters packages/web/src/lib/session-socket/event-log.ts, packages/web/src/lib/session-socket/event-log.test.ts, packages/web/src/lib/session-socket/artifact-metadata.ts, packages/web/src/lib/session-socket/artifact-metadata.test.ts |
Normalizes event timestamps, collapses replay tokens, buffers live assistant text, reconstructs pending tokens, and narrows wire artifact metadata into UI artifacts. |
Reducer state projection packages/web/src/lib/session-socket/reducer.ts, packages/web/src/lib/session-socket/reducer.test.ts |
Projects subscription, history, presence, sandbox, artifact, branch, metadata, event, and local actions into session state with reducer coverage. |
Session hook orchestration and cache updates packages/web/src/hooks/use-session-socket.ts, packages/web/src/lib/session-socket/swr-revalidation.ts, packages/web/src/lib/session-socket/swr-revalidation.test.ts |
Composes transport and reducer state, implements prompt, stop, typing, and history commands, exposes presence projections, and revalidates SWR keys for relevant server messages. |
Estimated code review effort: 4 (Complex) | ~60 minutes
Sequence Diagram(s)
sequenceDiagram
participant useSessionSocket
participant useSessionTransport
participant sessionSocketReducer
participant SWR
useSessionSocket->>useSessionTransport: connect and subscribe
useSessionTransport-->>useSessionSocket: validated ServerMessage
useSessionSocket->>sessionSocketReducer: dispatch server_message or events_appended
sessionSocketReducer-->>useSessionSocket: projected session state
useSessionSocket->>SWR: mutate affected cache keys
Possibly related PRs
- ColeMurray/background-agents#452: Modifies subscribed snapshot hydration and session branch handling used by the reducer.
- ColeMurray/background-agents#728: Modifies replayed assistant token ordering handled by the event-log layer.
- ColeMurray/background-agents#964: Modifies PR lifecycle metadata and artifact upserts handled by the new adapter and reducer.
Suggested reviewers: open-inspect
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 32.14% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title accurately summarizes the main change: splitting useSessionSocket into smaller focused layers. |
| 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. |
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Commit unit tests in branch
refactor/session-socket-decomposition
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.
Comment @coderabbitai help to get the list of available commands.
Terraform Validation Results
| Step | Status |
|---|---|
| Format | ✅ |
| Init | ✅ |
| Validate | ✅ |
Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.
Pushed by: @ColeMurray, Action: pull_request
Terraform Validation Results
| Step | Status |
|---|---|
| Format | ✅ |
| Init | ✅ |
| Validate | ✅ |
Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.
Pushed by: @ColeMurray, Action: pull_request
Addressed review feedback in 2239999e: dissolved the catch-all adapters.ts and cache.ts into concept-named modules — event-log.ts (the one-final-token-per-message invariant, replay + live paths), artifact-metadata.ts (wire→UI artifact narrowing), and swr-revalidation.ts (which SWR caches a message invalidates). parseWsMessage moved into the transport as a private helper since wire validation belongs there and it had no other caller. No behavior change; PR body table updated.
Terraform Validation Results
| Step | Status |
|---|---|
| Format | ✅ |
| Init | ✅ |
| Validate | ✅ |
Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.
Pushed by: @ColeMurray, Action: pull_request
Both review-body nitpicks addressed in f9b1ba5b. Added the hasAudio narrowing and lifecycleState: "merged" tests (in artifact-metadata.test.ts — adapters.test.ts was renamed in 2239999e). For the sync-close limitation: rather than making FakeWebSocket.close() globally async (which would churn every existing test), the new stale-close regression test replays the discarded socket's onclose after its replacement is live — the exact interleaving the sync fake hides — and the transport now nulls wsRef before closing so behavior is identical under both timings.
Terraform Validation Results
| Step | Status |
|---|---|
| Format | ✅ |
| Init | ✅ |
| Validate | ✅ |
Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.
Pushed by: @ColeMurray, Action: pull_request
Terraform Validation Results
| Step | Status |
|---|---|
| Format | ✅ |
| Init | ✅ |
| Validate | ✅ |
Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.
Pushed by: @ColeMurray, Action: pull_request