From f6019b7e5548053ff0c83705ebab2da901607686 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 11:31:59 -0600 Subject: [PATCH 1/3] fix(desktop): make continue-in-browser and bring-back reliable for every browser - Open Arc and Dia with a plain open instead of open -n, which started a second app instance; they open in their front profile, so the panel offers one choice per browser and bring-back reads every profile, taking the one that changed the site last - Bring-back imports what the browser has for the site right away and reloads the page; it waits (up to 30s, cancellable, after the Keychain prompt) only when the browser has nothing for the site yet - Keep the handoff pending after a bring-back so it can be brought back again; never write cookies once a cancel, newer continue, or sign-out retires it - Panel: busy state survives remounts, results and errors show inline, Cancel stays available while checking, clearer copy, passkey hint picks a browser and skips the AWS access portal, notices are announced --- apps/desktop/e2e/continue-sign-in.spec.ts | 4 +- .../src/main/browser-import/browser-launch.ts | 19 +- .../main/browser-import/browser-sources.ts | 13 + .../browser-import/chromium-cookies.test.ts | 52 ++- .../main/browser-import/chromium-cookies.ts | 54 ++- .../browser-import/import-service.test.ts | 30 +- .../src/main/browser-import/import-service.ts | 150 +++++++- .../src/main/browser-import/index.test.ts | 349 ++++++++++++------ apps/desktop/src/main/browser-import/index.ts | 85 +++-- .../src/main/browser-import/sqlite-source.ts | 44 ++- apps/desktop/src/main/ipc.test.ts | 30 +- apps/desktop/src/main/ipc.ts | 25 +- apps/desktop/src/preload/index.ts | 3 +- .../browser-continue-sign-in.tsx | 103 +++++- .../browser-session/browser-notice.tsx | 10 +- .../browser-session/sign-in-hosts.test.ts | 4 +- .../browser-session/sign-in-hosts.ts | 4 +- .../browser-session/use-continue-sign-in.ts | 103 ++++-- .../sim/hooks/queries/browser-import.test.tsx | 85 ++++- apps/sim/hooks/queries/browser-import.ts | 57 ++- packages/desktop-bridge/src/index.ts | 25 +- 21 files changed, 950 insertions(+), 299 deletions(-) diff --git a/apps/desktop/e2e/continue-sign-in.spec.ts b/apps/desktop/e2e/continue-sign-in.spec.ts index 0a157a8535d..2fd447cef09 100644 --- a/apps/desktop/e2e/continue-sign-in.spec.ts +++ b/apps/desktop/e2e/continue-sign-in.spec.ts @@ -83,7 +83,7 @@ test.describe('continue a sign-in in another browser', () => { pending: null, profiles: [], continued: { error: 'unknown' }, - broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }, + broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false }, }) }) @@ -108,6 +108,6 @@ test.describe('continue a sign-in in another browser', () => { await page.locator('#back').click() await expect .poll(() => read('broughtBack')) - .toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }) + .toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false }) }) }) diff --git a/apps/desktop/src/main/browser-import/browser-launch.ts b/apps/desktop/src/main/browser-import/browser-launch.ts index e7011fcd58c..b4d7c8ba509 100644 --- a/apps/desktop/src/main/browser-import/browser-launch.ts +++ b/apps/desktop/src/main/browser-import/browser-launch.ts @@ -2,6 +2,7 @@ import { execFile } from 'node:child_process' import { join } from 'node:path' import { promisify } from 'node:util' import { app } from 'electron' +import type { BrowserSource } from '@/main/browser-import/browser-sources' const execFileAsync = promisify(execFile) @@ -28,20 +29,22 @@ export async function defaultBrowserBundleId(): Promise { } /** - * Opens `url` in one profile of an installed Chromium-family browser. + * Opens `url` in one profile of an installed Chromium-family browser, or in + * the browser's frontmost profile when it cannot be told which. * * `-n` launches a fresh instance whose command line Chromium's process * singleton forwards to the running browser; without it a running browser - * drops `--args` and opens the page in whichever profile was last active. + * drops `--args` and opens the page in whichever profile was last active. A + * single-instance app shell (Arc, Dia) gets neither: a second instance is + * refused, so the running one is just handed the page. */ export async function openInBrowserProfile( - bundleId: string, + source: Pick, profileDirectory: string, url: string ): Promise { - await execFileAsync( - '/usr/bin/open', - ['-n', '-b', bundleId, '--args', `--profile-directory=${profileDirectory}`, url], - { timeout: OPEN_TIMEOUT_MS } - ) + const args = source.opensChosenProfile + ? ['-n', '-b', source.bundleId, '--args', `--profile-directory=${profileDirectory}`, url] + : ['-b', source.bundleId, url] + await execFileAsync('/usr/bin/open', args, { timeout: OPEN_TIMEOUT_MS }) } diff --git a/apps/desktop/src/main/browser-import/browser-sources.ts b/apps/desktop/src/main/browser-import/browser-sources.ts index fa4c100f5bf..aebe10e9aaa 100644 --- a/apps/desktop/src/main/browser-import/browser-sources.ts +++ b/apps/desktop/src/main/browser-import/browser-sources.ts @@ -28,6 +28,12 @@ export interface BrowserSource { keychain: { service: string; account: string } /** The macOS bundle identifier, used to open a page in this browser. */ bundleId: string + /** + * Whether a page can be opened in one chosen profile. Arc and Dia are app + * shells around Chromium that allow a single instance and ignore + * `--profile-directory`, so a page opens in whichever profile is in front. + */ + opensChosenProfile: boolean } export const BROWSER_SOURCES: readonly BrowserSource[] = [ @@ -37,6 +43,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Google', 'Chrome'], keychain: { service: 'Chrome Safe Storage', account: 'Chrome' }, bundleId: 'com.google.Chrome', + opensChosenProfile: true, }, { id: 'arc', @@ -44,6 +51,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Arc', 'User Data'], keychain: { service: 'Arc Safe Storage', account: 'Arc' }, bundleId: 'company.thebrowser.Browser', + opensChosenProfile: false, }, { id: 'dia', @@ -51,6 +59,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Dia', 'User Data'], keychain: { service: 'Dia Safe Storage', account: 'Dia' }, bundleId: 'company.thebrowser.dia', + opensChosenProfile: false, }, { id: 'brave', @@ -58,6 +67,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'BraveSoftware', 'Brave-Browser'], keychain: { service: 'Brave Safe Storage', account: 'Brave' }, bundleId: 'com.brave.Browser', + opensChosenProfile: true, }, { id: 'edge', @@ -65,6 +75,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Microsoft Edge'], keychain: { service: 'Microsoft Edge Safe Storage', account: 'Microsoft Edge' }, bundleId: 'com.microsoft.edgemac', + opensChosenProfile: true, }, { id: 'vivaldi', @@ -72,6 +83,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Vivaldi'], keychain: { service: 'Vivaldi Safe Storage', account: 'Vivaldi' }, bundleId: 'com.vivaldi.Vivaldi', + opensChosenProfile: true, }, { id: 'chromium', @@ -79,6 +91,7 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [ userDataSegments: ['Library', 'Application Support', 'Chromium'], keychain: { service: 'Chromium Safe Storage', account: 'Chromium' }, bundleId: 'org.chromium.Chromium', + opensChosenProfile: true, }, ] as const diff --git a/apps/desktop/src/main/browser-import/chromium-cookies.test.ts b/apps/desktop/src/main/browser-import/chromium-cookies.test.ts index b64db8c100d..f60e2b35a25 100644 --- a/apps/desktop/src/main/browser-import/chromium-cookies.test.ts +++ b/apps/desktop/src/main/browser-import/chromium-cookies.test.ts @@ -63,6 +63,8 @@ interface FixtureCookie { isSecure?: number sameSite?: number path?: string + creationUtc?: bigint + lastUpdateUtc?: bigint } let directory: string @@ -75,10 +77,18 @@ afterEach(async () => { await rm(directory, { recursive: true, force: true }) }) -async function writeCookieDatabase(cookies: FixtureCookie[]): Promise { +/** + * A cookie database in Chromium's shape. `schema` 18 added `last_update_utc`; + * the default is an older one without it. + */ +async function writeCookieDatabase( + cookies: FixtureCookie[], + { schema = 17 }: { schema?: 17 | 18 } = {} +): Promise { const { DatabaseSync } = await import('node:sqlite') const path = join(directory, 'Cookies') const database = new DatabaseSync(path) + const lastUpdate = schema >= 18 database.exec(` CREATE TABLE cookies ( creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL, name TEXT NOT NULL, @@ -86,16 +96,18 @@ async function writeCookieDatabase(cookies: FixtureCookie[]): Promise { is_secure INTEGER NOT NULL, is_httponly INTEGER NOT NULL, has_expires INTEGER NOT NULL, is_persistent INTEGER NOT NULL, samesite INTEGER NOT NULL, encrypted_value BLOB + ${lastUpdate ? ', last_update_utc INTEGER NOT NULL' : ''} ) `) const insert = database.prepare(` INSERT INTO cookies (creation_utc, host_key, name, value, path, expires_utc, - is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value + ${lastUpdate ? ', last_update_utc' : ''}) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${lastUpdate ? ', ?' : ''}) `) for (const cookie of cookies) { insert.run( - chromeTime(NOW_SECONDS - 100), + cookie.creationUtc ?? chromeTime(NOW_SECONDS - 100), cookie.hostKey, cookie.name, cookie.value ?? '', @@ -106,7 +118,8 @@ async function writeCookieDatabase(cookies: FixtureCookie[]): Promise { cookie.hasExpires ?? 1, cookie.isPersistent ?? 1, cookie.sameSite ?? 1, - cookie.encryptedValue ?? null + cookie.encryptedValue ?? null, + ...(lastUpdate ? [cookie.lastUpdateUtc ?? 0n] : []) ) } database.close() @@ -219,6 +232,35 @@ describe.skipIf(!sqliteAvailable)('readBrowserCookies', () => { expect(result.skipped['decrypt-failed']).toBe(0) }) + it('reports when an in-scope cookie last changed, ignoring other sites', async () => { + const scope = { domain: 'example.com', exact: false } + const cookies: FixtureCookie[] = [ + { hostKey: '.example.com', name: 'consent', creationUtc: chromeTime(NOW_SECONDS - 500) }, + { + hostKey: 'console.example.com', + name: 'session', + creationUtc: chromeTime(NOW_SECONDS - 400), + lastUpdateUtc: chromeTime(NOW_SECONDS - 10), + }, + { hostKey: 'other.com', name: 'tracker', creationUtc: chromeTime(NOW_SECONDS - 1) }, + ].map((cookie) => ({ ...cookie, encryptedValue: encryptV10(Buffer.from('v')) })) + + const current = await readBrowserCookies( + await writeCookieDatabase(cookies, { schema: 18 }), + KEY, + { nowSeconds: NOW_SECONDS, scope } + ) + expect(current.newestChange).toBe(chromeTime(NOW_SECONDS - 10)) + + await rm(join(directory, 'Cookies')) + const legacy = await readBrowserCookies(await writeCookieDatabase(cookies), KEY, { + nowSeconds: NOW_SECONDS, + scope, + }) + expect(legacy.cookies).toHaveLength(2) + expect(legacy.newestChange).toBe(chromeTime(NOW_SECONDS - 400)) + }) + it('reports an unrecognised schema rather than guessing', async () => { const path = join(directory, 'Cookies') const { DatabaseSync } = await import('node:sqlite') diff --git a/apps/desktop/src/main/browser-import/chromium-cookies.ts b/apps/desktop/src/main/browser-import/chromium-cookies.ts index 18e74676f57..b484eb22ddd 100644 --- a/apps/desktop/src/main/browser-import/chromium-cookies.ts +++ b/apps/desktop/src/main/browser-import/chromium-cookies.ts @@ -1,7 +1,7 @@ import { decryptChromiumValue } from '@/main/browser-import/chromium-crypto' import { translateCookieRow } from '@/main/browser-import/cookie-translate' import { isCookieHostInScope, type SiteScope } from '@/main/browser-import/site-scope' -import { queryBrowserDatabase } from '@/main/browser-import/sqlite-source' +import { allRows, readBrowserDatabase } from '@/main/browser-import/sqlite-source' import { type ChromiumCookieRow, type CookieSkipCounts, @@ -13,16 +13,11 @@ import { /** * Decrypts a Chrome profile's cookies. The source database is copied and read - * read-only by {@link queryBrowserDatabase}; nothing here writes to Chrome. + * read-only by {@link readBrowserDatabase}; nothing here writes to Chrome. */ const MAX_COOKIE_ROWS = 50_000 -const COOKIE_COLUMNS = ` - SELECT host_key, name, path, expires_utc, is_secure, is_httponly, - has_expires, is_persistent, samesite, encrypted_value, value - FROM cookies` - /** `%`, `_`, and the escape itself are LIKE metacharacters; a hostname may carry `_`. */ function escapeLike(value: string): string { return value.replace(/[\\%_]/g, '\\$&') @@ -32,18 +27,31 @@ function escapeLike(value: string): string { * The cookie query, narrowed in SQL to a site's rows when there is a scope. * The narrowing is only an efficiency: {@link isCookieHostInScope} still * decides every row, since LIKE is case-insensitive and knows no labels. + * + * `changed_utc` is when a row last changed: Chromium added `last_update_utc` + * in cookie schema 18 and leaves it 0 when unset, so the later of it and + * `creation_utc` counts; an older database has only `creation_utc`. */ -function cookieQuery(scope: SiteScope | undefined): { query: string; params: string[] } { - if (!scope) return { query: `${COOKIE_COLUMNS} LIMIT ${MAX_COOKIE_ROWS}`, params: [] } +function cookieQuery( + scope: SiteScope | undefined, + hasLastUpdate: boolean +): { query: string; params: string[] } { + const changedAt = hasLastUpdate ? 'max(creation_utc, last_update_utc)' : 'creation_utc' + const columns = ` + SELECT host_key, name, path, expires_utc, is_secure, is_httponly, + has_expires, is_persistent, samesite, encrypted_value, value, + ${changedAt} AS changed_utc + FROM cookies` + if (!scope) return { query: `${columns} LIMIT ${MAX_COOKIE_ROWS}`, params: [] } const exactHosts = [scope.domain, `.${scope.domain}`] if (scope.exact) { return { - query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`, + query: `${columns} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`, params: exactHosts, } } return { - query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`, + query: `${columns} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`, params: [...exactHosts, `%.${escapeLike(scope.domain)}`], } } @@ -53,6 +61,8 @@ export interface ReadCookiesResult { skipped: CookieSkipCounts /** Rows examined, so the caller can tell "no cookies" from "none survived". */ rowsSeen: number + /** When the newest examined row last changed, in Chromium time; 0n with none. */ + newestChange: bigint } function toRow(raw: Record): ChromiumCookieRow { @@ -85,16 +95,19 @@ export async function readBrowserCookies( key: Buffer, { nowSeconds = Date.now() / 1000, scope }: ReadCookiesOptions = {} ): Promise { - const { query, params } = cookieQuery(scope) - const rows = await queryBrowserDatabase(cookiesPath, 'Cookies', query, params) + const rows = await queryCookieRows(cookiesPath, scope) const cookies: ImportableCookie[] = [] const skipped = emptySkipCounts() let rowsSeen = 0 + let newestChange = 0n for (const raw of rows) { const row = toRow(raw) if (scope && !isCookieHostInScope(row.hostKey, scope)) continue rowsSeen += 1 + if (typeof raw.changed_utc === 'bigint' && raw.changed_utc > newestChange) { + newestChange = raw.changed_utc + } const encrypted = raw.encrypted_value let value: string | null if (encrypted instanceof Uint8Array && encrypted.length > 0) { @@ -116,5 +129,18 @@ export async function readBrowserCookies( } } - return { cookies, skipped, rowsSeen } + return { cookies, skipped, rowsSeen, newestChange } +} + +function queryCookieRows( + cookiesPath: string, + scope: SiteScope | undefined +): Promise[]> { + return readBrowserDatabase(cookiesPath, 'Cookies', (database) => { + const hasLastUpdate = allRows(database, 'SELECT name FROM pragma_table_info(?)', [ + 'cookies', + ]).some(({ name }) => name === 'last_update_utc') + const { query, params } = cookieQuery(scope, hasLastUpdate) + return allRows(database, query, params) + }) } diff --git a/apps/desktop/src/main/browser-import/import-service.test.ts b/apps/desktop/src/main/browser-import/import-service.test.ts index a06e8d26c40..0943dcbdcf3 100644 --- a/apps/desktop/src/main/browser-import/import-service.test.ts +++ b/apps/desktop/src/main/browser-import/import-service.test.ts @@ -57,7 +57,13 @@ function cookie(name = 'session'): ImportableCookie { } function read(overrides: Partial = {}): ReadCookiesResult { - return { cookies: [cookie()], skipped: emptySkipCounts(), rowsSeen: 1, ...overrides } + return { + cookies: [cookie()], + skipped: emptySkipCounts(), + rowsSeen: 1, + newestChange: 0n, + ...overrides, + } } function readPasswords(overrides: Partial = {}): ReadPasswordsResult { @@ -138,6 +144,7 @@ describe('listImportableProfiles', () => { browserId: 'chrome', browserLabel: 'Chrome', profileLabel: 'Person 1', + opensChosenProfile: true, }, { id: 'arc:Profile 2', @@ -145,6 +152,7 @@ describe('listImportableProfiles', () => { browserId: 'arc', browserLabel: 'Arc', profileLabel: 'Work', + opensChosenProfile: false, }, ]) }) @@ -571,23 +579,3 @@ describe('remembering the sites an import brought over', () => { expect(readSites).toHaveBeenCalledWith('/chrome/Default/History', new Set(['example.com'])) }) }) - -describe('importChromeCookies with a site scope', () => { - it('reads only the scoped site from the chosen profile', async () => { - const readCookies = vi.fn(async () => read()) - const scope = { domain: 'amazon.com', exact: false } - - await expect( - importChromeCookies('arc:Profile 2', createDeps({ readCookies }), scope) - ).resolves.toEqual({ cookiesImported: 1, cookiesSkipped: 0 }) - expect(readCookies).toHaveBeenCalledWith('/arc/Profile 2/Cookies', expect.any(Buffer), scope) - }) - - it('reports nothing found, not a failure, when the profile has no sign-in for the site', async () => { - const deps = createDeps({ readCookies: async () => read({ cookies: [], rowsSeen: 0 }) }) - - await expect( - importChromeCookies('chrome:Default', deps, { domain: 'example.com', exact: false }) - ).resolves.toEqual({ cookiesImported: 0, cookiesSkipped: 0 }) - }) -}) diff --git a/apps/desktop/src/main/browser-import/import-service.ts b/apps/desktop/src/main/browser-import/import-service.ts index e824b45fc7f..7f551de41b8 100644 --- a/apps/desktop/src/main/browser-import/import-service.ts +++ b/apps/desktop/src/main/browser-import/import-service.ts @@ -1,4 +1,5 @@ import type { + BrowserBringBackResult, BrowserChromeImportResult, BrowserCredentialConflictPolicy, BrowserImportProfile, @@ -6,6 +7,7 @@ import type { BrowserPasswordImportResult, } from '@sim/desktop-bridge' import { createLogger } from '@sim/logger' +import { sleep } from '@sim/utils/helpers' import { normalizeOrigin, normalizeUsername } from '@/main/browser-credentials/origin' import type { ImportCandidate, ImportOutcome } from '@/main/browser-credentials/vault' import type { ReadCookiesResult } from '@/main/browser-import/chromium-cookies' @@ -95,13 +97,19 @@ async function openBrowserProfile( if (!profile) { throw new ImportFailure('chrome-not-found', 'No matching browser profile.') } - // Each browser has its own Safe Storage item, so the prompt the user sees - // names the browser they actually chose. + return { profile, key: await readBrowserKey(profile, deps) } +} + +/** + * Every profile of one browser shares its Safe Storage item, so one read + * opens them all, and the prompt the user sees names the browser they chose. + */ +async function readBrowserKey(profile: BrowserProfile, deps: ImportServiceDeps): Promise { const safeStoragePassword = await deps.readSafeStoragePassword(profile.source.keychain) if (safeStoragePassword === null) { throw new ImportFailure('keychain-unavailable', 'Keychain access was unavailable.') } - return { profile, key: deriveEncryptionKey(safeStoragePassword) } + return deriveEncryptionKey(safeStoragePassword) } /** @@ -150,27 +158,22 @@ export function toDisplayProfiles(profiles: BrowserProfile[]): BrowserImportProf // Shown on its own in a profile picker, where the browser is already // chosen — so an unnamed profile reads as "Default" rather than blank. profileLabel: name === '' ? directory : name, + opensChosenProfile: source.opensChosenProfile, } }) } /** - * Copies one Chrome profile's cookies into the built-in browser — or, given a - * `scope`, only one site's: the sign-in the user just finished there. + * Copies one Chrome profile's cookies into the built-in browser. * * Fails closed at every step: an unsupported platform, an absent Chrome, a * refused Keychain prompt, or an unrecognised database all stop the import * with a category instead of falling back to a weaker path. The result carries * counts only — no cookie material, domain, or path reaches the caller. - * - * When a read finds no cookies and `lookAgain` resolves true, the profile is read - * once more with the same key, so a second look never re-prompts the Keychain. */ export async function importChromeCookies( profileId: string | undefined, - deps: ImportServiceDeps, - scope?: SiteScope, - lookAgain?: () => Promise + deps: ImportServiceDeps ): Promise { if (deps.platform !== 'darwin') return cookieFailure('unsupported-platform') @@ -178,12 +181,7 @@ export async function importChromeCookies( const open = await openBrowserProfile(profileId, deps) let outcome: CookieOutcome try { - outcome = await runCookieImport(open, deps, scope) - const { cookiesImported, cookiesSkipped, error } = outcome.result - const readNothing = cookiesImported === 0 && cookiesSkipped === 0 && !error - if (readNothing && lookAgain && (await lookAgain())) { - outcome = await runCookieImport(open, deps, scope) - } + outcome = await runCookieImport(open, deps) } finally { zeroKey(open) } @@ -194,6 +192,114 @@ export async function importChromeCookies( } } +/** + * Chromium commits cookie changes to disk every 30 seconds (or 512 changes), + * so a sign-in finished moments ago can still be missing from the database. + * A bring-back that finds nothing for the site reads again on this interval + * until the window closes. + */ +const SIGN_IN_READ_INTERVAL_MS = 3_000 +const SIGN_IN_WAIT_MS = 30_000 + +const RETIRED: BrowserBringBackResult = { cookiesImported: 0, cookiesSkipped: 0, retired: true } + +/** A bring-back that ran for a current handoff and failed. */ +export function bringBackFailure(error: BrowserImportResult['error']): BrowserBringBackResult { + return { ...cookieFailure(error), retired: false } +} + +interface ProfileCookieRead { + profile: BrowserProfile + read: ReadCookiesResult +} + +/** + * Brings one site's sign-in back from `profiles` (all one browser's): from the + * profile that changed the site's cookies last, the earlier one on a tie. + * + * Imports whatever the site has there at once. Only when no profile has any + * cookie for it yet, it reads again until the browser has had time to save a + * sign-in. The key is read once for every profile and every read, so waiting + * never re-prompts the Keychain, and the wait starts after the prompt is + * answered. Nothing is written once `isCurrent` turns false. + */ +export async function importSignInCookies( + profiles: readonly BrowserProfile[], + scope: SiteScope, + isCurrent: () => boolean, + deps: ImportServiceDeps +): Promise { + if (deps.platform !== 'darwin') return bringBackFailure('unsupported-platform') + const [first] = profiles + if (!first) return bringBackFailure('chrome-not-found') + + try { + const key = await readBrowserKey(first, deps) + let latest: ProfileCookieRead | null + try { + latest = await readUntilFound(profiles, key, scope, isCurrent, deps) + } finally { + key.fill(0) + } + if (!latest || !isCurrent()) return RETIRED + const outcome = await writeCookieRead(latest.read, deps) + await rememberImportedSites(outcome.domains, latest.profile, deps) + return { ...outcome.result, retired: false } + } catch (error) { + return bringBackFailure(categorize(error, 'cookie')) + } +} + +/** The latest profile read, once one has the site or the window closes; null once retired. */ +async function readUntilFound( + profiles: readonly BrowserProfile[], + key: Buffer, + scope: SiteScope, + isCurrent: () => boolean, + deps: ImportServiceDeps +): Promise { + const deadline = Date.now() + SIGN_IN_WAIT_MS + let latest = await readLatestProfile(profiles, key, scope, deps) + while (latest.read.rowsSeen === 0 && Date.now() + SIGN_IN_READ_INTERVAL_MS <= deadline) { + await sleep(SIGN_IN_READ_INTERVAL_MS) + if (!isCurrent()) return null + latest = await readLatestProfile(profiles, key, scope, deps) + } + return latest +} + +/** + * Reads the site from every profile and keeps the one that changed it last, + * the earlier profile on a tie. One unreadable profile does not hide a sign-in + * that landed in another. + */ +async function readLatestProfile( + profiles: readonly BrowserProfile[], + key: Buffer, + scope: SiteScope, + deps: ImportServiceDeps +): Promise { + const reads = await Promise.allSettled( + profiles.map(async (profile) => { + if (profile.cookiesPath === null) { + throw new ImportFailure('profile-unreadable', 'The profile has no cookie database.') + } + return { profile, read: await deps.readCookies(profile.cookiesPath, key, scope) } + }) + ) + let latest: ProfileCookieRead | undefined + let firstFailure: unknown + for (const read of reads) { + if (read.status === 'rejected') { + firstFailure ??= read.reason + } else if (!latest || read.value.read.newestChange > latest.read.newestChange) { + latest = read.value + } + } + if (!latest) throw firstFailure + return latest +} + /** What an import half brought over, and the hosts it can vouch for. */ interface CookieOutcome { result: BrowserImportResult @@ -213,14 +319,18 @@ interface PasswordOutcome { */ async function runCookieImport( { profile, key }: OpenProfile, - deps: ImportServiceDeps, - scope?: SiteScope + deps: ImportServiceDeps ): Promise { if (profile.cookiesPath === null) { return { result: cookieFailure('profile-unreadable'), domains: new Set() } } + return writeCookieRead(await deps.readCookies(profile.cookiesPath, key), deps) +} - const read = await deps.readCookies(profile.cookiesPath, key, scope) +async function writeCookieRead( + read: ReadCookiesResult, + deps: ImportServiceDeps +): Promise { const skippedReading = totalSkipped(read.skipped) // Rows present but nothing usable means the profile did not decrypt — // typically a scheme this importer does not support. Report it as a diff --git a/apps/desktop/src/main/browser-import/index.test.ts b/apps/desktop/src/main/browser-import/index.test.ts index 0a3d0e475e3..ac27f96b3c1 100644 --- a/apps/desktop/src/main/browser-import/index.test.ts +++ b/apps/desktop/src/main/browser-import/index.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { BROWSER_SOURCES, type BrowserSource } from '@/main/browser-import/browser-sources' import type { BrowserProfile } from '@/main/browser-import/types' -import { emptySkipCounts } from '@/main/browser-import/types' +import { emptySkipCounts, ImportFailure } from '@/main/browser-import/types' /** * Continuing a sign-in elsewhere and bringing it back, against stand-ins for @@ -58,36 +58,39 @@ afterAll(() => { /** Holds the next browser launch open until the test releases it. */ function holdLaunch(): () => void { - let release: (() => void) | undefined - vi.mocked(openInBrowserProfile).mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - return () => release?.() + const launch = hold(vi.mocked(openInBrowserProfile)) + return () => launch.release(undefined) } +const CHROME = BROWSER_SOURCES.find(({ id }) => id === 'chrome') as BrowserSource const ARC = BROWSER_SOURCES.find(({ id }) => id === 'arc') as BrowserSource -const PROFILE: BrowserProfile = { - id: 'arc:Profile 2', - directory: 'Profile 2', - label: 'Work', - source: ARC, - cookiesPath: '/arc/Profile 2/Cookies', - loginDataPaths: [], - faviconsPath: null, - historyPath: null, + +function profile(source: BrowserSource, directory: string): BrowserProfile { + return { + id: `${source.id}:${directory}`, + directory, + label: '', + source, + cookiesPath: `/${source.id}/${directory}/Cookies`, + loginDataPaths: [], + faviconsPath: null, + historyPath: null, + } } + +const PROFILE = profile(CHROME, 'Profile 2') const SIGN_IN_URL = 'https://signin.aws.amazon.com/oauth?redirect_uri=https%3A%2F%2Fconsole.aws.amazon.com' const request = (url = SIGN_IN_URL, profileId = PROFILE.id) => ({ profileId, tabId: 'tab-1', url }) -function readsCookies(count: number) { - vi.mocked(readBrowserCookies).mockResolvedValue({ +/** A Unix time in milliseconds as Chromium's microseconds since 1601. */ +const chromiumTime = (unixMs: number) => BigInt(unixMs + 11_644_473_600_000) * 1000n + +function cookieRead(count: number, changedMs = 0, name = 'session') { + return { cookies: Array.from({ length: count }, (_, index) => ({ url: 'https://console.aws.amazon.com/', - name: `session-${index}`, + name: `${name}-${index}`, value: 'value', path: '/', secure: true, @@ -96,10 +99,38 @@ function readsCookies(count: number) { })), skipped: emptySkipCounts(), rowsSeen: count, - }) + newestChange: count > 0 ? chromiumTime(Date.now() + changedMs) : 0n, + } +} + +function readsCookies(count: number) { + vi.mocked(readBrowserCookies).mockResolvedValue(cookieRead(count)) +} + +/** Holds the next call of `mock` open until the test releases it with a value. */ +function hold(mock: { mockImplementationOnce: (fn: () => Promise) => unknown }) { + let release: ((value: T) => void) | undefined + mock.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + return { + started: () => release !== undefined, + release: (value: T) => release?.(value), + } +} + +/** Runs a bring-back to completion, through every wait for the browser to save. */ +async function bringBack(scopeId: string) { + const broughtBack = bringSignInBack(scopeId) + await vi.runAllTimersAsync() + return broughtBack } beforeEach(() => { + vi.useRealTimers() vi.mocked(listAllBrowserProfiles).mockResolvedValue([PROFILE]) vi.mocked(openInBrowserProfile).mockResolvedValue() readsCookies(2) @@ -109,14 +140,14 @@ beforeEach(() => { describe('continueSignIn', () => { it('opens the exact page in the chosen profile and remembers it for the chat', async () => { await expect(continueSignIn('chat-a', request())).resolves.toEqual({ - pending: { site: 'amazon.com', browserLabel: 'Arc' }, + pending: { site: 'amazon.com', browserLabel: 'Chrome', broughtBack: false }, + }) + expect(openInBrowserProfile).toHaveBeenCalledWith(CHROME, 'Profile 2', SIGN_IN_URL) + expect(getPendingSignIn('chat-a')).toEqual({ + site: 'amazon.com', + browserLabel: 'Chrome', + broughtBack: false, }) - expect(openInBrowserProfile).toHaveBeenCalledWith( - 'company.thebrowser.Browser', - 'Profile 2', - SIGN_IN_URL - ) - expect(getPendingSignIn('chat-a')).toEqual({ site: 'amazon.com', browserLabel: 'Arc' }) expect(getPendingSignIn('chat-b')).toBeNull() }) @@ -153,119 +184,213 @@ describe('continueSignIn', () => { }) describe('bringSignInBack', () => { - it('imports only the handed-off site from that profile, without rescanning profiles', async () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + it('imports what the profile has for the site at once, and stays pending', async () => { await continueSignIn('chat-a', request()) + // No timers run: a profile that already has the site is never waited on. await expect(bringSignInBack('chat-a')).resolves.toEqual({ - result: { cookiesImported: 2, cookiesSkipped: 0 }, + result: { cookiesImported: 2, cookiesSkipped: 0, retired: false }, handoff: expect.objectContaining({ tabId: 'tab-1', url: SIGN_IN_URL }), - current: true, - }) - expect(readBrowserCookies).toHaveBeenCalledWith('/arc/Profile 2/Cookies', expect.any(Buffer), { - scope: { domain: 'amazon.com', exact: false }, + scopeId: 'chat-a', }) + expect(readBrowserCookies).toHaveBeenCalledOnce() + expect(readBrowserCookies).toHaveBeenCalledWith( + '/chrome/Profile 2/Cookies', + expect.any(Buffer), + { scope: { domain: 'amazon.com', exact: false } } + ) expect(listAllBrowserProfiles).toHaveBeenCalledOnce() - expect(getPendingSignIn('chat-a')).toBeNull() + expect(getPendingSignIn('chat-a')).toEqual({ + site: 'amazon.com', + browserLabel: 'Chrome', + broughtBack: true, + }) + await expect(bringSignInBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 2 }, + }) }) - it('keeps the handoff pending when nothing came back, so the user can retry', async () => { - vi.useFakeTimers() - try { - await continueSignIn('chat-a', request()) - readsCookies(0) - - const broughtBack = bringSignInBack('chat-a') - await vi.runAllTimersAsync() - await expect(broughtBack).resolves.toMatchObject({ - result: { cookiesImported: 0, cookiesSkipped: 0 }, - }) - expect(getPendingSignIn('chat-a')).not.toBeNull() - } finally { - vi.useRealTimers() - } + it('reads again until the browser saves the sign-in, with one Keychain read', async () => { + await continueSignIn('chat-a', request()) + vi.mocked(readBrowserCookies) + .mockResolvedValueOnce(cookieRead(0)) + .mockResolvedValueOnce(cookieRead(0)) + + await expect(bringBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 2, retired: false }, + }) + expect(readBrowserCookies).toHaveBeenCalledTimes(3) + expect(readSafeStoragePassword).toHaveBeenCalledOnce() }) - it('looks once more after a short wait, since browsers save a new sign-in late', async () => { - vi.useFakeTimers() - try { - await continueSignIn('chat-a', request()) - vi.mocked(readBrowserCookies).mockResolvedValueOnce({ - cookies: [], - skipped: emptySkipCounts(), - rowsSeen: 0, - }) + it('gives up after its window when the site never appears', async () => { + await continueSignIn('chat-a', request()) + readsCookies(0) - const broughtBack = bringSignInBack('chat-a') - await vi.runAllTimersAsync() + await expect(bringBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 0, cookiesSkipped: 0, retired: false }, + scopeId: 'chat-a', + }) + // A read at once, then one every 3 s through the 30 s window. + expect(readBrowserCookies).toHaveBeenCalledTimes(11) + expect(getPendingSignIn('chat-a')).toMatchObject({ broughtBack: false }) + }) - await expect(broughtBack).resolves.toMatchObject({ result: { cookiesImported: 2 } }) - expect(readBrowserCookies).toHaveBeenCalledTimes(2) - // The second look reuses the key: no second Keychain prompt. - expect(readSafeStoragePassword).toHaveBeenCalledOnce() - expect(getPendingSignIn('chat-a')).toBeNull() - } finally { - vi.useRealTimers() - } + it('starts the window only once the Keychain prompt is answered', async () => { + await continueSignIn('chat-a', request()) + readsCookies(0) + vi.mocked(readSafeStoragePassword).mockImplementationOnce( + () => new Promise((resolve) => setTimeout(() => resolve('safe-storage-password'), 60_000)) + ) + + await bringBack('chat-a') + expect(readBrowserCookies).toHaveBeenCalledTimes(11) }) - it('does not look again when the cookies were found but could not be stored', async () => { + it('writes nothing once the handoff is cancelled during the Keychain prompt', async () => { await continueSignIn('chat-a', request()) - vi.mocked(importAgentCookies).mockResolvedValueOnce({ imported: 0, failed: 2 }) + const keychain = hold(vi.mocked(readSafeStoragePassword)) + const broughtBack = bringSignInBack('chat-a') + await vi.waitFor(() => expect(keychain.started()).toBe(true)) + cancelSignIn('chat-a') + keychain.release('safe-storage-password') - await expect(bringSignInBack('chat-a')).resolves.toMatchObject({ - result: { cookiesImported: 0, cookiesSkipped: 2 }, + await expect(broughtBack).resolves.toMatchObject({ + result: { cookiesImported: 0, retired: true }, + scopeId: undefined, }) + expect(importAgentCookies).not.toHaveBeenCalled() + }) + + it('writes nothing once the handoff is cancelled during the read', async () => { + await continueSignIn('chat-a', request()) + const read = hold(vi.mocked(readBrowserCookies)) + const broughtBack = bringSignInBack('chat-a') + await vi.waitFor(() => expect(read.started()).toBe(true)) + cancelSignIn('chat-a') + read.release(cookieRead(2)) + + await expect(broughtBack).resolves.toMatchObject({ result: { retired: true } }) + expect(importAgentCookies).not.toHaveBeenCalled() + }) + + it('stops waiting once the handoff is cancelled', async () => { + await continueSignIn('chat-a', request()) + readsCookies(0) + + const broughtBack = bringSignInBack('chat-a') + await vi.waitFor(() => expect(readBrowserCookies).toHaveBeenCalledOnce()) + cancelSignIn('chat-a') + await vi.runAllTimersAsync() + + await expect(broughtBack).resolves.toMatchObject({ result: { retired: true } }) expect(readBrowserCookies).toHaveBeenCalledOnce() }) - it('does not look again once the handoff is cancelled during the wait', async () => { - vi.useFakeTimers() - try { - await continueSignIn('chat-a', request()) - readsCookies(0) - - const broughtBack = bringSignInBack('chat-a') - await vi.waitFor(() => expect(readBrowserCookies).toHaveBeenCalledOnce()) - cancelSignIn('chat-a') - await vi.runAllTimersAsync() - - await expect(broughtBack).resolves.toMatchObject({ current: false }) - expect(readBrowserCookies).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } + it('follows the chat to its saved id when it migrates mid-import', async () => { + await continueSignIn('pending:new-chat', request()) + const read = hold(vi.mocked(readBrowserCookies)) + const broughtBack = bringSignInBack('pending:new-chat') + await vi.waitFor(() => expect(read.started()).toBe(true)) + migrateSignIn('pending:new-chat', 'chat-a') + read.release(cookieRead(2)) + + await expect(broughtBack).resolves.toMatchObject({ + result: { cookiesImported: 2, retired: false }, + scopeId: 'chat-a', + }) + expect(getPendingSignIn('chat-a')).toMatchObject({ broughtBack: true }) + }) + + describe('a browser that opens the page in whichever profile is in front', () => { + const chosen = profile(ARC, 'Default') + const front = profile(ARC, 'Profile 3') + + beforeEach(async () => { + vi.mocked(listAllBrowserProfiles).mockResolvedValue([ + profile(CHROME, 'Default'), + front, + chosen, + ]) + await expect(continueSignIn('chat-a', request(SIGN_IN_URL, chosen.id))).resolves.toEqual({ + pending: { site: 'amazon.com', browserLabel: 'Arc', broughtBack: false }, + }) + expect(openInBrowserProfile).toHaveBeenCalledWith(ARC, 'Default', SIGN_IN_URL) + }) + + it('imports from the profile that changed the site last', async () => { + vi.mocked(readBrowserCookies).mockImplementation(async (path) => + path === front.cookiesPath + ? cookieRead(1, 1_000, 'signed-in') + : cookieRead(2, -60_000, 'consent') + ) + + await expect(bringBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 1 }, + }) + expect( + vi + .mocked(readBrowserCookies) + .mock.calls.map(([path]) => path) + .sort() + ).toEqual(['/arc/Default/Cookies', '/arc/Profile 3/Cookies']) + expect(importAgentCookies).toHaveBeenCalledWith([ + expect.objectContaining({ name: 'signed-in-0' }), + ]) + expect(readSafeStoragePassword).toHaveBeenCalledOnce() + }) + + it('still finds the sign-in when another profile will not read', async () => { + vi.mocked(readBrowserCookies).mockImplementation(async (path) => { + if (path === chosen.cookiesPath) throw new ImportFailure('profile-unreadable', 'locked') + return cookieRead(1, 1_000, 'signed-in') + }) + + await expect(bringBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 1, retired: false }, + }) + }) + + it('reports why when no profile will read', async () => { + vi.mocked(readBrowserCookies).mockRejectedValue( + new ImportFailure('unsupported-schema', 'unknown table') + ) + + await expect(bringBack('chat-a')).resolves.toMatchObject({ + result: { cookiesImported: 0, error: 'unsupported-schema', retired: false }, + }) + expect(importAgentCookies).not.toHaveBeenCalled() + }) }) it('keeps a newer handoff that replaced the one being brought back', async () => { await continueSignIn('chat-a', request()) - const signedIn = await vi.mocked(readBrowserCookies).getMockImplementation()?.( - '', - Buffer.alloc(0) - ) - let finishRead: (() => void) | undefined - vi.mocked(readBrowserCookies).mockImplementationOnce( - () => - new Promise((resolve) => { - finishRead = () => signedIn && resolve(signedIn) - }) - ) + const read = hold(vi.mocked(readBrowserCookies)) const broughtBack = bringSignInBack('chat-a') - await vi.waitFor(() => expect(finishRead).toBeTypeOf('function')) + await vi.waitFor(() => expect(read.started()).toBe(true)) await continueSignIn('chat-a', request('https://accounts.google.com/signin')) - finishRead?.() + read.release(cookieRead(2)) + await expect(broughtBack).resolves.toMatchObject({ - result: { cookiesImported: 2 }, - current: false, + result: { cookiesImported: 0, retired: true }, + scopeId: undefined, + }) + expect(getPendingSignIn('chat-a')).toEqual({ + site: 'google.com', + browserLabel: 'Chrome', + broughtBack: false, }) - - expect(getPendingSignIn('chat-a')).toEqual({ site: 'google.com', browserLabel: 'Arc' }) }) it('answers only to the chat that started the handoff', async () => { await continueSignIn('chat-a', request()) await expect(bringSignInBack('chat-b')).resolves.toEqual({ - result: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }, + result: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false }, }) expect(readBrowserCookies).not.toHaveBeenCalled() }) @@ -299,7 +424,11 @@ describe('a handoff retired or moved while its browser launches', () => { release() await expect(older).resolves.toEqual({}) - expect(getPendingSignIn('chat-a')).toEqual({ site: 'google.com', browserLabel: 'Arc' }) + expect(getPendingSignIn('chat-a')).toEqual({ + site: 'google.com', + browserLabel: 'Chrome', + broughtBack: false, + }) }) it('follows a provisional chat to its saved id, mid-launch or after', async () => { @@ -310,7 +439,7 @@ describe('a handoff retired or moved while its browser launches', () => { release() await continuing - expect(getPendingSignIn('chat-a')).toEqual({ site: 'amazon.com', browserLabel: 'Arc' }) + expect(getPendingSignIn('chat-a')).toMatchObject({ site: 'amazon.com' }) expect(getPendingSignIn('pending:new-chat')).toBeNull() migrateSignIn('chat-a', 'chat-b') await expect(bringSignInBack('chat-b')).resolves.toMatchObject({ diff --git a/apps/desktop/src/main/browser-import/index.ts b/apps/desktop/src/main/browser-import/index.ts index e5f5198dafe..8284f885232 100644 --- a/apps/desktop/src/main/browser-import/index.ts +++ b/apps/desktop/src/main/browser-import/index.ts @@ -1,4 +1,5 @@ import type { + BrowserBringBackResult, BrowserChromeImportResult, BrowserContinueSignInResult, BrowserCredentialConflictPolicy, @@ -7,7 +8,6 @@ import type { BrowserPasswordImportResult, BrowserPendingSignIn, } from '@sim/desktop-bridge' -import { sleep } from '@sim/utils/helpers' import { captureAccountDataGeneration, runAccountDataMutation, @@ -22,8 +22,9 @@ import { readBrowserPasswords } from '@/main/browser-import/chromium-passwords' import { listAllBrowserProfiles } from '@/main/browser-import/chromium-profiles' import { readBrowserSites } from '@/main/browser-import/chromium-site-names' import { - cookieFailure, + bringBackFailure, type ImportServiceDeps, + importSignInCookies, listImportableProfiles, importChromeCookies as runCookieImport, importChromeData as runDataImport, @@ -34,12 +35,6 @@ import type { BrowserProfile } from '@/main/browser-import/types' import { rememberSites } from '@/main/browser-sites' import { isSafeExternalUrl } from '@/main/navigation' -/** - * Chromium writes new cookies to disk in batches, so a sign-in finished - * moments ago can still be missing from the database the importer reads. - */ -const SIGN_IN_LOOK_AGAIN_DELAY_MS = 5_000 - /** * Composition root for the Chrome importer: binds the real Keychain, profile, * database, browser-profile, and vault implementations to the policy in @@ -90,11 +85,16 @@ export function importChromeData( /** A page the user took to another browser to finish signing in. */ interface SignInHandoff { - /** Resolved once, so bringing the sign-in back reads exactly this profile. */ - profile: BrowserProfile + /** + * Resolved once, so bringing the sign-in back reads exactly these: the chosen + * profile, or every profile of a browser that opens the page in whichever is + * in front, the chosen one first. + */ + profiles: BrowserProfile[] tabId: string url: string scope: SiteScope + broughtBack: boolean } /** @@ -109,13 +109,14 @@ interface HandoffSlot { /** At most one per chat: continuing another page replaces the previous slot. */ const slotsByScope = new Map() -function pendingSignIn({ profile, scope }: SignInHandoff): BrowserPendingSignIn { - return { site: scope.domain, browserLabel: profile.source.label } +function pendingSignIn({ profiles, scope, broughtBack }: SignInHandoff): BrowserPendingSignIn { + return { site: scope.domain, browserLabel: profiles[0].source.label, broughtBack } } -function isCurrentSlot(slot: HandoffSlot): boolean { - for (const current of slotsByScope.values()) if (current === slot) return true - return false +/** The chat `slot` belongs to now, which a migration may have changed; undefined once retired. */ +function scopeOfSlot(slot: HandoffSlot): string | undefined { + for (const [scopeId, current] of slotsByScope) if (current === slot) return scopeId + return undefined } /** @@ -139,13 +140,23 @@ export async function continueSignIn( const profiles = await listAllBrowserProfiles().catch(() => []) const profile = profiles.find(({ id }) => id === request.profileId) if (!profile?.cookiesPath) return retire(slot, { error: 'chrome-not-found' }) + const { source } = profile + const profilesToRead = source.opensChosenProfile + ? [profile] + : [profile, ...profiles.filter((other) => other !== profile && other.source.id === source.id)] try { - await openInBrowserProfile(profile.source.bundleId, profile.directory, request.url) + await openInBrowserProfile(source, profile.directory, request.url) } catch { return retire(slot, { error: 'launch-failed' }) } - if (!isCurrentSlot(slot)) return {} - slot.handoff = { profile, tabId: request.tabId, url: request.url, scope } + if (scopeOfSlot(slot) === undefined) return {} + slot.handoff = { + profiles: profilesToRead, + tabId: request.tabId, + url: request.url, + scope, + broughtBack: false, + } return { pending: pendingSignIn(slot.handoff) } } @@ -182,30 +193,32 @@ export function clearSignIns(): void { } /** - * Imports the chat's handed-off site from the profile it was continued in, - * looking once more after a short wait when the first read finds nothing. The - * handoff stays pending until something comes back, so the user can finish - * signing in and try again. `current` is false when a cancel, a newer - * continue, or teardown retired the handoff while it was being imported. + * Imports the chat's handed-off site from the profile that changed it last, + * waiting for the browser to save a sign-in only when there is nothing for the + * site yet. + * + * The handoff stays pending afterwards, so a sign-in the browser saved after + * an early bring-back can be brought back again; the user ends it by + * cancelling or continuing another page. `scopeId` is the chat the handoff + * belongs to once the import is done, which a migration may have changed, and + * is absent when a cancel, a newer continue, or teardown retired it. */ export async function bringSignInBack(scopeId: string): Promise<{ - result: BrowserImportResult + result: BrowserBringBackResult handoff?: { tabId: string; url: string } - current?: boolean + scopeId?: string }> { const slot = slotsByScope.get(scopeId) const handoff = slot?.handoff - if (!slot || !handoff) return { result: cookieFailure('unknown') } - const result = await runCookieImport( - handoff.profile.id, - { ...deps(), listProfiles: async () => [handoff.profile] }, + if (!slot || !handoff) return { result: bringBackFailure('unknown') } + const currentScope = () => (slot.handoff === handoff ? scopeOfSlot(slot) : undefined) + const result = await importSignInCookies( + handoff.profiles, handoff.scope, - async () => { - await sleep(SIGN_IN_LOOK_AGAIN_DELAY_MS) - return isCurrentSlot(slot) && slot.handoff === handoff - } + () => currentScope() !== undefined, + deps() ) - const current = slotsByScope.get(scopeId) === slot && slot.handoff === handoff - if (current && result.cookiesImported > 0) slotsByScope.delete(scopeId) - return { result, handoff, current } + const ownerScopeId = currentScope() + if (ownerScopeId && result.cookiesImported > 0) handoff.broughtBack = true + return { result, handoff, scopeId: ownerScopeId } } diff --git a/apps/desktop/src/main/browser-import/sqlite-source.ts b/apps/desktop/src/main/browser-import/sqlite-source.ts index 2cbb2eb6689..20b6972f978 100644 --- a/apps/desktop/src/main/browser-import/sqlite-source.ts +++ b/apps/desktop/src/main/browser-import/sqlite-source.ts @@ -1,7 +1,7 @@ import { copyFile, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { SQLInputValue } from 'node:sqlite' +import type { DatabaseSync, SQLInputValue } from 'node:sqlite' import { ImportFailure } from '@/main/browser-import/types' /** @@ -18,16 +18,25 @@ import { ImportFailure } from '@/main/browser-import/types' /** SQLite keeps recent writes beside the main file; sidecars are needed for a faithful copy. */ const SQLITE_SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] -async function queryCopy( - databasePath: string, +/** Runs `query` with BigInt reads, for statements against a browser database. */ +export function allRows( + database: DatabaseSync, query: string, - params: readonly SQLInputValue[] -): Promise[]> { + params: readonly SQLInputValue[] = [] +): Record[] { + const statement = database.prepare(query) + // Chrome's microsecond timestamps overflow a JS number's safe integer + // range, which this API rejects unless BigInt reads are enabled. + statement.setReadBigInts(true) + return statement.all(...params) as Record[] +} + +async function readCopy(databasePath: string, read: (database: DatabaseSync) => T): Promise { // Imported lazily: `node:sqlite` is only needed on the import path, and this // keeps module load working on runtimes that lack it. const { DatabaseSync } = await import('node:sqlite') - let database: InstanceType + let database: DatabaseSync try { database = new DatabaseSync(databasePath, { readOnly: true }) } catch { @@ -41,11 +50,7 @@ async function queryCopy( } try { - const statement = database.prepare(query) - // Chrome's microsecond timestamps overflow a JS number's safe integer - // range, which this API rejects unless BigInt reads are enabled. - statement.setReadBigInts(true) - return statement.all(...params) as Record[] + return read(database) } catch { throw new ImportFailure('unsupported-schema', 'The Chrome table is not in a recognised shape.') } finally { @@ -58,12 +63,25 @@ async function queryCopy( * and runs `query` with its bound `params` against the copy. The copy is * always deleted. */ -export async function queryBrowserDatabase( +export function queryBrowserDatabase( sourcePath: string, fileName: string, query: string, params: readonly SQLInputValue[] = [] ): Promise[]> { + return readBrowserDatabase(sourcePath, fileName, (database) => allRows(database, query, params)) +} + +/** + * Copies `sourcePath` like {@link queryBrowserDatabase} and hands the copy to + * `read`, for a reader that must inspect the schema before it queries. A throw + * from `read` reports the schema as unrecognised. + */ +export async function readBrowserDatabase( + sourcePath: string, + fileName: string, + read: (database: DatabaseSync) => T +): Promise { const staging = await mkdtemp(join(tmpdir(), 'sim-chrome-import-')) try { const workingCopy = join(staging, fileName) @@ -76,7 +94,7 @@ export async function queryBrowserDatabase( // Absent sidecars are normal: they only exist while a transaction is live. await copyFile(`${sourcePath}${suffix}`, `${workingCopy}${suffix}`).catch(() => {}) } - return await queryCopy(workingCopy, query, params) + return await readCopy(workingCopy, read) } finally { await rm(staging, { recursive: true, force: true }).catch(() => {}) } diff --git a/apps/desktop/src/main/ipc.test.ts b/apps/desktop/src/main/ipc.test.ts index 7aebaf03453..bf7199c51b2 100644 --- a/apps/desktop/src/main/ipc.test.ts +++ b/apps/desktop/src/main/ipc.test.ts @@ -24,9 +24,9 @@ vi.mock('@/main/browser-import', () => ({ pending: { site: 'example.com', browserLabel: 'Chrome' }, })), bringSignInBack: vi.fn(async () => ({ - result: { cookiesImported: 2, cookiesSkipped: 0 }, + result: { cookiesImported: 2, cookiesSkipped: 0, retired: false }, handoff: { tabId: 'tab-1', url: 'https://signin.example.com/login' }, - current: true, + scopeId: 'chat-signin', })), cancelSignIn: vi.fn(), getPendingSignIn: vi.fn(() => null), @@ -1290,6 +1290,7 @@ describe('registerIpcHandlers', () => { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', + retired: false, }) expect(await bringBack(evilEvent, 'chat-signin')).toMatchObject({ error: 'unknown' }) expect(bringSignInBack).not.toHaveBeenCalled() @@ -1299,6 +1300,7 @@ describe('registerIpcHandlers', () => { await expect(bringBack(activeAppEvent, 'chat-signin')).resolves.toEqual({ cookiesImported: 2, cookiesSkipped: 0, + retired: false, }) expect(bringSignInBack).toHaveBeenCalledWith('chat-signin') expect(panelAction.mock.calls).toEqual([ @@ -1324,11 +1326,10 @@ describe('registerIpcHandlers', () => { focus.mockRestore() }) - it('leaves the tabs alone when a newer continue retired the handoff mid-import', async () => { + it('leaves the tabs alone when the handoff was retired after its cookies were written', async () => { vi.mocked(bringSignInBack).mockResolvedValueOnce({ - result: { cookiesImported: 2, cookiesSkipped: 0 }, + result: { cookiesImported: 2, cookiesSkipped: 0, retired: false }, handoff: { tabId: 'tab-1', url: 'https://signin.example.com/login' }, - current: false, }) await bringBack(activeAppEvent, 'chat-signin') @@ -1336,11 +1337,26 @@ describe('registerIpcHandlers', () => { expect(panelAction).not.toHaveBeenCalled() }) + it('reopens the page in the chat the handoff migrated to mid-import', async () => { + vi.mocked(bringSignInBack).mockResolvedValueOnce({ + result: { cookiesImported: 2, cookiesSkipped: 0, retired: false }, + handoff: { tabId: 'tab-1', url: 'https://signin.example.com/login' }, + scopeId: 'chat-saved', + }) + + await bringBack(activeAppEvent, 'chat-signin') + + expect(panelAction.mock.calls).toEqual([ + ['chat-saved', { action: 'switch-tab', tabId: 'tab-1' }], + ['chat-saved', { action: 'navigate', url: 'https://signin.example.com/login' }], + ]) + }) + it('leaves the tabs alone when nothing came back', async () => { vi.mocked(bringSignInBack).mockResolvedValueOnce({ - result: { cookiesImported: 0, cookiesSkipped: 0 }, + result: { cookiesImported: 0, cookiesSkipped: 0, retired: false }, handoff: { tabId: 'tab-1', url: 'https://signin.example.com/login' }, - current: true, + scopeId: 'chat-signin', }) await bringBack(activeAppEvent, 'chat-signin') diff --git a/apps/desktop/src/main/ipc.ts b/apps/desktop/src/main/ipc.ts index 671edf574f8..d52db89df2a 100644 --- a/apps/desktop/src/main/ipc.ts +++ b/apps/desktop/src/main/ipc.ts @@ -10,6 +10,7 @@ import { isCurrentBrowserToolName, } from '@sim/browser-protocol' import { + type BrowserBringBackResult, ComputerUseError, type ComputerUseToolFailure, type DesktopExecutorDevice, @@ -113,6 +114,12 @@ const logger = createLogger('DesktopIpc') /** Workspace/chat ids are opaque tokens; anything else never reaches a URL. */ const ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/ const TERMINAL_WRITE_CHUNK_CHARACTERS = 64 * 1024 +const BRING_BACK_DENIED: BrowserBringBackResult = { + cookiesImported: 0, + cookiesSkipped: 0, + error: 'unknown', + retired: false, +} function writeTerminalText( terminal: TerminalRegistry, @@ -1568,18 +1575,26 @@ export function registerIpcHandlers(deps: IpcDeps): void { }, // Imports the chat's pending sign-in, then reopens the handed-off page // through the omnibox's navigation path, or in a new tab if it was closed. + // The handoff stays pending, so a later bring-back reopens it again. 'browser-import:bring-sign-in-back': { kind: 'invoke', gate: 'app-origin', requires: 'browser', passSender: true, needsUserActivation: true, - denied: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }, + denied: BRING_BACK_DENIED, handler: async (sender, rawScope) => { - const scopeId = activeRendererScope(browserScopeBySender, sender as WebContents, rawScope) - if (!scopeId) return { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' } - const { result, handoff, current } = await bringSignInBack(scopeId) - if (!handoff || !current || result.cookiesImported === 0) return result + const requestScopeId = activeRendererScope( + browserScopeBySender, + sender as WebContents, + rawScope + ) + if (!requestScopeId) { + return BRING_BACK_DENIED + } + // The chat's id may have migrated while the import ran; reopen in the one it has now. + const { result, handoff, scopeId } = await bringSignInBack(requestScopeId) + if (!handoff || !scopeId || result.cookiesImported === 0) return result const tabOpen = withBrowserScope(scopeId, () => peekTabsState().tabs.some(({ tabId }) => tabId === handoff.tabId) ) diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index 93cbc618c52..8317acc61bb 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -16,6 +16,7 @@ import type { } from '@sim/browser-protocol' import type { BrowserAddToChatPayload, + BrowserBringBackResult, BrowserChromeImportResult, BrowserContinueSignInResult, BrowserCredentialConflictPolicy, @@ -453,7 +454,7 @@ const api: SimDesktopApi = { scopeId: string ): Promise => ipcRenderer.invoke('browser-import:continue-sign-in', profileId, scopeId), - bringSignInBack: (scopeId: string): Promise => + bringSignInBack: (scopeId: string): Promise => ipcRenderer.invoke('browser-import:bring-sign-in-back', scopeId), cancelSignIn: (scopeId: string): Promise => ipcRenderer.invoke('browser-import:cancel-sign-in', scopeId), diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-continue-sign-in.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-continue-sign-in.tsx index 58d3b3f2b72..92c3d06bc5a 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-continue-sign-in.tsx +++ b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-continue-sign-in.tsx @@ -1,14 +1,19 @@ 'use client' +import type { BrowserBringBackResult, BrowserPendingSignIn } from '@sim/desktop-bridge' import { Chip, + DropdownMenu, + DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, + DropdownMenuTrigger, } from '@sim/emcn' -import { X } from '@sim/emcn/icons' +import { ChevronDown, X } from '@sim/emcn/icons' +import { importErrorMessage } from '@/components/browser-import/browser-import-dialog' import { BrowserNotice } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-notice' import type { ContinueSignInController } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/use-continue-sign-in' @@ -18,13 +23,14 @@ interface BrowserContinueSignInMenuItemsProps { afterClose: (action: () => void) => () => void } -/** "Continue in Chrome", or a picker when several browser profiles can take the page. */ +/** "Continue in Chrome", or a picker when several browsers or profiles can take the page. */ export function BrowserContinueSignInMenuItems({ controller, afterClose, }: BrowserContinueSignInMenuItemsProps) { - const { canContinue, profiles, continueIn } = controller + const { canContinue, profiles, replacesPending, continueIn } = controller if (!canContinue) return null + const suffix = replacesPending ? ' instead' : '' return ( <> @@ -32,10 +38,11 @@ export function BrowserContinueSignInMenuItems({ {profiles.length === 1 ? ( void continueIn(profiles[0]))}> Continue in {profiles[0].label} + {suffix} ) : ( - Continue in Browser + Continue in another browser{suffix} {profiles.map((profile) => ( - void bringBack()}> - {importing ? 'Bringing back…' : 'Bring session back'} - - - Cancel + {/* aria-disabled, not disabled: disabling the focused chip would drop keyboard focus. */} + void bringBack()} + > + {bringBackLabel(pending, importing, bringBackOutcome)} + {pending.broughtBack ? 'Done' : 'Cancel'} } /> @@ -89,15 +143,34 @@ export function BrowserContinueSignInNotice({ controller }: BrowserContinueSignI } if (!hintVisible) return null - const [profile] = profiles + const [onlyChoice] = profiles return ( - void continueIn(profile)}> - Continue in {profile.label} - + {profiles.length === 1 ? ( + void continueIn(onlyChoice)}> + Continue in {onlyChoice.label} + + ) : ( + + + + Choose browser + + + + {profiles.map((profile) => ( + void continueIn(profile)}> + {profile.label} + + ))} + + + )} } diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-notice.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-notice.tsx index 9e94c309dea..f97a60c1e6e 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-notice.tsx +++ b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-notice.tsx @@ -6,12 +6,18 @@ interface BrowserNoticeProps { actions: ReactNode } -/** A non-modal notice docked under the browser toolbar; a long message wraps rather than truncating. */ +/** + * A non-modal notice docked under the browser toolbar; a long message wraps + * rather than truncating. Only the message is a live region, so a changing + * button label is not announced a second time. + */ export function BrowserNotice({ message, actions }: BrowserNoticeProps) { return (
-

{message}

+

+ {message} +

{actions}
diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.test.ts b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.test.ts index c6d81c575cd..e407f4cd779 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.test.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.test.ts @@ -16,7 +16,8 @@ describe('signInHintHost', () => { 'https://accounts.google.com/v3/signin/identifier', 'https://signin.aws.amazon.com/oauth', 'https://us-east-1.signin.aws.amazon.com/oauth', - 'https://d-1234567890.awsapps.com/start', + 'https://d-1234567890.awsapps.com/login', + 'https://us-east-1.signin.aws/platform/login', 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', 'https://login.live.com/login.srf', 'https://acme.okta.com/app/UserHome', @@ -35,6 +36,7 @@ describe('signInHintHost', () => { ['the bare wildcard suffix', 'https://okta.com/'], ['the same host over plain http', 'http://accounts.google.com/'], ['a GitHub page that is not a sign-in', 'https://github.com/simstudioai/sim'], + ['the AWS access portal after sign-in', 'https://d-1234567890.awsapps.com/start'], ['a GitHub path that only starts with login', 'https://github.com/loginx'], ['an ordinary site', 'https://example.com/login'], ['a blank tab', 'about:blank'], diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.ts b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.ts index e8f35ff2bc0..729554f9f1b 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/sign-in-hosts.ts @@ -16,7 +16,9 @@ const SIGN_IN_HOSTS: readonly SignInHost[] = [ { host: 'accounts.google.com' }, { host: 'signin.aws.amazon.com' }, { host: 'signin.aws.amazon.com', subdomains: true }, - { host: 'awsapps.com', subdomains: true }, + // Identity Center's `/start` is the signed-in portal; `/login` hands off to `.signin.aws`. + { host: 'awsapps.com', subdomains: true, paths: ['/login'] }, + { host: 'signin.aws', subdomains: true }, { host: 'login.microsoftonline.com' }, { host: 'login.live.com' }, { host: 'okta.com', subdomains: true }, diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/use-continue-sign-in.ts b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/use-continue-sign-in.ts index 62849dc3137..8083939bcb9 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/use-continue-sign-in.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/use-continue-sign-in.ts @@ -1,9 +1,13 @@ 'use client' import { useCallback, useSyncExternalStore } from 'react' -import type { BrowserContinueSignInError, BrowserImportProfile } from '@sim/desktop-bridge' +import type { + BrowserBringBackResult, + BrowserContinueSignInError, + BrowserImportProfile, +} from '@sim/desktop-bridge' import { toast } from '@sim/emcn' -import { importErrorMessage } from '@/components/browser-import/browser-import-dialog' +import type { MutationState } from '@tanstack/react-query' import { continuablePage, signInHintHost, @@ -17,18 +21,37 @@ import { useStartSignInHandoff, } from '@/hooks/queries/browser-import' -const CONTINUE_ERROR_MESSAGES: Record = { - 'chrome-not-found': importErrorMessage('chrome-not-found'), - 'unsupported-page': 'This page can’t be continued in another browser.', - 'launch-failed': 'Could not open that browser.', - unknown: 'Could not open this page in another browser.', +/** An error a newer shell adds reads as unknown. */ +function continueErrorMessage(error: BrowserContinueSignInError, browserLabel: string): string { + switch (error) { + case 'chrome-not-found': + return `That ${browserLabel} profile no longer exists. Choose another one.` + case 'unsupported-page': + return 'This page can’t be continued in another browser.' + case 'launch-failed': + return `Couldn’t open ${browserLabel}. Open it, then try again.` + default: + return `Couldn’t open this page in ${browserLabel}.` + } } -/** As with import errors, a value from a newer shell reads as unknown. */ -function continueErrorMessage(error: BrowserContinueSignInError): string { - return Object.hasOwn(CONTINUE_ERROR_MESSAGES, error) - ? CONTINUE_ERROR_MESSAGES[error] - : CONTINUE_ERROR_MESSAGES.unknown +/** A bring-back that threw reads like one the shell reported as unknown. */ +const FAILED_BRING_BACK: BrowserBringBackResult = { + cookiesImported: 0, + cookiesSkipped: 0, + error: 'unknown', +} + +/** + * The settled bring-back's outcome worth showing, or null. A retired one (the + * handoff was cancelled or replaced while it ran) wrote nothing and is ignored. + */ +function bringBackOutcomeOf( + state: MutationState | undefined +): BrowserBringBackResult | null { + if (state?.status === 'error') return FAILED_BRING_BACK + if (state?.status !== 'success' || !state.data || state.data.retired) return null + return state.data } /** Hosts whose hint the user dismissed, for as long as the app stays open. */ @@ -44,6 +67,30 @@ function subscribeToDismissals(listener: () => void): () => void { const dismissalCount = () => dismissedHintHosts.size +/** + * One choice per profile, except for browsers that open a handed-off page in + * whichever profile is in front (Arc, Dia): those get one choice, named for + * the browser, since picking a profile would not be honored. + */ +function continueChoices(profiles: readonly BrowserImportProfile[]): BrowserImportProfile[] { + const offeredBrowsers = new Set() + const choices: BrowserImportProfile[] = [] + for (const profile of profiles) { + if (profile.opensChosenProfile !== false) { + choices.push(profile) + } else if (!offeredBrowsers.has(profile.browserId)) { + offeredBrowsers.add(profile.browserId) + choices.push({ ...profile, label: profile.browserLabel }) + } + } + return choices +} + +/** Whether `hostname` belongs to the registrable domain `site`. */ +function isOnSite(hostname: string, site: string): boolean { + return hostname === site || hostname.endsWith(`.${site}`) +} + interface UseContinueSignInProps { scopeId: string pageUrl: string | undefined @@ -57,11 +104,14 @@ interface UseContinueSignInProps { */ export function useContinueSignIn({ scopeId, pageUrl }: UseContinueSignInProps) { const supported = supportsContinueSignIn() - const { data: profiles = [] } = useBrowserImportProfiles(supported) + const { data: importProfiles = [] } = useBrowserImportProfiles(supported) + const profiles = continueChoices(importProfiles) const { data: pendingData = null, isSuccess: pendingKnown } = usePendingSignIn(scopeId, supported) const pending = supported ? pendingData : null const { mutateAsync: startHandoff, isPending: starting } = useStartSignInHandoff(scopeId) - const { mutateAsync: importBack, isPending: importing } = useBringSignInBack(scopeId) + const { bringBack: importBack, latest } = useBringSignInBack(scopeId) + const importing = latest?.status === 'pending' + const bringBackOutcome = bringBackOutcomeOf(latest) const { mutate: cancelHandoff } = useCancelSignInHandoff(scopeId) useSyncExternalStore(subscribeToDismissals, dismissalCount, dismissalCount) @@ -71,6 +121,8 @@ export function useContinueSignIn({ scopeId, pageUrl }: UseContinueSignInProps) // also support, so cached profiles alone must not reveal this feature. const canContinue = supported && profiles.length > 0 && page !== null const hintHost = page ? signInHintHost(page) : null + const replacesPending = + pending !== null && page !== null && !isOnSite(page.hostname, pending.site) // Until the shell answers, an existing handoff may be pending; the hint's Continue would replace it. const hintVisible = canContinue && @@ -83,34 +135,27 @@ export function useContinueSignIn({ scopeId, pageUrl }: UseContinueSignInProps) async (profile: BrowserImportProfile) => { try { const result = await startHandoff(profile.id) - if (result.error) toast.error(continueErrorMessage(result.error)) + if (result.error) toast.error(continueErrorMessage(result.error, profile.browserLabel)) } catch { - toast.error(CONTINUE_ERROR_MESSAGES.unknown) + toast.error(continueErrorMessage('unknown', profile.browserLabel)) } }, [startHandoff] ) const bringBack = useCallback(async () => { - if (!pending) return + if (!pending || importing) return const { site, browserLabel } = pending try { const result = await importBack() - if (result.error) { - toast.error(importErrorMessage(result.error)) - } else if (result.cookiesImported === 0 && result.cookiesSkipped > 0) { - toast.error(`Could not import a usable ${site} sign-in from ${browserLabel}.`) - } else if (result.cookiesImported === 0) { - toast.warning( - `${browserLabel} hasn’t saved your ${site} sign-in yet. Wait a few seconds and try again. If the site offers “Stay signed in”, choose it.` - ) - } else { + // An older shell (no `retired`) ends the handoff on success, taking the notice with it. + if (!result.error && result.cookiesImported > 0 && result.retired === undefined) { toast.success(`Brought back your ${site} session from ${browserLabel}`) } } catch { - toast.error(importErrorMessage('unknown')) + // The failure stays in the mutation state, which the notice shows. } - }, [importBack, pending]) + }, [importBack, importing, pending]) const cancel = useCallback(() => cancelHandoff(), [cancelHandoff]) @@ -126,6 +171,8 @@ export function useContinueSignIn({ scopeId, pageUrl }: UseContinueSignInProps) pending, starting, importing, + bringBackOutcome, + replacesPending, hintVisible, continueIn, bringBack, diff --git a/apps/sim/hooks/queries/browser-import.test.tsx b/apps/sim/hooks/queries/browser-import.test.tsx index ce1c1269c9d..81c390eac67 100644 --- a/apps/sim/hooks/queries/browser-import.test.tsx +++ b/apps/sim/hooks/queries/browser-import.test.tsx @@ -1,11 +1,16 @@ /** @vitest-environment jsdom */ import { act } from 'react' -import type { BrowserPendingSignIn } from '@sim/desktop-bridge' +import type { BrowserBringBackResult, BrowserPendingSignIn } from '@sim/desktop-bridge' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { usePendingSignIn, useStartSignInHandoff } from '@/hooks/queries/browser-import' +import { + useBringSignInBack, + useCancelSignInHandoff, + usePendingSignIn, + useStartSignInHandoff, +} from '@/hooks/queries/browser-import' /** The shell's pending sign-ins, by chat scope id. */ let pendingByScope: Record @@ -84,3 +89,79 @@ describe('pending sign-in after a chat is saved mid-handoff', () => { await vi.waitFor(() => expect(shown).toMatchObject({ site: 'github.com' })) }) }) + +describe('bring-back state across remounts and handoffs', () => { + let finishBringBack: ((result: BrowserBringBackResult) => void) | undefined + let bringBack: (() => Promise) | undefined + let cancel: (() => void) | undefined + let latestStatus: string | undefined + + function BringBackPanel({ scopeId }: PanelProps) { + const { bringBack: run, latest } = useBringSignInBack(scopeId) + bringBack = run + latestStatus = latest?.status + cancel = useCancelSignInHandoff(scopeId).mutate + return null + } + + beforeEach(() => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) + Object.assign(window, { + simDesktop: { + browserImport: { + getPendingSignIn: async () => null, + continueSignIn: vi.fn(), + bringSignInBack: () => + new Promise((resolve) => { + finishBringBack = resolve + }), + cancelSignIn: async () => {}, + }, + }, + }) + }) + + afterEach(() => { + act(() => root?.unmount()) + root = undefined + Reflect.deleteProperty(window, 'simDesktop') + }) + + async function mount(client: QueryClient, instance: number) { + root ??= createRoot(document.createElement('div')) + await act(async () => { + root?.render( + + + + ) + }) + } + + it('keeps showing a running check after the panel remounts', async () => { + const client = new QueryClient() + await mount(client, 1) + await act(async () => { + void bringBack?.() + }) + await mount(client, 2) + expect(latestStatus).toBe('pending') + }) + + it('never surfaces a check that settles after its handoff was cancelled', async () => { + const client = new QueryClient() + await mount(client, 1) + let running: Promise | undefined + await act(async () => { + running = bringBack?.() + }) + await act(async () => cancel?.()) + await vi.waitFor(() => expect(latestStatus).toBeUndefined()) + + await act(async () => { + finishBringBack?.({ cookiesImported: 3, cookiesSkipped: 0 }) + await running + }) + expect(latestStatus).toBeUndefined() + }) +}) diff --git a/apps/sim/hooks/queries/browser-import.ts b/apps/sim/hooks/queries/browser-import.ts index 2ef86c3673b..8a8127d2b70 100644 --- a/apps/sim/hooks/queries/browser-import.ts +++ b/apps/sim/hooks/queries/browser-import.ts @@ -1,7 +1,18 @@ 'use client' -import type { BrowserImportProfile, BrowserPendingSignIn } from '@sim/desktop-bridge' -import { type QueryClient, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { + BrowserBringBackResult, + BrowserImportProfile, + BrowserPendingSignIn, +} from '@sim/desktop-bridge' +import { + type MutationState, + type QueryClient, + useMutation, + useMutationState, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import { getDesktopBridge } from '@/lib/desktop' /** Local browser data read through the desktop shell, never the server. */ @@ -10,6 +21,7 @@ const browserImportKeys = { profiles: () => [...browserImportKeys.all, 'profiles'] as const, pendingSignIns: () => [...browserImportKeys.all, 'pending-sign-in'] as const, pendingSignIn: (scopeId: string) => [...browserImportKeys.pendingSignIns(), scopeId] as const, + bringBack: (scopeId: string) => [...browserImportKeys.all, 'bring-back', scopeId] as const, } /** The shell owns a pending sign-in, and every change to it goes through the hooks below. */ @@ -77,7 +89,9 @@ export function useStartSignInHandoff(scopeId: string) { return continueSignIn(profileId, scopeId) }, onSuccess: ({ pending }) => { - if (pending) queryClient.setQueryData(browserImportKeys.pendingSignIn(scopeId), pending) + if (!pending) return + queryClient.setQueryData(browserImportKeys.pendingSignIn(scopeId), pending) + clearBringBacks(queryClient, scopeId) }, // A failed or superseded launch can still retire the chat's previous // handoff, so the shell's answer replaces whatever the cache last held. @@ -85,23 +99,52 @@ export function useStartSignInHandoff(scopeId: string) { }) } +/** + * Forgets the chat's bring-backs once its handoff is replaced or finished, one + * still running included, so the last handoff's outcome never shows under the next. + */ +function clearBringBacks(queryClient: QueryClient, scopeId: string) { + const cache = queryClient.getMutationCache() + for (const mutation of cache.findAll({ + mutationKey: browserImportKeys.bringBack(scopeId), + exact: true, + })) { + cache.remove(mutation) + } +} + +/** + * Brings the chat's pending sign-in back. `latest` is the chat's newest + * bring-back, running or settled, whichever panel instance started it, so a + * check still running after a remount keeps showing as one. + */ export function useBringSignInBack(scopeId: string) { const queryClient = useQueryClient() - return useMutation({ - mutationFn: async () => { + const mutationKey = browserImportKeys.bringBack(scopeId) + const { mutateAsync } = useMutation({ + mutationKey, + mutationFn: async (): Promise => { const bringSignInBack = browserImport()?.bringSignInBack if (!bringSignInBack) throw new Error('Browser import is not available on this device.') return bringSignInBack(scopeId) }, - onSuccess: () => invalidatePendingSignIns(queryClient), + onSettled: () => invalidatePendingSignIns(queryClient), }) + const states = useMutationState({ + filters: { mutationKey, exact: true }, + select: (mutation) => mutation.state as MutationState, + }) + return { bringBack: mutateAsync, latest: states.at(-1) } } export function useCancelSignInHandoff(scopeId: string) { const queryClient = useQueryClient() return useMutation({ mutationFn: async () => browserImport()?.cancelSignIn?.(scopeId), - onSuccess: () => queryClient.setQueryData(browserImportKeys.pendingSignIn(scopeId), null), + onSuccess: () => { + queryClient.setQueryData(browserImportKeys.pendingSignIn(scopeId), null) + clearBringBacks(queryClient, scopeId) + }, onSettled: () => invalidatePendingSignIns(queryClient), }) } diff --git a/packages/desktop-bridge/src/index.ts b/packages/desktop-bridge/src/index.ts index 1356c7a2d8d..0a77d57168c 100644 --- a/packages/desktop-bridge/src/index.ts +++ b/packages/desktop-bridge/src/index.ts @@ -449,6 +449,13 @@ export interface BrowserImportProfile { browserLabel: string /** The profile on its own, e.g. `Microtrades` or `Default`. */ profileLabel: string + /** + * False for a browser that opens a handed-off page in whichever of its + * profiles is in front (Arc, Dia), so a sign-in cannot be sent to one + * profile and is offered once per browser. Absent on older shells, which + * always open the chosen profile. + */ + opensChosenProfile?: boolean } /** @@ -549,7 +556,7 @@ interface SimDesktopBrowserImportApi { */ continueSignIn?(profileId: string, scopeId: string): Promise /** Imports the chat's pending sign-in back. @see continueSignIn */ - bringSignInBack?(scopeId: string): Promise + bringSignInBack?(scopeId: string): Promise /** Drops the chat's pending sign-in. @see continueSignIn */ cancelSignIn?(scopeId: string): Promise /** The chat's pending sign-in, so a remounted panel can keep offering to bring it back. */ @@ -569,6 +576,22 @@ export interface BrowserPendingSignIn { site: string /** The browser it was continued in, e.g. `Chrome`. */ browserLabel: string + /** + * True once a bring-back has imported the site. The handoff stays pending + * until the user is done, so a sign-in the browser saved after an early + * bring-back can still be brought back again. Absent on older shells. + */ + broughtBack?: boolean +} + +/** + * A bring-back's import outcome. `retired` is true when a cancel, a newer + * continue, or sign-out ended the handoff while it was being brought back: + * nothing was written and the result should be ignored. Shells that keep the + * handoff pending after a bring-back always set it; older shells omit it. + */ +export interface BrowserBringBackResult extends BrowserImportResult { + retired?: boolean } /** From 8b212ba9192c3ab7d356c8dfa61beb424e9afdfb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 11:50:59 -0600 Subject: [PATCH 2/3] chore(desktop): keep cookieFailure module-private --- apps/desktop/src/main/browser-import/import-service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop/src/main/browser-import/import-service.ts b/apps/desktop/src/main/browser-import/import-service.ts index 7f551de41b8..9b8cdf18749 100644 --- a/apps/desktop/src/main/browser-import/import-service.ts +++ b/apps/desktop/src/main/browser-import/import-service.ts @@ -58,7 +58,7 @@ export interface ImportServiceDeps { } } -export function cookieFailure(error: BrowserImportResult['error']): BrowserImportResult { +function cookieFailure(error: BrowserImportResult['error']): BrowserImportResult { return { cookiesImported: 0, cookiesSkipped: 0, error } } From c0b7e6e04ce40b0ea537d12ad75d530a3538b42c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 11:52:19 -0600 Subject: [PATCH 3/3] fix(desktop): report cookies the built-in browser refused as nothing imported --- .../src/main/browser-import/import-service.test.ts | 8 ++++++++ apps/desktop/src/main/browser-import/import-service.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/apps/desktop/src/main/browser-import/import-service.test.ts b/apps/desktop/src/main/browser-import/import-service.test.ts index 0943dcbdcf3..315ef50a3d4 100644 --- a/apps/desktop/src/main/browser-import/import-service.test.ts +++ b/apps/desktop/src/main/browser-import/import-service.test.ts @@ -225,6 +225,14 @@ describe('importChromeCookies', () => { error: 'profile-unreadable', }) }) + it('reports cookies the built-in browser refused as nothing usable, not as an empty profile', async () => { + const deps = createDeps({ writeCookies: async () => ({ imported: 0, failed: 1 }) }) + await expect(importChromeCookies(undefined, deps)).resolves.toEqual({ + cookiesImported: 0, + cookiesSkipped: 1, + error: 'nothing-imported', + }) + }) }) describe('importChromePasswords', () => { diff --git a/apps/desktop/src/main/browser-import/import-service.ts b/apps/desktop/src/main/browser-import/import-service.ts index 9b8cdf18749..8de072708d6 100644 --- a/apps/desktop/src/main/browser-import/import-service.ts +++ b/apps/desktop/src/main/browser-import/import-service.ts @@ -349,6 +349,8 @@ async function writeCookieRead( const result: BrowserImportResult = { cookiesImported: written.imported, cookiesSkipped: skippedReading + written.failed, + // Cookies that decrypted but that the built-in browser refused are no more usable. + ...(written.imported === 0 ? { error: 'nothing-imported' as const } : {}), } // Counts only: cookie names, values, domains, and the profile path are // deliberately absent from local diagnostics.