Skip to content

fix(browser): serialize cookie imports per partition - #15095

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/sta-4601-serialize-cookie-imports
Aug 18, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/sta-4601-serialize-cookie-imports

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​509 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​509
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​552 $\color{#cf222e}{\Huge{\mathbf{−}}}$​500 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​52

ELI5

Two cookie imports running at the same time on the same browser profile can wipe out each other's work. One import finishes its cleanup after the other has already imported, and undoes it — or leaves behind a stale "restore this on next restart" file that overwrites the newer import when the app restarts.

What Changed

One lock now spans the whole live-jar transaction — the clear/replace, the writes, and the rollback — on both import paths. withCookieClearLock becomes acquireCookieMutationLock / withCookieMutationLock so path A can hold it across a try/finally rather than a single callback.

Deliberately bounded: this lock covers the live jar only. Staging and cold-start replay keep their existing semantics.

Why

Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock previously covered only the clear itself, so it was released before the memory writes and the final pending-image decision.

Reachable interleaving:

Import A clears, releases the lock, and later hits a rejected memory write. Import B clears. A then registers a staged image built from the jar as it was before B — and a restart replays it over B's result.

The same gap lets a stale rollback from A remove cookies B has already written and reported as imported.

Linked Issue

STA-4601

Visual Proof

Manual Electron validation was run on head cdb0db690b — see the "Manual Electron validation (STA-4601)" comment on this PR (4 screenshots, CDP ownership verified, isolated ORCA_DEV_USER_DATA_PATH).

Verdict: IMPORT WORKS. Two real Settings-surface imports (Chrome → stably.ai) into persist:orca-browser completed with no hang or deadlock — 949 total / 869 imported / 80 skipped, 333ms then 319ms — and importedAt advanced on the second run, showing the lock is released rather than merely not yet deadlocked.

The concurrency race itself is not covered by that run and cannot be: the Import Cookies menu is disabled while an import is in flight, so two concurrent imports cannot be started through the UI. The race is pinned by the deterministic concurrency suite instead.

Testing

  • pnpm vitest run --config config/vitest.config.ts src/main/browser — 63 files, 672 tests, green (on main)

  • pnpm typecheck clean, oxlint clean, oxfmt clean, max-lines ratchet OK

  • New browser-cookie-import-concurrency.test.ts drives deterministic interleavings against the lock primitive, so a failure names the ordering rule that broke instead of flaking on a race

  • Mutation-proved: making the lock a no-op reddens the two ordering cases and leaves the different-owner and release-on-throw cases green

  • I manually tested these changes locally (Electron validation on cdb0db690b — see the comment; the earlier tick predated any manual run)

  • Automated tests added/updated

Review

Superseded — this PR now sits on top of #15030. When it was opened, #15030 was unmerged and this change was deliberately expressed against main so neither PR depended on the other. #15030 has since merged and rewritten browser-cookie-import.ts, and this branch was rebased onto it.

That rebase was not textual. #15030 removed the Electron Session from importValidatedCookies' scope, and openWriteStore() builds a fresh adapter per call — so a lock keyed on that adapter would have been syntactically present and serialised nothing. The lock is now keyed on a new mutationLockOwner on CookieImportTarget. All 7 jar-mutation points across both paths are inside the lock; only cold-start replay is outside, by design. All 5 mutation proofs redden their detectors on the rebased code, including a new lock-present-but-miskeyed case.

The bug remains pre-existing and is not introduced by #15030.

Split out of #15030 at your request to keep that P0 reland scoped to partition preservation.

Still open in this subsystem, and deliberately not fixed here: the crash window between the live clear and the result handling, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change with its own failure modes.

Agent skill upstream boundary

  • Not applicable

Notes

  • Security: no new IPC, SQL, or wire surface.
  • Backwards compatibility: no persisted format or protocol change.
  • Performance: imports on the same partition now serialise rather than interleave. Imports are user-initiated and rare; different partitions are unaffected (the lock is keyed per owner) and that is pinned by a test.
  • Cross-platform / SSH / mobile: no platform-specific paths or transports touched.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • N/A with reason for visual proof
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm lint, pnpm typecheck, pnpm test pass locally

Author

  • X / Twitter: @BrennanKB5

@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-4601-serialize-cookie-imports branch from cfcea0b to 3121873 Compare August 17, 2026 10:02
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/sta-4300-reland-cdp-writes to main August 17, 2026 10:02
@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b0e8274e-55ff-443f-b51d-54c869162a3c

📥 Commits

Reviewing files that changed from the base of the PR and between e3003ab and 6203162.

📒 Files selected for processing (1)
  • src/main/browser/browser-cookie-import-concurrency.test.ts
💤 Files with no reviewable changes (1)
  • src/main/browser/browser-cookie-import-concurrency.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

Cookie mutation locking now uses a generalized registry with explicit acquisition and callback-scoped APIs. Replace-mode imports retain the lock through clearing, replacement, rollback, and cookie-store disposal. Browser imports protect live-cookie probing, clearing, and in-memory writes with one lock. Concurrency tests cover serialization, interleaving, error release, rollback scope, repeated release, and concurrent imports.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: serializing cookie imports per browser partition.
Description check ✅ Passed The description is detailed and covers the required change, rationale, testing, review, compatibility, and checklist information.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/browser/browser-cookie-import-clear.ts (1)

69-76: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the mutation-lock rationale comments.

Keep the STA reference and one short statement of the transaction boundary.

  • src/main/browser/browser-cookie-import-clear.ts#L69-L76: Reduce the API rationale to one concise statement.
  • src/main/browser/browser-cookie-import-concurrency.test.ts#L4-L14: Reduce the test background to one concise statement.
  • src/main/browser/browser-cookie-import.ts#L609-L611: Reduce the replace-mode rationale to one concise statement.
  • src/main/browser/browser-cookie-import.ts#L1902-L1905: Reduce the live-jar rationale to one concise statement.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 240765e2-b2da-46cc-a33e-8eaaad7a0e84

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae6aed and 3121873.

📒 Files selected for processing (3)
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-concurrency.test.ts
  • src/main/browser/browser-cookie-import.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-4601-serialize-cookie-imports branch 2 times, most recently from 583ba6e to cb5cfeb Compare August 17, 2026 10:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/main/browser/browser-cookie-import-concurrency.test.ts (2)

139-144: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the narrative block comments.

Both blocks record review history and reasoning about mutation testing. Keep the intent in one line each and drop the process narrative.

As per coding guidelines: "Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code."

Also applies to: 233-237

Source: Coding guidelines


19-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover lock release when dispose() throws.

Configure disposeClearStoreMock to throw and assert that a subsequent import on the same partition completes. No existing test covers this cleanup failure path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d3c3687e-9ef7-4be2-9379-6478ad7c6789

📥 Commits

Reviewing files that changed from the base of the PR and between 3121873 and cb5cfeb.

📒 Files selected for processing (3)
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-concurrency.test.ts
  • src/main/browser/browser-cookie-import.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-import-clear.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 1 remains after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review provenance and one caveat on how the final verdict was delivered

Recording this on the PR rather than only in working notes, because the merge decision is made from here.

Verdict

Round 4 returned CLEAN WITH NO CHANGES at cb5cfebbdb — the current head. It made no code changes, ran its own mutation testing (removing and restoring both import locks), and audited the full diff against HEAD^ for any live-jar mutation outside the lock.

Caveat, stated plainly: that verdict was UNDELIVERED through the orchestration channel. The reviewer's worker_done failed with Dispatch <id> capability is revoked, it retried, got the same failure, and explicitly self-flagged UNDELIVERED. The verdict text was read from its terminal, not received as a message.

That capability revocation is an infrastructure fault — every worker dispatch in this session started with runtime_unavailable, leaving dispatches that were later revoked. It is not evidence about this code. Accepting it is a deliberate call, made on these grounds:

  • Round 4 was not interrupted and not rate-limited — it completed its analysis and reached a verdict; only the transport failed.
  • Two independent rounds reached the same verdict on the same head. Round 3 also concluded CLEAN WITH NO CHANGES at cb5cfebbdb (that round was interrupted, so it is recorded UNVERIFIED on its own, but its substance corroborates).
  • The verdict was CLEAN WITH NO CHANGES, so there is no "did the fix actually land" ambiguity that an undelivered CLEAN-AFTER-PUSHES would carry.
  • Its substance matched independent mutation testing done outside the review (below).

The contrast that matters, given this PR's lineage: #14729's review was substantively incomplete — interrupted with concerns never re-verified. This one reached a conclusion; only the message failed to send.

What the earlier rounds found, and how each was fixed

Round Finding Resolution
1 Tests exercised only the lock primitive — they would pass if the production call sites stopped acquiring it Added a real two-concurrent-import test (path A)
2 Path B detector gap — the path A test never invokes importCookiesFromBrowser, so deleting path B's lock left all 673 tests green Added a native two-concurrent-import detector
2 The __init probe ruling was wrong. It had been left outside the lock on the claim that no import writes https://localhost/__init. False: normalizeCookieImportDomain accepts localhost, cookie names are unrestricted, and deriveUrl('localhost', true) returns exactly that URL — so an unlocked probe's remove() could delete a cookie a concurrent import had just written Probe now runs under the lock; the code comment records that the earlier claim was false rather than silently replacing it
3 No new findings; verdict CLEAN Interrupted + rate-limited → recorded UNVERIFIED
4 No new findings; verdict CLEAN WITH NO CHANGES Accepted, with the delivery caveat above

Independent mutation testing (not from any review)

Mutation Result
lock → no-op (primitive) 2 ordering cases red; different-owner and release-on-throw stay green
path A drops acquireCookieMutationLock expected [...] to not include 'remove:old-b'
path B lock → passthrough expected [ 'clearData', 'clearData' ] to have a length of 1 but got 2
both locks removed both detectors red — rules out the imports serialising incidentally rather than because of the lock

A mutation has to be structure-preserving to mean anything: an early attempt dropped path B's wrapper but left the closing }), turning the block into an uninvoked IIFE. Six tests went red for "the code never ran", which proves nothing.

Known-flaky CI

skill-install-lock.test.ts > reclaims a fresh legacy lock whose process was killed and its dependent verify gate failed on one run. Unrelated to this change — the diff touches zero files under src/main/skills, and that test passes 11/11 locally.

Two concurrent cookie imports on one partition can erase a session. Nothing
serialises imports per partition — neither the renderer IPC handler
(browser-session-profile-ipc.ts) nor the runtime RPC method
(orca-runtime-browser.ts) — and the clear lock covered only the clear itself,
so it was released before the writes and before any rollback.

Reachable interleaving:

  import A replaces cookies for its imported domains, releases the lock, and
  later fails a write; import B clears and writes; A's rollback then removes
  cookies B already wrote and reported as imported.

Path B has the same shape: A clears, B clears, then A writes its cookies on top
of B's jar.

Fix: one lock spans the whole live-jar transaction on both paths — the
clear/replace, the writes, and the rollback. withCookieClearLock becomes
acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a
try/finally rather than a single callback.

Rebased onto #15030 (STA-4300), which rewrote this file: imports now write
through CDP identities, so path A's writes moved from an inline cookies.set()
loop into writeImportedCookies(), path B's into the same helper, and — the part
that matters for a lock — importValidatedCookies no longer holds the Electron
Session at all. It receives a CookieImportTarget that hides the Session behind
openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so
keying the lock on anything reachable from it would serialise nothing. The
target therefore carries mutationLockOwner, set to session.fromPartition's
instance, which is the same object the native path locks on. That is what keeps
both paths on one key per partition.

Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start
replay keep their existing semantics, so two other pre-existing hazards in that
subsystem are untouched and still open — the crash window between the clear and
the result, and a permanently-armed replay when replay keeps failing. Both need
the pending-image operations to become provable, which is a different change.

The lock is keyed per owner, so imports into different partitions still run
concurrently.

Mutation-proved against the rebased tree, every mutation structure-preserving
(brace/paren balance pinned) and every one re-run rather than carried over:
dropping path A's acquire reddens the file-import detector; keying path A's
acquire on a fresh object instead of mutationLockOwner reddens it too — the
lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with
a passthrough reddens the native detector; doing both reddens both, which rules
out incidental serialisation; and neutering the cold-init probe's lock reddens
the new probe detector. That last detector is new: neutering the probe lock
previously left all 779 browser tests green, so the probe's protection was
unproven.

The concurrency suite's store stub also gained writeCookieIdentity and
getStoragePath. Without them the STA-4300 code throws a TypeError that
writeImportedCookies catches as a write rejection, so the imports would have
taken the failure path while the ordering assertions still passed. Each real
import test now asserts writeCookieIdentity was CALLED, and that cookies.set
never was.

src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware
code quality, oxfmt and the max-lines ratchet all clean.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-4601-serialize-cookie-imports branch from cb5cfeb to f8a3a48 Compare August 18, 2026 09:59
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Rebased onto current main — the lock re-established against #15030's rewrite

The review-provenance comment above still stands for the pre-rebase tree. This adds what changed, and re-derives the protection from scratch rather than carrying the old evidence forward.

The conflict

The branch went 69 commits behind and browser-cookie-import.ts conflicted, because #15030 (STA-4300) rewrote it: every cookie-import write now goes through CDP identities.

Two structural changes matter for a lock:

  1. The write sites moved. Path A's inline targetSession.cookies.set() loop and path B's became calls to writeImportedCookies(store, …), which writes via store.writeCookieIdentity(). The rollback moved with it — phase.attemptedKeys replaced the hand-built importedCookieKeys.
  2. importValidatedCookies no longer holds the Electron Session at all. It now takes a CookieImportTarget — { partition, openWriteStore } — that keeps the Session inside a closure. The lock is keyed on an object identity, so this is the part a textual resolution silently gets wrong: openWriteStore() builds a fresh adapter per call, so anything reachable from the new signature is a new key every time, and a lock on it serialises nothing while looking entirely correct.

Resolution: CookieImportTarget carries a mutationLockOwner, set by cookieImportTarget() to session.fromPartition(partition) — the same instance the native path locks on, since Electron returns one Session per partition string. That is what keeps both paths on one key per partition. Everything else in the conflicted hunks was taken from main wholesale; no STA-4300 behaviour was absorbed, reverted, or restructured.

Every live-jar / staged-image mutation in main's current structure, and whether the lock covers it

Path A — importValidatedCookies (file import, Firefox, Safari). Lock: acquireCookieMutationLock(target.mutationLockOwner) … releaseMutationLock() in the outer finally.

# Mutation Inside the lock
1 replaceCookiesForImportedDomains(cookieClearStore, …) — removes existing cookies in the replace scope yes
2 writeImportedCookies(cookieClearStore, …) → writeCookieIdentity yes
3 rollback cookieClearStore.remove(url, name) over phase.attemptedKeys yes
4 rollback cookieClearStore.restoreClearIdentities(…) yes

Both early returns inside the span (replace failure, rollback failure) exit through the finally, so the lock is released on every path. The lock is taken after openWriteStore() deliberately: that call only constructs the adapter and attaches no debugger, so a queued import cannot hold a resource the lock holder needs.

Path B — importCookiesFromBrowser (native Chromium). Two spans.

# Mutation Inside the lock
5 cold-init probe cookies.set / cookies.remove / flushStore on https://localhost/__init yes — its own withCookieMutationLock
6 removeTransplantableCookies(…, nativePlan.skippedFamilies) → clearData + removes + restores yes
7 writeImportedCookies(cookieClearStore, writable, …) yes

Stated plainly — what sits outside the lock:

  • The pre-staging targetSession.cookies.flushStore() that runs before the staging copy is taken. It changes no cookie, but it does decide what the staged image captures.
  • browserSessionRegistry.setPendingCookieImport / clearPendingCookieImport and discardStagingFile() — the staged-image and cold-start-replay operations.

Both are the declared boundary of this change, unchanged from the pre-rebase version: it covers the live jar only. The staging-side hazards (the crash window between the clear and the result, and a permanently-armed replay) still need the pending-image operations to become provable, which is a different change.

removeTransplantableCookies' own internal lock remains a no-op for the importer, because both paths hand it a freshly-built adapter literal. That is why the importer's outer lock is load-bearing and must not be removed on the assumption the inner one covers it.

Mutation proofs — re-run against the REBASED code, not carried over

Every mutation is structure-preserving; brace/paren/bracket balance was asserted identical to the clean file before each run, so nothing turned into an uninvoked block.

Mutation Detector Result
Path A: drop acquireCookieMutationLock, keep releaseMutationLock as a no-op two concurrent imports into one partition RED — expected […] to not include 'remove:old-b'
Path A: keep the acquire but key it on {} instead of mutationLockOwner same RED — same assertion
Path B: withCookieMutationLock → an identically-shaped passthrough two concurrent NATIVE imports into one partition RED — expected ['clearData','clearData'] to have a length of 1 but got 2
Both path A and path B at once both RED, both — rules out incidental serialisation
Cold-init probe: its lock → a passthrough cold-init probe on a partition that has never stored a cookie RED — expected ['set:__init','remove:__init'] to not include 'set:__init'

The second row is the one this rebase specifically needed: it is the lock present but no longer covering the right thing shape, and the detector catches it.

Two detector defects found and fixed while re-proving

1. The store stub went stale and would have made both real-import tests vacuous. STA-4300 writes via writeCookieIdentity, which the concurrency suite's openCookieClearStore mock did not have. The resulting TypeError is caught by writeImportedCookies as a write rejection — exactly the swallow-and-fall-through trap this module is known for. Both imports would have written nothing while the ordering assertions still held. The stub now implements writeCookieIdentity (and getStoragePath, which STA-4300 made the source of the partition dir), and each test asserts writeCookieIdentity was called — path attempted, not just end state — and that cookies.set was never reached.

2. The cold-init probe's lock had no detector at all. Neutering it left all 779 browser tests green, because the other native test pre-creates the target DB so the probe never runs. Added cold-init probe on a partition that has never stored a cookie: it holds the partition lock externally, starts a native import, asserts __init is neither written nor removed while the lock is held, then releases and asserts the probe did run — the non-vacuity guard that caught the first draft of this very test, where the pre-staging flushStore created the DB early and the probe was skipped.

Validation at f8a3a48ffb

  • src/main/browser — 72 files, 780 tests, green (vitest run --config config/vitest.config.ts src/main/browser)
  • typecheck (project runner, not tsc -b) — clean; probed by injecting a type error into both changed source files to confirm the gate is live and covers them
  • oxlint src/main/browser — clean; probed with a deliberate no-debugger violation to confirm the gate is not silently dead
  • oxlint --config config/oxlint-code-quality-native-plugins.json src config tests mobile --deny-warnings — clean
  • oxlint --type-aware --config config/oxlint-code-quality-type-aware.json src --deny-warnings — clean
  • oxfmt --check on the three changed files — clean (the 8 unformatted files elsewhere in src/ are pre-existing on main)
  • max-lines ratchet — OK — 190 grandfathered suppression(s), no new bypasses; no max-lines disable was added

Scope is unchanged: one commit, STA-4601 only. STA-4183 and STA-4240 are untouched.

@coderabbitai

coderabbitai Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/browser/browser-cookie-import-concurrency.test.ts (1)

233-234: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

A failed assertion leaves import promises pending forever. In all three suites the unblock call runs after the assertions. If an assertion throws, the gate is never resolved, the awaited import promises stay pending, and the run stalls until the Vitest timeout instead of reporting the assertion. Release the gate from cleanup in each suite.

  • src/main/browser/browser-cookie-import-concurrency.test.ts#L233-L234: call releaseFirstWrite() in the suite afterEach as well, and await the imports with the assertions in a try/finally.
  • src/main/browser/browser-cookie-import-concurrency.test.ts#L353-L354: apply the same afterEach release for the native suite gate.
  • src/main/browser/browser-cookie-import-concurrency.test.ts#L456-L457: store the lock release in a suite-scoped variable and call it from afterEach so a failed probe assertion cannot wedge the lock owner.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 467c162e-edb5-407f-8c65-e5470f8ab67a

📥 Commits

Reviewing files that changed from the base of the PR and between 6efd406 and 3d97f1e.

📒 Files selected for processing (3)
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-concurrency.test.ts
  • src/main/browser/browser-cookie-import.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/browser/browser-cookie-import-clear.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 3 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop — rounds 1 and 2 (round 3 running)

Recording each round on the PR, because both rounds changed the branch and the merge decision is made from here. The rebase comment above still stands for f8a3a48ffb; this is what happened to it since.

The branch is now three commits:

Commit Round What it does
f8a3a48ffb — The rebased STA-4601 change: one per-partition lock spanning the live-jar mutations on both import paths.
70946bda56 1 Wraps the entire body of importCookiesFromBrowser in one withCookieMutationLock, from the first flushStore() through SQLite staging, live clear/writes, pending-image bookkeeping and cleanup; removes the two inner locks.
3d97f1efbe 2 Test-only: makes the native session's flushStore mock emit an event and asserts exactly one flush occurs while the first transaction holds the partition.

Round 1 — made changes

It re-derived the mutation inventory, found the native path's flush / staging / pending-image mutations sitting outside the lock, and hoisted the lock to cover the whole function.

70946bda56 is 479 insertions and 479 deletions, but only 8 lines change under git show -w — the rest is indentation from the wrap.

I did not take its report at face value. What I verified independently:

  • No deadlock. importCookiesFromFirefox and importCookiesFromSafari return before the wrap begins, and nothing inside the wrap re-enters importValidatedCookies, so the whole-function lock cannot contend with path A's acquireCookieMutationLock on the same Session.
  • Gates genuinely green at 70946bda56 — 72 files / 780 tests, typecheck, oxfmt, max-lines ratchet (188 grandfathered, no new bypasses).
  • But it was entirely unpinned. I put f8a3a48ffb's version of browser-cookie-import.ts back while keeping every test file from 70946bda56: 72 files / 780 tests still passed. Round 1 changed no test file, so the protection it added could not be distinguished from its absence by any test in the repo. That is "correct in code but unpinned by test" — a finding, not a pass.
  • It crossed a boundary that f8a3a48ffb had drawn deliberately and explained in its commit message (live jar only; staging and cold-start replay keep their existing semantics), without arguing against that rationale.

Round 2 — made changes, agrees round 1 should stay

Round 2 was dispatched with round 1's own commit as its primary target. Its verdict, verbatim from its terminal:

ROUND 2 VERDICT — MADE CHANGES; ANOTHER REVIEW ROUND REQUIRED
Recommendation: KEEP 70946bda56 whole-function native lock. The protection is real, reachable, and correctly closes a native staged-image/live-jar ordering hazard; reverting it would re-open the race.

It pushed 3d97f1efbe, which closes the unpinned-ness. I verified that detector is load-bearing myself rather than trusting the claim: replacing browser-cookie-import.ts with f8a3a48ffb's version, so the wrap narrows back to the live jar only, makes it fail with

AssertionError: expected [ 'flushStore', 'flushStore' ] to have a length of 1 but got 2

Round 2 also ran its own mutation battery with an explicit brace/paren/bracket balance check before trusting any red result, and confirmed by diff that the source was byte-identical afterwards — the discipline this PR needs, since an earlier attempt on it turned a block into an uninvoked IIFE and read six "the code never ran" failures as a passing mutation.

Full suite at 3d97f1efbe: 72 files / 780 tests green.

One correction to my own earlier reasoning

I initially suspected round 1's wrap now holds the partition lock across a blocking macOS Keychain prompt. It does span getEncryptionKey, but that is execFileSync with a 30s timeout — it already blocks the whole main process regardless of the lock, so the marginal cost is not a real regression. Withdrawing that concern.

Round 3 is running

Round 2 stated it did not end clean, so the loop continues. Round 3's primary target is round 2's own detector, with two questions it must settle by mutation rather than by reading:

  1. The detector pins only the first flushStore. Round 1 also brought SQLite staging, the staging file copy, and setPendingCookieImport / clearPendingCookieImport inside the lock. If a mutation that narrows the wrap to cover flush-plus-live-jar but excludes the pending-image bookkeeping still leaves the suite green, then round 1's central claim is still unpinned and round 2's detector gives false confidence.
  2. Neither round wrote the staged-image hazard down as a concrete reachable interleaving. Round 3 must produce that sequence — which import does what, in what order, what the user loses — or say plainly that it is not reachable and 70946bda56 should be reverted to restore the declared live-jar-only boundary.

Two process notes

  • worker_done delivery is broken by STA-4671 (dispatch capability revoked mid-run). Round 2 hit it: its dispatch settled while it was still working, and its verdict never reached the coordinator mailbox. The verdict above was read from its terminal, not delivered. Round 2's own work did land — it committed and pushed before finishing.
  • Rounds 1 and 2 were each created by worker-start --base-branch on a stale local branch of the PR's name sitting at cfcea0b687 (92 behind main, carrying an unrelated revert(browser): move import serialization out to STA-4601). Round 1 read that tree before I caught it and repointed both worktrees at the real head; I confirmed it picked up the correction before drawing conclusions.

Not merged. Rounds 1 and 2 are recorded as changed, not clean; the loop continues until a round returns CLEAN WITH NO CHANGES.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Round 3 — made changes, and its detector is vacuous

Recording this because it is the kind of thing that otherwise reads as progress. Round 4 is running with it as the primary target.

Round 3 was dispatched with round 2's detector as its target, and asked to settle two things by mutation rather than by reading: whether round 2's flushStore assertion is sufficient (it pins only the leading edge of round 1's wrap), and whether the staged-image hazard is real enough to justify round 1 crossing f8a3a48ffb's declared live-jar-only boundary.

It found the first gap correctly and pushed e3003ab36f — a new describe block, staged-image bookkeeping is serialized with native imports, which mocks ./browser-session-registry and asserts import A registers its pending image before import B retires it.

That test does not detect what it was added to detect. Reproduction, from the repo root:

git show f8a3a48ffb:src/main/browser/browser-cookie-import.ts > src/main/browser/browser-cookie-import.ts
npx vitest run --config config/vitest.config.ts \
  src/main/browser/browser-cookie-import-concurrency.test.ts -t "staged-image" --reporter=verbose

f8a3a48ffb is exactly the state the test claims to catch — the pending-image bookkeeping outside the lock. Result:

✓ staged-image bookkeeping is serialized with native imports > registers A before B retires the pending image 13ms
  Test Files  1 passed (1)
       Tests  1 passed | 8 skipped (9)

It ran, it was not skipped, and it passed. The captured diag shows why: import A reached staged at … for 1 cookies that need restart and import B then reached all cookies loaded in-memory — no restart needed, so A registered and B cleared afterwards by microtask scheduling, not because any lock enforced it. The assertion holds in the broken state, which makes it worse than no test — it reports the protection as covered.

For contrast, round 2's detector is genuinely load-bearing. The same narrowing makes it fail:

AssertionError: expected [ 'flushStore', 'flushStore' ] to have a length of 1 but got 2

I verified both of these myself rather than relying on the round reports.

Where that leaves the branch

Commit Round Status
f8a3a48ffb — the rebased STA-4601 change
70946bda56 1 whole-function native lock — leading edge pinned, tail still unpinned
3d97f1efbe 2 flushStore detector — verified load-bearing
e3003ab36f 3 staged-image detector — vacuous, must be replaced or deleted

Suite at e3003ab36f: 72 files / 781 tests green — but one of those 781 is not measuring anything.

The interleaving nobody has written down yet

Three rounds have asserted the staged-image hazard is real without stating it. Here is the sequence I believe is reachable on the pre-70946bda56 code, which round 4 has been asked to confirm, correct, or refute:

Import A writes everything successfully, so it will call clearPendingCookieImport. Import B has write failures, so it registers stagingPathB for cold-start replay. With the lock released before the bookkeeping, B can register before A clears — and A's clearPendingCookieImport then wipes B's pending image. B's failed cookies never replay at cold start, and B already reported success to the user.

That is the same silent-partial-loss shape as STA-4013 / 4061 / 4090 / 4170, which is why it is worth pinning properly rather than with a test that passes either way. If round 4 finds it is not reachable, then 70946bda56 should be reverted and f8a3a48ffb's declared boundary restored.

Round 4's instructions

Replace the vacuous test with one that fails against f8a3a48ffb's source and passes against the current source — showing both results with actual assertion text — or delete it. Explicitly: if the interleaving cannot be made deterministic, delete the test rather than ship a coin flip. Round 4 must also apply that same check to every test on the branch, since round 3's was written by a reviewer working from the same instructions.

Rounds 1, 2 and 3 are all recorded as changed, not clean. Not merged.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Rounds 4 and 5 — the loop's premise was wrong, and the real hazard is a different one

Rounds 1–3 all argued that round 1's whole-function lock closes a pending-image bookkeeping ordering hazard. That is not the hazard. Round 4 deleted round 3's test for the right action but the wrong reason, and round 5 settled it.

Round 4 — deleted the vacuous test

Round 4 reproduced the vacuity and pushed 6203162fa7, removing round 3's test. Verdict: MADE CHANGES; ANOTHER ROUND REQUIRED.

The bookkeeping-ordering hazard is NOT reachable

I need to correct something I wrote in the previous comment. I described round 3's test as passing by "microtask luck." It wasn't luck — the property holds deterministically, and the test could never have reddened.

On f8a3a48ffb, the live-jar lock ends at line 2082 and browserSessionRegistry.setPendingCookieImport is at line 2094. That span contains zero await:

      })                              <- lock callback ends
    } finally { cookieClearStore.dispose() }
    diag(`  memory load: …`)
    let warning: BrowserCookieImportSummary['warning']
    if (memoryFailed > 0 && stagingAvailable) {
      browserSessionRegistry.setPendingCookieImport(targetPartition, stagingCookiesPath)

dispose(), diag(), the let, and the if/else are all synchronous, and discardStagingFile is unlinkSync. JavaScript is single-threaded, so once import A's await on the lock resolves, A runs straight through its bookkeeping in that same continuation. Import B cannot interleave there — with or without the lock.

The REAL hazard: a stale staged image

copyFileWithWindowsRetry(liveCookiesPath, stagingCookiesPath) is at line 1641 — outside and before the live-jar lock at 2047. So both concurrent imports take their staging copy before either acquires the lock:

  1. Import A copies the live cookie DB. Image A reflects jar state S0.
  2. Import B copies the live cookie DB. Image B also reflects S0.
  3. Both decrypt and build their staging DBs — that half is full of awaits, so there are many interleaving points.
  4. B takes the lock, clears the jar, writes B's cookies, releases, bookkeeps.
  5. A takes the lock, clears, writes. A had at least one write rejection, so A calls setPendingCookieImport(partition, stagingA).

stagingA is S0 plus A's inserted rows. It predates B's import entirely. At the next cold start it replays over the live partition and B's whole import is gone — after B already reported success to the user. Same silent-partial-loss shape as STA-4013 / 4061 / 4090 / 4170.

Round 1's whole-function lock closes it by bringing line 1641 inside the transaction: A copies, clears, writes and bookkeeps, and only then does B copy — so no image can predate a completed concurrent import.

So 70946bda56 should stay — but for this reason, not the one rounds 1–3 gave.

Round 5 — confirmed both, and shipped the detector that was missing

Round 5 was dispatched with both claims and told explicitly I would rather be corrected than confirmed. Its verdict:

ROUND 5 VERDICT: STALE STAGED IMAGE HAZARD CONFIRMED; BOOKKEEPING-ORDERING HAZARD REFUTED AS UNREACHABLE.

It pushed 57db159ebc, instrumenting the staging copy so each import emits an ordered event and asserting the second import's copy cannot happen until the first has finished writing.

I ran the acceptance test on it myself. Against f8a3a48ffb's source it fails:

FAIL  two concurrent NATIVE imports into one partition
      > does not let a second native import clear while the first is still writing
AssertionError: expected [ 'flushStore', 'copy:first', …(4) ] to not include 'copy:second'

Against the current source it passes, 8/8. It is enforced by the lock rather than by scheduling, so unlike round 3's it cannot pass in the broken state.

Branch and gates at 57db159ebc

Commit Round Status
f8a3a48ffb — the rebased STA-4601 change
70946bda56 1 whole-function native lock — keep, justified by the stale-image hazard
3d97f1efbe 2 flushStore detector — verified load-bearing
e3003ab36f 3 vacuous detector
6203162fa7 4 deletes it
57db159ebc 5 stale-staging-image detector — verified load-bearing
  • src/main/browser — 72 files, 780 tests, green
  • typecheck (project runner, not tsc -b) — clean
  • oxlint, native code-quality (src config tests mobile --deny-warnings), type-aware code-quality — all clean
  • oxfmt --check — clean
  • max-lines ratchet — OK — 188 grandfathered suppression(s), no new bypasses; zero max-lines disables added across the whole diff

Round 6 is running as a convergence round, with round 5's own detector as its primary target and an explicit instruction that returning CLEAN WITH NO CHANGES is the desired outcome rather than a failure — plus the same acceptance test applied to every test on the branch, since two of six rounds shipped something that did not do what it claimed.

Not merged.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Rounds 6 and 7, and where I am stopping the loop

I ran seven rounds. Every round made a change, so the loop never formally returned CLEAN WITH NO CHANGES. But the changes shrank monotonically — round 1 restructured the lock, round 7 changed three lines of test setup — and rounds 6 and 7 both reported no production-code defects. I am calling that substantive convergence and handing it to you rather than running an eighth round, because the marginal finding is now test hardening rather than correctness.

Round 6 — 941748430f, a real non-vacuity fix

Two toContain guards before an ordering assertion:

expect(events).toContain('set:new-a')
expect(events).toContain('remove:old-b')
expect(events.indexOf('set:new-a')).toBeLessThan(events.indexOf('remove:old-b'))

Not cosmetic. Without them, an absent set:new-a makes indexOf return -1, and -1 < k is true for any present remove:old-b — so the ordering assertion passed vacuously whenever the event it was ordering went missing. Round 6 otherwise found nothing.

Round 7 — cdb0db690b, widened the detector's boundary

It starts both native imports before either writes, instead of starting B only after A parks in its write. That makes the detector cover the whole lock boundary — B's staging copy must be blocked, not merely B's clear/write.

The acceptance-test evidence shows the widening is real. Before round 7, narrowing to f8a3a48ffb produced [ 'flushStore', 'copy:first', …(4) ]. After, it produces [ 'flushStore', 'flushStore', …(4) ] — B now gets all the way to its own flush under the narrowed lock, which the earlier version never exercised.

I also ran the concurrency suite 5×: 8/8 every time, no flake, which matters because this test coordinates two real imports through a polling hold point.

Final state at cdb0db690b

Eight commits, three files. The raw diff on browser-cookie-import.ts is 1018 lines, but under git diff -w the whole branch is 40 semantic lines in that file — everything else is indentation from round 1's wrap.

Commit Round Outcome
f8a3a48ffb — STA-4601 rebased onto #15030's rewrite
70946bda56 1 whole-function native lock — keep, justified by the stale-image hazard
3d97f1efbe 2 flushStore detector — load-bearing
e3003ab36f 3 staged-image detector — vacuous
6203162fa7 4 deletes round 3's test
57db159ebc 5 stale-staging-image detector — load-bearing
941748430f 6 non-vacuity guards
cdb0db690b 7 widens the detector's lock boundary

Gates, all run by me at this head rather than taken from the round reports:

  • src/main/browser — 72 files, 780 tests, green; concurrency suite 5× stable
  • acceptance test — the suite fails against f8a3a48ffb's source and passes against current, so the detectors are load-bearing rather than decorative
  • typecheck (project runner, never tsc -b) — clean
  • oxlint, native code-quality (src config tests mobile --deny-warnings), type-aware code-quality — clean
  • oxfmt --check — clean
  • max-lines ratchet — OK — 188 grandfathered, no new bypasses; zero max-lines disables added

main moved 8 commits during the session. Its three newest commits touch none of these three files, and GitHub reports the PR MERGEABLE, so I did not re-rebase again — chasing a moving base adds risk without adding signal.

What I'd want you to decide

  1. Keep 70946bda56? It crosses the live-jar-only boundary f8a3a48ffb declared. I believe it should stay — the stale-staged-image hazard is real and reachable, and it is now pinned. But it is a scope expansion past what the ticket described, so it is your call, not the loop's.
  2. Squash? Eight commits, four of which are the loop arguing with itself (round 3 adds a test, round 4 deletes it). The repo squash-merges, so this resolves itself on merge — but if you want the branch itself readable, it should collapse to one or two.

Process notes

  • worker_done delivery is unreliable (STA-4671). Round 2's capability was revoked mid-run and its verdict never reached the mailbox; I read it from the terminal. Rounds 3, 5, 6 and 7 delivered. worker-start also twice returned "the Orca runtime closed the connection before responding" and needed --retry-request to recover idempotently.
  • worker-start --base-branch resolved to a stale local branch at cfcea0b687 (92 behind main, carrying an unrelated revert(browser): move import serialization out to STA-4601). Round 1 read that tree before I caught it. Every subsequent round's worktree had to be manually repointed at the real head.
  • Two of seven rounds shipped something that did not do what it claimed (rounds 1 and 3), and both passed their own author's review. The acceptance test — fail against the pre-fix source, pass against current, or be deleted — is what caught them, and is worth making standard for any concurrency detector.

Not merged.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Manual Electron validation (STA-4601)

Verdict: IMPORT WORKS
Back-to-back imports completed: YES

This is the missing local Settings-surface run. It does not prove or disprove the concurrency race (that is already pinned by the automated suite). It tests whether wrapping every jar mutation in a per-partition lock broke or deadlocked ordinary import.

I did not merge.

Instance (CDP ownership)

window.api.app.getIdentity() on http://127.0.0.1:9333:

  • name: Orca: brennanb2025/sta4601-qa-15095
  • isDev: true
  • devBranch: brennanb2025/sta4601-qa-15095
  • devWorktreeName: sta4601-qa-15095
  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta4601-qa-15095
  • HEAD: cdb0db690b
  • Isolated with ORCA_DEV_USER_DATA_PATH=/tmp/orca-electron-qa-15095-profile (did not touch the interactive profile)
  • Product code was not modified

What I actually clicked

Settings → Browser → Session & Cookies → Import Cookies → From Google Chrome → stably.ai (Chrome directory Default) into the Default profile (persist:orca-browser). Then the same path again immediately.

Import 1

Result status: success, error: null — completed, no hang, no stuck spinner
Summary total 949 / imported 869 / skipped 80 (googleCookiesSkipped: 80)
Duration 333 ms click → source.importedAt
Visible Default row went from No cookies imported to Google Chrome (stably.ai); toast reported 869 imported / 80 Google skipped

Import 2 (same partition, immediately after)

Result status: success, error: null — completed
Summary total 949 / imported 869 / skipped 80
Duration 319 ms click → source.importedAt
Proof it re-ran importedAt advanced 1787089401396 → 1787089447091

A lock that never released would have hung import 2. It did not.

Timing

Both real Chrome imports of 949 cookies finished in ~320–330 ms. That is not a noticeable stall. I did not time main as a paired baseline, so this is not a regression number against the pre-lock code — only that a single import is not stuck or multi-second-slow under the new lock.

Concurrent imports through the UI

Could not start two imports close together through the UI. Import Cookies is disabled while importState.status === 'importing'. That is an expected answer, not a failure, and it is not a race proof. I did not fire parallel store actions.

Unproven (said plainly)

  • The interleaving race itself (timing-dependent; already covered by the automated suite)
  • Concurrent imports through the Settings UI (button disabled)
  • File-import, remote/SSH host import, or a second Orca profile/partition
  • Latency vs main (no paired baseline)

Screenshots

Before — Default / No cookies imported:

before import

Menu — From Google Chrome → stably.ai / Brennan:

chrome profiles

After import 1 — toast + Google Chrome (stably.ai):

after import 1

After import 2 — same partition, completed:

after import 2

@brennanb2025
brennanb2025 merged commit 9312c5c into main Aug 18, 2026
46 checks passed
brennanb2025 added a commit that referenced this pull request Aug 18, 2026
…d clear (STA-4797)

#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
#15095's protection is intact and the re-anchoring did not hollow it out.
brennanb2025 added a commit that referenced this pull request Aug 19, 2026
…d clear (STA-4797)

#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
#15095's protection is intact and the re-anchoring did not hollow it out.
brennanb2025 added a commit that referenced this pull request Aug 19, 2026
…imports (STA-4797) (#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
* fix(browser): serialize cookie imports per partition (STA-4601)

Two concurrent cookie imports on one partition can erase a session. Nothing
serialises imports per partition — neither the renderer IPC handler
(browser-session-profile-ipc.ts) nor the runtime RPC method
(orca-runtime-browser.ts) — and the clear lock covered only the clear itself,
so it was released before the writes and before any rollback.

Reachable interleaving:

  import A replaces cookies for its imported domains, releases the lock, and
  later fails a write; import B clears and writes; A's rollback then removes
  cookies B already wrote and reported as imported.

Path B has the same shape: A clears, B clears, then A writes its cookies on top
of B's jar.

Fix: one lock spans the whole live-jar transaction on both paths — the
clear/replace, the writes, and the rollback. withCookieClearLock becomes
acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a
try/finally rather than a single callback.

Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write
through CDP identities, so path A's writes moved from an inline cookies.set()
loop into writeImportedCookies(), path B's into the same helper, and — the part
that matters for a lock — importValidatedCookies no longer holds the Electron
Session at all. It receives a CookieImportTarget that hides the Session behind
openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so
keying the lock on anything reachable from it would serialise nothing. The
target therefore carries mutationLockOwner, set to session.fromPartition's
instance, which is the same object the native path locks on. That is what keeps
both paths on one key per partition.

Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start
replay keep their existing semantics, so two other pre-existing hazards in that
subsystem are untouched and still open — the crash window between the clear and
the result, and a permanently-armed replay when replay keeps failing. Both need
the pending-image operations to become provable, which is a different change.

The lock is keyed per owner, so imports into different partitions still run
concurrently.

Mutation-proved against the rebased tree, every mutation structure-preserving
(brace/paren balance pinned) and every one re-run rather than carried over:
dropping path A's acquire reddens the file-import detector; keying path A's
acquire on a fresh object instead of mutationLockOwner reddens it too — the
lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with
a passthrough reddens the native detector; doing both reddens both, which rules
out incidental serialisation; and neutering the cold-init probe's lock reddens
the new probe detector. That last detector is new: neutering the probe lock
previously left all 779 browser tests green, so the probe's protection was
unproven.

The concurrency suite's store stub also gained writeCookieIdentity and
getStoragePath. Without them the STA-4300 code throws a TypeError that
writeImportedCookies catches as a write rejection, so the imports would have
taken the failure path while the ordering assertions still passed. Each real
import test now asserts writeCookieIdentity was CALLED, and that cookies.set
never was.

src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware
code quality, oxfmt and the max-lines ratchet all clean.

* fix(browser): serialize native cookie staging

* test(browser): pin native flush serialization

* test(browser): pin staged cookie replay ordering

* test(browser): remove vacuous staged replay detector

* test(browser): detect stale native staging images

* test(browser): guard cookie import ordering events

* test(browser): cover staging lock boundary
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
* fix(browser): serialize cookie imports per partition (STA-4601)

Two concurrent cookie imports on one partition can erase a session. Nothing
serialises imports per partition — neither the renderer IPC handler
(browser-session-profile-ipc.ts) nor the runtime RPC method
(orca-runtime-browser.ts) — and the clear lock covered only the clear itself,
so it was released before the writes and before any rollback.

Reachable interleaving:

  import A replaces cookies for its imported domains, releases the lock, and
  later fails a write; import B clears and writes; A's rollback then removes
  cookies B already wrote and reported as imported.

Path B has the same shape: A clears, B clears, then A writes its cookies on top
of B's jar.

Fix: one lock spans the whole live-jar transaction on both paths — the
clear/replace, the writes, and the rollback. withCookieClearLock becomes
acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a
try/finally rather than a single callback.

Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write
through CDP identities, so path A's writes moved from an inline cookies.set()
loop into writeImportedCookies(), path B's into the same helper, and — the part
that matters for a lock — importValidatedCookies no longer holds the Electron
Session at all. It receives a CookieImportTarget that hides the Session behind
openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so
keying the lock on anything reachable from it would serialise nothing. The
target therefore carries mutationLockOwner, set to session.fromPartition's
instance, which is the same object the native path locks on. That is what keeps
both paths on one key per partition.

Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start
replay keep their existing semantics, so two other pre-existing hazards in that
subsystem are untouched and still open — the crash window between the clear and
the result, and a permanently-armed replay when replay keeps failing. Both need
the pending-image operations to become provable, which is a different change.

The lock is keyed per owner, so imports into different partitions still run
concurrently.

Mutation-proved against the rebased tree, every mutation structure-preserving
(brace/paren balance pinned) and every one re-run rather than carried over:
dropping path A's acquire reddens the file-import detector; keying path A's
acquire on a fresh object instead of mutationLockOwner reddens it too — the
lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with
a passthrough reddens the native detector; doing both reddens both, which rules
out incidental serialisation; and neutering the cold-init probe's lock reddens
the new probe detector. That last detector is new: neutering the probe lock
previously left all 779 browser tests green, so the probe's protection was
unproven.

The concurrency suite's store stub also gained writeCookieIdentity and
getStoragePath. Without them the STA-4300 code throws a TypeError that
writeImportedCookies catches as a write rejection, so the imports would have
taken the failure path while the ordering assertions still passed. Each real
import test now asserts writeCookieIdentity was CALLED, and that cookies.set
never was.

src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware
code quality, oxfmt and the max-lines ratchet all clean.

* fix(browser): serialize native cookie staging

* test(browser): pin native flush serialization

* test(browser): pin staged cookie replay ordering

* test(browser): remove vacuous staged replay detector

* test(browser): detect stale native staging images

* test(browser): guard cookie import ordering events

* test(browser): cover staging lock boundary
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(browser): serialize cookie imports per partition (STA-4601)

Two concurrent cookie imports on one partition can erase a session. Nothing
serialises imports per partition — neither the renderer IPC handler
(browser-session-profile-ipc.ts) nor the runtime RPC method
(orca-runtime-browser.ts) — and the clear lock covered only the clear itself,
so it was released before the writes and before any rollback.

Reachable interleaving:

  import A replaces cookies for its imported domains, releases the lock, and
  later fails a write; import B clears and writes; A's rollback then removes
  cookies B already wrote and reported as imported.

Path B has the same shape: A clears, B clears, then A writes its cookies on top
of B's jar.

Fix: one lock spans the whole live-jar transaction on both paths — the
clear/replace, the writes, and the rollback. withCookieClearLock becomes
acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a
try/finally rather than a single callback.

Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write
through CDP identities, so path A's writes moved from an inline cookies.set()
loop into writeImportedCookies(), path B's into the same helper, and — the part
that matters for a lock — importValidatedCookies no longer holds the Electron
Session at all. It receives a CookieImportTarget that hides the Session behind
openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so
keying the lock on anything reachable from it would serialise nothing. The
target therefore carries mutationLockOwner, set to session.fromPartition's
instance, which is the same object the native path locks on. That is what keeps
both paths on one key per partition.

Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start
replay keep their existing semantics, so two other pre-existing hazards in that
subsystem are untouched and still open — the crash window between the clear and
the result, and a permanently-armed replay when replay keeps failing. Both need
the pending-image operations to become provable, which is a different change.

The lock is keyed per owner, so imports into different partitions still run
concurrently.

Mutation-proved against the rebased tree, every mutation structure-preserving
(brace/paren balance pinned) and every one re-run rather than carried over:
dropping path A's acquire reddens the file-import detector; keying path A's
acquire on a fresh object instead of mutationLockOwner reddens it too — the
lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with
a passthrough reddens the native detector; doing both reddens both, which rules
out incidental serialisation; and neutering the cold-init probe's lock reddens
the new probe detector. That last detector is new: neutering the probe lock
previously left all 779 browser tests green, so the probe's protection was
unproven.

The concurrency suite's store stub also gained writeCookieIdentity and
getStoragePath. Without them the STA-4300 code throws a TypeError that
writeImportedCookies catches as a write rejection, so the imports would have
taken the failure path while the ordering assertions still passed. Each real
import test now asserts writeCookieIdentity was CALLED, and that cookies.set
never was.

src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware
code quality, oxfmt and the max-lines ratchet all clean.

* fix(browser): serialize native cookie staging

* test(browser): pin native flush serialization

* test(browser): pin staged cookie replay ordering

* test(browser): remove vacuous staged replay detector

* test(browser): detect stale native staging images

* test(browser): guard cookie import ordering events

* test(browser): cover staging lock boundary
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant