A local video studio for your coding agent. Describe a video in one sentence: your agent directs, your machine renders. Claude Code, Codex, Cursor, Devin and more. No API keys, no uploads.
Python agent-skillsai-agentscaptionsclaude-codeclaude-code-pluginclaude-skillscodexcursorexplainer-videoffmpegheadless-chromekokoro-ttslocal-firstmanimmcp-servermotion-graphicstext-to-speechvideovideo-editingvideo-generation
showtime 0.4.1 (draft): a browser that stops answering no longer hangs a command (macOS CI stalls)
Favio Vázquez1ab14bc9657e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a9ed373..24a4c90 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -172,6 +172,9 @@ All notable changes to showtime. Each entry says what changed and why, so this f- `guide --find` takes several words unquoted; the templates' sample URL is a reserved `.example` name; the siteshows a stray placeholder tag as text instead of hiding the page; the critic is described as reviewing everyvideo in quality mode; `history clear` also removes the signature picks.+ - A browser that stops answering no longer hangs a command: every page showtime opens has a deadline (5 minutes,+ longer for slow pages) and one retry in a new browser, and check exits with an error naming the step; a 3D look+ whose WebGL context is lost stays in check's report with its fallback.## 0.4.0 (2026-10-05)diff --git a/skills/showtime/references/components.md b/skills/showtime/references/components.mdindex 42984c9..25ec8ab 100644--- a/skills/showtime/references/components.md+++ b/skills/showtime/references/components.md@@ -57,9 +57,9 @@ Run `showtime motion` for the live list.| 4. Data: chart, world-map | 220-271 || 5. Product and UI: browser-frame / device-frame, cursor and keystrokes, code-block, ... | 273-335 || 6. Camera, stills, closers, texture | 337-378 |-| 7. Looks (WebGL): fluted-glass, tilt-shift, liquid-metal, mesh-gradient, god-rays, marble, metaballs | 380-549 |-| 8. Themes (runtime/themes) | 551-564 |-| 9. Writing your own component | 566-585 |+| 7. Looks (WebGL): fluted-glass, tilt-shift, liquid-metal, mesh-gradient, god-rays, marble, metaballs | 380-550 |+| 8. Themes (runtime/themes) | 552-565 |+| 9. Writing your own component | 567-586 |## 1. Setup (two lines) and the time model@@ -421,7 +421,8 @@ with its render: the `_looks` demo in the showtime repository's examples folder.when a seek comes back, so a long reel can have a look in every scene. Chrome keeps about 16 contexts perpage: `check` warns (`look_contexts`) above 8 looks on screen at once and fails above 14; past 12 at oncethe oldest give theirs back and show a still copy of their frame. A context the browser takes back anyway- is `look_lost`.+ (also one lost while the look builds its shaders: a GPU reset) is `look_lost`; the look draws again on a new+ one or shows its fallback, and keeps its place and its cost in check's report.- **With a GPU.** A GPU can hand the screenshot a WebGL canvas it has not finished drawing (the frame then showsthe look a few frames back), so in a render on a GPU each look reads its frame back into a 2D canvas the pageshows; `check` lists it as `present: "readback"`. It adds about 10 ms to a 1080p frame of a full-frame lookdiff --git a/skills/showtime/runtime/effects/gl.js b/skills/showtime/runtime/effects/gl.jsindex b426668..e6ff972 100644--- a/skills/showtime/runtime/effects/gl.js+++ b/skills/showtime/runtime/effects/gl.js@@ -285,6 +285,16 @@ function material(gl, h) {}}+/**+ * material() on a context that may be gone: true when built. A context the browser took back while a look built+ * on it (a GPU process that crashed or reset; seen on the macOS CI runner's virtual GPU) does nothing and reads+ * every shader as failed with no log (null): that is no context, not a broken shader, so it is false here and+ * the look gets a new context (or its fallback) when it draws, keeping its place in check's report.+ */+function buildOn(gl, h) {+ try { material(gl, h); return true; } catch (e) { if (gl.isContextLost()) return false; throw e; }+}+/* ---------------------------------------------- frames read back on a GPU */// In a render on a GPU the screenshot of a WebGL canvas can come out stale: the compositor reads the canvas's@@ -314,6 +324,14 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = nullconst readback = readbackHere();// what check reports (looks[].present): 'readback' (a 2D canvas the frames are read into) or 'webgl'el.__stLookPresent = readback ? 'readback' : 'webgl';+ // one lost context is one loss, whichever of the event, the failed build and the failed re-acquire sees it first+ // (a look's record exists only once its setup is done: a loss before that waits for the event or for draw())+ const countLost = (canvas) => {+ const rec = el.__stLook;+ if (!rec || (canvas && canvas.__stCounted)) return;+ if (canvas) canvas.__stCounted = true;+ rec.lost = (rec.lost || 0) + 1;+ };const layer = {el, gl: null, glc: null, canvas: null, ctx: null, px: null, buf: null, W, H, dpr, scale, box: [bw, bh], used: 0, failed: false, readback,/** Get a context (a new canvas each time) and build every handle on it. false when WebGL cannot be had. */@@ -328,11 +346,11 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = nullcanvas.setAttribute('aria-hidden', 'true');let gl = null;try { gl = canvas.getContext('webgl', opts) || canvas.getContext('experimental-webgl', opts); } catch { gl = null; }- if (!gl) return false;+ if (!gl || gl.isContextLost()) return false;// a context the browser takes back (too many at once, a GPU reset) is reported: check says look_lostcanvas.addEventListener('webglcontextlost', () => {if (canvas.__stReleased) return;- if (el.__stLook) el.__stLook.lost = (el.__stLook.lost || 0) + 1;+ countLost(canvas);if (layer.glc === canvas) { layer.gl = null; LIVE.delete(layer); }});if (readback) {@@ -355,7 +373,7 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = nulllayer.buf = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER, layer.buf);gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);- for (const h of handles) material(gl, h);+ for (const h of handles) if (!buildOn(gl, h)) { layer.gl = null; return false; }LIVE.add(layer);hookSeeks();return true;@@ -384,11 +402,13 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = nullconst ext = gl.getExtension('WEBGL_lose_context');if (ext) ext.loseContext();},+ /** The context went while a handle was built on it: let it go; draw() gets a new one or the fallback. */+ dropLost() { countLost(layer.glc); LIVE.delete(layer); layer.gl = null; },/** defines: {NAME: value} become #define lines, for variants compiled apart instead of branched per pixel */program(frag, defines = {}) {const h = { kind: 'program', name, frag, defines, prog: null, aPos: -1, loc: {} };handles.push(h);- if (layer.gl) material(layer.gl, h);+ if (layer.gl && !buildOn(layer.gl, h)) layer.dropLost();return h;},/** Upload an image or canvas. mips: draw it into a power-of-two canvas first and build mipmaps. */@@ -401,14 +421,14 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = nulltry { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source); } catch { /* keep the last */ }} };handles.push(h);- if (layer.gl) material(layer.gl, h);+ if (layer.gl && !buildOn(layer.gl, h)) layer.dropLost();return h;},/** An offscreen RGBA target of w x h px (linear filtering, clamped). */target(w, h) {const t = { kind: 'target', name, w, h, tex: null, fb: null };handles.push(t);- if (layer.gl) material(layer.gl, t);+ if (layer.gl && !buildOn(layer.gl, t)) layer.dropLost();return t;},/**@@ -420,7 +440,10 @@ export function lookLayer(el, { name, scale = 1, alpha = false, fallback = null// no context to be had any more: the look's still fallback, oncelayer.failed = true;if (layer.canvas) layer.canvas.style.visibility = 'hidden';- if (el.__stLook) { el.__stLook.lost = (el.__stLook.lost || 0) + 1; el.__stLook.gl = false; }+ if (el.__stLook) {+ countLost(layer.glc); el.__stLook.gl = false; el.__stLook.present = null;+ el.__stLook.note = 'WebGL context lost and no new one to be had: drew the fallback';+ }if (fallback) fallback();}const gl = layer.gl;diff --git a/skills/showtime/scripts/adopt.mjs b/skills/showtime/scripts/adopt.mjsindex d258b76..c89dbe1 100644--- a/skills/showtime/scripts/adopt.mjs+++ b/skills/showtime/scripts/adopt.mjs@@ -17,7 +17,7 @@ import {parseCli, runMain, UserError, info, warn, c, slugify, jobDir, venvPython, pyEnv, runPyCli, runProc, cpuCount,fmtDuration, IS_WIN,} from './lib/cli.mjs';-import { openBrowser, openStage, openLab, parseSize } from './lib/stagehost.mjs';+import { openBrowser, openPage, openLab, parseSize } from './lib/stagehost.mjs';import { resolveFF, ffmpeg, probe, hasEncoder } from './lib/ff.mjs';import { skillDir } from './lib/deps.mjs';import { resolveJobDir } from './lib/studio/paths.mjs';@@ -762,7 +762,7 @@ async function probePage(dest, cfg, findings, entry, quietNoDuration = false) {try {srv = await startServer({ root: dest, port: 0 });b = await openBrowser({});- sess = await openStage(b.browser, { url: srv.url, page: 'index.html', config: cfg, followPageSize: false, readyTimeout: 60000 });+ sess = await openPage(b, { url: srv.url, page: 'index.html', config: cfg, followPageSize: false, readyTimeout: 60000 });const probe = await sess.page.evaluate(() => (window.__stAdoptProbe ? window.__stAdoptProbe() : null));const errs = sess.log.errors.slice(0, 3);for (const e of errs) findings.add('warning', 'page_error', `the page threw while loading: ${e.message}`, '', 'showtime check lists every page error with its time');@@ -789,7 +789,7 @@ async function determinismPage(dest, res, findings) {b = await openBrowser({});const cfg = readJSON(path.join(dest, 'showtime.json'));// a loop is also seeked one frame past its end (frame n must be frame 0 again)- sess = await openStage(b.browser, { url: srv.url, page: 'index.html', config: res.loop ? { ...cfg, duration: cfg.duration + 2 / res.fps } : cfg, followPageSize: false });+ sess = await openPage(b, { url: srv.url, page: 'index.html', config: res.loop ? { ...cfg, duration: cfg.duration + 2 / res.fps } : cfg, followPageSize: false });const shot = async (k) => { await sess.seek(k / res.fps); return sess.shot({ format: 'png' }); };const p1 = [];for (const k of ks) p1.push(await shot(k));@@ -797,7 +797,7 @@ async function determinismPage(dest, res, findings) {for (let i = ks.length - 1; i >= 0; i--) p2[i] = await shot(ks[i]);await new Promise((r) => setTimeout(r, 150));const again = await sess.shot({ format: 'png' }); // still on ks[0]: nothing may move in real time- lab = await openLab(b.browser, srv.url);+ lab = await openLab(b, srv.url);const frames = [];let verdict = 'deterministic';for (let i = 0; i < ks.length; i++) {diff --git a/skills/showtime/scripts/check.mjs b/skills/showtime/scripts/check.mjsindex 3f2a31e..f756784 100644--- a/skills/showtime/scripts/check.mjs+++ b/skills/showtime/scripts/check.mjs@@ -7,8 +7,8 @@ import path from 'node:path';import crypto from 'node:crypto';import { fileURLToPath } from 'node:url';import { startServer } from './server.mjs';-import { parseCli, runMain, resolveProject, info, c, fmtTime, fmtDuration, parseTimes, parseTime, UserError, cpuCount, workName, briefOutput, runPyCli, hasPyModule, sinceLastLooked, printSince } from './lib/cli.mjs';-import { openBrowser, openStage, openLab, parseSize, paceSummary } from './lib/stagehost.mjs';+import { parseCli, runMain, failNow, resolveProject, info, c, fmtTime, fmtDuration, parseTimes, parseTime, UserError, cpuCount, workName, briefOutput, runPyCli, hasPyModule, sinceLastLooked, printSince } from './lib/cli.mjs';+import { openBrowser, openPage, openLab, parseSize, paceSummary, watchBrowser, closeSoon, STUCK_HINT } from './lib/stagehost.mjs';import { textSnapshot, hideText, fontInfo, leafAlpha, captionCollisions, gpuProbeScript } from './lib/audit.mjs';import { phoneConfig, createPhone, readNeed, readingRate, ptOf, phoneLine } from './lib/phone.mjs';import { brandFindings } from './lib/brandcheck.mjs';@@ -169,8 +169,11 @@ const snip = (s, n = 40) => (s.length > n ? s.slice(0, n - 1) + '…' : s);export function looksLine(looks) {const items = (looks && looks.items) || [];if (!items.length) return '';+ // a look that lost its WebGL context after it set up keeps its passes' cost, and says it fell back hereconst one = (lk) => `${lk.look}${items.filter((x) => x.look === lk.look).length > 1 && lk.sel ? ` ${lk.sel}` : ''} ` +- (lk.gl && Number.isFinite(Number(lk.ms)) ? `${Number(lk.ms)} ms${Number(lk.ms) > looks.budget_ms ? ' (over)' : ''}` : 'fallback (no WebGL)');+ ((lk.gl || Number(lk.ms) > 0) && Number.isFinite(Number(lk.ms))+ ? `${Number(lk.ms)} ms${Number(lk.ms) > looks.budget_ms ? ' (over)' : ''}${lk.gl ? '' : ' (WebGL lost: fallback here)'}`+ : 'fallback (no WebGL)');return `${items.map(one).join(', ')} per frame without a GPU (budget ${looks.budget_ms} ms)`;}@@ -189,13 +192,21 @@ async function main() {const add = (sev, code, message, extra = {}) => findings.push({ severity: sev, code, message, ...extra });const quiet = !!a.quiet;const talk = !quiet && !a.json && !briefOutput(); // progress steps: terminals and --verbose only- const step = (m) => { if (talk) info(c.dim(` ${m}`)); };+ let doing = 'opening the page'; // check's last step (the watchdog's error names it)+ const step = (m) => { doing = m; if (talk) info(c.dim(` ${m}`)); };if (talk) info(`${c.bold('showtime check')} ${proj.dir}`);const server = await startServer({ root: proj.dir, port: 0 });const b = await openBrowser({ gpu: a.gpu || 'auto' });- const cleanup = async () => { await b.browser.close().catch(() => {}); await server.close().catch(() => {}); };+ // every page opens under the page-open deadline (stagehost openGuarded: once more in a new browser, then an+ // error naming the step), and a browser that stops answering at any other step ends check with an error+ // instead of a check that never returns (a macOS CI runner's check once outlived its caller's 5 minutes)+ const stopWatch = watchBrowser(b, (m, hint) => failNow(`${m}; check's last step: ${doing}`, hint));+ const cleanup = async () => { stopWatch(); await closeSoon(b.browser.close()); await server.close().catch(() => {}); };let sess, lab, sess2;+ // once the first page is open, a later open that finds the browser stuck must not go on in a new one (the open+ // page belongs to the old browser): end with the error+ const noRelaunch = { onRetry: (m, what) => failNow(`the browser stopped answering: ${what}; check's last step: ${doing}`, STUCK_HINT) };let phone = null, floorPx = TINY * 1080, ranTimeline = false; // the phone check's collector; smallest readable size in frame pxlet reel = { on: false, source: 'default', detail: '' }; // the showreel tone (showtime.json tone, the job's tone or its brief)const report = { project: proj.dir, page: proj.page, ok: false, findings, timings: {}, samples: [] };@@ -212,11 +223,13 @@ async function main() {// ---------------------------------------------------------- loadlet t = Date.now();try {- sess = await openStage(b.browser, { url: server.url, page: proj.page, config: proj.config, size, init: gpuProbeScript(false) });+ sess = await openPage(b, { url: server.url, page: proj.page, config: proj.config, size, init: gpuProbeScript(false) });} catch (e) {+ if (e && e.browserStuck) throw e; // the browser, not the page: an error, not a findingadd('error', 'ready_failed', String(e.message || e), { fix: e.hint || 'open the page with `showtime preview` and look at the console' });return await finish();}+ doing = 'opened the page; reading its timeline and text';const inf = sess.info;// an overlay page (rendered with --alpha over other footage: lower thirds, step chips) is empty// between its elements on purpose: <body data-overlay> or showtime.json "overlay": true@@ -242,7 +255,9 @@ async function main() {.map((e) => (e.closest('[data-storyboard-shot]') || e.closest('[id]') || {}).id || '?'))]).catch(() => []);if (briefs.length) add('warning', 'storyboard_brief', `${briefs.length} shot(s) still show their storyboard brief instead of a picture: ${briefs.slice(0, 8).join(', ')}${briefs.length > 8 ? ', ...' : ''}`,{ fix: 'build each shot in its <section> from its brief (storyboard.json has every row), then delete the [data-storyboard-brief] elements' });- lab =await openLab(b.browser, server.url);+ doing = 'opening the image lab page';+ lab = await openLab(b, server.url, noRelaunch);+ doing = 'opened the image lab page; sampling the frames';const D = inf.duration, fps = inf.fps, W = inf.width, H = inf.height;// language of the on-screen text (sets the reading speed): showtime.json "lang", else <html lang>, else enconst pageLang = await sess.page.evaluate(() => document.documentElement.getAttribute('lang') || '').catch(() => '');@@ -922,7 +937,7 @@ async function main() {const hashes = [];const cross = [];try {- sess2 = await openStage(b.browser, { url: server.url, page: proj.page, config: proj.config, size });+ sess2 = await openPage(b, { url: server.url, page: proj.page, config: proj.config, size }, noRelaunch);for (let i = uniq.length - 1; i >= 0; i--) {if (!A[i]) continue;await sess2.seek(uniq[i]);@@ -936,8 +951,9 @@ async function main() {}}} catch (e) {+ if (e && e.browserStuck) throw e;add('warning', 'determinism_incomplete', `the second page load failed: ${String(e.message || e).split('\n')[0]}`);- } finally { if (sess2) { await sess2.close(); sess2 = null; } }+ } finally { if (sess2) { await closeSoon(sess2.close()); sess2 = null; } }hashes.sort((x, y) => x.t - y.t);report.determinism.hashes = hashes;report.determinism.cross = cross;@@ -1358,7 +1374,7 @@ async function main() {if (asks) {t = Date.now();const gpuSels = await sess.page.evaluate(() => [...document.querySelectorAll('canvas[data-st-ctx~="webgpu"]')].map((c) => (c.id ? '#' + c.id : null)).filter(Boolean)).catch(() => []);- const noGpu = await probeNoGpu({ browser: b.browser, url: server.url, proj, size, lab, times: sampleTimes, gpuSels });+ const noGpu = await probeNoGpu({ b, url: server.url, proj, size, lab, times: sampleTimes, gpuSels, noRelaunch });// name the calls that ask (requestAdapter, a 'webgpu' context) first; a bare navigator.gpu test only when nothing else showsconst named = [...runtimeWhere.map(([what, w]) => ({ what, at: rel(w) || 'an unknown line' })), ...staticHits.map((h) => ({ what: h.what, at: `${h.file}:${h.line}` }))];const strong = named.filter((n) => n.what !== 'navigator.gpu');@@ -1379,6 +1395,7 @@ async function main() {report.webgpu = { where: staticHits.map((h) => `${h.what} at ${h.file}:${h.line}`).slice(0, 4), asked: false };}} catch (e) {+ if (e && e.browserStuck) throw e;add('info', 'webgpu_probe_failed', `the WebGPU probe did not run: ${String(e.message || e).split('\n')[0]}`);}// WebGL looks (fluted-glass, tilt-shift, liquid-metal, mesh-gradient, god-rays, marble, metaballs;@@ -1408,7 +1425,9 @@ async function main() {const moves = /still move/.test(lk.note || ''), what = String(lk.note || '').replace(/^no WebGL:\s*(drew\s+)?/, '');add('warning', 'look_fallback', `${lk.look} ${lk.sel} drew its ${moves ? '' : 'still '}fallback${what ? ` (${what})` : ''}: WebGL is not available in this browser, so ${moves ? 'the look is drawn flat' : 'the look does not move'} here and this render will differ from one made where WebGL works`,{ fix: 'render where Chrome has WebGL (with or without a GPU: SwiftShader is enough); `showtime doctor` shows the browser' });- } else if (lk.ms > budget) {+ }+ // a look that lost its context after it set up still knows its passes: what it costs where WebGL works+ if (lk.ms > budget) {const passes = (lk.passes || []).map((p) => `${p.kind} ${p.w}x${p.h}`).join(' + ');add('warning', 'look_budget', `${lk.look} ${lk.sel} costs about ${lk.ms} ms per frame without a GPU (${passes}; budget ${budget} ms): on a machine without a GPU every frame it shows renders that much slower`,{ fix: KNOB[lk.look] || 'render the look at a smaller data-scale' });@@ -1450,7 +1469,7 @@ async function main() {if (lab && !overlayPage) {t = Date.now();try {- sess2 = await openStage(b.browser, { url: server.url, page: proj.page, config: proj.config, size });+ sess2 = await openPage(b, { url: server.url, page: proj.page, config: proj.config, size }, noRelaunch);report.cuts = await cutFrames({ sess: sess2, lab, fps, W, lastT, txWin });const late = report.cuts.filter((x) => x.late);if (late.length) {@@ -1458,8 +1477,9 @@ async function main() {{ t: late[0].t, times: late.map((c) => c.t), fix: 'decide what a scene draws from the stage\'s own clip windows: ST.clips() is frame-exact (on screen while t >= start && t < end); do not compare t with scene times typed again in the script or read from data-start yourself' });}} catch (e) {+ if (e && e.browserStuck) throw e;add('info', 'cut_probe_failed', `the first frames after the cuts were not probed: ${String(e.message || e).split('\n')[0]}`);- } finally { if (sess2) { await sess2.close(); sess2 = null; } }+ } finally { if (sess2) { await closeSoon(sess2.close()); sess2 = null; } }report.timings.cuts = Date.now() - t;}const log = sess.log;@@ -1591,8 +1611,8 @@ async function main() {await lookHistory();return await finish();} finally {- if (lab) await lab.close();- if (sess) await sess.close();+ if (lab) await closeSoon(lab.close());+ if (sess) await closeSoon(sess.close());await cleanup();}@@ -1868,11 +1888,11 @@ function webgpuSources(dir, requests, base) {* screen, the page's own WebGL / 2D canvases are hidden for a moment: when that changes the pixels under* them, the fallback draws. -> { drew: {t, sel, ctx} | null, probed: n, errors: [page errors] }*/-async function probeNoGpu({ browser, url, proj, size, lab, times, gpuSels }) {+async function probeNoGpu({ b, url, proj, size, lab, times, gpuSels, noRelaunch }) {let s2 = null;const res = { drew: null, probed: 0, errors: [] };try {- s2 = await openStage(browser, { url, page: proj.page, config: proj.config, size, init: gpuProbeScript(true) });+ s2 = await openPage(b, { url, page: proj.page, config: proj.config, size, init: gpuProbeScript(true) }, noRelaunch);// the middle of every clip that holds a canvas first, then the sample timesconst mids = await s2.page.evaluate(() => {const all = [...document.querySelectorAll('[data-start]')], cl = window.ST.clips(), out = [];@@ -1915,8 +1935,9 @@ async function probeNoGpu({ browser, url, proj, size, lab, times, gpuSels }) {}res.errors = s2.log.errors.slice(0, 3).map((e) => String(e.message).split('\n')[0]);} catch (e) {+ if (e && e.browserStuck) throw e;res.errors.push(String(e.message || e).split('\n')[0]);- } finally { if (s2) await s2.close(); }+ } finally { if (s2) await closeSoon(s2.close()); }return res;}diff --git a/skills/showtime/scripts/demo.mjs b/skills/showtime/scripts/demo.mjsindex 742a544..88c1e67 100644--- a/skills/showtime/scripts/demo.mjs+++ b/skills/showtime/scripts/demo.mjs@@ -10,7 +10,7 @@import fs from 'node:fs';import path from 'node:path';import { pathToFileURL } from 'node:url';-import { launchBrowser } from './lib/chrome.mjs';+import { launchGuarded, openGuarded, closeSoon } from './lib/stagehost.mjs';import { parseCli, runMain, UserError, info, warn, c, jobDir, fmtDuration, printHelp, Progress } from './lib/cli.mjs';import { newCaptureContext, installConsent, waitConsent, cleanupOverlays, robustGoto, detectBotWall, blockedMarkdown, slug, sleep, serveStatic, landingProblem, redactUrl, chromeUA, emulatePlatform, hostPlatform } from './lib/capture.mjs';import { resolveFF, ffmpeg, fpsArg } from './lib/ff.mjs';@@ -440,17 +440,25 @@ async function record(argv) {info(`${c.bold('demo record')} ${path.basename(scriptPath)} ${c.dim(`${viewport.width}x${viewport.height} @${dpr}x, ${fps} fps${baseUrl ? ', ' + baseUrl : ''}`)}`);if (server) info(c.dim(` serving ${server.root} (plain static server, stopped when done)`));info(c.dim(` output ${out}`));- const { browser } = await launchBrowser({ gpu: o.gpu, headless: !o.headed });+ const B = await launchGuarded({ gpu: o.gpu, headless: !o.headed });let rec;try {const platform = String(o.platform || so.platform || hostPlatform()).toLowerCase();- const ctx = await newCaptureContext(browser, { css: viewport, dpr, mobile: false }, { dark: !!o.dark, reducedMotion: 'no-preference',- userAgent: chromeUA(browser.version(), { platform }) });- await emulatePlatform(ctx, platform);+ // the context, the tab and its CDP session under the page-open deadline (once more in a new browser)+ const { consentLog, page, cdp } = await openGuarded(B, async (browser, track) => {+ track.step = 'creating the browser context';+ const ctx = await newCaptureContext(browser, { css: viewport, dpr, mobile: false }, { dark: !!o.dark, reducedMotion: 'no-preference',+ userAgent: chromeUA(browser.version(), { platform }) });+ await emulatePlatform(ctx, platform);+ track.step = 'setting up the consent clicker';+ const consentLog = o['no-consent'] ? null : await installConsent(ctx);+ track.step = 'opening a tab';+ const page = await ctx.newPage();+ track.step = 'opening the tab\'s CDP session';+ const cdp = await ctx.newCDPSession(page);+ return { consentLog, page, cdp, close: () => ctx.close() };+ }, { label: 'opening the recording tab' });if (platform !== hostPlatform()) info(c.dim(` the page sees ${platform} (recording on ${hostPlatform()})`));- const consentLog = o['no-consent'] ? null : await installConsent(ctx);- const page = await ctx.newPage();- const cdp = await ctx.newCDPSession(page);const animations = o.animations === 'real' ? 'real' : 'step';rec = new Recorder({ page, cdp, out, fps, dpr, viewport, baseUrl, quality: Math.min(100, Math.max(40, Number(o.quality))), animations });rec.consentLog = consentLog;@@ -470,7 +478,7 @@ async function record(argv) {}if (!rec.n) throw new UserError('the script finished without recording any frame', 'add steps like `await demo.wait(1)` or `await demo.click(...)`');} finally {- await browser.close().catch(() => {});+ await closeSoon(B.browser.close());if (server) { try { await server.close(); } catch { /* already closed */ } }}const duration = rec.n / fps;diff --git a/skills/showtime/scripts/lib/capture.mjs b/skills/showtime/scripts/lib/capture.mjsindex 323981b..dd8341d 100644--- a/skills/showtime/scripts/lib/capture.mjs+++ b/skills/showtime/scripts/lib/capture.mjs@@ -9,6 +9,7 @@ import net from 'node:net';import { pathToFileURL } from 'node:url';import { depPath } from './deps.mjs';import { UserError } from './cli.mjs';+import { openGuarded, closeSoon } from './stagehost.mjs';import { realpathUnderRoot, symlinkRefusal, escapesBySymlink } from './pathguard.mjs';export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));@@ -519,14 +520,21 @@ export async function contactSheet(browser, items, outFile, { title = '', cols =figcaption{padding:6px 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:13px;color:#c9c9d1}b{color:#fff;margin-right:4px}</style></head><body>${title ? `<h1>${esc(title)}</h1>` : ''}<main>${cells}</main></body></html>`);- const page = await browser.newPage({ viewport: { width, height: 800 }, deviceScaleFactor: 1 });+ let page = null;try {- await page.goto(pathToFileURL(htmlFile).href, { waitUntil: 'load', timeout: 60000 });+ // the tab and its load under the page-open deadline (the browser is the caller's: no second try)+ page = await openGuarded({ browser }, async (br, track) => {+ track.step = 'opening a tab';+ const pg = await br.newPage({ viewport: { width, height: 800 }, deviceScaleFactor: 1 });+ track.step = 'loading the sheet';+ await pg.goto(pathToFileURL(htmlFile).href, { waitUntil: 'load', timeout: 60000 });+ return pg;+ }, { label: 'opening the contact sheet' });await page.evaluate(() => Promise.all([...document.images].map((i) => i.decode().catch(() => {}))));fs.mkdirSync(path.dirname(path.resolve(outFile)), { recursive: true });await page.screenshot({ path: outFile, fullPage: true, type: 'jpeg', quality: 82 });} finally {- await page.close();+ if (page) await closeSoon(page.close());try { fs.unlinkSync(htmlFile); } catch { /* keep */ }}return outFile;diff --git a/skills/showtime/scripts/lib/cli.mjs b/skills/showtime/scripts/lib/cli.mjsindex 3cb79f6..eaf613a 100644--- a/skills/showtime/scripts/lib/cli.mjs+++ b/skills/showtime/scripts/lib/cli.mjs@@ -98,6 +98,17 @@ export async function runMain(main) {}}+/**+ * End the command now with an error, in runMain's words (for a watchdog: the command's own work is stuck in a+ * call that never returns, so it cannot throw).+ */+export function failNow(message, hint) {+ PLOG.error = String(message).split('\n')[0].slice(0, 300);+ process.stderr.write(`${c.red(`${CMD}: error:`)} ${message}\n`);+ if (hint) process.stderr.write(` ${c.bold('fix:')} ${hint}\n`);+ process.exit(1);+}+/** Known failure patterns -> one-line fixes. */export function hintFor(msg) {const m = String(msg);diff --git a/skills/showtime/scripts/lib/export/probe.mjs b/skills/showtime/scripts/lib/export/probe.mjsindex ad1ca49..0d2abc2 100644--- a/skills/showtime/scripts/lib/export/probe.mjs+++ b/skills/showtime/scripts/lib/export/probe.mjs@@ -1,7 +1,7 @@// Probe a project for `showtime export html`: open it in render mode (live shader transitions, as// the exported player draws them), play through the timeline and record every file the page asks// the server for, the chapters, the poster frame and (on request) the offline ST.score.-import { openBrowser, stageSource, isLocalUrl, withTimeout, pullScore } from '../stagehost.mjs';+import { openBrowser, openGuarded, closeSoon, stageSource, isLocalUrl, withTimeout, pullScore } from '../stagehost.mjs';import { UserError } from '../cli.mjs';// Film.start() options are private to film.js; this hook keeps its `acts` (or `chapters`) for the@@ -95,37 +95,46 @@ export async function probeProject(o) {const consoleErrors = [];const blocked = [];try {- const context = await b.browser.newContext({- viewport: { width, height }, deviceScaleFactor: 1, colorScheme: 'light', reducedMotion: 'no-preference',- locale: 'en-US', timezoneId: 'UTC', serviceWorkers: 'block',- });- const page = await context.newPage();- page.on('request', (r) => {- const u = r.url();- if (!u.startsWith(origin + '/')) return;- const p = decodeURIComponent(new URL(u).pathname);- if (!seen.has(p)) { seen.add(p); requests.push(p); firstAt.set(p, curT); }- });- page.on('response', (r) => {- if (r.status() >= 400 && r.url().startsWith(origin + '/')) failed.push({ path: decodeURIComponent(new URL(r.url()).pathname), status: r.status() });- });- page.on('pageerror', (e) => errors.push(String(e.message || e).slice(0, 400)));- page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 400)); });- await page.route('**/*', (route) => {- const u = route.request().url();- if (isLocalUrl(u)) return route.continue();- if (!blocked.includes(u)) blocked.push(u);- return route.abort('blockedbyclient');- });- const seed = cfg.seed === undefined ? 1 : cfg.seed;- const renderCfg = { config: cfg, override: null, alpha: false, settle: 'raf1', layers: false, seed };- await page.addInitScript({ content: `window.__ST_RENDER__=${JSON.stringify(renderCfg)};\n${FILM_HOOK}\n${stageSource()}` });- const target = `${o.url}/${String(o.page || 'index.html').replace(/^\/+/, '')}`;- try {- await page.goto(target, { waitUntil: 'load', timeout: 60000 });- } catch (e) {- throw new UserError(`could not open ${target}: ${e.message.split('\n')[0]}`);- }+ // the context, the tab and the first load under the page-open deadline (once more in a new browser)+ const { context, page } = await openGuarded(b, async (browser, track) => {+ for (const list of [requests, failed, errors, consoleErrors, blocked]) list.length = 0;+ seen.clear(); firstAt.clear();+ track.step = 'creating the browser context';+ const context = await browser.newContext({+ viewport: { width, height }, deviceScaleFactor: 1, colorScheme: 'light', reducedMotion: 'no-preference',+ locale: 'en-US', timezoneId: 'UTC', serviceWorkers: 'block',+ });+ track.step = 'opening a tab';+ const page = await context.newPage();+ page.on('request', (r) => {+ const u = r.url();+ if (!u.startsWith(origin + '/')) return;+ const p = decodeURIComponent(new URL(u).pathname);+ if (!seen.has(p)) { seen.add(p); requests.push(p); firstAt.set(p, curT); }+ });+ page.on('response', (r) => {+ if (r.status() >= 400 && r.url().startsWith(origin + '/')) failed.push({ path: decodeURIComponent(new URL(r.url()).pathname), status: r.status() });+ });+ page.on('pageerror', (e) => errors.push(String(e.message || e).slice(0, 400)));+ page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 400)); });+ await page.route('**/*', (route) => {+ const u = route.request().url();+ if (isLocalUrl(u)) return route.continue();+ if (!blocked.includes(u)) blocked.push(u);+ return route.abort('blockedbyclient');+ });+ const seed = cfg.seed === undefined ? 1 : cfg.seed;+ const renderCfg = { config: cfg, override: null, alpha: false, settle: 'raf1', layers: false, seed };+ await page.addInitScript({ content: `window.__ST_RENDER__=${JSON.stringify(renderCfg)};\n${FILM_HOOK}\n${stageSource()}` });+ const target = `${o.url}/${String(o.page || 'index.html').replace(/^\/+/, '')}`;+ track.step = 'loading the page';+ try {+ await page.goto(target, { waitUntil: 'load', timeout: 60000 });+ } catch (e) {+ throw new UserError(`could not open ${target}: ${e.message.split('\n')[0]}`);+ }+ return { context, page, close: () => context.close() };+ }, { label: 'opening the page to probe it' });let info;try {info = await withTimeout(page.evaluate(() => window.ST.ready()), 120000, 'the page never became ready');@@ -218,10 +227,10 @@ export async function probeProject(o) {let score = null;if (o.wantScore && info.hasScore) score = await pullScore(page, { duration: D, sampleRate: 48000 });- await context.close().catch(() => {});+ await closeSoon(context.close());return { info, requests, failed, errors, consoleErrors, blocked, chapters, poster, posterT, score, samples: list.length, domText, look, canvasFonts };} finally {- await b.browser.close().catch(() => {});+ await closeSoon(b.browser.close());}}diff --git a/skills/showtime/scripts/lib/frames.mjs b/skills/showtime/scripts/lib/frames.mjsindex 223ba94..e63575a 100644--- a/skills/showtime/scripts/lib/frames.mjs+++ b/skills/showtime/scripts/lib/frames.mjs@@ -4,7 +4,7 @@ import fs from 'node:fs';import path from 'node:path';import { startServer } from '../server.mjs';import { resolveProject, info, c, UserError } from './cli.mjs';-import { openStage } from './stagehost.mjs';+import { openPage } from './stagehost.mjs';import { resolveFF, ffmpeg, probe, STILL_VF } from './ff.mjs';import { stripColorChunks } from './png.mjs';@@ -44,7 +44,7 @@ export async function openSource(arg, a, shared) {const proj = resolveProject(arg || '.', { page: a.page });const server = await startServer({ root: proj.dir, port: 0 });const b = await shared.browser();- const sess = await openStage(b.browser, { url: server.url, page: proj.page, config: proj.config, size: a.size });+ const sess = await openPage(b, { url: server.url, page: proj.page, config: proj.config, size: a.size });shared.serverUrl = shared.serverUrl || server.url;return {kind: 'project', dir: proj.dir, name: path.basename(proj.dir), title: proj.title, proj, sess, info: sess.info,diff --git a/skills/showtime/scripts/lib/raster.mjs b/skills/showtime/scripts/lib/raster.mjsindex 26769bc..4dbb155 100644--- a/skills/showtime/scripts/lib/raster.mjs+++ b/skills/showtime/scripts/lib/raster.mjs@@ -8,7 +8,7 @@import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';-import { launchBrowser } from './chrome.mjs';+import { launchGuarded, openGuarded, closeSoon } from './stagehost.mjs';function aspectOf(svg) {const vb = /viewBox\s*=\s*"([^"]+)"/i.exec(svg);@@ -22,10 +22,15 @@ function aspectOf(svg) {}export async function rasterize(jobs, { background = null } = {}) {- const { browser } = await launchBrowser({ gpu: 'off' });+ const b = await launchGuarded({ gpu: 'off' });try {- const ctx = await browser.newContext({ deviceScaleFactor: 1 });- const page = await ctx.newPage();+ // the context and the tab under the page-open deadline (once more in a new browser)+ const { page } = await openGuarded(b, async (browser, track) => {+ track.step = 'creating the browser context';+ const ctx = await browser.newContext({ deviceScaleFactor: 1 });+ track.step = 'opening a tab';+ return { page: await ctx.newPage(), close: () => ctx.close() };+ }, { label: 'opening the drawing page' });const out = [];for (const job of jobs) {const svg = fs.readFileSync(job.in, 'utf8');@@ -45,7 +50,7 @@ export async function rasterize(jobs, { background = null } = {}) {}return out;} finally {- await browser.close();+ await closeSoon(b.browser.close());}}diff --git a/skills/showtime/scripts/lib/review/where.mjs b/skills/showtime/scripts/lib/review/where.mjsindex 05dd6cb..583a8c2 100644--- a/skills/showtime/scripts/lib/review/where.mjs+++ b/skills/showtime/scripts/lib/review/where.mjs@@ -162,18 +162,18 @@ function sessions() {const p = (async () => {const { resolveProject } = await import('../cli.mjs');const { startServer } = await import('../../server.mjs');- const { openBrowser, openStage } = await import('../stagehost.mjs');+ const { openBrowser, openPage } = await import('../stagehost.mjs');const P = resolveProject(proj.dir, { page: proj.page });if (!shared) shared = openBrowser({ gpu: 'auto' });const b = await shared;const server = await startServer({ root: P.dir, port: 0 });try {- let sess = await openStage(b.browser, { url: server.url, page: P.page, config: P.config });+ let sess = await openPage(b, { url: server.url, page: P.page, config: P.config });// a render at another aspect (render --size): open the page at the video's sizeconst va = proj.width > 0 && proj.height > 0 ? proj.width / proj.height : 0;if (va && Math.abs(sess.info.width / sess.info.height - va) > 0.01) {await sess.close();- sess = await openStage(b.browser, { url: server.url, page: P.page, config: P.config, size: `${proj.width}x${proj.height}` });+ sess = await openPage(b, { url: server.url, page: P.page, config: P.config, size: `${proj.width}x${proj.height}` });}return { sess, server };} catch (e) { await server.close().catch(() => {}); throw e; }diff --git a/skills/showtime/scripts/lib/stagehost.mjs b/skills/showtime/scripts/lib/stagehost.mjsindex 003033f..f31b042 100644--- a/skills/showtime/scripts/lib/stagehost.mjs+++ b/skills/showtime/scripts/lib/stagehost.mjs@@ -3,9 +3,10 @@// and snap so every tool sees exactly the same pixels.import fs from 'node:fs';import path from 'node:path';+import { spawn } from 'node:child_process';import { skillDir } from './deps.mjs';import { launchBrowser } from './chrome.mjs';-import { UserError } from './cli.mjs';+import { UserError, warn } from './cli.mjs';const STAGE_SRC = () => fs.readFileSync(path.join(skillDir(), 'runtime', 'stage.js'), 'utf8');let stageCache = null;@@ -19,7 +20,8 @@ export function isLocalUrl(u) {/*** Launch one browser (retrying once in software mode if the GPU path fails to start).- * -> { browser, kind, version, executablePath, flags }+ * -> { browser, kind, version, executablePath, flags, relaunch() } (relaunch: a new one the same way, for+ * openGuarded below)*/// Extra flags for capture on top of the shared set (scripts/lib/chrome-flags.json).// --disable-lcd-text: text in composited layers is always grayscale-antialiased while text in the@@ -29,12 +31,165 @@ export const CAPTURE_ARGS = ['--disable-lcd-text'];export async function openBrowser({ gpu = 'auto', headless = true, args = [], ownSignals = false } = {}) {const extra = [...CAPTURE_ARGS, ...args];+ let rec;try {- return await launchBrowser({ gpu, headless, args: extra, ownSignals });+ rec = await launchBrowser({ gpu, headless, args: extra, ownSignals });} catch (e) {if (gpu === 'off') throw e;- return launchBrowser({ gpu: 'off', headless, args: extra, ownSignals });+ rec = await launchBrowser({ gpu: 'off', headless, args: extra, ownSignals });}+ rec.relaunch = () => openBrowser({ gpu, headless, args, ownSignals });+ rec.pid = await browserPid(rec.browser);+ return rec;+}++/**+ * A browser record from launchBrowser made ready for openGuarded: relaunch() (a function that returns another+ * such record) and the process id. -> rec+ */+export async function guardable(rec, relaunch) {+ rec.relaunch = relaunch;+ rec.pid = await browserPid(rec.browser);+ return rec;+}++/** launchBrowser(o) as a record for openGuarded (relaunch() the same way, the process id). */+export async function launchGuarded(o = {}) {+ const launch = async () => guardable(await launchBrowser(o), launch);+ return launch();+}++/** The browser's process id (CDP SystemInfo.getProcessInfo), or null. */+async function browserPid(browser) {+ try {+ const s = await withTimeout(browser.newBrowserCDPSession(), 15000, 'reading the browser process id');+ const r = await withTimeout(s.send('SystemInfo.getProcessInfo'), 15000, 'reading the browser process id');+ s.detach().catch(() => {});+ const p = ((r && r.processInfo) || []).find((x) => x.type === 'browser');+ return p && Number.isInteger(p.id) && p.id > 0 ? p.id : null;+ } catch { return null; }+}++/**+ * Give up a browser that stopped answering: close it if it still can, and kill its process (its process group:+ * Playwright starts it as a group leader) so it never keeps the command alive or holds the machine.+ */+export function abandonBrowser(rec) {+ if (!rec || !rec.browser) return;+ closeSoon(rec.browser.close(), 3000);+ const pid = rec.pid;+ if (!pid) { warn('the browser stopped answering and its process id is unknown: it was only asked to close; it ends with this command'); return; }+ if (process.platform === 'win32') {+ try { spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).on('error', () => {}); } catch { /* gone */ }+ } else {+ try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } }+ }+}++// tests only: SHOWTIME_TEST_STOP_BROWSER=open stops (SIGSTOP) the browser just before the first page opens,+// =ready:N just after the N-th page opened: a real browser that stops answering, for the deadline and the+// watchdog (POSIX only)+const TEST_STOP = /^(open|ready)(?::(\d+))?$/.exec(process.platform === 'win32' ? '' : String(process.env.SHOWTIME_TEST_STOP_BROWSER || ''));+let testStop = TEST_STOP ? { when: TEST_STOP[1], n: Number(TEST_STOP[2] || 1) } : null;+let opened = 0;+function testStopNow(b, when) {+ if (when === 'ready') opened++;+ if (!testStop || testStop.when !== when || (when === 'ready' && opened !== testStop.n) || !b.pid) return;+ testStop = null;+ try { process.kill(b.pid, 'SIGSTOP'); } catch { /* gone */ }+}++// ------------------------------------------------------------------ opening a page, with a deadline+// A browser on a very busy machine can stop answering while it opens a page (a render once waited 14 minutes;+// on macOS CI runners a render and a check outlived their callers' deadlines): creating its context, its page+// or its CDP session has no deadline of its own. Every page showtime opens goes through openGuarded: the whole+// open (context, page, the first navigation, the page getting ready) gets PAGE_OPEN_MS, longer than the load and+// ready timeouts inside, times the page's pace factor; past it the browser is given up (killed), the open tried+// once more in a new browser, and then the command fails naming the step it was stuck at instead of waiting with+// no end.+// SHOWTIME_TEST_OPEN_TIMEOUT=<seconds> shortens it (tests).+export const PAGE_OPEN_MS = Number(process.env.SHOWTIME_TEST_OPEN_TIMEOUT) > 0 ? Number(process.env.SHOWTIME_TEST_OPEN_TIMEOUT) * 1000 : 300000;++/** close() of a browser or page that may not answer: never waits more than ms. */+export function closeSoon(p, ms = 10000) {+ return withTimeout(Promise.resolve().then(() => p), ms, 'closing a browser').catch(() => {});+}++/**+ * Run open(browser, track, pace) under the page-open deadline. b is a browser record ({browser, relaunch()}, as+ * openBrowser returns): a browser that never answers is closed and replaced in b itself (Object.assign), so the+ * caller's later pages and its own close use the new one. open() keeps track.step current ('creating the+ * browser context', ...) for the error, and may report the page's pace into pace (its deadline grows with it).+ * onRetry(message, what) is told before the second try (default: a warning on stderr); what is the step it was+ * stuck at. It may throw instead (a caller that holds pages of the old browser cannot go on in a new one).+ * -> whatever open() returns (it must have close() if it holds anything)+ */+export async function openGuarded(b, open, { label = 'opening the page', onRetry = (m) => warn(m) } = {}) {+ for (let attempt = 1; ; attempt++) {+ const track = { step: 'starting' };+ const pace = newPace();+ testStopNow(b, 'open');+ const p = Promise.resolve().then(() => open(b.browser, track, pace));+ try {+ const got = await withPacedTimeout(p, PAGE_OPEN_MS, label, pace);+ testStopNow(b, 'ready');+ return got;+ } catch (e) {+ if (!e || e.deadline !== label) throw e;+ p.then((x) => x && typeof x.close === 'function' && closeSoon(x.close(), 5000), () => {});+ const what = `${String(e.message)} (stuck at: ${track.step})`;+ // a record without relaunch() lends a browser that others use (render's soundtrack borrows worker 0's):+ // the caller decides what to do with it+ if (typeof b.relaunch === 'function') abandonBrowser(b);+ if (attempt > 1 || typeof b.relaunch !== 'function') {+ throw Object.assign(new UserError(`the browser stopped answering: ${what}${attempt > 1 ? ', in a new browser too' : ''}`, STUCK_HINT),+ { browserStuck: true });+ }+ onRetry(`the browser did not answer while ${label}: ${what}; trying once more in a new browser`, what);+ Object.assign(b, await b.relaunch());+ }+ }+}++export const STUCK_HINT = 'the machine is too busy or the browser is stuck: close other heavy programs and retry, or try --gpu off; `showtime doctor` checks the browser';++/**+ * Watch a browser record while a command works with it (calls on a page have no deadline of their own): a+ * browser that does not answer a ping (CDP Browser.getVersion, answered by the browser process however busy its+ * pages are) within PAGE_OPEN_MS has stopped. onStuck(message, hint) is called once, after the browser is killed;+ * the command then ends with that error instead of waiting with no end. A browser replaced meanwhile+ * (openGuarded) is pinged anew. -> stop()+ */+export function watchBrowser(b, onStuck) {+ const every = Math.min(30000, Math.max(500, PAGE_OPEN_MS / 4));+ let stopped = false, timer = null, sess = null, sessFor = null;+ const tick = async () => {+ if (stopped) return;+ const br = b.browser;+ const t0 = Date.now();+ try {+ if (sessFor !== br) { sess = null; sessFor = br; sess = await withTimeout(br.newBrowserCDPSession(), PAGE_OPEN_MS, 'answering a ping'); }+ await withTimeout(sess.send('Browser.getVersion'), PAGE_OPEN_MS, 'answering a ping');+ } catch (e) {+ if (stopped) return;+ if (e && e.deadline && b.browser === br) {+ stopped = true;+ abandonBrowser(b);+ onStuck(`the browser stopped answering (no answer for ${Math.round((Date.now() - t0) / 1000)} s)`, STUCK_HINT);+ return;+ }+ sessFor = null; // closed or replaced: a new session next time+ }+ if (!stopped) { timer = setTimeout(tick, every); timer.unref(); }+ };+ timer = setTimeout(tick, every);+ timer.unref();+ return () => { stopped = true; clearTimeout(timer); if (sess) sess.detach().catch(() => {}); };+}++/** openStage under openGuarded: b is a browser record (see openBrowser); its browser may be replaced once. */+export function openPage(b, o, opts = {}) {+ return openGuarded(b, (browser, track, pace) => openStage(browser, { ...o, pace, track }), opts);}// WebGL renderer strings of a CPU rasteriser: Chrome's SwiftShader, Mesa's llvmpipe/softpipe, Windows' WARP@@ -48,19 +203,23 @@ export const SOFTWARE_GL = /swiftshader|llvmpipe|softpipe|basic render driver|\bexport async function glRenderer(browser) {let context = null;try {- context = await browser.newContext({ viewport: { width: 64, height: 64 }, deviceScaleFactor: 1 });- const page = await context.newPage();- const renderer = await withTimeout(page.evaluate(() => {- const gl = document.createElement('canvas').getContext('webgl');- if (!gl) return '';- const ext = gl.getExtension('WEBGL_debug_renderer_info');- return String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));- }), 15000, 'WebGL probe');+ // one deadline for the whole probe: a browser that stopped answering (a busy machine) never answers+ // newContext or newPage either, and the render must not wait for it here (it gets a new one for its page)+ const renderer = await withTimeout((async () => {+ context = await browser.newContext({ viewport: { width: 64, height: 64 }, deviceScaleFactor: 1 });+ const page = await context.newPage();+ return page.evaluate(() => {+ const gl = document.createElement('canvas').getContext('webgl');+ if (!gl) return '';+ const ext = gl.getExtension('WEBGL_debug_renderer_info');+ return String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));+ });+ })(), 30000, 'WebGL probe');return { renderer: renderer || 'none (no WebGL)', software: !renderer || SOFTWARE_GL.test(renderer) };} catch {return { renderer: 'unknown', software: null };} finally {- if (context) await context.close().catch(() => {});+ if (context) await withTimeout(context.close(), 5000, 'closing the WebGL probe').catch(() => {});}}@@ -111,7 +270,7 @@ export function withPacedTimeout(p, baseMs, label, pace) {const lim = baseWait(baseMs) * f;const left = lim - (Date.now() - t0);if (left <= 0) {- rej(new Error(`timed out after ${Math.round(lim / 1000)}s${f > 1 ? ` (x${f} for this page's pace)` : ''}: ${label}`));+ rej(Object.assign(new Error(`timed out after ${Math.round(lim / 1000)}s${f > 1 ? ` (x${f} for this page's pace)` : ''}: ${label}`), { deadline: label }));return;}timer = setTimeout(tick, Math.min(left, 1000));@@ -144,6 +303,7 @@ export function withPacedTimeout(p, baseMs, label, pace) {export async function openStage(browser, o) {const size = parseSize(o.size);o = o.pace ? o : { ...o, pace: newPace() };+ const track = o.track || {};const opts = size ? { ...o, override: { ...(o.override || {}), width: size.width, height: size.height } } : o;const sess = await openStageOnce(browser, opts);const cfg = o.config || {};@@ -153,6 +313,7 @@ export async function openStage(browser, o) {// the page set its own size with ST.config and nothing else did: reopen at that size, so snap,// check, studio frames and exports see the page as render does (a 1080x1080 page is not stretched)const w = sess.info.width, h = sess.info.height;+ track.step = 'closing the page to reopen it at its own size';await sess.close();return openStageOnce(browser, { ...o, override: { ...(o.override || {}), width: w, height: h } });}@@ -188,10 +349,13 @@ async function openStageOnce(browser, o) {// so downscaling happens in the capture (clip.scale); supersampling (> 1) uses the DSF.const dsf = scale > 1 ? scale : 1;const clipScale = scale < 1 ? scale : null;+ const track = o.track || {};+ track.step = 'creating the browser context';const context = await browser.newContext({viewport: { width, height }, deviceScaleFactor: dsf, colorScheme: 'light',reducedMotion: 'no-preference', locale: 'en-US', timezoneId: 'UTC', serviceWorkers: 'block',});+ track.step = 'opening a tab';const page = await context.newPage();const log = { console: [], errors: [], requests: [], failed: [], blocked: [], http: [], cancelled: 0 };const ring = (arr, v, max = 200) => { arr.push(v); if (arr.length > max) arr.shift(); };@@ -214,6 +378,7 @@ async function openStageOnce(browser, o) {});page.on('response', (r) => { if (r.status() >= 400) ring(log.http, { url: r.url(), status: r.status() }); });page.on('request', (r) => ring(log.requests, r.url(), 500));+ track.step = 'setting up the tab';await page.route('**/*', (route) => {const u = route.request().url();if (isLocalUrl(u)) return route.continue();@@ -233,6 +398,7 @@ async function openStageOnce(browser, o) {if (o.init) await page.addInitScript({ content: String(o.init) });const cdp = await context.newCDPSession(page);const target = `${o.url}/${String(o.page || 'index.html').replace(/^\/+/, '')}`;+ track.step = 'loading the page';try {await page.goto(target, { waitUntil: 'domcontentloaded', timeout: 60000 });} catch (e) {@@ -248,6 +414,7 @@ async function openStageOnce(browser, o) {polling = page.evaluate(() => (window.ST && typeof window.ST.pace === 'function' ? window.ST.pace() : null)).then((r) => notePace(pace, r), () => {}).finally(() => { polling = null; });}, 1000);+ track.step = 'waiting for the page to be ready';try {info = await withPacedTimeout(page.evaluate(() => window.ST.ready()), o.readyTimeout || 120000, 'the page never became ready', pace);notePace(pace, info && info.pace);@@ -309,7 +476,7 @@ export function withTimeout(p, ms, label) {let timer;return Promise.race([p,- new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`timed out after ${Math.round(ms / 1000)}s: ${label}`)), ms); }),+ new Promise((_, rej) => { timer = setTimeout(() => rej(Object.assign(new Error(`timed out after ${Math.round(ms / 1000)}s: ${label}`), { deadline: label })), ms); }),]).finally(() => clearTimeout(timer));}@@ -367,10 +534,21 @@ export async function pullScore(page, { duration, sampleRate = 48000 }) {return { channels, sampleRate: meta.sampleRate, peak: meta.peak };}-/** A blank page served by our server, for image math (diffs, contact sheets, colour sampling). */-export async function openLab(browser, url) {+/**+ * A blank page served by our server, for image math (diffs, contact sheets, colour sampling). b: a browser record+ * (openBrowser; opened under openGuarded, its browser may be replaced once) or a bare Playwright browser.+ */+export async function openLab(b, url, opts = {}) {+ if (b && b.browser) return openGuarded(b, (browser, track) => openLabOn(browser, url, track), { label: 'opening the image lab page', ...opts });+ return openLabOn(b, url, {});+}++async function openLabOn(browser, url, track) {+ track.step = 'creating the browser context';const context = await browser.newContext({ viewport: { width: 800, height: 600 }, deviceScaleFactor: 1 });+ track.step = 'opening a tab';const page = await context.newPage();+ track.step = 'loading the page';await page.goto(`${url}/_st/lab`, { waitUntil: 'load' });await page.addScriptTag({ content: LAB_JS });return {diff --git a/skills/showtime/scripts/lib/studio/frames.mjs b/skills/showtime/scripts/lib/studio/frames.mjsindex 44e4866..03364e8 100644--- a/skills/showtime/scripts/lib/studio/frames.mjs+++ b/skills/showtime/scripts/lib/studio/frames.mjs@@ -9,7 +9,7 @@import fs from 'node:fs';import path from 'node:path';import { startServer } from '../../server.mjs';-import { openBrowser, openStage } from '../stagehost.mjs';+import { openBrowser, openPage } from '../stagehost.mjs';export async function captureFrames({ root, page, config = {}, override = null, shots, width = 1280, thumbWidth = 480, quality = 90, gpu = 'auto' }) {const server = await startServer({ root, port: 0 });@@ -20,7 +20,7 @@ export async function captureFrames({ root, page, config = {}, override = null,const groups = new Map();for (const s of shots) { const k = s.query || ''; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(s); }for (const [query, list] of groups) {- const sess = await openStage(b.browser, { url: server.url, page: page + query, config, override });+ const sess = await openPage(b, { url: server.url, page: page + query, config, override });try {const W = sess.width;for (const s of list) {diff --git a/skills/showtime/scripts/look.mjs b/skills/showtime/scripts/look.mjsindex f26c9c3..4778588 100644--- a/skills/showtime/scripts/look.mjs+++ b/skills/showtime/scripts/look.mjs@@ -204,7 +204,7 @@ async function main() {const image = path.join(outDir, `look-${n}.jpg`);if (!shared.serverUrl) { labServer = await startServer({ root: tmpRoot, port: 0 }); shared.serverUrl = labServer.url; }- lab = await openLab((await shared.browser()).browser, shared.serverUrl);+ lab = await openLab(await shared.browser(), shared.serverUrl);const width = Math.max(320, Math.min(3840, Number(a.width || 1280)));const k = frames.length;const vertical = H > W;diff --git a/skills/showtime/scripts/render.mjs b/skills/showtime/scripts/render.mjsindex d5b454d..8b50649 100644--- a/skills/showtime/scripts/render.mjs+++ b/skills/showtime/scripts/render.mjs@@ -10,7 +10,7 @@ import {parseTime, runPyCli, hasPyModule, UserError, progressLog, briefOutput, sinceLastLooked, printSince,} from './lib/cli.mjs';import { checkFreshness } from './lib/lean.mjs';-import { openBrowser, openStage, writeDiagnostics, pullScore, parseSize, glRenderer, withTimeout, withPacedTimeout, newPace, paceSummary } from './lib/stagehost.mjs';+import { openBrowser, openStage, openPage, abandonBrowser, PAGE_OPEN_MS, writeDiagnostics, pullScore, parseSize, glRenderer, withTimeout, withPacedTimeout, newPace, paceSummary } from './lib/stagehost.mjs';import { resolveFF, ffmpeg, probe, ebur128, writeWavFloat, fpsArg, hasEncoder, setLogFile, logLine, meanFrameDiff, JPEG_VF } from './lib/ff.mjs';import { CaptureQueue, OrderedFeed, autoWorkers, machineLimits } from './lib/pipeline.mjs';import { renderFlags } from './lib/chrome.mjs';@@ -321,7 +321,12 @@ async function main() {const outW = even(base * scale);scale = outW / base;openOpts.scale = scale;- const s0 = await openStage(b0.browser, openOpts);+ // every page render opens has the page-open deadline (stagehost openGuarded: PAGE_OPEN_MS, times the page's+ // pace factor); the first one, past it, is tried once more in a new browser (b0 itself is updated); a+ // worker's page has its own retries (openWorkerPage below)+ const firstRetry = (m) => { warn(m); logLine(`first page: ${m}`); };+ const openFirst = (opts) => openPage(b0, opts, { onRetry: firstRetry });+ const s0 = await openFirst(openOpts);sessions.push(s0);const inf = s0.info;if (inf.width !== base || inf.height !== baseH) {@@ -332,7 +337,7 @@ async function main() {const outW2 = even(inf.width * (a.scale !== undefined ? Number(a.scale) : (a.preview ? Math.min(1, 720 / Math.min(inf.width, inf.height)) : 1)));openOpts.scale = outW2 / inf.width;openOpts.config = cfg;- sessions.push(await openStage(b0.browser, openOpts));+ sessions.push(await openFirst(openOpts));}const info0 = sessions[0].info;timings.load = Date.now() - t;@@ -614,11 +619,8 @@ async function main() {const wsess = [sessions[0]]; // one page per worker, kept across its runsconst drawn = []; // per worker: the frame after the last one its page drew (null: a new page)- // a worker's page. A browser that never answers while it opens one (seen on a very busy machine: the- // render waited 14 minutes) is closed after 5 minutes (longer than the page load and ready timeouts- // inside; times the page's pace factor, which the page reports while it gets ready) and replaced; frames- // go only to a worker whose page is open, so a stuck one never holds frames- const OPEN_MS = 300000;+ // a worker's page. A browser that never answers while it opens one is closed after PAGE_OPEN_MS and+ // replaced; frames go only to a worker whose page is open, so a stuck one never holds frames// (SHOWTIME_SHOT_TIMEOUT=S shortens it: the stuck-browser test)const SHOT_MS = Number(process.env.SHOWTIME_SHOT_TIMEOUT) > 0 ? Number(process.env.SHOWTIME_SHOT_TIMEOUT) * 1000 : 600000;// a frame whose write failed (disk full, an I/O error) may leave a partial file: it is re-captured after@@ -636,15 +638,17 @@ async function main() {const openWorkerPage = async (w) => {if (!browsers[w] || !browsers[w].browser.isConnected()) browsers[w] = await openBrowser({ gpu, ownSignals: true, args: renderFlags() });const pace = newPace();- const p = openStage(browsers[w].browser, { ...openOpts, pace });+ const track = { step: 'starting' };+ const p = openStage(browsers[w].browser, { ...openOpts, pace, track });let sess;try {- sess = await withPacedTimeout(p, OPEN_MS, `opening the page in worker ${w}`, pace);+ sess = await withPacedTimeout(p, PAGE_OPEN_MS, `opening the page in worker ${w}`, pace);} catch (e) {+ if (e && e.deadline) e.message += ` (stuck at: ${track.step})`;p.then((x) => x.close(), () => {});const b = browsers[w];browsers[w] = null;- if (b) b.browser.close().catch(() => {});+ if (b) abandonBrowser(b); // closed if it can, its process killedthrow e;}sessions.push(sess);@@ -721,7 +725,7 @@ async function main() {const b = browsers[w];browsers[w] = null;if (sess) closeSoon(sess.close(), 5000);- if (b) closeSoon(b.browser.close(), 10000);+ if (b) abandonBrowser(b);} else {if (sess) await closeSoon(sess.close());if (browsers[w] && !browsers[w].browser.isConnected()) browsers[w] = null;@@ -772,7 +776,7 @@ async function main() {addWarn(`${missing.length} frame(s) missing after capture; re-capturing`);const b = await openBrowser({ gpu, ownSignals: true, args: renderFlags() });browsers.push(b);- const sess = await openStage(b.browser, openOpts);+ const sess = await openPage(b, openOpts, { onRetry: (m) => { warn(m); logLine(m); } });sessions.push(sess);for (const i of missing) {await sess.seek(i / fps);@@ -1265,7 +1269,8 @@ async function buildAudio({ proj, cfg, info, browser, openOpts, audioDir, from,// 1) ST.score, rendered offline in its own pageif (info.hasScore) {const t = Date.now();- const sess = await openStage(browser, { ...openOpts, scale: 1 });+ // the page-open deadline; past it this attempt fails and render's audio retry starts a new browser+ const sess = await openPage({ browser }, { ...openOpts, scale: 1 }, { label: 'opening the page for the soundtrack' });try {const sc = await pullScore(sess.page, { duration: fullDur, sampleRate: 48000 });if (sc) {diff --git a/skills/showtime/scripts/score.mjs b/skills/showtime/scripts/score.mjsindex f90adc5..6635d1c 100644--- a/skills/showtime/scripts/score.mjs+++ b/skills/showtime/scripts/score.mjs@@ -4,7 +4,7 @@ import path from 'node:path';import { startServer } from './server.mjs';import { parseCli, runMain, resolveProject, jobDir, freshPath, info, warn, c, fmtDuration, UserError } from './lib/cli.mjs';import { enclosingJob } from './lib/studio/paths.mjs';-import { openBrowser, openStage, pullScore } from './lib/stagehost.mjs';+import { openBrowser, openPage, pullScore } from './lib/stagehost.mjs';import { measureLoudness, writeWavFloat } from './lib/ff.mjs';const SPEC = {@@ -90,7 +90,7 @@ async function main() {let report;try {b = await openBrowser({ gpu: 'auto' });- s = await openStage(b.browser, { url: server.url, page: proj.page, config: proj.config });+ s = await openPage(b, { url: server.url, page: proj.page, config: proj.config });const dur = s.info.duration;if (!s.info.hasScore) {throw new UserError('this project has no ST.score',diff --git a/skills/showtime/scripts/site.mjs b/skills/showtime/scripts/site.mjsindex f0b1c09..f1c4f08 100644--- a/skills/showtime/scripts/site.mjs+++ b/skills/showtime/scripts/site.mjs@@ -11,7 +11,7 @@// Landing on showtime's own preview player (/_st/...) or on a directory listing is an error.import fs from 'node:fs';import path from 'node:path';-import { launchBrowser } from './lib/chrome.mjs';+import { launchGuarded, openGuarded, closeSoon } from './lib/stagehost.mjs';import { parseCli, runMain, UserError, info, warn, c, jobDir, freshPath, fmtBytes, fmtDuration, printHelp, Progress } from './lib/cli.mjs';import {aspectViewport, newCaptureContext, installConsent, waitConsent, cleanupOverlays, robustGoto, detectBotWall,@@ -138,10 +138,17 @@ async function guardLanding(page, o, warnings) {throw new UserError(`wrong page: ${p.reason}`, p.hint);}-async function openPage(browser, vp, o, url, { dark = false } = {}) {- const ctx = await newCaptureContext(browser, vp, { dark, locale: o.locale, userAgent: o['user-agent'] });- const consent = o['no-consent'] ? [] : await installConsent(ctx);- const page = await ctx.newPage();+async function openPage(B, vp, o, url, { dark = false } = {}) {+ // the context and the tab under the page-open deadline (once more in a new browser); the site's own load+ // has --timeout+ const { ctx, consent, page } = await openGuarded(B, async (browser, track) => {+ track.step = 'creating the browser context';+ const ctx = await newCaptureContext(browser, vp, { dark, locale: o.locale, userAgent: o['user-agent'] });+ track.step = 'setting up the consent clicker';+ const consent = o['no-consent'] ? [] : await installConsent(ctx);+ track.step = 'opening a tab';+ return { ctx, consent, page: await ctx.newPage(), close: () => ctx.close() };+ }, { label: 'opening a tab for the site' });const responses = [];page.on('response', (r) => {try {@@ -224,7 +231,7 @@ async function captureRun(o, tgt) {info(`${c.bold('site capture')} ${url}`);info(c.dim(` output ${out}`));- let { browser } = await launchBrowser({ gpu: o.gpu, headless: !o.headed });+ const B = await launchGuarded({ gpu: o.gpu, headless: !o.headed });const result = {url, finalUrl: null, served: tgt.server ? tgt.server.root : null, status: null, capturedAt: new Date().toISOString(), aspects: aspects.map((a) => a.spec),shots: {}, sections: [], full: null, dark: null, consent: [], overlays: null, warnings,@@ -235,13 +242,13 @@ async function captureRun(o, tgt) {phase(1, 7, `loading (${vp.spec}, ${vp.css.width}x${vp.css.height} @${vp.dpr}x)`);let opened;try {- opened = await openPage(browser, vp, o, url);+ opened = await openPage(B, vp, o, url);} catch (e) {if (/Timeout|crash|closed/i.test(String(e.message)) && o.gpu !== 'off') {warn('page load failed; retrying once with GPU/WebGL off');- await browser.close().catch(() => {});- ({ browser } = await launchBrowser({ gpu: 'off', headless: !o.headed, args: ['--disable-webgl', '--disable-3d-apis'] }));- opened = await openPage(browser, vp, o, url);+ await closeSoon(B.browser.close());+ Object.assign(B, await launchGuarded({ gpu: 'off', headless: !o.headed, args: ['--disable-webgl', '--disable-3d-apis'] }));+ opened = await openPage(B, vp, o, url);warnings.push('loaded with WebGL disabled after a first failed attempt');} else throw e;}@@ -312,7 +319,7 @@ async function captureRun(o, tgt) {if (wantDark && o.dark !== 'off') {phase(5, 7, 'dark-mode variant');try {- const d = await openPage(browser, vp, o, url, { dark: true });+ const d = await openPage(B, vp, o, url, { dark: true });await cleanupOverlays(d.page, { hide: !o['keep-overlays'] });await lazyScroll(d.page, { budgetMs: 8000 });const lumDark = await d.page.evaluate(() => {@@ -336,7 +343,7 @@ async function captureRun(o, tgt) {for (const avp of aspects.slice(1)) {info(c.dim(` ${avp.spec}: ${avp.css.width}x${avp.css.height} @${avp.dpr}x${avp.mobile ? ' (phone layout)' : ''}`));try {- const a = await openPage(browser, avp, o, url);+ const a = await openPage(B, avp, o, url);await cleanupOverlays(a.page, { hide: !o['keep-overlays'] });await lazyScroll(a.page, { budgetMs: 10000 });result.shots[avp.name] = await viewportSeries(a.page, avp, path.join(out, 'shots', avp.name), Number(o['max-shots']), fmt, shotOpts, out);@@ -376,11 +383,11 @@ async function captureRun(o, tgt) {for (const [name, list] of Object.entries(result.shots)) for (const s of list) sheetItems.push({ file: s.file, label: `${name} ${s.label}` });for (const s of result.sections) sheetItems.push({ file: s.file, label: `section: ${s.label}` });if (result.dark) for (const s of result.dark.shots) sheetItems.push({ file: s.file, label: `dark ${s.label}` });- const sheet = await contactSheet(browser, sheetItems.slice(0, 36), path.join(out, 'contact-sheet.jpg'), { title: `${data.meta.title || host} - screens`, dir: out });+ const sheet = await contactSheet(B.browser, sheetItems.slice(0, 36), path.join(out, 'contact-sheet.jpg'), { title: `${data.meta.title || host} - screens`, dir: out });const assetItems = assets.files.filter((f) => /\.(png|jpe?g|webp|gif|svg|avif|ico)$/i.test(f.file)).sort((a, b) => (b.kind === 'logo') - (a.kind === 'logo')).slice(0, 36).map((f) => ({ file: f.file, label: `${f.kind}: ${path.basename(f.file)}` }));- const aSheet = await contactSheet(browser, assetItems, path.join(out, 'assets-sheet.jpg'), { title: `${data.meta.title || host} - assets`, dir: out, cols: 4, cell: 360 });+ const aSheet = await contactSheet(B.browser, assetItems, path.join(out, 'assets-sheet.jpg'), { title: `${data.meta.title || host} - assets`, dir: out, cols: 4, cell: 360 });fs.writeFileSync(path.join(out, 'inventory.md'), inventory(out, url, siteJson, { sheet, aSheet, seconds: (Date.now() - t0) / 1000 }));const summary = {ok: true, url, finalUrl: result.finalUrl, served: tgt.server ? tgt.server.root : null, title: data.meta.title || null,@@ -403,7 +410,7 @@ async function captureRun(o, tgt) {}return 0;} finally {- await browser.close().catch(() => {});+ await closeSoon(B.browser.close());}}@@ -637,9 +644,9 @@ async function component(argv) {throw new UserError('missing <selector>', 'example: showtime site component https://example.com "#pricing"');}const vp = aspectViewport(String(o.aspect).split(',')[0], { dpr: o.dpr ? Number(o.dpr) : undefined, width: o.width ? Number(o.width) : undefined });- const { browser } = await launchBrowser({ gpu: o.gpu, headless: !o.headed });+ const B = await launchGuarded({ gpu: o.gpu, headless: !o.headed });try {- const { page, nav } = await openPage(browser, vp, o, url, { dark: !!o.dark });+ const { page, nav } = await openPage(B, vp, o, url, { dark: !!o.dark });await guardLanding(page, o, null);const wall = await detectBotWall(page, nav.status);if (wall.blocked) {@@ -688,7 +695,7 @@ async function component(argv) {else { info(`${c.green('done')}: ${files.length} of ${n} match(es)`); for (const f of files) console.log(f.file); }return files.length ? 0 : 1;} finally {- await browser.close().catch(() => {});+ await closeSoon(B.browser.close());if (tgt.server) await tgt.server.close().catch(() => {});}}@@ -738,9 +745,9 @@ async function record(argv) {info(`${c.bold('site record')} ${url}`);info(c.dim(` output ${out}`));const t0 = Date.now();- const { browser } = await launchBrowser({ gpu: o.gpu, headless: !o.headed });+ const B = await launchGuarded({ gpu: o.gpu, headless: !o.headed });try {- const { page, nav } = await openPage(browser, vp, o, url, { dark: !!o.dark });+ const { page, nav } = await openPage(B, vp, o, url, { dark: !!o.dark });await guardLanding(page, o, null);const wall = await detectBotWall(page, nav.status);if (wall.blocked) {@@ -786,7 +793,7 @@ async function record(argv) {else { info(`${c.green('done')}: ${total} frames (${rec.duration.toFixed(1)} s) in ${fmtDuration(Date.now() - t0)}`); console.log(out); if (mp4) console.log(mp4); console.log(path.join(out, 'record.json')); }return 0;} finally {- await browser.close().catch(() => {});+ await closeSoon(B.browser.close());if (tgt.server) await tgt.server.close().catch(() => {});}}diff --git a/skills/showtime/scripts/snap.mjs b/skills/showtime/scripts/snap.mjsindex c8a6af1..96a330b 100644--- a/skills/showtime/scripts/snap.mjs+++ b/skills/showtime/scripts/snap.mjs@@ -123,7 +123,7 @@ async function main() {const all = [...new Set([...atTimes.map(q), ...sheetTimes].map((x) => +x.toFixed(6)))].sort((x, y) => x - y);// the lab page (sheets, resizing) is served by the project server, or a tiny one for video filesif (!shared.serverUrl) { labServer = await startServer({ root: tmpRoot, port: 0 }); shared.serverUrl = labServer.url; }- lab = await openLab((await shared.browser()).browser, shared.serverUrl);+ lab = await openLab(await shared.browser(), shared.serverUrl);const shots = new Map();// keys are rounded to 6 decimals; seek the exact frame time (k / fps): a rounded time can fall a hair// before the frame boundary, and the stage floors it to the previous framediff --git a/skills/showtime/tests/test_looks.py b/skills/showtime/tests/test_looks.pyindex d28e79a..0296166 100644--- a/skills/showtime/tests/test_looks.py+++ b/skills/showtime/tests/test_looks.py@@ -13,7 +13,11 @@ marble, metaballs).the WebGL one; the metaballs fallback still moves, the others are still* `showtime check` warns when a look costs more per frame without a GPU than runtime/thresholds.json"look_budget_ms" (a tilt-shift at full size over a box larger than 1080p; a marble at twice the size) and stays- quiet for the defaults (each of the newer looks at 1080p estimates under the budget)+ quiet for the defaults (each of the newer looks at 1080p estimates under the budget); every look is in the+ report in every run, and a run where this browser's GPU gave a look no WebGL says so (the budget is then+ checked with --gpu off, the cost without a GPU it describes)+ * a WebGL context lost while a look builds its shaders (a GPU reset) does not drop the look: it draws its+ fallback, and check reports it (look_lost) with its passes' cost* WebGL contexts (Chrome keeps about 16 per page): 20 looks in one scene all draw (none white or empty) andcheck fails the page with look_contexts; 20 scenes with a look each draw every scene, give the same frameswith 1 and 3 workers, pass check's shuffled-order probe, and count one look on screen at a time@@ -286,15 +290,36 @@ class LooksTests(unittest.TestCase):style="inset:auto;left:0;top:0;width:2400px;height:1350px" id="big"></div></div><div class="p" style="left:50%%;width:50%%"><div data-st="tilt-shift" data-src="media/plate.png" id="small"></div></div>"""proj = self.project("budget", page(body=body.replace("%%", "%")))- rep = check(proj)- # the summary names each look's cost too (it was only in report.json)- cp = showtime("check", proj, "--no-determinism", "--no-timeline", "--no-history", "--samples", "2", check=False)- line = re.search(r"looks\s+(.+ per frame without a GPU \(budget 50 ms\))", cp.stdout)- self.assertTrue(line, cp.stdout)- self.assertRegex(line.group(1), r"tilt-shift #big [\d.]+ ms \(over\)")- self.assertRegex(line.group(1), r"tilt-shift #small [\d.]+ ms(,| per)")- items = {x["sel"]: x for x in (rep.get("looks") or {}).get("items", [])}- self.assertIn("#big", items, items)++ def runs(*extra):+ rep = check(proj, *extra)+ # the summary names each look's cost too (it was only in report.json)+ cp = showtime("check", proj, "--no-determinism", "--no-timeline", "--no-history", "--samples", "2", *extra,+ check=False)+ line = re.search(r"looks\s+(.+ per frame without a GPU \(budget 50 ms\))", cp.stdout)+ self.assertTrue(line, cp.stdout)+ items = {x["sel"]: x for x in (rep.get("looks") or {}).get("items", [])}+ # every look is in the report, a look that fell back here too (one whose WebGL context went while it+ # set up once vanished from it: macOS runner, a GPU reset)+ self.assertEqual(set(items), {"#big", "#small"}, items)+ fell = sorted(s for s, x in items.items() if not x["gl"])+ for s in fell:+ self.assertTrue(items[s]["note"], items[s])+ self.assertTrue([f for f in rep["findings"] if f["code"] in ("look_fallback", "look_lost") and s in f["message"]],+ (s, rep["findings"]))+ return rep, line.group(1), items, fell or "fallback" in line.group(1)++ rep, line, items, fell = runs()+ if fell:+ # this browser had no WebGL for a look in one of the runs (the GPU's own path: the macOS runner's+ # virtual GPU resets now and then), and the report said so above. The budget is the cost without a+ # GPU: measured where it is defined, Chrome's SwiftShader, which has WebGL on every machine+ print(" (WebGL fell back on this GPU for a look: %s; the budget is checked with --gpu off)" % line,+ file=sys.stderr)+ rep, line, items, fell = runs("--gpu", "off")+ self.assertFalse(fell, (line, items))+ self.assertRegex(line, r"tilt-shift #big [\d.]+ ms \(over\)")+ self.assertRegex(line, r"tilt-shift #small [\d.]+ ms(,| per)")self.assertGreater(items["#big"]["ms"], 50, items["#big"])self.assertLess(items["#small"]["ms"], 50, items["#small"])warn = [f for f in rep["findings"] if f["code"] == "look_budget"]@@ -302,6 +327,39 @@ class LooksTests(unittest.TestCase):self.assertIn("#big", warn[0]["message"])self.assertIn("data-scale", warn[0].get("fix", ""))+ def test_04b_context_lost_while_setting_up(self):+ """A GPU reset while a look builds its shaders (its context lost, every later request null, as on the macOS+ runner once): the look is not dropped from check's report (its shader read as failed to compile, its setup+ threw), it draws its fallback and the report says so, with its passes' cost kept."""+ crash = """<script>+ (function () { var g = HTMLCanvasElement.prototype.getContext, n = 0;+ HTMLCanvasElement.prototype.getContext = function (t, o) {+ if (!/webgl/i.test(String(t)) || this.className !== 'st-look-canvas') return g.call(this, t, o);+ if (++n > 1) return null;+ var c = g.call(this, t, o);+ if (c) { var e = c.getExtension('WEBGL_lose_context'), cs = c.compileShader.bind(c);+ c.compileShader = function (x) { if (e) e.loseContext(); return cs(x); }; }+ return c;+ }; })();+</script>"""+ body = """+ <div class="p" style="left:0;width:50%"><div data-st="tilt-shift" data-src="media/plate.png" id="one"></div></div>+ <div class="p" style="left:50%;width:50%"><div data-st="tilt-shift" data-src="media/plate.png" id="two"></div></div>"""+ proj = self.project("lostsetup", page(extra_head=crash, body=body))+ rep = check(proj)+ items = {x["sel"]: x for x in (rep.get("looks") or {}).get("items", [])}+ self.assertEqual(set(items), {"#one", "#two"}, items)+ self.assertFalse(any(x["gl"] for x in items.values()), items)+ lost = [x for x in items.values() if x["lost"]]+ self.assertEqual(len(lost), 1, items)+ self.assertEqual(lost[0]["lost"], 1, lost[0]) # one reset is one loss, not one per place that sees it+ self.assertGreater(lost[0]["ms"], 0, lost[0])+ self.assertIn("lost", lost[0]["note"])+ codes = {(f["code"], s) for f in rep["findings"] for s in items if s in f["message"]}+ self.assertIn(("look_lost", lost[0]["sel"]), codes, rep["findings"])+ failed = [w for w in rep["diag"]["waits"] if w["state"].startswith("failed")]+ self.assertEqual(failed, [], "a look's setup threw")+# ------------------------------------------- WebGL contexts (Chrome keeps about 16 per page)def gray(self, png_path, w, h):from st import ffdiff --git a/skills/showtime/tests/test_mcp.py b/skills/showtime/tests/test_mcp.pyindex e779691..1ade4a3 100644--- a/skills/showtime/tests/test_mcp.py+++ b/skills/showtime/tests/test_mcp.py@@ -95,6 +95,31 @@ def poll_task(task, cwd, env, tries=30):raise AssertionError("task %s still running after %d status calls" % (task, tries))+def result_of(step, out=None, cwd=None) -> dict:+ """The step's JSON-RPC result. A step without one fails the test with what came instead: the error body, or+ the test client's own deadline (its {"timeout": true}) with the progress the server sent until then, the+ server's stderr and the tail of the background run's log (runs started in `cwd`)."""+ res = step["response"].get("result")+ if res is not None:+ return res+ lines = ["%s returned no result: %s" % (step.get("method"), json.dumps(step["response"])[:2000])]+ if step.get("progress"):+ lines.append("progress: " + "; ".join(p.get("message", "") for p in step["progress"][-12:]))+ if out and out.get("stderr"):+ lines.append("server stderr:\n" + out["stderr"][-2500:])+ if cwd is not None:+ for d in sorted((HOME / "runs").glob("*/run.json"), key=lambda p: p.stat().st_mtime)[-20:]:+ try:+ run = json.loads(d.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ continue+ if Path(run.get("cwd") or "/nonexistent").resolve() == Path(cwd).resolve():+ log = d.parent / "output.log"+ tail = log.read_text(encoding="utf-8", errors="replace")[-3000:] if log.is_file() else "(no output.log)"+ lines.append("run %s (%s, state %s):\n%s" % (run.get("id"), run.get("command"), run.get("state"), tail))+ raise AssertionError("\n".join(lines))++def text_of(step) -> str:res = step["response"].get("result") or {}return "\n".join(c.get("text", "") for c in res.get("content", []))@@ -344,23 +369,27 @@ class TestFlow(unittest.TestCase):ready = plat.venv_python(HOME / "venv").exists() and (HOME / "node" / "node_modules" / "playwright").is_dir()steps = [call("doctor", {}), call("new_project", {"template": "dom", "dir": "tiny", "duration": 2, "size": "640x360"})]if ready:- steps.append(call("render", {"project": "tiny", "preview": True}, progress=True))- out = mcp(steps, self.tmp, env=self.env)+ # the call waits as long as render's own recovery from a browser that stops answering (it gives a page+ # 5 minutes to open, then a new browser; once on the macOS runner this call ran out of its 4 minutes,+ # where unknown): the render still has to finish OK, only a stuck one is no longer cut off by the test+ # first, and a call without a result says what came instead (result_of)+ steps.append(call("render", {"project": "tiny", "preview": True}, progress=True, timeout_ms=600000))+ out = mcp(steps, self.tmp, env=self.env, timeout=700)doctor, new = out["results"][1:3]dt = text_of(doctor)self.assertIn("showtime doctor", dt)self.assertRegex(dt, r"\d+ pass")- self.assertIn("--quick", doctor["response"]["result"]["_meta"]["showtime/result"]["command"])+ self.assertIn("--quick", result_of(doctor)["_meta"]["showtime/result"]["command"])if not ready:- self.assertTrue(doctor["response"]["result"]["isError"] or "setup" in dt)+ self.assertTrue(result_of(doctor)["isError"] or "setup" in dt)print(" (render + qa skipped: run `showtime setup` for the browser tools)", file=sys.stderr)return- self.assertFalse(new["response"]["result"]["isError"], text_of(new))+ self.assertFalse(result_of(new)["isError"], text_of(new))proj = self.tmp / "tiny"cfg = json.loads((proj / "showtime.json").read_text(encoding="utf-8"))self.assertEqual((cfg["width"], cfg["height"], cfg["duration"]), (640, 360, 2.0))render = out["results"][3]- res = render["response"]["result"]+ res = result_of(render, out, self.tmp)self.assertFalse(res["isError"], text_of(render))self.assertTrue(text_of(render).startswith("OK: showtime render"))self.assertNotIn("structuredContent", res, "the text summary is what the model should see")@@ -380,12 +409,12 @@ class TestFlow(unittest.TestCase):qt = text_of(qa)self.assertIn("verdict:", qt)self.assertNotIn("verdict: FAIL", qt)- self.assertTrue(any(f.endswith("qa.json") for f in qa["response"]["result"]["_meta"]["showtime/result"]["files"]), qt)+ self.assertTrue(any(f.endswith("qa.json") for f in result_of(qa)["_meta"]["showtime/result"]["files"]), qt)# README loops through the tool: from/to/width/fps reach `deliver exports`lp = mcp([call("deliver_exports", {"video": str(video), "targets": ["gif-small"], "from": 0.5, "to": 1.5,"width": 160, "fps": 10})], self.tmp, env=self.env)["results"][1]- self.assertFalse(lp["response"]["result"]["isError"], text_of(lp))+ self.assertFalse(result_of(lp)["isError"], text_of(lp))gif = video.parent / "exports" / (video.stem + ".loop-small.gif")self.assertTrue(gif.is_file(), text_of(lp))self.assertEqual(int.from_bytes(gif.read_bytes()[6:8], "little"), 160)@@ -393,11 +422,11 @@ class TestFlow(unittest.TestCase):# the same render as a task: a task id at once, then status until the result (any host)first = mcp([call("render", {"project": "tiny", "preview": True, "background": True}, progress=True)],self.tmp, env=self.env)["results"][1]- res = first["response"]["result"]+ res = result_of(first)self.assertTrue(text_of(first).startswith("RUNNING: showtime render"), text_of(first))task = res["_meta"]["showtime/result"]["task"]final = poll_task(task, self.tmp, self.env)- fres = final["response"]["result"]+ fres = result_of(final)self.assertFalse(fres["isError"], text_of(final))self.assertTrue(text_of(final).startswith("OK: showtime render"), text_of(final))self.assertEqual(fres["_meta"]["showtime/result"]["task"], task)diff --git a/skills/showtime/tests/test_pace.py b/skills/showtime/tests/test_pace.pyindex f4aefd2..7186351 100644--- a/skills/showtime/tests/test_pace.py+++ b/skills/showtime/tests/test_pace.py@@ -13,6 +13,10 @@ seeks, and every wait is its fixed value times a factor of 1-5 (never shorter thfactor (5, the ceiling) and the seek cost* a page whose ST.waitFor gate takes 3 s of work in 200 ms pieces (scale 0.03: the gate gets 1.8 s): with thefixed waits the page never becomes ready; paced, the gaps between its frames raise the factor and it does+ * the page-open deadline (stagehost openGuarded, SHOWTIME_TEST_OPEN_TIMEOUT shortens it): render's first page+ and check's pages are tried once more in a new browser, then the command fails naming the step; a browser+ really stopped (SIGSTOP) before check opens its page is killed and check finishes in a new one, and stopped+ later the watchdog ends check with an error naming its last stepNeeds a browser. usage: python tests/test_pace.py [--fast] [-v]"""@@ -62,6 +66,10 @@ def showtime(*args, env=None, timeout=600):timeout=timeout)+STUCK_AT = (r"stuck at: (creating the browser context|opening a tab|setting up the tab|loading the page|"+ r"waiting for the page to be ready)")++def write(path, text):path.parent.mkdir(parents=True, exist_ok=True)path.write_text(text, encoding="utf-8")@@ -171,6 +179,76 @@ process.exit(0);self.assertGreater(paced["pace"]["frame_ms"], 50, paced)self.assertGreater(paced["factor"], 1, paced)+ def test_first_page_open_deadline(self):+ """render's first page has the workers' page-open deadline (5 min; SHOWTIME_TEST_OPEN_TIMEOUT shortens+ it): a browser that never answers while it opens the page is given up, the page tried once more in a new+ browser, and then the render fails with the deadline instead of waiting with none (the first page and+ the WebGL probe had no deadline of their own)."""+ proj = self.tmp / "slowopen"+ write(proj / "showtime.json", json.dumps({"width": 320, "height": 180, "fps": 10, "duration": 0.5, "background": "#202830"}))+ write(proj / "index.html", HEAD + "</head><body><script>"+ "ST.waitFor(new Promise((r) => setTimeout(r, 20000)), 'slow open');\n"+ "ST.onSeek(() => {});</script></body></html>")+ cp = showtime("render", proj, "-o", self.tmp / "slowopen.mp4", "--no-check", "--workers", "1",+ env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT="3"), timeout=300)+ self.assertNotEqual(cp.returncode, 0, cp.stdout[-1500:])+ self.assertIn("trying once more in a new browser", cp.stderr)+ self.assertEqual(cp.stderr.count("trying once more"), 1, cp.stderr[-2000:])+ self.assertRegex(cp.stderr, r"timed out after \d+s: opening the page")+ # names the step (on a fast machine the page's own 20 s wait; a slow one may still be setting the tab up)+ self.assertRegex(cp.stderr, STUCK_AT)++ def slow_open_project(self, name):+ proj = self.tmp / name+ write(proj / "showtime.json", json.dumps({"width": 320, "height": 180, "fps": 10, "duration": 0.5, "background": "#202830"}))+ write(proj / "index.html", HEAD + "</head><body><script>"+ "ST.waitFor(new Promise((r) => setTimeout(r, 20000)), 'slow open');\n"+ "ST.onSeek(() => {});</script></body></html>")+ return proj++ def test_check_open_deadline(self):+ """check opens its pages the way render does (stagehost openGuarded): the page-open deadline, once more in+ a new browser, then an error naming the step it was stuck at; never a check that does not return (a+ macOS CI runner's check outlived its caller's 5 minutes)."""+ proj = self.slow_open_project("slowcheck")+ cp = showtime("check", proj, "--json", "--no-determinism", "--no-timeline", "--no-history", "--samples", "2",+ env=dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT="3"), timeout=300)+ self.assertNotEqual(cp.returncode, 0, cp.stdout[-1500:])+ self.assertEqual(cp.stderr.count("trying once more in a new browser"), 1, cp.stderr[-2000:])+ self.assertIn("the browser stopped answering", cp.stderr)+ # names the step (on a fast machine the page's own 20 s wait; a slow one may still be setting the tab up)+ self.assertRegex(cp.stderr, STUCK_AT)+ self.assertIn("in a new browser too", cp.stderr)++ @unittest.skipIf(sys.platform == "win32", "SIGSTOP is POSIX")+ def test_check_stopped_browser(self):+ """A browser that really stops answering (SIGSTOP, SHOWTIME_TEST_STOP_BROWSER): stopped before the first+ page opens, check gives it up at the deadline, kills it and finishes in a new browser; stopped after the+ image lab page opened, the watchdog ends check with an error naming its last step. Both return in seconds+ (the open deadline is 3 s here) and leave no stopped browser behind."""+ proj = self.tmp / "stopped"+ write(proj / "showtime.json", json.dumps({"width": 320, "height": 180, "fps": 10, "duration": 1, "background": "#202830"}))+ write(proj / "index.html", HEAD + "</head><body style=\"margin:0;background:#234\"><h1 style=\"color:#fff;"+ "font:40px sans-serif\">Hi</h1><script>ST.onSeek(() => {});</script></body></html>")+ args = ("check", proj, "--json", "--no-determinism", "--no-timeline", "--no-history", "--samples", "2")+ env = dict(ENV, SHOWTIME_TEST_OPEN_TIMEOUT="3")+ before = {l for l in subprocess.run(["ps", "-axo", "stat=,command="], stdout=subprocess.PIPE, encoding="utf-8",+ errors="replace").stdout.splitlines() if l.strip().startswith("T")}+ cp = showtime(*args, env=dict(env, SHOWTIME_TEST_STOP_BROWSER="open"), timeout=180)+ self.assertEqual(cp.returncode, 0, cp.stderr[-2000:])+ self.assertTrue(json.loads(cp.stdout)["ok"], cp.stdout[-1500:])+ self.assertEqual(cp.stderr.count("trying once more in a new browser"), 1, cp.stderr[-2000:])+ self.assertIn("stuck at: ", cp.stderr)+ cp = showtime(*args, env=dict(env, SHOWTIME_TEST_STOP_BROWSER="ready:2"), timeout=180)+ self.assertEqual(cp.returncode, 1, cp.stderr[-2000:])+ self.assertIn("the browser stopped answering", cp.stderr)+ self.assertIn("check's last step: opened the image lab page", cp.stderr)+ ps = subprocess.run(["ps", "-axo", "stat=,command="], stdout=subprocess.PIPE, encoding="utf-8", errors="replace").stdout+ # the run's browsers hold a temp profile (--user-data-dir) of their own; the command line never names the+ # project, so a stopped (state T) Chrome after the run is any stopped Chrome that was not stopped before+ stopped = [l for l in ps.splitlines() if l.strip().startswith("T") and "--user-data-dir" in l and "chrom" in l.lower()]+ self.assertEqual([l for l in stopped if l not in before], [], "a stopped browser was left behind")+if __name__ == "__main__":unittest.main(argv=[a for a in sys.argv if a != "--fast"])