Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
pnpm shots: fail fast and clean up on every way Chrome or the page can fail
Leigh12-93ae9125b614fe
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 94da7fe21f..34dc26594a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -14,8 +14,8 @@ makes a PR easy to merge. Read it once before opening anything; it's short on pu- **Keep it green.** `pnpm typecheck && pnpm test` must pass. Server changes need tests (see below).- **UI changes follow [`DESIGN.md`](DESIGN.md).** Tokens, type, spacing, components, words andstates. Before/after screenshots in Midnight and Daylight go in the PR body; video for anything animated.- With `pnpm dev` running, `pnpm shots /some-preview.html?state=x --name before` saves them at 390, 768- and 1440 wide in both skins to `shots/`.+ With `pnpm dev` running, `pnpm shots '/room-card-preview.html?state=memory' --name before` saves them at+ 390, 768 and 1440 wide in both skins to `shots/`.## Dev setupdiff --git a/scripts/shots.test.ts b/scripts/shots.test.tsindex 1a963b9db1..699c0a4288 100644--- a/scripts/shots.test.ts+++ b/scripts/shots.test.ts@@ -17,6 +17,8 @@ describe("pnpm shots", () => {expect(() => parseShotsArgs(["room-card-preview.html"])).toThrow(/starts with "\/"/);expect(() => parseShotsArgs(["/", "/rail"])).toThrow(/usage/);expect(() => parseShotsArgs(["--name", "../before"])).toThrow(/--name/);+ for (const elsewhere of ["//other.test/room-card-preview.html", "/\\other.test/room-card-preview.html"]) expect(() => parseShotsArgs([elsewhere])).toThrow(/not another site/);+ expect(parseShotsArgs(["/rail.html", "--url", "http://localhost:6000"]).path).toBe("/rail.html");});it("covers phone, tablet and desktop in Midnight and Daylight, each with its own file and skin in the address", () => {diff --git a/scripts/shots.ts b/scripts/shots.tsindex f3d5072477..0a212dd79b 100644--- a/scripts/shots.ts+++ b/scripts/shots.ts@@ -1,11 +1,6 @@-// The before and after pictures a UI PR carries (CONTRIBUTING.md): one page of the running `pnpm dev` app at a phone, a-// tablet and a desktop width, in Midnight and Daylight, with a headless Chrome in a throwaway profile (OMB_CDP_CHROME,-// else the installed Google Chrome).-//-// pnpm shots [PATH] [--name before|after] [--url http://127.0.0.1:5199] [--out shots] [--wait SELECTOR]-//-// PATH is the app's own page ("/") or a preview such as "/room-card-preview.html?state=memory". It fails when the page-// does not wear the skin it was asked for, so a picture is never mislabelled.+// The before and after pictures a UI PR carries: one page of the running `pnpm dev` app at a phone, a tablet and a+// desktop width, in Midnight and Daylight, with a headless Chrome in a throwaway profile (OMB_CDP_CHROME, else the+// installed Google Chrome).import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";@@ -14,7 +9,7 @@ import { pathToFileURL } from "node:url";import { parseArgs } from "node:util";import { removeTempDir } from "../server/testing/cleanup.ts";-import { openHeadlessChrome } from "./testing/headless-chrome.ts";+import { openHeadlessChrome, type HeadlessPage } from "./testing/headless-chrome.ts";export const SIZES = [{ width: 390, height: 844, mobile: true },@@ -63,6 +58,8 @@ export function parseShotsArgs(argv: string[]): ShotsOptions {if (positionals.length > 1) throw new Error(USAGE);const path = positionals[0] ?? "/";if (!path.startsWith("/")) throw new Error(`PATH starts with "/", such as /room-card-preview.html\n${USAGE}`);+ // "//host/page" and "/\host/page" start with "/" too, yet name another site.+ if (new URL(path, values.url).origin !== new URL(values.url!).origin) throw new Error(`PATH is a page of ${values.url}, not another site\n${USAGE}`);if (values.name !== undefined && !/^[\w-]+$/.test(values.name)) throw new Error("--name takes letters, digits, - and _");return { path, name: values.name ?? nameFor(path), url: values.url!, out: values.out!, wait: values.wait! };}@@ -80,27 +77,37 @@ async function main(argv: string[]): Promise<void> {const options = parseShotsArgs(argv);mkdirSync(resolve(options.out), { recursive: true });const profile = mkdtempSync(join(tmpdir(), "omb-shots-chrome-"));- const page = await openHeadlessChrome(profile);+ let page: HeadlessPage | undefined;try {+ page = await openHeadlessChrome(profile);for (const shot of shotPlan(options)) {// The app keeps its skin in localStorage; set before its first paint, like a person's own choice.const { identifier } = await page.send("Page.addScriptToEvaluateOnNewDocument", { source: `try { localStorage.setItem("omb-skin", ${JSON.stringify(shot.skin)}) } catch {}` });await page.send("Emulation.setDeviceMetricsOverride", { width: shot.width, height: shot.height, deviceScaleFactor: 2, mobile: shot.mobile });await page.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: shot.scheme }] });await page.evaluate("globalThis.ombShotsLeft = true");- await page.send("Page.navigate", { url: shot.url });+ const went = await page.send("Page.navigate", { url: shot.url });+ if (went.errorText) throw new Error(`${shot.url} did not load: ${went.errorText}`);+ // The same address with a #fragment moves within the page; a new page is what clears the marker.+ if (!went.loaderId) await page.send("Page.reload");await page.until(`!globalThis.ombShotsLeft && document.readyState === "complete" && document.querySelector(${JSON.stringify(options.wait)})`, 30_000);await page.evaluate("document.fonts.ready.then(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))))");- const worn = await page.evaluate("document.documentElement.dataset.skin");+ const worn = await page.evaluate("globalThis.ombShotsChecked = true, document.documentElement.dataset.skin");if (worn !== shot.skin) throw new Error(`${shot.url} wears "${worn}", not ${shot.skin}`);- writeFileSync(resolve(shot.file), await page.capture());+ const png = await page.capture();+ if (await page.evaluate("globalThis.ombShotsChecked") !== true) throw new Error(`${shot.url} reloaded while it was photographed; run again`);+ writeFileSync(resolve(shot.file), png);await page.send("Page.removeScriptToEvaluateOnNewDocument", { identifier });console.log(shot.file);}} finally {- // Killing Chrome leaves its profile locked on Windows while its children wind down; closing it lets them go first.- await Promise.race([page.send("Browser.close").catch(() => undefined), delay(5_000)]);- page.close();+ if (page) {+ // Killing Chrome leaves its profile locked on Windows while its children wind down; closing it and waiting for it to+ // exit lets them go first.+ await Promise.race([page.send("Browser.close").catch(() => undefined), delay(5_000, undefined, { ref: false })]);+ await page.exited(5_000);+ page.close();+ }await removeTempDir(profile);}}diff --git a/scripts/testing/headless-chrome.ts b/scripts/testing/headless-chrome.tsindex eac2a93739..216b772b30 100644--- a/scripts/testing/headless-chrome.ts+++ b/scripts/testing/headless-chrome.ts@@ -16,33 +16,63 @@ export interface HeadlessPage {/** A PNG of the page, or of `clip` in CSS pixels. */capture: (clip?: { x: number; y: number; width: number; height: number }) => Promise<Buffer>;close: () => void;+ /** Whether Chrome's process ended within `timeoutMs`, as it does after Browser.close. */+ exited: (timeoutMs: number) => Promise<boolean>;+}++/** `work`, or a rejection with `error` once `ms` pass without it settling. */+async function within<T>(work: Promise<T>, ms: number, error: () => Error): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([work, new Promise<never>((_, fail) => { timer = setTimeout(() => fail(error()), Math.max(0, ms)); })]);+ } finally {+ clearTimeout(timer);+ }}export async function openHeadlessChrome(profile: string): Promise<HeadlessPage> {const chrome = spawn(CHROME_PATH, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--use-mock-keychain",`--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"], { stdio: "ignore" });+ const ended = new Promise<void>((done) => { chrome.once("exit", () => done()); });+ let spawnError: Error | undefined;+ chrome.once("error", (error) => { spawnError = error; });let port = "";- for (let i = 0; i < 100 && !port; i++) {+ for (let i = 0; i < 100 && !port && !spawnError; i++) {await delay(100);try { port = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]!.trim(); } catch {}}- if (!port) { chrome.kill(); throw new Error("Chrome did not start"); }- const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; webSocketDebuggerUrl: string }>;- const socket = new WebSocket(targets.find((target) => target.type === "page")!.webSocketDebuggerUrl);- await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; });+ if (!port) { chrome.kill(); throw new Error(`Chrome did not start${spawnError ? `: ${spawnError.message}` : ""}`); }+ let socket: WebSocket | undefined;+ try {+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; webSocketDebuggerUrl: string }>;+ const opening = new WebSocket(targets.find((target) => target.type === "page")!.webSocketDebuggerUrl);+ socket = opening;+ await new Promise((done, fail) => { opening.onopen = done; opening.onerror = () => fail(new Error("Chrome's DevTools connection did not open")); });+ } catch (error) {+ socket?.close();+ chrome.kill();+ throw error;+ }+ const open = socket;let next = 0;const waiting = new Map<number, { done: (value: any) => void; fail: (error: Error) => void }>();- socket.onmessage = (event) => {+ open.onmessage = (event) => {const message = JSON.parse(String(event.data));const call = waiting.get(message.id);if (!call) return;waiting.delete(message.id);if (message.error) call.fail(new Error(message.error.message)); else call.done(message.result);};+ // A call Chrome can no longer answer fails instead of waiting for ever.+ open.onclose = () => {+ for (const call of waiting.values()) call.fail(new Error("Chrome's DevTools connection closed"));+ waiting.clear();+ };const send = (method: string, params: object = {}) => new Promise<any>((done, fail) => {+ if (open.readyState !== WebSocket.OPEN) { fail(new Error("Chrome's DevTools connection closed")); return; }const id = ++next;waiting.set(id, { done, fail });- socket.send(JSON.stringify({ id, method, params }));+ open.send(JSON.stringify({ id, method, params }));});const evaluate = async (expression: string) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true })).result?.value;return {@@ -50,8 +80,10 @@ export async function openHeadlessChrome(profile: string): Promise<HeadlessPage>evaluate,async until(condition, timeoutMs = 60_000) {const end = Date.now() + timeoutMs;- while (!(await evaluate(`Boolean(${condition})`).catch(() => false))) {- if (Date.now() > end) throw new Error(`${condition} never held (${await evaluate("document.querySelector('main')?.textContent?.slice(0, 120) ?? ''").catch(() => "")})`);+ const late = () => new Error(`${condition} never held`);+ // Each look is bounded too: a page that stops answering still ends the wait on time.+ while (!(await within(evaluate(`Boolean(${condition})`).catch(() => false), Math.max(1_000, end - Date.now()), late))) {+ if (Date.now() > end) throw new Error(`${condition} never held (${await within(evaluate("document.querySelector('main')?.textContent?.slice(0, 120) ?? ''"), 1_000, late).catch(() => "")})`);await delay(250);}},@@ -59,6 +91,7 @@ export async function openHeadlessChrome(profile: string): Promise<HeadlessPage>const { data } = await send("Page.captureScreenshot", { format: "png", ...(clip ? { clip: { ...clip, scale: 1 } } : {}) });return Buffer.from(data, "base64");},- close() { socket.close(); chrome.kill(); },+ close() { open.close(); chrome.kill(); },+ exited: (timeoutMs) => within(ended.then(() => true), timeoutMs, () => new Error("Chrome is still running")).catch(() => false),};}