Repository navigation
fix(web): orphaned answers on Summary→Review→Done + crypto key leak - #25
Conversation
Two data-integrity bugs discovered via manual testing with DIAG logging: 1. The `/review` route's "Done" button called `markComplete` without flushing pending ops first. If the user answered questions, navigated to `/summary → /review → Done` within the 3s auto-sync debounce window, the debounce timer was cleared by the Question unmount and the pending ops were stranded in localStorage forever — the server never received those answers. Results showed 0 matches even though both users answered. Fix: extract a `useMarkComplete` hook that always calls `flushPendingOps` before `sync.markComplete`. Both the in-question "I'm done" button and the `/review` Done now go through this single hook, making it structurally impossible for any mark-complete path to skip the flush. 2. `getGroupKeyFromUrl()` cached the AES key in module scope + `sessionStorage` under a global `"groupKey"` key, not scoped by token. Navigating from an encrypted group to an unencrypted one in the same tab left the old key cached; the unencrypted group's data was silently encrypted with the wrong key (observed as `e:1:` prefix on a `group.encrypted = false` row in the DB). Fix: scope both the module-level cache and the sessionStorage key by the session scope (fnv1a hash of the token). Invalidate the module cache whenever the scope changes. Also: - `useSyncQueue` now delegates to `flushPendingOps` (same shared fn) instead of duplicating the push + conflict-retry logic. - Added ref-based dedup gate on the `scheduleSync` effect to avoid redundant re-schedules from StrictMode double-mount and unrelated re-renders with the same pending count. - Hide the "Go for it" summary strip column when `showTiming` is off — the green-light tier requires `now` timing answers, which are only collected in timing mode. Showing a permanent 0 is noise. - Remove temporary DIAG logging added for the investigation. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughScope-aware group-key caching added; flushPendingOps centralizes pending-op push/merge/retry flow; useMarkComplete hook added and useSyncQueue refactored to delegate flushing; UI components accept a new showTiming prop and are wired to the new hook. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant UI as UI (useSyncQueue / useMarkComplete)
participant Flush as flushPendingOps
participant Store as Storage (getPendingOps / setStoken / drainSent / setAnswers)
participant Push as PushService (push)
participant Merge as Merge (mergeAfterRejection)
rect rgba(100,150,240,0.5)
User->>UI: trigger flush (e.g., markComplete)
UI->>Flush: flushPendingOps(pushFn, getProgress)
Flush->>Store: getPendingOps()
alt no pending ops
Store-->>Flush: []
Flush-->>UI: done
else pending ops present
Flush->>Flush: getProgress()
Flush->>Push: push({stoken, operations, progress})
alt push accepted
Push-->>Flush: {stoken, pushRejected:false}
Flush->>Store: setStoken(stoken)
Flush->>Store: drainSent(sentCount)
Flush-->>UI: done
else push rejected
Push-->>Flush: {stoken, pushRejected:true, entries}
Flush->>Merge: mergeAfterRejection(getAnswers(), operations, entries)
Merge-->>Flush: mergedAnswers
Flush->>Store: setAnswers(mergedAnswers)
Flush->>Flush: getProgress() (recompute)
Flush->>Push: push(retry with original ops and retry stoken)
alt retry accepted
Push-->>Flush: {stoken, pushRejected:false}
Flush->>Store: setStoken(stoken)
Flush->>Store: drainSent(sentCount)
Flush-->>UI: done
else retry rejected
Push-->>Flush: {stoken, pushRejected:true}
Flush->>Console: console.error(...)
Flush-->>UI: done (ops retained)
end
end
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Tests the exact contract that the orphaned-answers bug violated: - push is called before markComplete when pending ops exist - pending ops are fully cleared before markComplete runs (asserted inside the markComplete mock at the exact moment of execution) - markComplete still runs when no ops are pending (auto-sync path) - markComplete does NOT run if push fails — prevents marking a user complete when their answers haven't been saved Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
packages/web/src/lib/crypto.test.ts (1)
125-134: Misleading comment about sessionStorage reset behavior.Lines 125-126 state "
sessionStorageis stubbed at thedescribescope (not reset per-test)", but line 134 reassignssessionStoreMap = new Map<string, string>()inbeforeEach, which does reset the backing store per test.The tests work correctly because each test simulates a complete user journey within a single tab. Consider clarifying the comment:
📝 Suggested comment clarification
- // `sessionStorage` is stubbed at the `describe` scope (not reset per-test) - // so the fallback-read path in `getGroupKeyFromUrl` can see a key written - // during the same tab, which is what the real-world flow does: the user + // Each test simulates a complete user journey within a single browser tab. + // `sessionStoreMap` is reset per-test so tests are independent, while the + // stub functions let the fallback-read path in `getGroupKeyFromUrl` see keys written + // earlier in the same test—mirroring the real-world flow where a user🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/web/src/lib/crypto.test.ts` around lines 125 - 134, The comment claiming "sessionStorage is stubbed at the describe scope (not reset per-test)" is misleading because the test does reinitialize the backing store in beforeEach via sessionStoreMap = new Map<string, string>(); Update the comment near sessionStoreMap and beforeEach to accurately state that sessionStoreMap is reset per test (so getGroupKeyFromUrl's fallback-read sees only keys set within the same test/tab), and mention that sessionStorage is stubbed at describe scope but its backing map is re-created in beforeEach; reference sessionStoreMap, beforeEach, and getGroupKeyFromUrl when editing the comment.packages/web/src/lib/sync-flush.ts (1)
4-17: Useinterfacefor these transport shapes.
PushInputandPushResultare object shapes, so they should follow the repo’sinterfaceconvention here.PushFncan stay a type alias.As per coding guidelines, "Use
interfacefor defining object shapes in TypeScript".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/web/src/lib/sync-flush.ts` around lines 4 - 17, Replace the object type aliases PushInput and PushResult with TypeScript interfaces to follow the repo convention: change the declarations for PushInput and PushResult into interfaces (keeping the same property names and types) and leave the PushFn type alias as-is; update any imports/usages that reference those symbols if necessary so they continue to refer to the newly created interfaces PushInput and PushResult.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/web/src/lib/sync-flush.ts`:
- Around line 35-59: flushPendingOps currently snapshots ops via getPendingOps()
then calls clearPendingOps(), which deletes any ops appended while the push was
in-flight; instead, after each successful send (both initial and retry) read the
current full queue (via getPendingOps()), remove only the prefix equal to the
original snapshot length (ops.length) and write the remaining suffix back to
storage (use the existing setter for pending ops or add
setPendingOps/removePrefixPendingOps as needed), do this where clearPendingOps()
is called (both after the first push when !result.pushRejected and after a
successful retry), and add a regression test "enqueue during push" that enqueues
a new op while push is awaiting to ensure the new op remains in storage;
remember pending ops are opaque strings so only rely on array slicing by count.
In `@packages/web/src/lib/use-mark-complete.ts`:
- Around line 21-36: useMarkComplete is not re-entrant safe; add an in-flight
guard (e.g. isRunning boolean via useRef or useState) to prevent concurrent
executions of flushPendingOps, pushMutation.mutateAsync and
markCompleteMutation.mutateAsync, set isRunning=true before starting operations
and clear it in finally, and short-circuit if already running; expose that state
to callers (return an object or tuple like { run: useMarkCompleteFn, isRunning
}) so UI buttons can be disabled while the operation is in-flight; ensure
navigate("/waiting") still runs after success and that
onSuccess/invalidateStatus behavior is preserved.
---
Nitpick comments:
In `@packages/web/src/lib/crypto.test.ts`:
- Around line 125-134: The comment claiming "sessionStorage is stubbed at the
describe scope (not reset per-test)" is misleading because the test does
reinitialize the backing store in beforeEach via sessionStoreMap = new
Map<string, string>(); Update the comment near sessionStoreMap and beforeEach to
accurately state that sessionStoreMap is reset per test (so getGroupKeyFromUrl's
fallback-read sees only keys set within the same test/tab), and mention that
sessionStorage is stubbed at describe scope but its backing map is re-created in
beforeEach; reference sessionStoreMap, beforeEach, and getGroupKeyFromUrl when
editing the comment.
In `@packages/web/src/lib/sync-flush.ts`:
- Around line 4-17: Replace the object type aliases PushInput and PushResult
with TypeScript interfaces to follow the repo convention: change the
declarations for PushInput and PushResult into interfaces (keeping the same
property names and types) and leave the PushFn type alias as-is; update any
imports/usages that reference those symbols if necessary so they continue to
refer to the newly created interfaces PushInput and PushResult.
🪄 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: 6fd8352c-4fa2-4d2e-8f5b-1ebfbdec98bc
📒 Files selected for processing (9)
packages/web/src/lib/crypto.test.tspackages/web/src/lib/crypto.tspackages/web/src/lib/sync-flush.test.tspackages/web/src/lib/sync-flush.tspackages/web/src/lib/use-mark-complete.tspackages/web/src/lib/use-sync-queue.tspackages/web/src/screens/Comparison.tsxpackages/web/src/screens/PersonApp.tsxpackages/web/src/screens/Question.tsx
…tics
Address PR review feedback:
1. useMarkComplete now returns an identity-stable callback via
useCallback + mutation refs (same pattern as useSyncQueue). Prevents
unnecessary re-renders of <Button onClick={markComplete}>.
2. Add comment explaining why the conflict retry re-sends the original
ops array: ops are append-only journal entries that don't change
after a merge — only the local answers cache does. The fresh stoken
tells the server the client has seen its latest state.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/web/src/lib/sync-flush.test.ts (1)
75-97: Add a test for the “retry also rejected” branch.Great conflict coverage for retry-success; please also lock in the opposite terminal path where the second push is still rejected, so ops are explicitly preserved for later sync.
➕ Suggested test case
+ test("keeps pending ops when retry is also rejected", async () => { + localStorage.setItem("pendingOps", JSON.stringify(["opA"])); + const push = vi + .fn() + .mockResolvedValueOnce({ + stoken: "s1", + pushRejected: true, + entries: [], + }) + .mockResolvedValueOnce({ + stoken: "s2", + pushRejected: true, + entries: [], + }); + + await flushPendingOps(push, async () => "p:1:progress"); + + expect(push).toHaveBeenCalledTimes(2); + expect(getPendingOps()).toEqual(["opA"]); + expect(localStorage.getItem("stoken")).toBe("s2"); + });Based on learnings: "Test contracts, not internals — test the interface a consumer depends on. Boundary behavior matters: defensive copies, error propagation, unknown/missing inputs, edge cases."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/web/src/lib/sync-flush.test.ts` around lines 75 - 97, Add a new test variant for flushPendingOps that mocks two sequential push responses both with pushRejected: true (e.g., first {stoken: "s1", pushRejected: true, entries: []} and second {stoken: "s2", pushRejected: true, entries: []}), call flushPendingOps with a pendingOps value in localStorage, then assert push was called twice, that localStorage still contains the original "pendingOps" value (ops preserved for later sync) and that the "stoken" value was updated to the latest returned stoken ("s2"); reference flushPendingOps, the push mock, and localStorage keys "pendingOps" and "stoken" when adding this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/web/src/lib/sync-flush.test.ts`:
- Around line 75-97: Add a new test variant for flushPendingOps that mocks two
sequential push responses both with pushRejected: true (e.g., first {stoken:
"s1", pushRejected: true, entries: []} and second {stoken: "s2", pushRejected:
true, entries: []}), call flushPendingOps with a pendingOps value in
localStorage, then assert push was called twice, that localStorage still
contains the original "pendingOps" value (ops preserved for later sync) and that
the "stoken" value was updated to the latest returned stoken ("s2"); reference
flushPendingOps, the push mock, and localStorage keys "pendingOps" and "stoken"
when adding this test.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: bd26b755-3b4d-4626-8d22-7d3ab729c963
📒 Files selected for processing (1)
packages/web/src/lib/sync-flush.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/web/src/lib/sync-flush.ts (1)
36-45:⚠️ Potential issue | 🔴 CriticalPreserve ops enqueued during in-flight flush (current clear drops unsent suffix).
Line 36 snapshots
ops, but Line 44 and Line 63 clear the entire queue. If a new op is appended whilepush(...)is awaiting, that newer op is removed without ever being sent.Proposed fix
-import { clearPendingOps, getAnswers, getPendingOps, getStoken, setAnswers, setStoken } from "./storage.js"; +import { clearPendingOps, getAnswers, getPendingOps, getStoken, setAnswers, setPendingOps, setStoken } from "./storage.js"; + +function acknowledgeFlushedPrefix(flushedCount: number): void { + const current = getPendingOps(); + if (current.length <= flushedCount) { + clearPendingOps(); + return; + } + setPendingOps(current.slice(flushedCount)); +} @@ if (!result.pushRejected) { - clearPendingOps(); + acknowledgeFlushedPrefix(ops.length); return; } @@ if (!retry.pushRejected) { - clearPendingOps(); + acknowledgeFlushedPrefix(ops.length); return; }Please also add/keep a regression test for “enqueue during push”.
As per coding guidelines, "Pending ops are opaque strings."Also applies to: 56-64
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/web/src/lib/sync-flush.ts` around lines 36 - 45, The current flush snapshots ops via getPendingOps() then calls push(...) and calls clearPendingOps(), which deletes any ops enqueued while push was in-flight; instead remove only the prefix that was sent. After push returns (in the code handling result.pushRejected false), load the current queue again (or compute remaining = currentQueue.slice(ops.length)) and write back only the remaining suffix (via existing setter like setPendingOps or a new removePendingOps(count) helper) rather than calling clearPendingOps(); do the same fix for the mirrored block around the second occurrence (lines ~56-64). Also add/keep the regression test “enqueue during push” that enqueues opaque string ops while push is awaiting to verify the suffix is preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/web/src/lib/sync-flush.ts`:
- Around line 4-14: The Pull Request uses type aliases for object shapes; change
the two declarations PushInput and PushResult from "type" to "interface" (i.e.,
replace "type PushInput = { ... }" with "interface PushInput { ... }" and
similarly for PushResult), preserving all property names and types (stoken,
operations, progress, pushRejected, entries) and any nullability; then update
any local references/usages if your editor flags differences (interfaces are
compatible but search for "type PushInput" / "type PushResult" to ensure no
leftover aliases remain).
---
Duplicate comments:
In `@packages/web/src/lib/sync-flush.ts`:
- Around line 36-45: The current flush snapshots ops via getPendingOps() then
calls push(...) and calls clearPendingOps(), which deletes any ops enqueued
while push was in-flight; instead remove only the prefix that was sent. After
push returns (in the code handling result.pushRejected false), load the current
queue again (or compute remaining = currentQueue.slice(ops.length)) and write
back only the remaining suffix (via existing setter like setPendingOps or a new
removePendingOps(count) helper) rather than calling clearPendingOps(); do the
same fix for the mirrored block around the second occurrence (lines ~56-64).
Also add/keep the regression test “enqueue during push” that enqueues opaque
string ops while push is awaiting to verify the suffix is preserved.
🪄 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: c57bfb2d-386a-498d-879f-cfa691c8dc36
📒 Files selected for processing (2)
packages/web/src/lib/sync-flush.tspackages/web/src/lib/use-mark-complete.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/web/src/lib/use-mark-complete.ts
Address CodeRabbit review feedback: 1. clearPendingOps() nuked the entire queue, including any ops appended while the push was in flight (user answers another question during the network round-trip). Replace with drainSent(count) that removes only the prefix that was sent, keeping the suffix intact. 2. useMarkComplete now has an inFlightRef guard so double-clicking "Done" can't run flush + markComplete in parallel. New tests: - "preserves ops enqueued during in-flight push" — appends an op inside the push mock, verifies it survives after flush - "concurrent double-click: second call is a no-op" — fires two concurrent guardedMarkComplete calls, verifies push + markComplete each run exactly once Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Per codebase style guide: use interfaces for object shapes. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Fixed the |
Tests the "both pushes rejected" path: first push returns pushRejected + stoken s1, retry also returns pushRejected + stoken s2. Verifies ops remain in localStorage for the next sync cycle and the stoken advances to the latest server response (s2). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/web/src/lib/sync-flush.ts (1)
4-14: 🛠️ Refactor suggestion | 🟠 MajorUse
interfaceforPushInputandPushResult.Line 4 and Line 10 still define object shapes with
type, which violates the TS guideline for this repo.♻️ Suggested refactor
-type PushInput = { +interface PushInput { stoken: string | null; operations: string[]; progress: string | null; -}; +} -type PushResult = { +interface PushResult { stoken: string | null; pushRejected: boolean; entries: string[]; -}; +}As per coding guidelines, "Use
interfacefor defining object shapes in TypeScript".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/web/src/lib/sync-flush.ts` around lines 4 - 14, The file defines PushInput and PushResult with Type aliases; change both to TypeScript interfaces instead (replace "type PushInput = { ... }" and "type PushResult = { ... }" with "interface PushInput { ... }" and "interface PushResult { ... }") keeping the same property names and types (stoken, operations, progress, pushRejected, entries) so callers using PushInput and PushResult remain compatible; update any exports or references if necessary to ensure tooling recognizes the new interfaces.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@packages/web/src/lib/sync-flush.ts`:
- Around line 4-14: The file defines PushInput and PushResult with Type aliases;
change both to TypeScript interfaces instead (replace "type PushInput = { ... }"
and "type PushResult = { ... }" with "interface PushInput { ... }" and
"interface PushResult { ... }") keeping the same property names and types
(stoken, operations, progress, pushRejected, entries) so callers using PushInput
and PushResult remain compatible; update any exports or references if necessary
to ensure tooling recognizes the new interfaces.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 43ed1da0-7c91-45fa-9d04-dcdc39f2810a
📒 Files selected for processing (3)
packages/web/src/lib/sync-flush.test.tspackages/web/src/lib/sync-flush.tspackages/web/src/lib/use-mark-complete.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/web/src/lib/use-mark-complete.ts
|
🎉 This PR is included in version 1.5.1 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |
Summary
Two data-integrity bugs found via diagnostic logging during manual testing:
Orphaned answers (data loss): The
/reviewroute's "Done" button calledmarkCompletewithout flushing pending ops. If the user navigated/questions → /summary → /review → Donewithin the 3s auto-sync debounce window, the Question unmount cleared the debounce timer and pending ops were stranded in localStorage — the server never received those answers, producing empty results.useMarkCompletehook that always callsflushPendingOpsbeforesync.markComplete. Both mark-complete paths (end-of-questions and/review) now go through this single hook. NewflushPendingOpsfunction insync-flush.tsis shared between the hook anduseSyncQueue, so there's exactly one code path that clears the pending-ops queue.flushPendingOps: success, null progress, network error (ops preserved), and conflict retry.Crypto key leak across groups:
getGroupKeyFromUrl()cached the AES key globally in module scope +sessionStorage["groupKey"]. Navigating from an encrypted group to an unencrypted one in the same tab leaked the old key — the unencrypted group's data was silently encrypted with the wrong key (e:1:prefix ongroup.encrypted = falserows).fnv1a(token)). Invalidate on scope change.UI: Hide "Go for it" summary strip column when
showTimingis off — the green-light tier is unreachable without timing mode, so showing a permanent 0 is noise.Cleanup: Remove DIAG logging from investigation; deduplicate
scheduleSynceffect with a ref gate.Test plan
pnpm -r typecheckcleanpnpm test— 297 tests pass (7 new: 5sync-flush, 3cryptoscope isolation, minus 1 existing = net +7)e:1:prefix on journal ops. Navigate to an unencrypted group in the same tab — verify ops usep:1:prefix (note:1:)🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests