Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

test(docs): share Chrome capture launcher [I13]

Corey Olson1105b0c8a210
diff --git a/docs/shots/capture-browser.mjs b/docs/shots/capture-browser.mjs
index 15b35ab7..75b08923 100644
--- a/docs/shots/capture-browser.mjs
+++ b/docs/shots/capture-browser.mjs
@@ -1,71 +1,28 @@
/** Real Chrome capture with explicit document and data readiness (I13,A10). */
-import { spawn } from 'node:child_process';
-import { readFile, writeFile } from 'node:fs/promises';
-import { join } from 'node:path';
-import { evaluationValue } from './devtools-evaluation.mjs';
-
-/** Allow Chrome or the page's next response to advance before another read-only observation. */
-const pause = (ms) => new Promise((resolvePause) => setTimeout(resolvePause, ms));
-
-/** Stop this owned Chrome process and await its sockets and profile release. */
-async function stop(child) {
- if (child.exitCode !== null || child.signalCode !== null) return;
- child.kill();
- await new Promise((resolveStop) => child.once('close', resolveStop));
-}
+import { writeFile } from 'node:fs/promises';
+import { startChrome } from '../../test/chrome-fixture.js';
/** Start Chrome with a disposable profile and return the DevTools connection for its page. */
export async function browser(chrome, profile, url) {
- const child = spawn(chrome, ['--headless=new', '--disable-gpu', '--no-proxy-server', '--use-mock-keychain', '--password-store=basic', '--no-first-run', '--no-default-browser-check', '--disable-background-networking', '--disable-sync', '--disable-extensions', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--window-size=1440,1100', 'about:blank'], { stdio: 'ignore' });
- let socket;
- let port;
+ const view = await startChrome({ executable: chrome, profileDirectory: profile, url });
+ /** Keep this capture's readiness label while using the shared bounded DevTools wait. */
+ async function waitFor(expression, label, timeoutMs = 30_000) {
+ try { await view.waitFor(expression, timeoutMs); }
+ catch (error) { throw new Error(`The demo page did not become ready: ${label}`, { cause: error }); }
+ }
try {
- for (let n = 0; n < 100 && !port; n++) {
- try { port = (await readFile(join(profile, 'DevToolsActivePort'), 'utf8')).split('\n')[0]; } catch {}
- if (!port) await pause(100);
- }
- if (!port) throw new Error('Chrome did not start');
- const response = await fetch(`http://127.0.0.1:${port}/json/new?${encodeURIComponent('about:blank')}`, { method: 'PUT' });
- if (!response.ok) throw new Error('Chrome could not open the demo view');
- const target = await response.json();
- socket = new WebSocket(target.webSocketDebuggerUrl);
- await new Promise((ok, fail) => { socket.addEventListener('open', ok, { once: true }); socket.addEventListener('error', fail, { once: true }); });
- let id = 0;
- const pending = new Map();
- socket.addEventListener('message', ({ data }) => { const m = JSON.parse(String(data)); const waiter = pending.get(m.id); if (waiter) { pending.delete(m.id); m.error ? waiter.reject(new Error('Chrome operation failed: ' + m.error.message)) : waiter.resolve(m.result); } });
- /** Bound a protocol operation so a stalled renderer cannot strand Chrome or a capture. */
- const send = (method, params = {}) => new Promise((ok, fail) => {
- const key = ++id;
- const timer = setTimeout(() => { pending.delete(key); fail(new Error(`Chrome operation timed out: ${method}`)); }, 30_000);
- pending.set(key, { resolve: (value) => { clearTimeout(timer); ok(value); }, reject: (error) => { clearTimeout(timer); fail(error); } });
- socket.send(JSON.stringify({ id: key, method, params }));
- });
- await send('Page.enable');
- await send('Runtime.enable');
- const evaluate = async (expression) => evaluationValue(await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }));
- /** Wait for a read-only page condition; a timeout is a failed capture, never a silent success. */
- async function waitFor(expression, label, timeoutMs = 30_000) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (await evaluate(expression)) return;
- await pause(100);
- }
- throw new Error(`The demo page did not become ready: ${label}`);
- }
- await send('Page.navigate', { url });
await waitFor(`location.href === ${JSON.stringify(url)} && document.readyState === 'complete'`, 'intended HTTP document');
- return {
- evaluate,
- waitFor,
- viewport: (width, height) => send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }),
- screenshot: async (path) => { const result = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); await writeFile(path, Buffer.from(result.data, 'base64')); },
- close: async () => { socket.close(); await stop(child); },
- };
} catch (error) {
- socket?.close();
- await stop(child);
+ await view.close();
throw error;
}
+ return {
+ evaluate: view.evaluate,
+ waitFor,
+ viewport: (width, height) => view.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }),
+ screenshot: async (path) => { const result = await view.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); await writeFile(path, Buffer.from(result.data, 'base64')); },
+ close: () => view.close(),
+ };
}
/** Wait for this demo's API data and rendered controls before storage writes or selection. */
diff --git a/docs/shots/capture-browser.test.js b/docs/shots/capture-browser.test.js
index 031047a2..bd153c76 100644
--- a/docs/shots/capture-browser.test.js
+++ b/docs/shots/capture-browser.test.js
@@ -1,7 +1,7 @@
/** Real Chrome readiness over the disposable demo's exported API (I13,A10). */
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
-import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -104,6 +104,33 @@ test('capture cleanup retries while a closed browser flushes its profile [I13,A1
}
});
+test('demo capture preserves one shared Chrome startup diagnostic [I13]', { timeout: 40_000 }, async (t) => {
+ const directory = await mkdtemp(join(tmpdir(), 'pullboard-demo-chrome-no-port-'));
+ const profile = join(directory, 'profile');
+ const launches = join(directory, 'launches');
+ const wrapper = join(directory, 'chrome-no-port');
+ t.after(() => rm(directory, { recursive: true, force: true }));
+ await writeFile(wrapper, [
+ '#!/usr/bin/env node',
+ "const fs = require('node:fs');",
+ `const launches = ${JSON.stringify(launches)};`,
+ "fs.appendFileSync(launches, 'launch\\n');",
+ "process.stderr.write('DEMO_CAPTURE_NO_PORT_STDERR\\n');",
+ "process.on('SIGTERM', () => { fs.appendFileSync(launches, 'stopped\\n'); process.exit(0); });",
+ 'setInterval(() => {}, 1000);',
+ ].join('\n'));
+ await chmod(wrapper, 0o700);
+
+ await assert.rejects(browser(wrapper, profile, 'about:blank'), (error) => {
+ assert.match(error.message, /did not publish its DevTools port/u);
+ assert.match(error.message, /elapsed \d+ms; 30000ms DevTools budget/u);
+ assert.ok(Number(/elapsed (\d+)ms/u.exec(error.message)[1]) >= 30_000, 'the capture uses the shared 30-second startup budget');
+ assert.match(error.message, /DEMO_CAPTURE_NO_PORT_STDERR/u, 'the capture preserves Chrome stderr in its startup refusal');
+ return true;
+ });
+ assert.equal(await readFile(launches, 'utf8'), 'launch\nstopped\n', 'the shared launcher starts once and exits before profile cleanup');
+});
+
test('demo capture waits for the intended HTTP document and populated board in Chrome [I13,A10]', { timeout: 90_000 }, async (t) => {
const chrome = [process.env.PULLBOARD_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'].filter(Boolean).find((file) => spawnSync(file, ['--version'], { stdio: 'ignore' }).status === 0);
if (!chrome) return t.skip('Install Chrome to prove demo capture readiness.');