diff --git a/src/main/browser/browser-cookie-import.test.ts b/src/main/browser/browser-cookie-import.test.ts index 276630170..55fae27c9 100644 --- a/src/main/browser/browser-cookie-import.test.ts +++ b/src/main/browser/browser-cookie-import.test.ts @@ -6,13 +6,25 @@ const { copyFileSyncMock, execFileSyncMock, sessionFromPartitionMock, - dialogShowOpenDialogMock + dialogShowOpenDialogMock, + setPendingCookieImportMock, + clearPendingCookieImportMock } = vi.hoisted(() => ({ appGetPathMock: vi.fn(), copyFileSyncMock: vi.fn(), execFileSyncMock: vi.fn(), sessionFromPartitionMock: vi.fn(), - dialogShowOpenDialogMock: vi.fn() + dialogShowOpenDialogMock: vi.fn(), + setPendingCookieImportMock: vi.fn(), + clearPendingCookieImportMock: vi.fn() +})) + +vi.mock('./browser-session-registry', () => ({ + browserSessionRegistry: { + setPendingCookieImport: setPendingCookieImportMock, + clearPendingCookieImport: clearPendingCookieImportMock, + persistUserAgent: vi.fn() + } })) vi.mock('node:child_process', () => ({ execFileSync: execFileSyncMock })) @@ -47,8 +59,16 @@ import { createChromiumCookieTestDatabase, encryptMacChromiumCookie } from './browser-cookie-import-test-database' -import { existsSync, writeFileSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' -import { join } from 'node:path' +import { + existsSync, + mkdirSync, + writeFileSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync +} from 'node:fs' +import { dirname, join } from 'node:path' import { tmpdir } from 'node:os' function chromeBrowser(cookiesPath: string): DetectedBrowser { @@ -382,6 +402,8 @@ describe('importCookiesFromBrowser Chromium', () => { appGetPathMock.mockReset() appGetPathMock.mockReturnValue(join(tmpDir, 'userData')) copyFileSyncMock.mockClear() + setPendingCookieImportMock.mockClear() + clearPendingCookieImportMock.mockClear() execFileSyncMock.mockReset() execFileSyncMock.mockImplementation(() => { throw new Error('OS credential commands are unavailable in this test') @@ -515,20 +537,198 @@ describe('importCookiesFromBrowser Chromium', () => { } }) - it('removes partial staging data when the target database copy fails', async () => { + // Why: #9355 — staging only backs the cold-restart replay, so an AV/EDR handle that blocks + // the staging copy must degrade that fallback, not abort an import the memory path can serve. + it('still imports in-memory when the target database copy fails', async () => { const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') - createChromiumCookieTestDatabase(sourceCookiesPath, []).close() + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() createChromiumCookieTestDatabase(targetCookiesPath, []).close() + // The staging copy runs before the source snapshot, so the first copy is the staging one. copyFileSyncMock.mockImplementationOnce((_source: string, destination: string) => { writeFileSync(destination, 'partial cookie database') - throw new Error('simulated copy failure') + const error = new Error('EBUSY: resource busy or locked, copyfile') as NodeJS.ErrnoException + error.code = 'EBUSY' + throw error }) - const result = await importCookiesFromBrowser(chromeBrowser(sourceCookiesPath), 'persist:test') + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) - expect(result).toEqual({ ok: false, reason: 'Could not create staging cookie database.' }) - expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + expect(result.ok).toBe(true) + expect(cookiesSetMock).toHaveBeenCalledWith( + expect.objectContaining({ name: 'sid', value: 'source-value' }) + ) + // The partial staging file is still discarded, so no stale DB replays on cold start. + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + } finally { + platformSpy.mockRestore() + } + }) + + // Why: #9355 — the staged file is also named "Cookies", so the same transient handle can make + // opening it throw. That was fatal too, and the count must stay truthful without a staging DB. + it('still imports in-memory when the staging database cannot be opened', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() + mkdirSync(dirname(targetCookiesPath), { recursive: true }) + // A live partition DB that copies fine but is not openable as SQLite. + writeFileSync(targetCookiesPath, 'not a sqlite database') + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(cookiesSetMock).toHaveBeenCalledWith( + expect.objectContaining({ name: 'sid', value: 'source-value' }) + ) + // The summary counts importable cookies, not staged rows. + expect(result.ok && result.summary?.importedCookies).toBe(1) + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + } finally { + platformSpy.mockRestore() + } + }) + + // Why: #9355 — registering a staged path that was never written would make the next cold start + // replay a missing or partial DB over the live partition. + it('never registers a restart replay when staging is unavailable', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() + mkdirSync(dirname(targetCookiesPath), { recursive: true }) + writeFileSync(targetCookiesPath, 'not a sqlite database') + // Forces the restart fallback to be the only way these cookies could ever land. + cookiesSetMock.mockRejectedValue(new Error('cookie rejected')) + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(setPendingCookieImportMock).not.toHaveBeenCalled() + // An older staged DB must not survive an import that already rewrote the live session. + expect(clearPendingCookieImportMock).toHaveBeenCalledWith('persist:test') + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + // Why: the jar was cleared and nothing replaced it, so this must not read as a clean success. + expect(result.ok && result.summary?.warning).toEqual({ + code: 'restart-fallback-unavailable', + loadedCookies: 0, + failedCookies: 1 + }) + } finally { + platformSpy.mockRestore() + } + }) + + // Why: #9355 — a staging write that fails mid-transaction must disable the restart fallback + // rather than abort an import whose in-memory half still works. + it('still imports in-memory when a staging insert fails', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() + const targetDb = createChromiumCookieTestDatabase(targetCookiesPath, []) + // Rejects every staged row the way a corrupt index or disk error would. + targetDb.exec( + `CREATE TRIGGER reject_insert BEFORE INSERT ON cookies + BEGIN SELECT RAISE(ABORT, 'staging write failed'); END` + ) + targetDb.close() + // Why: without a memory failure, memoryFailed === 0 would suppress registration on its own and + // the assertion below would pass even if the insert failure never disabled staging. + cookiesSetMock.mockRejectedValue(new Error('cookie rejected')) + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(cookiesSetMock).toHaveBeenCalledWith( + expect.objectContaining({ name: 'sid', value: 'source-value' }) + ) + expect(setPendingCookieImportMock).not.toHaveBeenCalled() + expect(clearPendingCookieImportMock).toHaveBeenCalledWith('persist:test') + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + } finally { + platformSpy.mockRestore() + } + }) + + // Why: #9355 — a successful in-memory import must retire any older staged replay, or the next + // cold start will overwrite the live session with a stale snapshot. + it('clears a stale staged replay after an import that fully succeeds in memory', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() + createChromiumCookieTestDatabase(targetCookiesPath, []).close() + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(setPendingCookieImportMock).not.toHaveBeenCalled() + expect(clearPendingCookieImportMock).toHaveBeenCalledWith('persist:test') + // A fully in-memory import needs no restart, so it must not warn. + expect(result.ok && result.summary?.warning).toBeUndefined() + } finally { + platformSpy.mockRestore() + } + }) + + // Why: the staged path is the restart fallback's only input, so a working staging DB must register it. + it('registers the staged database when cookies need a restart', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: 'source-value' } + ]).close() + createChromiumCookieTestDatabase(targetCookiesPath, []).close() + cookiesSetMock.mockRejectedValue(new Error('cookie rejected')) + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(setPendingCookieImportMock).toHaveBeenCalledTimes(1) + const [partition, stagedPath] = setPendingCookieImportMock.mock.calls[0] + expect(partition).toBe('persist:test') + expect(existsSync(stagedPath as string)).toBe(true) + } finally { + platformSpy.mockRestore() + } }) }) diff --git a/src/main/browser/browser-cookie-import.ts b/src/main/browser/browser-cookie-import.ts index 7bcfd4ea2..e7703a1f5 100644 --- a/src/main/browser/browser-cookie-import.ts +++ b/src/main/browser/browser-cookie-import.ts @@ -80,6 +80,7 @@ import { type ChromiumCookieSnapshot } from './chromium-cookie-snapshot' import { resolveChromiumCookiesPath } from './chromium-cookie-path' +import { copyFileWithWindowsRetry } from '../codex-accounts/fs-utils' // --------------------------------------------------------------------------- // Browser detection @@ -1449,17 +1450,24 @@ export async function importCookiesFromBrowser( stagingDir, `Cookies-${partitionSegment}-${Date.now()}-${randomUUID()}` ) + // Why: #9355 — staging only backs the cold-restart replay for cookies the in-memory + // import rejects, so losing it must degrade that fallback rather than abort the import. + let stagingAvailable = false try { mkdirSync(stagingDir, { recursive: true }) - copyFileSync(liveCookiesPath, stagingCookiesPath) - } catch { + copyFileWithWindowsRetry(liveCookiesPath, stagingCookiesPath) + stagingAvailable = true + } catch (err) { + const fsErr = err as NodeJS.ErrnoException + diag( + ` staging copy unavailable: code=${fsErr.code ?? 'unknown'} errno=${fsErr.errno ?? 'unknown'} syscall=${fsErr.syscall ?? 'unknown'} path=${liveCookiesPath} destination=${stagingCookiesPath}` + ) // Why: copyFile is non-atomic and can leave a partial DB; delete it so failed imports retain no cookie data. try { unlinkSync(stagingCookiesPath) } catch { /* best-effort */ } - return { ok: false, reason: 'Could not create staging cookie database.' } } let sourceSnapshot: ChromiumCookieSnapshot @@ -1481,6 +1489,21 @@ export async function importCookiesFromBrowser( let sourceDb: InstanceType | null = null let stagingDb: InstanceType | null = null + const closeStagingDb = (): void => { + try { + stagingDb?.close() + } catch { + /* best-effort */ + } + stagingDb = null + } + const discardStagingFile = (): void => { + try { + unlinkSync(stagingCookiesPath) + } catch { + /* best-effort */ + } + } try { // Why: Chromium timestamps (µs since 1601) can exceed Number.MAX_SAFE_INTEGER; readBigInts avoids precision loss. @@ -1488,15 +1511,32 @@ export async function importCookiesFromBrowser( readOnly: true, readBigInts: true }) - stagingDb = new DatabaseSync(stagingCookiesPath) - - const targetColumnInfo = stagingDb - .prepare('PRAGMA table_info(cookies)') - .all() as ChromiumCookieColumnInfo[] - const targetCols: string[] = targetColumnInfo.map((r) => r.name) - const colList = targetCols.join(', ') - - stagingDb.exec('DELETE FROM cookies') + let targetColumnInfo: ChromiumCookieColumnInfo[] | null = null + let colList: string | null = null + let placeholders: string | null = null + if (stagingAvailable) { + // Why: the staged file is Orca's own partition DB, also named "Cookies", so the same + // transient AV handle can make opening it throw — degrade instead of killing the import. + try { + stagingDb = new DatabaseSync(stagingCookiesPath) + targetColumnInfo = stagingDb + .prepare('PRAGMA table_info(cookies)') + .all() as ChromiumCookieColumnInfo[] + const targetCols: string[] = targetColumnInfo.map((r) => r.name) + colList = targetCols.join(', ') + placeholders = targetCols.map(() => '?').join(', ') + stagingDb.exec('DELETE FROM cookies') + } catch (err) { + diag(` staging database unusable, restart fallback disabled: ${err}`) + stagingAvailable = false + targetColumnInfo = null + colList = null + placeholders = null + closeStagingDb() + // Why: the copy holds real partition cookies; discard it now rather than at the exit branches. + discardStagingFile() + } + } const sourceRows = sourceDb.prepare('SELECT * FROM cookies ORDER BY rowid').all() as Record< string, @@ -1508,13 +1548,8 @@ export async function importCookiesFromBrowser( diag(` source has ${sourceRows.length} cookies`) if (sourceRows.length === 0) { - stagingDb.close() - stagingDb = null - try { - unlinkSync(stagingCookiesPath) - } catch { - /* best-effort */ - } + closeStagingDb() + discardStagingFile() return { ok: false, reason: `No cookies found in ${browser.label}.` } } @@ -1526,14 +1561,9 @@ export async function importCookiesFromBrowser( ? getEncryptionKey(browser.keychainService!, browser.keychainAccount!, browser) : null if (needsSourceKey && !sourceKey) { - stagingDb.close() - stagingDb = null + closeStagingDb() // Why: key denial happens after staging, so clean up the target DB copy or retries pile up. - try { - unlinkSync(stagingCookiesPath) - } catch { - /* best-effort */ - } + discardStagingFile() return { ok: false, reason: `Could not access ${browser.label} encryption key. The OS may have denied access.` @@ -1577,12 +1607,29 @@ export async function importCookiesFromBrowser( const decryptedCookies: DecryptedCookie[] = [] - const placeholders = targetCols.map(() => '?').join(', ') - const insertStmt = stagingDb.prepare( - `INSERT OR REPLACE INTO cookies (${colList}) VALUES (${placeholders})` - ) + // Why: staging only backs the cold-restart replay, so any failure writing it disables that + // fallback instead of aborting an import whose in-memory half still works. + let insertStmt: ReturnType['prepare']> | null = null + const disableStaging = (reason: string): void => { + diag(` staging disabled, restart fallback unavailable: ${reason}`) + stagingAvailable = false + insertStmt = null + closeStagingDb() + discardStagingFile() + } - stagingDb.exec('BEGIN TRANSACTION') + if (stagingDb && colList && placeholders) { + try { + insertStmt = stagingDb.prepare( + `INSERT OR REPLACE INTO cookies (${colList}) VALUES (${placeholders})` + ) + stagingDb.exec('BEGIN TRANSACTION') + } catch (err) { + disableStaging(String(err)) + } + } else if (stagingAvailable) { + disableStaging('staged database exposed no cookies columns') + } for (const sourceRow of sourceRows) { const encRaw = sourceRow.encrypted_value @@ -1637,17 +1684,35 @@ export async function importCookiesFromBrowser( expirationDate: expiresUtc > 0 ? expiresUtc : undefined }) - const params = buildChromiumCookieInsertParams(targetColumnInfo, sourceRow, decryptedValue) - insertStmt.run(...params) + if (insertStmt && targetColumnInfo) { + try { + const params = buildChromiumCookieInsertParams( + targetColumnInfo, + sourceRow, + decryptedValue + ) + insertStmt.run(...params) + } catch (err) { + disableStaging(String(err)) + } + } + // Why: counts importable cookies, not staged rows — the summary must stay truthful when + // the optional staging DB is unavailable. imported++ } diag(` skipped ${integritySkipped} Google integrity cookies (SIDCC/STRP/AEC)`) - stagingDb.exec('COMMIT') - stagingDb.close() - stagingDb = null - - diag(` SQLite staging complete: ${imported} cookies, ${domainSet.size} domains`) + if (stagingDb) { + try { + stagingDb.exec('COMMIT') + closeStagingDb() + diag(` SQLite staging complete: ${imported} cookies, ${domainSet.size} domains`) + } catch (err) { + disableStaging(String(err)) + } + } else { + diag(` staging skipped: ${imported} cookies will load in-memory only`) + } // Why: clear stale cookies first; mixing them with the imported set makes sites like Google reject the session. await targetSession.clearStorageData({ storages: ['cookies'] }) @@ -1684,16 +1749,27 @@ export async function importCookiesFromBrowser( diag(` memory load: ${memoryLoaded} OK, ${memoryFailed} failed`) - if (memoryFailed > 0) { + let warning: BrowserCookieImportSummary['warning'] + if (memoryFailed > 0 && stagingAvailable) { // Why: keep the staging DB so the failed cookies load from SQLite on next cold start, where CookieMonster skips validation. browserSessionRegistry.setPendingCookieImport(targetPartition, stagingCookiesPath) diag(` staged at ${stagingCookiesPath} for ${memoryFailed} cookies that need restart`) - } else { - try { - unlinkSync(stagingCookiesPath) - } catch { - /* best-effort */ + } else if (memoryFailed > 0) { + // Why: never register a path that was never written — cold start would replay a missing + // or partial DB over the live partition. + browserSessionRegistry.clearPendingCookieImport(targetPartition) + discardStagingFile() + diag(` ${memoryFailed} cookies need a restart but staging is unavailable — skipped`) + // Why: the jar was already cleared, so silence here would report a lossy import as a clean success. + warning = { + code: 'restart-fallback-unavailable', + loadedCookies: memoryLoaded, + failedCookies: memoryFailed } + } else { + // Why: this import already rewrote the live session, so an older staged DB must not replay over it. + browserSessionRegistry.clearPendingCookieImport(targetPartition) + discardStagingFile() diag(` all cookies loaded in-memory — no restart needed`) } @@ -1709,7 +1785,8 @@ export async function importCookiesFromBrowser( totalCookies: sourceRows.length, importedCookies: imported, skippedCookies: skipped, - domains: [...domainSet].sort() + domains: [...domainSet].sort(), + ...(warning ? { warning } : {}) } return { ok: true, profileId: '', summary } diff --git a/src/main/browser/browser-session-registry.persistence.test.ts b/src/main/browser/browser-session-registry.persistence.test.ts index 174b5aa77..50166f6f5 100644 --- a/src/main/browser/browser-session-registry.persistence.test.ts +++ b/src/main/browser/browser-session-registry.persistence.test.ts @@ -235,6 +235,91 @@ describe('BrowserSessionRegistry persistence', () => { }) }) + it('clears only the requested partition and unlinks its staged database files', async () => { + const otherPartition = 'persist:orca-browser-session-bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + const fsState = createFsState() + seedMeta(fsState, { + defaultSource: null, + userAgent: null, + userAgentByPartition: {}, + pendingCookieDbPath: '/staged/default', + pendingCookieImports: { + 'persist:orca-browser': '/staged/default', + [otherPartition]: '/staged/other' + }, + profiles: [] + }) + for (const suffix of ['', '-wal', '-shm']) { + fsState.files.set(`/staged/other${suffix}`, 'db') + fsState.present.add(`/staged/other${suffix}`) + fsState.files.set(`/staged/default${suffix}`, 'db') + fsState.present.add(`/staged/default${suffix}`) + } + + installModuleMocks(fsState) + const { browserSessionRegistry } = await import('./browser-session-registry') + + browserSessionRegistry.clearPendingCookieImport(otherPartition) + + const written = JSON.parse(fsState.files.get(META_PATH) ?? '{}') + expect(written.pendingCookieImports).toEqual({ 'persist:orca-browser': '/staged/default' }) + // Why: the default partition still has a staged replay, so the legacy pointer must survive. + expect(written.pendingCookieDbPath).toBe('/staged/default') + for (const suffix of ['', '-wal', '-shm']) { + expect(fsState.present.has(`/staged/other${suffix}`)).toBe(false) + expect(fsState.present.has(`/staged/default${suffix}`)).toBe(true) + } + }) + + it('drops the legacy pointer when the default partition is the one cleared', async () => { + const otherPartition = 'persist:orca-browser-session-cccccccc-cccc-4ccc-8ccc-cccccccccccc' + const fsState = createFsState() + seedMeta(fsState, { + defaultSource: null, + userAgent: null, + userAgentByPartition: {}, + pendingCookieDbPath: '/staged/default', + pendingCookieImports: { + 'persist:orca-browser': '/staged/default', + [otherPartition]: '/staged/other' + }, + profiles: [] + }) + + installModuleMocks(fsState) + const { browserSessionRegistry } = await import('./browser-session-registry') + + browserSessionRegistry.clearPendingCookieImport('persist:orca-browser') + + const written = JSON.parse(fsState.files.get(META_PATH) ?? '{}') + expect(written.pendingCookieImports).toEqual({ [otherPartition]: '/staged/other' }) + expect(written.pendingCookieDbPath).toBeNull() + }) + + it('is a no-op when the partition has no pending import', async () => { + const fsState = createFsState() + seedMeta(fsState, { + defaultSource: null, + userAgent: null, + userAgentByPartition: {}, + pendingCookieDbPath: '/staged/default', + pendingCookieImports: { 'persist:orca-browser': '/staged/default' }, + profiles: [] + }) + fsState.files.set('/staged/default', 'db') + fsState.present.add('/staged/default') + + installModuleMocks(fsState) + const { browserSessionRegistry } = await import('./browser-session-registry') + const metaBefore = fsState.files.get(META_PATH) + + browserSessionRegistry.clearPendingCookieImport('persist:orca-browser-session-unknown') + + // Why: an absent key must not rewrite meta or touch another partition's staged file. + expect(fsState.files.get(META_PATH)).toBe(metaBefore) + expect(fsState.present.has('/staged/default')).toBe(true) + }) + it('restores persisted UA for non-default partitions', async () => { const importedPartition = 'persist:orca-browser-session-11111111-1111-4111-8111-111111111111' const importedUa = 'Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36' diff --git a/src/main/browser/browser-session-registry.ts b/src/main/browser/browser-session-registry.ts index 72a888edb..1dfd03c77 100644 --- a/src/main/browser/browser-session-registry.ts +++ b/src/main/browser/browser-session-registry.ts @@ -290,6 +290,28 @@ class BrowserSessionRegistry { }) } + // Why: a degraded import still rewrites the live session, so an older staged DB must stop replaying over it. + clearPendingCookieImport(partition: string): void { + const meta = this.loadPersistedMeta() + if (!(partition in meta.pendingCookieImports)) { + return + } + const pendingCookieImports = { ...meta.pendingCookieImports } + const stagedPath = pendingCookieImports[partition] + delete pendingCookieImports[partition] + this.persistMeta({ + pendingCookieImports, + pendingCookieDbPath: pendingCookieImports[this.defaultPartition] ?? null + }) + for (const suffix of ['', '-wal', '-shm']) { + try { + unlinkSync(stagedPath + suffix) + } catch { + /* best-effort */ + } + } + } + persistUserAgent(partition: string, userAgent: string | null): void { const meta = this.loadPersistedMeta() const userAgentByPartition = { ...meta.userAgentByPartition } diff --git a/src/main/browser/chromium-cookie-snapshot.test.ts b/src/main/browser/chromium-cookie-snapshot.test.ts index 16fbd50a6..f2d6e322d 100644 --- a/src/main/browser/chromium-cookie-snapshot.test.ts +++ b/src/main/browser/chromium-cookie-snapshot.test.ts @@ -156,6 +156,63 @@ describe('createChromiumCookieSnapshot', () => { expect(readdirSync(snapshotsRoot)).toEqual([]) }) + // Why: #9355 — the attempt loop only reacts to a `false` return, so before the retry a + // transient AV/EDR lock on the main copy threw straight out of the snapshot. + it('retries a transient Windows lock on the main database copy', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + createChromiumCookieTestDatabase(sourcePath, [{ name: 'sid', value: 'locked-value' }]).close() + let mainCopyAttempts = 0 + beforeCopyMock.mockImplementation((source: string) => { + if (source !== sourcePath) { + return + } + mainCopyAttempts += 1 + if (mainCopyAttempts === 1) { + throw Object.assign(new Error('EBUSY: resource busy or locked, copyfile'), { + code: 'EBUSY' + }) + } + }) + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + + try { + const snapshot = createChromiumCookieSnapshot(sourcePath, { tempRoot: root }) + const database = new DatabaseSync(snapshot.databasePath, { readOnly: true }) + const row = database.prepare('SELECT name, value FROM cookies').get() + database.close() + + expect(row).toEqual(expect.objectContaining({ name: 'sid', value: 'locked-value' })) + expect(mainCopyAttempts).toBe(2) + snapshot.cleanup() + } finally { + platformSpy.mockRestore() + } + }) + + // Why: the retry is Windows-scoped, so POSIX keeps failing fast instead of sleeping. + it('does not retry a locked copy off Windows', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + const snapshotsRoot = join(root, 'snapshots') + mkdirSync(snapshotsRoot) + createChromiumCookieTestDatabase(sourcePath, [{ name: 'sid', value: 'value' }]).close() + let mainCopyAttempts = 0 + beforeCopyMock.mockImplementation(() => { + mainCopyAttempts += 1 + throw Object.assign(new Error('EBUSY: resource busy or locked, copyfile'), { code: 'EBUSY' }) + }) + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + + try { + expect(() => createChromiumCookieSnapshot(sourcePath, { tempRoot: snapshotsRoot })).toThrow( + 'EBUSY' + ) + expect(mainCopyAttempts).toBe(1) + expect(readdirSync(snapshotsRoot)).toEqual([]) + } finally { + platformSpy.mockRestore() + } + }) + it('removes its temporary directory when the source database is missing', () => { const snapshotsRoot = join(root, 'snapshots') mkdirSync(snapshotsRoot) diff --git a/src/main/browser/chromium-cookie-snapshot.ts b/src/main/browser/chromium-cookie-snapshot.ts index 4b54e98be..452dfca00 100644 --- a/src/main/browser/chromium-cookie-snapshot.ts +++ b/src/main/browser/chromium-cookie-snapshot.ts @@ -1,6 +1,7 @@ -import { copyFileSync, mkdtempSync, rmSync, statSync, unlinkSync } from 'node:fs' +import { mkdtempSync, rmSync, statSync, unlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { copyFileWithWindowsRetry } from '../codex-accounts/fs-utils' const SNAPSHOT_ATTEMPTS = 5 @@ -83,12 +84,15 @@ function copyStableAttempt(sourcePath: string, databasePath: string): boolean { } removeAttemptFiles(databasePath) - copyFileSync(sourcePath, databasePath) + // Why: #9355 — AV/EDR briefly opens a file literally named "Cookies" with FILE_SHARE_NONE, + // so an otherwise-fine copy throws EBUSY. The attempt loop below only handles a false + // return, so a throw here would escape it entirely. + copyFileWithWindowsRetry(sourcePath, databasePath) if (walBefore) { try { // Why: SQLite only discovers a WAL whose basename exactly matches the DB. - copyFileSync(sourceWalPath, `${databasePath}-wal`) + copyFileWithWindowsRetry(sourceWalPath, `${databasePath}-wal`) } catch (error) { if (isMissingFileError(error)) { return false diff --git a/src/renderer/src/components/browser-pane/BrowserImportHintButton.tsx b/src/renderer/src/components/browser-pane/BrowserImportHintButton.tsx index 96f1abab3..32af12eeb 100644 --- a/src/renderer/src/components/browser-pane/BrowserImportHintButton.tsx +++ b/src/renderer/src/components/browser-pane/BrowserImportHintButton.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { Import } from 'lucide-react' import { toast } from 'sonner' +import { emitBrowserCookieImportToast } from '@/lib/browser-cookie-import-toast' import { Button } from '@/components/ui/button' import { DropdownMenu, @@ -89,7 +90,8 @@ export function BrowserImportHintButton({ ) if (result.ok) { const browser = detectedBrowsers.find((entry) => entry.family === browserFamily) - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.browser.pane.BrowserImportHintButton.02e89014c5', 'Imported {{value0}} cookies from {{value1}}{{value2}}.', @@ -112,7 +114,8 @@ export function BrowserImportHintButton({ setImportMenuOpen(false) const result = await importCookiesToProfile(effectiveProfileId) if (result.ok) { - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.browser.pane.BrowserImportHintButton.d40d584769', 'Imported {{value0}} cookies from file.', diff --git a/src/renderer/src/components/browser-pane/BrowserToolbarMenu.tsx b/src/renderer/src/components/browser-pane/BrowserToolbarMenu.tsx index 7b0bae361..aa5ab16c5 100644 --- a/src/renderer/src/components/browser-pane/BrowserToolbarMenu.tsx +++ b/src/renderer/src/components/browser-pane/BrowserToolbarMenu.tsx @@ -1,5 +1,6 @@ import { useLayoutEffect, useState } from 'react' import { toast } from 'sonner' +import { emitBrowserCookieImportToast } from '@/lib/browser-cookie-import-toast' import { useAppStore } from '@/store' import { useMountedRef } from '@/hooks/useMountedRef' import { shouldShowBrowserImportHint } from './browser-import-hint-visibility' @@ -171,7 +172,8 @@ export function BrowserToolbarMenu({ const result = await importCookiesFromBrowser(effectiveProfileId, browserFamily, browserProfile) if (result.ok) { const browser = detectedBrowsers.find((b) => b.family === browserFamily) - toast.success( + emitBrowserCookieImportToast( + result.summary, browserProfile ? translate( 'auto.components.browser.pane.BrowserToolbarMenu.c5f0e4d3b2a1', @@ -199,7 +201,8 @@ export function BrowserToolbarMenu({ const handleImportFromFile = async (): Promise => { const result = await importCookiesToProfile(effectiveProfileId) if (result.ok) { - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.browser.pane.BrowserToolbarMenu.53bbe3dab4', 'Imported {{value0}} cookies from file.', diff --git a/src/renderer/src/components/settings/BrowserProfileRow.tsx b/src/renderer/src/components/settings/BrowserProfileRow.tsx index 0d1c377c4..9f5dc38ef 100644 --- a/src/renderer/src/components/settings/BrowserProfileRow.tsx +++ b/src/renderer/src/components/settings/BrowserProfileRow.tsx @@ -1,5 +1,6 @@ import { Import, Loader2, Trash2 } from 'lucide-react' import { toast } from 'sonner' +import { emitBrowserCookieImportToast } from '@/lib/browser-cookie-import-toast' import type { BrowserCookieImportSummary, BrowserSessionProfile } from '../../../../shared/types' import { Button } from '../ui/button' import { @@ -58,7 +59,8 @@ export function BrowserProfileRow({ .importCookiesFromBrowser(profile.id, browserFamily, browserProfile) if (result.ok) { const browser = detectedBrowsers.find((b) => b.family === browserFamily) - toast.success( + emitBrowserCookieImportToast( + result.summary, browserProfile ? translate( 'auto.components.settings.BrowserProfileRow.a3f8c2d1e0b4', @@ -88,7 +90,8 @@ export function BrowserProfileRow({ const handleImportFromFile = async (): Promise => { const result = await useAppStore.getState().importCookiesToProfile(profile.id) if (result.ok) { - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.settings.BrowserProfileRow.b4c167764d', 'Imported {{value0}} cookies from file into {{value1}}.', diff --git a/src/renderer/src/components/settings/BrowserUseCookieImportStep.tsx b/src/renderer/src/components/settings/BrowserUseCookieImportStep.tsx index f73668fa9..3ac98241a 100644 --- a/src/renderer/src/components/settings/BrowserUseCookieImportStep.tsx +++ b/src/renderer/src/components/settings/BrowserUseCookieImportStep.tsx @@ -1,5 +1,6 @@ import { Import, Loader2 } from 'lucide-react' import { toast } from 'sonner' +import { emitBrowserCookieImportToast } from '@/lib/browser-cookie-import-toast' import { cn } from '@/lib/utils' import { Button } from '../ui/button' import { @@ -47,7 +48,8 @@ export function BrowserUseCookieImportStep({ .importCookiesFromBrowser(profileId, browserFamily, browserProfile) if (result.ok) { const browser = detectedBrowsers.find((b) => b.family === browserFamily) - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.settings.BrowserUsePane.2ea4617e3a', 'Imported {{value0}} cookies from {{value1}}{{value2}}.', @@ -66,7 +68,8 @@ export function BrowserUseCookieImportStep({ const handleImportFromFile = async (): Promise => { const result = await useAppStore.getState().importCookiesToProfile('default') if (result.ok) { - toast.success( + emitBrowserCookieImportToast( + result.summary, translate( 'auto.components.settings.BrowserUsePane.8f2675c2f3', 'Imported {{value0}} cookies from file.', diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 44b4124a0..01a53e110 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -639,6 +639,16 @@ "triageFollowupsPrompt": "Use {{value0}} to triage the linked Linear issue — set priority and estimate — and create a parented follow-up ticket for the deferred cleanup." } } + }, + "browser": { + "cookie": { + "import": { + "toast": { + "restartFallbackUnavailableNone": "None of the {{value0}} cookies could be loaded, and the restart fallback was unavailable. The previous cookies for this profile were replaced. Try the import again.", + "restartFallbackUnavailablePartial": "Imported {{value0}} of {{value1}} cookies. The rest could not be loaded, and the restart fallback was unavailable. Try the import again." + } + } + } } }, "hooks": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 8e6783cf3..df89084b3 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -616,6 +616,16 @@ "triageFollowupsPrompt": "Use {{value0}} to triage the linked Linear issue — set priority and estimate — and create a parented follow-up ticket for the deferred cleanup." } } + }, + "browser": { + "cookie": { + "import": { + "toast": { + "restartFallbackUnavailableNone": "No se pudo cargar ninguna de las {{value0}} cookies y la alternativa tras reiniciar no estaba disponible. Se reemplazaron las cookies anteriores de este perfil. Intenta importar de nuevo.", + "restartFallbackUnavailablePartial": "Se importaron {{value0}} de {{value1}} cookies. El resto no se pudo cargar y la alternativa tras reiniciar no estaba disponible. Intenta importar de nuevo." + } + } + } } }, "hooks": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 1448421ca..62fd5330a 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -616,6 +616,16 @@ "triageFollowupsPrompt": "Use {{value0}} to triage the linked Linear issue — set priority and estimate — and create a parented follow-up ticket for the deferred cleanup." } } + }, + "browser": { + "cookie": { + "import": { + "toast": { + "restartFallbackUnavailableNone": "{{value0}} 件の Cookie を読み込めず、再起動時の代替処理も利用できませんでした。このプロファイルの以前の Cookie は置き換えられました。もう一度インポートしてください。", + "restartFallbackUnavailablePartial": "{{value1}} 件中 {{value0}} 件の Cookie をインポートしました。残りは読み込めず、再起動時の代替処理も利用できませんでした。もう一度インポートしてください。" + } + } + } } }, "hooks": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 22a54ebb5..df331ec2e 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -616,6 +616,16 @@ "triageFollowupsPrompt": "Use {{value0}} to triage the linked Linear issue — set priority and estimate — and create a parented follow-up ticket for the deferred cleanup." } } + }, + "browser": { + "cookie": { + "import": { + "toast": { + "restartFallbackUnavailableNone": "{{value0}}개의 쿠키를 하나도 불러오지 못했고 재시작 대체 경로도 사용할 수 없었습니다. 이 프로필의 기존 쿠키가 교체되었습니다. 다시 가져오세요.", + "restartFallbackUnavailablePartial": "쿠키 {{value1}}개 중 {{value0}}개를 가져왔습니다. 나머지는 불러오지 못했고 재시작 대체 경로도 사용할 수 없었습니다. 다시 가져오세요." + } + } + } } }, "hooks": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 390037d42..a6075fd7f 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -616,6 +616,16 @@ "triageFollowupsPrompt": "Use {{value0}} to triage the linked Linear issue — set priority and estimate — and create a parented follow-up ticket for the deferred cleanup." } } + }, + "browser": { + "cookie": { + "import": { + "toast": { + "restartFallbackUnavailableNone": "无法加载这 {{value0}} 个 Cookie 中的任何一个,且重启回退机制不可用。此配置文件之前的 Cookie 已被替换。请重试导入。", + "restartFallbackUnavailablePartial": "已导入 {{value1}} 个 Cookie 中的 {{value0}} 个。其余 Cookie 无法加载,且重启回退机制不可用。请重试导入。" + } + } + } } }, "hooks": { diff --git a/src/renderer/src/lib/browser-cookie-import-toast.test.ts b/src/renderer/src/lib/browser-cookie-import-toast.test.ts new file mode 100644 index 000000000..a59c7a93f --- /dev/null +++ b/src/renderer/src/lib/browser-cookie-import-toast.test.ts @@ -0,0 +1,72 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { successToastMock, warningToastMock } = vi.hoisted(() => ({ + successToastMock: vi.fn(), + warningToastMock: vi.fn() +})) + +vi.mock('sonner', () => ({ + toast: { success: successToastMock, warning: warningToastMock } +})) + +import type { BrowserCookieImportSummary } from '../../../shared/types' +import { emitBrowserCookieImportToast } from './browser-cookie-import-toast' + +const summary: BrowserCookieImportSummary = { + totalCookies: 3, + importedCookies: 3, + skippedCookies: 0, + domains: ['example.com'] +} + +describe('emitBrowserCookieImportToast', () => { + beforeEach(() => { + successToastMock.mockReset() + warningToastMock.mockReset() + }) + + it('shows the localized total-failure warning', () => { + emitBrowserCookieImportToast( + { + ...summary, + warning: { + code: 'restart-fallback-unavailable', + loadedCookies: 0, + failedCookies: 3 + } + }, + 'Imported 3 cookies.' + ) + + expect(warningToastMock).toHaveBeenCalledWith( + 'None of the 3 cookies could be loaded, and the restart fallback was unavailable. The previous cookies for this profile were replaced. Try the import again.' + ) + expect(successToastMock).not.toHaveBeenCalled() + }) + + it('shows the localized partial-failure warning', () => { + emitBrowserCookieImportToast( + { + ...summary, + warning: { + code: 'restart-fallback-unavailable', + loadedCookies: 2, + failedCookies: 1 + } + }, + 'Imported 3 cookies.' + ) + + expect(warningToastMock).toHaveBeenCalledWith( + 'Imported 2 of 3 cookies. The rest could not be loaded, and the restart fallback was unavailable. Try the import again.' + ) + expect(successToastMock).not.toHaveBeenCalled() + }) + + it('shows success when the import has no warning', () => { + emitBrowserCookieImportToast(summary, 'Imported 3 cookies.') + + expect(successToastMock).toHaveBeenCalledWith('Imported 3 cookies.') + expect(warningToastMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/browser-cookie-import-toast.ts b/src/renderer/src/lib/browser-cookie-import-toast.ts new file mode 100644 index 000000000..4bdd031f8 --- /dev/null +++ b/src/renderer/src/lib/browser-cookie-import-toast.ts @@ -0,0 +1,39 @@ +import { toast } from 'sonner' +import type { BrowserCookieImportSummary } from '../../../shared/types' +import { translate } from '@/i18n/i18n' + +type CookieImportWarning = NonNullable + +function formatCookieImportWarning(warning: CookieImportWarning): string { + switch (warning.code) { + case 'restart-fallback-unavailable': + return warning.loadedCookies === 0 + ? translate( + 'auto.lib.browser.cookie.import.toast.restartFallbackUnavailableNone', + 'None of the {{value0}} cookies could be loaded, and the restart fallback was unavailable. The previous cookies for this profile were replaced. Try the import again.', + { value0: warning.failedCookies } + ) + : translate( + 'auto.lib.browser.cookie.import.toast.restartFallbackUnavailablePartial', + 'Imported {{value0}} of {{value1}} cookies. The rest could not be loaded, and the restart fallback was unavailable. Try the import again.', + { + value0: warning.loadedCookies, + value1: warning.loadedCookies + warning.failedCookies + } + ) + } +} + +// Why: a degraded import returns ok:true with a warning, so every call site must route it to a +// warning toast instead of reporting an unqualified success (#9355). +export function emitBrowserCookieImportToast( + summary: BrowserCookieImportSummary, + successMessage: string +): void { + const warning = summary.warning + if (warning) { + toast.warning(formatCookieImportWarning(warning)) + return + } + toast.success(successMessage) +} diff --git a/src/shared/types.ts b/src/shared/types.ts index cb63444b4..c1faa77ab 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1035,6 +1035,11 @@ export type BrowserCookieImportSummary = { importedCookies: number skippedCookies: number domains: string[] + warning?: { + code: 'restart-fallback-unavailable' + loadedCookies: number + failedCookies: number + } } export type BrowserCookieImportResult =