Skip to content

fix(web): orphaned answers on Summary→Review→Done + crypto key leak - #25

Merged
iskhakovt merged 6 commits into
mainfrom
fix/orphaned-answers-and-crypto-leak
Apr 12, 2026
Merged

iskhakovt merged 6 commits into
mainfrom
fix/orphaned-answers-and-crypto-leak

Conversation

@iskhakovt

@iskhakovt iskhakovt commented Apr 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two data-integrity bugs found via diagnostic logging during manual testing:

  • Orphaned answers (data loss): The /review route's "Done" button called markComplete without flushing pending ops. If the user navigated /questions → /summary → /review → Done within 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.

    • Fix: New useMarkComplete hook that always calls flushPendingOps before sync.markComplete. Both mark-complete paths (end-of-questions and /review) now go through this single hook. New flushPendingOps function in sync-flush.ts is shared between the hook and useSyncQueue, so there's exactly one code path that clears the pending-ops queue.
    • Unit tests for 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 on group.encrypted = false rows).

    • Fix: Scope both the module cache and sessionStorage key by the session scope (fnv1a(token)). Invalidate on scope change.
    • Three unit tests: single scope caching, cross-scope leak prevention, two-encrypted-group isolation.
  • UI: Hide "Go for it" summary strip column when showTiming is off — the green-light tier is unreachable without timing mode, so showing a permanent 0 is noise.

  • Cleanup: Remove DIAG logging from investigation; deduplicate scheduleSync effect with a ref gate.

Test plan

  • pnpm -r typecheck clean
  • pnpm test — 297 tests pass (7 new: 5 sync-flush, 3 crypto scope isolation, minus 1 existing = net +7)
  • Manual: create unencrypted group, answer questions, navigate Summary → Review → Done — results show matches (not empty)
  • Manual: create encrypted group, note e:1: prefix on journal ops. Navigate to an unencrypted group in the same tab — verify ops use p:1: prefix (not e:1:)
  • Manual: create group without timing mode — "Go for it" column should not appear in results summary strip

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Scope-based isolation for group encryption keys to prevent cross-scope reuse.
    • Unified "mark complete" flow that flushes pending operations before navigation.
    • Optional timing display in comparison results.
  • Bug Fixes

    • Improved sync conflict handling with merge-and-retry behavior.
    • Auto-sync deduplication to avoid redundant scheduling.
    • Prevented cross-navigation key leakage within a tab.
  • Tests

    • Added tests for scope isolation, sync flush/control flow, conflict/retry, and completion ordering.

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]>
@coderabbitai

coderabbitai Bot commented Apr 12, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Scope-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

Cohort / File(s) Summary
Scope-based caching & tests
packages/web/src/lib/crypto.ts, packages/web/src/lib/crypto.test.ts
Group-key caching now scoped by dynamic scope key (${scope}groupKey) with cachedScope invalidation; tests added to assert scope isolation, module cache resets, and caching behavior.
Sync flushing core & tests
packages/web/src/lib/sync-flush.ts, packages/web/src/lib/sync-flush.test.ts
New exported flushPendingOps(push, getProgress) centralizes snapshot->push->stoken update->drainSent or one-retry-on-rejection flow, merges answers on rejection, preserves ops appended during in-flight pushes; comprehensive tests for success, no-op, null progress, error propagation, retry semantics, and ordering with markComplete.
Hook extraction & refactor
packages/web/src/lib/use-mark-complete.ts, packages/web/src/lib/use-sync-queue.ts
Added useMarkComplete() which flushes pending ops then calls markComplete and navigates; useSyncQueue now delegates flushing to flushPendingOps, removing inline push/merge/clear logic.
UI updates
packages/web/src/screens/Comparison.tsx, packages/web/src/screens/PersonApp.tsx, packages/web/src/screens/Question.tsx
Comparison/PairComparison gain required showTiming: boolean prop and render timing column conditionally; PersonApp/Question wired to useMarkComplete; Question deduplicates auto-sync scheduling.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐇 I scoped the keys and hopped around,

Flushed queued hops without a sound,
When pushes balked I stitched the seam,
Extracted hooks and kept the stream —
A tidy burrow, neat and round.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 accurately summarizes the two main bug fixes in the changeset: orphaned answers on the Summary→Review→Done path and a crypto key leak across groups.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/orphaned-answers-and-crypto-leak

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

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]>

@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: 2

🧹 Nitpick comments (2)
packages/web/src/lib/crypto.test.ts (1)

125-134: Misleading comment about sessionStorage reset behavior.

Lines 125-126 state "sessionStorage is stubbed at the describe scope (not reset per-test)", but line 134 reassigns sessionStoreMap = new Map<string, string>() in beforeEach, 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: Use interface for these transport shapes.

PushInput and PushResult are object shapes, so they should follow the repo’s interface convention here. PushFn can stay a type alias.

As per coding guidelines, "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/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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ada2d6 and 6fcf3d9.

📒 Files selected for processing (9)
  • packages/web/src/lib/crypto.test.ts
  • packages/web/src/lib/crypto.ts
  • packages/web/src/lib/sync-flush.test.ts
  • packages/web/src/lib/sync-flush.ts
  • packages/web/src/lib/use-mark-complete.ts
  • packages/web/src/lib/use-sync-queue.ts
  • packages/web/src/screens/Comparison.tsx
  • packages/web/src/screens/PersonApp.tsx
  • packages/web/src/screens/Question.tsx

Comment thread packages/web/src/lib/sync-flush.ts Resolved
…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]>

@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.

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6fcf3d9 and 1fadfd0.

📒 Files selected for processing (1)
  • packages/web/src/lib/sync-flush.test.ts

@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

♻️ Duplicate comments (1)
packages/web/src/lib/sync-flush.ts (1)

36-45: ⚠️ Potential issue | 🔴 Critical

Preserve 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 while push(...) 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fadfd0 and de650d7.

📒 Files selected for processing (2)
  • packages/web/src/lib/sync-flush.ts
  • packages/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

Comment thread packages/web/src/lib/sync-flush.ts Resolved
iskhakovt and others added 2 commits April 12, 2026 10:43
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]>
@iskhakovt

Copy link
Copy Markdown
Owner Author

Fixed the type → interface nit for PushInput/PushResult in d21f449.

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]>

@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.

♻️ Duplicate comments (1)
packages/web/src/lib/sync-flush.ts (1)

4-14: 🛠️ Refactor suggestion | 🟠 Major

Use interface for PushInput and PushResult.

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 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/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

📥 Commits

Reviewing files that changed from the base of the PR and between de650d7 and 972f617.

📒 Files selected for processing (3)
  • packages/web/src/lib/sync-flush.test.ts
  • packages/web/src/lib/sync-flush.ts
  • packages/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

@iskhakovt
iskhakovt enabled auto-merge (squash) April 12, 2026 09:50
@iskhakovt
iskhakovt merged commit 26428fd into main Apr 12, 2026
7 checks passed
@iskhakovt
iskhakovt deleted the fix/orphaned-answers-and-crypto-leak branch April 12, 2026 09:51
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 1.5.1 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

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