Repository navigation
fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797) - #15375
Conversation
📝 WalkthroughWalkthroughCookie import cleanup now uses explicit imported-domain scopes. Live removal follows a frozen, per-cookie plan with rollback and mutation locking. Staged Chromium databases record scope metadata and merge only matching cookies, while legacy images retain whole-image replay. Pending imports now support structured metadata, validation, Windows-safe staged-file consumption, and retry preservation. Tests cover domain filtering, preserved cookie families, concurrency, rollback, schema drift, cold-start replay, and future formats. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/main/browser/browser-cookie-import-policy.ts (1)
144-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce repeated rationale comments.
Keep one short comment where the shared scope contract is defined. Remove or shorten repeated explanations at downstream call sites.
src/main/browser/browser-cookie-import-policy.ts#L144-L147: reduce the scope rationale to one brief contract comment.src/main/browser/browser-cookie-import-clear.ts#L48-L50: shorten theclearDatarationale.src/main/browser/browser-cookie-import-clear.ts#L186-L188: shorten the required-scope rationale.src/main/browser/browser-cookie-import-clear.ts#L217-L223: shorten the per-coordinate removal rationale.src/main/browser/browser-cookie-import.ts#L1929-L1938: reference the shared scope contract briefly.src/main/browser/browser-cookie-import.ts#L2026-L2031: reduce the repeated live-clear rationale.src/main/browser/browser-cookie-staged-image-clear.ts#L11-L17: reduce the staged-image rationale.As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
src/main/browser/browser-cookie-import-scope.test.ts (1)
146-156: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the partition session mock into a helper.
The same session literal is repeated three times. Only
cookies.getdiffers between the three copies. A helper keeps the fixture in one place, so a future field added to the session shape needs one edit instead of three.♻️ Proposed helper
+function mockPartitionSession( + jarCookies: Record<string, unknown>[], + storagePath: string, + remove: ReturnType<typeof vi.fn> +) { + return { + cookies: { + get: vi.fn().mockResolvedValue(jarCookies), + set: vi.fn(async () => undefined), + remove, + flushStore: vi.fn().mockResolvedValue(undefined) + }, + clearData: vi.fn().mockResolvedValue(undefined), + setUserAgent: vi.fn(), + getStoragePath: () => storagePath + } +}Then each call site becomes:
- sessionFromPartitionMock.mockReturnValue({ - cookies: { - get: vi - .fn() - .mockResolvedValue(populatedTargetJar().filter((cookie) => cookie.domain !== '')), - set: vi.fn(async () => undefined), - remove: cookiesRemoveMock, - flushStore: vi.fn().mockResolvedValue(undefined) - }, - clearData: vi.fn().mockResolvedValue(undefined), - setUserAgent: vi.fn(), - getStoragePath: () => join(tmpDir, 'userData', 'Partitions', 'test') - }) + sessionFromPartitionMock.mockReturnValue( + mockPartitionSession( + populatedTargetJar().filter((cookie) => cookie.domain !== ''), + join(tmpDir, 'userData', 'Partitions', 'test'), + cookiesRemoveMock + ) + )Also applies to: 182-213, 231-243
src/main/browser/browser-cookie-import-partition.electron.test.ts (1)
79-86: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the preserved cookie so its name matches its role.
The cookie named
staleis the one that must survive the import, and its value iskeep-me. The cookie that must be removed is namedsuperseded. The namestalenow contradicts the assertion it supports. Rename it to something likeunrelatedin both the fixture and theremainingNamesexpectation.♻️ Proposed rename
await targetSession.cookies.set({ url: 'https://stale.example/', - name: 'stale', + name: 'unrelated', value: 'keep-me', secure: true })'partitioned-google', - 'stale' + 'unrelated'Keep the expected array sorted after the rename.
Also applies to: 220-221
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 543f1b46-9a8a-4915-8e04-6d94e1adf34f
📥 Commits
Reviewing files that changed from the base of the PR and between ccb2305 and d44981f18facc572e758336d2fe23217cd42c9c3.
📒 Files selected for processing (11)
src/main/browser/browser-cookie-clear-preserve.test.tssrc/main/browser/browser-cookie-import-clear-atomicity.test.tssrc/main/browser/browser-cookie-import-clear.tssrc/main/browser/browser-cookie-import-google-exclusion.test.tssrc/main/browser/browser-cookie-import-partition-rollback.electron.test.tssrc/main/browser/browser-cookie-import-partition.electron.test.tssrc/main/browser/browser-cookie-import-policy.test.tssrc/main/browser/browser-cookie-import-policy.tssrc/main/browser/browser-cookie-import-scope.test.tssrc/main/browser/browser-cookie-import.tssrc/main/browser/browser-cookie-staged-image-clear.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
769952f to
5ac83f9
Compare
Electron QA — PR #15375 / STA-4797Worktree: Gate this PR actually needsA native cookie import (
This is the native Chromium path. The file/paste path already used Launch
|
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7d23cb15-cb9b-431e-9747-29dea3a340ca
📒 Files selected for processing (8)
src/main/browser/browser-cookie-import-scope.test.tssrc/main/browser/browser-cookie-import.tssrc/main/browser/browser-cookie-staged-import.tssrc/main/browser/browser-session-cookie-staging.scoped.test.tssrc/main/browser/browser-session-cookie-staging.tssrc/main/browser/browser-session-meta-store.tssrc/main/browser/browser-session-registry.persistence.test.tssrc/main/browser/browser-session-registry.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| copyFileSync(stagedPath, liveCookiesPath) | ||
| // Why: stale WAL/SHM sidecars would corrupt CookieMonster's read of the freshly swapped DB. | ||
| let sidecarCopyFailed = false | ||
| for (const suffix of ['-wal', '-shm']) { | ||
| try { | ||
| unlinkSync(liveCookiesPath + suffix) | ||
| } catch { | ||
| /* may not exist */ | ||
| } | ||
| const stagingSidecar = stagedPath + suffix | ||
| if (!existsSync(stagingSidecar)) { | ||
| continue | ||
| } | ||
| try { | ||
| copyFileSync(stagingSidecar, liveCookiesPath + suffix) | ||
| } catch { | ||
| sidecarCopyFailed = true | ||
| } | ||
| } | ||
| const stagingSidecar = stagedPath + suffix | ||
| if (!existsSync(stagingSidecar)) { | ||
| if (sidecarCopyFailed) { | ||
| // Why: sidecar copy failed → inconsistent replay; keep this entry for retry. | ||
| continue |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Prevent partial replay when a sidecar copy fails.
Line 113 replaces the live database before Lines 122-130 copy the staged WAL and SHM files. If a sidecar copy fails, Line 134 retains the pending entry but leaves the live database replaced and its prior sidecars removed. A WAL-backed staged image can then lose committed frames before the retry occurs.
Stage the complete database bundle before replacing the live bundle, or restore the prior live database and sidecars on failure. Add a regression test for a -wal copy failure.
Review complete — LANDFinal reviewed head: No P0, P1, or P2 findings remain after the same-model senior review loop and closing readiness audit. Meaningful fixes made during review:
Validation:
Electron evidence and uncropped screenshots are attached in the Electron QA comment. The exact isolated worktree identity and disposable partition fixtures were verified. The visible Settings import flow was not driven: the renderer hit a pre-existing main-branch This is desktop browser-cookie code only; mobile, SSH, and remote-wire validation were not applicable. Windows compatibility is covered by the passing Windows package job and the retry-safe file handling review. |
…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).
…TA-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.
…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.
8b1ddc2 to
214fa5e
Compare
|
Rebase + revalidation update for
The destructive real-profile import path was intentionally not exercised against the developer machine. Domain-scoped preservation, transactional rollback, and cold-start replay remain covered by the passing Electron/unit fixtures. Status: LAND / ready to merge. |
…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)
…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)
…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)



