import { type ChildProcess, spawn } from "node:child_process"; import { EventEmitter } from "node:events"; import { homedir } from "node:os"; import { PassThrough } from "node:stream"; import { afterEach, expect, it, vi } from "vitest"; vi.mock("node:child_process", () => ({ spawn: vi.fn() })); vi.mock("node:fs/promises", async (original) => ({ ...(await original()), access: vi.fn(async () => {}), })); const { createCanvasLayout } = await import("../src/layout.ts"); const { createDraw, emptyState } = await import("../src/store.ts"); afterEach(() => { vi.restoreAllMocks(); }); it("reports bounded startup evidence through the real layout operation without weakening Chromium sandboxing", async () => { const calls: string[][] = []; vi.mocked(spawn).mockImplementation((executable, args) => { const values = args as string[]; calls.push(values); const stderr = new PassThrough(); const child = Object.assign(new EventEmitter(), { stderr, spawnfile: String(executable), exitCode: null as number | null, signalCode: null, kill: vi.fn(), }); queueMicrotask(() => { const profile = values .find((arg) => arg.startsWith("--user-data-dir="))! .split("=") .slice(1) .join("="); stderr.write( `launch explanation ${profile} http://127.0.0.1:1234/?key=URL_SECRET token=TOKEN_SECRET\n`, ); for (let chunk = 0; chunk < 16; chunk++) { stderr.write(`${"x".repeat(1024)}\n`); } stderr.write( `\nfinal startup marker ${profile} http://127.0.0.1:1234/?key=FINAL_URL_SECRET token=FINAL_TOKEN_SECRET\n`, ); child.exitCode = 13; child.emit("exit", 13, null); }); return child as unknown as ChildProcess; }); const layout = createCanvasLayout(); try { const state = emptyState(); const draw = createDraw(state, { baseRevision: 0, title: "fixture", additions: [ { id: "rectangle", type: "rectangle", x: 0, y: 0, width: 20, height: 20, }, ], }); const error = await layout .generate(state, draw) .catch((error) => error as Error); expect(error).toBeInstanceOf(Error); if (!(error instanceof Error)) throw new Error("Expected startup failure"); const evidence = JSON.parse( error.message.slice("Chromium exited during startup. ".length), ); expect(evidence).toMatchObject({ code: 13, signal: null }); expect(spawn).toHaveBeenCalledOnce(); // Evidence redacts the home directory, so a Chromium under $HOME appears as [home]. expect(evidence.executable).toBe( String(vi.mocked(spawn).mock.calls[0]?.[0]).replaceAll( homedir(), "[home]", ), ); expect(evidence.stderr.length).toBeLessThanOrEqual(2048); expect(evidence.stderr).toContain("launch explanation"); expect(evidence.stderr).toContain("final startup marker"); expect(evidence.stderr).toContain("[profile]"); expect(error.message).not.toMatch( /URL_SECRET|TOKEN_SECRET|pi-canvas-layout-|--user-data-dir=/, ); expect(calls[0]).toContain("--headless=new"); expect(calls[0]).not.toContain("--no-sandbox"); } finally { await layout.close(); } });