Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 58 additions & 43 deletions packages/cli/src/browser/manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const HF_RECLAIM_LOCK = join(CACHE_ROOT, ".chrome.install.reclaim.lock");
const PUPPETEER_CACHE = join(FAKE_HOME, ".cache", "puppeteer", "chrome-headless-shell");
const PUPPETEER_BINARY = join(
PUPPETEER_CACHE,
"linux-148.0.7778.97",
`linux-${CHROME_VERSION}`,
"chrome-headless-shell-linux64",
"chrome-headless-shell",
);
Expand Down Expand Up @@ -900,7 +900,7 @@ describe("findBrowser — cache resolution", () => {
// scenario from the hf#677 spike.
installFsMocks({
existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY]),
dirs: { [PUPPETEER_CACHE]: ["linux-148.0.7778.97"] },
dirs: { [PUPPETEER_CACHE]: [`linux-${CHROME_VERSION}`] },
});
installPuppeteerBrowsersMock();

Expand Down Expand Up @@ -955,7 +955,7 @@ describe("findBrowser — cache resolution", () => {
value: hostArch,
configurable: true,
});
const version = "host-148.0.7778.97";
const version = `host-${CHROME_VERSION}`;
const candidates = [
["chrome-headless-shell-linux64", "chrome-headless-shell"],
["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
Expand Down Expand Up @@ -997,7 +997,7 @@ describe("findBrowser — cache resolution", () => {
value: hostArch,
configurable: true,
});
const version = "host-148.0.7778.97";
const version = `host-${CHROME_VERSION}`;
const binaries = [
join(PUPPETEER_CACHE, version, "chrome-headless-shell-linux64", "chrome-headless-shell"),
join(PUPPETEER_CACHE, version, "chrome-headless-shell-win64", "chrome-headless-shell.exe"),
Expand All @@ -1016,7 +1016,7 @@ describe("findBrowser — cache resolution", () => {
it("skips an empty executable in the puppeteer cache", async () => {
installFsMocks({
existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY]),
dirs: { [PUPPETEER_CACHE]: ["linux-148.0.7778.97"] },
dirs: { [PUPPETEER_CACHE]: [`linux-${CHROME_VERSION}`] },
emptyFiles: new Set([PUPPETEER_BINARY]),
});
installPuppeteerBrowsersMock();
Expand All @@ -1027,75 +1027,90 @@ describe("findBrowser — cache resolution", () => {
expect(result?.executablePath).not.toBe(PUPPETEER_BINARY);
});

it("prefers the puppeteer cache over the hyperframes cache when BOTH are populated", async () => {
// The HF cache is pinned to `CHROME_VERSION` (131-era) which lags upstream
// by many releases. The engine's `resolveHeadlessShellPath` scans the
// puppeteer cache and selects newest-version-first; if the CLI handed
// engine the older HF-cache binary while a newer puppeteer-cache binary
// exists, the two would silently disagree on which binary to use.
// This test pins the priority: puppeteer cache wins when both are populated.
it("prefers our pinned cache over the puppeteer cache when BOTH are populated", async () => {
installFsMocks({
existing: new Set([HF_CACHE, HF_BINARY, PUPPETEER_CACHE, PUPPETEER_BINARY]),
dirs: { [PUPPETEER_CACHE]: ["linux-148.0.7778.97"] },
dirs: { [PUPPETEER_CACHE]: [`linux-${CHROME_VERSION}`] },
});
installPuppeteerBrowsersMock({
installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }],
installedInHfCache: [
{ browser: "chrome-headless-shell", executablePath: HF_BINARY, buildId: CHROME_VERSION },
],
});

const { findBrowser } = await import("./manager.js");
const result = await findBrowser();

expect(result?.executablePath).toBe(PUPPETEER_BINARY);
expect(result?.source).toBe("cache");
expect(result).toEqual({ executablePath: HF_BINARY, source: "cache" });
});

it("picks the newest version when multiple chrome-headless-shell builds are cached", async () => {
const olderBinary = join(
it("uses our pinned build, not another tool's older shell in the puppeteer cache", async () => {
// Field report: a Mac whose puppeteer cache held mac_arm-121 got that shell for check and snapshot, and it died.
const oldBinary = join(
PUPPETEER_CACHE,
"linux-131.0.6778.85",
"linux-121.0.6167.85",
"chrome-headless-shell-linux64",
"chrome-headless-shell",
);
installFsMocks({
existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY, olderBinary]),
dirs: {
[PUPPETEER_CACHE]: ["linux-131.0.6778.85", "linux-148.0.7778.97"],
},
existing: new Set([HF_CACHE, HF_BINARY, PUPPETEER_CACHE, oldBinary]),
dirs: { [PUPPETEER_CACHE]: ["linux-121.0.6167.85"] },
});
installPuppeteerBrowsersMock({
installedInHfCache: [
{ browser: "chrome-headless-shell", executablePath: HF_BINARY, buildId: CHROME_VERSION },
],
});
installPuppeteerBrowsersMock();

const { findBrowser } = await import("./manager.js");
const result = await findBrowser();

expect(result?.executablePath).toBe(PUPPETEER_BINARY);
await expect(findBrowser()).resolves.toEqual({ executablePath: HF_BINARY, source: "cache" });
});

it("uses numeric (not lexicographic) version ordering — linux-148 beats linux-99", async () => {
// Regression guard for the lexicographic-sort bug: `"linux-99..."` sorts
// after `"linux-148..."` character-by-character (because `'9' > '1'`),
// which would have caused the CLI to hand engine an ancient 99-era binary
// when a fresh 148 was sitting right next to it. Numeric semver-style
// ordering is the only correct semantic.
const linux99Binary = join(
it("skips another build in the puppeteer cache that does not start", async () => {
const oldBinary = join(
PUPPETEER_CACHE,
"linux-99.0.6533.123",
"linux-121.0.6167.85",
"chrome-headless-shell-linux64",
"chrome-headless-shell",
);
installFsMocks({
existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY, linux99Binary]),
// Intentionally list the entries in an order that would expose the bug
// under naive `.sort().reverse()` (which puts `linux-99...` first).
dirs: {
[PUPPETEER_CACHE]: ["linux-99.0.6533.123", "linux-148.0.7778.97"],
},
existing: new Set([PUPPETEER_CACHE, oldBinary]),
dirs: { [PUPPETEER_CACHE]: ["linux-121.0.6167.85"] },
});
installPuppeteerBrowsersMock();

const { findBrowser } = await import("./manager.js");
const result = await findBrowser();

expect(result?.executablePath).toBe(PUPPETEER_BINARY);
expect((await findBrowser())?.executablePath).not.toBe(oldBinary);
});

it("keeps the newest working shell in the puppeteer cache when the pinned build is absent", async () => {
const shared = (version: string) =>
join(
PUPPETEER_CACHE,
`linux-${version}`,
"chrome-headless-shell-linux64",
"chrome-headless-shell",
);
installFsMocks({
existing: new Set([PUPPETEER_CACHE, shared("99.0.6533.123"), shared("148.0.7778.97")]),
dirs: { [PUPPETEER_CACHE]: ["linux-99.0.6533.123", "linux-148.0.7778.97"] },
});
installPuppeteerBrowsersMock();
vi.doMock("node:child_process", () => ({
execSync: vi.fn(() => {
throw new Error("not found");
}),
spawnSync: vi.fn(() => ({ status: 0 })),
}));

const { findBrowser } = await import("./manager.js");

await expect(findBrowser()).resolves.toEqual({
executablePath: shared("148.0.7778.97"),
source: "cache",
});
});

it("falls back to system Chrome and warns on Linux when no cache has headless-shell", async () => {
Expand Down Expand Up @@ -1557,7 +1572,7 @@ describe("browser resolution on macOS 12 (Darwin < 22)", () => {
});
});

it("keeps the newest puppeteer-cache build on macOS 13", async () => {
it("keeps the pinned puppeteer-cache build on macOS 13", async () => {
installFsMocks({
existing: new Set([
PUPPETEER_CACHE,
Expand Down
117 changes: 11 additions & 106 deletions packages/cli/src/browser/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
import { homedir } from "node:os";
import { debuglog } from "node:util";
import { basename, dirname, join, relative } from "node:path";
import { chromeMajorCeiling, exceedsChromeCeiling } from "@hyperframes/engine/chrome-host-ceiling";
import { managedChromeVersion, pickSharedShell } from "@hyperframes/engine/chrome-host-ceiling";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";

Expand All @@ -33,30 +33,6 @@ async function loadPuppeteerBrowsers(): Promise<PuppeteerBrowsers> {
}
}

// Bumped from 152.0.7928.2 on 2026-08-10 to pick up crbug 522872457's fix
// (CL 8032671, "Force-merge PendingLayer for canvas child descendant", merged
// 2026-07-07 — after the 152.0.7935.0 canary cut, so the old pin predated it).
//
// Measured on the shipping headless-shell binary, drawElementImage vs a CDP
// screenshot of the identical state:
// sibling content dropped from 3D captures — FIXED
// background lost from 3D captures — FIXED
// backface-visibility:hidden ignored — STILL BROKEN (1.4 dB -> 14.8 dB;
// better, still far under the
// 32 dB floor)
// So the 3D compile gate must stay. See PRINFRA-486.
//
// Deliberately Beta, not Canary. 153.0.8000.0 measured identical to this build
// on every probe variant, so crossing a major buys nothing measurable.
const CHROME_VERSION = "152.0.7977.30";
// Last headless-shell milestone that launches on macOS 12 (Darwin < 22); Chrome 151 dropped it.
// Measured: this build exposes canvas.drawElementImage under --enable-features=CanvasDrawElement.
const MACOS_12_CHROME_VERSION = "150.0.7871.124";

/** The one place that decides which build HyperFrames installs and matches in its own cache. */
function managedChromeVersion(): string {
return chromeMajorCeiling() === undefined ? CHROME_VERSION : MACOS_12_CHROME_VERSION;
}
const CACHE_ROOT_DIR = join(homedir(), ".cache", "hyperframes");
const CACHE_DIR = join(homedir(), ".cache", "hyperframes", "chrome");
// Puppeteer's managed cache — where `@puppeteer/browsers install
Expand Down Expand Up @@ -388,71 +364,11 @@ async function findFromHyperframesCache(): Promise<CacheLookupResult> {
}

async function findFromCache(): Promise<CacheLookupResult> {
// 1) Puppeteer's managed cache — where `npx @puppeteer/browsers install
// chrome-headless-shell` lands, and where `puppeteer install` from a project
// depending on full `puppeteer` (not `puppeteer-core`) lands. The engine's
// `resolveHeadlessShellPath` reads from here and selects newest-version-
// first; the CLI must match that semantic or it will silently hand the
// engine an older binary than the engine itself would pick.
//
// We intentionally check puppeteer BEFORE the hyperframes-managed cache:
// this is the non-`preferManagedChrome` path, which exists so a user who
// installed chrome-headless-shell separately (via `@puppeteer/browsers
// install`) keeps using that binary instead of being silently switched to
// the HF-pinned one. Note `CHROME_VERSION` (above) is a pre-Stable pin
// that may be NEWER than a user's puppeteer-cache Stable build — this is
// about respecting an explicit prior choice, not "newest wins".
// Our pinned build first, as the engine's resolveHeadlessShellPath reads it; then the shared cache's pick.
const ours = await findFromHyperframesCache();
if (ours.result) return ours;
const fromPuppeteer = findFromPuppeteerCache();
if (fromPuppeteer) {
return { result: fromPuppeteer };
}

// 2) Hyperframes-managed cache. This is the fallback path: only reached
// when no puppeteer-cache binary exists.
return findFromHyperframesCache();
}

/**
* Parse a puppeteer-cache version directory name (`linux-148.0.7778.97`,
* `mac_arm-131.0.6778.85`, etc.) into a numeric tuple for ordering.
*
* Lexicographic sort on these strings is buggy because `"99"` > `"148"` (the
* `9` outranks the `1` character-wise), so a 99-era binary would beat a
* 148-era binary in `.sort().reverse()`. We split on `-` to drop the platform
* prefix, then on `.` to get integer segments. Returns `undefined` for names
* that don't have at least one parseable numeric segment so they sort last.
*/
function parseVersionSegments(versionDir: string): number[] | undefined {
const dashIdx = versionDir.indexOf("-");
const versionPart = dashIdx >= 0 ? versionDir.slice(dashIdx + 1) : versionDir;
const segments = versionPart.split(".");
const parsed: number[] = [];
for (const seg of segments) {
const n = parseInt(seg, 10);
if (!Number.isFinite(n)) {
// Stop at the first non-numeric segment but keep what we've collected.
break;
}
parsed.push(n);
}
return parsed.length > 0 ? parsed : undefined;
}

/** Numeric semver-style descending comparator for puppeteer cache dirs. */
function compareVersionDirsDescending(a: string, b: string): number {
const pa = parseVersionSegments(a);
const pb = parseVersionSegments(b);
// Unparseable names sort after parseable ones (so we still try them, just last).
if (!pa && !pb) return 0;
if (!pa) return 1;
if (!pb) return -1;
const len = Math.max(pa.length, pb.length);
for (let i = 0; i < len; i += 1) {
const av = pa[i] ?? 0;
const bv = pb[i] ?? 0;
if (av !== bv) return bv - av; // descending (newest first)
}
return 0;
return fromPuppeteer ? { result: fromPuppeteer } : ours;
}

const CACHED_HEADLESS_SHELL_EXECUTABLES: Readonly<
Expand Down Expand Up @@ -484,26 +400,15 @@ function findFromPuppeteerCache(): BrowserResult | undefined {
if (!executable) return undefined;
let versions: string[];
try {
// Numeric semver-style sort, newest first. Lexicographic `.sort().reverse()`
// (the previous implementation, still in engine `resolveHeadlessShellPath`)
// mis-orders `linux-99...` ahead of `linux-148...` because character `'9'`
// outranks `'1'`. See `parseVersionSegments` above.
versions = [...readdirSync(PUPPETEER_CACHE_DIR)].sort(compareVersionDirsDescending);
versions = readdirSync(PUPPETEER_CACHE_DIR);
} catch {
return undefined;
}
const ceiling = chromeMajorCeiling();
for (const version of versions) {
if (exceedsChromeCeiling(version, ceiling)) continue;
// Same shape as `resolveHeadlessShellPath` in engine/browserManager.ts —
// keep them aligned. If puppeteer ever changes the on-disk layout the two
// need to move together.
const binary = join(PUPPETEER_CACHE_DIR, version, ...executable);
if (isUsableExecutable(binary)) {
return { executablePath: binary, source: "cache" };
}
}
return undefined;
const binary = pickSharedShell(versions, (version) => {
const candidate = join(PUPPETEER_CACHE_DIR, version, ...executable);
return isUsableExecutable(candidate) ? candidate : undefined;
});
return binary ? { executablePath: binary, source: "cache" } : undefined;
}

/**
Expand Down
Loading
Loading