Skip to content

feat: tRPC subscriptions over WebSocket for cross-user status sync - #8

Merged
iskhakovt merged 3 commits into
mainfrom
feat/websocket-status-subscription
Apr 10, 2026
Merged

iskhakovt merged 3 commits into
mainfrom
feat/websocket-status-subscription

Conversation

@iskhakovt

Copy link
Copy Markdown
Owner

Summary

Replaces the 5s/30s polling in useGroupStatus with a tRPC v11 subscription delivered via @trpc/server/adapters/ws. Updates that used to wait up to 5s for the next poll cycle now arrive in well under a second, the long-standing E2E flakiness around two-player.spec.ts:42 is gone, and the polling fallback stays in place for environments where WS is blocked (CF Tunnel buffering, corporate proxies, etc).

Architecture

Browser                                  Hono server (port 8080)
  |  HTTP queries/mutations --------------->|  /api/trpc       (existing)
  |                                         |
  |  WS upgrade /api/trpc-ws -------------->|  server.on('upgrade')
  |  + connectionParams: { token } -------->|    -> wss.handleUpgrade
  |<------ subscription stream -------------|    -> applyWSSHandler
  |                                         |
  |  [tRPC mutation] ---------------------->|  broadcastingProcedure
  |<-- subscription yields new status ------|  emit -> subscribers
  |                                         |
  |  [WS dies] ...                          |  client falls back
  |  [polling fallback] ------------------->|  to /api/trpc polling
  • WS server uses noServer: true and shares the existing HTTP server via server.on('upgrade'). Routes /api/trpc-ws and leaves other paths alone for HMR / future use.
  • splitLink routes subscriptions over wsLink and queries/mutations over httpBatchLink — defense in depth: if WS dies, mutations still work and the polling fallback covers reads.
  • useGroupStatus API surface is unchanged; PersonApp.tsx needs no edits.

Key design decisions

  1. sync.push does NOT broadcast. It fires every 3s per active user during questionnaire flow — too noisy. Progress is cosmetic and the polling fallback keeps waiting screens in sync.
  2. Async generator subscription pattern, not the deprecated observable. node:events's on(emitter, evt, { signal }) handles cleanup automatically.
  3. Listener registered before initial yield. Events that fire in the window between the initial state fetch and the consumer's next pull are queued by on() (not lost).
  4. Public procedure (not authed) so it works during the brief pre-setupAdmin window where the URL holds an admin token but no person record exists. Caught during E2E debug — without this, the WS subscription dies on first mount and never recovers, defeating the whole point.
  5. Personalised broadcasts. Each subscriber re-runs getStatus(token) so each gets their own person field. 2-6 queries per group event is negligible.
  6. lazy: { enabled: true, closeMs: 5_000 } on the wsClient — defers connection until first subscription so connectionParams reads the auth token after setSession() has run.

Known limitation

If a user navigates between two /p/:token URLs in the same tab (rare — normally a fresh page load), the existing WS keeps its original auth context. New subscriptions still go through the same connection and would be authorized as the previous person. The polling fallback recovers within pollMs and a hard reload fixes it permanently. Documented in packages/web/src/lib/trpc.ts.

E2E timeout audit

File:line Old New Why
two-player.spec.ts:37-43 15-20s 3s Cross-user — WS push delivers in <100ms
self-pick-flow.spec.ts:56 20s 3s Same — Alice receives Bob's anatomy broadcast
multi-tab, refresh, sync-conflict 10s unchanged In-tab or local-debounce, not affected
Globals (60s test, 10s action/expect) unchanged Sane defaults stay

Test plan

  • pnpm typecheck (3 packages)
  • pnpm lint
  • pnpm test — 207 unit tests pass (added 17: events module + broadcasting middleware coverage)
  • pnpm test:integration — 21 integration tests pass (added 11: subscription via real Postgres covering initial yield, broadcasts, personalisation, multi-subscriber, no-broadcast on push, encrypted, missing/unknown/admin tokens, listener cleanup)
  • pnpm test:e2e — 32 E2E tests pass in 58s (added 2 realtime tests: WS happy path with sub-2s assertion, polling fallback via blocked WS)

Files

Server

  • packages/server/src/events.ts — new shared EventEmitter
  • packages/server/src/trpc/init.ts — broadcastingProcedure middlewares
  • packages/server/src/trpc/context.ts — personToken field, createWSContext
  • packages/server/src/trpc/routes/groups.ts — onStatus subscription, swap to broadcasting procedures
  • packages/server/src/trpc/routes/sync.ts — swap markComplete / unmarkComplete to broadcasting (push intentionally not)
  • packages/server/src/index.ts — WebSocketServer({ noServer: true }) + applyWSSHandler + upgrade routing

Client

  • packages/web/src/lib/trpc.ts — splitLink + wsLink + lazy createWSClient
  • packages/web/src/lib/use-group-status.ts — subscription + polling fallback (same external API)
  • packages/web/vite.config.ts — /api/trpc-ws proxy with ws: true

🤖 Generated with Claude Code

iskhakovt and others added 3 commits April 10, 2026 11:41
Replaces 5s/30s polling in useGroupStatus with a tRPC v11 subscription
delivered via @trpc/server/adapters/ws on the same Hono HTTP server.
Polling stays as a fallback so the app degrades gracefully when WS is
blocked (CF Tunnel buffering, corporate proxies, etc).

Server:
- Add ws + @types/ws deps
- packages/server/src/events.ts: shared EventEmitter keyed by group:<id>
- broadcastingProcedure / broadcastingAdminProcedure middlewares emit
  after successful mutations (markComplete, unmarkComplete, setProfile,
  addPerson, removePerson, markReady). sync.push intentionally stays
  out — its 3s debounce per user would be too noisy and progress is
  cosmetic, covered by the polling fallback.
- groups.onStatus subscription: async generator pattern (recommended in
  v11), public so it works with admin tokens during the pre-setupAdmin
  window. The event listener is registered before the initial yield so
  broadcasts that fire in the yield window are queued (not lost).
- WS server uses noServer:true and shares the existing HTTP server via
  server.on('upgrade'); routes /api/trpc-ws and leaves other paths for
  Vite HMR / future use.

Client:
- splitLink routes subscriptions to wsLink, queries/mutations stay on
  httpBatchLink — defense in depth, mutations work even if WS dies.
- createWSClient uses lazy mode so the connection waits for setSession
  to populate the auth token before opening (avoids spurious unauth
  errors on initial mount).
- useGroupStatus subscribes via tRPC and tracks wsConnected state;
  polling only runs while WS is not delivering. The hook's external
  API is unchanged so PersonApp needs no edits.
- Vite dev proxy adds /api/trpc-ws (must come before /api).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…meouts

Unit tests (vitest, mocked stores):
- events.test.ts: emitGroupUpdate fires the right event, max-listeners=0
- sync.test.ts: broadcastingProcedure fires after markComplete /
  unmarkComplete; does NOT fire on validation errors / unauth /
  successful sync.push
- groups.test.ts: same coverage for setProfile, addPerson, removePerson,
  markReady (admin variants); negative cases for store throws and
  failed admin checks

