Skip to content

Commit 1e84ba4

Browse files
committed
fix(engine): audio effects launch Chrome like every other render, sandbox retry included
Audio effects launched Chrome with its own two flags and no retry, so inside an agent's macOS seatbelt Chrome died at startup with "Target closed" while the CLI's own browser launch recovered. The sandbox launch policy now lives in the engine; the engine's Chrome launch retries once in one process over a pipe when the sandbox refuses it, and audio effects use the shared Chrome flags in software GPU mode. The CLI imports the same policy from the engine.
1 parent 7053aa9 commit 1e84ba4

10 files changed

Lines changed: 214 additions & 28 deletions

File tree

‎packages/cli/src/browser/launch.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
11
import type { ChildProcess } from "node:child_process";
2+
import {
3+
inAgentSandbox,
4+
isOneProcessOverPipe,
5+
machServiceDenied,
6+
oneProcessOverPipe,
7+
pipeLaunchClosedOnMac,
8+
sandboxDeniedRemediation,
9+
} from "@hyperframes/engine";
210
import { explainChromeLaunchFailure } from "@hyperframes/engine/chrome-startup";
311
import type { Browser, LaunchOptions, PuppeteerNode } from "puppeteer-core";
412
import { withHyperframesBrowserMarker } from "@hyperframes/core/browser-marker";
@@ -12,14 +20,6 @@ import { requestCliExit } from "../utils/commandResult.js";
1220
import { processIsAlive } from "../utils/processTree.js";
1321
import { chromeDescendants, reapChromeTree } from "./chromeTree.js";
1422
import { watchChromeTree, type ChromeWatchdog } from "./windowsChromeWatchdog.js";
15-
import {
16-
inAgentSandbox,
17-
isOneProcessOverPipe,
18-
pipeLaunchClosedOnMac,
19-
machServiceDenied,
20-
oneProcessOverPipe,
21-
sandboxDeniedRemediation,
22-
} from "./sandboxDenied.js";
2323

2424
export class BrowserCleanupError extends AggregateError {}
2525

‎packages/cli/src/capture/captureCompositionFrame.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
import { oneProcessOverPipe } from "@hyperframes/engine";
12
import {
23
rethrowAfterBrowserCleanup,
34
launchManagedBrowser,
45
resolveManagedGpuMode,
56
} from "../browser/launch.js";
6-
import { oneProcessOverPipe } from "../browser/sandboxDenied.js";
77
import { spawn } from "node:child_process";
88
import type { Browser, Page } from "puppeteer-core";
99
import type { InProcessRequest, InProcessResponse } from "../utils/staticProjectServer.js";

