/** * Shoot: launch system Chrome, wait for page `data-jg-capture=ready` (tiny * handshake), pull pixels off the CDP screencast pump (see `captureViewportPng`), * write binary PNG. No Playwright. PNG never travels through the page console. * * Persistent service: `shoot daemon start` keeps headless Chrome warm and * starts apps/dev or apps/web lazily on first use. Manual `--keep`/`--connect` * remains available. See `jgengine-verify`. */ import { provisionCapturedGame } from "./provisionCapture"; import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import type { ChildProcess } from "node:child_process"; import { join, resolve } from "node:path"; import { type CdpSession, DEVICES, applyCaptureQuality, applyDevice, assertQualityApplied, captureViewportPng, checkoutIdentity, draftSuffix, ensureDevServer, ensureWebServer, forwardPageConsole, readCapturePageState, readMissingModels, missingModelsProblem, captureProfile, ensureCaptureFreeSpace, screencastCapturesFully, isUp, navigateCapturePageWithRetry, openPageSession, readReportedQuality, parseSizeArg, preparingCoverLabel, qualitySuffix, sizeForDraft, sizeSuffix, sweepCaptureProfiles, webGlRenderer, withBrowserSession, writePngAtomic, type Device, type SizeMode, } from "./browser-lib"; import { decodePng } from "../packages/assets/src/imageCodec"; import { shootOutPath } from "./shotPath"; import { clearOriginStorage } from "./capture-storage"; import { headRevision } from "./captureRevision"; import { engineRecord, resolveEngineIdentity, type EngineRecord } from "./engineIdentity"; import { externalCaptureUrl } from "./captureTarget"; import { assertOneTarget, serveGameDir, splitGameDir } from "./servedGame"; import { assertQuickIsIterationOnly, quickProfile, quickSuffix, quickTimingLine, splitQuickFlag } from "./capture-preset"; import { detail } from "./verbosity"; import { CAPTURE_FLAGS, captureFlagHelp, parseCaptureArgs, parseGraphicsTier, type GraphicsTier } from "../packages/jgengine/src/templates/captureArgs"; import { applyLookSearchParams, parseLookAim } from "./lookArg"; import { MIN_SAMPLED_SHARE, computeShotMetrics, evaluateThresholds, metricsPathFor, sceneFrameProblem, shotSignature, } from "./shot-metrics"; import { buildShotRecord, clearShotTarget, describeReplacement, writeShotRecord, type PreviousShot, } from "./shotProvenance"; import { markStep, SERVER_STEP_MS, withStepDeadline } from "./hangReport"; import { acquireWarmCaptureOrExit, runWithDaemonRecovery, ensureDaemonTarget, isDaemonArgv, runDaemonCommand, startDaemon, withDaemonWatch, brokerTurn, writeDaemonState, type ShootDaemonState, } from "./shoot-daemon"; /** One reload retry absorbs Vite's transient post-HMR rebuild window; see capture-retry.ts. */ const CAPTURE_MAX_ATTEMPTS = 2; /** What this run served, set once the engine gate passes and stamped into every shot record. */ let engineForRecord: EngineRecord | null = null; /** * Navigate to `url` and wait for an honest frame, reloading fresh once if the * first attempt lands in Vite's transient post-HMR rebuild window (stale module * graph → "start menu still on screen" / readiness timeout). The retry waits for * the dev server to settle, disables the page HTTP cache so no stale module is * reused, and re-navigates — turning the old "fails twice until daemon stop/start" * into an automatic in-invocation recovery. Deterministic failures (unknown state, * unregistered command) are not stale-shaped, so they surface on the first attempt. */ type Mode = "ui" | "play" | "poster" | "preview"; type DeviceArg = Device | "both"; type Args = { game: string; mode: Mode; device: DeviceArg; size: SizeMode; /** The tier `--quality` pinned; undefined leaves the game's own tier, which the summary still reports. */ quality?: GraphicsTier; /** `--draft`: the low-tier half-size iteration preset. */ draft: boolean; stage?: boolean | undefined; state?: string | undefined; preview?: string | undefined; fixture?: string | undefined; listFixtures: boolean; run?: string[] | undefined; settle?: number | undefined; spawn?: string | undefined; style?: string | undefined; look?: string | undefined; lookFrom?: string | undefined; view?: string | undefined; listViews: boolean; out?: string | undefined; url?: string | undefined; site?: string | undefined; connect?: number | undefined; keep: boolean; /** `--cold`: boot Chrome and Vite directly, proving a clean start. */ cold: boolean; inspect: boolean; /** Show a real window (off-screen) instead of headless Chrome. */ headed: boolean; /** 960x540 iteration preset: one settled frame, no evidence claims. */ quick: boolean; /** `--game-dir`: serve this game from another checkout instead of `games/`. */ gameDir: string | null; help: boolean; timeoutMs: number; timeoutExplicit: boolean; port?: number | undefined; width?: number | undefined; height?: number | undefined; params: [string, string][]; }; const HELP = `bun run shoot [game] [options] ${captureFlagHelp("shoot", "engine", CAPTURE_FLAGS)} JG_CAPTURE_SCREENCAST=0 forces Page.captureScreenshot instead of the screencast frame pump (same pixels, several times slower on software GL). Engine: Every run prints the engine it actually renders: the dev runner serves this checkout's source, so the line names its version and commit. --game-dir serves from another checkout - a lane's worktree, not this repo's games/ clone - and keeps the rest of this runner: this checkout's engine source, --state boot states, --view and the engine line. The folder is named after the game, and its parent is read for the engine pin. Persistent daemon (started for you; no lane ever starts it by hand): bun run shoot --mode play # starts or reuses the daemon, then attaches --cold skips the daemon entirely: fresh Chrome and Vite, for evidence runs that must prove a clean boot. Every run prints which happened and how long it took: warm: reused :9261 (0.2s) cold: started :9261 (4.1s) bun run shoot --serve # keep Chrome warm; Vite starts on demand bun run shoot daemon start|status|stop # managed background service bun run shoot daemon reap # retire warm Chrome idle past JG_SHOOT_IDLE_MINUTES Manual warm loop: bun run shoot --mode play --keep # cold boot, stays warm bun run shoot --mode play --connect --size half # cheap judge PNG --headed opens a real Chrome window off-screen, for debugging a capture; every run is headless unless you ask, and the window never lands on the desktop. --quick is the iteration preset: 960x540, one settled frame, no video or perf pass. It cannot support a 1600x900 pixel claim or a frame-time claim, so asking for either alongside it fails; re-run without --quick for the shot that goes in the PR. `; /** Map the shared capture command line (packages/jgengine/src/templates/captureArgs.ts) onto shoot's options. */ function parseArgs(argv: string[]): Args { // `--headed` is parsed here, not in CAPTURE_FLAGS: the scaffold's shoot.mjs has no local window to // show, so the flag stays engine-only instead of parsing there and doing nothing. const quick = splitQuickFlag("shoot", argv); // `--cold` is parsed here, not in CAPTURE_FLAGS: the portable harness has no daemon to skip. const cold = quick.argv.includes("--cold"); const headed = quick.argv.includes("--headed"); // `--game-dir` is parsed here, not in CAPTURE_FLAGS: the portable harness has no `games/` to swap. const served = splitGameDir(quick.argv); const parsed = parseCaptureArgs( "shoot", served.argv.filter((arg) => arg !== "--headed" && arg !== "--cold"), CAPTURE_FLAGS, ); const o = parsed.options; const str = (name: string): string | undefined => (typeof o[name] === "string" ? (o[name] as string) : undefined); const num = (name: string): number | undefined => (str(name) === undefined ? undefined : Number(str(name))); if (parsed.positionals.length > 1) throw new Error(`shoot: one game id, got ${parsed.positionals.join(" ")}`); const mode = str("mode") ?? "ui"; if (!["ui", "play", "poster", "preview"].includes(mode)) throw new Error(`--mode must be ui, play, poster, or preview (got ${mode})`); const run = str("run")?.split(",").map((name) => name.trim()).filter((name) => name.length > 0); const view = str("view"); const draft = o["draft"] === true; const quality = draft ? "low" : str("quality") === undefined ? undefined : parseGraphicsTier(str("quality")); const args: Args = { game: str("game") ?? parsed.positionals[0] ?? "world-of-warcraft", mode: mode as Mode, device: (str("device") ?? "desktop") as DeviceArg, ...(quality === undefined ? {} : { quality }), draft, size: sizeForDraft(draft, str("size") === undefined ? undefined : parseSizeArg(str("size"))), stage: o["stage"] === true ? true : undefined, state: str("state"), preview: str("preview") ?? (mode === "preview" ? "" : undefined), fixture: str("fixture"), listFixtures: o["list"] === true, run: run !== undefined && run.length > 0 ? run : undefined, settle: num("settle"), spawn: str("spawn"), style: str("style"), look: str("look"), lookFrom: str("look-from"), view: view === "" ? undefined : view, listViews: o["list-views"] === true || view === "", out: str("out"), url: str("url") === undefined ? undefined : externalCaptureUrl(str("url")), site: str("site"), connect: num("connect"), keep: o["keep"] === true, cold, inspect: o["inspect"] === true, headed, quick: quick.quick, gameDir: served.dir, help: parsed.help, timeoutMs: (num("timeout") ?? 60) * 1000, timeoutExplicit: str("timeout") !== undefined, port: num("port"), width: num("width"), height: num("height"), params: ((o["param"] as string[] | undefined) ?? []).map((pair) => [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)] as [string, string]), }; assertQuickIsIterationOnly({ tool: "shoot", quick: args.quick, width: args.width, height: args.height, size: str("size"), device: str("device"), }); if (args.site !== undefined && (args.look !== undefined || args.lookFrom !== undefined)) { throw new Error( "shoot: --look needs the dev-runner game shell, and --site renders a plain web page that never reads an aim. Serve the game from a dev runner and pass --url http://127.0.0.1:/?game= instead.", ); } if (!args.help && str("quality") !== undefined && args.mode === "ui" && args.view === undefined && args.look === undefined && args.url === undefined && args.site === undefined) { // The HUD preview mounts no 3D scene, so no tier ever reaches the page; this used to fail after // the whole boot as "never reported its tier". throw new Error(`shoot: --quality pins the 3D render tier, but --mode ui (the default) is a HUD-only preview with no 3D scene. Add --mode play.`); } if (args.quick) { const preset = quickProfile(true); args.width = preset.width; args.height = preset.height; args.size = "full"; } if (args.site !== undefined && !args.timeoutExplicit) { args.timeoutMs = process.platform === "linux" || process.env["CI"] !== undefined ? 30_000 : 10_000; } return args; } function devicesFor(arg: DeviceArg): Device[] { return arg === "both" ? ["desktop", "mobile"] : [arg]; } function outPathFor(args: Args, device: Device, outDir: string): string { if (args.out !== undefined) { const resolved = shootOutPath(args.out, outDir); if (args.device !== "both") return resolved; if (device === "desktop") return resolved; const dot = resolved.lastIndexOf("."); if (dot <= 0) return `${resolved}-mobile`; return `${resolved.slice(0, dot)}-mobile${resolved.slice(dot)}`; } const suffix = `${device === "mobile" ? "-mobile" : ""}${sizeSuffix(args.size)}${qualitySuffix(args.quality)}${draftSuffix(args.draft)}${quickSuffix(args.quick)}`; if (args.fixture !== undefined && args.fixture.length > 0) { const key = args.fixture.replace(/[^A-Za-z0-9._-]+/g, "_"); return join(outDir, `fixture-${key}${suffix}.png`); } if (args.view !== undefined) { const key = args.view.replace(/[^A-Za-z0-9._-]+/g, "_"); return join(outDir, `${args.game}-view-${key}${suffix}.png`); } if (args.state !== undefined) { const key = args.state.replace(/[^A-Za-z0-9._-]+/g, "_"); return join(outDir, `${args.game}-state-${key}${suffix}.png`); } if (args.preview !== undefined) { const state = args.preview === "" ? "default" : args.preview.replace(/[^A-Za-z0-9._-]+/g, "_"); return join(outDir, `${args.game}-preview-${state}${suffix}.png`); } if (args.site !== undefined) { const pathname = new URL(args.site.startsWith("/") ? args.site : `/${args.site}`, "http://site").pathname; const key = pathname.replace(/^\/+|\/+$/g, "").replace(/[^A-Za-z0-9._-]+/g, "_") || "home"; return join(outDir, `site-${key}${suffix}.png`); } return join(outDir, `${args.game}-${args.mode}${suffix}.png`); } function targetUrl(args: Args, device: Device, devBase: string): string { return applyCaptureQuality(rawTargetUrl(args, device, devBase), args.quality).toString(); } /** The page a shot opens, before the tier pin: `--quality` reaches every target the same way. */ function rawTargetUrl(args: Args, device: Device, devBase: string): URL { const aim = parseLookAim(args.look, args.lookFrom, { withNamedView: args.view !== undefined }); if (args.url !== undefined) { const url = new URL(args.url); url.searchParams.set("capture", "1"); url.searchParams.set("device", device === "mobile-landscape" ? "mobile" : device); // An external URL is commonly this engine's own dev runner on another checkout's Vite (a lane // measuring its branch), so it reads the same aim params as the local one. A page with no runner // publishes no applied aim, and `reportAppliedAim` fails the capture instead of returning a // plausible wrong view. applyLookSearchParams(url, aim); return url; } if (args.site !== undefined) { const path = args.site.startsWith("/") ? args.site : `/${args.site}`; const url = new URL(path, devBase); url.searchParams.set("capture", "1"); url.searchParams.set("device", device === "mobile-landscape" ? "mobile" : device); return url; } if (args.fixture !== undefined && args.fixture.length > 0) { const url = new URL(devBase); url.searchParams.set("fixture", args.fixture); url.searchParams.set("device", device === "mobile-landscape" ? "mobile" : device); url.searchParams.set("capture", "1"); return url; } const url = new URL(devBase); url.searchParams.set("game", args.game); url.searchParams.set("mode", args.mode); url.searchParams.set("device", device === "mobile-landscape" ? "mobile" : device); url.searchParams.set("capture", "1"); if (args.stage === true) url.searchParams.set("stage", "1"); if (args.state !== undefined) url.searchParams.set("state", args.state); if (args.preview !== undefined) url.searchParams.set("preview", args.preview); if (args.run !== undefined && args.run.length > 0) url.searchParams.set("run", args.run.join(",")); if (args.settle !== undefined && Number.isFinite(args.settle)) url.searchParams.set("settle", String(args.settle)); if (args.spawn !== undefined && args.spawn.length > 0) url.searchParams.set("spawn", args.spawn); if (args.style !== undefined && args.style.length > 0) url.searchParams.set("style", args.style); if (args.view !== undefined) url.searchParams.set("view", args.view); applyLookSearchParams(url, aim); return url; } function shotCommand(): string { return ["bun run shoot", ...process.argv.slice(2)].join(" "); } function gitProvenance(): { head: string; dirty: boolean } | undefined { try { const head = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); if (head.status !== 0) return undefined; const status = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }); return { head: head.stdout.trim(), dirty: (status.stdout ?? "").trim().length > 0 }; } catch { return undefined; } } /** * Read back the aim the page reports applying. The dev runner publishes it on `data-jg-look`, so a * missing readout means the override never reached the camera — the silent-no-op that used to return * a plausible screenshot of the game's own view and cost a whole round of re-shooting. A `--url` page * that applies `?look=` itself can publish the same string on `window.__jgLook`; the refusal is about * an unconfirmed camera, not about which checkout served the page. */ async function readAppliedAim(session: CdpSession): Promise<{ applied: string | null; shot: string | null }> { const read = `(() => { const reported = (value) => (typeof value === "string" && value.length > 0 ? value : null); const root = document.documentElement; return { applied: reported(root.dataset.jgLook) ?? reported(window.__jgLook) ?? reported(window.__jgCaptureLook) ?? null, shot: reported(root.dataset.jgView), }; })()`; return (await session.evaluate<{ applied: string | null; shot: string | null }>(read)) ?? { applied: null, shot: null }; } async function reportAppliedAim(session: CdpSession, args: Args): Promise { const aimed = args.look !== undefined && args.look.length > 0; // A `--view` can carry the aim instead of `--look`, and a view whose framing silently failed to // apply is the same wrong-view-that-looks-fine failure as a dropped `--look`. if (!aimed && args.view === undefined) return; const { applied, shot } = await readAppliedAim(session); if (args.view !== undefined && shot !== args.view) { throw new Error(`--view ${args.view} never reached the runner — no declared view was applied`); } if (typeof applied !== "string" || applied.length === 0) { if (!aimed && args.view !== undefined) { console.error(`shoot: view ${args.view} applied (no camera override)`); return; } throw new Error( `--look ${args.look} never reached the camera — the page reported no applied aim. ` + `A game dev runner publishes it for you, including one behind --url (?game=); ` + `a page that applies --param look= itself must report the aim it applied on ` + `document.documentElement.dataset.jgLook (or window.__jgLook) after the frame.`, ); } console.error(`shoot: ${args.view === undefined ? "look" : `view ${args.view}`} applied ${applied}`); } function formatCollisionReport(raw: string): string { try { const parsed = JSON.parse(raw) as { a: string; b: string; area: number }[]; return parsed.map((c) => `${c.a} ∩ ${c.b} (${c.area}px²)`).join(", "); } catch { return raw; } } async function shootOne( debugPort: number, args: Args, device: Device, outPath: string, devBase: string, previous: PreviousShot | undefined, ): Promise { const startedAt = performance.now(); let phaseStartedAt = startedAt; const timings: string[] = []; const mark = (name: string): void => { const now = performance.now(); timings.push(`${name}=${((now - phaseStartedAt) / 1_000).toFixed(2)}s`); phaseStartedAt = now; }; const session = await openPageSession(debugPort); mark("target"); let stopConsoleForward: (() => void) | undefined; try { await session.send("Page.enable"); await session.send("Runtime.enable"); stopConsoleForward = forwardPageConsole(session, "shoot:"); mark("enable"); const renderer = await webGlRenderer(session); if (renderer === null) { throw new Error("shoot: the launched Chrome has no WebGL2 - every frame would be an empty canvas; fix the launch flags before capturing"); } detail(`shoot: webgl2 ${renderer}`); const viewportSize = { width: args.width, height: args.height }; await applyDevice(session, device, args.size, viewportSize); mark("device"); const target = new URL(targetUrl(args, device, devBase)); for (const [key, value] of args.params) target.searchParams.set(key, value); const url = target.toString(); // A warm profile keeps the previous run's saves and settings, so a reused browser would render // "continue your story" where a clean one renders "hit the street" (#warm-capture signatures). await clearOriginStorage(session, target.origin); markStep(`open ${url}`); await navigateCapturePageWithRetry(session, url, devBase, args.timeoutMs, CAPTURE_MAX_ATTEMPTS, { legacyCanvas: args.url !== undefined }); mark("ready"); await reportAppliedAim(session, args); // Read the tier the game resolved, not the flag: a tier that never reached the render path is // the failure this readout exists to catch, and the summary line repeats it for the record. const reportedTier = await readReportedQuality(session); if (args.quality !== undefined) assertQualityApplied(args.quality, reportedTier); await new Promise((r) => setTimeout(r, 600)); mark("settle"); const profile = DEVICES[device]; const label = `${device} ${profile.width}x${profile.height}${args.size === "half" ? " (half-res)" : ""}${args.draft ? " (draft)" : ""} tier ${reportedTier ?? "n/a"}`; const preparing = await preparingCoverLabel(session); if (preparing !== null) { console.error( `shoot [${label}]: the scene is still preparing (${preparing}) - that frame is the loading cover, not the game; nothing was written`, ); return false; } const expected = captureProfile(device, args.size, viewportSize); // Read before capturing, not alongside it: the region is what lets the fast path reject a // frame whose 3D viewport the canvas never committed into, and a shot that is a black hole // where the world should be is worth more than the frame time the overlap saved. const { overflow, collision, ...regions } = await readCapturePageState(session); const editor = await session.evaluate(`document.documentElement.dataset.jgEditor === "1"`); const { bytes, via } = await captureViewportPng(session, { screencast: editor !== true && screencastCapturesFully(expected), expect: { width: Math.round(expected.width * expected.deviceScaleFactor), height: Math.round(expected.height * expected.deviceScaleFactor), }, ...(regions.region === undefined ? {} : { liveRegion: regions.region }), }); mark(`frame(${via})`); const decoded = decodePng(bytes); const frame = computeShotMetrics(decoded.width, decoded.height, decoded.data); const scoped = computeShotMetrics(decoded.width, decoded.height, decoded.data, regions); const viewport = (scoped.sampledShare ?? 1) >= MIN_SAMPLED_SHARE ? scoped : null; // Judged before the write, unlike the old post-write viewport warning: a frame that fails here // is not evidence, and a file on disk is what gets cited later. `--view`/`--look` promise a 3D // framing, so they demand a canvas whatever the mode; `--mode ui` alone is an honest HUD capture. const problem = sceneFrameProblem({ ...(regions.region === undefined ? {} : { region: regions.region }), frame, viewport, mode: args.mode, wantsScene: args.mode !== "ui" || args.view !== undefined || args.look !== undefined, }); if (problem !== null) { console.error(`shoot [${label}]: ${problem} — nothing was written`); return false; } if (regions.region === undefined) { console.error(`shoot [${label}]: mode ui HUD preview, no 3D canvas — this frame is not evidence of the world`); } writePngAtomic(outPath, bytes); const record = buildShotRecord({ bytes, command: shotCommand(), capturedAt: new Date().toISOString(), signature: shotSignature(decoded.width, decoded.height, decoded.data), width: decoded.width, height: decoded.height, ...(previous === undefined ? {} : { previous }), git: gitProvenance(), ...(engineForRecord === null ? {} : { engine: engineForRecord }), }); writeShotRecord(outPath, record); console.log(outPath); mark("score"); let ok = true; if (overflow !== null) { console.error(`HUD OVERFLOW [${label}]: panels escape the viewport — ${overflow}`); ok = false; } if (collision !== null) { console.error(`MOBILE LAYOUT COLLISION [${label}]: ${formatCollisionReport(collision)}`); ok = false; } const missingModels = missingModelsProblem(await readMissingModels(session)); if (missingModels !== null) { console.error(`${missingModels} [${label}]`); ok = false; } const replacement = describeReplacement(record); if (replacement !== null) console.error(`shoot [${label}]: ${replacement}`); // Viewport metrics are advisory now: a dead 3D view is refused before the write, so anything // reaching here is a frame that rendered something and is being measured for how it reads. if (viewport !== null) { for (const warning of evaluateThresholds(viewport)) { console.error(`shoot [${label}]: viewport ${warning.message}`); } } if (args.inspect) { const metricsPath = metricsPathFor(outPath); writeFileSync(metricsPath, JSON.stringify({ frame, viewport }, null, 2)); console.log(metricsPath); } mark("inspect"); const total = (performance.now() - startedAt) / 1_000; detail( args.quick ? quickTimingLine("shoot", { seconds: total, width: Math.round(expected.width * expected.deviceScaleFactor), height: Math.round(expected.height * expected.deviceScaleFactor), device, phases: timings, tier: reportedTier, }) : `shoot: timing ${device} tier ${reportedTier ?? "n/a"} ${timings.join(" ")} total=${total.toFixed(2)}s`, ); return ok; } finally { stopConsoleForward?.(); await session.close(); } } const rawArgv = process.argv.slice(2); if (isDaemonArgv(rawArgv)) { if (rawArgv.includes("--serve")) { await startDaemon({ foreground: true }); process.exit(0); } const daemonArgv = rawArgv[0] === "daemon" ? rawArgv.slice(1) : rawArgv; process.exit(await runDaemonCommand(daemonArgv)); } const args = parseArgs(rawArgv); if (args.help) { console.log(HELP); process.exit(0); } // Discovery: `shoot --list` or `shoot --fixture` (no name) prints the registered // engine preview fixtures from the @jgengine/ui registry (single source of truth). if (args.listFixtures || (args.fixture !== undefined && args.fixture.length === 0)) { // The @jgengine/ui registry is the single source of truth; scripts resolve it from // source (bare `@jgengine/*` specifiers only type-resolve through dist, not at bun runtime). const { PREVIEW_FIXTURES, previewFixtureNames } = await import( resolve(import.meta.dir, "../packages/ui/src/previewFixtures.ts") ); console.log("engine preview fixtures (bun run shoot --fixture ):"); for (const name of previewFixtureNames()) { console.log(` ${name.padEnd(18)} ${PREVIEW_FIXTURES[name]!.description}`); } process.exit(0); } const outDir = resolve(import.meta.dir, "../shots"); try { if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true }); } catch (error) { const code = error instanceof Error && "code" in error ? (error as NodeJS.ErrnoException).code : undefined; if (code !== "EEXIST" || !existsSync(outDir)) throw error; } const targets = devicesFor(args.device); const preparedShots = new Map(); if (!args.listViews) { for (const device of targets) { const path = outPathFor(args, device, outDir); preparedShots.set(path, clearShotTarget(path)); } } if (args.port !== undefined) process.env["JG_DEV_PORT"] = String(args.port); if (args.gameDir !== null) { assertOneTarget({ served: args.gameDir, ...(args.url === undefined ? {} : { url: args.url }), ...(args.site === undefined ? {} : { site: args.site }) }); serveGameDir(args.gameDir, args.game); } // An external server that is down fails the run before the profile sweep, which lists every // browser process and took 3 to 4 s on a busy Windows PC (2026-11-08). if (args.url !== undefined && !(await isUp(args.url))) { console.error(`shoot: nothing is listening at ${args.url} — start that external server first`); process.exit(1); } // Reclaim profiles that killed runs left behind before this one can add to them, and refuse to // start on a drive that cannot hold this capture. sweepCaptureProfiles(); // A game captured from this checkout pulls the packs it references first, the way its own `dev` does, // so a missing model in the shot is a real path bug rather than an unprovisioned checkout. if (args.url === undefined && args.site === undefined) await provisionCapturedGame(args.gameDir ?? resolve(import.meta.dir, "../games", args.game)); ensureCaptureFreeSpace(); interface ShootTarget { devBase: string; server: ChildProcess | null; serverPid: number | undefined; attachedDaemon: boolean; } /** Resolve the page this shot draws from: explicit URL, a daemon target, or a Vite this run owns. */ async function resolveTarget(daemon: ShootDaemonState | null): Promise { if (args.url !== undefined) { if (args.site !== undefined) throw new Error("shoot: --url and --site select different targets; pass one"); return { devBase: args.url, server: null, serverPid: undefined, attachedDaemon: daemon !== null }; } if (daemon !== null) { const target = await withStepDeadline("start or reuse the dev server", SERVER_STEP_MS, () => ensureDaemonTarget(daemon, args.site !== undefined ? "web" : "dev")); detail(`shoot: attached to daemon — chrome :${daemon.chromePort}, target ${target.base}`); return { devBase: target.base, server: null, serverPid: undefined, attachedDaemon: true }; } const server = await withStepDeadline("start or reuse the dev server", SERVER_STEP_MS, () => args.site === undefined ? ensureDevServer() : ensureWebServer()); return { devBase: server.base, server: server.child, serverPid: server.pid, attachedDaemon: false }; } /** * Print the game's declared `capture.views`. The runner publishes them on `data-jg-shots` as soon * as the game module resolves — well before an honest frame — so discovery costs a navigation, not * a capture, and still works when the `?shot=` that sent you here was the wrong name. */ async function listViews(debugPort: number, base: string, game: string): Promise { const session = await openPageSession(debugPort); try { await session.send("Page.enable"); await session.send("Runtime.enable"); const url = new URL(base); url.searchParams.set("game", game); await session.send("Page.navigate", { url: url.toString() }); const deadline = Date.now() + 30_000; while (Date.now() < deadline) { const raw = await session.evaluate(`document.documentElement.dataset.jgViews ?? null`); if (typeof raw === "string") { const shots = JSON.parse(raw) as string[]; if (shots.length === 0) { console.log(`${game} declares no capture.views — add them to defineGame({ capture: { views } })`); return 0; } console.log(`declared views (bun run shoot ${game} --view ):`); for (const shot of shots) console.log(` ${shot}`); return 0; } await new Promise((resolve) => setTimeout(resolve, 100)); } throw new Error(`timed out reading ${game}'s declared views`); } finally { await session.close(); } } /** * One capture pass against a resolved target. Kept a function so a run whose daemon * died under it can be repeated once on the direct path instead of failing. */ async function shootSession(daemon: ShootDaemonState | null): Promise { const { devBase, server, serverPid, attachedDaemon } = await resolveTarget(daemon); return withDaemonWatch(daemon, withBrowserSession( { keep: args.keep, connect: args.connect, timeoutMs: args.timeoutMs, server, serverPid, debugPort: daemon !== null ? daemon.chromePort : undefined, attach: attachedDaemon, leaveWarm: args.keep || attachedDaemon, chromePrefix: "jg-shoot-", turn: brokerTurn(daemon), headed: args.headed, hardDeadlineMs: args.site === undefined ? args.timeoutMs * Math.max(targets.length, 1) + 120_000 : args.timeoutMs * CAPTURE_MAX_ATTEMPTS * Math.max(targets.length, 1) + 10_000, }, async ({ debugPort, chrome }) => { if (args.listViews) return listViews(debugPort, devBase, args.game); let code = 0; for (const device of targets) { const outPath = outPathFor(args, device, outDir); const previous = preparedShots.get(outPath); const fits = await shootOne(debugPort, args, device, outPath, devBase, previous); if (!fits) code = 1; } if (args.keep && !attachedDaemon) { const state: ShootDaemonState = { identity: checkoutIdentity(), chromePort: debugPort, head: headRevision(), chromePid: chrome?.pid, userDataDir: chrome?.userDataDir, startedAt: new Date().toISOString(), }; const target = { port: Number(new URL(devBase).port), base: devBase, pid: serverPid ?? server?.pid }; if (args.url === undefined && args.site === undefined) { state.devPort = target.port; state.devBase = target.base; state.devPid = target.pid; } else if (args.url === undefined) { state.webPort = target.port; state.webBase = target.base; state.webPid = target.pid; } writeDaemonState(state); console.error(`shoot: kept warm — chrome debug port ${debugPort}, dev server on ${devBase}`); console.error(`shoot: next shot → bun run shoot ${args.url === undefined ? `${args.game} --mode ${args.mode}` : `--url ${args.url}`} (daemon auto-attach)`); console.error(`shoot: or explicit → bun run shoot ${args.url === undefined ? `${args.game} --mode ${args.mode}` : `--url ${args.url}`} --connect ${debugPort} --size half`); } return code; }, )); } /** * Name the engine this run renders, and stop before any browser starts when it is older than the * version the game pins. A `--url` page belongs to whatever server it points at, so it is not * checked — the identity line would describe this checkout, not that page. */ { const identity = resolveEngineIdentity(); if (args.url === undefined) { console.error(identity.line); engineForRecord = engineRecord(identity); } } const explicitTarget = args.connect !== undefined || args.port !== undefined || args.url !== undefined; // The daemon's Chrome was launched headless with the display frame clock, so a run that needs a // window of its own must not borrow it. An external --url is not this checkout's app either. const ownBrowser = args.headed ? "--headed needs its own browser window" : undefined; const warm = explicitTarget ? { daemon: null, mode: "cold" as const, seconds: 0 } : await acquireWarmCaptureOrExit({ cold: args.cold || ownBrowser !== undefined, ...(ownBrowser === undefined ? {} : { because: ownBrowser }), }); /** Run one session, reporting a failure the same way `withBrowserSession` does. */ async function attempt(daemon: ShootDaemonState | null): Promise { try { return await shootSession(daemon); } catch (error) { console.error(error instanceof Error ? error.message : error); return 1; } } process.exit(await runWithDaemonRecovery(warm, (daemon) => attempt(daemon)));