fix(engine): diagnose the launch attempt whose error surfaces (#7630)

When a sandboxed Linux launch fails and the no-sandbox retry also fails,
the startup diagnosis re-ran Chrome with the first attempt's flags, so it
described a launch that was not the one reported. The engine and CLI now
diagnose the flags of the attempt that produced the error.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-13 00:34:30 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent a810a8b002
commit 43722355a3
4 changed files with 140 additions and 15 deletions
@@ -0,0 +1,61 @@
import { chmodSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { LaunchOptions, PuppeteerNode } from "puppeteer-core";
import { afterEach, describe, expect, it, vi } from "vitest";
import { launchManagedBrowser } from "./launch.js";
/** A browser that prints the flags it was started with and exits. */
function argvEchoingBrowser(): string {
const path = join(mkdtempSync(join(tmpdir(), "hf-fake-chrome-")), "chrome");
writeFileSync(
path,
"#!/usr/bin/env node\nconsole.error(process.argv.slice(2).join(' ')); process.exit(3);\n",
);
chmodSync(path, 0o755);
return path;
}
const closedTarget = () =>
Object.assign(new Error("Protocol error: Target closed"), { name: "TargetCloseError" });
describe.runIf(process.platform === "linux")(
"the startup diagnosis after a sandboxed launch and its retry both fail",
() => {
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it("starts the diagnosis with the retry's flags, which produced the surfaced error", async () => {
vi.stubEnv("HYPERFRAMES_CHROME_SANDBOX", "");
vi.spyOn(console, "warn").mockImplementation(() => {});
const real = (await import("puppeteer-core")).default;
const launches: LaunchOptions[] = [];
const puppeteer = {
launch: async (options: LaunchOptions) => {
launches.push(options);
throw closedTarget();
},
defaultArgs: (options: Parameters<PuppeteerNode["defaultArgs"]>[0]) =>
real.defaultArgs(options),
} as unknown as PuppeteerNode;
const failure = await launchManagedBrowser(puppeteer, {
executablePath: argvEchoingBrowser(),
headless: true,
args: ["--headless"],
}).then(
() => undefined,
(error: unknown) => error as Error,
);
expect(launches.map((options) => options.args?.includes("--no-sandbox"))).toEqual([
false,
true,
]);
expect(failure?.message).toContain("exited with code 3");
expect(failure?.message).toMatch(/--no-sandbox/);
}, 60_000);
},
);
+10 -9
View File
@@ -110,21 +110,22 @@ export async function launchManagedBrowser(
): Promise<Browser> {
const sandboxed = isOneProcessOverPipe(options) || inAgentSandbox();
const prepared = sandboxed ? oneProcessOverPipe(options) : options;
let attempted = prepared;
try {
return await launchWithChromeSandboxFallback(prepared.args ?? [], (args) =>
launchOwnedBrowser(puppeteer, { ...prepared, args }),
);
return await launchWithChromeSandboxFallback(prepared.args ?? [], (args) => {
attempted = { ...prepared, args };
return launchOwnedBrowser(puppeteer, attempted);
});
} catch (error) {
const unnamedSeatbelt =
!sandboxed &&
(machServiceDenied(normalizeErrorMessage(error)) || pipeLaunchClosedOnMac(error));
if (!unnamedSeatbelt)
throw await withStartupDiagnosis(withRemediation(error), puppeteer, options, diagnose);
return launchOwnedBrowser(puppeteer, oneProcessOverPipe(options)).catch(
async (retryError: unknown) => {
throw await withStartupDiagnosis(withRemediation(retryError), puppeteer, options, diagnose);
},
);
throw await withStartupDiagnosis(withRemediation(error), puppeteer, attempted, diagnose);
const retry = oneProcessOverPipe(options);
return launchOwnedBrowser(puppeteer, retry).catch(async (retryError: unknown) => {
throw await withStartupDiagnosis(withRemediation(retryError), puppeteer, retry, diagnose);
});
}
}
@@ -0,0 +1,60 @@
import type { LaunchOptions, PuppeteerNode } from "puppeteer-core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
_resetBrowserPoolForTests,
_setPuppeteerForTests,
acquireBrowser,
drainBrowserPool,
} from "./browserManager.js";
import { _resetChromeSandboxFallbackForTests } from "./chromeSandbox.js";
const explained = vi.hoisted(() => [] as (readonly string[] | undefined)[]);
vi.mock("./chromeStartup.js", async (importActual) => ({
...(await importActual<typeof import("./chromeStartup.js")>()),
explainChromeLaunchFailure: async (error: unknown, _path: unknown, args?: readonly string[]) => {
explained.push(args);
return error;
},
}));
const closedTarget = () =>
Object.assign(new Error("Protocol error: Target closed"), { name: "TargetCloseError" });
describe("the startup diagnosis after a sandboxed launch and its retry both fail", () => {
beforeEach(() => {
explained.length = 0;
_resetChromeSandboxFallbackForTests();
vi.stubEnv("PRODUCER_HEADLESS_SHELL_PATH", process.execPath);
vi.stubEnv("HYPERFRAMES_CHROME_SANDBOX", "");
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(async () => {
await drainBrowserPool();
_resetBrowserPoolForTests();
_setPuppeteerForTests(undefined);
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it("describes the retry's args, which produced the surfaced error", async () => {
const retryError = closedTarget();
const launch = vi.fn<(options: LaunchOptions) => Promise<never>>();
launch.mockRejectedValueOnce(closedTarget()).mockRejectedValueOnce(retryError);
const defaultArgs = vi.fn(async (options: { args?: string[] }) => options.args ?? []);
_setPuppeteerForTests({ launch, defaultArgs } as unknown as PuppeteerNode);
const error = await acquireBrowser(["--headless"], { forceScreenshot: true }).catch((e) => e);
expect(error).toBe(retryError);
expect(launch.mock.calls.map(([options]) => options.args?.includes("--no-sandbox"))).toEqual([
false,
true,
]);
expect(explained).toHaveLength(1);
expect(explained[0]).toEqual(expect.arrayContaining(["--headless", "--no-sandbox"]));
});
});
@@ -923,9 +923,11 @@ async function launchBrowser(
const env = launchEnv(fingerprint);
let captureMode = fingerprint.requestedCaptureMode;
let browser: Browser | undefined;
const launch = (args: readonly string[]) =>
launchWithChromeSandboxFallback(args, (launchArgs) =>
launchInsideSandbox(ppt, {
const launch = (args: readonly string[]) => {
let attempted = args;
return launchWithChromeSandboxFallback(args, (launchArgs) => {
attempted = launchArgs;
return launchInsideSandbox(ppt, {
...ownedLaunchOptions(),
headless: true,
args: withHyperframesBrowserMarker(launchArgs),
@@ -934,18 +936,19 @@ async function launchBrowser(
env,
timeout: fingerprint.browserTimeoutMs,
protocolTimeout: fingerprint.protocolTimeoutMs,
}),
).catch(async (error: unknown) => {
});
}).catch(async (error: unknown) => {
const remediation =
process.platform === "darwin" &&
sandboxDeniedRemediation(error instanceof Error ? error.message : "");
if (remediation) throw new Error(remediation, { cause: error });
const defaults = await ppt.defaultArgs({
headless: true,
args: withHyperframesBrowserMarker(args),
args: withHyperframesBrowserMarker(attempted),
});
throw await explainChromeLaunchFailure(error, fingerprint.executablePath, defaults);
});
};
const probe = (target: Browser, timeoutMs?: number) =>
probeBeginFrameSupport(target, timeoutMs).catch((error) => ({
supported: true,