Skip to content

feat: migrate to TanStack Query with tracked() real-time delivery - #9

Merged
iskhakovt merged 23 commits into
mainfrom
feat/tanstack-query-migration
Apr 11, 2026
Merged

iskhakovt merged 23 commits into
mainfrom
feat/tanstack-query-migration

Conversation

@iskhakovt

@iskhakovt iskhakovt commented Apr 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Migrates the client state layer from hand-rolled hooks (useGroupStatus, ref-chain sync loop, refreshStatus() threading) to TanStack Query v5 + @trpc/tanstack-react-query
  • Adds lossless reconnect-safe journal delivery via tRPC v11's tracked() primitive — a dedicated sync.onJournalChange subscription that the wsLink auto-resumes from its lastEventId cursor on reconnect
  • Introduces an edit-without-unmark UX: marked-complete users can return to /questions via explicit buttons without kicking their partner from /results; edits propagate live through the journal subscription

Architecture changes

Server

  • New journalEvents bus alongside the existing groupEvents. Separated by concern: status broadcasts vs journal appends have very different emission rates and different consumers.
  • sync.compare → sync.journal({ sinceId }) with cursor semantics. Returns { members, entries, cursor }. Empty delta echoes input cursor (so repeated callers don't regress).
  • New sync.onJournalChange subscription using the canonical tRPC pattern: attach listener to journalEvents BEFORE the backfill query, yield via tracked(id, data), dedup overlap. SubscribeBefore-query invariant is covered by an explicit integration test.
  • sync.push emits on journalEvents after successful non-rejected commits. Unconditional — if nobody is subscribed, emit is a no-op.

Client

  • createTRPCContext<AppRouter>() via @trpc/tanstack-react-query; AppProviders wraps QueryClientProvider + TRPCProvider with stable useState(() => ...) clients
  • use-live-status.ts replaces use-group-status.ts: useSuspenseQuery(trpc.groups.status) + useSubscription(trpc.groups.onStatus) feeding the same cache entry via setQueryData
  • Comparison.tsx rewritten: useSuspenseQuery(trpc.sync.journal) for initial backfill + useSubscription(trpc.sync.onJournalChange) with setQueryData merge. Reconnect recovery via tracked() resume.
  • useSyncQueue hook extracts the 3s-debounced sync.push + conflict retry loop from Question.tsx (-60 LoC, no more ref chains)
  • All mutations migrated to useMutation with onSuccess: invalidateQueries — no more refreshStatus() threading
  • Polling fallback removed entirely. Recovery relies on wsLink auto-reconnect + keepAlive (30s ping / 5s pong) + tracked() resume.

UX

  • /questions is a free route — the guard no longer kicks marked-complete users away from it
  • /waiting gains an "Edit my answers" button that navigates to /questions without mutating
  • /results "Change my answers" button becomes navigate-only (previously called unmarkComplete)
  • Partner viewing /results is never kicked to /waiting when the other edits — they see the updated pair matches live via the journal subscription

Test plan

Automated

  • pnpm -r typecheck — 3 packages clean
  • pnpm lint — 116 files clean
  • pnpm test — 245 unit + integration tests pass (+30 new)
    • New: packages/web/src/lib/merge-journal.test.ts (9 pure-function tests)
    • Extended: events.test.ts, sync.test.ts, sync.integration.test.ts
    • New integration: sync.journal-subscription.integration.test.ts with 10 scenarios:
      • Fresh subscribe yields all entries as a single tracked event
      • sync.push triggers append with tracked id
      • Resume with lastEventId returns only entries > cursor
      • Concurrent subscribers receive same events
      • Subscribe-before-query race: emit during backfill is still delivered
      • PRECONDITION_FAILED before allComplete
      • Listener cleanup on abort
      • Encrypted payloads delivered as-is
  • pnpm test:e2e — full suite runs, occasional parallel-load flakiness on pre-existing specs (same as before this PR); CI's retries: 1 covers it. New specs pass in isolation and under most parallel runs.
    • New: e2e/edit-post-completion.spec.ts — verifies Alice's live edit propagates to Bob's /results, and the /waiting "Edit my answers" button navigates without unmarking
    • New: e2e/reconnect-resume.spec.ts — blocks Bob's WS, Alice edits, unblock WS, asserts tracked() resume replays the missed event
    • Deleted: polling-fallback test from realtime-status.spec.ts (polling is gone)

Manual

  • Two browser tabs, both complete, both on /results. Click "Change my answers" on one — verify the other sees the updated match classification within 2s without being kicked from /results
  • Kill server mid-session → verify wsLink auto-reconnects and tracked() catches up
  • DevTools Network/WS: verify tracked events include id field on yields
  • DevTools Application → Local Storage: verify scoped s{hash}: prefixed keys still work
  • React Query devtools (dev build) shows cache state

Notable files

  • New: packages/web/src/lib/{query-client,trpc-providers,use-live-status,use-sync-queue,merge-journal}.ts
  • New: packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts
  • New: e2e/{edit-post-completion,reconnect-resume}.spec.ts
  • Deleted: packages/web/src/lib/use-group-status.ts
  • Rewritten: Comparison.tsx, Question.tsx, PersonApp.tsx, events.ts, sync.ts (server route + store)
  • Docs: substantial rewrite of CLAUDE.md, DESIGN.md, design/sync.md, design/ui.md; stack line updated in README.md; todo.md marks the migration done

Bundle size

+14KB gzipped (~120KB → ~134KB main chunk) for TanStack Query core. Devtools dynamic-imported in DEV only.

Follow-ups (not in this PR)

  • The pre-existing parallel-load E2E flakiness is unchanged; if it becomes chronic we could reduce worker count or bump individual timeouts
  • sync.unmarkComplete procedure kept on the server as a safety valve; no UI caller remains

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Real-time group status and answer updates via WebSocket subscriptions
    • Edit answers after completion (navigate back to /questions) with partners seeing edits live
    • Live comparison view updates in-place as answers change
  • Improvements

    • Better reconnect/resume so clients catch up after offline periods
    • Faster, more reliable loading via prefetching + Suspense
    • Expanded free-route exemption to include /questions and smoother waiting-screen flow

iskhakovt added a commit that referenced this pull request Apr 11, 2026
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]>
iskhakovt added a commit that referenced this pull request Apr 11, 2026
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]>
@iskhakovt iskhakovt changed the title feat: TanStack Query migration with tracked() real-time delivery feat: migrate to TanStack Query with tracked() real-time delivery Apr 11, 2026
iskhakovt and others added 17 commits April 11, 2026 11:26
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]>
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]>
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]>
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]>
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]>
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]>
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]>
…idation

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]>
…flict 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]>
…ut 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]>
…or 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]>
…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]>
…ME, 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]>
…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]>
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]>
… 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]>
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]>
@iskhakovt
iskhakovt force-pushed the feat/tanstack-query-migration branch from 08a84cf to 007f1a6 Compare April 11, 2026 10:27
@coderabbitai

coderabbitai Bot commented Apr 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 37c8ec5a-3ced-455f-bd4e-1b2e7df2a029

📥 Commits

Reviewing files that changed from the base of the PR and between 060129c and 1acdfd1.

📒 Files selected for processing (1)
  • packages/server/src/trpc/routes/groups.subscription.integration.test.ts

📝 Walkthrough

Walkthrough

Migrates client to React 19 + TanStack Query v5 and tRPC v11 (HTTP+WS); replaces polling with a subscribe-before-backfill, resume-safe journal model (separate snapshot groupEvents and append-only journalEvents), shifts to cache-driven invalidate/refetch flows, and adds extensive subscription and E2E tests.

Changes

