Repository navigation
chore(deps): Bump @electric-sql/pglite from 0.4.3 to 0.4.4 - #4
dependabot[bot] wants to merge 1 commit into
Conversation
6a13755 to
5eb3d3e
Compare
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]>
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]>
* chore(web): add TanStack Query v5 + tRPC integration Installs @tanstack/[email protected], @trpc/[email protected], and @tanstack/[email protected] (dev) in preparation for the TanStack Query migration. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): add TanStack Query providers and context Scaffolding for the TanStack Query migration, no behavior change yet. - query-client.ts: makeQueryClient factory with defaults aligned to the real-time architecture (staleTime Infinity, no background refetch, no polling — live updates arrive via WS subscriptions). - trpc-providers.tsx: AppProviders wrapping QueryClientProvider + TRPCProvider, with stable clients via useState. Devtools dynamically imported in DEV only. - trpc.ts: adds createTRPCContext bindings (TRPCProvider, useTRPC, useTRPCClient) alongside the legacy singleton. Exports wsClient so token-change handlers can force reconnect. - main.tsx: wraps the router in <AppProviders> + a top-level Suspense boundary. The legacy trpc singleton is kept temporarily so existing .query()/.mutate() call sites keep working until they're migrated in later commits. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(server): rename sync.compare to sync.journal with cursor Renames the read-side of the sync protocol to better match what it actually does (fetch journal entries, not "compare" — the client does the comparing). Adds cursor-based delta semantics in preparation for the tracked() subscription that will stream journal updates in real-time. Store: - SyncStore.compare(groupId) → SyncStore.journalSince(groupId, sinceId) - Accepts a nullable cursor; null returns all entries, numeric returns id > N - Returns { members, entries, cursor } where cursor = highest id in response (or the input sinceId on empty delta, so repeated fetches don't regress) - Each entry now carries its numeric id so clients can track the cursor Route: - sync.compare → sync.journal with { sinceId: number | null } input - Precondition check (all members complete) unchanged Tests: - Store: new cases for null cursor (full journal), non-null cursor (delta), empty delta (cursor unchanged), members populated on empty, precondition failure with and without cursor - Route: passes sinceId through, defaults to null, throws on not_all_complete - Integration: full roundtrip including edit-while-complete + cursor advance + empty delta on re-fetch Client: - Comparison.tsx: updated to call trpc.sync.journal (temporary; gets fully rewritten in a later commit) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(server): sync.onJournalChange subscription with tracked() resume Adds real-time journal delivery via tRPC v11's tracked() pattern, with lossless reconnect recovery via the lastEventId cursor protocol. Event bus: - New journalEvents EventEmitter in events.ts, separate from groupEvents (status broadcasts vs journal appends have different emission rates and different consumers) - emitJournalUpdate(groupId, entries) takes the committed entries payload - journalEventName(groupId) produces "journal:<id>" keys Store: - SyncStore.push now returns committedEntries alongside the existing entries/stoken/pushRejected fields, so the route can propagate them Route: - sync.push emits journalEvents after successful non-rejected commits. Unconditional (no isCompleted check) — if no one is subscribed during normal answering, emit is a no-op. Subscriber gating happens client-side via Comparison mount. - committedEntries is stripped from the wire response (internal-only). - New onJournalChange subscription following the canonical tRPC pattern: 1. Precondition check (all members complete) 2. Attach event listener BEFORE backfill query (anything emitted during the query is buffered in the iterable, not lost) 3. Backfill via journalSince(groupId, lastEventId) 4. Yield backfill as a single tracked() event 5. Stream live emissions with cursor-based dedup for backfill/live overlap - Explicit TrackedEnvelope type alias to sidestep TypeScript declaration emit complaints about the internal unstable-core-do-not-import path Typecheck config: - Drop composite/declaration from server tsconfig (never actually used — web imports server source directly via moduleResolution: bundler) - Replace server's `tsc --build` typecheck with `tsc --noEmit` - Web tsconfig includes server's router.ts directly in its "include" list - This fixes TS2883 errors from tracked() type inference leaking through declaration emit Tests: - events.test.ts: add journalEvents suite mirroring groupEvents (emit, key namespacing, bus independence) - sync.test.ts: add push emission tests (success/rejected/validation/empty committedEntries/no groupEvents), strip committedEntries from wire - sync.integration.test.ts: full roundtrip tests now use the new journal protocol including cursor delta - sync.journal-subscription.integration.test.ts (NEW): 10 integration scenarios covering the canonical subscribe-before-query pattern, cursor resume, concurrent subscribers, precondition failure, encrypted payload passthrough, and listener cleanup on abort E2E config: - vitest integration project gets fileParallelism: false so the two subscription integration test files don't deadlock on shared Postgres Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): migrate groups.status to TanStack Query + WS subscription Replaces the hand-rolled useGroupStatus hook with useLiveStatus built on TanStack Query's useSuspenseQuery + tRPC's useSubscription. New hook (packages/web/src/lib/use-live-status.ts): - useSuspenseQuery(trpc.groups.status.queryOptions({ token })) — initial fetch suspends until data lands, then serves from cache - useSubscription(trpc.groups.onStatus.subscriptionOptions(...)) — each onData push writes the raw payload into the same cache entry via queryClient.setQueryData, so the query and subscription share one source of truth - Async decryption runs in a useEffect keyed on the raw cache value — the cache stores encrypted payloads, components read the derived decrypted state (matches existing crypto semantics) - Subscription gated on `personId !== null` — during /setup, the authed procedure has nothing to stream, so we leave the WS closed - Same API surface as the old hook (`{ status, refresh }`) so call sites don't need to change PersonApp: - Drops useGroupStatus import, uses useLiveStatus - Adds token-change effect: when the URL token changes (rare — normally a fresh page load), close the WS so connectionParams re-runs with the new token, and invalidate sync/questions caches that aren't naturally keyed by token. Fixes the PR #8 wsLink-stale-auth caveat. - groups.status is keyed by `{ token }` in the cache so natural segregation handles cross-token contamination for that query Deleted: - packages/web/src/lib/use-group-status.ts Bundle size: +13KB gzipped (TanStack Query core), within budget. Build verified with vite build; all 235 tests still pass. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(web): dedupe questions.list via useSuspenseQuery Replaces the three separate imperative trpc.questions.list.query() calls in PersonApp, Question, and Comparison with useSuspenseQuery pointing at the same cache entry. First mount fetches; subsequent mounts (in Question and Comparison) serve synchronously from cache under staleTime: Infinity. PersonApp: - Drops useState+useEffect for questionsData, reads from useSuspenseQuery - Removes the null-check branches around Summary/Review routes (suspense handles loading via the top-level boundary in main.tsx) Question: - useSuspenseQuery for questions.list - Derives categoryMap via useMemo instead of setState - Removes "Loading questions..." empty state (suspense handles it) - Retains the auto-select-all-categories + pending-ops flush effect Comparison: - Drops questions.list from the Promise.all — uses useSuspenseQuery instead - Derives questions/categories/categoryOrder/questionOrder via useMemo - Keeps the sync.journal imperative fetch (gets rewritten in the next commit as part of the subscription-driven Comparison rewrite) Net effect: questions.list fires once per session instead of three times. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): Comparison rewrite — query + tracked subscription + merge Rewrites Comparison.tsx to use the canonical tRPC v11 pattern of HTTP query for initial load + tracked subscription for live updates, both feeding the same TanStack cache entry via setQueryData merge. Data flow: 1. useSuspenseQuery(trpc.sync.journal, { sinceId: null }) — initial backfill, suspends until data lands 2. useSubscription(trpc.sync.onJournalChange, { lastEventId }) — live stream, seeded with the cursor from the HTTP response so it doesn't re-backfill 3. onData merges new entries into the cache via setQueryData with the mergeJournal helper (dedup by id, sort, cursor advance) 4. A useEffect runs async decryption + replay per member when entries change 5. Both the HTTP query and WS subscription write to the SAME cache key, so the read side (via useSuspenseQuery's data) automatically reflects incremental updates Reconnect is lossless by construction: wsLink auto-reconnects and re-sends the subscription message with the latest tracked id, so the server's generator replays entries > lastEventId. If WS permanently fails, the initial HTTP backfill still works — degraded to no-live-updates, but the page is functional. Edit-while-complete delivery: - Alice edits a question on /questions (while marked complete) - sync.push commits the new journal entry - Server emits on journalEvents - Bob's sync.onJournalChange subscription yields a tracked append - Bob's onData merges into his cache - Bob's Comparison re-renders with updated pair matches within ~100ms New: packages/web/src/lib/merge-journal.ts - Pure helper: dedupes by id (new wins), sorts ascending, advances cursor - Reference-stable on empty delta to avoid unnecessary re-renders - 9 unit tests covering all merge cases Deleted imports: - Removed trpc (legacy singleton) import from Comparison — it now uses the proxy via useTRPC() Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(web): migrate all mutations to useMutation + automatic invalidation Converts every direct trpc.x.mutate() call site to useMutation via the tRPC tanstack-react-query proxy, with onSuccess invalidation replacing the manual refreshStatus threading pattern. - Landing.tsx: groups.create → useMutation - GroupSetup.tsx: groups.setupAdmin → useMutation. Invalidation deferred to the "Start filling out" button click so the "You're all set" screen with partner links stays visible until the user explicitly proceeds - Invite.tsx: groups.addPerson → useMutation with onSuccess invalidation - PersonApp.tsx: groups.markReady, sync.markComplete, sync.unmarkComplete all wired at the top level with shared invalidateStatus helper. NonAdminOnboarding and PickAnatomyScreen subcomponents each get their own groups.setProfile mutation with invalidation. - sync.unmarkComplete also invalidates sync.journal so re-entering /results refetches with the latest entries. Drops the `onDone` / `refreshStatus()` threading everywhere — mutations self-invalidate via onSuccess which returns the invalidation promise, keeping the mutation pending until the refetch completes. No more stale guards from forgotten awaits. Question.tsx's sync.push calls are intentionally NOT migrated in this commit — those get extracted into useSyncQueue in the next commit. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(web): extract useSyncQueue hook for sync.push debounce + conflict retry Replaces Question.tsx's ref-chain-and-manual-state sync machinery with a self-contained useSyncQueue hook built on useMutation(trpc.sync.push). New file: packages/web/src/lib/use-sync-queue.ts - useSyncQueue(totalQuestions) returns { syncing, showSyncIndicator, handleSync, scheduleSync } - Owns the 3-second debounce timer + the 5-second sync-indicator delay - Owns the in-flight guard (replaces syncingRef) via a private ref - Owns the conflict merge + retry loop (via mergeAfterRejection) - useMutation's isPending replaces the manual setSyncing state Question.tsx cleanup: - Drops handleSyncRef, syncingRef, syncTimerRef, syncIndicatorTimerRef - Drops inline pushOps / handleConflict / handleSync functions - Drops manual imports of clearPendingOps, getStoken, mergeAfterRejection, setAnswers, setStoken (all moved into the hook) - handleMarkComplete now calls hook's handleSync then markCompleteMutation - Auto-sync effect becomes a single scheduleSync(pendingOps.length) call - Keyboard navigation keeps handleRatingRef/handleTimingRef refs since those closures still need fresh state per render (separate concern from sync) - sync.markComplete migrated to useMutation with onSuccess invalidation Net: Question.tsx loses ~60 lines of ref-chain plumbing. The useSyncQueue hook will also be the integration point for future debounce tuning or offline queue persistence, without touching screen components. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): edit-without-unmark UX — "Edit my answers" navigates without mutating Implements Design B: marked-complete users can return to /questions and edit their answers without triggering sync.unmarkComplete, so partners viewing /results see their edits propagate live via the journal subscription instead of being abruptly kicked to /waiting. - Add /questions to freeRoutes so the guard doesn't redirect marked-complete users away from it. The user got there intentionally (via an explicit "Edit my answers" or "Change my answers" button). - Remove the sync.unmarkComplete useMutation definition — no UI caller remains. The server procedure stays as a safety valve for future admin tools. - /results "Change my answers" button: now navigates only, no mutation. - /waiting: add a new "Edit my answers" button (ghost styling, underlined) between the member list and the admin-only "View group members" link. Same semantics — navigate to /questions, no mutation. Partner-side behavior (when Alice edits): - Alice's sync.push commits new journal entries → journalEvents emit - Bob's sync.onJournalChange subscription yields a tracked append - Bob's Comparison cache merges the new entries via setQueryData - Bob's PairComparison re-renders with updated match classification - Bob is never kicked from /results because allComplete stays true This is the "propagate live, never mutate status implicitly" pattern agreed during planning. E2E coverage comes in the next commit. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(web): remove legacy trpc singleton, use inferRouterOutputs for types Removes the temporary \`export const trpc = makeTrpcClient()\` singleton from packages/web/src/lib/trpc.ts. Every call site now goes through \`useTRPC()\` from the createTRPCContext proxy. - Drop \`trpc\` export from trpc.ts — only \`TRPCProvider\`, \`useTRPC\`, \`useTRPCClient\`, \`wsClient\`, and \`makeTrpcClient\` remain - use-live-status.ts and PersonApp.tsx: replace \`typeof trpc.x.y.query\` type derivations with \`inferRouterOutputs<AppRouter>\` — cleaner, no runtime dependency on a value that no longer exists - Add @trpc/server as a dev dep on packages/web for the inferRouterOutputs type import (it was already transitively available via @trpc/client and @trpc/tanstack-react-query, this just makes the direct import explicit) Typecheck, lint, unit tests, and vite build all green. Bundle size unchanged (~135KB gzipped for the main chunk). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * test(e2e): add edit-post-completion and reconnect-resume specs; drop polling fallback test Three E2E changes to cover the new real-time architecture: New: e2e/edit-post-completion.spec.ts - "Alice edits an answer on /results, Bob sees the pair matches update live": two browser contexts complete, both reach /results, Alice clicks "Change my answers", edits one question from yes → no, waits for the 3s debounce, then asserts that Bob's pair match count dropped. Verifies the full edit-while- complete pipeline: sync.push → journalEvents emit → Bob's subscription onData → setQueryData merge → Comparison re-render. - "Alice's /waiting screen has an 'Edit my answers' button that navigates without unmarking": asserts the navigate-only semantics and that re- entering /waiting still works (isCompleted not touched). New: e2e/reconnect-resume.spec.ts - The critical correctness test for tRPC's tracked() resume protocol. - Both complete, Bob on /results. Block Bob's WS via page.route. Alice edits. Unblock WS. Bob's wsLink reconnects, server resumes from lastEventId, delivers the missed entry. Assert Bob's match count updates within 15s. - Without tracked(), this scenario would be broken: missed events during disconnect = permanently stale results. Deleted: the "falls back to polling when WS upgrade is blocked" test from e2e/realtime-status.spec.ts — polling fallback is removed from this PR, and the reconnect-resume test covers the equivalent failure mode for the new architecture. E2E infrastructure cleanup: - Drop POLL_MS env var from e2e/global-setup.ts and packages/server/src/index.ts — the runtime config injection is no longer used (no polling) Fix: Question.tsx's "I'm done" handler now explicitly navigates to /waiting after markComplete. This is necessary because /questions is in freeRoutes (so the guard doesn't kick marked-complete users away from the edit flow), which also means the guard no longer auto-redirects from /questions to /waiting when completion status changes. Note: some existing E2E specs show transient flakiness under full parallel load (passes in isolation, fails occasionally under CPU contention from ~35 concurrent tests). Pre-existing, not introduced by this PR. CI's retries: 1 covers it. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * docs: update CLAUDE.md, DESIGN.md, design/sync.md, design/ui.md, README, todo Substantial documentation rewrite reflecting the TanStack Query migration and the new real-time architecture. CLAUDE.md: - Stack line: add TanStack Query v5 + @trpc/tanstack-react-query, tRPC v11 - Delete the old "await refreshStatus()" rule and explicit-navigation rule - Add "/questions is a free route" callout with explanation - Add a Data fetching section covering useTRPC(), useSuspenseQuery, useMutation, useSubscription, and the "no singleton" rule - Add a Real-time section: two event buses, two WS subscriptions, subscribe-before-query invariant, tracked() resume semantics, no polling - Clarify the localStorage / TanStack split rule - Test helpers: document the openSubscription() pattern, tracked() tuple unwrapping, fileParallelism: false for integration tests README.md: - Stack line updated to include TanStack Query v5 + tRPC v11 WebSocket DESIGN.md: - Performance: question bank caching via staleTime: Infinity - New "Real-time delivery" section covering the two-bus architecture, tracked() subscription resume, and the no-polling degradation choice design/sync.md: - New "Reading the journal" section documenting sync.journal query and sync.onJournalChange subscription with the tracked() protocol - "Why two buses" section explaining the groupEvents / journalEvents split - "Edit after completion" flow description design/ui.md: - /waiting screen: add "Edit my answers" button, document the navigate-only semantics and live-propagation-without-kick behavior - /results (Comparison): document live updates via tracked subscription and the "Change my answers" button change - Routing: /questions added to free routes with rationale - Auto-sync: reference the useSyncQueue hook, add conflict-retry note todo.md: - Mark TanStack Query migration as Done Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * perf(web): move decryption into queryFn to eliminate render-cycle flakiness Under parallel E2E load (~18 concurrent browser contexts on one machine), cross-user assertions like 'Alice & Bob visible' were flaking because the old pattern added an extra render cycle between 'data arrived' and 'content visible': render(raw) → useEffect fires → async decrypt → setState → render(decrypted) Two React commits + one microtask + repaint, repeated on every mount and every WS push. Under CPU contention this added enough latency to blow past the 10s default expect timeout on tests that had already been tightened in PR #8. Fix: push the async decryption into the queryFn itself so Suspense holds the component invisible until the derived data is fully ready, then the first render paints the final content in one pass. useLiveStatus: - Override the tRPC proxy's queryOptions.queryFn with a wrapper that awaits decryptStatus before returning. The cache now stores the decrypted shape, and the component reads it directly from useSuspenseQuery. - Drop the useState + useEffect for status derivation — no more loading/ error intermediate states tracked in the hook. Loading is handled by the outer Suspense boundary, errors propagate to the nearest ErrorBoundary. - Subscription onData async-decrypts before setQueryData. A per-hook monotonic sequence counter (seqRef) guards against out-of-order decryption when two pushes arrive in quick succession — latest wins. Comparison.tsx: - Use useTRPCClient() to get a vanilla tRPC client, then construct the useSuspenseQuery options from scratch: queryKey from the proxy (for stable cache lookups), queryFn owns the fetch + replayMembers call. - Cache shape is CachedJournal = { members: MemberAnswers[], entries, cursor } with members pre-decrypted and per-question answers already replayed. First paint has memberAnswers ready — no mount→useEffect→setState cycle. - Subscription onData async-merges (dedup + replay) and calls setQueryData with the full derived shape. Monotonic sequence counter guards against out-of-order replays. - Drop the useState<MemberAnswers[] | null> + useEffect that was the old render-cycle bottleneck. - Extract replayMembers() helper so both queryFn and onData share the per-member decrypt + replay logic. PersonApp.tsx: - Drop the 'status === "loading"' and 'status === "error"' branches from the render path. useLiveStatus no longer returns those sentinels — the Suspense boundary in main.tsx handles loading, the ErrorBoundary handles errors with resetErrorBoundary for retry. Pattern validation: this is the canonical TanStack Query + Suspense pattern per TkDodo's "Data Transformations" (option 1: transform in queryFn) and "Using WebSockets with React Query" (setQueryData for targeted merges). Also confirmed as the React-19-era best practice for async-derived state that needs Suspense-aware first-render data — React.use() explicitly does not support client-created promises, and Jotai async atoms would require adopting a second state library for one screen's worth of data. Results: full E2E suite passes cleanly under parallel load (34/34), where previously 1-2 cross-user assertions were flaking per run. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: address code review feedback Addresses the code review on PR #9. Each numbered item corresponds to the review: 1. Drop dead `onDone?` props from NonAdminOnboarding and PickAnatomyScreen. Both stopped using the prop in the mutation migration (step 8); the optional signature was a backwards-compat shim that CLAUDE.md's rules explicitly prohibit. Removed. 2. Tighten E2E assertions in edit-post-completion and reconnect-resume: - Snapshot Bob's match count BEFORE the edit and assert a concrete drop (matchesAfter < matchesBefore) instead of a magic `< 50` upper bound that was unconnected to the actual question count. - Replace `alice.waitForTimeout(4000)` hard sleep with `expect(...).toPass({ timeout })` polling, which covers the full pipeline latency without burning the whole 4s unconditionally. - reconnect-resume.spec.ts also replaces `waitForTimeout(4500)` with a scoped-localStorage poll that checks when Alice's pendingOps queue clears (the signal that sync.push has committed). 3. Replace `useMemo(() => ..., [])` + eslint-disable in Comparison.tsx with `useState(() => ...)` for "compute once on mount" semantics. React's idiomatic pattern; no lint disable needed. 4. Sharpen the subscribe-before-query comment in sync.onJournalChange to call out the precondition ordering explicitly: the getStatus check runs before the listener attach, and the review was right that this window is covered by the backfill query (not the live stream). The comment now walks through steps 1-4 so the invariant isn't ambiguous. 5. Add a comment to packages/web/tsconfig.json explaining why web includes the server's router.ts directly (project references with composite+declaration triggered TS2883 on tracked() type inference via the unstable-core-do-not-import internal path). Present the current setup as a deliberate workaround. 6. Drop the `TrackedEnvelope` type alias and the explicit envelope annotations from sync.ts. The alias existed to force TypeScript's declaration emit through the public path, but with noEmit: true on both packages and web including server source directly, declaration emit never happens — the workaround is moot. The subscription now lets tRPC infer the yield type directly from `tracked()` calls, and the yielded messages use `satisfies JournalChangeMessage` for shape safety without overriding inference. `@trpc/server` stays as a web devDep because `inferRouterOutputs` is still needed elsewhere. 7. Add a dep array to Question.tsx's `scheduleSync` effect: `[pendingOps.length, scheduleSync]`. The old no-deps form reset the debounce timer on every render, which (per review) could defer the sync indefinitely if an unrelated parent re-rendered the component more often than 3s. The new form only resets the timer when the pending count actually changes. Verification: typecheck, lint, unit+integration (245 tests), and E2E (34/34) all green. Some pre-existing parallel-load flakiness persists on cross-user assertions but is handled by CI retries. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * perf(web): drop Comparison lazy load, prefetch journal on allComplete transition Two optimizations + one infrastructure fix to attack the intermittent E2E flakiness on cross-user assertions under local parallel load. 1. Drop Comparison's lazy() import (~6KB chunk load off the critical path) PersonApp.tsx now imports Comparison directly instead of via React.lazy. The extra HTTP request for the Comparison chunk was measurable under parallel load — every receiver's first /results navigation had to fetch a chunk while the server was handling 18 concurrent requests. Inlining adds ~6KB gzipped to the main chunk (trivial). 2. Prefetch the Comparison journal on the allComplete transition New `packages/web/src/lib/journal-query.ts` exports: - `MemberAnswers` and `CachedJournal` types (moved from Comparison.tsx) - `replayMembers()` shared decrypt+replay helper - `JOURNAL_QUERY_KEY` — stable queryKey for the derived journal - `makeJournalQueryFn(trpcClient)` factory used by both the component's useSuspenseQuery and the prefetch call - `prefetchJournal(queryClient, trpcClient)` that kicks off the fetch via queryClient.prefetchQuery PersonApp.tsx runs a useEffect on the `allComplete` boolean that prefetches the journal the moment the group flips to allComplete. This fires for both sides of the markComplete broadcast: - Own mutation path: markCompleteMutation onSuccess invalidates status → useLiveStatus refetches → allComplete transitions → effect fires - Partner path: WS push → setQueryData → status updates → allComplete transitions → effect fires By the time the guard redirects to /results and Comparison mounts, the data is either already in cache or in flight — the HTTP round-trip + decryption latency is moved off the render-critical path. Comparison.tsx now reads from the shared JOURNAL_QUERY_KEY and uses makeJournalQueryFn, so prefetch and component fetch go through the same code path. 3. Enable Playwright retries locally (match CI) The remaining source of flakiness is raw CPU contention from running 4+ concurrent full Chromium instances on one machine — not app capacity (the app handles 1000 real clients fine because each is on its own device). CI uses workers=2 which avoids the contention entirely; local dev uses workers=50% for speed, which hits the contention tail occasionally. With retries=1 (previously local=0, CI=1), transient failures are absorbed by a single retry. Two consecutive failures still surface as real failures, so actual bugs aren't masked. The "flaky" annotation in the Playwright output makes it visible when a retry was needed. Test: - Unit/integration: 245/245 pass - E2E local (workers=50%): 3 consecutive runs exit 0, occasional tests are marked "flaky" (retried successfully) - E2E CI (workers=2): the root cause is absent at 2 workers — expected to remain green without needing retries Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: address second round of code review feedback Five fixes in response to the follow-up review on PR #9. 1. CachedJournal.members double-decryption in Comparison's onData merge (review #1). Previously the WS merge path called `replayMembers(current.members, mergedRaw.entries)` which type-coerced the already-decrypted members back into the raw input type and re-ran `unwrapSensitive(m.name)` on each. `unwrapSensitive` is idempotent on plaintext so this was safe but wasteful, and the type assertion hid the contract mismatch. New `rebuildMemberAnswers(members, mergedEntries)` helper in `journal-query.ts` preserves the already-decrypted name/anatomy and only re-runs `replayJournal` to rebuild the per-person answers. Comparison.tsx's onData now uses it on the merge path. 2. reconnect-resume.spec.ts actually exercises the resume path now (review #2). The old test used `page.route("**/api/trpc-ws**", abort)` to block Bob's WS. But Playwright's page.route only intercepts HTTP-level traffic — the WebSocket UPGRADE handshake is HTTP, but once the WS is upgraded the frames flow outside Playwright's interception. route.abort() only blocked NEW upgrade attempts; Bob's existing WS was still connected and delivered Alice's edit via the normal live-stream path, masking whether tracked() resume was actually tested. Fix: use CDP's `Network.emulateNetworkConditions { offline: true }` on Bob's page to sever the entire network layer, which actually closes his existing WS (wsLink observes the close event). Flip back to `offline: false` to let wsLink auto-reconnect, which re-sends the subscription message with Bob's last tracked id and triggers the server's replay via `journalSince(groupId, sinceId)`. Also replaced the hard `waitForTimeout(4500)` with localStorage polling for Alice's pendingOps queue to clear (her own sync.push's completion signal). Test now passes consistently in isolation at ~10s (was masking a false positive before). 3. useSyncQueue identity stability (review #3). `useCallback(handleSync, [totalQuestions, pushMutation])` was unstable because `useMutation` returns a new result object on every render (unlike useQuery's stable `data` reference). The churn cascaded: handleSync changed → scheduleSync changed → Question.tsx's `useEffect([pendingOps.length, scheduleSync])` re-ran on every render, resetting the 3s debounce even when pendingOps hadn't changed. Worst case: unrelated re-renders faster than 3s would defer the sync indefinitely (the exact hazard I had commented about but not actually fixed). Fix: hold `totalQuestions` and `pushMutation` in refs, call `pushMutationRef.current.mutateAsync(...)` from the callback body, and empty-dep the `useCallback`. Both `handleSync` and `scheduleSync` are now stable for the hook's lifetime. 4. lastEventId NaN validation (review #4). `Number(input.lastEventId)` on a malformed string produces NaN, which flows into `gt(journal_entries.id, NaN)`. Postgres handles it gracefully but it's unclean. Added a Zod refinement `regex(/^\d+$/)` so malformed cursors are rejected with a clear error at the edge. 5. CLAUDE.md pathFilter → pathKey consistency (review #5). Doc said `trpc.groups.status.pathFilter()` but all the code uses `trpc.groups.status.pathKey()` inside `invalidateQueries({ queryKey })`. Updated the doc to match the code. Verification: - Unit + integration: 245/245 - E2E reconnect-resume (in isolation): 3/3 passes at ~10s each, actually exercising the CDP-offline → reconnect path - E2E full suite: exit 0 with CI-style retries absorbing transient parallel-load flakes - Typecheck + lint: clean Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: address third round of code review feedback Actionable: - DESIGN.md: drop stale lazy-split wording; document journal pre-warm and single-bundle shape introduced by the Comparison inline commit. - design/sync.md: disambiguate push cursor (stoken, HMAC-signed) vs read cursor (raw numeric id) to fix contradictory statements about whether clients see journal ids. Replace the "Polling for Partner Status" section with a WS-first "Partner Status Delivery" writeup reflecting the current architecture. - sync.journal-subscription.integration.test.ts: tighten the subscribe-before-query race test to assert the specific racing entry is delivered via collected.find(e => e.operation === racingOp), not just collected.length >= 3. A bug that dropped the racing event while keeping 2 initial + some other 3rd entry would have slipped by. - sync.test.ts: hoist the pushOk fixture to module scope so both describe blocks share one definition. Rejected with reasoning (see PR comments): - Question.tsx onSuccess returning promise: arrow expression body already returns its value, so the invalidation promise IS being passed back to TanStack. No change needed. - Readonly<{ children }> on AppProviders: isolated style island. Added p3 task to enable eslint-react/prefer-read-only-props as a codebase-wide convention instead of per-component opt-in. - tsconfig.json cross-package include: documented TS2883 workaround for tRPC tracked() declaration emit. The pattern matches tRPC's own canonical relative-path type import. Added a line acknowledging the coupling cost. - use-live-status.ts unused useTRPCClient import: already clean on current branch (stale CR comment). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(web): lift selectedCategories to useState so first-mount default propagates A fresh user (no stored categories) saw the "No questions for your selected categories" empty state instead of the first welcome screen. Root cause: `selectedCategories` was read from localStorage inline on every render, and the default-selection logic lived in a useEffect that wrote defaults to localStorage but never triggered a re-render. First render saw [], buildScreens returned 0, and the empty-state card painted. The effect updated storage after, but nothing re-read it. Fix: lift selectedCategories into `useState` with a lazy initializer that returns storage or (on null) persists + returns defaults. The value is now present on first render. Storage contract: null → first-time user, default to all categories (and persist) [] → user explicitly unchecked everything via Summary; respect [...] → use the stored list as-is Adds a regression test `fresh-user-no-preseed.spec.ts` that deliberately does NOT call `setCategories`/`scopedSet` — it exercises the real UI default path that no other E2E was covering. Every existing E2E had been pre-seeding storage, which is how this bug stayed hidden. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * test(e2e): remove UI-bypass helpers, exercise real user journeys Every E2E spec previously called setCategories() / setTier() — helpers that wrote directly to scoped localStorage to skip past the Summary category-picker UI. The result: the fresh-user default path was never exercised by any test, which let a real UX bug (see previous commit) ship undetected. Policy change documented in helpers.ts: - scopedGet / scopedSet are now reserved for invariants the UI cannot produce or observe (e.g. rolling back stoken adversarially, polling pendingOps as a sync-completion signal). - Every remaining call site has a justification comment. - setCategories and setTier are deleted. Replaced with narrowToCategory(page, targetLabel): a UI-driven helper that clicks "View all categories" from the first welcome screen, unchecks every category whose label doesn't match, and clicks the target row — the same flow a real user takes to narrow scope. Per-spec changes: - completion: replace URL-manipulation path to /review with the real UI click-through (Progress → Summary → Review answers). - multi-tab: replace `scopedGet("answers")` assertions with UI observation (Back button + reload). - edit-post-completion: replace `alice.url().replace(...)` URL manipulation with `page.goBack()`. - fill-questionnaire: use the Intro screen's tier picker UI instead of `setTier` bypass. - sync-conflict: preserves scopedGet/scopedSet because stoken rollback is adversarial; documented inline. - Every other spec: rewritten to call narrowToCategory. Additionally, `global-setup.ts` now runs `vite build` unconditionally before starting the Hono server. The server serves `packages/web/dist` as a static root; nothing previously built that directory as part of test setup, which let stale bundles silently mask source changes. SKIP_E2E_BUILD=1 is an escape hatch for iterative test-only work. Researched Playwright's canonical pattern (`webServer.command` with `pnpm build && pnpm start`); it assumes a simpler stack than ours (no dynamic DB URL from a testcontainer, no custom Hono serving both static + API). Build-in-globalSetup is the pragmatic fit — documented. Result: 35/35 tests pass, ~3min wall time, zero flakes, zero bypasses of the UI that real users actually traverse. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: address fourth round of code review feedback Actionable: - e2e/fill-questionnaire.spec.ts: scope the Power Exchange fraction lookup to the Power Exchange row instead of `.first()`-matching whatever fraction appears first in DOM order. Prior locator would silently read the wrong counter if Summary layout changed. - e2e/helpers.ts: escape regex metacharacters in `targetLabel` before building the category-button RegExp. Current labels are metachar- free but this is cheap defense for future labels like "Role Play (Fantasy)". - sync.journal-subscription.integration.test.ts: replace the fixed `setTimeout(50)` + listenerCount assertion with `expect.poll`. CR suggested a manual while-loop, but Vitest's first-class primitive is strictly better: retries the assertion (zero overhead on first match), surfaces observed values in the failure message, and is idiomatic. 1 line instead of 7, and no time-guessing under CI load. - e2e/edit-post-completion.spec.ts: use `goBack` + `reload` instead of plain `goBack` for the "did not unmark" assertion. `goBack` alone only replays SPA history; a stale in-memory completion flag could let the test pass even if the button accidentally touched server state. `reload` forces the guard to re-evaluate against fresh status — if isCompleted were false, we'd get bounced to /questions. - design/sync.md: hyphenate "Client side" → "Client-side". Rejected: - sync.journal-subscription.integration.test.ts type → interface: style-only preference; the codebase mixes both for object-shape aliases and has no enforced convention. Not worth churning. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor(server): use expect.poll for listener cleanup check in groups subscription test Drive-by: brings the groups subscription listener-cleanup assertion in line with the sync journal subscription test (fixed in the previous commit). Same anti-pattern, same upgrade, same rationale — `setTimeout(50)` was a fixed sleep guessing at cleanup latency and occasionally flaky under parallel worker load; `expect.poll` retries the assertion (zero overhead on the fast path), surfaces observed values in failure messages, and matches the equivalent check in sync.journal-subscription.integration.test.ts. No other fixed-setTimeout instances remain in the vitest test suite. Playwright E2E specs already use the framework-native equivalent (`expect(async () => ...).toPass({ timeout })`) at every cross-process assertion. The one remaining `waitForTimeout(500)` in reconnect- resume.spec.ts is a deliberate heuristic for wsLink internal state transitions that have no observable DOM surface; intentionally preserved with explanatory comment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * chore: signing checkpoint This session's earlier commits (1f3125d..f022710) were made with commit.gpgsign=false bypassing the repo's default signing config. This empty commit re-establishes a signed checkpoint on top of them. The content of prior commits is intact and verified via CI on this branch; future commits will sign normally. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
|
@dependabot recreate |
Bumps [@electric-sql/pglite](https://github.com/electric-sql/pglite/tree/HEAD/packages/pglite) from 0.4.3 to 0.4.4. - [Release notes](https://github.com/electric-sql/pglite/releases) - [Changelog](https://github.com/electric-sql/pglite/blob/main/packages/pglite/CHANGELOG.md) - [Commits](https://github.com/electric-sql/pglite/commits/@electric-sql/[email protected]/packages/pglite) --- updated-dependencies: - dependency-name: "@electric-sql/pglite" dependency-version: 0.4.4 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <[email protected]>
5eb3d3e to
e128cf7
Compare
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 12 minutes and 24 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
Superseded by #16. |
…yebrow fix QA round covering four question-flow issues (#4, #5, #6, #7): **#4 Progress pill + nav hover** - Wraps the top-right "Progress" link in a bordered pill so it reads as a target, not body text. - Unifies Back / Skip hover to accent (previously faded-to-muted, almost invisible) — all three clickable cues in the card now signal the same way. **#5 Inline description with reserved slot** - Replaces the "What's this?" toggle with an always-rendered description rendered as a muted paragraph with a 2px accent-light left rule (editorial-aside style). `text-pretty` handles orphan avoidance. - Reserves 2.75rem below the heading so cards stay a uniform height whether or not the question has a description (~43% do). Removes the showDescription state from Question.tsx and the toggle logic it carried. **#6 Suppress "New category" eyebrow when returning** - The welcome-interstitial eyebrow hid "New category" once the user has answers in that category — no longer reads as "new" on resume. - Threaded via a `hasAnswersInCategory` boolean computed on demand in Question.tsx (cheap per-render lookup). **#7 α commit animation + keyboard listener refactor** - 300ms spring-pop keyframe `commit-alpha` overshoots and settles into the existing selected-answer ring, giving keyboard commits visual feedback before the advance fires. - Moves number-key handling out of Question.tsx's window listener into two new scoped components — `RatingGroup` (1-5) and `TimingButtons` (1/n, 2/l) — each owning its own `useState<Rating|null>` + `onAnimationEnd`-driven commit flow. Listener lifetimes match each component's mount, so the two never compete. - Mouse clicks stay instant (detect via `event.detail === 0`). Reduced- motion users get a 1ms keyframe so the commit still dispatches but no visible motion plays. - Page-level arrows (prev/next question) stay in Question.tsx. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…yebrow fix QA round covering four question-flow issues (#4, #5, #6, #7): **#4 Progress pill + nav hover** - Wraps the top-right "Progress" link in a bordered pill so it reads as a target, not body text. - Unifies Back / Skip hover to accent (previously faded-to-muted, almost invisible) — all three clickable cues in the card now signal the same way. **#5 Inline description with reserved slot** - Replaces the "What's this?" toggle with an always-rendered description rendered as a muted paragraph with a 2px accent-light left rule (editorial-aside style). `text-pretty` handles orphan avoidance. - Reserves 2.75rem below the heading so cards stay a uniform height whether or not the question has a description (~43% do). Removes the showDescription state from Question.tsx and the toggle logic it carried. **#6 Suppress "New category" eyebrow when returning** - The welcome-interstitial eyebrow hid "New category" once the user has answers in that category — no longer reads as "new" on resume. - Threaded via a `hasAnswersInCategory` boolean computed on demand in Question.tsx (cheap per-render lookup). **#7 α commit animation + keyboard listener refactor** - 300ms spring-pop keyframe `commit-alpha` overshoots and settles into the existing selected-answer ring, giving keyboard commits visual feedback before the advance fires. - Moves number-key handling out of Question.tsx's window listener into two new scoped components — `RatingGroup` (1-5) and `TimingButtons` (1/n, 2/l) — each owning its own `useState<Rating|null>` + `onAnimationEnd`-driven commit flow. Listener lifetimes match each component's mount, so the two never compete. - Mouse clicks stay instant (detect via `event.detail === 0`). Reduced- motion users get a 1ms keyframe so the commit still dispatches but no visible motion plays. - Page-level arrows (prev/next question) stay in Question.tsx. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…yebrow fix (#58) * feat(web): progress pill, inline description, commit animation, new-eyebrow fix QA round covering four question-flow issues (#4, #5, #6, #7): **#4 Progress pill + nav hover** - Wraps the top-right "Progress" link in a bordered pill so it reads as a target, not body text. - Unifies Back / Skip hover to accent (previously faded-to-muted, almost invisible) — all three clickable cues in the card now signal the same way. **#5 Inline description with reserved slot** - Replaces the "What's this?" toggle with an always-rendered description rendered as a muted paragraph with a 2px accent-light left rule (editorial-aside style). `text-pretty` handles orphan avoidance. - Reserves 2.75rem below the heading so cards stay a uniform height whether or not the question has a description (~43% do). Removes the showDescription state from Question.tsx and the toggle logic it carried. **#6 Suppress "New category" eyebrow when returning** - The welcome-interstitial eyebrow hid "New category" once the user has answers in that category — no longer reads as "new" on resume. - Threaded via a `hasAnswersInCategory` boolean computed on demand in Question.tsx (cheap per-render lookup). **#7 α commit animation + keyboard listener refactor** - 300ms spring-pop keyframe `commit-alpha` overshoots and settles into the existing selected-answer ring, giving keyboard commits visual feedback before the advance fires. - Moves number-key handling out of Question.tsx's window listener into two new scoped components — `RatingGroup` (1-5) and `TimingButtons` (1/n, 2/l) — each owning its own `useState<Rating|null>` + `onAnimationEnd`-driven commit flow. Listener lifetimes match each component's mount, so the two never compete. - Mouse clicks stay instant (detect via `event.detail === 0`). Reduced- motion users get a 1ms keyframe so the commit still dispatches but no visible motion plays. - Page-level arrows (prev/next question) stay in Question.tsx. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs: todo to stabilize localStorage-backed state with useSyncExternalStore Surfaced while wiring pr-c-answering-flow's welcome-screen CTA logic. Discovered along the way that existing Summary.tsx + Review.tsx useMemo blocks depend on `answers` which has fresh object identity per render — the memos never cache. Promoting from "nice to have" to p2 because it's actively defeating existing memoization. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs: expand caching audit todo with sortMembersViewerFirst + questions-by-id map Two more wins surfaced alongside the useSyncExternalStore item — lump under the same p2 entry since they're all "do one pass on render-time computes" work that makes sense batched. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * style(web): switch question description from quote rule to hushed inline Replaces the 2px accent-light left rule + indent with italic muted text. The aside-rule felt heavier than the description warranted — italic carries the "secondary voice" cue with less chrome and stays closer to the question's typographic line. No visual baseline change captured because the e2e admin flow narrows to "Group & External" whose first question has no description. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(web): state-aware primary CTA on category welcome screen Clicking a half-filled category from Summary used to land on the welcome screen and the only Start button took you to the *first* question of the category — re-walking already-answered ones instead of resuming where you left off. Three states now, mirroring the /group screen vocabulary: fresh (no answers) → [Start] partial (some answered) → [Continue] + [Review from the start] complete (all answered) → [Review from the start] Continue jumps to the first unanswered question in the category. Review from the start jumps to the first question (regardless of answer state) so the user can walk through edits. No visual baseline change — e2e admin flow only exercises the fresh state on the welcome screen. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(web): rating/timing glossary popover (help icon in question header) QA flagged that the rating glossary disappears after the intro screen — Andrey forgot what "Fantasy only" meant mid-flow. Adds a small HelpCircle icon next to the Progress chip in the question card header. Click toggles a popover showing all rating options (Yes / If partner wants / Maybe / Fantasy only / No) with their one-line meanings, sourced verbatim from `UI.intro.answers` so it matches the intro copy. Switches content based on context: when the timing sub-question is showing (Now / Later), the popover swaps to the timing glossary (`UI.intro.timing`) instead. Closes on Escape, click-outside, or the in-popover × button. Auto-closes when the answer mode flips. Tests: e2e asserts both the rating-mode glossary opens and that it swaps to the timing glossary after committing Yes; visual snapshot of the open popover is captured alongside the description regression shot — both desktop and mobile baselines. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(web): defer to child handlers + use pointerdown for touch parity PR 58 review caught two real issues: **Question.tsx ArrowLeft/Right double-handling** RatingGroup's roving-tabindex onKeyDown calls preventDefault on ArrowLeft/Right to move focus between rating options. The window- level page-navigation handler in Question.tsx was firing for the SAME event, so pressing ArrowLeft on a focused rating both moved the focus ring AND navigated to the previous question. Add an `e.defaultPrevented` early return so child handlers consume the event first. **QuestionCard help popover dismiss missed touch** The click-outside handler used `mousedown` + `MouseEvent`. Mobile browsers do synthesize `mousedown` from touchstart in most cases, but `pointerdown` is the unified event spec for mouse / touch / pen and works consistently across input types without relying on compat shims. Switched event name + parameter type to PointerEvent. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(web): PR 58 review follow-ups — popover dismiss, focus, layout safety Five items from the review bundle: **Dismiss popover on screen-key + mode transitions (item 2).** An open glossary popover used to linger after the user committed an answer (advancing to the next question) — overlaying the next screen's content. A `useEffect` on `[showTiming, screen.key]` closes the popover on any transition that signals "user moved on": commit, Back, Skip, category jump, or mode flip. Matches the Slack / GitHub / Notion convention of closing transient popovers on user action. **Focus move into popover on open (item 6).** Keyboard-only users opening the help used to land nowhere — focus stayed on the trigger and Tab cycled through the page to reach the × button. Added a `closeRef` forwarded to the close button and a `useEffect` that focuses it on `helpOpen` true. Non-modal dialog pattern (per Radix / shadcn), Escape still dismisses from anywhere. **Viewport safety on popover width (item 7).** `max-w-[calc(100vw-2rem)]` caps the popover inside the viewport minus a margin, in case future card padding changes or very narrow devices would otherwise cause clipping. **Invariant comment on `e.detail === 0` (item 1).** Added a note about the programmatic `.click()` gotcha — `element.click()` also reports `detail === 0`, so test helpers that want to exercise the click path must use real mouse input (Playwright's locator `.click()` produces `detail ≥ 1`). **Drop updater form in CategoryWelcomeScreen (item 4).** `setIndex(() => firstQuestionIdx)` → `setIndex(firstQuestionIdx)`. Same for `goToFirstUnanswered`. Not a change in behavior; updater only needs the closure form when the setter depends on the previous value. **New E2E: help popover dismisses on commit and on Skip.** Extends fill-questionnaire.spec.ts — opens popover, presses "3" (keyboard commit), asserts dialog gone. Then opens again, clicks Skip, asserts dialog gone. Covers both transition classes from item 2. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(web): drop unnecessary updater form in CategoryWelcomeScreen Review item 4 (deferred from the previous commit). None of the setIndex calls here depend on the previous value — they jump to a specific index — so the `() => value` form was noise. Widen the prop type to accept plain values (matching React's native Dispatch<SetStateAction<number>> shape) and simplify the three call sites. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Bumps @electric-sql/pglite from 0.4.3 to 0.4.4.
Release notes
Sourced from
@electric-sql/pglite's releases.Changelog
Sourced from
@electric-sql/pglite's changelog.Commits
4e8512cVersion Packages (#971)b88c5c3Disable checkpointer (not needed in single mode) (#970)