Integration tests (real Postgres via testcontainers):
- groups.subscription.integration.test.ts (10 tests): drives the
  subscription via createCallerFactory with a real AbortController
  signal. Covers initial yield, broadcasts on markComplete and
  setProfile, personalised payloads per subscriber, multi-subscriber
  fan-out, no-broadcast on push, encrypted blobs, missing/unknown
  token rejection, admin-token pre-setupAdmin window, listener
  cleanup on cancel.

E2E tests (Playwright):
- realtime-status.spec.ts: 1) Alice's waiting screen updates
  sub-second when Bob marks done (WS happy path); 2) polling
  fallback still delivers when WS upgrades are blocked via
  page.route().
- two-player.spec.ts: cross-user assertions tightened from 15-20s
  → 3s now that updates arrive via WS push instead of waiting up
  to 5s for the next poll cycle.
- self-pick-flow.spec.ts: same — Alice sees the group-ready
  broadcast within 3s after Bob picks anatomy (was 20s).

Test factories: authedCtx now accepts an optional personToken so
subscription tests can resolve groups by token.

todo.md: WebSockets/SSE item moved to Done.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…tokens

Replaces the publicProcedure admin-token fallback with the cleaner
"client gates on status.person" pattern:

- groups.onStatus reverts to authedProcedure — the server no longer
  special-cases admin tokens, and uses ctx.group.id / ctx.personToken
  directly (no more derive-group-id-from-getStatus dance)
- authedProcedure now also narrows personToken to non-null (it's
  always populated alongside person in buildContext); eliminates the
  non-null assertions biome was complaining about
- useGroupStatus gates the subscription useEffect on status.person.id,
  so the admin-token-pre-setupAdmin window simply doesn't mount a WS
  subscription (nothing to subscribe to — Alice is alone on the
  form). Once refresh() picks up the new status with a real person
  after setupAdmin, the effect re-runs and opens the subscription.
- mockCtx helpers default personToken to "mock-token" when person
  is provided, matching real-world usage
- Integration tests: consolidated no-token and bad-token cases under
  authedProcedure's single rejection path; dropped the now-obsolete
  "works with admin token" test
- Bumped two-player and self-pick-flow cross-user timeouts from 3s
  to 5s — occasional flakes under parallel CI load when the gated
  subscription opens slightly later than before

Why B over A: the data invariant ("subscribe iff we have a person")
is more robust than the admin-token special case. Future pre-setup
screens get the right behaviour automatically. Bad tokens fail
gracefully (subscription never opens) instead of opening + rejecting.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@iskhakovt
iskhakovt merged commit e523615 into main Apr 10, 2026
5 checks passed
@iskhakovt
iskhakovt deleted the feat/websocket-status-subscription branch April 10, 2026 13:53
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 1.1.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

iskhakovt added a commit that referenced this pull request Apr 10, 2026
Replaces the hand-rolled useGroupStatus hook with useLiveStatus built on
TanStack Query's useSuspenseQuery + tRPC's useSubscription.

New hook (packages/web/src/lib/use-live-status.ts):
- useSuspenseQuery(trpc.groups.status.queryOptions({ token })) — initial
  fetch suspends until data lands, then serves from cache
- useSubscription(trpc.groups.onStatus.subscriptionOptions(...)) — each
  onData push writes the raw payload into the same cache entry via
  queryClient.setQueryData, so the query and subscription share one
  source of truth
- Async decryption runs in a useEffect keyed on the raw cache value —
  the cache stores encrypted payloads, components read the derived
  decrypted state (matches existing crypto semantics)
- Subscription gated on `personId !== null` — during /setup, the authed
  procedure has nothing to stream, so we leave the WS closed
- Same API surface as the old hook (`{ status, refresh }`) so call sites
  don't need to change

PersonApp:
- Drops useGroupStatus import, uses useLiveStatus
- Adds token-change effect: when the URL token changes (rare — normally
  a fresh page load), close the WS so connectionParams re-runs with the
  new token, and invalidate sync/questions caches that aren't naturally
  keyed by token. Fixes the PR #8 wsLink-stale-auth caveat.
- groups.status is keyed by `{ token }` in the cache so natural
  segregation handles cross-token contamination for that query

Deleted:
- packages/web/src/lib/use-group-status.ts

Bundle size: +13KB gzipped (TanStack Query core), within budget.
Build verified with vite build; all 235 tests still pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 10, 2026
…kiness

Under parallel E2E load (~18 concurrent browser contexts on one machine),
cross-user assertions like 'Alice & Bob visible' were flaking because the
old pattern added an extra render cycle between 'data arrived' and 'content
visible':

  render(raw) → useEffect fires → async decrypt → setState → render(decrypted)

Two React commits + one microtask + repaint, repeated on every mount and
every WS push. Under CPU contention this added enough latency to blow past
the 10s default expect timeout on tests that had already been tightened in
PR #8.

Fix: push the async decryption into the queryFn itself so Suspense holds
the component invisible until the derived data is fully ready, then the
first render paints the final content in one pass.

useLiveStatus:
- Override the tRPC proxy's queryOptions.queryFn with a wrapper that awaits
  decryptStatus before returning. The cache now stores the decrypted shape,
  and the component reads it directly from useSuspenseQuery.
- Drop the useState + useEffect for status derivation — no more loading/
  error intermediate states tracked in the hook. Loading is handled by the
  outer Suspense boundary, errors propagate to the nearest ErrorBoundary.
- Subscription onData async-decrypts before setQueryData. A per-hook
  monotonic sequence counter (seqRef) guards against out-of-order decryption
  when two pushes arrive in quick succession — latest wins.

Comparison.tsx:
- Use useTRPCClient() to get a vanilla tRPC client, then construct the
  useSuspenseQuery options from scratch: queryKey from the proxy (for
  stable cache lookups), queryFn owns the fetch + replayMembers call.
- Cache shape is CachedJournal = { members: MemberAnswers[], entries, cursor }
  with members pre-decrypted and per-question answers already replayed.
  First paint has memberAnswers ready — no mount→useEffect→setState cycle.
- Subscription onData async-merges (dedup + replay) and calls setQueryData
  with the full derived shape. Monotonic sequence counter guards against
  out-of-order replays.
- Drop the useState<MemberAnswers[] | null> + useEffect that was the
  old render-cycle bottleneck.
- Extract replayMembers() helper so both queryFn and onData share the
  per-member decrypt + replay logic.

PersonApp.tsx:
- Drop the 'status === "loading"' and 'status === "error"' branches from
  the render path. useLiveStatus no longer returns those sentinels — the
  Suspense boundary in main.tsx handles loading, the ErrorBoundary handles
  errors with resetErrorBoundary for retry.

Pattern validation: this is the canonical TanStack Query + Suspense pattern
per TkDodo's "Data Transformations" (option 1: transform in queryFn) and
"Using WebSockets with React Query" (setQueryData for targeted merges).
Also confirmed as the React-19-era best practice for async-derived state
that needs Suspense-aware first-render data — React.use() explicitly does
not support client-created promises, and Jotai async atoms would require
adopting a second state library for one screen's worth of data.