Cohort / File(s) Summary
Docs & design
CLAUDE.md, DESIGN.md, README.md, design/sync.md, design/ui.md, todo.md
Updated stack versions and architecture notes; documented two-event-bus model, subscribe-before-query invariant, WS resume via lastEventId/tracked(), edit-after-completion UX, and removal of polling fallback.
Server events & tests
packages/server/src/events.ts, packages/server/src/events.test.ts
Added journalEvents, journalEventName, emitJournalUpdate, and JournalEntryPayload; tests validate journal bus semantics and separation from groupEvents.
Store: cursored journal & push
packages/server/src/store/sync.ts, packages/server/src/store/sync.test.ts
Replaced compare() with journalSince(groupId, sinceId) returning entries+cursor; push() now surfaces committedEntries internally; tests for cursor progression, empty deltas, and precondition errors added.
tRPC sync routes & subscription tests
packages/server/src/trpc/routes/sync.ts, packages/server/src/trpc/.../sync.*.test.ts
Added sync.journal query and sync.onJournalChange subscription (attach listener before backfill, backfill then append-stream via tracked(), dedupe); push emits journal events; extensive integration/unit tests added.
Server runtime/build tweaks
packages/server/src/index.ts, packages/server/tsconfig.json, packages/server/package.json, e2e/global-setup.ts
Removed POLL_MS env injection into client runtime; switched server TS to noEmit; changed typecheck script; e2e global setup builds web bundle by default.
Web infra: trpc + TanStack Query providers
packages/web/package.json, packages/web/src/lib/trpc.ts, packages/web/src/lib/trpc-providers.tsx, packages/web/src/lib/query-client.ts, packages/web/tsconfig.json, packages/web/src/main.tsx
Added TanStack Query v5 and @trpc/tanstack-react-query; replaced singleton trpc with makeTrpcClient() + createTRPCContext() (TRPCProvider, useTRPC, useTRPCClient); added makeQueryClient() and AppProviders with Suspense fallback.
Journal client utilities
packages/web/src/lib/merge-journal.ts, packages/web/src/lib/merge-journal.test.ts, packages/web/src/lib/journal-query.ts
New journal merge/replay utilities (mergeJournal, JournalEntry/JournalState), replayMembers/rebuildMemberAnswers, JOURNAL_QUERY_KEY, makeJournalQueryFn, and prefetchJournal.
Sync queue & live status hooks
packages/web/src/lib/use-sync-queue.ts, packages/web/src/lib/use-live-status.ts, (removed) packages/web/src/lib/use-group-status.ts
Added useSyncQueue(totalQuestions) for debounced push + conflict-merge/retry; added useLiveStatus(token) combining useSuspenseQuery + groups.onStatus subscription updating TanStack cache; removed old polling hook.
Screens and flows
packages/web/src/screens/... (e.g., PersonApp.tsx, Question.tsx, Comparison.tsx, GroupSetup.tsx, Invite.tsx, Landing.tsx)
Refactored UIs to Suspense + useSuspenseQuery + useMutation, centralized invalidate-on-success patterns, integrated useSyncQueue and journal subscription merging, expanded free-route exemption (/questions), and adjusted component props/flows.
TRPC client usage & exports
packages/web/src/lib/trpc.ts, packages/web/src/lib/trpc-providers.tsx, various screens
Replaced direct singleton usage with hook-based useTRPC() + useQueryClient() and factory client creation; exported wsClient and makeTrpcClient().
E2E tests & helpers
e2e/helpers.ts, many e2e/*.spec.ts (e.g., edit-post-completion.spec.ts, reconnect-resume.spec.ts, realtime-status.spec.ts, etc.)
Replaced storage-bypass helpers with UI-driven narrowToCategory; added edit-after-completion and reconnect/resume tests; removed WS-fallback polling test; updated many tests and assertions; global setup now builds web bundle by default; Playwright retries changed.
Vitest & Playwright config
vitest.config.ts, playwright.config.ts
Disabled integration file parallelism (Vitest) to avoid DB/truncate deadlocks; Playwright retries set to 1 unconditionally.
Misc small changes & docs
assorted server/web tests/screens
Doc/comments updated, wire response shapes adjusted to omit committedEntries on the wire, wsClient exported, and tests updated to new behaviors.

Sequence Diagram(s)

sequenceDiagram
    participant Browser as Browser (Client)
    participant QCache as TanStack Cache
    participant TRPCWS as tRPC WebSocket
    participant Server as Server
    participant DB as Database

    Browser->>QCache: useSuspenseQuery(makeJournalQueryFn)
    QCache->>Server: sync.journal({ sinceId: null })
    Server->>DB: SELECT journal entries
    DB-->>Server: entries + cursor
    Server-->>QCache: { entries, cursor, members }
    QCache-->>Browser: render initial journal

    Browser->>TRPCWS: subscribe sync.onJournalChange({ lastEventId })
    TRPCWS->>Server: open subscription
    Server->>DB: backfill entries > lastEventId
    Server-->>TRPCWS: tracked(backfill)
    TRPCWS-->>Browser: onData -> mergeJournal -> setQueryData

    Browser->>Server: sync.push (useSyncQueue mutate)
    Server->>DB: INSERT journal entries -> committedEntries
    Server->>Server: emitJournalUpdate(groupId, committedEntries)
    Server-->>TRPCWS: journal event (tracked)
    TRPCWS-->>Browser: onData -> mergeJournal -> setQueryData
Loading
sequenceDiagram
    participant Bob as Bob (Client)
    participant BobWS as Bob WS
    participant Alice as Alice (Client)
    participant AliceWS as Alice WS
    participant Server as Server
    participant DB as Database
    participant Network as Network

    Bob->>BobWS: subscribe(lastEventId: 5)
    BobWS->>Server: open, request backfill since 5
    Server->>DB: SELECT entries > 5
    DB-->>Server: entries [6..9]
    Server->>BobWS: tracked(backfill)
    BobWS-->>Bob: apply backfill

    Network->>Bob: go offline
    BobWS-->>Bob: connection drops

    Alice->>AliceWS: sync.push(edit) -> DB INSERT id=10
    Server->>Server: emitJournalUpdate(id=10)

    Network->>Bob: back online
    Bob->>BobWS: reconnect with lastEventId:5
    Server->>DB: SELECT entries > 5 -> [6..10]
    Server->>BobWS: tracked(backfill including 10)
    BobWS-->>Bob: apply merged entries -> UI updates
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇
I nibble bytes and stitch the stream,
tracked() hops in like a dream.
No polling thumps — events arrive,
Journals replay and keep state live.
Cache and WS dance, the UI gleams.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: migrate to TanStack Query with tracked() real-time delivery' is clear, specific, and accurately captures the main change: a client-side migration to TanStack Query with tracked() real-time subscriptions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/tanstack-query-migration

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (5)
packages/web/src/lib/trpc-providers.tsx (1)

22-22: Consider Readonly props typing for boundary immutability.

You can tighten the provider prop contract with Readonly<{ children: ReactNode }> for consistency with immutable boundary patterns.

As per coding guidelines, “Return defensive copies and use Readonly<T> where practical to prevent mutable state across boundaries.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/web/src/lib/trpc-providers.tsx` at line 22, The AppProviders props
typing should be made readonly to enforce boundary immutability; change the
function signature for AppProviders to accept props typed as Readonly<{
children: ReactNode }> instead of { children: ReactNode } and propagate that
type where AppProviders is referenced to ensure the compiler enforces
immutability of the incoming props (update any usages or tests that expect the
previous mutable type if necessary).
packages/web/tsconfig.json (1)

23-23: Consider reducing cross-package coupling from direct source include.

Including ../server/src/trpc/router.ts works, but it ties web typecheck to a specific internal server filepath. A small exported type surface (e.g., server-side AppRouter type entrypoint consumed as a package import) would be more resilient to server refactors.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/web/tsconfig.json` at line 23, The tsconfig "include" currently
points directly at ../server/src/trpc/router.ts which creates tight coupling;
instead, export the server's router type (e.g., export type AppRouter from a
stable entry like server package's index or a dedicated types file) and consume
it via a package import in the web code; then remove
../server/src/trpc/router.ts from packages/web/tsconfig.json "include" and
update any web files that reference the type to use "import type { AppRouter }
from 'server'". Ensure the server package re-exports AppRouter (unique symbol
AppRouter) from a stable entrypoint and update package exports/typings so the
web package can type-import it without cross-package source includes.
packages/web/src/lib/use-live-status.ts (1)

7-7: Unused import: useTRPCClient is not used in this file.

Only useTRPC is used in this hook.

🧹 Remove unused import
-import { useTRPC, useTRPCClient } from "./trpc.js";
+import { useTRPC } from "./trpc.js";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/web/src/lib/use-live-status.ts` at line 7, The import statement
includes an unused symbol useTRPCClient; remove useTRPCClient from the import so
only useTRPC is imported (i.e., update the import from "./trpc.js" to exclude
useTRPCClient) to eliminate the unused import in use-live-status.ts.
packages/server/src/trpc/routes/sync.test.ts (1)

63-69: Consider extracting pushOk helper to reduce duplication.

The pushOk helper is defined identically in both sync.push and sync.push journal bus emission describe blocks. This is a minor duplication—acceptable for test readability, but could be hoisted to module scope if preferred.

Also applies to: 117-123

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/server/src/trpc/routes/sync.test.ts` around lines 63 - 69, The
helper pushOk is duplicated in two describe blocks; extract it to module scope
and import/restore its exact signature so both describe("sync.push") and
describe("sync.push journal bus emission") use the same function. Move the const
pushOk = (entries: { id: number; personId: string; operation: string }[] = [])
=> ({ stoken: "s1", entries: [], committedEntries: entries, pushRejected: false
as const, }); out of the inner describes into the top of the test file so both
tests call the shared pushOk helper, run tests, and remove the duplicated
definitions inside the describe blocks.
packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts (1)

256-286: Good invariant test, with a timing caveat.

This test exercises the subscribe-before-query invariant by racing a push against the subscription setup. The approach is sound — if the invariant is violated, the new entry could be lost. The 3-yield drain with 500ms timeouts provides reasonable coverage.

Note: The test asserts collected.length >= 3 but doesn't verify the specific entry is present. A stricter assertion could check that an entry with the "maybe" rating exists in the collected set.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts`
around lines 256 - 286, The test "subscribe-before-query invariant: emit during
backfill is delivered" only asserts collected.length >= 3 but doesn't confirm
the specific racing entry was received; update the test to assert that the
collected array (variable collected, produced by unwrap(next).entries from sub
via openSubscription(journalSub(alice.ctx))) contains an entry matching the
pushed operation (the object with rating "maybe" or key "oral:give") — e.g. scan
collected for an entry whose data.rating === "maybe" or key === "oral:give" and
expect that match to be found before cancelling the subscription, so the
invariant checks presence of the specific racing entry rather than just count.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@DESIGN.md`:
- Around line 64-67: The performance section still describes the old bundle
shape; update the paragraph that mentions "Question bank cached" and "staleTime:
Infinity" and remove or change the lines "Lazy-load comparison view (dynamic
import, loaded only when needed)" and "Single code split: main app + comparison
chunk" to reflect the new architecture where the Comparison view is included in
the main bundle (no separate comparison chunk and no dynamic import), while
retaining the TanStack Query cache behavior; ensure the wording clearly states
there is no SSR and that the app ships as a single bundle with the question bank
cached per session via staleTime: Infinity.

In `@design/sync.md`:
- Around line 239-274: Remove the stale "Polling for Partner Status" section and
the 30s polling loop description from this doc; replace it (or rewrite) with a
short statement that the system is WS-first using sync.onJournalChange backed by
journalEvents and wsLink resume/backfill semantics (lossless reconnect), and
note that status broadcasts use groupEvents for differing rates—do not describe
polling as part of the recovery model. Ensure the doc no longer suggests any
client-side 30s polling loop or implies polling is required for reconnect
recovery.
- Around line 218-237: Update the earlier data-model paragraph that currently
says "clients never see journal IDs and only get stoken" to match the journal
API: state that clients do receive numeric journal ids/cursors via sync.journal
and sync.onJournalChange (describe that cursor is the highest entry id or echoes
the input), and clarify that stoken remains an internal snapshot token distinct
from the journal id (or explicitly map how stoken relates to id if intended).
Replace any assertion that clients never see ids with this corrected behavior
and ensure mentions of cursor, id, sync.journal, sync.onJournalChange, and
stoken are consistent across the doc.

In `@e2e/realtime-status.spec.ts`:
- Around line 26-33: The timer starts after Bob's click so it misses the initial
markComplete latency; move the timestamp to before invoking
bob.getByRole(...).click() (i.e., set start = Date.now() immediately before the
click) or alternatively start the timer when the outgoing sync.markComplete
request is fired, then await alice.getByText("Your results") and compute elapsed
as Date.now() - start to measure the full path from sync.markComplete →
groupEvents → Alice's WS onData → redirect.

In `@packages/web/src/screens/Question.tsx`:
- Around line 57-61: The onSuccess handler for markCompleteMutation (created
with useMutation and trpc.sync.markComplete.mutationOptions) currently calls
queryClient.invalidateQueries({ queryKey: trpc.groups.status.pathKey() }) but
does not return that promise, so the mutation may appear complete before refetch
finishes; update the onSuccess to return the promise from
queryClient.invalidateQueries and ensure markCompleteMutation (and any callers
such as handleMarkComplete that await mutateAsync()) will remain pending until
the invalidation/refetch resolves.

In `@todo.md`:
- Around line 9-10: The two checklist items conflict about polling
fallback—update the Done list so both entries agree: decide whether polling
fallback was removed or retained, then edit the "TanStack Query v5 +
`@trpc/tanstack-react-query` migration" line and the "tRPC subscriptions over
WebSocket for cross-user state sync" line to state the chosen outcome
consistently (e.g., both say "polling fallback removed" or both say "polling
fallback retained"), ensuring the phrasing around polling fallback is identical
for clarity.

---

Nitpick comments:
In
`@packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts`:
- Around line 256-286: The test "subscribe-before-query invariant: emit during
backfill is delivered" only asserts collected.length >= 3 but doesn't confirm
the specific racing entry was received; update the test to assert that the
collected array (variable collected, produced by unwrap(next).entries from sub
via openSubscription(journalSub(alice.ctx))) contains an entry matching the
pushed operation (the object with rating "maybe" or key "oral:give") — e.g. scan
collected for an entry whose data.rating === "maybe" or key === "oral:give" and
expect that match to be found before cancelling the subscription, so the
invariant checks presence of the specific racing entry rather than just count.

In `@packages/server/src/trpc/routes/sync.test.ts`:
- Around line 63-69: The helper pushOk is duplicated in two describe blocks;
extract it to module scope and import/restore its exact signature so both
describe("sync.push") and describe("sync.push journal bus emission") use the
same function. Move the const pushOk = (entries: { id: number; personId: string;
operation: string }[] = []) => ({ stoken: "s1", entries: [], committedEntries:
entries, pushRejected: false as const, }); out of the inner describes into the
top of the test file so both tests call the shared pushOk helper, run tests, and
remove the duplicated definitions inside the describe blocks.

In `@packages/web/src/lib/trpc-providers.tsx`:
- Line 22: The AppProviders props typing should be made readonly to enforce
boundary immutability; change the function signature for AppProviders to accept
props typed as Readonly<{ children: ReactNode }> instead of { children:
ReactNode } and propagate that type where AppProviders is referenced to ensure
the compiler enforces immutability of the incoming props (update any usages or
tests that expect the previous mutable type if necessary).

In `@packages/web/src/lib/use-live-status.ts`:
- Line 7: The import statement includes an unused symbol useTRPCClient; remove
useTRPCClient from the import so only useTRPC is imported (i.e., update the
import from "./trpc.js" to exclude useTRPCClient) to eliminate the unused import
in use-live-status.ts.

In `@packages/web/tsconfig.json`:
- Line 23: The tsconfig "include" currently points directly at
../server/src/trpc/router.ts which creates tight coupling; instead, export the
server's router type (e.g., export type AppRouter from a stable entry like
server package's index or a dedicated types file) and consume it via a package
import in the web code; then remove ../server/src/trpc/router.ts from
packages/web/tsconfig.json "include" and update any web files that reference the
type to use "import type { AppRouter } from 'server'". Ensure the server package
re-exports AppRouter (unique symbol AppRouter) from a stable entrypoint and
update package exports/typings so the web package can type-import it without
cross-package source includes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 54a4df8d-4bc0-452c-aee7-6b9eea9b776d

📥 Commits

Reviewing files that changed from the base of the PR and between 61bea2a and 007f1a6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (41)
  • CLAUDE.md
  • DESIGN.md
  • README.md
  • design/sync.md
  • design/ui.md
  • e2e/edit-post-completion.spec.ts
  • e2e/global-setup.ts
  • e2e/realtime-status.spec.ts
  • e2e/reconnect-resume.spec.ts
  • packages/server/package.json
  • packages/server/src/events.test.ts
  • packages/server/src/events.ts
  • packages/server/src/index.ts
  • packages/server/src/store/sync.test.ts
  • packages/server/src/store/sync.ts
  • packages/server/src/trpc/routes/sync.integration.test.ts
  • packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts
  • packages/server/src/trpc/routes/sync.test.ts
  • packages/server/src/trpc/routes/sync.ts
  • packages/server/tsconfig.json
  • packages/web/package.json
  • packages/web/src/lib/journal-query.ts
  • packages/web/src/lib/merge-journal.test.ts
  • packages/web/src/lib/merge-journal.ts
  • packages/web/src/lib/query-client.ts
  • packages/web/src/lib/trpc-providers.tsx
  • packages/web/src/lib/trpc.ts
  • packages/web/src/lib/use-group-status.ts
  • packages/web/src/lib/use-live-status.ts
  • packages/web/src/lib/use-sync-queue.ts
  • packages/web/src/main.tsx
  • packages/web/src/screens/Comparison.tsx
  • packages/web/src/screens/GroupSetup.tsx
  • packages/web/src/screens/Invite.tsx
  • packages/web/src/screens/Landing.tsx
  • packages/web/src/screens/PersonApp.tsx
  • packages/web/src/screens/Question.tsx
  • packages/web/tsconfig.json
  • playwright.config.ts
  • todo.md
  • vitest.config.ts
💤 Files with no reviewable changes (3)
  • e2e/global-setup.ts
  • packages/server/src/index.ts
  • packages/web/src/lib/use-group-status.ts

Comment thread DESIGN.md Resolved
Comment thread design/sync.md Resolved
Comment thread design/sync.md Resolved
Comment thread e2e/realtime-status.spec.ts Resolved
Comment thread packages/web/src/screens/Question.tsx Resolved
Comment thread todo.md Resolved
iskhakovt and others added 3 commits April 11, 2026 17:23
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]>
…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]>
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]>
@iskhakovt

Copy link
Copy Markdown
Owner Author

Response to review

Pushed 3 commits in response to this review (1f3125d, 12615f7, 3539acd).

Actionable comments (6)

File Status Commit
DESIGN.md:67 lazy-split wording fixed 1f3125d
design/sync.md:237 stoken/id contract fixed (explicit push-cursor vs read-cursor split) 1f3125d
design/sync.md:274 polling section fixed (WS-first rewrite) 1f3125d
e2e/realtime-status.spec.ts:33 timer placement fixed 3539acd (part of full E2E rewrite)
Question.tsx:61 onSuccess return no change needed — expression-body arrow already returns the invalidation promise. See inline reply. —
todo.md:10 polling contradiction already resolved — contradictory Done entries were removed before this review —

Nitpick comments (5)

File Status Notes
sync.test.ts:63 hoist pushOk fixed 1f3125d
sync.journal-subscription.integration.test.ts:256 specific racing entry fixed 1f3125d — now uses collected.find(e => e.operation === racingOp)
trpc-providers.tsx:22 Readonly<{ children }> rejected Isolated style island in a codebase that otherwise doesn't use Readonly<Props>. React's prop contract is immutable by cultural convention; Readonly<T> is also shallow and doesn't prevent the common props.foo.bar = x footgun. Added a p3 task in todo.md to land eslint-react/prefer-read-only-props as a codebase-wide convention in one bulk pass, which is the right way to enforce this.
use-live-status.ts:7 unused useTRPCClient already clean Stale CR comment — no such import exists in the file. Grep confirms.
tsconfig.json:23 direct cross-package include rejected This is a documented TS2883 workaround (see tsconfig header comment). tRPC's tracked() return type names @trpc/server/unstable-core-do-not-import, which breaks declaration emit for consumers. The direct-source-include is the pragmatic workaround until there's an upstream fix, and the import pattern matches tRPC's own canonical relative-path type import. Added a one-liner to the tsconfig comment acknowledging the coupling cost (mechanical + cheap to refactor if the file moves).

Unrelated work that came out of this review

While investigating the Question.tsx CR comment, I found a real bug: a fresh user with no stored categories saw the "No questions for your selected categories" empty state because selectedCategories was read from localStorage inline on every render and the default-selection logic lived in a useEffect that wrote storage but never re-rendered.

Fix landed in 12615f7, with a regression test e2e/fresh-user-no-preseed.spec.ts.

The reason this bug wasn't caught earlier: every existing E2E spec was pre-seeding selectedCategories via a setCategories helper that wrote directly to scoped localStorage, bypassing the Summary UI entirely. None of the tests ever exercised the fresh-user default path.

That's fixed in 3539acd: every bypass helper is deleted (or documented as adversarial-only), and tests now go through the real UI via a new narrowToCategory helper that clicks through Summary. global-setup.ts also now runs vite build unconditionally before serving dist/, because the earlier setup silently served stale bundles.

35/35 E2E tests pass, ~3 min wall time.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
design/sync.md (1)

253-253: ⚠️ Potential issue | 🟡 Minor

Minor: "Client side" should be hyphenated.

Static analysis flagged this grammatical issue.

Suggested fix
-Client side (`wsLink` in tRPC v11):
+Client-side (`wsLink` in tRPC v11):
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@design/sync.md` at line 253, The phrase "Client side" in the line containing
"Client side (`wsLink` in tRPC v11):" should be hyphenated to "Client-side" to
fix the grammar; locate the occurrence referencing wsLink and tRPC v11 in the
sync documentation and replace "Client side" with "Client-side" (also scan for
any other identical occurrences of "Client side" in the file and update them
similarly).
🧹 Nitpick comments (2)
e2e/edit-post-completion.spec.ts (1)

87-93: Use a reload/direct revisit for the “did not unmark” assertion.

goBack() only replays the SPA history entry. A stale in-memory completion flag can still make this pass even if the button accidentally changed persisted/server state. Reloading /waiting after the navigation would exercise the real guard.

Suggested tightening
-    await alice.goBack();
-    await expect(alice.getByText("Waiting for everyone")).toBeVisible();
+    await alice.goBack();
+    await alice.reload();
+    await expect(alice).toHaveURL(/\/waiting/);
+    await expect(alice.getByText("Waiting for everyone")).toBeVisible();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@e2e/edit-post-completion.spec.ts` around lines 87 - 93, The test's assertion
uses alice.goBack(), which only replays SPA history and can miss server-side
changes; replace the history-based check with an actual reload or direct revisit
to the waiting page (e.g., use alice.reload() or alice.goto('/waiting') instead
of alice.goBack()) and then assert await expect(alice.getByText("Waiting for
everyone")).toBeVisible() so the guard is exercised against persisted/server
state.
packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts (1)

122-123: Prefer interface over object type aliases here.

JournalEntry and TrackedMessage are object shapes and should use interface to match repository conventions.

♻️ Proposed refactor
-type JournalEntry = { id: number; personId: string; operation: string };
-type TrackedMessage = { entries: JournalEntry[] };
+interface JournalEntry {
+  id: number;
+  personId: string;
+  operation: string;
+}
+
+interface TrackedMessage {
+  entries: JournalEntry[];
+}

As per coding guidelines, **/*.{ts,tsx}: “Use interface for defining object shapes in TypeScript.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts`
around lines 122 - 123, Replace the object type aliases with interfaces: change
the declarations for JournalEntry and TrackedMessage (currently declared as
"type JournalEntry = { id: number; personId: string; operation: string }" and
"type TrackedMessage = { entries: JournalEntry[] }") to interface declarations
so they follow the repository convention (e.g., "interface JournalEntry { ... }"
and "interface TrackedMessage { entries: JournalEntry[] }"); keep the same
property names and types and ensure any imports/usages continue to refer to
JournalEntry and TrackedMessage unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@e2e/fill-questionnaire.spec.ts`:
- Around line 90-100: The locator that reads the "digits/digits" fraction (used
to set essentialsCount and adventurousCount) is too generic and first()-selects
whatever matches in DOM order; scope that lookup to the Power Exchange row
instead so you always read the Power Exchange fraction. Update the two places
where you call page.locator("text=/\\d+\\/\\d+/").first() (the code that sets
essentialsCount and adventurousCount) to locate the row containing the "Power
Exchange" label (e.g., use page.getByText("Power Exchange") or a locator
targeting that row) and then query its descendant text matching /\d+\/\d+/,
keeping the subsequent split/Number logic unchanged; this ensures the tier
change check after page.getByText("Adventurous").click targets the correct
counter.