‎packages/cli/src/commands/render.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,6 @@ import {
128128
import { chromeLaunchRemediation } from "../browser/linuxDeps.js";
129129
import { macosOldChromeCrashRemediation } from "../browser/macosOldChromeCrash.js";
130130
import { windowsChromeCrashRemediation } from "../browser/windowsCrash.js";
131-
import { sandboxDeniedRemediation } from "../browser/sandboxDenied.js";
132131
import { killOrphanedProcessesForRender } from "../utils/orphanCleanup.js";
133132
import { createRenderCancellationScope } from "../utils/renderCancellation.js";
134133
import {
@@ -137,7 +136,11 @@ import {
137136
runPostRenderStepAsync,
138137
} from "../utils/render-success-state.js";
139138
import type { ProducerLogger, RenderJob, RenderPerfSummary } from "@hyperframes/producer";
140-
import { EXTRACT_CACHE_DIR_DISABLED_ALIASES, type VideoFrameFormat } from "@hyperframes/engine";
139+
import {
140+
EXTRACT_CACHE_DIR_DISABLED_ALIASES,
141+
sandboxDeniedRemediation,
142+
type VideoFrameFormat,
143+
} from "@hyperframes/engine";
141144
import {
142145
checkOutputResolutionCompatibility,
143146
suggestMatchingPreset,

‎packages/engine/src/index.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,3 +495,12 @@ export {
495495
DrawElementCaptureError,
496496
isDrawElementCaptureError,
497497
} from "./services/drawElementCaptureError.js";
498+
499+
export {
500+
inAgentSandbox,
501+
isOneProcessOverPipe,
502+
machServiceDenied,
503+
oneProcessOverPipe,
504+
pipeLaunchClosedOnMac,
505+
sandboxDeniedRemediation,
506+
} from "./services/sandboxLaunch.js";
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
3+
const execSync = vi.hoisted(() => vi.fn(() => ""));
4+
vi.mock("child_process", async (importActual) => ({
5+
...(await importActual<typeof import("child_process")>()),
6+
execSync,
7+
}));
8+
9+
describe("importing the engine", () => {
10+
it("runs no subprocess", async () => {
11+
await import("./audioFxRender.js");
12+
await import("../index.js");
13+
expect(execSync).not.toHaveBeenCalled();
14+
}, 60_000);
15+
});
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { mkdtempSync, rmSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
6+
const acquire = vi.hoisted(() => vi.fn());
7+
vi.mock("./browserManager.js", async (importActual) => ({
8+
...(await importActual<typeof import("./browserManager.js")>()),
9+
acquireBrowser: acquire,
10+
}));
11+
12+
import { applyAudioFxChain, writeWav } from "./audioFxRender.js";
13+
import { buildChromeArgs } from "./browserManager.js";
14+
15+
let dir: string;
16+
afterEach(() => rmSync(dir, { recursive: true, force: true }));
17+
18+
describe("audio effects browser launch", () => {
19+
it("asks for the shared Chrome args, not its own list", async () => {
20+
acquire.mockRejectedValue(new Error("stop here"));
21+
dir = mkdtempSync(join(tmpdir(), "hf-fx-launch-"));
22+
const input = join(dir, "in.wav");
23+
writeWav(input, new Float32Array(480), 48000);
24+
const chain = {
25+
version: 1 as const,
26+
nodes: [
27+
{ type: "peaking" as const, enabled: true, params: { frequency: 440, gain: -3, q: 1 } },
28+
],
29+
};
30+
await expect(
31+
applyAudioFxChain(input, chain, join(dir, "out.wav"), { trackId: "t" }),
32+
).rejects.toThrow();
33+
expect(acquire).toHaveBeenCalledWith(
34+
buildChromeArgs(
35+
{ width: 1280, height: 720, captureMode: "screenshot" },
36+
{ browserGpuMode: "software" },
37+
),
38+
);
39+
});
40+
});

‎packages/engine/src/services/audioFxRender.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import { getAudioFxRuntimeScript } from "@hyperframes/core/audio-fx-runtime";
3030
import { enabledAudioFxNodes, type HfAudioFxChain } from "@hyperframes/core/audio-fx";
3131
import { serializeAutomation, type HfAutomation } from "@hyperframes/core/audio-automation";
3232
import { removeScratch } from "../utils/removeScratch.js";
33-
import { acquireBrowser } from "./browserManager.js";
33+
import { acquireBrowser, buildChromeArgs } from "./browserManager.js";
3434
import { createEnvelopeWalker } from "./audioVolumeEnvelope.js";
3535
import { riffChunks, wavFormatTag } from "./wavChunks.js";
3636
import { windowPrerollSeconds } from "./audioFxWarmup.js";
@@ -606,6 +606,14 @@ export async function applyAudioFxChain(
606606
});
607607
}
608608

609+
/** Audio processing needs no GPU, so software mode; every other launch detail is the shared one. */
610+
let fxBrowserArgs: string[] | undefined;
611+
const fxChromeArgs = () =>
612+
(fxBrowserArgs ??= buildChromeArgs(
613+
{ width: 1280, height: 720, captureMode: "screenshot" },
614+
{ browserGpuMode: "software" },
615+
));
616+
609617
/** Run `body` with a leased browser and a way to open pages on the runtime; both are released in the same try that takes them. */
610618
async function withFxBrowser<T>(
611619
options: { trackId: string; signal?: AbortSignal },
@@ -621,7 +629,7 @@ async function withFxBrowser<T>(
621629
if (options.signal?.aborted) {
622630
throw new AudioFxRenderError(`Audio FX cancelled for track ${options.trackId}`);
623631
}
624-
lease = await acquireBrowser(["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]);
632+
lease = await acquireBrowser(fxChromeArgs());
625633
const { browser } = lease;
626634
return await body(() => openFxPage(browser, hostDir));
627635
} catch (err) {
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import type { LaunchOptions, PuppeteerNode } from "puppeteer-core";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import {
4+
_resetAutoBrowserGpuModeCacheForTests,
5+
_resetBrowserPoolForTests,
6+
_setPuppeteerForTests,
7+
acquireBrowser,
8+
drainBrowserPool,
9+
} from "./browserManager.js";
10+
11+
vi.mock("./chromeStartup.js", async (importActual) => ({
12+
...(await importActual<typeof import("./chromeStartup.js")>()),
13+
explainChromeLaunchFailure: async (error: unknown) => error,
14+
}));
15+
16+
const chrome = () => ({
17+
connected: true,
18+
newPage: vi.fn().mockResolvedValue({ evaluate: vi.fn() }),
19+
version: vi.fn().mockResolvedValue("HeadlessChrome/152.0.7977.30"),
20+
close: vi.fn().mockResolvedValue(undefined),
21+
disconnect: vi.fn(),
22+
process: () => ({ kill: vi.fn(), killed: false }),
23+
});
24+
25+
const denied = new Error(
26+
"Failed to launch: bootstrap_check_in org.chromium.Chromium.MachPortRendezvousServer: Permission denied (1100)",
27+
);
28+
29+
describe("engine Chrome launch inside an agent seatbelt", () => {
30+
beforeEach(() => {
31+
vi.stubEnv("PRODUCER_HEADLESS_SHELL_PATH", process.execPath);
32+
vi.spyOn(console, "log").mockImplementation(() => {});
33+
vi.spyOn(console, "warn").mockImplementation(() => {});
34+
});
35+
36+
afterEach(async () => {
37+
await drainBrowserPool();
38+
_resetBrowserPoolForTests();
39+
_resetAutoBrowserGpuModeCacheForTests();
40+
_setPuppeteerForTests(undefined);
41+
vi.unstubAllEnvs();
42+
vi.restoreAllMocks();
43+
});
44+
45+
it("retries once in one process over a pipe when the mach service is refused", async () => {
46+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
47+
const launch = vi.fn<(options: LaunchOptions) => Promise<ReturnType<typeof chrome>>>();
48+
launch.mockRejectedValueOnce(denied).mockResolvedValue(chrome());
49+
_setPuppeteerForTests({ launch } as unknown as PuppeteerNode);
50+
const lease = await acquireBrowser(["--no-sandbox"], { forceScreenshot: true });
51+
await lease.release();
52+
expect(launch).toHaveBeenCalledTimes(2);
53+
const [first, second] = launch.mock.calls.map(([options]) => options);
54+
expect(first?.args).not.toContain("--single-process");
55+
expect(second?.pipe).toBe(true);
56+
expect(second?.args).toContain("--single-process");
57+
});
58+
59+
it("launches one process over a pipe at once when the host names a seatbelt", async () => {
60+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
61+
vi.stubEnv("CODEX_SANDBOX", "seatbelt");
62+
const launch = vi.fn(async (_options: LaunchOptions) => chrome());
63+
_setPuppeteerForTests({ launch } as unknown as PuppeteerNode);
64+
const lease = await acquireBrowser(["--no-sandbox"], { forceScreenshot: true });
65+
await lease.release();
66+
const calls = launch.mock.calls.map(([options]) => options);
67+
expect(calls).toHaveLength(1);
68+
expect(calls[0]?.pipe).toBe(true);
69+
expect(calls[0]?.args).toContain("--single-process");
70+
});
71+
72+
it.each([
73+
["a refused mach service", denied],
74+
["a pipe launch that closed", Object.assign(new Error("closed"), { name: "TargetCloseError" })],
75+
])("on Linux launches once and keeps %s as the failure", async (_, failure) => {
76+
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
77+
vi.stubEnv("CODEX_SANDBOX", "seatbelt");
78+
const launch = vi.fn<(options: LaunchOptions) => Promise<ReturnType<typeof chrome>>>();
79+
launch.mockRejectedValue(failure);
80+
_setPuppeteerForTests({
81+
launch,
82+
defaultArgs: vi.fn().mockResolvedValue([]),
83+
} as unknown as PuppeteerNode);
84+
const error = await acquireBrowser(["--no-sandbox"], { forceScreenshot: true }).catch((e) => e);
85+
expect(launch).toHaveBeenCalledTimes(1);
86+
expect(launch.mock.calls[0]?.[0].args).not.toContain("--single-process");
87+
expect(error).toBe(failure);
88+
});
89+
});

‎packages/engine/src/services/browserManager.ts‎

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@
88

99
import { explainChromeLaunchFailure } from "./chromeStartup.js";
1010
import { withHyperframesBrowserMarker } from "@hyperframes/core/browser-marker";
11+
import {
12+
inAgentSandbox,
13+
machServiceDenied,
14+
oneProcessOverPipe,
15+
pipeLaunchClosedOnMac,
16+
sandboxDeniedRemediation,
17+
} from "./sandboxLaunch.js";
1118
import { scanHtmlOpeningTags } from "@hyperframes/parsers/html-attribute-spans";
1219
import type { Browser, LaunchOptions, Page, PuppeteerNode } from "puppeteer-core";
1320
import { execSync } from "child_process";
@@ -889,6 +896,19 @@ export async function acquireBrowser(
889896
return browserLeasePool.acquire(createBrowserLaunchFingerprint(chromeArgs, config), enablePool);
890897
}
891898

899+
/** An agent's macOS seatbelt allows one launch shape only: Chrome in one process over a pipe. */
900+
async function launchInsideSandbox(ppt: PuppeteerNode, options: LaunchOptions): Promise<Browser> {
901+
const sandboxed = inAgentSandbox();
902+
try {
903+
return await ppt.launch(sandboxed ? oneProcessOverPipe(options) : options);
904+
} catch (error) {
905+
const message = error instanceof Error ? error.message : "";
906+
const refused = machServiceDenied(message) || pipeLaunchClosedOnMac(error);
907+
if (process.platform !== "darwin" || sandboxed || !refused) throw error;
908+
return ppt.launch(oneProcessOverPipe(options));
909+
}
910+
}
911+
892912
// fallow-ignore-next-line complexity
893913
async function launchBrowser(
894914
fingerprint: Readonly<BrowserLaunchFingerprint>,
@@ -898,24 +918,26 @@ async function launchBrowser(
898918
let captureMode = fingerprint.requestedCaptureMode;
899919
let browser: Browser | undefined;
900920
const launch = (args: readonly string[]) =>
901-
ppt
902-
.launch({
903-
...ownedLaunchOptions(),
921+
launchInsideSandbox(ppt, {
922+
...ownedLaunchOptions(),
923+
headless: true,
924+
args: withHyperframesBrowserMarker(args),
925+
defaultViewport: null,
926+
executablePath: fingerprint.executablePath,
927+
env,
928+
timeout: fingerprint.browserTimeoutMs,
929+
protocolTimeout: fingerprint.protocolTimeoutMs,
930+
}).catch(async (error: unknown) => {
931+
const remediation =
932+
process.platform === "darwin" &&
933+
sandboxDeniedRemediation(error instanceof Error ? error.message : "");
934+
if (remediation) throw new Error(remediation, { cause: error });
935+
const defaults = await ppt.defaultArgs({
904936
headless: true,
905937
args: withHyperframesBrowserMarker(args),
906-
defaultViewport: null,
907-
executablePath: fingerprint.executablePath,
908-
env,
909-
timeout: fingerprint.browserTimeoutMs,
910-
protocolTimeout: fingerprint.protocolTimeoutMs,
911-
})
912-
.catch(async (error: unknown) => {
913-
const defaults = await ppt.defaultArgs({
914-
headless: true,
915-
args: withHyperframesBrowserMarker(args),
916-
});
917-
throw await explainChromeLaunchFailure(error, fingerprint.executablePath, defaults);
918938
});
939+
throw await explainChromeLaunchFailure(error, fingerprint.executablePath, defaults);
940+
});
919941
const probe = (target: Browser, timeoutMs?: number) =>
920942
probeBeginFrameSupport(target, timeoutMs).catch((error) => ({
921943
supported: true,
File renamed without changes.

0 commit comments

Comments
 (0)