browser: one launch resolver; console fill never reports a hidden error

`console fill --fresh-profile` failed with "Executable doesn't exist ...
chromium-1187" when only Playwright's headless shell was downloaded,
although Google Chrome was installed (also with STOREBOUND_CHROME set).
The Chrome launch did run, but failed because an earlier storebound run
still held the profile, and the fallback rethrew the FIRST error.

Every launch (renders, captures, console profile and copy modes, the
desktop sidecar) now goes through one resolver that checks the exact
executable before trying it:
- headless: STOREBOUND_CHROME, headless shell, full Chromium, Chrome
- visible / persistent: STOREBOUND_CHROME, Google Chrome, full Chromium
  (channel "chromium"); never the headless shell
- copy mode: Google Chrome only
A missing browser is skipped; an installed one that fails reports its own
error; nothing usable names what was looked for plus the doctor /
playwright install hint. A profile whose SingletonLock names a live
process is reported before launching.
This commit is contained in:
CRTkafa 2026-10-12 06:17:19 +08:00
parent db363be37b
commit e21e274c2a
3 changed files with 291 additions and 25 deletions

View file

@ -28,7 +28,7 @@
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os'; import { homedir, tmpdir } from 'node:os';
import { dirname, join } from 'node:path'; import { dirname, join } from 'node:path';
import { chromiumFor, launchPersistent } from '../shots/browser'; import { chromiumFor, type LaunchDeps, launchPersistent } from '../shots/browser';
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
@ -170,6 +170,8 @@ export interface OpenOpts {
platform?: string; platform?: string;
/** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */ /** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */
launchTimeoutMs?: number; launchTimeoutMs?: number;
/** Tests: Playwright's chromium and the installed browsers the launch resolver sees. */
launchDeps?: LaunchDeps;
say: (m: string) => void; say: (m: string) => void;
} }
@ -213,7 +215,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
const endpoint = o.cdp ?? devToolsEndpoint(chromeDir); const endpoint = o.cdp ?? devToolsEndpoint(chromeDir);
if (endpoint) { if (endpoint) {
try { try {
const c = await chromiumFor(root); const c = o.launchDeps?.pw ?? await chromiumFor(root);
const browser = await c.connectOverCDP(endpoint, { timeout: 5000 }); const browser = await c.connectOverCDP(endpoint, { timeout: 5000 });
const context = browser.contexts()[0] ?? await browser.newContext(); const context = browser.contexts()[0] ?? await browser.newContext();
const page = await context.newPage(); const page = await context.newPage();
@ -233,12 +235,11 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
let copy: SessionCopy | null = null; let copy: SessionCopy | null = null;
try { try {
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) }); copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
const c = await chromiumFor(root); const context = await launchPersistent(root, copy.dir, {
const context = await c.launchPersistentContext(copy.dir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}),
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}),
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read // Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'], ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
}); }, { ...o.launchDeps, kind: 'chrome' }); // only real Google Chrome decrypts the owner's cookies
o.say(`browser: your Chrome sign-in (profile "${copy.profile}"). storebound copied only ${copy.files.join(', ')} into a temporary profile` o.say(`browser: your Chrome sign-in (profile "${copy.profile}"). storebound copied only ${copy.files.join(', ')} into a temporary profile`
+ `${copy.filtered ? `, kept only the cookies for App Store Connect and Play Console (${copy.kept ?? 0})` : ' (the whole cookie file: it could not be filtered)'}` + `${copy.filtered ? `, kept only the cookies for App Store Connect and Play Console (${copy.kept ?? 0})` : ' (the whole cookie file: it could not be filtered)'}`
+ ', and deletes it when this run ends. Passwords, history and extensions are never copied. macOS may ask once to let Google Chrome use "Chrome Safe Storage" in your Keychain: that is Chrome reading its own cookies. Opt out: --fresh-profile'); + ', and deletes it when this run ends. Passwords, history and extensions are never copied. macOS may ask once to let Google Chrome use "Chrome Safe Storage" in your Keychain: that is Chrome reading its own cookies. Opt out: --fresh-profile');
@ -253,7 +254,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
} }
// (c) storebound's persistent profile, the owner signs in there // (c) storebound's persistent profile, the owner signs in there
mkdirSync(o.profileDir, { recursive: true }); mkdirSync(o.profileDir, { recursive: true });
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}) }); const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}) }, { ...o.launchDeps, kind: 'visible' });
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`); o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
const page = await ownTab(context); const page = await ownTab(context);
return wrapContext('profile', context, page, () => { /* kept on purpose */ }); return wrapContext('profile', context, page, () => { /* kept on purpose */ });

View file

@ -2,7 +2,23 @@
// project that never renders screenshots never downloads a browser. The compiled desktop sidecar carries its own // project that never renders screenshots never downloads a browser. The compiled desktop sidecar carries its own
// playwright-core (tools/build-sidecars.ts bundles it) and renders with the Chrome for Testing the desktop app manages // playwright-core (tools/build-sidecars.ts bundles it) and renders with the Chrome for Testing the desktop app manages
// (STOREBOUND_CHROME), so desktop users need neither playwright nor a browser in their project. // (STOREBOUND_CHROME), so desktop users need neither playwright nor a browser in their project.
// Launch order: STOREBOUND_CHROME, Playwright's own Chromium, then an installed Google Chrome (channel "chrome"). // Every browser storebound launches goes through ONE resolver (`launchCandidates` / `withCandidates`), which checks the
// exact executable each candidate would use before trying it:
// - headless renders and captures: STOREBOUND_CHROME, Playwright's headless shell, Playwright's full Chromium
// (channel "chromium"), then Google Chrome (channel "chrome").
// - visible / persistent windows (`console fill`): STOREBOUND_CHROME, Google Chrome (channel "chrome"), then
// Playwright's full Chromium (channel "chromium"). Never the headless shell: it has no window, and it drops session
// cookies (no --restore-last-session), so a sign-in would not survive.
// - "chrome" (console fill's copy of the owner's Chrome sign-in: only real Google Chrome can decrypt those cookies
// with its own Keychain key): Google Chrome only.
// A candidate that is not installed is skipped; one that IS installed but fails to start stops the search with its own
// error (an earlier "Executable doesn't exist" never hides it). A persistent profile another browser still holds (its
// SingletonLock names a live process) is reported as such before anything is launched.
// Sources (checked October 2026): Playwright BrowserType.launch / launchPersistentContext `channel` ("chrome";
// "chromium" = the full Chromium build, new headless mode) https://playwright.dev/docs/browsers#chromium-new-headless-mode ;
// Google Chrome channel locations https://playwright.dev/docs/browsers#google-chrome--microsoft-edge
import { existsSync, readlinkSync } from 'node:fs';
import { hostname } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import { compiled } from '../lib/runner'; import { compiled } from '../lib/runner';
@ -19,31 +35,137 @@ async function chromium(root: string): Promise<any> {
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)'); throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
} }
/** Playwright's chromium (same resolution as `launch`), for connectOverCDP and Chrome-channel launches. */ /** Playwright's chromium (same resolution as `launch`), for connectOverCDP. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const chromiumFor = (root: string): Promise<any> => chromium(root); export const chromiumFor = (root: string): Promise<any> => chromium(root);
// eslint-disable-next-line @typescript-eslint/no-explicit-any /** What a launch is for: a headless render, a visible / persistent window, or real Google Chrome only. */
export async function launch(root: string, opts: Record<string, unknown>): Promise<any> { export type LaunchKind = 'headless' | 'visible' | 'chrome';
const c = await chromium(root);
// the desktop app's own Chrome for Testing (or any Chrome the user points at) /** The executables on this machine (null: not there). */
const exe = process.env.STOREBOUND_CHROME; export interface Installed {
if (exe) { try { return await c.launch({ ...opts, executablePath: exe }); } catch { /* fall back below */ } } /** STOREBOUND_CHROME when set and present. */
try { return await c.launch(opts); } catch (e) { storeboundChrome: string | null;
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; } /** Google Chrome where Playwright's channel "chrome" looks for it. */
chrome: string | null;
/** Playwright's full Chromium build (chromium.executablePath()) when present. */
chromium: string | null;
}
export interface Candidate {
label: string;
/** Merged into the launch options. */
opts: Record<string, unknown>;
}
/** Where Playwright's channel "chrome" finds Google Chrome (stable). */
export function chromeChannelPaths(platform: string = process.platform, env: Record<string, string | undefined> = process.env): string[] {
if (platform === 'darwin') return ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'];
if (platform === 'win32') return [env.LOCALAPPDATA, env.PROGRAMFILES, env['PROGRAMFILES(X86)']].filter((d): d is string => !!d).map(d => join(d, 'Google', 'Chrome', 'Application', 'chrome.exe'));
return ['/opt/google/chrome/chrome'];
}
/** The executables present, as the resolver sees them. `pw`: Playwright's chromium. */
export function installedBrowsers(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pw: any, env: Record<string, string | undefined> = process.env, exists: (p: string) => boolean = existsSync, platform: string = process.platform,
): Installed {
let full: string | null = null;
try { const p = pw?.executablePath?.(); if (typeof p === 'string' && p && exists(p)) full = p; } catch { /* not resolvable */ }
return {
storeboundChrome: env.STOREBOUND_CHROME && exists(env.STOREBOUND_CHROME) ? env.STOREBOUND_CHROME : null,
chrome: chromeChannelPaths(platform, env).find(p => exists(p)) ?? null,
chromium: full,
};
}
/**
* The launch order for `kind` (see the header), only candidates whose executable is present. The headless shell has
* no public path: it is always tried first for headless renders (skipped quietly when it is not downloaded).
*/
export function launchCandidates(kind: LaunchKind, i: Installed): Candidate[] {
const out: Candidate[] = [];
if (i.storeboundChrome && kind !== 'chrome') out.push({ label: `STOREBOUND_CHROME (${i.storeboundChrome})`, opts: { executablePath: i.storeboundChrome } });
const chrome: Candidate | null = i.chrome ? { label: `Google Chrome (${i.chrome})`, opts: { channel: 'chrome' } } : null;
const full: Candidate | null = i.chromium ? { label: `Playwright Chromium (${i.chromium})`, opts: { channel: 'chromium' } } : null;
if (kind === 'headless') {
out.push({ label: 'Playwright headless shell', opts: {} });
if (full) out.push(full);
if (chrome) out.push(chrome);
} else if (kind === 'visible') {
if (chrome) out.push(chrome);
if (full) out.push(full);
} else if (chrome) out.push(chrome);
return out;
}
const LOOKED_FOR: Record<LaunchKind, string> = {
headless: 'STOREBOUND_CHROME, Playwright\'s headless shell or Chromium, Google Chrome',
visible: 'STOREBOUND_CHROME, Google Chrome, Playwright\'s full Chromium; never the headless shell (no window, no kept sign-in)',
chrome: 'Google Chrome',
};
/** Playwright's "no such browser" errors (build not downloaded, Chrome channel not installed). */
export const notInstalled = (e: unknown): boolean =>
/Executable doesn't exist|distribution '[^']+' is not found|Failed to launch .* because executable/i.test((e as Error | undefined)?.message ?? '');
/**
* Tries the candidates of `kind` in order with `start(opts)`. A missing browser moves on; an installed browser that
* fails stops with its own error (labelled). Nothing usable: an error naming what was looked for, and the fix.
*/
export async function withCandidates<T>(kind: LaunchKind, i: Installed, start: (opts: Record<string, unknown>) => Promise<T>, env: Record<string, string | undefined> = process.env): Promise<T> {
const skipped: string[] = [];
if (env.STOREBOUND_CHROME && !i.storeboundChrome && kind !== 'chrome') skipped.push(`STOREBOUND_CHROME ${env.STOREBOUND_CHROME}: no such file`);
for (const c of launchCandidates(kind, i)) {
try { return await start(c.opts); } catch (e) {
if (notInstalled(e)) { skipped.push(`${c.label}: not installed`); continue; }
throw new Error(`${c.label} did not start: ${(e as Error).message.split('\n')[0]}`, { cause: e });
}
} }
throw new Error(`no usable browser (looked for ${LOOKED_FOR[kind]})${skipped.length ? `; ${skipped.join('; ')}` : ''}. `
+ (kind === 'chrome' ? 'Install Google Chrome.' : 'Install Google Chrome, or run `bunx playwright install chromium` in your project; `storebound doctor` lists what is missing.'));
}
/**
* The live process (pid) that still holds a Chromium profile: its SingletonLock ("<host>-<pid>") names a running
* process on this machine. Else null (also on Windows, which has no symlink lock).
*/
export function profileHolder(userDataDir: string, alive: (pid: number) => boolean = pidAlive, host: string = hostname()): number | null {
let target: string;
try { target = readlinkSync(join(userDataDir, 'SingletonLock')); } catch { return null; }
const m = target.match(/^(.*)-(\d+)$/);
if (!m || m[1] !== host) return null;
const pid = Number(m[2]);
return alive(pid) ? pid : null;
}
function pidAlive(pid: number): boolean {
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
}
/** Test seam: Playwright's chromium and the installed browsers (default: resolved from `root` and this machine). */
export interface LaunchDeps {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pw?: any;
installed?: Installed;
}
/** A browser for renders and captures (headless unless `headless: false`). */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launch(root: string, opts: Record<string, unknown>, deps: LaunchDeps = {}): Promise<any> {
const c = deps.pw ?? await chromium(root);
const kind: LaunchKind = opts.headless === false ? 'visible' : 'headless';
return withCandidates(kind, deps.installed ?? installedBrowsers(c), o => c.launch({ ...opts, ...o }));
} }
/** /**
* A persistent browser profile (cookies of a console sign-in the owner did by hand stay there between runs; storebound * A persistent browser profile (cookies of a console sign-in the owner did by hand stay there between runs; storebound
* never reads them). Same resolution and launch order as `launch`. Used by `storebound console fill` (visible window). * never reads them). Used by `storebound console fill`: always a real Chrome / Chromium (kind "visible", also when a
* test asks for headless), or Google Chrome only (kind "chrome", the copy of the owner's sign-in).
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launchPersistent(root: string, userDataDir: string, opts: Record<string, unknown>): Promise<any> { export async function launchPersistent(root: string, userDataDir: string, opts: Record<string, unknown>, deps: LaunchDeps & { kind?: 'visible' | 'chrome' } = {}): Promise<any> {
const c = await chromium(root); const holder = profileHolder(userDataDir);
const exe = process.env.STOREBOUND_CHROME; if (holder) throw new Error(`the browser profile ${userDataDir} is still open in another browser (process ${holder}), probably an earlier storebound run that waits for its window to close. Close that window (or end that run) and start again`);
if (exe) { try { return await c.launchPersistentContext(userDataDir, { ...opts, executablePath: exe }); } catch { /* fall back below */ } } const c = deps.pw ?? await chromium(root);
try { return await c.launchPersistentContext(userDataDir, opts); } catch (e) { return withCandidates(deps.kind ?? 'visible', deps.installed ?? installedBrowsers(c), o => c.launchPersistentContext(userDataDir, { ...opts, ...o }));
try { return await c.launchPersistentContext(userDataDir, { ...opts, channel: 'chrome' }); } catch { throw e; }
}
} }

View file

@ -0,0 +1,143 @@
// The one browser resolver (cli/shots/browser.ts): which executable each launch kind uses, checked against a fake
// Playwright cache layout, never launching a real browser. Regression: with only chromium_headless_shell-<rev> in the
// cache, `console fill --fresh-profile` reported "Executable doesn't exist ... chromium-<rev>" although Google Chrome
// was installed (the Chrome error was hidden behind the first one; that Chrome failed because an earlier run still
// held the profile).
import { afterAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
import { openConsoleBrowser } from '../cli/console/session';
import { installedBrowsers, launch, launchCandidates, launchPersistent, profileHolder } from '../cli/shots/browser';
/* eslint-disable @typescript-eslint/no-explicit-any */
const tmp = mkdtempSync(join(tmpdir(), 'sb-browser-resolve-'));
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
const CHROME = '/opt/google/chrome/chrome'; // channel "chrome" on linux
/** A Playwright cache with the given builds (dirs) and a fake chromium whose launches are recorded. */
function fakeCache(name: string, builds: string[], opts: { chrome?: boolean; fail?: (o: any) => Error | null } = {}) {
const cache = join(tmp, name);
for (const b of builds) {
const exe = b.startsWith('chromium-') ? join(cache, b, 'chrome-linux', 'chrome') : join(cache, b, 'chrome-linux', 'headless_shell');
mkdirSync(join(exe, '..'), { recursive: true });
writeFileSync(exe, '');
}
const fullPath = join(cache, 'chromium-1187', 'chrome-linux', 'chrome');
const shellPresent = builds.some(b => b.startsWith('chromium_headless_shell-'));
const calls: any[] = [];
const start = (o: any) => {
calls.push(o);
const f = opts.fail?.(o);
if (f) throw f;
// what Playwright does: no channel + headless -> the headless shell; channel chromium / no channel headed -> full build
const exe = o.executablePath ?? (o.channel === 'chrome' ? (opts.chrome ? CHROME : null) : (!o.channel && o.headless !== false) ? (shellPresent ? 'shell' : null) : existsSync(fullPath) ? fullPath : null);
if (!exe) throw new Error(`browserType.launch: Executable doesn't exist at ${fullPath}`);
return { exe, pages: () => [], newPage: async () => ({ close: async () => {} }), on: () => {}, close: async () => {} };
};
const pw = { executablePath: () => fullPath, launch: async (o: any) => start(o), launchPersistentContext: async (_dir: string, o: any) => start(o) };
const exists = (p: string) => p === CHROME ? !!opts.chrome : existsSync(p);
const installed = installedBrowsers(pw, {}, exists, 'linux');
return { pw, calls, installed };
}
describe('launch order', () => {
test('visible / persistent: Google Chrome, then full Chromium, never the headless shell', () => {
expect(launchCandidates('visible', { storeboundChrome: null, chrome: CHROME, chromium: '/c' }).map(c => c.opts)).toEqual([{ channel: 'chrome' }, { channel: 'chromium' }]);
expect(launchCandidates('visible', { storeboundChrome: null, chrome: null, chromium: null })).toEqual([]);
});
test('headless: headless shell, full Chromium, Google Chrome', () => {
expect(launchCandidates('headless', { storeboundChrome: null, chrome: CHROME, chromium: '/c' }).map(c => c.opts)).toEqual([{}, { channel: 'chromium' }, { channel: 'chrome' }]);
});
test('STOREBOUND_CHROME first for every kind but the Chrome-only copy mode', () => {
const i = { storeboundChrome: '/x/chrome', chrome: CHROME, chromium: null };
expect(launchCandidates('headless', i)[0]!.opts).toEqual({ executablePath: '/x/chrome' });
expect(launchCandidates('visible', i)[0]!.opts).toEqual({ executablePath: '/x/chrome' });
expect(launchCandidates('chrome', i).map(c => c.opts)).toEqual([{ channel: 'chrome' }]);
});
});
describe('fake Playwright cache', () => {
test('headless shell only + Google Chrome: console (persistent) uses Chrome, renders use the shell', async () => {
const f = fakeCache('shell-only', ['chromium_headless_shell-1187'], { chrome: true });
expect(f.installed.chromium).toBeNull();
const ctx = await launchPersistent(tmp, join(tmp, 'p1'), { headless: false }, { pw: f.pw, installed: f.installed });
expect(ctx.exe).toBe(CHROME);
expect(f.calls).toEqual([{ headless: false, channel: 'chrome' }]);
// a test asking for headless still gets a real Chrome, not the shell
const h = await launchPersistent(tmp, join(tmp, 'p1'), { headless: true }, { pw: f.pw, installed: f.installed });
expect(h.exe).toBe(CHROME);
const r = await launch(tmp, { headless: true }, { pw: f.pw, installed: f.installed });
expect(r.exe).toBe('shell');
});
test('full Chromium only: console uses it via channel "chromium"', async () => {
const f = fakeCache('full-only', ['chromium-1187']);
const ctx = await launchPersistent(tmp, join(tmp, 'p2'), { headless: true }, { pw: f.pw, installed: f.installed });
expect(ctx.exe).toBe(f.installed.chromium!);
expect(f.calls[0].channel).toBe('chromium');
});
test('headless render without the shell falls back to full Chromium', async () => {
const f = fakeCache('render-full', ['chromium-1187'], { chrome: true });
const r = await launch(tmp, { headless: true }, { pw: f.pw, installed: f.installed });
expect(r.exe).toBe(f.installed.chromium!);
});
test('nothing usable: a clear error naming what was looked for and the fix', async () => {
const f = fakeCache('empty', ['chromium_headless_shell-1187']);
const e = await launchPersistent(tmp, join(tmp, 'p3'), {}, { pw: f.pw, installed: f.installed }).catch(x => x as Error);
expect((e as Error).message).toContain('no usable browser');
expect((e as Error).message).toContain('Google Chrome');
expect((e as Error).message).toContain('never the headless shell');
expect((e as Error).message).toContain('bunx playwright install chromium');
expect((e as Error).message).toContain('storebound doctor');
expect(f.calls).toEqual([]);
});
test('an installed browser that fails reports its own error, not an earlier "Executable doesn\'t exist"', async () => {
const f = fakeCache('chrome-fails', ['chromium_headless_shell-1187'], { chrome: true, fail: o => o.channel === 'chrome' ? new Error('Target page, context or browser has been closed') : null });
const e = await launchPersistent(tmp, join(tmp, 'p4'), {}, { pw: f.pw, installed: f.installed }).catch(x => x as Error);
expect((e as Error).message).toMatch(/^Google Chrome .* did not start: Target page/);
expect((e as Error).message).not.toContain("Executable doesn't exist");
});
});
describe('profile held by another browser', () => {
test('a SingletonLock naming a live process is reported before any launch', async () => {
const dir = join(tmp, 'locked');
mkdirSync(dir);
symlinkSync(`${hostname()}-${process.pid}`, join(dir, 'SingletonLock'));
expect(profileHolder(dir)).toBe(process.pid);
const f = fakeCache('locked-cache', [], { chrome: true });
const e = await launchPersistent(tmp, dir, {}, { pw: f.pw, installed: f.installed }).catch(x => x as Error);
expect((e as Error).message).toContain(`is still open in another browser (process ${process.pid})`);
expect(f.calls).toEqual([]);
});
test('a stale lock (dead process, other host) is ignored', () => {
const dir = join(tmp, 'stale');
mkdirSync(dir);
symlinkSync(`${hostname()}-999999`, join(dir, 'SingletonLock'));
expect(profileHolder(dir, () => false)).toBeNull();
expect(profileHolder(dir, () => true, 'another-host')).toBeNull();
expect(profileHolder(join(tmp, 'no-such-dir'))).toBeNull();
});
});
describe('console fill', () => {
test('the persistent launch gets executablePath = STOREBOUND_CHROME when it is set', async () => {
const exe = join(tmp, 'Chrome for Testing');
writeFileSync(exe, '');
const before = process.env.STOREBOUND_CHROME;
process.env.STOREBOUND_CHROME = exe;
try {
const f = fakeCache('sb-chrome', ['chromium_headless_shell-1187'], { chrome: true });
const b = await openConsoleBrowser(tmp, { store: 'apple', fresh: true, profileDir: join(tmp, 'sb-profile'), say: () => {}, launchDeps: { pw: f.pw } });
expect(b.mode).toBe('profile');
expect(f.calls).toHaveLength(1);
expect(f.calls[0].executablePath).toBe(exe);
expect(f.calls[0].channel).toBeUndefined();
expect(f.calls[0].args).toContain('--restore-last-session');
} finally {
if (before === undefined) delete process.env.STOREBOUND_CHROME; else process.env.STOREBOUND_CHROME = before;
}
});
});