In `@e2e/helpers.ts`:
- Line 159: The selector uses new RegExp(`^${targetLabel}`) in e2e/helpers.ts
which breaks if targetLabel contains regex metacharacters; fix by escaping
targetLabel before constructing the RegExp (create/inline a small escape
function that replaces characters like . * + ? ^ $ { } ( ) | [ ] \ with escaped
versions, then build new RegExp(`^${escapedLabel}`) for page.getByRole("button",
{ name: ... }).click()); update any uses of targetLabel in this file to use the
escaped version.

In
`@packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts`:
- Line 337: Replace the fragile fixed sleep (await new Promise((r) =>
setTimeout(r, 50))) with a bounded poll that repeatedly checks the listener
count until a deadline (e.g., Date.now()+timeoutMs) before making the assertion;
poll at short intervals (e.g., 10–50ms), break early when the expected value of
listenerCount is observed, and fail the test if the deadline elapses—apply this
change around the test's listener cleanup assertion that references
listenerCount so the assertion becomes deterministic under CI.

---

Duplicate comments:
In `@design/sync.md`:
- Line 253: The phrase "Client side" in the line containing "Client side
(`wsLink` in tRPC v11):" should be hyphenated to "Client-side" to fix the
grammar; locate the occurrence referencing wsLink and tRPC v11 in the sync
documentation and replace "Client side" with "Client-side" (also scan for any
other identical occurrences of "Client side" in the file and update them
similarly).