Results: full E2E suite passes cleanly under parallel load (34/34), where
previously 1-2 cross-user assertions were flaking per run.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 11, 2026
Replaces the hand-rolled useGroupStatus hook with useLiveStatus built on
TanStack Query's useSuspenseQuery + tRPC's useSubscription.

New hook (packages/web/src/lib/use-live-status.ts):
- useSuspenseQuery(trpc.groups.status.queryOptions({ token })) — initial
  fetch suspends until data lands, then serves from cache
- useSubscription(trpc.groups.onStatus.subscriptionOptions(...)) — each
  onData push writes the raw payload into the same cache entry via
  queryClient.setQueryData, so the query and subscription share one
  source of truth
- Async decryption runs in a useEffect keyed on the raw cache value —
  the cache stores encrypted payloads, components read the derived
  decrypted state (matches existing crypto semantics)
- Subscription gated on `personId !== null` — during /setup, the authed
  procedure has nothing to stream, so we leave the WS closed
- Same API surface as the old hook (`{ status, refresh }`) so call sites
  don't need to change

PersonApp:
- Drops useGroupStatus import, uses useLiveStatus
- Adds token-change effect: when the URL token changes (rare — normally
  a fresh page load), close the WS so connectionParams re-runs with the
  new token, and invalidate sync/questions caches that aren't naturally
  keyed by token. Fixes the PR #8 wsLink-stale-auth caveat.
- groups.status is keyed by `{ token }` in the cache so natural
  segregation handles cross-token contamination for that query

Deleted:
- packages/web/src/lib/use-group-status.ts

Bundle size: +13KB gzipped (TanStack Query core), within budget.
Build verified with vite build; all 235 tests still pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 11, 2026
…kiness

Under parallel E2E load (~18 concurrent browser contexts on one machine),
cross-user assertions like 'Alice & Bob visible' were flaking because the
old pattern added an extra render cycle between 'data arrived' and 'content
visible':

  render(raw) → useEffect fires → async decrypt → setState → render(decrypted)

Two React commits + one microtask + repaint, repeated on every mount and
every WS push. Under CPU contention this added enough latency to blow past
the 10s default expect timeout on tests that had already been tightened in
PR #8.

Fix: push the async decryption into the queryFn itself so Suspense holds
the component invisible until the derived data is fully ready, then the
first render paints the final content in one pass.

useLiveStatus:
- Override the tRPC proxy's queryOptions.queryFn with a wrapper that awaits
  decryptStatus before returning. The cache now stores the decrypted shape,
  and the component reads it directly from useSuspenseQuery.
- Drop the useState + useEffect for status derivation — no more loading/
  error intermediate states tracked in the hook. Loading is handled by the
  outer Suspense boundary, errors propagate to the nearest ErrorBoundary.
- Subscription onData async-decrypts before setQueryData. A per-hook
  monotonic sequence counter (seqRef) guards against out-of-order decryption
  when two pushes arrive in quick succession — latest wins.

Comparison.tsx:
- Use useTRPCClient() to get a vanilla tRPC client, then construct the
  useSuspenseQuery options from scratch: queryKey from the proxy (for
  stable cache lookups), queryFn owns the fetch + replayMembers call.
- Cache shape is CachedJournal = { members: MemberAnswers[], entries, cursor }
  with members pre-decrypted and per-question answers already replayed.
  First paint has memberAnswers ready — no mount→useEffect→setState cycle.
- Subscription onData async-merges (dedup + replay) and calls setQueryData
  with the full derived shape. Monotonic sequence counter guards against
  out-of-order replays.
- Drop the useState<MemberAnswers[] | null> + useEffect that was the
  old render-cycle bottleneck.
- Extract replayMembers() helper so both queryFn and onData share the
  per-member decrypt + replay logic.

PersonApp.tsx:
- Drop the 'status === "loading"' and 'status === "error"' branches from
  the render path. useLiveStatus no longer returns those sentinels — the
  Suspense boundary in main.tsx handles loading, the ErrorBoundary handles
  errors with resetErrorBoundary for retry.

Pattern validation: this is the canonical TanStack Query + Suspense pattern
per TkDodo's "Data Transformations" (option 1: transform in queryFn) and
"Using WebSockets with React Query" (setQueryData for targeted merges).
Also confirmed as the React-19-era best practice for async-derived state
that needs Suspense-aware first-render data — React.use() explicitly does
not support client-created promises, and Jotai async atoms would require
adopting a second state library for one screen's worth of data.

Results: full E2E suite passes cleanly under parallel load (34/34), where
previously 1-2 cross-user assertions were flaking per run.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 11, 2026
* chore(web): add TanStack Query v5 + tRPC integration

Installs @tanstack/[email protected], @trpc/[email protected],
and @tanstack/[email protected] (dev) in preparation for the
TanStack Query migration.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(web): add TanStack Query providers and context

Scaffolding for the TanStack Query migration, no behavior change yet.

- query-client.ts: makeQueryClient factory with defaults aligned to the real-time
  architecture (staleTime Infinity, no background refetch, no polling — live updates
  arrive via WS subscriptions).
- trpc-providers.tsx: AppProviders wrapping QueryClientProvider + TRPCProvider,
  with stable clients via useState. Devtools dynamically imported in DEV only.
- trpc.ts: adds createTRPCContext bindings (TRPCProvider, useTRPC, useTRPCClient)
  alongside the legacy singleton. Exports wsClient so token-change handlers can
  force reconnect.
- main.tsx: wraps the router in <AppProviders> + a top-level Suspense boundary.

The legacy trpc singleton is kept temporarily so existing .query()/.mutate()
call sites keep working until they're migrated in later commits.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(server): rename sync.compare to sync.journal with cursor

Renames the read-side of the sync protocol to better match what it actually
does (fetch journal entries, not "compare" — the client does the comparing).
Adds cursor-based delta semantics in preparation for the tracked() subscription
that will stream journal updates in real-time.

