Skip to content

reland(browser): route every cookie-import write through CDP identities, and never clear what it will not write back - #15030

Merged
brennanb2025 merged 16 commits into
mainfrom
brennanb2025/sta-4300-reland-cdp-writes
Aug 17, 2026
Merged

brennanb2025 merged 16 commits into
mainfrom
brennanb2025/sta-4300-reland-cdp-writes

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2771 $\color{#cf222e}{\Huge{\mathbf{−}}}$​56 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2715
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​942 $\color{#cf222e}{\Huge{\mathbf{−}}}$​255 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​687

ELI5

Electron's cookies.set() silently throws away a cookie's "which site was I embedded under" tag. So importing a partitioned (CHIPS) cookie quietly downgraded it into a different cookie the site can't read — and the import said "success".

The first attempt at this fix shipped and was reverted 47 minutes later, because it cleared the whole cookie jar and then wrote back only part of it, erasing working logins. This reland fixes the original bug and that one: if any cookie in a site's family can't be written faithfully, the whole family is left completely alone — not written, and not deleted.

What Changed

Reverts the revert 3c8410d927 (#14942) to restore the reviewed #14729 tree, then fixes the defect that caused it in separate, legible commits:

  1. registrableFamily() — one definition of "cookie family", used by every consumer of the skip set.
  2. planImportWrites() — decides every cookie's fate before any mutation. Two passes, because family-atomic skip is a property of the whole input.
  3. Path A — the removal scope and the write set are now literally the same array.
  4. Path B — the row loop splits into scan and emit; nothing is emitted until the plan exists.
  5. The clear — removeTransplantableCookies takes preserveFamilies and never submits a preserved coordinate to a removal or a restore.

The shipped defect, exactly:

decryptedCookies.push({ ..., partition })   // write set built HERE
if (partition.status === 'unreadable') { ... continue }   // guard applied AFTER

…followed by a jar-wide clear. The mutation set was the whole jar; the write set was a strict subset of it.

Two deliberate behaviour changes, stated rather than discovered later:

  • A skip-bearing import gets no staged cold-restart image. A staged image is a whole-database replacement on next start, so it cannot express "preserve this family"; main's existing restart-fallback-unavailable warning already reports the degradation.
  • A skip-bearing clear does not use bulk clearData. Its own contract admits a rejection may already have emptied part of the jar, and a preserved family is deliberately absent from the snapshot, so a partial delete then a rejection would destroy it with nothing able to restore it. The ordinary no-skip import keeps today's single clearData call unchanged.

Why

cookies.set() cannot express partitionKey. That one API boundary produced four P0s (STA-4013 → 4061 → 4090 → 4170). Routing writes through CDP identities is the root fix; the invariant added here is what makes it safe:

Never remove what you will not write back because its partition could not be read.

Linked Issue

STA-4300

Visual Proof

N/A — main-process cookie-import logic with no UI change. Behaviour is pinned by a real-Electron test that is red against main and green here, on both write paths. Electron QA evidence is being attached separately.

Testing

  • pnpm vitest run --config config/vitest.config.ts src/main/browser — 71 files, 740 tests, green
  • pnpm typecheck clean; oxlint clean (verified alive by injecting a violation — it is silent when clean); oxfmt --check clean; max-lines ratchet OK, no max-lines disable added
  • Real Electron, both paths: browser-cookie-import-partition-reland.electron.test.ts. Verified RED against main's product code and GREEN with the fix by reverting and re-running, not by assuming.

Mutation proofs (each broken deliberately, then reverted):

Mutation Result
IP check before normalisation in registrableFamily 5 alternate-spelling cases red, and only those
two-pass planner collapsed to a per-row guard readable-before-unreadable red, unreadable-before-readable green — the predicted asymmetry
drop the preserved-family filter from the clear 6 of 8 populated-jar cases red
use bulk clearData while preserving 6 of 8 red, including the erasure case itself

The populated-jar suite is the point. Every pre-existing end-to-end fixture in this module starts with cookies.get returning [], and against an empty jar "clear then write all" and "clear then write some" are indistinguishable. That is why the original defect passed code review, a readiness audit, Electron QA and full CI. The new fixtures start populated.

Platforms: macOS tested locally. Main-process only — no mobile, SSH, or Windows/WSL surface (no platform-specific paths, shells, or transports touched).

  • I manually tested these changes locally
  • Automated tests added/updated

AI Disclosure

Review

#14683 liveness. This reland conflicts with #14683 (886dec1d2a, merged hours earlier) in browser-cookie-import.ts. Both conflict hunks are keep-both. Its two suites still pass (13/13); its session double gains getStoragePath, and its positive-write assertion moves from cookies.set to the CDP identity store — adapted, not weakened, and now strictly stronger because it also asserts cookies.set carries no imported user data. Every decryption assertion is untouched.

Scope call for the merge decision. The revert restores one change that is not a CDP-write fix: targetPartition is derived from targetSession.getStoragePath() rather than accepted from the caller. It arrives with the revert and removing it means extra hand-written surgery on the reviewed tree, so it is kept — but flagged here rather than buried. Trivially removable as a follow-up if you'd rather it land separately.

Concurrency split out — now #15095 (STA-4601). An earlier revision of this branch also serialized cookie imports per partition. That is a pre-existing defect independent of this reland, so at Brennan's direction it moved to its own PR against its own ticket, and this PR is scoped to partition preservation only. The net diff here contains no locking change.

Known limitation, disclosed rather than half-fixed. The pre-existing staged-image/replay subsystem has defects this PR deliberately does not touch: a crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. (The third — concurrent imports — is now #15095.) This PR's guarantee is therefore bounded to this import's own mutations: it never removes a preserved coordinate. It does not promise immunity from a file-level replay. One case becomes newly reachable (skip + write rejection + a silently-failed prior-image clear + restart), which is stated rather than folded into "unchanged".

Agent skill upstream boundary

  • Not applicable

Notes

  • Security: narrows caller-controlled input (getStoragePath derivation); no new SQL, no string-interpolated queries, no new IPC surface.
  • Backwards compatibility: partitionSkippedCookies is an optional summary field gated by an explicit supportsPartitionSkippedCookies capability; a client that cannot render the skip fails the import before any mutation rather than reporting a partial import as success. Follows docs/reference/remote-wire-compatibility.md.
  • Performance: a skip-bearing import trades one clearData for a per-cookie removal pass, already bounded by COOKIE_CLEAR_CONCURRENCY. The common no-skip path is unchanged.
  • Cross-platform / SSH / mobile: no platform-specific code paths, no mobile protocol or transport surface.

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

Reverts the revert 3c8410d (#14942) to restore the reviewed bf6dc6f
tree. The defect that caused that revert is NOT fixed by this commit — it is
fixed in the commits that follow, so the delta a reviewer must scrutinise
stays small instead of hiding inside a 2000-line re-add.

Conflict resolutions, all keep-both:
- browser-cookie-import.ts: two hunks around the zero-import early return.
  #14683's undecryptable warning and decryptedCookies.length === 0 condition
  are kept alongside the reland's old-client gate and partitionSkippedCookies.
  The old-client gate stays above the early return, and so above any mutation.
- en.json: both string sets (#14683's undecryptable copy and partitionSkipped).
- crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket.

getStoragePath, and its positive-write assertion moves from cookies.set to the
CDP identity store — adapted, not weakened, and now strictly stronger because
it also asserts cookies.set carries no imported user data. Every decryption
assertion is untouched.
STA-4300, change 1 of the reland fixes. No behaviour change yet — this only
adds the helper the later commits derive every skip scope from.

Deriving "family" inline in several places is what let the removal scope and
the write set disagree in STA-4090 and STA-4170, so there is exactly one.

The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string.
psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain
is '0.1' — and Chromium accepts many spellings of one address. new URL() inside
normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and
a trailing dot to a dotted quad first, so isIP() then catches all of them.
Mutation-proved: moving the check ahead of normalisation reddens the five
alternate-spelling cases and nothing else.

Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the
value falls through to psl, which throws, which returns the host — the right
answer for the wrong reason.

Returns null for a bare public suffix: naming `com` as a family would preserve
an entire TLD from removal and silently turn an import into a no-op.
STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and
every removal scope can derive from one value instead of being computed twice.
Not yet wired into the import paths; that is the next commits.

TWO passes, and the second is not optional. Family-atomic skip is a property of
the whole input: with a readable mixed.example row BEFORE an unreadable
sub.mixed.example row, a per-row guard emits the readable one before anything
knows the family will be skipped. Pass 1 classifies and collects the skipped
families; pass 2 re-filters the provisional writes.

Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you
go): the readable-before-unreadable case goes red and the unreadable-before-
readable case still passes. That asymmetry is why both orders are tested and
why only the first is the named detector.

Family closure is at the registrable boundary because that is the boundary the
removal scope actually expands to: importedDomainScopes turns an imported
mixed.example into descendant roots, so a readable apex cookie drags a skipped
subdomain's live session into the removal scope (STA-4300 §2b).

hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we
cannot name is one we cannot exclude from the removal plan, and clearing a
family we cannot protect is the P0 this ticket exists to stop — so the caller
refuses before mutating rather than proceeding and hoping.
…4300 §2b)

Change 3. importValidatedCookies now plans before it opens the jar, and the
replacement scope and the write set are the SAME array.

bf6dc6f filtered replacementDomains per exact cookie
(partition.status !== 'unreadable'). That is not sufficient:
replaceCookiesForImportedDomains expands each imported domain into its
descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example
into the removal scope — and a skipped cookie living there has its session
removed with nothing written back. Same erasure as the P0, different path.

plan.writes is family-closed, and because path A passes the very same array to
replaceCookiesForImportedDomains and to writeImportedCookies, the two sets
cannot drift apart. That is stronger than keeping them in sync: there is only
one set.

Also here, both before any mutation:
- an unrepresentable skip (registrableFamily → null) refuses the import, because
  a family we cannot name is one we cannot exclude from the removal scope;
- the old-client gate now keys off plan.skips rather than re-deriving the
  condition.

Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the
unreadable rows plus their family-suppressed siblings — added in exactly once,
so totalCookies === importedCookies + skippedCookies keeps holding. Counting it
separately is how a summary silently stops adding up.

Full src/main/browser suite: 69 files, 729 tests, green.
… (STA-4300)

Change 4 — this is the commit that fixes the shipped P0.

bf6dc6f did:
    decryptedCookies.push({ ..., partition })   // write set built HERE
    if (partition.status === 'unreadable') { ... continue }   // guard AFTER

so an unreadable row discovered late could not retract a sibling already
emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation
set was the whole jar and the write set a strict subset of it, which is how a
mixed readable/unreadable source emptied a populated jar and repopulated only
part of it.

Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies,
not domainSet, not a staging row, not the imported count. Between scan and emit,
planImportWrites closes the skip over whole registrable families, and emit walks
the plan. Each scanned candidate carries its raw source row because
buildChromiumCookieInsertParams needs it; a record holding only the derived
fields compiles and then silently cannot stage.

Also between scan and emit, both before any mutation:
- an unrepresentable skip refuses the import;
- any skipped family calls disableStaging. A staged image is a whole-database
  replacement on the next start, so it cannot express "preserve this family";
  main's existing memoryFailed arm then reports restart-fallback-unavailable.

Test contract change, deliberately stronger: "never stages a partitioned row
whose ancestor bit is unreadable" asserted that an image WAS registered and
merely omitted the row. That image would still have erased the preserved family
on replay. It now asserts no image is registered at all — plus a new paired case
proving a no-skip import still stages, so "disable on skip" cannot be
implemented as "disable always" unnoticed.

Honest note on detection: reverting the emit filter currently reddens only the
staging assertion, because every end-to-end fixture in this module still starts
with an EMPTY jar — where clear-then-write-all and clear-then-write-some are
indistinguishable. That is the blind spot that let this ship. The populated-jar
suite in the next commit is what actually detects the erasure.

Full src/main/browser: 69 files, 730 tests, green.
…-4300 I2)

Change 5, and the one that makes preservation observable.

removeTransplantableCookies takes preserveFamilies. removableCookieEntries
filters those families out, which keeps them out of the removal plan AND — since
the CDP snapshot is taken from that same list — out of the restore set, so a
preserved coordinate is never submitted to any mutation at all.

When anything is preserved, the bulk clearData path is not used. clearData
removes everything outside excludeOrigins, and its own comment concedes a
rejection may already have emptied part of the jar; a preserved family is
deliberately absent from the snapshot, so a partial delete followed by a
rejection would destroy it with no identity able to restore it. Handing a
dynamically derived preserve list to that primitive cannot be made safe, so a
skip-bearing clear runs the frozen per-coordinate plan — which already excludes
those families — as its primary path instead. Nothing is preserved on an
ordinary import, so that path keeps today's single clearData call unchanged.

New populated-jar suite. Every end-to-end fixture in this module starts with
cookies.get returning [], and against an empty jar "clear then write all" and
"clear then write some" are indistinguishable — which is why four independent
gates missed the P0. These fixtures start populated.

Mutation-proved, and this is the first detector in the change set that catches
the actual erasure rather than a proxy:
- drop the preserved-family filter          → 6 of 8 red
- use bulk clearData while preserving       → 6 of 8 red, including
  "leaves a preserved family untouched", which is the erasure itself

IPv4-literal and single-label host families are covered explicitly: psl reads
127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to
match the preserve set and erase the live loopback session.

Full src/main/browser: 70 files, 738 tests, green.
…aths

Ports the pre-implementation reproduction into the PR. Verified RED against
main's product code and GREEN with the fix, on both paths — I re-ran it both
ways rather than assuming.

Two assertions are INVERTED rather than deleted, and both are now stronger. The
repro proved the defect by showing cookies.set was called WITHOUT a partitionKey;
after the reland the import write path does not touch cookies.set for user data
at all, so seeing the imported cookie there is itself the regression. The
fixture's internal guard is inverted the same way.

Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero
importedCookies, the importer reaching its terminal step, the source really
carrying its partition fields, and a CONTROL cookie written via CDP *with* a
partitionKey and read back with it — so "partitionKey absent" cannot be confused
with "the oracle cannot see partitions". electronVersion proves Electron ran.

Fixture correction worth recording, because the original reproduction was
invalid on this path and I did not catch it on first read: readJsonCookiePartition
reads a NESTED partitionKey object, but the fixture wrote topLevelSite and
hasCrossSiteAncestor at the entry's top level, where the importer never looks.
The file/paste case therefore failed on main for a fixture-shape reason rather
than for the defect — and its own non-vacuity check validated what the fixture
wrote instead of what the parser reads, which is exactly how a check that looks
rigorous proves nothing. Only the native half was ever a real reproduction.

Partition keys use a schemeful SITE, not an origin: Chromium canonicalises
https://app.example.com to https://example.com, measured via CDP.
@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
📝 Walkthrough

Walkthrough

The change adds partition metadata readers for Chromium, Firefox, and JSON cookies. Import planning skips unreadable partition families before mutation and preserves readable partition keys during writes. Cookie clearing can preserve registrable families. CDP identity writes are shared by import and restoration, with validation and aggregate failure handling. Chromium storage paths come from Electron. Runtime and renderer layers report partition-skipped counts and display localized warnings. Tests cover unit, mock-based, concurrency, and Electron integration paths.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.76% 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 identifies the main changes: routing cookie writes through CDP identities and preserving cookies that cannot be written back.
Description check ✅ Passed The description is detailed and covers the required sections, linked issue, testing, compatibility, and scope, with only minor checklist omissions.
✨ 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.

Actionable comments posted: 2

🧹 Nitpick comments (6)
src/main/browser/browser-cookie-clear-preserve.test.ts (1)

115-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a rejection-path test for preserved families.

The suite pins the snapshot and removal plans. It does not exercise a failing remove while a family is preserved. That path calls restoreClearedCookies, which replays the snapshot through restoreClearIdentities. A regression that put a preserved coordinate back into the snapshot would still pass every current test, because no test makes the restore run.

Add a case where removeMock rejects for the non-preserved cookie and assert that the restored identities contain no preserved coordinate.

src/main/browser/browser-cookie-import.ts (1)

1891-1949: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm the skipped accounting for a row that is both undecryptable and partition-skipped.

The decrypt-failure branch at Line 1869 increments skipped and continues, so the row never reaches the plannedSourceRows check at Line 1893. partitionSkipped still counts it because nativePlan.skips is computed before decryption. The summary then reports that one row inside both partitionSkippedCookies and the cookies-undecryptable warning.

The identity totalCookies === importedCookies + skippedCookies still holds, and browser-cookie-import-undecryptable.test.ts pins this exact case. State the overlap in the comment so a later reader does not treat the double attribution as a bug and "fix" it by subtracting.

src/main/browser/browser-cookie-import-partition-fidelity.test.ts (1)

293-357: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reset the write mock between the two imports in this test.

Line 325 arms mockRejectedValueOnce before the blocked import. Line 336 asserts the blocked import performed no write, so the queued rejection survives into the second import at Line 342. The test is correct today only because of that ordering, and the call-count assertion at Line 346 counts calls from both imports.

Reset the mock after the blocked assertions and re-arm the rejection. The second import's assertions then depend on one import only.

♻️ Proposed change
     expect(blockedSession.cookies.remove).not.toHaveBeenCalled()
 
+    cookieWriteMock.mockReset()
+    cookieWriteMock.mockRejectedValueOnce(new Error('plain cookie needs restart'))
     const result = await importCookiesFromBrowser(chromeBrowser(sourceCookiesPath), 'persist:test')
src/main/browser/browser-cookie-clear-store.ts (1)

140-160: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider bounding the hidden-window load.

leaseHiddenCookieDebugger awaits window.loadURL with no time limit. Every cookie write now depends on this attach step. If the renderer never finishes creating, attach() never settles and the caller waits without an error.

A timeout that destroys the window and rejects would keep the failure observable.

♻️ Optional bound on the load step
 async function leaseHiddenCookieDebugger(targetSession: Session): Promise<CookieClearSession> {
   const window = openHiddenCookieWindow(targetSession)
   try {
-    await window.loadURL('data:text/html,<!doctype html><title>cookie-clear</title>')
+    await Promise.race([
+      window.loadURL('data:text/html,<!doctype html><title>cookie-clear</title>'),
+      new Promise<never>((_, reject) =>
+        setTimeout(
+          () => reject(new Error('Could not attach to the cookie session for an atomic clear')),
+          10_000
+        ).unref()
+      )
+    ])
src/main/browser/browser-cookie-import-partition-reland.electron.test.ts (1)

386-398: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Three new Electron fixtures depend on xvfb-run on Linux without a guard. Each fixture selects xvfb-run as the executable when process.platform === 'linux'. If the binary is not installed, spawnSync returns an error and the run fails with an opaque message instead of naming the missing dependency. The shared root cause is one unverified environment assumption repeated in three files.

  • src/main/browser/browser-cookie-import-partition-reland.electron.test.ts#L386-L398: confirm the Electron test job provisions xvfb, or skip the suite when xvfb-run is absent.
  • src/main/browser/browser-cookie-import-partition-success.electron.test.ts#L209-L218: apply the same guard to this fixture's spawnSync launch.
  • src/main/browser/browser-cookie-import-validated-partition.electron.test.ts#L187-L192: apply the same guard to this fixture's spawnSync launch.

Extracting the shared launch logic into one Electron fixture-launch module would keep the guard in a single place.

src/main/runtime/rpc/methods/browser-schemas.ts (1)

152-152: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Accept an explicit boolean capability value.

z.literal(true).optional() rejects false before the handler runs. Use z.boolean().optional() and change the runtime parameter type to supportsPartitionSkippedCookies?: boolean.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 33cc6210-c0b9-4698-9653-44fc15b4a025

📥 Commits

Reviewing files that changed from the base of the PR and between 81d7f9b and 4e13947.

📒 Files selected for processing (32)
  • src/main/browser/browser-cookie-clear-preserve.test.ts
  • src/main/browser/browser-cookie-clear-store-lifecycle.test.ts
  • src/main/browser/browser-cookie-clear-store.test.ts
  • src/main/browser/browser-cookie-clear-store.ts
  • src/main/browser/browser-cookie-identity-restore.ts
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-google-exclusion.test.ts
  • src/main/browser/browser-cookie-import-partition-fidelity.test.ts
  • src/main/browser/browser-cookie-import-partition-reland.electron.test.ts
  • src/main/browser/browser-cookie-import-partition-success.electron.test.ts
  • src/main/browser/browser-cookie-import-plan-writes.test.ts
  • src/main/browser/browser-cookie-import-policy.ts
  • src/main/browser/browser-cookie-import-replacement.test.ts
  • src/main/browser/browser-cookie-import-test-database.ts
  • src/main/browser/browser-cookie-import-undecryptable.test.ts
  • src/main/browser/browser-cookie-import-validated-partition.electron.test.ts
  • src/main/browser/browser-cookie-import-write.test.ts
  • src/main/browser/browser-cookie-import-write.ts
  • src/main/browser/browser-cookie-import.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-registrable-family.test.ts
  • src/main/browser/browser-cookie-source-partition.test.ts
  • src/main/browser/browser-cookie-source-partition.ts
  • src/main/runtime/orca-runtime-browser.ts
  • src/main/runtime/rpc/methods/browser-schemas.ts
  • src/main/runtime/rpc/methods/browser.test.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/lib/browser-cookie-import-toast.test.ts
  • src/renderer/src/lib/browser-cookie-import-toast.ts
  • src/renderer/src/store/slices/browser-session-host-selection.test.ts
  • src/renderer/src/store/slices/browser.ts
  • src/shared/browser-workspace-types.ts

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

Comment on lines 818 to 823
return importValidatedCookies(
validated,
parsed.length,
targetPartition,
cookieImportTarget(targetPartition),
'replace-imported-domains'
)

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Locate importCookiesFromFile callers and any capability plumbing.
rg -nP --type=ts -C6 '\bimportCookiesFromFile\s*\('
rg -nP --type=ts -C4 'supportsPartitionSkippedCookies|canReportPartitionSkippedCookies'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
fd -i 'browser-cookie-import|cookie' src | head -80
printf '%s\n' '--- importCookiesFromFile references ---'
rg -n -C5 '\bimportCookiesFromFile\b' src .
printf '%s\n' '--- capability identifiers ---'
rg -n -C4 'supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' src .

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
file=$(fd -i -t f 'browser-cookie-import' . | head -1)
printf '%s\n' "--- $file: relevant definitions ---"
rg -n -C12 'importCookiesFromFile|importValidatedCookies|readJsonCookiePartition|canReportPartitionSkippedCookies' "$file"
printf '%s\n' '--- all callers and RPC handlers ---'
rg -n -C8 '\bimportCookiesFromFile\s*\(' .

Repository: stablyai/orca

Length of output: 247


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- tracked source files ---'
git ls-files | rg '(^|/)(browser-cookie-import|.*cookie.*)\.(ts|tsx|js|jsx)$' | head -100
printf '%s\n' '--- references across tracked files ---'
git grep -n -C6 -E 'importCookiesFromFile|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' -- '*.ts' '*.tsx' '*.js' '*.jsx' || true

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
grep -RIn -C6 -E 'importCookiesFromFile|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' . --exclude-dir=.git --exclude-dir=node_modules || true

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- src/main/browser/browser-cookie-import.ts ---'
sed -n '620,675p;750,835p' src/main/browser/browser-cookie-import.ts
printf '%s\n' '--- src/main/ipc/browser-session-profile-ipc.ts ---'
sed -n '1,105p' src/main/ipc/browser-session-profile-ipc.ts
printf '%s\n' '--- file-import RPC schema and handler references ---'
rg -n -C8 'profileImportFromFile|importFromFile|ProfileImportFromBrowser|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/main src/shared src/renderer

Repository: stablyai/orca

Length of output: 38478


🏁 Script executed:

#!/bin/bash
set -e
sed -n '620,675p;750,835p' src/main/browser/browser-cookie-import.ts
sed -n '1,105p' src/main/ipc/browser-session-profile-ipc.ts
rg -n -C8 'profileImportFromFile|importFromFile|ProfileImportFromBrowser|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/main src/shared src/renderer

Repository: stablyai/orca

Length of output: 38322


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- browser:session:importCookies callers and argument shapes ---'
rg -n -C10 "'browser:session:importCookies'|browser:session:importCookies|importCookies\(" src/main src/renderer src/shared
printf '%s\n' '--- result rendering and capability declarations ---'
rg -n -C8 'partitionSkippedCookies|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/renderer/src src/main/ipc src/shared | head -240

Repository: stablyai/orca

Length of output: 12274


🏁 Script executed:

#!/bin/bash
set -e
rg -n -C10 "'browser:session:importCookies'|browser:session:importCookies|importCookies\(" src/main src/renderer src/shared
rg -n -C8 'partitionSkippedCookies|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/renderer/src src/main/ipc src/shared | head -240

Repository: stablyai/orca

Length of output: 12155


Forward the file-import capability through the IPC path.

Extend importCookiesFromFile with CookieImportOptions and pass it to importValidatedCookies. Extend browser:session:importCookies arguments with supportsPartitionSkippedCookies, then pass canReportPartitionSkippedCookies: args.supportsPartitionSkippedCookies === true. Otherwise, unreadable JSON partitions can produce ok: true with unreported skipped cookies.

Comment on lines +127 to +130
'auto.lib.browser.cookie.import.toast.partitionSkipped',
'{{value0}} cookies were not imported because their site-partition could not be read. Sign in to those sites again in Orca.',
{ value0: summary.partitionSkippedCookies }
),

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Provide singular and plural warning text.

If partitionSkippedCookies is 1 and the translation key is unavailable for the active locale, this fallback displays 1 cookies. Define singular and plural translation variants and update the test to cover both forms.

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73f264ee-85ed-48c5-93d5-e1e41a664c82

📥 Commits

Reviewing files that changed from the base of the PR and between 4e13947 and ce55ed8.

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

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/browser/browser-cookie-clear-store.ts (1)

64-74: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Treat null partition keys as unpartitioned.

CdpCookie.partitionKey allows null. The current check does not. A null value reaches normalization and throws, which aborts atomic cookie snapshots. Return undefined for both undefined and null, and add a regression test.

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

109-112: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the multi-line implementation comments.

Keep the invariants. Reduce each Why block to a brief, non-obvious 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.”

Also applies to: 190-216

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 059195d7-d3dd-4910-8e11-46386097253a

📥 Commits

Reviewing files that changed from the base of the PR and between 23a375b and f7c27b7.

📒 Files selected for processing (8)
  • src/main/browser/browser-cookie-clear-store.test.ts
  • src/main/browser/browser-cookie-clear-store.ts
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-concurrency.test.ts
  • src/main/browser/browser-cookie-import-partition-fidelity.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-source-partition.test.ts
  • src/main/browser/browser-cookie-source-partition.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/browser/browser-cookie-source-partition.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

Copy link
Copy Markdown
Contributor Author

Electron QA — STA-4300 cookie-import partition preservation

Ran against a dev build of this branch, not another worktree.

  • CDP: 127.0.0.1:9333
  • Process: .../sta4300-qa-15030/out/electron-dev/d48dc4b85900/Orca: qa-sta-4300.app/Contents/MacOS/Electron . --remote-debugging-port=9333 (PID 94864)
  • Identity: window.api.app.getIdentity() → devLabel: "sta4300-qa-15030 @ qa/sta-4300", devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta4300-qa-15030, devBranch: qa/sta-4300
  • Renderer: http://localhost:5173/
  • Isolated ORCA_DEV_USER_DATA_PATH so this did not touch the interactive app profile

(1) Ordinary import — proved

A real Import Cookies → From Google Chrome → Brennan run completed in Settings → Browser. Store summary: totalCookies: 51, importedCookies: 32, skippedCookies: 19 (all Google skips), partitionSkippedCookies absent, domains github.com, nordaccount.com, youtube.com, auth.nordaccount.com.

Before — empty Default profile, no cookies imported.

01-before-import-empty-profile.png

Import menu on the real Settings surface (Chrome / Comet / Firefox / Safari / From File…).

02-import-menu-open.png

After — profile source updated to Google Chrome (Brennan).

04-after-chrome-import-profile.png

Same import reporting on screen (Google-skip warning toast; accessibility tree also had Imported 32 cookies from Google Chrome … into Default.). This is a successful import with the existing Google-skip warning, not a failure.

05-ordinary-import-success-toast.png

(2) New partitionSkipped string — proved

A skip-bearing From File… import was driven through the same Settings menu. Source JSON had one unreadable-partition cookie on .github.com (partitionKey with topLevelSite only) plus one readable cookie on .plain.example. The live toast rendered the new locale string:

1 cookies were not imported because their site-partition could not be read. Sign in to those sites again in Orca.

Store summary after this run: importedCookies: 1, skippedCookies: 1, partitionSkippedCookies: 1, domains: ["plain.example"]. Profile source flipped to File.

07-partition-skipped-toast.png

(3) Preserved session — proved in the live cookie jar

Before the skip import I seeded orca-qa-sta4300-seed=must-survive on .github.com in persist:orca-browser (the Default profile partition). After the skip-bearing import, session.fromPartition('persist:orca-browser').cookies.get({}) still had:

  • github.com (7, untouched family): _gh_sess, _octo, cpu_bucket, logged_in, orca-qa-sta4300-seed=must-survive, preferred_color_mode, tz
  • plain.example (written): plain=ok
  • youtube.com / nordaccount.com still present — the jar was not cleared

The old reverted behavior would have replaced/erased the github.com family while reporting success. This run neither wrote nor removed that family.

The panel below is QA inspection drawn on the running window, populated from that live cookies.get result — it is not a product cookie viewer.

08-after-skip-seed-survived.png

What I could not verify

  • I did not open an Orca browser tab to github.com and show a logged-in page after the skip. This QA profile has no workspace, so there was no guest browser tab to load. Survival is from the live Electron cookie jar, not from a site rendering a session.
  • From File… uses a native open-dialog. CDP cannot drive that picker. For the skip case I patched dialog.showOpenDialog in this process only so the real Settings → From File… path ran against the crafted JSON, then restored the original dialog. I did not use OS-level mouse/keyboard automation.
  • The green “Imported 32 cookies…” success toast and the Google-skip toast stacked; the screenshot for (1) shows the Google-skip toast. The 32-cookie success string was present in the notification region at the same moment.

Method notes

Playwright CDP only (playwright-cli -s=sta4300qa). Identity checked before each evidence capture. Isolated user-data directory. Native file dialog hook restored after the skip import.

Reverts only the concurrency-serialization half of f7c27b7 so #15030 stays
scoped to the STA-4300 reland. That commit mixed two concerns; this removes one
of them and keeps the other.

REMOVED (moves to STA-4601, a separate pre-existing P1):
- acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map;
  clear.ts goes back to withCookieClearLock
- the import-wide lock in path A (mutationOwner on the target, acquire/release
  around replace + writes + rollback)
- the widened lock around path B's clear + memory writes
- browser-cookie-import-concurrency.test.ts

KEPT (genuinely STA-4300 scope, not concurrency):
- partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot.
  An opaque partition key cannot be represented faithfully, so it reads as
  unreadable and its family is preserved — exactly the rule this ticket adds.
  194e57a's refinement of that shape stays too.

The concurrent-import interleaving is real and reachable (nothing serialises
imports per partition, and the clear lock is released before the memory writes),
but it predates this change and is not caused or worsened by it. It gets its own
PR and its own review rather than riding a P0 reland whose history is that every
additional fix introduced a new defect.

src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on
both write paths and still goes red against main's product code.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Populated-jar Electron QA follow-up — STA-4300

This is the populated-jar follow-up to the earlier empty-profile Electron QA on this PR. That run imported Chrome cookies into an empty Default profile and never loaded a page. This run exists because that is the exact blind spot that let #14729 pass review, readiness, Electron QA, and CI and still get reverted for erasing user sessions.

Do not merge on the strength of the earlier empty-profile comment.

Instance (CDP ownership verified)

  • Isolated ORCA_DEV_USER_DATA_PATH (did not touch the interactive profile)
  • CDP 127.0.0.1:9333
  • window.api.app.getIdentity() → devLabel: "sta4300-realqa-15030", devBranch: "brennanb2025/sta4300-realqa-15030", devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta4300-realqa-15030, SHA 50d5fb4e32
  • Target partition: Default persist:orca-browser

RUN A — populated-jar survival: ERASED

  1. Established a real working logged-in session in Default: signed in at https://the-internet.herokuapp.com/login as tomsmith. The page rendered You logged into a secure area! at /secure.

03-run-a-orca-window-signed-in.png

02-run-a-signed-in-secure-area.png

  1. Imported cookies through the real Settings surface into that same Default partition: Import Cookies → From Google Chrome → Brennan. This is the same skip-bearing source as the empty-profile run.

05-import-menu-open.png

06-chrome-profiles-submenu.png

Store summary after import: totalCookies: 51, importedCookies: 32, skippedCookies: 19, googleCookiesSkipped: 19, domains auth.nordaccount.com, github.com, nordaccount.com, youtube.com. Profile source updated to Google Chrome (Brennan).

07-settings-after-import.png

  1. Reloaded / navigated to /secure in the same partition. The site redirected to /login and rendered You must login to view the secure area!

09-after-import-address-bar-login.png

  1. A fresh Default-profile tab opened directly to /secure also landed on /login. This is not a stale-tab artifact.

11-run-a-fresh-tab-secure-erased.png

the-internet.herokuapp.com is not in the imported write set. A family-preserve import should have left that session alone. It did not. Cookie counts and toasts are not the evidence — the signed-in page became a login page.

Verdict A: ERASED


RUN B — imported-session authenticity

Same Chrome Brennan import as RUN A. Then loaded the imported domains in Orca.

YouTube — SURVIVED. https://www.youtube.com/ rendered signed-in chrome (avatar, Create, Notifications, You). The account menu identified Brennan Benson / [email protected] and offered Sign out. Imported YouTube cookies produced a working session, not merely a present jar attribute.

16-run-b-youtube-orca-window.png

GitHub — NOT PROVEN. Rendered the logged-out marketing homepage (Sign in / Sign up). Chrome Brennan has _gh_sess and logged_in but no user_session. The source profile was not signed into GitHub, so this cannot prove or disprove partition-key survival.

15-run-b-github-orca-window.png

Nord Account — NOT PROVEN. https://my.nordaccount.com/ rendered Log in to Nord Account. Source Brennan does have session / sessions_bag cookies for nordaccount.com; that is not enough to claim the source session was still valid. Observed result: not signed-in.

17-run-b-nord-orca-window.png

Verdict B: YouTube SURVIVED. GitHub NOT PROVEN (source had no live user_session). Nord NOT PROVEN (rendered login).


Why this matters

The earlier empty-profile QA could not have seen RUN A. Against an empty jar, clearing then writing back 32 cookies looks successful. Against a populated jar, the pre-existing session disappeared while imported YouTube cookies still authenticated. That is the original revert class: jar-level green and user-visible broken can coexist.

Did not merge.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Correction to the populated-jar QA above — RUN A's "ERASED" is not a defect in this PR

I wrote the brief for that QA run, and the pass criterion I set was wrong. Recording it here so nobody reads "ERASED" as a blocker on this PR.

I asked for: a pre-existing logged-in session must survive an import into the same partition. A cookie import in replace mode is designed to do the opposite.

On main today — without this PR — removeTransplantableCookies reads the entire jar:

const initialCookies = await store.get({})

and removes everything except the non-transplantable (Google) family, under the existing comment:

"clear stale cookies first; mixing them with the imported set makes sites reject the session. Non-transplantable families are exempt."

So a the-internet.herokuapp.com session that was not among the imported domains is cleared by design, on main, before and after this change. RUN A reproduced intended behaviour.

The missing piece was a control run. Without executing the same steps on main, an ERASED result cannot distinguish "this PR broke it" from "this has always happened." That omission is mine, not the QA's — the run itself was well executed, with CDP ownership verified and a genuine signed-in session established first.

What the populated-jar test should actually assert

The STA-4090 / STA-4170 failures were never about a successful import clearing unrelated cookies. They were about a failed or partial import leaving the jar cleared and not written back. The meaningful assertions are:

  1. After a failed / partially-failed import, pre-existing cookies are restored or never removed — the regression tests in this PR cover this, and it is the invariant it was built around.
  2. After a successful import, the imported session actually authenticates — RUN B proved this: imported YouTube rendered signed-in as a real account. That is the genuine positive signal from this QA, and it is what the empty-profile run could not show.

Standing

RUN B (SURVIVED) stands as real evidence. RUN A should be read as "import clears the target jar, as designed," not as a finding against this PR. The earlier note in this thread to not merge on the strength of the empty-profile comment alone still holds — but RUN A is not the reason.

Separately worth knowing, and out of scope here: importing cookies silently signs the user out of every unrelated site in that partition. That is pre-existing behaviour, not introduced by this PR, and may deserve its own ticket.

@brennanb2025
brennanb2025 merged commit 32ee3b0 into main Aug 17, 2026
45 checks passed
brennanb2025 added a commit that referenced this pull request Aug 18, 2026
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 added a commit that referenced this pull request Aug 18, 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 #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
…es, and never clear what it will not write back (stablyai#15030)

* reland(browser): restore CDP-identity cookie-import writes (stablyai#14729)

Reverts the revert 3c8410d (stablyai#14942) to restore the reviewed bf6dc6f
tree. The defect that caused that revert is NOT fixed by this commit — it is
fixed in the commits that follow, so the delta a reviewer must scrutinise
stays small instead of hiding inside a 2000-line re-add.

Conflict resolutions, all keep-both:
- browser-cookie-import.ts: two hunks around the zero-import early return.
  stablyai#14683's undecryptable warning and decryptedCookies.length === 0 condition
  are kept alongside the reland's old-client gate and partitionSkippedCookies.
  The old-client gate stays above the early return, and so above any mutation.
- en.json: both string sets (stablyai#14683's undecryptable copy and partitionSkipped).
- crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket.

getStoragePath, and its positive-write assertion moves from cookies.set to the
CDP identity store — adapted, not weakened, and now strictly stronger because
it also asserts cookies.set carries no imported user data. Every decryption
assertion is untouched.

* fix(browser): add registrableFamily, one definition of a cookie family

STA-4300, change 1 of the reland fixes. No behaviour change yet — this only
adds the helper the later commits derive every skip scope from.

Deriving "family" inline in several places is what let the removal scope and
the write set disagree in STA-4090 and STA-4170, so there is exactly one.

The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string.
psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain
is '0.1' — and Chromium accepts many spellings of one address. new URL() inside
normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and
a trailing dot to a dotted quad first, so isIP() then catches all of them.
Mutation-proved: moving the check ahead of normalisation reddens the five
alternate-spelling cases and nothing else.

Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the
value falls through to psl, which throws, which returns the host — the right
answer for the wrong reason.

Returns null for a bare public suffix: naming `com` as a family would preserve
an entire TLD from removal and silently turn an import into a no-op.

* fix(browser): plan every cookie's fate before any jar mutation

STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and
every removal scope can derive from one value instead of being computed twice.
Not yet wired into the import paths; that is the next commits.

TWO passes, and the second is not optional. Family-atomic skip is a property of
the whole input: with a readable mixed.example row BEFORE an unreadable
sub.mixed.example row, a per-row guard emits the readable one before anything
knows the family will be skipped. Pass 1 classifies and collects the skipped
families; pass 2 re-filters the provisional writes.

Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you
go): the readable-before-unreadable case goes red and the unreadable-before-
readable case still passes. That asymmetry is why both orders are tested and
why only the first is the named detector.

Family closure is at the registrable boundary because that is the boundary the
removal scope actually expands to: importedDomainScopes turns an imported
mixed.example into descendant roots, so a readable apex cookie drags a skipped
subdomain's live session into the removal scope (STA-4300 §2b).

hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we
cannot name is one we cannot exclude from the removal plan, and clearing a
family we cannot protect is the P0 this ticket exists to stop — so the caller
refuses before mutating rather than proceeding and hoping.

* fix(browser): derive path A's removal scope from the write plan (STA-4300 §2b)

Change 3. importValidatedCookies now plans before it opens the jar, and the
replacement scope and the write set are the SAME array.

bf6dc6f filtered replacementDomains per exact cookie
(partition.status !== 'unreadable'). That is not sufficient:
replaceCookiesForImportedDomains expands each imported domain into its
descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example
into the removal scope — and a skipped cookie living there has its session
removed with nothing written back. Same erasure as the P0, different path.

plan.writes is family-closed, and because path A passes the very same array to
replaceCookiesForImportedDomains and to writeImportedCookies, the two sets
cannot drift apart. That is stronger than keeping them in sync: there is only
one set.

Also here, both before any mutation:
- an unrepresentable skip (registrableFamily → null) refuses the import, because
  a family we cannot name is one we cannot exclude from the removal scope;
- the old-client gate now keys off plan.skips rather than re-deriving the
  condition.

Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the
unreadable rows plus their family-suppressed siblings — added in exactly once,
so totalCookies === importedCookies + skippedCookies keeps holding. Counting it
separately is how a summary silently stops adding up.

Full src/main/browser suite: 69 files, 729 tests, green.

* fix(browser): split path B into scan and emit, and never stage a skip (STA-4300)

Change 4 — this is the commit that fixes the shipped P0.

bf6dc6f did:
    decryptedCookies.push({ ..., partition })   // write set built HERE
    if (partition.status === 'unreadable') { ... continue }   // guard AFTER

so an unreadable row discovered late could not retract a sibling already
emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation
set was the whole jar and the write set a strict subset of it, which is how a
mixed readable/unreadable source emptied a populated jar and repopulated only
part of it.

Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies,
not domainSet, not a staging row, not the imported count. Between scan and emit,
planImportWrites closes the skip over whole registrable families, and emit walks
the plan. Each scanned candidate carries its raw source row because
buildChromiumCookieInsertParams needs it; a record holding only the derived
fields compiles and then silently cannot stage.

Also between scan and emit, both before any mutation:
- an unrepresentable skip refuses the import;
- any skipped family calls disableStaging. A staged image is a whole-database
  replacement on the next start, so it cannot express "preserve this family";
  main's existing memoryFailed arm then reports restart-fallback-unavailable.

Test contract change, deliberately stronger: "never stages a partitioned row
whose ancestor bit is unreadable" asserted that an image WAS registered and
merely omitted the row. That image would still have erased the preserved family
on replay. It now asserts no image is registered at all — plus a new paired case
proving a no-skip import still stages, so "disable on skip" cannot be
implemented as "disable always" unnoticed.

Honest note on detection: reverting the emit filter currently reddens only the
staging assertion, because every end-to-end fixture in this module still starts
with an EMPTY jar — where clear-then-write-all and clear-then-write-some are
indistinguishable. That is the blind spot that let this ship. The populated-jar
suite in the next commit is what actually detects the erasure.

Full src/main/browser: 69 files, 730 tests, green.

* fix(browser): never remove a family the import declined to write (STA-4300 I2)

Change 5, and the one that makes preservation observable.

removeTransplantableCookies takes preserveFamilies. removableCookieEntries
filters those families out, which keeps them out of the removal plan AND — since
the CDP snapshot is taken from that same list — out of the restore set, so a
preserved coordinate is never submitted to any mutation at all.

When anything is preserved, the bulk clearData path is not used. clearData
removes everything outside excludeOrigins, and its own comment concedes a
rejection may already have emptied part of the jar; a preserved family is
deliberately absent from the snapshot, so a partial delete followed by a
rejection would destroy it with no identity able to restore it. Handing a
dynamically derived preserve list to that primitive cannot be made safe, so a
skip-bearing clear runs the frozen per-coordinate plan — which already excludes
those families — as its primary path instead. Nothing is preserved on an
ordinary import, so that path keeps today's single clearData call unchanged.

New populated-jar suite. Every end-to-end fixture in this module starts with
cookies.get returning [], and against an empty jar "clear then write all" and
"clear then write some" are indistinguishable — which is why four independent
gates missed the P0. These fixtures start populated.

Mutation-proved, and this is the first detector in the change set that catches
the actual erasure rather than a proxy:
- drop the preserved-family filter          → 6 of 8 red
- use bulk clearData while preserving       → 6 of 8 red, including
  "leaves a preserved family untouched", which is the erasure itself

IPv4-literal and single-label host families are covered explicitly: psl reads
127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to
match the preserve set and erase the live loopback session.

Full src/main/browser: 70 files, 738 tests, green.

* test(browser): pin STA-4300 end to end in real Electron, both write paths

Ports the pre-implementation reproduction into the PR. Verified RED against
main's product code and GREEN with the fix, on both paths — I re-ran it both
ways rather than assuming.

Two assertions are INVERTED rather than deleted, and both are now stronger. The
repro proved the defect by showing cookies.set was called WITHOUT a partitionKey;
after the reland the import write path does not touch cookies.set for user data
at all, so seeing the imported cookie there is itself the regression. The
fixture's internal guard is inverted the same way.

Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero
importedCookies, the importer reaching its terminal step, the source really
carrying its partition fields, and a CONTROL cookie written via CDP *with* a
partitionKey and read back with it — so "partitionKey absent" cannot be confused
with "the oracle cannot see partitions". electronVersion proves Electron ran.

Fixture correction worth recording, because the original reproduction was
invalid on this path and I did not catch it on first read: readJsonCookiePartition
reads a NESTED partitionKey object, but the fixture wrote topLevelSite and
hasCrossSiteAncestor at the entry's top level, where the importer never looks.
The file/paste case therefore failed on main for a fixture-shape reason rather
than for the defect — and its own non-vacuity check validated what the fixture
wrote instead of what the parser reads, which is exactly how a check that looks
rigorous proves nothing. Only the native half was ever a real reproduction.

Partition keys use a schemeful SITE, not an origin: Chromium canonicalises
https://app.example.com to https://example.com, measured via CDP.

* fix(browser): fail closed on lossy cookie identity recovery

* fix(browser): preserve unreadable families before decrypt

* fix(browser): reject malformed cookie partition sites

* fix(browser): validate recovered cookie partition sites

* fix(browser): reject empty JSON partition identities

* fix(browser): fail closed and serialize cookie imports

* fix(browser): reject malformed CDP opaque flags

* fix(browser): roll back outcome-unknown cookie writes

* revert(browser): move import serialization out to STA-4601

Reverts only the concurrency-serialization half of f7c27b7 so stablyai#15030 stays
scoped to the STA-4300 reland. That commit mixed two concerns; this removes one
of them and keeps the other.

REMOVED (moves to STA-4601, a separate pre-existing P1):
- acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map;
  clear.ts goes back to withCookieClearLock
- the import-wide lock in path A (mutationOwner on the target, acquire/release
  around replace + writes + rollback)
- the widened lock around path B's clear + memory writes
- browser-cookie-import-concurrency.test.ts

KEPT (genuinely STA-4300 scope, not concurrency):
- partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot.
  An opaque partition key cannot be represented faithfully, so it reads as
  unreadable and its family is preserved — exactly the rule this ticket adds.
  194e57a's refinement of that shape stays too.

The concurrent-import interleaving is real and reachable (nothing serialises
imports per partition, and the clear lock is released before the memory writes),
but it predates this change and is not caused or worsened by it. It gets its own
PR and its own review rather than riding a P0 reland whose history is that every
additional fix introduced a new defect.

src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on
both write paths and still goes red against main's product code.
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
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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…es, and never clear what it will not write back (stablyai#15030)

* reland(browser): restore CDP-identity cookie-import writes (stablyai#14729)

Reverts the revert 23fe91e (stablyai#14942) to restore the reviewed 210f961
tree. The defect that caused that revert is NOT fixed by this commit — it is
fixed in the commits that follow, so the delta a reviewer must scrutinise
stays small instead of hiding inside a 2000-line re-add.

Conflict resolutions, all keep-both:
- browser-cookie-import.ts: two hunks around the zero-import early return.
  stablyai#14683's undecryptable warning and decryptedCookies.length === 0 condition
  are kept alongside the reland's old-client gate and partitionSkippedCookies.
  The old-client gate stays above the early return, and so above any mutation.
- en.json: both string sets (stablyai#14683's undecryptable copy and partitionSkipped).
- crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket.

getStoragePath, and its positive-write assertion moves from cookies.set to the
CDP identity store — adapted, not weakened, and now strictly stronger because
it also asserts cookies.set carries no imported user data. Every decryption
assertion is untouched.

* fix(browser): add registrableFamily, one definition of a cookie family

STA-4300, change 1 of the reland fixes. No behaviour change yet — this only
adds the helper the later commits derive every skip scope from.

Deriving "family" inline in several places is what let the removal scope and
the write set disagree in STA-4090 and STA-4170, so there is exactly one.

The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string.
psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain
is '0.1' — and Chromium accepts many spellings of one address. new URL() inside
normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and
a trailing dot to a dotted quad first, so isIP() then catches all of them.
Mutation-proved: moving the check ahead of normalisation reddens the five
alternate-spelling cases and nothing else.

Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the
value falls through to psl, which throws, which returns the host — the right
answer for the wrong reason.

Returns null for a bare public suffix: naming `com` as a family would preserve
an entire TLD from removal and silently turn an import into a no-op.

* fix(browser): plan every cookie's fate before any jar mutation

STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and
every removal scope can derive from one value instead of being computed twice.
Not yet wired into the import paths; that is the next commits.

TWO passes, and the second is not optional. Family-atomic skip is a property of
the whole input: with a readable mixed.example row BEFORE an unreadable
sub.mixed.example row, a per-row guard emits the readable one before anything
knows the family will be skipped. Pass 1 classifies and collects the skipped
families; pass 2 re-filters the provisional writes.

Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you
go): the readable-before-unreadable case goes red and the unreadable-before-
readable case still passes. That asymmetry is why both orders are tested and
why only the first is the named detector.

Family closure is at the registrable boundary because that is the boundary the
removal scope actually expands to: importedDomainScopes turns an imported
mixed.example into descendant roots, so a readable apex cookie drags a skipped
subdomain's live session into the removal scope (STA-4300 §2b).

hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we
cannot name is one we cannot exclude from the removal plan, and clearing a
family we cannot protect is the P0 this ticket exists to stop — so the caller
refuses before mutating rather than proceeding and hoping.

* fix(browser): derive path A's removal scope from the write plan (STA-4300 §2b)

Change 3. importValidatedCookies now plans before it opens the jar, and the
replacement scope and the write set are the SAME array.

210f961 filtered replacementDomains per exact cookie
(partition.status !== 'unreadable'). That is not sufficient:
replaceCookiesForImportedDomains expands each imported domain into its
descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example
into the removal scope — and a skipped cookie living there has its session
removed with nothing written back. Same erasure as the P0, different path.

plan.writes is family-closed, and because path A passes the very same array to
replaceCookiesForImportedDomains and to writeImportedCookies, the two sets
cannot drift apart. That is stronger than keeping them in sync: there is only
one set.

Also here, both before any mutation:
- an unrepresentable skip (registrableFamily → null) refuses the import, because
  a family we cannot name is one we cannot exclude from the removal scope;
- the old-client gate now keys off plan.skips rather than re-deriving the
  condition.

Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the
unreadable rows plus their family-suppressed siblings — added in exactly once,
so totalCookies === importedCookies + skippedCookies keeps holding. Counting it
separately is how a summary silently stops adding up.

Full src/main/browser suite: 69 files, 729 tests, green.

* fix(browser): split path B into scan and emit, and never stage a skip (STA-4300)

Change 4 — this is the commit that fixes the shipped P0.

210f961 did:
    decryptedCookies.push({ ..., partition })   // write set built HERE
    if (partition.status === 'unreadable') { ... continue }   // guard AFTER

so an unreadable row discovered late could not retract a sibling already
emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation
set was the whole jar and the write set a strict subset of it, which is how a
mixed readable/unreadable source emptied a populated jar and repopulated only
part of it.

Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies,
not domainSet, not a staging row, not the imported count. Between scan and emit,
planImportWrites closes the skip over whole registrable families, and emit walks
the plan. Each scanned candidate carries its raw source row because
buildChromiumCookieInsertParams needs it; a record holding only the derived
fields compiles and then silently cannot stage.

Also between scan and emit, both before any mutation:
- an unrepresentable skip refuses the import;
- any skipped family calls disableStaging. A staged image is a whole-database
  replacement on the next start, so it cannot express "preserve this family";
  main's existing memoryFailed arm then reports restart-fallback-unavailable.

Test contract change, deliberately stronger: "never stages a partitioned row
whose ancestor bit is unreadable" asserted that an image WAS registered and
merely omitted the row. That image would still have erased the preserved family
on replay. It now asserts no image is registered at all — plus a new paired case
proving a no-skip import still stages, so "disable on skip" cannot be
implemented as "disable always" unnoticed.

Honest note on detection: reverting the emit filter currently reddens only the
staging assertion, because every end-to-end fixture in this module still starts
with an EMPTY jar — where clear-then-write-all and clear-then-write-some are
indistinguishable. That is the blind spot that let this ship. The populated-jar
suite in the next commit is what actually detects the erasure.

Full src/main/browser: 69 files, 730 tests, green.

* fix(browser): never remove a family the import declined to write (STA-4300 I2)

Change 5, and the one that makes preservation observable.

removeTransplantableCookies takes preserveFamilies. removableCookieEntries
filters those families out, which keeps them out of the removal plan AND — since
the CDP snapshot is taken from that same list — out of the restore set, so a
preserved coordinate is never submitted to any mutation at all.

When anything is preserved, the bulk clearData path is not used. clearData
removes everything outside excludeOrigins, and its own comment concedes a
rejection may already have emptied part of the jar; a preserved family is
deliberately absent from the snapshot, so a partial delete followed by a
rejection would destroy it with no identity able to restore it. Handing a
dynamically derived preserve list to that primitive cannot be made safe, so a
skip-bearing clear runs the frozen per-coordinate plan — which already excludes
those families — as its primary path instead. Nothing is preserved on an
ordinary import, so that path keeps today's single clearData call unchanged.

New populated-jar suite. Every end-to-end fixture in this module starts with
cookies.get returning [], and against an empty jar "clear then write all" and
"clear then write some" are indistinguishable — which is why four independent
gates missed the P0. These fixtures start populated.

Mutation-proved, and this is the first detector in the change set that catches
the actual erasure rather than a proxy:
- drop the preserved-family filter          → 6 of 8 red
- use bulk clearData while preserving       → 6 of 8 red, including
  "leaves a preserved family untouched", which is the erasure itself

IPv4-literal and single-label host families are covered explicitly: psl reads
127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to
match the preserve set and erase the live loopback session.

Full src/main/browser: 70 files, 738 tests, green.

* test(browser): pin STA-4300 end to end in real Electron, both write paths

Ports the pre-implementation reproduction into the PR. Verified RED against
main's product code and GREEN with the fix, on both paths — I re-ran it both
ways rather than assuming.

Two assertions are INVERTED rather than deleted, and both are now stronger. The
repro proved the defect by showing cookies.set was called WITHOUT a partitionKey;
after the reland the import write path does not touch cookies.set for user data
at all, so seeing the imported cookie there is itself the regression. The
fixture's internal guard is inverted the same way.

Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero
importedCookies, the importer reaching its terminal step, the source really
carrying its partition fields, and a CONTROL cookie written via CDP *with* a
partitionKey and read back with it — so "partitionKey absent" cannot be confused
with "the oracle cannot see partitions". electronVersion proves Electron ran.

Fixture correction worth recording, because the original reproduction was
invalid on this path and I did not catch it on first read: readJsonCookiePartition
reads a NESTED partitionKey object, but the fixture wrote topLevelSite and
hasCrossSiteAncestor at the entry's top level, where the importer never looks.
The file/paste case therefore failed on main for a fixture-shape reason rather
than for the defect — and its own non-vacuity check validated what the fixture
wrote instead of what the parser reads, which is exactly how a check that looks
rigorous proves nothing. Only the native half was ever a real reproduction.

Partition keys use a schemeful SITE, not an origin: Chromium canonicalises
https://app.example.com to https://example.com, measured via CDP.

* fix(browser): fail closed on lossy cookie identity recovery

* fix(browser): preserve unreadable families before decrypt

* fix(browser): reject malformed cookie partition sites

* fix(browser): validate recovered cookie partition sites

* fix(browser): reject empty JSON partition identities

* fix(browser): fail closed and serialize cookie imports

* fix(browser): reject malformed CDP opaque flags

* fix(browser): roll back outcome-unknown cookie writes

* revert(browser): move import serialization out to STA-4601

Reverts only the concurrency-serialization half of f7c27b7 so stablyai#15030 stays
scoped to the STA-4300 reland. That commit mixed two concerns; this removes one
of them and keeps the other.

REMOVED (moves to STA-4601, a separate pre-existing P1):
- acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map;
  clear.ts goes back to withCookieClearLock
- the import-wide lock in path A (mutationOwner on the target, acquire/release
  around replace + writes + rollback)
- the widened lock around path B's clear + memory writes
- browser-cookie-import-concurrency.test.ts

KEPT (genuinely STA-4300 scope, not concurrency):
- partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot.
  An opaque partition key cannot be represented faithfully, so it reads as
  unreadable and its family is preserved — exactly the rule this ticket adds.
  194e57a's refinement of that shape stays too.

The concurrent-import interleaving is real and reachable (nothing serialises
imports per partition, and the clear lock is released before the memory writes),
but it predates this change and is not caused or worsened by it. It gets its own
PR and its own review rather than riding a P0 reland whose history is that every
additional fix introduced a new defect.

src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on
both write paths and still goes red against main's product code.
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
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