---

Nitpick comments:
In `@e2e/edit-post-completion.spec.ts`:
- Around line 87-93: The test's assertion uses alice.goBack(), which only
replays SPA history and can miss server-side changes; replace the history-based
check with an actual reload or direct revisit to the waiting page (e.g., use
alice.reload() or alice.goto('/waiting') instead of alice.goBack()) and then
assert await expect(alice.getByText("Waiting for everyone")).toBeVisible() so
the guard is exercised against persisted/server state.

In
`@packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts`:
- Around line 122-123: Replace the object type aliases with interfaces: change
the declarations for JournalEntry and TrackedMessage (currently declared as
"type JournalEntry = { id: number; personId: string; operation: string }" and
"type TrackedMessage = { entries: JournalEntry[] }") to interface declarations
so they follow the repository convention (e.g., "interface JournalEntry { ... }"
and "interface TrackedMessage { entries: JournalEntry[] }"); keep the same
property names and types and ensure any imports/usages continue to refer to
JournalEntry and TrackedMessage unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5697a4a8-f508-4dfa-8d75-b4b78124eaeb

📥 Commits

Reviewing files that changed from the base of the PR and between 007f1a6 and 3539acd.

📒 Files selected for processing (22)
  • DESIGN.md
  • design/sync.md
  • e2e/answer-variety.spec.ts
  • e2e/completion.spec.ts
  • e2e/edit-post-completion.spec.ts
  • e2e/fill-questionnaire.spec.ts
  • e2e/fresh-user-no-preseed.spec.ts
  • e2e/global-setup.ts
  • e2e/helpers.ts
  • e2e/multi-tab.spec.ts
  • e2e/realtime-status.spec.ts
  • e2e/reconnect-resume.spec.ts
  • e2e/refresh.spec.ts
  • e2e/results.spec.ts
  • e2e/self-pick-flow.spec.ts
  • e2e/sync-conflict.spec.ts
  • e2e/two-player.spec.ts
  • packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts
  • packages/server/src/trpc/routes/sync.test.ts
  • packages/web/src/screens/Question.tsx
  • packages/web/tsconfig.json
  • todo.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • todo.md
  • e2e/realtime-status.spec.ts
  • e2e/global-setup.ts
  • packages/web/tsconfig.json

