mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-14 17:05:28 +02:00
fix(browse): XProtect launch-kill self-heal — classify, quarantine-clear, bounded reinstall (P0 #2554)
macOS XProtect definition updates can start SIGKILLing the exact Chromium revision the lockfile pins (xprotectd killed revision 1208's headless shell at spawn; the failure surfaced as a generic launch timeout). New browse/src/xprotect-heal.ts heals it, once per process: - Classifier (F9): positive signatures sourced from the #2554 report + Playwright's launch-error format (signal=SIGKILL process-exit lines, and launch timeout WITH a <launched> marker), negative-checked FIRST against missing executable, spawn EACCES/EPERM, Linux sandbox denials, and plain exitCode=1 crashes. darwin-gated. - Heal (F4 one-shot, in-memory flag): clears com.apple.quarantine via `xattr -dr` on chromium* revision dirs in the Playwright cache ONLY — never a GSTACK_CHROMIUM_PATH bundle (probePoisonedChromiumBundle's scope contract, double-gated at the call sites via usesCustomExecutable). - Reinstall (E1/ENG-OV3): `bunx playwright install --force chromium` run FROM THE GSTACK INSTALL ROOT — the root whose node_modules/playwright-core/browsers.json pins the SAME chromium revision our embedded playwright-core expects (a cwd-resolved bunx would fetch latest and heal to the wrong revision). Bounded at 120s with a process-GROUP SIGKILL on timeout; on any heal failure the caller gets the ORIGINAL launch error + manual `bunx playwright install chromium` guidance — the CLI never hangs. - Verification (F9): post-install asserts the REGISTRY-derived executable path exists (the revision dir playwright-core 1.62.1 expects), not merely install exit 0. - Logging (F11): every action emits one structured stderr line ([browse:xprotect-heal] JSON). All three launch sites in browser-manager.ts (headless launch, headed launchPersistentContext, handoff relaunch) route through launchWithXProtectHeal with one post-heal retry. setup's ensure_playwright_browser failure path gains the same quarantine-clear (_clear_playwright_quarantine, Darwin-only, Playwright cache scope) before its Chromium reinstall. Tests: browse/test/xprotect-heal.test.ts — 33 pass (classifier both polarities, one-shot guard incl. failed-heal consumption, custom-executable scope, registry-revision expectation vs playwright-core browsers.json, install-root revision matching, quarantine-clear scope, wrapper retry + guidance surfacing). browser-manager unit/custom-chromium: 36 pass. bridge-chromium-e2e real-launch smoke: 3 pass. setup-windows-fallback ln-invariant: 9 pass. bash -n setup: clean. Fixes #2554. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
2851535f3b
commit
822de7d0c3
@@ -22,6 +22,7 @@ import { emitActivity } from './activity';
|
||||
import { validateNavigationUrl } from './url-validation';
|
||||
import { TabSession, type RefEntry } from './tab-session';
|
||||
import { resolveChromiumProfile, cleanSingletonLocks } from './config';
|
||||
import { launchWithXProtectHeal } from './xprotect-heal';
|
||||
import { withCdpSession } from './cdp-bridge';
|
||||
import type { MemorySnapshot, MemoryStructureStats, MemoryTabSnapshot, MemoryProcess } from './memory-snapshot';
|
||||
|
||||
@@ -458,7 +459,12 @@ export class BrowserManager {
|
||||
console.log(`[browse] Extensions loaded from: ${extensionsDir}`);
|
||||
}
|
||||
|
||||
this.browser = await chromium.launch({
|
||||
// XProtect self-heal wrapper (P0 #2554): a macOS definition update can
|
||||
// start SIGKILLing the pinned Chromium at spawn. On the classified
|
||||
// signature, clear quarantine on the Playwright cache + force-reinstall
|
||||
// once, then retry this launch once. This headless path always uses the
|
||||
// Playwright cache (no executablePath), so the heal is never scoped out.
|
||||
this.browser = await launchWithXProtectHeal(() => chromium.launch({
|
||||
headless: useHeadless,
|
||||
// On Windows, Chromium's sandbox fails when the server is spawned through
|
||||
// the Bun→Node process chain (GitHub #276). Disable it — local daemon
|
||||
@@ -468,7 +474,7 @@ export class BrowserManager {
|
||||
chromiumSandbox: shouldEnableChromiumSandbox(),
|
||||
...(launchArgs.length > 0 ? { args: launchArgs } : {}),
|
||||
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
|
||||
});
|
||||
}));
|
||||
|
||||
// Chromium disconnect → distinguish clean user-quit from crash. Both
|
||||
// events look identical to Playwright (one 'disconnected' fires), but
|
||||
@@ -651,7 +657,11 @@ export class BrowserManager {
|
||||
// three more (--disable-popup-blocking, --disable-component-update,
|
||||
// --disable-default-apps — each a documented automation tell per Patchright).
|
||||
const { STEALTH_IGNORE_DEFAULT_ARGS } = await import('./stealth');
|
||||
this.context = await chromium.launchPersistentContext(userDataDir, {
|
||||
// XProtect self-heal wrapper (P0 #2554). usesCustomExecutable scopes the
|
||||
// heal out when GSTACK_CHROMIUM_PATH supplies the bundle — that bundle
|
||||
// belongs to the wrapper/embedder and is never quarantine-cleared or
|
||||
// reinstalled over (probePoisonedChromiumBundle's scope contract).
|
||||
this.context = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
|
||||
headless: false,
|
||||
// Match the sandbox policy used by launch() above. Without this,
|
||||
// Playwright auto-adds --no-sandbox on every headed launch and the user
|
||||
@@ -663,7 +673,7 @@ export class BrowserManager {
|
||||
...(executablePath ? { executablePath } : {}),
|
||||
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
|
||||
ignoreDefaultArgs: STEALTH_IGNORE_DEFAULT_ARGS,
|
||||
});
|
||||
}), { usesCustomExecutable: Boolean(executablePath) });
|
||||
this.browser = this.context.browser();
|
||||
this.connectionMode = 'headed';
|
||||
this.intentionalDisconnect = false;
|
||||
@@ -1702,7 +1712,10 @@ export class BrowserManager {
|
||||
// The handoff path (headless → headed re-launch) takes the same
|
||||
// anti-detection posture.
|
||||
const { STEALTH_IGNORE_DEFAULT_ARGS } = await import('./stealth');
|
||||
newContext = await chromium.launchPersistentContext(userDataDir, {
|
||||
// XProtect self-heal wrapper (P0 #2554): handoff always launches the
|
||||
// Playwright-cache bundle (no executablePath), so the heal applies
|
||||
// exactly as in launch()/launchHeaded().
|
||||
newContext = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
|
||||
headless: false,
|
||||
// Match the sandbox policy used by launchHeaded() / launch(). The
|
||||
// handoff path is the headless→headed re-launch and shares the same
|
||||
@@ -1713,7 +1726,7 @@ export class BrowserManager {
|
||||
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
|
||||
ignoreDefaultArgs: STEALTH_IGNORE_DEFAULT_ARGS,
|
||||
timeout: 15000,
|
||||
});
|
||||
}));
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return `ERROR: Cannot open headed browser — ${msg}. Headless browser still running.`;
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
/**
|
||||
* XProtect launch-kill self-heal (P0 #2554).
|
||||
*
|
||||
* macOS XProtect definition updates can start killing the exact Chromium
|
||||
* revision the committed bun.lock pins (observed: revision 1208 under
|
||||
* playwright 1.58.2 — xprotectd SIGKILLs chrome-headless-shell at spawn, so
|
||||
* the failure surfaces as a Playwright launch timeout or a "Browser closed"
|
||||
* error carrying `signal=SIGKILL`, never anything naming XProtect).
|
||||
*
|
||||
* The heal, in order, at most ONCE per process (F4):
|
||||
* 1. Classify the launch failure against the XProtect kill signature
|
||||
* (positive AND negative fixtures under test, F9).
|
||||
* 2. Clear com.apple.quarantine on the Playwright cache bundles ONLY —
|
||||
* a GSTACK_CHROMIUM_PATH bundle belongs to the wrapper/embedder and is
|
||||
* never touched (same scope contract as probePoisonedChromiumBundle).
|
||||
* 3. Force-reinstall Chromium FROM THE GSTACK INSTALL ROOT (ENG-OV3: the
|
||||
* root whose node_modules pins the same playwright-core our compiled
|
||||
* binary embeds — a cwd-resolved `bunx playwright install` would fetch
|
||||
* the LATEST playwright's revision, which the embedded playwright-core
|
||||
* won't find, and the one-shot guard would then block the retry).
|
||||
* The install is BOUNDED (~120s, process-GROUP kill on timeout; E1).
|
||||
* 4. Verify the revision dir the embedded playwright-core EXPECTS exists
|
||||
* post-heal (registry-derived expectation, not merely install exit 0).
|
||||
*
|
||||
* Every action emits one structured stderr line (F11). When the heal cannot
|
||||
* complete (offline, timeout, no install root, one-shot spent), the caller
|
||||
* surfaces the ORIGINAL launch error plus manual
|
||||
* `bunx playwright install chromium` guidance — the CLI never hangs on it.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { spawn } from 'child_process';
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
/** F11: one structured stderr line per self-heal action. */
|
||||
function logHeal(action: string, fields: Record<string, unknown> = {}): void {
|
||||
console.error(`[browse:xprotect-heal] ${JSON.stringify({ action, ...fields })}`);
|
||||
}
|
||||
|
||||
// ─── Classifier (F9: positives AND negatives) ────────────────────────────
|
||||
|
||||
/**
|
||||
* Failure shapes that are definitively NOT an XProtect kill. Checked before
|
||||
* the positives so an ambiguous message never triggers a pointless reinstall:
|
||||
* - missing executable (browser was never installed / cache wiped)
|
||||
* - spawn-level permission errors (EACCES / EPERM / ENOENT)
|
||||
* - Linux sandbox denials (wrong OS anyway, but the text is distinctive)
|
||||
*/
|
||||
const NEGATIVE_SIGNATURES: RegExp[] = [
|
||||
/executable doesn't exist/i,
|
||||
/spawn\s+\S+\s+(EACCES|EPERM|ENOENT)/i,
|
||||
/\b(EACCES|EPERM)\b/,
|
||||
/no usable sandbox/i,
|
||||
/failed to move to new namespace/i,
|
||||
/suid sandbox helper/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Failure shapes an OS-level kill produces (sourced from the #2554 report
|
||||
* plus Playwright's launch-error format): the browser process SPAWNED, then
|
||||
* died to SIGKILL, or never became ready (launch timeout with a `<launched>`
|
||||
* marker — the report's visible symptom, since xprotectd kills the child
|
||||
* without Playwright ever learning why).
|
||||
*/
|
||||
const POSITIVE_SIGNATURES: RegExp[] = [
|
||||
/<process did exit:[^>]*signal=SIGKILL/i,
|
||||
/signal[:=]\s*['"]?SIGKILL/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* True when a launch failure message matches the macOS XProtect kill
|
||||
* signature. Platform-gated: XProtect exists only on darwin.
|
||||
*/
|
||||
export function isXProtectKillSignature(
|
||||
message: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean {
|
||||
if (platform !== 'darwin') return false;
|
||||
if (!message) return false;
|
||||
for (const neg of NEGATIVE_SIGNATURES) {
|
||||
if (neg.test(message)) return false;
|
||||
}
|
||||
for (const pos of POSITIVE_SIGNATURES) {
|
||||
if (pos.test(message)) return true;
|
||||
}
|
||||
// XProtect kill at spawn also surfaces as a launch timeout where the
|
||||
// process DID launch (<launched> marker present) but never became ready —
|
||||
// this is the exact symptom the #2554 report describes.
|
||||
return /timeout \d+\s*ms exceeded/i.test(message) && /<launched>/i.test(message);
|
||||
}
|
||||
|
||||
// ─── Playwright cache path helpers (pure) ────────────────────────────────
|
||||
|
||||
const REVISION_DIR_RE = /^chromium(?:_headless_shell)?-\d+$/;
|
||||
|
||||
/**
|
||||
* Walk up from a Chromium executable to its Playwright cache revision dir
|
||||
* (e.g. …/ms-playwright/chromium-1234 or …/chromium_headless_shell-1234).
|
||||
* Returns null when the executable is not in the standard cache layout.
|
||||
*/
|
||||
export function findPlaywrightRevisionDir(executablePath: string): string | null {
|
||||
let dir = path.dirname(executablePath);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
if (REVISION_DIR_RE.test(path.basename(dir))) return dir;
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) return null;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Chromium revision the EMBEDDED playwright-core expects, derived from
|
||||
* the registry-computed executable path (chromium.executablePath() embeds
|
||||
* the revision from playwright-core's browsers.json — it is not read from
|
||||
* disk, so it stays correct even when nothing is installed yet).
|
||||
*/
|
||||
export function expectedChromiumRevision(executablePath: string): string | null {
|
||||
const revDir = findPlaywrightRevisionDir(executablePath);
|
||||
if (!revDir) return null;
|
||||
const m = path.basename(revDir).match(/-(\d+)$/);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the gstack install root whose node_modules pins the SAME
|
||||
* playwright-core revision our binary embeds (ENG-OV3). Candidates:
|
||||
* the dev checkout (source runs) and the global ./setup install. A candidate
|
||||
* qualifies only when its playwright-core/browsers.json chromium revision
|
||||
* matches — running the reinstall anywhere else heals to the WRONG revision.
|
||||
*/
|
||||
export function findGstackInstallRoot(
|
||||
expectedRevision: string,
|
||||
candidates?: string[],
|
||||
): string | null {
|
||||
const roots = candidates ?? [
|
||||
// Dev checkout: browse/src/ → repo root. In the compiled binary
|
||||
// __dirname points into the bunfs bundle and won't exist on disk,
|
||||
// so this candidate simply fails the existsSync below.
|
||||
path.resolve(__dirname, '..', '..'),
|
||||
// Global install root (the ./setup target).
|
||||
path.join(process.env.HOME || '', '.claude', 'skills', 'gstack'),
|
||||
];
|
||||
for (const root of roots) {
|
||||
try {
|
||||
const browsersJson = path.join(root, 'node_modules', 'playwright-core', 'browsers.json');
|
||||
if (!fs.existsSync(browsersJson)) continue;
|
||||
const parsed = JSON.parse(fs.readFileSync(browsersJson, 'utf-8'));
|
||||
const rev = parsed?.browsers?.find((b: { name?: string }) => b?.name === 'chromium')?.revision;
|
||||
if (String(rev) === String(expectedRevision)) return root;
|
||||
} catch {
|
||||
continue; // unreadable/malformed candidate — try the next one
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Quarantine clear ────────────────────────────────────────────────────
|
||||
|
||||
function defaultRunXattr(target: string): number | null {
|
||||
const res = Bun.spawnSync(['xattr', '-dr', 'com.apple.quarantine', target], {
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
timeout: 10_000,
|
||||
});
|
||||
return res.exitCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear com.apple.quarantine on every chromium* revision dir in the
|
||||
* Playwright cache (the headless shell is what XProtect actually killed in
|
||||
* #2554; the headed bundle rides along so a later headed launch doesn't
|
||||
* re-trip). Scope contract mirrors probePoisonedChromiumBundle: NEVER act
|
||||
* on a GSTACK_CHROMIUM_PATH bundle — that belongs to the wrapper/embedder.
|
||||
* Best-effort: xattr failures are logged, never thrown (the forced
|
||||
* reinstall below is the real heal).
|
||||
*/
|
||||
export function clearQuarantineOnPlaywrightCache(
|
||||
executablePath: string,
|
||||
runXattr: (target: string) => number | null = defaultRunXattr,
|
||||
): boolean {
|
||||
const customPath = process.env.GSTACK_CHROMIUM_PATH;
|
||||
if (customPath && path.resolve(executablePath) === path.resolve(customPath)) {
|
||||
logHeal('quarantine-clear-skipped', { reason: 'custom-chromium-path' });
|
||||
return false;
|
||||
}
|
||||
const revDir = findPlaywrightRevisionDir(executablePath);
|
||||
if (!revDir) {
|
||||
logHeal('quarantine-clear-skipped', { reason: 'not-in-playwright-cache', executablePath });
|
||||
return false;
|
||||
}
|
||||
const cacheRoot = path.dirname(revDir);
|
||||
let cleared = 0;
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(cacheRoot);
|
||||
} catch (err) {
|
||||
logHeal('quarantine-clear-skipped', {
|
||||
reason: 'cache-unreadable',
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!REVISION_DIR_RE.test(entry)) continue;
|
||||
const target = path.join(cacheRoot, entry);
|
||||
try {
|
||||
const exitCode = runXattr(target);
|
||||
// Non-zero usually means "no such xattr" — nothing to clear, fine.
|
||||
logHeal('quarantine-clear', { target, exitCode });
|
||||
cleared++;
|
||||
} catch (err) {
|
||||
logHeal('quarantine-clear', {
|
||||
target,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
return cleared > 0;
|
||||
}
|
||||
|
||||
// ─── Bounded forced reinstall (E1) ───────────────────────────────────────
|
||||
|
||||
export const XPROTECT_REINSTALL_TIMEOUT_MS = 120_000;
|
||||
|
||||
export interface ReinstallResult {
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
exitCode?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `bunx playwright install --force chromium` from the gstack install
|
||||
* root, bounded at ~120s. The child gets its own process group (detached)
|
||||
* so a timeout kills the WHOLE tree (bunx → playwright CLI → download
|
||||
* workers), never leaving a zombie download saturating the network.
|
||||
*/
|
||||
export function runBoundedChromiumReinstall(
|
||||
installRoot: string,
|
||||
timeoutMs: number = XPROTECT_REINSTALL_TIMEOUT_MS,
|
||||
): Promise<ReinstallResult> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
child = spawn('bunx', ['playwright', 'install', '--force', 'chromium'], {
|
||||
cwd: installRoot,
|
||||
detached: true, // own process group → group-kill on timeout
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch (err) {
|
||||
resolve({ ok: false, reason: `spawn-error: ${err instanceof Error ? err.message : String(err)}` });
|
||||
return;
|
||||
}
|
||||
let stderrTail = '';
|
||||
child.stderr?.on('data', (d: Buffer) => {
|
||||
stderrTail = (stderrTail + String(d)).slice(-2000);
|
||||
});
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
try {
|
||||
if (child.pid) process.kill(-child.pid, 'SIGKILL'); // whole group
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException)?.code !== 'ESRCH') {
|
||||
try { child.kill('SIGKILL'); } catch { /* already gone */ }
|
||||
}
|
||||
}
|
||||
resolve({ ok: false, reason: 'timeout' });
|
||||
}, timeoutMs);
|
||||
child.on('error', (err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve({ ok: false, reason: `spawn-error: ${err.message}` });
|
||||
});
|
||||
child.on('exit', (code) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (code === 0) {
|
||||
resolve({ ok: true, exitCode: code });
|
||||
} else {
|
||||
resolve({
|
||||
ok: false,
|
||||
reason: `install-exit-${code}${stderrTail ? `: ${stderrTail.slice(-300)}` : ''}`,
|
||||
exitCode: code,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── One-shot orchestration (F4) ─────────────────────────────────────────
|
||||
|
||||
let healAttempted = false;
|
||||
|
||||
/** Test seam only — production never resets the one-shot guard. */
|
||||
export function resetXProtectHealForTests(): void {
|
||||
healAttempted = false;
|
||||
}
|
||||
|
||||
export interface XProtectHealDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
executablePath?: () => string;
|
||||
clearQuarantine?: (execPath: string) => boolean;
|
||||
installRoot?: (expectedRevision: string) => string | null;
|
||||
runReinstall?: (installRoot: string) => Promise<ReinstallResult>;
|
||||
verifyInstalled?: (execPath: string) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt the XProtect self-heal for a classified launch failure.
|
||||
*
|
||||
* Returns true when the heal completed AND the revision dir the embedded
|
||||
* playwright-core expects exists on disk — the caller should retry the
|
||||
* launch exactly once. Returns false when the error doesn't match the
|
||||
* signature, the launch used a custom executable, the one-shot guard
|
||||
* already fired, or any heal step failed (the caller then surfaces the
|
||||
* original error + manual guidance).
|
||||
*/
|
||||
export async function maybeHealXProtectKill(
|
||||
err: unknown,
|
||||
opts: { usesCustomExecutable?: boolean } = {},
|
||||
deps: XProtectHealDeps = {},
|
||||
): Promise<boolean> {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (!isXProtectKillSignature(message, deps.platform ?? process.platform)) return false;
|
||||
if (opts.usesCustomExecutable) {
|
||||
// A GSTACK_CHROMIUM_PATH bundle belongs to the wrapper/embedder — never
|
||||
// quarantine-clear or reinstall over it (probePoisonedChromiumBundle's
|
||||
// scope contract).
|
||||
logHeal('skip', { reason: 'custom-executable' });
|
||||
return false;
|
||||
}
|
||||
if (healAttempted) {
|
||||
logHeal('skip', { reason: 'already-attempted-this-process' });
|
||||
return false;
|
||||
}
|
||||
healAttempted = true; // F4: at most one heal per process, even on failure
|
||||
logHeal('classified', { signature: 'xprotect-kill' });
|
||||
|
||||
const execPath = (deps.executablePath ?? (() => chromium.executablePath()))();
|
||||
(deps.clearQuarantine ?? clearQuarantineOnPlaywrightCache)(execPath);
|
||||
|
||||
const revision = expectedChromiumRevision(execPath);
|
||||
if (!revision) {
|
||||
logHeal('reinstall-skipped', { reason: 'no-revision-in-path', execPath });
|
||||
return false;
|
||||
}
|
||||
const root = (deps.installRoot ?? findGstackInstallRoot)(revision);
|
||||
if (!root) {
|
||||
// No install root pins our revision — a cwd-resolved install would heal
|
||||
// to the WRONG revision (ENG-OV3), so surface guidance instead.
|
||||
logHeal('reinstall-skipped', { reason: 'no-install-root', revision });
|
||||
return false;
|
||||
}
|
||||
|
||||
logHeal('reinstall-start', { installRoot: root, revision, timeoutMs: XPROTECT_REINSTALL_TIMEOUT_MS });
|
||||
const result = await (deps.runReinstall ?? runBoundedChromiumReinstall)(root);
|
||||
if (!result.ok) {
|
||||
logHeal('reinstall-failed', { reason: result.reason });
|
||||
return false;
|
||||
}
|
||||
|
||||
// F9/ENG-OV3: assert the revision dir the embedded playwright-core
|
||||
// EXPECTS exists post-heal — install exit 0 alone can mean "installed the
|
||||
// wrong revision" when resolution went sideways.
|
||||
const verify = deps.verifyInstalled ?? ((p: string) => fs.existsSync(p));
|
||||
if (!verify(execPath)) {
|
||||
logHeal('verify-failed', { expected: execPath });
|
||||
return false;
|
||||
}
|
||||
logHeal('reinstall-ok', { installRoot: root, revision });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Original launch error + manual remediation, for classified failures the
|
||||
* heal could not fix (offline, timeout, one-shot spent, no install root).
|
||||
*/
|
||||
export function buildXProtectGuidance(originalMessage: string): string {
|
||||
return (
|
||||
`${originalMessage}\n` +
|
||||
'[browse] This launch failure matches the macOS XProtect kill signature (#2554): ' +
|
||||
"the OS killed Playwright's Chromium at spawn. Automatic self-heal did not complete. " +
|
||||
'Fix manually: run `bunx playwright install chromium` from your gstack install ' +
|
||||
'(the directory whose node_modules pins playwright — ~/.claude/skills/gstack for ' +
|
||||
'global installs), then retry.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a Playwright launch call with the XProtect self-heal: on a classified
|
||||
* failure, heal once and retry the launch once. On a classified failure the
|
||||
* heal could not fix, throw the ORIGINAL error text augmented with manual
|
||||
* guidance. Unclassified failures pass through untouched.
|
||||
*/
|
||||
export async function launchWithXProtectHeal<T>(
|
||||
doLaunch: () => Promise<T>,
|
||||
opts: { usesCustomExecutable?: boolean } = {},
|
||||
deps: XProtectHealDeps = {},
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await doLaunch();
|
||||
} catch (err) {
|
||||
const healed = await maybeHealXProtectKill(err, opts, deps);
|
||||
if (healed) {
|
||||
logHeal('retry-launch', {});
|
||||
return await doLaunch();
|
||||
}
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (isXProtectKillSignature(message, deps.platform ?? process.platform)) {
|
||||
throw new Error(buildXProtectGuidance(message), { cause: err });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user