perf(hub,web): emit structured patches for session todos/teamState/metadata/agentState writes (closes #895, second half of #884)
Summary
Closes #895. Second half of #884 (paired with #885 for the first half — staleTime suppression for navigation thrash).
hub/src/socket/handlers/cli/sessionHandlers.ts has four CLI emit-sites that fire session-updated SSE events with no data payload when todos / teamState / metadata / agentState change. On the web side, useSSE.ts parses missing/empty data as "no patch I can apply" and falls through to per-session REST invalidation (queueSessionDetailInvalidation + queueSessionListInvalidation at web/src/hooks/useSSE.ts:509-512). On a 130-session install that's O(N) REST refetches every time any one session writes a todo or pings keep-alive — the dominant component of the storm described in #884.
This PR closes the gap end-to-end:
shared/src/schemas.ts— extendsSessionPatchSchemawith optionaltodos/teamState/metadata/agentStatefields. Versioned wrappers ({ version, value }) formetadataandagentStatemirror the existing socket.ioupdate-sessionbroadcast shape so downstream caches can reject stale patches.hub/src/socket/handlers/cli/sessionHandlers.ts— the four emit-sites now carry structured payload data instead of firingdata: undefined. Web hitsgetSessionPatch's truthy branch and patches the React Query cache in place; no REST refetch.hub/src/sync/sessionCache.ts— newapplySessionPatch()that mirrors the patch into the in-memory cache (no DB re-read). KeepsNotificationHub.getSession, sidebar dedup, and other in-process consumers coherent with what just landed in the DB. Returnsfalsefor empty{}patches and cross-namespace mismatches so the caller falls back to the legacy refresh path safely.hub/src/sync/syncEngine.ts—handleRealtimeEventfast-path: if the event has data andapplySessionPatchsucceeds, forward the patch as-is withoutrefreshSession's DB read + full-Session SSE broadcast. Falls back to legacy refresh on empty/unparseable patches.web/src/hooks/useSSE.ts—patchSessionDetailandpatchSessionSummaryunwrap the versionedmetadata/agentStatewrappers before assigning to the cached Session. Without unwrapping,session.metadatawould silently become{ version, value }and corrupt every consumer that readsmetadata.flavor,metadata.cursorSessionId, etc.
Subtle bug fixed in commit 2
applySessionPatch MUTATES the cached Session in place (reassigns session.metadata = patch.metadata.value). handleRealtimeEvent has a dedup-on-agent-session-id-change trigger that compares before.metadata vs after.metadata — both reads were going through sessionCache.getSession(id) which returns the SAME object reference, so the mutation overwrote before.metadata and hasSameAgentSessionIds always returned true. Dedup silently never fired on the fast path.
The legacy refreshSession path got dedup for free because it REPLACES the cache map entry with a new Session object, leaving the pre-refresh reference intact for the comparator.
Fix: snapshot the metadata reference before applySessionPatch runs and use the snapshot for both branches so the comparison contract is identical. Three regression tests in hub/src/sync/syncEngineHandleRealtimeEvent.test.ts — verified they FAIL on the un-fixed code and PASS on the fixed.
Commits
05147a6a— schema extension + emit-sites + cache patch path + web unwrap + tests.eaa0281f— snapshot metadata before mutation; regression tests for dedup fast-path.f261a790— pure cosmetic reorder ofSessionPatchSchemafield order so soup-merge with the codex-usage-indicator fork branch (which adds a flatmetadatafield at the same place upstream/main has the model fields) raises an explicit conflict instead of silently producing a duplicate-key object. No upstream impact.
Downstream compatibility
SessionPatchSchema is .strict(). Older web clients connecting to a newer hub will fail to parse patches carrying the new todos / teamState / wrapped metadata / wrapped agentState fields and fall back to the very REST invalidation this PR closes. The fix needs hub + web to ship together. Newer web clients against an older hub work fine — the hub just keeps firing the no-data events as before.
Test plan
- [x]
bun typecheckclean across cli / web / hub. - [x]
bun run test— hub 449 / 449 pass; the one CLI failure (runner.integration.test.ts > should detect version mismatch and kill old runner) is a pre-existing flake on the version-comparison assertion and is unrelated. - [x] New tests:
shared/src/schemas.sessionPatch.test.ts— 7 cases (bare todos, bare teamState, versioned metadata, versioned agentState with null, rejects metadata-without-version, rejects unknown keys, rejects full-Session payload).hub/src/sync/sessionCache.applySessionPatch.test.ts— 7 cases (todos / metadata-wrapped / agentState-wrapped-null / unknown session / bad schema / empty{}/ cross-namespace).hub/src/sync/syncEngineHandleRealtimeEvent.test.ts— 3 cases (metadata-change fires dedup on fast path, todos patch does NOT fire dedup, legacy refresh path still fires dedup).hub/src/socket/handlers/cli/sessionHandlers.test.ts— 3 cases extending the existing suite for the four emit-sites' structured payloads.shared/src/sessionSummary.test.ts—toSessionSummaryMetadataextraction tests.
- [ ] Operator empirical verification (in progress): branch is the topmost layer on the daily-driver soup; awaiting activation on the reporter's
:3006. Will report the before/afterjournalctl -u hapi-hub.serviceREST hit counts on the same 5-min idle window used in #884.
Related
- #884 — root issue (refetch storm on multi-session installs).
- #885 — first half (per-query
staleTimefor navigation thrash). Non-overlapping diff; this PR is independent. - #895 — verification / scope confirmation (this PR closes it).
- HAPI Bot pre-verified the scope on #895 13min before this PR opened: the four emit-sites and the patch-vs-refresh shape called out in the issue match the codebase exactly.
Made with Cursor
Addressed in f80d7bd9 - thanks for catching this; you're right, both the hub cache and the web fallback were broken on TeamDelete.
Applied your suggested fix in all four coordinated spots (wire ↔ cache contract):
shared/src/schemas.ts:teamState: TeamStateSchema.nullable().optional()sonullis the explicit clear signal on the wire (with a comment documenting the discriminator contract).hub/src/socket/handlers/cli/sessionHandlers.ts: dropped the?? undefinedcoalesce sonullsurvives JSON serialization.hub/src/sync/sessionCache.ts(applySessionPatch):Object.prototype.hasOwnProperty.call(patch, 'teamState')discriminates "absent" vs "null clear"; null → undefined to match the cachedSession.teamStateshape.web/src/hooks/useSSE.ts(patchSessionDetail): same hasOwnProperty + null → undefined pattern.
Regression tests:
shared/src/schemas.sessionPatch.test.ts: locks{ teamState: null }as a valid wire shape.hub/src/sync/sessionCache.applySessionPatch.test.ts: TeamDelete clears cached teamState; todos-only patch leaves teamState untouched (the second test guards the hasOwnProperty branch against a regression back to!== undefined).
bun typecheck + bun run test both clean for the affected packages (the one failure in the wider run was an unrelated flaky CLI runner integration test, no CLI code in this PR).
Addressed in 1f845149 - thanks, you're right about the reconnect-window vulnerability.
Mirrored the hub CLI room handler's incoming.version > currentVersion contract on the web side:
patchSessionDetail: gated metadata/agentState assignment behindisNewerVersionedPatch(patch.version, nextSession.<field>Version). The pre-patch version is captured by the{ ...previous.session }spread, so the comparison is against cache-at-write-time.patchSessionSummary: read the detail cache (viaqueryClient.getQueryData) for the canonicalmetadataVersion/agentStateVersion. Uses>=(not>) because the callsite runspatchSessionDetailfirst - when detail accepts a newer patch the cache already holds the new version, so>=keeps summary aligned with detail's acceptance; when detail rejects,>=aligns summary with detail's rejection. Defaults to 0 when detail isn't cached (allows first-write through).- Exported
isNewerVersionedPatch(patchVersion, currentVersion)as a pure helper so the rule is unit-testable. - Test:
useSSE.test.tspins the 4 cases (strictly newer ✓ / older ✗ / same-version ✗ / first-write currentVersion=0 ✓).
Hub side: I considered adding the same gate to sessionCache.applySessionPatch but didn't, because the in-process events from handleUpdateMetadata / handleUpdateState are emitted only AFTER the store's optimistic-concurrency check succeeds, and syncEngine.handleRealtimeEvent consumes them synchronously in order. The vulnerability is specifically the SSE reconnect/replay window on the web client. Happy to add the symmetric guard if you'd prefer defense-in-depth there too.
bun typecheck clean. Hub (431 pass), shared (94 pass), web useSSE.test.ts (7 pass) all green.