Comment thread e2e/fill-questionnaire.spec.ts Resolved
Comment thread e2e/helpers.ts Resolved
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]>
@iskhakovt

Copy link
Copy Markdown
Owner Author

Response to 4th review (060129c)

Actionable (3)

Item Status Commit
fill-questionnaire.spec.ts scope \d+/\d+ to Power Exchange row ✅ fixed (scoped locator via hasText: /^Power Exchange\s*\d+\/\d+/) 060129c
helpers.ts escape regex in narrowToCategory ✅ fixed 060129c
journal-subscription.integration.test.ts replace setTimeout(50) with bounded poll ✅ fixed — upgraded to Vitest's expect.poll instead of the hand-rolled loop. 1 line, retries the assertion not the read, surfaces observed values in failure message, uses Vitest's configured interval/timeout defaults. See inline reply for rationale. 060129c

Duplicate / nitpick (2)

Item Status Commit
design/sync.md:253 "Client side" → "Client-side" hyphenation ✅ fixed 060129c
edit-post-completion.spec.ts use reload() instead of plain goBack() to actually exercise the guard ✅ fixed (now goBack + reload + URL assertion) 060129c

Rejected (1)

Item Reason
sync.journal-subscription.integration.test.ts:122 prefer interface over type alias Style-only, and CR's claim that interface "matches repository conventions" doesn't hold — the repo mixes both for object shapes (grep shows multiple type X = {...} aliases alongside interface). Not worth churning a perfectly valid type alias for a stylistic preference that isn't even consistent.

iskhakovt and others added 2 commits April 11, 2026 17:51
…s 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]>
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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
e2e/helpers.ts (1)

163-164: Make the category-row selector exact.

new RegExp(\^${escapedLabel}`)still matches longer labels with the same prefix, so a future category likeGroupwould also matchGroup & External. Closing the pattern with $` keeps this helper deterministic.

Suggested change
-  await page.getByRole("button", { name: new RegExp(`^${escapedLabel}`) }).click();
+  await page.getByRole("button", { name: new RegExp(`^${escapedLabel}$`) }).click();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@e2e/helpers.ts` around lines 163 - 164, The selector currently uses new
RegExp(`^${escapedLabel}`) which matches prefixes and can erroneously match
longer labels; update the regex used in page.getByRole("button", { name: ... })
to anchor the end as well (e.g., change the pattern to `^${escapedLabel}$`) so
the button name match is exact for the escapedLabel variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@e2e/edit-post-completion.spec.ts`:
- Around line 8-10: The test creates Playwright contexts via
browser.newContext() (e.g., aliceCtx, bobCtx) but only closes them on the happy
path; wrap each manual context allocation in a try/finally so the context is
always closed on failure. For each occurrence (aliceCtx, bobCtx created before
calling createGroupAndSetup or before newPage/other work), move the test logic
inside a try block and call await aliceCtx.close() / await bobCtx.close() in the
corresponding finally block to ensure cleanup.

---

Nitpick comments:
In `@e2e/helpers.ts`:
- Around line 163-164: The selector currently uses new
RegExp(`^${escapedLabel}`) which matches prefixes and can erroneously match
longer labels; update the regex used in page.getByRole("button", { name: ... })
to anchor the end as well (e.g., change the pattern to `^${escapedLabel}$`) so
the button name match is exact for the escapedLabel variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f666798c-a8cf-426e-b86c-57b560dfb46b

📥 Commits

Reviewing files that changed from the base of the PR and between 3539acd and 060129c.

📒 Files selected for processing (5)
  • design/sync.md
  • e2e/edit-post-completion.spec.ts
  • e2e/fill-questionnaire.spec.ts
  • e2e/helpers.ts
  • packages/server/src/trpc/routes/sync.journal-subscription.integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • e2e/fill-questionnaire.spec.ts

Comment thread e2e/edit-post-completion.spec.ts Resolved
iskhakovt added a commit that referenced this pull request Apr 11, 2026
…xtures

Addresses the final CR comment on #9: manual `browser.newContext()`
instances are not auto-disposed by Playwright. If a test fails
mid-flow, contexts leak until the worker exits, which can starve
memory and produce incomplete traces.

Instead of adding try/finally blocks to every test (CR's suggestion)
or a factory escape hatch, land named per-role fixtures in
fixtures.ts:

  - `alice` / `bob` — each provides a Page inside its own fresh
    BrowserContext. Two-user tests destructure whichever they need;
    Playwright's fixture-level lazy evaluation ensures unused
    fixtures never create contexts.
  - `multiTab` — single shared BrowserContext + pre-created admin
    Page. Used only by `multi-tab.spec.ts` which intentionally
    tests cross-tab localStorage isolation within one browser.

Every per-test manual `browser.newContext()` + `ctx.close()` pair
is gone. Test signatures now read as what they need:
  async ({ alice, bob }) => { ... }
  async ({ multiTab: { ctx, admin } }) => { ... }

Also fixed: the Alice-only `/waiting` "Edit my answers" test in
`edit-post-completion.spec.ts` was previously creating a manual
context for no reason — it's now on the built-in `{ page }` fixture
since it's a genuinely single-user test.

Why this pattern instead of a factory:
  - Self-documenting signatures (the test parameters tell you the
    topology before you read the body)
  - Lazy fixture evaluation: a `{ alice }` test doesn't create a
    Bob context
  - Type-safe, composable: adding roles means adding fixtures
  - Canonical per Playwright's fixture docs — no escape hatch needed

Files touched: fixtures.ts + the 7 specs that previously used
`browser.newContext()` manually.

Refs: coderabbitai review on #9 (edit-post-completion.spec.ts:10)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@iskhakovt
iskhakovt merged commit ef8bcee into main Apr 11, 2026
7 checks passed
@iskhakovt
iskhakovt deleted the feat/tanstack-query-migration branch April 11, 2026 18:06
iskhakovt added a commit that referenced this pull request Apr 11, 2026
…xtures

Addresses the final CR comment on #9: manual `browser.newContext()`
instances are not auto-disposed by Playwright. If a test fails
mid-flow, contexts leak until the worker exits, which can starve
memory and produce incomplete traces.

Instead of adding try/finally blocks to every test (CR's suggestion)
or a factory escape hatch, land named per-role fixtures in
fixtures.ts:

  - `alice` / `bob` — each provides a Page inside its own fresh
    BrowserContext. Two-user tests destructure whichever they need;
    Playwright's fixture-level lazy evaluation ensures unused
    fixtures never create contexts.
  - `multiTab` — single shared BrowserContext + pre-created admin
    Page. Used only by `multi-tab.spec.ts` which intentionally
    tests cross-tab localStorage isolation within one browser.

Every per-test manual `browser.newContext()` + `ctx.close()` pair
is gone. Test signatures now read as what they need:
  async ({ alice, bob }) => { ... }
  async ({ multiTab: { ctx, admin } }) => { ... }

Also fixed: the Alice-only `/waiting` "Edit my answers" test in
`edit-post-completion.spec.ts` was previously creating a manual
context for no reason — it's now on the built-in `{ page }` fixture
since it's a genuinely single-user test.

Why this pattern instead of a factory:
  - Self-documenting signatures (the test parameters tell you the
    topology before you read the body)
  - Lazy fixture evaluation: a `{ alice }` test doesn't create a
    Bob context
  - Type-safe, composable: adding roles means adding fixtures
  - Canonical per Playwright's fixture docs — no escape hatch needed

Files touched: fixtures.ts + the 7 specs that previously used
`browser.newContext()` manually.

Refs: coderabbitai review on #9 (edit-post-completion.spec.ts:10)

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

Copy link
Copy Markdown

🎉 This PR is included in version 1.2.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

iskhakovt added a commit that referenced this pull request Apr 11, 2026
* test(e2e): replace manual browser.newContext() with named per-role fixtures

Addresses the final CR comment on #9: manual `browser.newContext()`
instances are not auto-disposed by Playwright. If a test fails
mid-flow, contexts leak until the worker exits, which can starve
memory and produce incomplete traces.

Instead of adding try/finally blocks to every test (CR's suggestion)
or a factory escape hatch, land named per-role fixtures in
fixtures.ts:

  - `alice` / `bob` — each provides a Page inside its own fresh
    BrowserContext. Two-user tests destructure whichever they need;
    Playwright's fixture-level lazy evaluation ensures unused
    fixtures never create contexts.
  - `multiTab` — single shared BrowserContext + pre-created admin
    Page. Used only by `multi-tab.spec.ts` which intentionally
    tests cross-tab localStorage isolation within one browser.

Every per-test manual `browser.newContext()` + `ctx.close()` pair
is gone. Test signatures now read as what they need:
  async ({ alice, bob }) => { ... }
  async ({ multiTab: { ctx, admin } }) => { ... }

Also fixed: the Alice-only `/waiting` "Edit my answers" test in
`edit-post-completion.spec.ts` was previously creating a manual
context for no reason — it's now on the built-in `{ page }` fixture
since it's a genuinely single-user test.

Why this pattern instead of a factory:
  - Self-documenting signatures (the test parameters tell you the
    topology before you read the body)
  - Lazy fixture evaluation: a `{ alice }` test doesn't create a
    Bob context
  - Type-safe, composable: adding roles means adding fixtures
  - Canonical per Playwright's fixture docs — no escape hatch needed

Files touched: fixtures.ts + the 7 specs that previously used
`browser.newContext()` manually.

Refs: coderabbitai review on #9 (edit-post-completion.spec.ts:10)

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

* chore(e2e): drop redundant "single-user" comment

The test signature (`async ({ page }) => ...`) already communicates
that this is a single-user test using the built-in page fixture.
The comment restates what the code says.

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

---------

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

Replaces `.stagger-1` through `.stagger-5` (five hardcoded rules,
silent no-op on a 6th element) with a single `.stagger` class whose
delay is driven by an inline `--stagger-index` custom property per
element.

Before:
  <div className="stagger-3">...</div>
  /* .stagger-3 { animation-delay: 0.25s; } */

After:
  <div className="stagger" style={{ "--stagger-index": 2 }}>...</div>
  /* .stagger { animation-delay: calc(var(--stagger-index, 0) * 100ms + 50ms); } */

Scales to any count, no ceiling. Missing --stagger-index falls back
to 0 (no delay) — gracefully degrades rather than silently dropping
the animation. The reduced-motion override also simplifies: one
class selector instead of two attribute-prefix selectors.

Applied in Landing, WelcomeScreen, Comparison. Zero visual change —
the calc reproduces the exact delays of the old hardcoded rules
(index 0→50ms, 1→150ms, 2→250ms, 3→350ms, 4→450ms).

Also adds three todo items:
- `p3` migrate to CSS `sibling-index()` once Firefox ships it
  (caniuse.com/css-sibling-functions) — fully declarative, no
  inline style needed
- `p2` adopt Pino server logger (already listed in DESIGN.md as
  "Pino available" but not wired up)
- `p2` mention TanStack Query in README/DESIGN.md — the migration
  from PR #9 landed but some docs still describe the old hand-rolled
  state pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 11, 2026
* feat(web): polish Landing / Question / Comparison screens

A refresh of the three most visible screens under the existing Peach &
Sage theme — no functional changes, just visual intentionality.

Landing
  - Atmospheric backdrop: two drifting peach blobs + one sage accent,
    pointer-events:none, hidden from screen readers
  - Larger logo with a warm drop-shadow glow
  - Tighter display typography (-0.03em tracking, 0.95 leading)
  - Italic tagline flanked by thin accent rules
  - Staggered entrance via new .stagger-1..5 utilities
  - Footer separators using middle-dot glyphs

QuestionCard + WelcomeScreen
  - Category header rebuilt as a pulsing-dot pill with tabular position
    ("ORAL · 3/11") — reads as one "where am I" unit
  - Question heading keyed on screen.key so each question fades in
    individually (page-turning rhythm)
  - Progress bar: gradient fill, inset track shadow, warm outer glow
  - WelcomeScreen: eyebrow label, 2.25rem display heading, thin rules
    framing the question count

Comparison
  - Header: "Everyone's done / Your matches" display treatment
  - Summary strip: tabular Go-for-it + total counts with vertical
    divider (testids added for reliable test targeting)
  - Visual hierarchy for match types:
    · green-light → gradient container + solid accent badge
    · match → accent-light container
    · both-maybe / possible → surface-tone container
    · fantasy → dashed border + italic
  - Category headings become tracked-caps with accent-dot marker + fill
    rule + per-category count
  - Match rows carry data-testid + data-match-type for E2E targeting
  - Empty state rewritten from clinical to warm:
    "No overlaps this time — but that's part of the conversation too"
  - "Change my answers" affordance gets a pencil icon

CSS
  - Soft radial background wash (top-left peach 6%, bottom-right
    accent-light 8%) via background-attachment:fixed
  - @Keyframes floatA/floatB for drifting blobs (18s/22s, offset)
  - @Keyframes celebrate reserved for future micro-interactions
  - Lexend stylistic alternates via font-feature-settings
  - Respects prefers-reduced-motion

Bundle size impact: ~7.76 KB gzipped CSS (was ~7.1 KB), main chunk
unchanged.

(Originally committed as `style(web):` — renamed to `feat(web):` since
the word "style" in conventional commits means code formatting, not
visual design. This is a user-visible UI refresh and should ship as a
release.)

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

* fix(server): deterministic ordering for member list + journal replay

Two distinct ordering bugs found while investigating an E2E flake
during the feat/ui-polish rebase.

(1) Member ordering (groups.getStatus + sync.journalSince)

  setupAdmin inserts admin + partners in one transaction; Postgres's
  now() returns the transaction START time, so all persons share
  createdAt. The existing `.orderBy(persons.createdAt)` had no stable
  tiebreaker — Postgres's heap/index scan order became the de-facto
  sort, which can flip across runs (after VACUUM, under parallel
  query, etc.).

  Symptom: the E2E two-player test intermittently saw the pair
  heading in a non-canonical order. Caught as a single retry-passing
  flake; the underlying bug was real.

  Fix: order by `createdAt, id`. createdAt separates persons added
  in different transactions (e.g. initial setupAdmin vs a later
  addPerson call). id (UUID) is the stable tiebreaker for persons
  sharing a transaction timestamp.

  No `isAdmin DESC`: admin is a technical role (the creator), not a
  social hierarchy. The client re-sorts for display (viewer-first +
  alphabetical, see Comparison.tsx in the follow-up commit); the
  server just needs a deterministic neutral order for caching and
  stable-sort pre-conditions.

(2) Journal replay ordering (sync.push — both the conflict and the
    success paths returned entries for client replay WITHOUT an
    ORDER BY)

  Symptom: none observed yet — but this is a latent data-corruption
  bug. Clients replay these entries using last-write-wins semantics:
  if the server ever returns them out of commit order (which Postgres
  can, under parallel query plans, after VACUUM, or with different
  planner stats), the client's final state ends up wrong. Two ops on
  the same key replayed in wrong order = the newer answer is
  silently overwritten by the older one.

  Fix: `.orderBy(journalEntries.id)` on both push branches. The id is
  a bigserial assigned at INSERT time; filtered by `personId = X`,
  each person's client serializes pushes so id ASC = commit order
  strictly.

Audit: grep'd all `.from(persons|journalEntries|groups|categories|
questions)` call sites in packages/server/src/. Remaining queries are
either single-row (limit 1) or already have explicit ordering. No
other unguarded multi-row reads found.

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

* fix(web): pair heading renders viewer as "You", others alphabetical

Previously the pair heading in /results used the raw member order
from the server, which (after the server-side ordering fix) meant
the heading read "Alice & Bob" for everyone regardless of who was
viewing. In a couples app where partners are semantically equal,
this hardcodes an arbitrary naming order — Bob viewing his own
results sees "Alice & Bob" as if Alice's results were primary and
his were secondary.

Viewer-first rendering:
  - Comparison sorts members locally: viewer first, then others
    sorted alphabetically by decrypted name
  - The viewer's name is rendered as the pronoun "You" in tab
    buttons and the h2 pair heading
  - buildPairMatches also gets the viewer's display name so match
    text labels read as "You want X" / "X wants you"

Pair generation naturally falls out of the sort: all `{viewer, X}`
pairs come before any `{other, other}` pairs, because viewer sits
at memberAnswers[0] after the sort. For 3+ person groups, you-pairs
get tab prominence and other-vs-other pairs come after — viewer
sees their own pairs first, but no pairs are hidden.

Examples for 2-person:
  - Alice viewing: "You & Bob"
  - Bob viewing:   "You & Alice"

Examples for 3-person (Alice viewing, [Alice, Bob, Carol]):
  - Tabs: [You & Bob] [You & Carol] [Bob & Carol]

Tests updated: results, self-pick-flow, two-player now assert
"You & Alice" or "You & Bob" instead of the hardcoded "Alice & Bob".

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

* docs(claude): clarify conventional-commit type semantics

Add a table mapping each commit type to what it means and whether it
triggers a release. The key gotcha: in Angular's vocabulary, `style`
means CODE formatting (whitespace, semicolons, lint fixes) — NOT
visual/UX changes. A UI polish that ships pixels to users is `feat`,
not `style`.

Caught this when a polish commit was about to be named
`style(web):` and would have suppressed the release — users wouldn't
have seen the new design until some unrelated feat/fix landed later.

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

* chore(e2e): set retries=0 to surface flakes instead of hiding them

A retry that passes is a flake that deserves investigation, not
silent absorption. If a flake shows up, investigate the root cause
rather than papering over it.

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

* docs(todo): add DB indices audit — zero non-PK indices on hot paths

The repo currently has zero non-PK indices on journal_entries,
persons, and questions. Fine at dev scale (seq-scans hit a warm
heap in <1ms), but at production scale every sync.push would
linearly scan millions of rows.

Logged as p2 for eventual work; the composite `(person_id, id)` on
journal_entries is the critical one (covers every sync.push filter
+ the ORDER BY in one B-tree traversal). Cross-moved from the
claude-code session memory scratchpad.

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

* fix(web): accessibility — reduced-motion + tab keyboard navigation

(1) reduced-motion fully disables decorative animations.

The prior block only reset `.animate-in` and `*` animation-duration.
The infinite `.float-a`/`.float-b`/`.celebrate` animations would
still loop at ~100Hz under reduced-motion (imperceptibly, but
wasteful and arguably still motion per WAI-ARIA). Explicit
`animation: none !important` for the decorative classes + stagger
utilities is stricter and cleaner.

(2) Pair tablist: roving tabindex + arrow key navigation.

Per WAI-ARIA APG, `role="tab"` inside a `role="tablist"` requires
keyboard navigation (ArrowLeft/ArrowRight/Home/End) and roving
`tabIndex` (0 on active, -1 on others). The previous implementation
announced as tabs but only responded to click.

Added handleTabKeyDown on the tablist:
  - ArrowRight/ArrowLeft: previous/next pair with wrap
  - Home/End: first/last pair
  - Activates the new pair (setActivePairKey) and focuses the
    newly-active button to keep the keyboard user inside the tablist

Only fires for 3+ person groups (when showTabs is true). For
2-person the tablist doesn't render, so this is purely additive.

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

* refactor(web): extract Comparison component types to interfaces

Per CLAUDE.md's "Idiomatic TypeScript — use interfaces for object
shapes" convention. Extracts three inline type literals into named
interfaces: `MatchStyle` (the MATCH_STYLES table value shape),
`ComparisonProps`, and `PairComparisonProps`.

Zero behavior change — pure type-level refactor.

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

* test(e2e): await visibility before counting match-type rows

`await rows.count()` can race with rendering: the count is captured
at the moment the locator is queried, which may be before React
has committed the match rows into the DOM (even though the parent
"Your matches" heading is already visible). Prefix each count
assertion with `await expect(rows.first()).toBeVisible()` to
guarantee at least one row is rendered before counting.

Playwright's standard pattern for "I expect N elements, where
N > 0": wait for visibility first, then assert the count.

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

* fix(web): drop "(You)" parenthetical on viewer pair match-row labels

Previously, give/receive rows concatenated the A-name in parens to
disambiguate whose perspective the row reflects — e.g.
"eating out (Alice)" when Alice is A. After the viewer-first rename
landed, this produced "eating out (You)" on every viewer-pair row,
which reads as grammatically stilted label syntax rather than a
natural description.

The parenthetical was only ever useful for disambiguation in
other-vs-other pairs (3+ person groups, e.g. Bob & Carol viewed by
Alice). Viewer pairs already read naturally from A's perspective
because both giveText ("Talking dirty to your partner") and
receiveText ("Hearing dirty talk from your partner") are phrased
with A as the implicit subject.

Refactored buildPairMatches to take an options object with an
explicit `aIsViewer` flag. When true, the parenthetical is omitted.
When false, existing behavior is preserved for other-vs-other pairs.

- Viewer pair (You & Bob): "Talking dirty to your partner"
- Other pair (Bob & Carol, viewed by Alice): "Talking dirty to your partner (Bob)"

Includes unit tests for both cases.

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

* test(e2e): regression guard — viewer-pair give/receive labels have no "(You)"

The "(You)" parenthetical-drop behavior from the previous commit
(57da757) was unit-tested in build-pair-matches but had zero E2E
coverage: every existing E2E narrows to "Group & External" (6
mutual + 1 give/receive) which barely exercises the give/receive
display path.

Added a focused test that narrows to "Bondage & Restraint" — the
only category with ZERO mutual questions (9 give/receive only), so
every rendered match row is guaranteed to use giveText/receiveText.
The test asserts:
  - at least one match row exists (display path was exercised)
  - `getByText("(You)")` has count 0 (no parenthetical leaked)

Also adds a todo for a proper 3-person E2E covering the parts of
Comparison.tsx that only fire in 3+ person groups:
pair-heading ordering, "(Bob)" parenthetical on other-vs-other
pairs, tab-widget keyboard navigation, multi-pair rendering.

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

* refactor(web): extract viewer-first sort + "You" display to lib/ with tests

The viewer-first sort and "You"-substitution were inline in
Comparison.tsx and only E2E-verified. Both are pure functions with
branchy edge-case behavior (viewer absent, name ties, single
member, empty list) that belong in a unit-testable lib helper.

New: `packages/web/src/lib/member-display.ts` exports:
  - `sortMembersViewerFirst(members, viewerId)` — viewer at index 0,
    others alphabetical via localeCompare (case-insensitive, not
    binary string compare). Defensive: returns alphabetical list
    without a viewer prefix if viewerId isn't found. Relies on ES2019
    stable sort for tied-name input-order preservation. Non-mutating.
  - `viewerDisplayName(member, viewerId)` — returns "You" for viewer,
    member.name otherwise.

Tests cover: empty list, single-member (is/isn't viewer), viewer
first/middle/last in input, alphabetical sort independence from
input order, case-insensitive localeCompare (would fail under
binary `<` string compare), stable sort on ties, viewer-not-found
fallback, input array immutability, and `viewerDisplayName` for
viewer/non-viewer/empty-name cases.

Comparison.tsx now imports both helpers and becomes 4 lines shorter.
Zero behavior change.

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

* refactor(web): unify PairComparison render branches to dedupe props + key

The tabs branch passed key={`${a.id}-${b.id}`}; the no-tabs branch
didn't. Benign in practice (no-tabs has exactly one pair, key never
changes), but the asymmetry was confusing — future readers might
wonder whether one branch deliberately opts out of remount-on-pair-
change. Easy to drift into real inconsistency on a future edit.

Single PairComparison instantiation. The tabs vs no-tabs branches
only differ in whether we wrap with a tabpanel role. `showHeading`
derives from `!showTabs` for a single source of truth. The IIFE
inside JSX is mildly ugly but localizes the "compute once, wrap
maybe" logic without hoisting a new function component.

Zero behavior change.

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

* refactor(web): extract Comparison compute to lib/ with unit tests

Three pure functions that were inline in Comparison.tsx, now
extractable + individually unit-testable:

1. `buildPairs<T>(items)` → `lib/member-display.ts`
   All unordered pairs with i<j. Generic so tests can use primitives.
   Properties verified: n choose 2 output size, deterministic order,
   input-order preservation (the property Comparison relies on for
   "viewer-pairs first"), no mutation.

2. `nextTabIndex(key, activeIndex, length)` → `lib/member-display.ts`
   Pure math for the ARIA tablist keyboard handler. Returns null for
   non-navigation keys. Tests cover ArrowLeft/Right wrap-around,
   Home/End, length 0 and 1 edge cases, and unrecognized keys. This
   function only fires for 3+ person groups (which no E2E currently
   exercises) — unit tests are the primary coverage.

3. `buildGroupedMatches(pairMatches, questions, categories,
   categoryOrder, questionOrder)` → `lib/build-pair-matches.ts`
   Buckets pair matches by category, orders categories per
   categoryOrder, sorts within each category by questionOrder,
   drops empty categories and unknown questions. The previous
   inline version mutated `group.matches` via in-place `.sort()`;
   the extracted version is immutable (uses `.slice().sort()`).
   Tests cover empty input, single and multi-category, deterministic
   category order, dropped empty categories, within-category sort,
   missing questions, missing labels (fallback to categoryId),
   missing questionOrder entries, and input immutability.

Comparison.tsx now imports all three and is ~30 lines shorter. The
inline tab-keyboard handler reduces from 12 lines of conditionals
to a 4-line `if (next === null) return` guard. Zero behavior
change — unit and E2E tests prove it.

Unit test total: 289 (was 261, +28 new tests across the three
extracted functions).

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

* refactor(web): stagger animation via CSS custom property, not hardcoded classes

Replaces `.stagger-1` through `.stagger-5` (five hardcoded rules,
silent no-op on a 6th element) with a single `.stagger` class whose
delay is driven by an inline `--stagger-index` custom property per
element.

Before:
  <div className="stagger-3">...</div>
  /* .stagger-3 { animation-delay: 0.25s; } */

After:
  <div className="stagger" style={{ "--stagger-index": 2 }}>...</div>
  /* .stagger { animation-delay: calc(var(--stagger-index, 0) * 100ms + 50ms); } */

Scales to any count, no ceiling. Missing --stagger-index falls back
to 0 (no delay) — gracefully degrades rather than silently dropping
the animation. The reduced-motion override also simplifies: one
class selector instead of two attribute-prefix selectors.

Applied in Landing, WelcomeScreen, Comparison. Zero visual change —
the calc reproduces the exact delays of the old hardcoded rules
(index 0→50ms, 1→150ms, 2→250ms, 3→350ms, 4→450ms).

Also adds three todo items:
- `p3` migrate to CSS `sibling-index()` once Firefox ships it
  (caniuse.com/css-sibling-functions) — fully declarative, no
  inline style needed
- `p2` adopt Pino server logger (already listed in DESIGN.md as
  "Pino available" but not wired up)
- `p2` mention TanStack Query in README/DESIGN.md — the migration
  from PR #9 landed but some docs still describe the old hand-rolled
  state pattern

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

* docs(todo): add CSS toolchain + font-feature-settings scoping items

Two follow-ups flagged on the #11 review thread:

- Revisit CSS toolchain (transpiler/linter). Plain CSS + Tailwind v4
  works but we have no CSS-aware lint rules — CR flagged camelCase
  keyframe names that stylelint's keyframes-name-pattern would have
  caught. Evaluate stylelint + config-standard before the CSS file
  grows past its current ~200 lines.

- Scope `font-feature-settings: "ss01", "cv11"` off the global body.
  Harmless today (Tailwind tabular-nums uses font-variant-numeric,
  no clobber; no <code>/<pre> in the app), but latent risk: any
  future font-feature-settings on a child silently wipes the parent
  features because the property replaces rather than composes.
  Modern idiomatic fix is `font-variant-alternates: styleset(...)`
  with a `@font-feature-values Lexend { ... }` rule.

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

* chore(web): drop cargo-cult font-feature-settings line

`body { font-feature-settings: "ss01", "cv11"; }` was added during
the polish pass with a vague rationale ("Lexend stylistic
alternates"). Researched what these features actually do in Lexend:
neither Lexend's README, lexend.com, nor the Google Fonts specimen
documents any stylistic sets or character variants. Lexend's
reading-fluency mechanism (the Shaver-Troup formulation) is
delivered via seven width variants — Deca, Exa, Giga, Mega, Peta,
Tera, Zetta — not OpenType features.

So the line is either a silent no-op (the features aren't defined
in the font) or an undocumented tweak nobody can explain. Either
way, delete. Simpler CSS, no composability risk, no scoping
concerns.

Replaces the previous "scope font-feature-settings" todo with a
more meaningful one: pick the right Lexend width family for our
target readership explicitly, documented with intent.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 12, 2026
The migration to TanStack Query v5 + @trpc/tanstack-react-query landed
in #9 but the design docs still described the old hand-rolled state
pattern. Update the stack table, real-time delivery section, client
logic, local storage split, and partner status delivery to reflect the
current useSuspenseQuery / useMutation / useSubscription patterns.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
iskhakovt added a commit that referenced this pull request Apr 12, 2026
* docs: mention TanStack Query in DESIGN.md and design/sync.md

The migration to TanStack Query v5 + @trpc/tanstack-react-query landed
in #9 but the design docs still described the old hand-rolled state
pattern. Update the stack table, real-time delivery section, client
logic, local storage split, and partner status delivery to reflect the
current useSuspenseQuery / useMutation / useSubscription patterns.

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

* chore: remove completed TanStack Query docs todo

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