Fixes STA-4797.
The defect
A native cookie import (Settings → Browser → Import Cookies → From Google Chrome) cleared the entire target partition's cookie jar, keeping only the non-transplantable
google.comfamily. Every unrelated site you were signed into in that partition was silently signed out — no warning before, no disclosure after. Observed in Electron QA on 2026-08-17: a workingthe-internet.herokuapp.comlogin was destroyed by an import that brought overgithub.com,nordaccount.comandyoutube.com.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 through
replaceCookiesForImportedDomains; the two import paths simply disagreed about scope, and the narrow one is the defensible shape.The fix
The native import's clear now covers only the domains it 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. (NON_TRANSPLANTABLE_HOST_KEY_SQLandNON_TRANSPLANTABLE_CLEAR_EXCLUDED_ORIGINSlost their last production callers and are gone.)browser-cookie-import-clear.ts—removeTransplantableCookiestakes a requiredimportScope. It is deliberately 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.clearDatashortcut is gone, andclearDataleavesCookieClearSessionfor the same structural reasonsetalready had. It clears by exclusion, so the only scope it can express is "everything except google.com" — the defect itself. 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 STA-4090/4170 shape). 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) — this is the half that is easy to miss. The staged image is a copy of the live jar that replaces it wholesale on the next cold start, so itsDELETE 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 — the same rows the writes come from — so the removal set is the write set. Google stays exempt by policy (STA-3811), unchanged.
Scope note
The ticket offered a fallback ("at minimum, disclose before destroying"). This PR does the preferred fix instead, which makes the fallback unnecessary: the destroyed scope is now exactly the imported scope, and the summary's existing
domainsfield already names it. No wire or summary-type change, so nothing here is a mixed-version concern.Testing
Fixtures in this module start with an empty cookie jar, which is why a full gate stack — review, readiness audit, Electron QA, CI — previously passed a session-erasing defect.
browser-cookie-import-scope.test.ts(new) uses a populated jar holding 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 fail against pre-fix source (verified by reverting only the fix's source files and re-running): case 3 comes back with 2 staged rows where 3 are expected — the unrelated site's row missing from the restart image.
The real-Electron partition test now seeds both an in-scope stale cookie (still removed) and an out-of-scope live one (now survives), so the behaviour is proven against a real Electron cookie jar, not only mocks. That expectation was mutation-checked to confirm the fixture genuinely runs.
Existing tests that only pinned the bulk-
clearDatapath were rewritten to pin the per-coordinate removal, and two cases that had become vacuous were re-seeded: one forced its rejection on a domain the import never covered (so nothing entered the removal plan at all). The STA-4170 mid-clear-arrival hooks moved fromclearDatatosnapshotClearIdentities— the same window — and were mutation-verified to still go red.src/main/browser: 72 files, 773 tests, all passing. Typecheck and oxlint clean.Rebased onto #15095
This branch was rebased after #15095 (serialize cookie imports per partition) landed. That PR re-indented the whole native import inside a per-partition lock, so the textual conflict was large and mostly indentation. Rather than resolve it line by line,
browser-cookie-import.tswas reset to main's version and the five edits above re-applied on top —git diff origin/mainfor that file is now exactly those edits, andwithCookieMutationLock/acquireCookieMutationLock/mutationLockOwnerare untouched. The scoped staged-image delete sits inside the sameBEGIN/COMMITit did before.#15095's new native concurrency detector read "has the second import started clearing yet?" off
clearDatacall counts. Removing the bulkclearDatapath takes that signal away, so the assertion no longer measured anything. It is re-anchored on the removals themselves —remove:old-apresent whileremove:old-bis absent — which distinguishes "the first import cleared" from "the second import cleared" in a way a call count could not, and the completed run pins the exact removal sequence (which incidentally records that each import now clears only its own domain).Its seeded jar 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 in disguise — the clear removes nothing and every assertion passes vacuously.
Mutation-checked: with the per-partition lock removed, that detector still fails. #15095's protection is intact.