Store:
- SyncStore.compare(groupId) → SyncStore.journalSince(groupId, sinceId)
- Accepts a nullable cursor; null returns all entries, numeric returns id > N
- Returns { members, entries, cursor } where cursor = highest id in response
  (or the input sinceId on empty delta, so repeated fetches don't regress)
- Each entry now carries its numeric id so clients can track the cursor

Route:
- sync.compare → sync.journal with { sinceId: number | null } input
- Precondition check (all members complete) unchanged

Tests:
- Store: new cases for null cursor (full journal), non-null cursor (delta),
  empty delta (cursor unchanged), members populated on empty, precondition
  failure with and without cursor
- Route: passes sinceId through, defaults to null, throws on not_all_complete
- Integration: full roundtrip including edit-while-complete + cursor advance +
  empty delta on re-fetch

Client:
- Comparison.tsx: updated to call trpc.sync.journal (temporary; gets fully
  rewritten in a later commit)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(server): sync.onJournalChange subscription with tracked() resume

Adds real-time journal delivery via tRPC v11's tracked() pattern, with
lossless reconnect recovery via the lastEventId cursor protocol.

Event bus:
- New journalEvents EventEmitter in events.ts, separate from groupEvents
  (status broadcasts vs journal appends have different emission rates and
  different consumers)
- emitJournalUpdate(groupId, entries) takes the committed entries payload
- journalEventName(groupId) produces "journal:<id>" keys

Store:
- SyncStore.push now returns committedEntries alongside the existing
  entries/stoken/pushRejected fields, so the route can propagate them

Route:
- sync.push emits journalEvents after successful non-rejected commits.
  Unconditional (no isCompleted check) — if no one is subscribed during
  normal answering, emit is a no-op. Subscriber gating happens client-side
  via Comparison mount.
- committedEntries is stripped from the wire response (internal-only).
- New onJournalChange subscription following the canonical tRPC pattern:
  1. Precondition check (all members complete)
  2. Attach event listener BEFORE backfill query (anything emitted during
     the query is buffered in the iterable, not lost)
  3. Backfill via journalSince(groupId, lastEventId)
  4. Yield backfill as a single tracked() event
  5. Stream live emissions with cursor-based dedup for backfill/live overlap
- Explicit TrackedEnvelope type alias to sidestep TypeScript declaration
  emit complaints about the internal unstable-core-do-not-import path

Typecheck config:
- Drop composite/declaration from server tsconfig (never actually used —
  web imports server source directly via moduleResolution: bundler)
- Replace server's `tsc --build` typecheck with `tsc --noEmit`
- Web tsconfig includes server's router.ts directly in its "include" list
- This fixes TS2883 errors from tracked() type inference leaking through
  declaration emit

Tests:
- events.test.ts: add journalEvents suite mirroring groupEvents (emit, key
  namespacing, bus independence)
- sync.test.ts: add push emission tests (success/rejected/validation/empty
  committedEntries/no groupEvents), strip committedEntries from wire
- sync.integration.test.ts: full roundtrip tests now use the new journal
  protocol including cursor delta
- sync.journal-subscription.integration.test.ts (NEW): 10 integration
  scenarios covering the canonical subscribe-before-query pattern, cursor
  resume, concurrent subscribers, precondition failure, encrypted payload
  passthrough, and listener cleanup on abort

E2E config:
- vitest integration project gets fileParallelism: false so the two
  subscription integration test files don't deadlock on shared Postgres

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(web): migrate groups.status to TanStack Query + WS subscription

Replaces the hand-rolled useGroupStatus hook with useLiveStatus built on
TanStack Query's useSuspenseQuery + tRPC's useSubscription.

New hook (packages/web/src/lib/use-live-status.ts):
- useSuspenseQuery(trpc.groups.status.queryOptions({ token })) — initial
  fetch suspends until data lands, then serves from cache
- useSubscription(trpc.groups.onStatus.subscriptionOptions(...)) — each
  onData push writes the raw payload into the same cache entry via
  queryClient.setQueryData, so the query and subscription share one
  source of truth
- Async decryption runs in a useEffect keyed on the raw cache value —
  the cache stores encrypted payloads, components read the derived
  decrypted state (matches existing crypto semantics)
- Subscription gated on `personId !== null` — during /setup, the authed
  procedure has nothing to stream, so we leave the WS closed
- Same API surface as the old hook (`{ status, refresh }`) so call sites
  don't need to change

PersonApp:
- Drops useGroupStatus import, uses useLiveStatus
- Adds token-change effect: when the URL token changes (rare — normally
  a fresh page load), close the WS so connectionParams re-runs with the
  new token, and invalidate sync/questions caches that aren't naturally
  keyed by token. Fixes the PR #8 wsLink-stale-auth caveat.
- groups.status is keyed by `{ token }` in the cache so natural
  segregation handles cross-token contamination for that query

Deleted:
- packages/web/src/lib/use-group-status.ts

Bundle size: +13KB gzipped (TanStack Query core), within budget.
Build verified with vite build; all 235 tests still pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(web): dedupe questions.list via useSuspenseQuery

Replaces the three separate imperative trpc.questions.list.query() calls
in PersonApp, Question, and Comparison with useSuspenseQuery pointing at
the same cache entry. First mount fetches; subsequent mounts (in Question
and Comparison) serve synchronously from cache under staleTime: Infinity.

PersonApp:
- Drops useState+useEffect for questionsData, reads from useSuspenseQuery
- Removes the null-check branches around Summary/Review routes (suspense
  handles loading via the top-level boundary in main.tsx)

Question:
- useSuspenseQuery for questions.list
- Derives categoryMap via useMemo instead of setState
- Removes "Loading questions..." empty state (suspense handles it)
- Retains the auto-select-all-categories + pending-ops flush effect

Comparison:
- Drops questions.list from the Promise.all — uses useSuspenseQuery instead
- Derives questions/categories/categoryOrder/questionOrder via useMemo
- Keeps the sync.journal imperative fetch (gets rewritten in the next
  commit as part of the subscription-driven Comparison rewrite)

Net effect: questions.list fires once per session instead of three times.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(web): Comparison rewrite — query + tracked subscription + merge

Rewrites Comparison.tsx to use the canonical tRPC v11 pattern of HTTP
query for initial load + tracked subscription for live updates, both
feeding the same TanStack cache entry via setQueryData merge.

Data flow:
1. useSuspenseQuery(trpc.sync.journal, { sinceId: null }) — initial backfill,
   suspends until data lands
2. useSubscription(trpc.sync.onJournalChange, { lastEventId }) — live stream,
   seeded with the cursor from the HTTP response so it doesn't re-backfill
3. onData merges new entries into the cache via setQueryData with the
   mergeJournal helper (dedup by id, sort, cursor advance)
4. A useEffect runs async decryption + replay per member when entries change
5. Both the HTTP query and WS subscription write to the SAME cache key, so
   the read side (via useSuspenseQuery's data) automatically reflects
   incremental updates

Reconnect is lossless by construction: wsLink auto-reconnects and re-sends
the subscription message with the latest tracked id, so the server's
generator replays entries > lastEventId. If WS permanently fails, the
initial HTTP backfill still works — degraded to no-live-updates, but the
page is functional.

Edit-while-complete delivery:
- Alice edits a question on /questions (while marked complete)
- sync.push commits the new journal entry
- Server emits on journalEvents
- Bob's sync.onJournalChange subscription yields a tracked append
- Bob's onData merges into his cache
- Bob's Comparison re-renders with updated pair matches within ~100ms

New: packages/web/src/lib/merge-journal.ts
- Pure helper: dedupes by id (new wins), sorts ascending, advances cursor
- Reference-stable on empty delta to avoid unnecessary re-renders
- 9 unit tests covering all merge cases

Deleted imports:
- Removed trpc (legacy singleton) import from Comparison — it now uses the
  proxy via useTRPC()

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(web): migrate all mutations to useMutation + automatic invalidation

Converts every direct trpc.x.mutate() call site to useMutation via the
tRPC tanstack-react-query proxy, with onSuccess invalidation replacing
the manual refreshStatus threading pattern.

- Landing.tsx: groups.create → useMutation
- GroupSetup.tsx: groups.setupAdmin → useMutation. Invalidation deferred
  to the "Start filling out" button click so the "You're all set" screen
  with partner links stays visible until the user explicitly proceeds
- Invite.tsx: groups.addPerson → useMutation with onSuccess invalidation
- PersonApp.tsx: groups.markReady, sync.markComplete, sync.unmarkComplete
  all wired at the top level with shared invalidateStatus helper.
  NonAdminOnboarding and PickAnatomyScreen subcomponents each get their
  own groups.setProfile mutation with invalidation.
- sync.unmarkComplete also invalidates sync.journal so re-entering /results
  refetches with the latest entries.

Drops the `onDone` / `refreshStatus()` threading everywhere — mutations
self-invalidate via onSuccess which returns the invalidation promise,
keeping the mutation pending until the refetch completes. No more stale
guards from forgotten awaits.

Question.tsx's sync.push calls are intentionally NOT migrated in this
commit — those get extracted into useSyncQueue in the next commit.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(web): extract useSyncQueue hook for sync.push debounce + conflict retry

Replaces Question.tsx's ref-chain-and-manual-state sync machinery with a
self-contained useSyncQueue hook built on useMutation(trpc.sync.push).

New file: packages/web/src/lib/use-sync-queue.ts
- useSyncQueue(totalQuestions) returns { syncing, showSyncIndicator, handleSync, scheduleSync }
- Owns the 3-second debounce timer + the 5-second sync-indicator delay
- Owns the in-flight guard (replaces syncingRef) via a private ref
- Owns the conflict merge + retry loop (via mergeAfterRejection)
- useMutation's isPending replaces the manual setSyncing state

Question.tsx cleanup:
- Drops handleSyncRef, syncingRef, syncTimerRef, syncIndicatorTimerRef
- Drops inline pushOps / handleConflict / handleSync functions
- Drops manual imports of clearPendingOps, getStoken, mergeAfterRejection,
  setAnswers, setStoken (all moved into the hook)
- handleMarkComplete now calls hook's handleSync then markCompleteMutation
- Auto-sync effect becomes a single scheduleSync(pendingOps.length) call
- Keyboard navigation keeps handleRatingRef/handleTimingRef refs since those
  closures still need fresh state per render (separate concern from sync)
- sync.markComplete migrated to useMutation with onSuccess invalidation

Net: Question.tsx loses ~60 lines of ref-chain plumbing. The useSyncQueue
hook will also be the integration point for future debounce tuning or
offline queue persistence, without touching screen components.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(web): edit-without-unmark UX — "Edit my answers" navigates without mutating

Implements Design B: marked-complete users can return to /questions and edit
their answers without triggering sync.unmarkComplete, so partners viewing
/results see their edits propagate live via the journal subscription instead
of being abruptly kicked to /waiting.

- Add /questions to freeRoutes so the guard doesn't redirect marked-complete
  users away from it. The user got there intentionally (via an explicit
  "Edit my answers" or "Change my answers" button).
- Remove the sync.unmarkComplete useMutation definition — no UI caller
  remains. The server procedure stays as a safety valve for future admin
  tools.
- /results "Change my answers" button: now navigates only, no mutation.
- /waiting: add a new "Edit my answers" button (ghost styling, underlined)
  between the member list and the admin-only "View group members" link.
  Same semantics — navigate to /questions, no mutation.

Partner-side behavior (when Alice edits):
- Alice's sync.push commits new journal entries → journalEvents emit
- Bob's sync.onJournalChange subscription yields a tracked append
- Bob's Comparison cache merges the new entries via setQueryData
- Bob's PairComparison re-renders with updated match classification
- Bob is never kicked from /results because allComplete stays true

This is the "propagate live, never mutate status implicitly" pattern agreed
during planning. E2E coverage comes in the next commit.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(web): remove legacy trpc singleton, use inferRouterOutputs for types

Removes the temporary \`export const trpc = makeTrpcClient()\` singleton
from packages/web/src/lib/trpc.ts. Every call site now goes through
\`useTRPC()\` from the createTRPCContext proxy.

- Drop \`trpc\` export from trpc.ts — only \`TRPCProvider\`, \`useTRPC\`,
  \`useTRPCClient\`, \`wsClient\`, and \`makeTrpcClient\` remain
- use-live-status.ts and PersonApp.tsx: replace \`typeof trpc.x.y.query\`
  type derivations with \`inferRouterOutputs<AppRouter>\` — cleaner, no
  runtime dependency on a value that no longer exists
- Add @trpc/server as a dev dep on packages/web for the inferRouterOutputs
  type import (it was already transitively available via @trpc/client and
  @trpc/tanstack-react-query, this just makes the direct import explicit)

Typecheck, lint, unit tests, and vite build all green. Bundle size
unchanged (~135KB gzipped for the main chunk).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* test(e2e): add edit-post-completion and reconnect-resume specs; drop polling fallback test

Three E2E changes to cover the new real-time architecture:

New: e2e/edit-post-completion.spec.ts
- "Alice edits an answer on /results, Bob sees the pair matches update live":
  two browser contexts complete, both reach /results, Alice clicks "Change my
  answers", edits one question from yes → no, waits for the 3s debounce, then
  asserts that Bob's pair match count dropped. Verifies the full edit-while-
  complete pipeline: sync.push → journalEvents emit → Bob's subscription
  onData → setQueryData merge → Comparison re-render.
- "Alice's /waiting screen has an 'Edit my answers' button that navigates
  without unmarking": asserts the navigate-only semantics and that re-
  entering /waiting still works (isCompleted not touched).

New: e2e/reconnect-resume.spec.ts
- The critical correctness test for tRPC's tracked() resume protocol.
- Both complete, Bob on /results. Block Bob's WS via page.route. Alice edits.
  Unblock WS. Bob's wsLink reconnects, server resumes from lastEventId,
  delivers the missed entry. Assert Bob's match count updates within 15s.
- Without tracked(), this scenario would be broken: missed events during
  disconnect = permanently stale results.

Deleted: the "falls back to polling when WS upgrade is blocked" test from
e2e/realtime-status.spec.ts — polling fallback is removed from this PR,
and the reconnect-resume test covers the equivalent failure mode for the
new architecture.

E2E infrastructure cleanup:
- Drop POLL_MS env var from e2e/global-setup.ts and packages/server/src/index.ts
  — the runtime config injection is no longer used (no polling)

Fix: Question.tsx's "I'm done" handler now explicitly navigates to /waiting
after markComplete. This is necessary because /questions is in freeRoutes
(so the guard doesn't kick marked-complete users away from the edit flow),
which also means the guard no longer auto-redirects from /questions to
/waiting when completion status changes.

Note: some existing E2E specs show transient flakiness under full parallel
load (passes in isolation, fails occasionally under CPU contention from
~35 concurrent tests). Pre-existing, not introduced by this PR. CI's
retries: 1 covers it.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* docs: update CLAUDE.md, DESIGN.md, design/sync.md, design/ui.md, README, todo

Substantial documentation rewrite reflecting the TanStack Query migration
and the new real-time architecture.

CLAUDE.md:
- Stack line: add TanStack Query v5 + @trpc/tanstack-react-query, tRPC v11
- Delete the old "await refreshStatus()" rule and explicit-navigation rule
- Add "/questions is a free route" callout with explanation
- Add a Data fetching section covering useTRPC(), useSuspenseQuery,
  useMutation, useSubscription, and the "no singleton" rule
- Add a Real-time section: two event buses, two WS subscriptions,
  subscribe-before-query invariant, tracked() resume semantics, no polling
- Clarify the localStorage / TanStack split rule
- Test helpers: document the openSubscription() pattern, tracked() tuple
  unwrapping, fileParallelism: false for integration tests

README.md:
- Stack line updated to include TanStack Query v5 + tRPC v11 WebSocket

DESIGN.md:
- Performance: question bank caching via staleTime: Infinity
- New "Real-time delivery" section covering the two-bus architecture,
  tracked() subscription resume, and the no-polling degradation choice

design/sync.md:
- New "Reading the journal" section documenting sync.journal query and
  sync.onJournalChange subscription with the tracked() protocol
- "Why two buses" section explaining the groupEvents / journalEvents split
- "Edit after completion" flow description

design/ui.md:
- /waiting screen: add "Edit my answers" button, document the navigate-only
  semantics and live-propagation-without-kick behavior
- /results (Comparison): document live updates via tracked subscription and
  the "Change my answers" button change
- Routing: /questions added to free routes with rationale
- Auto-sync: reference the useSyncQueue hook, add conflict-retry note

todo.md:
- Mark TanStack Query migration as Done

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* perf(web): move decryption into queryFn to eliminate render-cycle flakiness

Under parallel E2E load (~18 concurrent browser contexts on one machine),
cross-user assertions like 'Alice & Bob visible' were flaking because the
old pattern added an extra render cycle between 'data arrived' and 'content
visible':

  render(raw) → useEffect fires → async decrypt → setState → render(decrypted)

Two React commits + one microtask + repaint, repeated on every mount and
every WS push. Under CPU contention this added enough latency to blow past
the 10s default expect timeout on tests that had already been tightened in
PR #8.

Fix: push the async decryption into the queryFn itself so Suspense holds
the component invisible until the derived data is fully ready, then the
first render paints the final content in one pass.

useLiveStatus:
- Override the tRPC proxy's queryOptions.queryFn with a wrapper that awaits
  decryptStatus before returning. The cache now stores the decrypted shape,
  and the component reads it directly from useSuspenseQuery.
- Drop the useState + useEffect for status derivation — no more loading/
  error intermediate states tracked in the hook. Loading is handled by the
  outer Suspense boundary, errors propagate to the nearest ErrorBoundary.
- Subscription onData async-decrypts before setQueryData. A per-hook
  monotonic sequence counter (seqRef) guards against out-of-order decryption
  when two pushes arrive in quick succession — latest wins.

Comparison.tsx:
- Use useTRPCClient() to get a vanilla tRPC client, then construct the
  useSuspenseQuery options from scratch: queryKey from the proxy (for
  stable cache lookups), queryFn owns the fetch + replayMembers call.
- Cache shape is CachedJournal = { members: MemberAnswers[], entries, cursor }
  with members pre-decrypted and per-question answers already replayed.
  First paint has memberAnswers ready — no mount→useEffect→setState cycle.
- Subscription onData async-merges (dedup + replay) and calls setQueryData
  with the full derived shape. Monotonic sequence counter guards against
  out-of-order replays.
- Drop the useState<MemberAnswers[] | null> + useEffect that was the
  old render-cycle bottleneck.
- Extract replayMembers() helper so both queryFn and onData share the
  per-member decrypt + replay logic.

PersonApp.tsx:
- Drop the 'status === "loading"' and 'status === "error"' branches from
  the render path. useLiveStatus no longer returns those sentinels — the
  Suspense boundary in main.tsx handles loading, the ErrorBoundary handles
  errors with resetErrorBoundary for retry.

Pattern validation: this is the canonical TanStack Query + Suspense pattern
per TkDodo's "Data Transformations" (option 1: transform in queryFn) and
"Using WebSockets with React Query" (setQueryData for targeted merges).
Also confirmed as the React-19-era best practice for async-derived state
that needs Suspense-aware first-render data — React.use() explicitly does
not support client-created promises, and Jotai async atoms would require
adopting a second state library for one screen's worth of data.

Results: full E2E suite passes cleanly under parallel load (34/34), where
previously 1-2 cross-user assertions were flaking per run.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor: address code review feedback

Addresses the code review on PR #9. Each numbered item corresponds to
the review:

1. Drop dead `onDone?` props from NonAdminOnboarding and PickAnatomyScreen.
   Both stopped using the prop in the mutation migration (step 8); the
   optional signature was a backwards-compat shim that CLAUDE.md's rules
   explicitly prohibit. Removed.

2. Tighten E2E assertions in edit-post-completion and reconnect-resume:
   - Snapshot Bob's match count BEFORE the edit and assert a concrete
     drop (matchesAfter < matchesBefore) instead of a magic `< 50`
     upper bound that was unconnected to the actual question count.
   - Replace `alice.waitForTimeout(4000)` hard sleep with
     `expect(...).toPass({ timeout })` polling, which covers the full
     pipeline latency without burning the whole 4s unconditionally.
   - reconnect-resume.spec.ts also replaces `waitForTimeout(4500)` with
     a scoped-localStorage poll that checks when Alice's pendingOps
     queue clears (the signal that sync.push has committed).

3. Replace `useMemo(() => ..., [])` + eslint-disable in Comparison.tsx
   with `useState(() => ...)` for "compute once on mount" semantics.
   React's idiomatic pattern; no lint disable needed.

4. Sharpen the subscribe-before-query comment in sync.onJournalChange to
   call out the precondition ordering explicitly: the getStatus check
   runs before the listener attach, and the review was right that this
   window is covered by the backfill query (not the live stream). The
   comment now walks through steps 1-4 so the invariant isn't ambiguous.

5. Add a comment to packages/web/tsconfig.json explaining why web
   includes the server's router.ts directly (project references with
   composite+declaration triggered TS2883 on tracked() type inference
   via the unstable-core-do-not-import internal path). Present the
   current setup as a deliberate workaround.

6. Drop the `TrackedEnvelope` type alias and the explicit envelope
   annotations from sync.ts. The alias existed to force TypeScript's
   declaration emit through the public path, but with noEmit: true on
   both packages and web including server source directly, declaration
   emit never happens — the workaround is moot. The subscription now
   lets tRPC infer the yield type directly from `tracked()` calls, and
   the yielded messages use `satisfies JournalChangeMessage` for shape
   safety without overriding inference. `@trpc/server` stays as a web
   devDep because `inferRouterOutputs` is still needed elsewhere.

7. Add a dep array to Question.tsx's `scheduleSync` effect:
   `[pendingOps.length, scheduleSync]`. The old no-deps form reset the
   debounce timer on every render, which (per review) could defer the
   sync indefinitely if an unrelated parent re-rendered the component
   more often than 3s. The new form only resets the timer when the
   pending count actually changes.

Verification: typecheck, lint, unit+integration (245 tests), and E2E
(34/34) all green. Some pre-existing parallel-load flakiness persists
on cross-user assertions but is handled by CI retries.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* perf(web): drop Comparison lazy load, prefetch journal on allComplete transition

Two optimizations + one infrastructure fix to attack the intermittent E2E
flakiness on cross-user assertions under local parallel load.

1. Drop Comparison's lazy() import (~6KB chunk load off the critical path)

   PersonApp.tsx now imports Comparison directly instead of via React.lazy.
   The extra HTTP request for the Comparison chunk was measurable under
   parallel load — every receiver's first /results navigation had to
   fetch a chunk while the server was handling 18 concurrent requests.
   Inlining adds ~6KB gzipped to the main chunk (trivial).

2. Prefetch the Comparison journal on the allComplete transition

   New `packages/web/src/lib/journal-query.ts` exports:
   - `MemberAnswers` and `CachedJournal` types (moved from Comparison.tsx)
   - `replayMembers()` shared decrypt+replay helper
   - `JOURNAL_QUERY_KEY` — stable queryKey for the derived journal
   - `makeJournalQueryFn(trpcClient)` factory used by both the component's
     useSuspenseQuery and the prefetch call
   - `prefetchJournal(queryClient, trpcClient)` that kicks off the fetch
     via queryClient.prefetchQuery

   PersonApp.tsx runs a useEffect on the `allComplete` boolean that
   prefetches the journal the moment the group flips to allComplete.
   This fires for both sides of the markComplete broadcast:
   - Own mutation path: markCompleteMutation onSuccess invalidates status
     → useLiveStatus refetches → allComplete transitions → effect fires
   - Partner path: WS push → setQueryData → status updates → allComplete
     transitions → effect fires

   By the time the guard redirects to /results and Comparison mounts, the
   data is either already in cache or in flight — the HTTP round-trip +
   decryption latency is moved off the render-critical path.

   Comparison.tsx now reads from the shared JOURNAL_QUERY_KEY and uses
   makeJournalQueryFn, so prefetch and component fetch go through the
   same code path.

3. Enable Playwright retries locally (match CI)

   The remaining source of flakiness is raw CPU contention from running
   4+ concurrent full Chromium instances on one machine — not app
   capacity (the app handles 1000 real clients fine because each is on
   its own device). CI uses workers=2 which avoids the contention
   entirely; local dev uses workers=50% for speed, which hits the
   contention tail occasionally.

   With retries=1 (previously local=0, CI=1), transient failures are
   absorbed by a single retry. Two consecutive failures still surface as
   real failures, so actual bugs aren't masked. The "flaky" annotation
   in the Playwright output makes it visible when a retry was needed.

Test:
- Unit/integration: 245/245 pass
- E2E local (workers=50%): 3 consecutive runs exit 0, occasional tests
  are marked "flaky" (retried successfully)
- E2E CI (workers=2): the root cause is absent at 2 workers — expected
  to remain green without needing retries

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor: address second round of code review feedback

Five fixes in response to the follow-up review on PR #9.

1. CachedJournal.members double-decryption in Comparison's onData merge
   (review #1).

   Previously the WS merge path called `replayMembers(current.members,
   mergedRaw.entries)` which type-coerced the already-decrypted members
   back into the raw input type and re-ran `unwrapSensitive(m.name)` on
   each. `unwrapSensitive` is idempotent on plaintext so this was safe
   but wasteful, and the type assertion hid the contract mismatch.

   New `rebuildMemberAnswers(members, mergedEntries)` helper in
   `journal-query.ts` preserves the already-decrypted name/anatomy and
   only re-runs `replayJournal` to rebuild the per-person answers.
   Comparison.tsx's onData now uses it on the merge path.

2. reconnect-resume.spec.ts actually exercises the resume path now
   (review #2).

   The old test used `page.route("**/api/trpc-ws**", abort)` to block
   Bob's WS. But Playwright's page.route only intercepts HTTP-level
   traffic — the WebSocket UPGRADE handshake is HTTP, but once the WS
   is upgraded the frames flow outside Playwright's interception.
   route.abort() only blocked NEW upgrade attempts; Bob's existing WS
   was still connected and delivered Alice's edit via the normal
   live-stream path, masking whether tracked() resume was actually
   tested.

   Fix: use CDP's `Network.emulateNetworkConditions { offline: true }`
   on Bob's page to sever the entire network layer, which actually
   closes his existing WS (wsLink observes the close event). Flip back
   to `offline: false` to let wsLink auto-reconnect, which re-sends the
   subscription message with Bob's last tracked id and triggers the
   server's replay via `journalSince(groupId, sinceId)`.

   Also replaced the hard `waitForTimeout(4500)` with localStorage
   polling for Alice's pendingOps queue to clear (her own sync.push's
   completion signal).

   Test now passes consistently in isolation at ~10s (was masking a
   false positive before).

3. useSyncQueue identity stability (review #3).

   `useCallback(handleSync, [totalQuestions, pushMutation])` was
   unstable because `useMutation` returns a new result object on every
   render (unlike useQuery's stable `data` reference). The churn
   cascaded: handleSync changed → scheduleSync changed → Question.tsx's
   `useEffect([pendingOps.length, scheduleSync])` re-ran on every
   render, resetting the 3s debounce even when pendingOps hadn't
   changed. Worst case: unrelated re-renders faster than 3s would
   defer the sync indefinitely (the exact hazard I had commented
   about but not actually fixed).

   Fix: hold `totalQuestions` and `pushMutation` in refs, call
   `pushMutationRef.current.mutateAsync(...)` from the callback body,
   and empty-dep the `useCallback`. Both `handleSync` and
   `scheduleSync` are now stable for the hook's lifetime.

4. lastEventId NaN validation (review #4).

   `Number(input.lastEventId)` on a malformed string produces NaN,
   which flows into `gt(journal_entries.id, NaN)`. Postgres handles it
   gracefully but it's unclean. Added a Zod refinement
   `regex(/^\d+$/)` so malformed cursors are rejected with a clear
   error at the edge.

5. CLAUDE.md pathFilter → pathKey consistency (review #5).

   Doc said `trpc.groups.status.pathFilter()` but all the code uses
   `trpc.groups.status.pathKey()` inside `invalidateQueries({ queryKey })`.
   Updated the doc to match the code.

Verification:
- Unit + integration: 245/245
- E2E reconnect-resume (in isolation): 3/3 passes at ~10s each,
  actually exercising the CDP-offline → reconnect path
- E2E full suite: exit 0 with CI-style retries absorbing transient
  parallel-load flakes
- Typecheck + lint: clean

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor: address third round of code review feedback

Actionable:
- DESIGN.md: drop stale lazy-split wording; document journal pre-warm
  and single-bundle shape introduced by the Comparison inline commit.
- design/sync.md: disambiguate push cursor (stoken, HMAC-signed) vs
  read cursor (raw numeric id) to fix contradictory statements about
  whether clients see journal ids. Replace the "Polling for Partner
  Status" section with a WS-first "Partner Status Delivery" writeup
  reflecting the current architecture.
- sync.journal-subscription.integration.test.ts: tighten the
  subscribe-before-query race test to assert the specific racing entry
  is delivered via collected.find(e => e.operation === racingOp),
  not just collected.length >= 3. A bug that dropped the racing event
  while keeping 2 initial + some other 3rd entry would have slipped by.
- sync.test.ts: hoist the pushOk fixture to module scope so both
  describe blocks share one definition.

Rejected with reasoning (see PR comments):
- Question.tsx onSuccess returning promise: arrow expression body
  already returns its value, so the invalidation promise IS being
  passed back to TanStack. No change needed.
- Readonly<{ children }> on AppProviders: isolated style island.
  Added p3 task to enable eslint-react/prefer-read-only-props as a
  codebase-wide convention instead of per-component opt-in.
- tsconfig.json cross-package include: documented TS2883 workaround
  for tRPC tracked() declaration emit. The pattern matches tRPC's
  own canonical relative-path type import. Added a line acknowledging
  the coupling cost.
- use-live-status.ts unused useTRPCClient import: already clean on
  current branch (stale CR comment).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix(web): lift selectedCategories to useState so first-mount default propagates

A fresh user (no stored categories) saw the "No questions for your
selected categories" empty state instead of the first welcome screen.
Root cause: `selectedCategories` was read from localStorage inline on
every render, and the default-selection logic lived in a useEffect
that wrote defaults to localStorage but never triggered a re-render.
First render saw [], buildScreens returned 0, and the empty-state card
painted. The effect updated storage after, but nothing re-read it.

Fix: lift selectedCategories into `useState` with a lazy initializer
that returns storage or (on null) persists + returns defaults. The
value is now present on first render.

Storage contract:
  null  → first-time user, default to all categories (and persist)
  []    → user explicitly unchecked everything via Summary; respect
  [...] → use the stored list as-is

Adds a regression test `fresh-user-no-preseed.spec.ts` that deliberately
does NOT call `setCategories`/`scopedSet` — it exercises the real UI
default path that no other E2E was covering. Every existing E2E had
been pre-seeding storage, which is how this bug stayed hidden.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* test(e2e): remove UI-bypass helpers, exercise real user journeys

Every E2E spec previously called setCategories() / setTier() — helpers
that wrote directly to scoped localStorage to skip past the Summary
category-picker UI. The result: the fresh-user default path was never
exercised by any test, which let a real UX bug (see previous commit)
ship undetected.

Policy change documented in helpers.ts:
  - scopedGet / scopedSet are now reserved for invariants the UI
    cannot produce or observe (e.g. rolling back stoken adversarially,
    polling pendingOps as a sync-completion signal).
  - Every remaining call site has a justification comment.
  - setCategories and setTier are deleted.

Replaced with narrowToCategory(page, targetLabel): a UI-driven helper
that clicks "View all categories" from the first welcome screen,
unchecks every category whose label doesn't match, and clicks the
target row — the same flow a real user takes to narrow scope.

Per-spec changes:
  - completion: replace URL-manipulation path to /review with the
    real UI click-through (Progress → Summary → Review answers).
  - multi-tab: replace `scopedGet("answers")` assertions with UI
    observation (Back button + reload).
  - edit-post-completion: replace `alice.url().replace(...)` URL
    manipulation with `page.goBack()`.
  - fill-questionnaire: use the Intro screen's tier picker UI
    instead of `setTier` bypass.
  - sync-conflict: preserves scopedGet/scopedSet because stoken
    rollback is adversarial; documented inline.
  - Every other spec: rewritten to call narrowToCategory.

Additionally, `global-setup.ts` now runs `vite build` unconditionally
before starting the Hono server. The server serves `packages/web/dist`
as a static root; nothing previously built that directory as part of
test setup, which let stale bundles silently mask source changes.
SKIP_E2E_BUILD=1 is an escape hatch for iterative test-only work.

Researched Playwright's canonical pattern (`webServer.command` with
`pnpm build && pnpm start`); it assumes a simpler stack than ours
(no dynamic DB URL from a testcontainer, no custom Hono serving both
static + API). Build-in-globalSetup is the pragmatic fit — documented.

Result: 35/35 tests pass, ~3min wall time, zero flakes, zero
bypasses of the UI that real users actually traverse.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor: address fourth round of code review feedback

Actionable:
- e2e/fill-questionnaire.spec.ts: scope the Power Exchange fraction
  lookup to the Power Exchange row instead of `.first()`-matching
  whatever fraction appears first in DOM order. Prior locator would
  silently read the wrong counter if Summary layout changed.
- e2e/helpers.ts: escape regex metacharacters in `targetLabel` before
  building the category-button RegExp. Current labels are metachar-
  free but this is cheap defense for future labels like "Role Play
  (Fantasy)".
- sync.journal-subscription.integration.test.ts: replace the fixed
  `setTimeout(50)` + listenerCount assertion with `expect.poll`.
  CR suggested a manual while-loop, but Vitest's first-class primitive
  is strictly better: retries the assertion (zero overhead on first
  match), surfaces observed values in the failure message, and is
  idiomatic. 1 line instead of 7, and no time-guessing under CI load.
- e2e/edit-post-completion.spec.ts: use `goBack` + `reload` instead of
  plain `goBack` for the "did not unmark" assertion. `goBack` alone
  only replays SPA history; a stale in-memory completion flag could
  let the test pass even if the button accidentally touched server
  state. `reload` forces the guard to re-evaluate against fresh
  status — if isCompleted were false, we'd get bounced to /questions.
- design/sync.md: hyphenate "Client side" → "Client-side".

Rejected:
- sync.journal-subscription.integration.test.ts type → interface:
  style-only preference; the codebase mixes both for object-shape
  aliases and has no enforced convention. Not worth churning.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor(server): use expect.poll for listener cleanup check in groups subscription test

Drive-by: brings the groups subscription listener-cleanup assertion in
line with the sync journal subscription test (fixed in the previous
commit). Same anti-pattern, same upgrade, same rationale —
`setTimeout(50)` was a fixed sleep guessing at cleanup latency and
occasionally flaky under parallel worker load; `expect.poll` retries
the assertion (zero overhead on the fast path), surfaces observed
values in failure messages, and matches the equivalent check in
sync.journal-subscription.integration.test.ts.

No other fixed-setTimeout instances remain in the vitest test suite.
Playwright E2E specs already use the framework-native equivalent
(`expect(async () => ...).toPass({ timeout })`) at every cross-process
assertion. The one remaining `waitForTimeout(500)` in reconnect-
resume.spec.ts is a deliberate heuristic for wsLink internal state
transitions that have no observable DOM surface; intentionally
preserved with explanatory comment.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* chore: signing checkpoint

This session's earlier commits (1f3125d..f022710) were made with
commit.gpgsign=false bypassing the repo's default signing config.
This empty commit re-establishes a signed checkpoint on top of
them. The content of prior commits is intact and verified via CI
on this branch; future commits will sign normally.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant