/** * `render_page` through the self-host image's Chrome sidecar, end to end (#292). CI only: * .github/workflows/docker.yml runs it on the candidate image, and it refuses to start outside * GitHub Actions. * * 1. Starts SeaweedFS and one instance on one network, and the compose file's Chrome on a network * of its own that it shares with the instance only (as the compose file's chrome profile does). * The browser publishes no port. * 2. The first owner publishes and makes an agent key. The agent calls `render_page` over `/mcp` * for the starter post, and a JPEG screenshot and the checks come back. * 3. Afterwards the browser keeps no context: every render's browser context is gone. * * node scripts/render-smoke.ts --image [--port ] */ import { execFile } from "node:child_process"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; if (process.env.GITHUB_ACTIONS !== "true") { console.error("render-smoke runs in CI only (.github/workflows/docker.yml), never locally"); process.exit(2); } const arg = (name: string): string | undefined => { const i = process.argv.indexOf(`--${name}`); return i === -1 ? undefined : process.argv[i + 1]; }; const image = arg("image") ?? "cloudhal:ci"; const port = Number(arg("port") ?? 48787); const id = `cloudhal-render-${process.pid}`; const nets = { main: `${id}-main`, render: `${id}-render` }; const names = { store: `${id}-store`, chrome: `${id}-chrome`, cloudhal: `${id}-cloudhal` }; // 127.0.0.1, never localhost (#306) const studio = `http://127.0.0.1:${port}`; const compose = readFileSync( path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), "utf8", ); const pinned = (repo: string) => { const at = compose.indexOf(`image: ${repo}:`); if (at === -1) throw new Error(`compose.yml names no ${repo} image`); return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); }; const STORE_IMAGE = pinned("chrislusf/seaweedfs"); const CHROME_IMAGE = pinned("chromedp/headless-shell"); const run = promisify(execFile); async function docker(args: string[], timeout = 120_000): Promise { const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); return stdout.trim(); } async function dockerLogs(name: string): Promise { const { stdout, stderr } = await run("docker", ["logs", "--tail", "200", "--timestamps", name], { encoding: "utf8", timeout: 30_000, maxBuffer: 64 << 20, }); return `${stdout}${stderr}`; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const step = (text: string) => console.log(`āœ“ ${text}`); function expect(ok: boolean, what: string, detail?: unknown): void { if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); } const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-render-")); function envFile(name: string, env: Record): string { const file = path.join(work, `${name}.env`); writeFileSync( file, Object.entries(env) .map(([k, v]) => `${k}=${v}\n`) .join(""), { mode: 0o600 }, ); return file; } interface Res { status: number; text: string; body: unknown; headers: Headers; } async function req(url: string, init: RequestInit = {}, ms = 30_000): Promise { try { const res = await fetch(url, { ...init, signal: AbortSignal.timeout(ms) }); const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch { // not JSON } return { status: res.status, text, body, headers: res.headers }; } catch (e) { const err = e as { name?: string; cause?: { code?: string } }; const text = err.cause?.code ?? err.name ?? String(e); return { status: 0, text, body: text, headers: new Headers() }; } } async function until(what: string, seconds: number, check: () => Promise) { const deadline = Date.now() + seconds * 1000; while (Date.now() < deadline) { const v = await check().catch(() => undefined); if (v !== undefined) return v; await sleep(1000); } throw new Error(`${what} within ${seconds} s`); } async function start(env: Record): Promise { await docker(["network", "create", nets.main]); await docker(["network", "create", nets.render]); const s3 = JSON.stringify({ identities: [ { name: "cloudhal", credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], actions: ["Admin", "Read", "Write", "List", "Tagging"], }, ], }); await docker([ ...["run", "-d", "--name", names.store, "--network", nets.main, "--network-alias", "seaweedfs"], ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], STORE_IMAGE, "-c", 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', ]); // as the chrome profile runs it: no port, its own network, no capabilities await docker([ ...["run", "-d", "--name", names.chrome, "--network", nets.render, "--network-alias", "chrome"], ...["--shm-size", "512m", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], CHROME_IMAGE, ]); const cloudhal = envFile("cloudhal", { ...env, CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", CLOUDHAL_S3_BUCKET: "cloudhal", CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, CLOUDHAL_SITE_NAME: "Render Site", CLOUDHAL_BASE_URL: studio, CLOUDHAL_BROWSER_URL: "http://chrome:9222", }); await docker([ ...["run", "-d", "--name", names.cloudhal, "--network", nets.main, "--read-only"], ...["--tmpfs", "/tmp", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], ...["--env-file", cloudhal, "-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], image, ]); // the browser reaches the instance as `cloudhal`, the default CLOUDHAL_RENDER_ORIGIN's host await docker(["network", "connect", "--alias", "cloudhal", nets.render, names.cloudhal]); } /** One JSON-RPC answer from `/mcp`, as JSON or as the first matching server-sent event. */ async function rpc( key: string, session: string | undefined, message: Record, ): Promise<{ answer: Record | undefined; session: string | undefined }> { const res = await fetch(`${studio}/mcp`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}), }, body: JSON.stringify({ jsonrpc: "2.0", ...message }), signal: AbortSignal.timeout(120_000), }); const text = await res.text(); const next = res.headers.get("mcp-session-id") ?? session; if (!("id" in message)) return { answer: undefined, session: next }; expect(res.status === 200, `/mcp ${String(message.method)}`, { status: res.status, text }); const json = (res.headers.get("content-type") ?? "").includes("text/event-stream") ? text .split("\n") .filter((l) => l.startsWith("data:")) .map((l) => JSON.parse(l.slice(5)) as Record) .find((m) => m.id === message.id) : (JSON.parse(text) as Record); return { answer: json, session: next }; } async function ownerAndKey(env: Record): Promise<{ cookie: string; key: string }> { const json = { origin: studio, "content-type": "application/json" }; const signUp = await req(`${studio}/api/auth/sign-up/email`, { method: "POST", headers: { ...json, "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, body: JSON.stringify({ name: "Render Owner", email: "owner@example.com", password: "render-smoke-password", }), }); expect(signUp.status === 200, "sign-up of the first owner", signUp.body); const cookie = signUp.headers .getSetCookie() .map((c) => c.split(";")[0] as string) .find((c) => c.includes("better-auth.session_token=")) ?? ""; const published = await req(`${studio}/api/sites/${env.CLOUDHAL_SITE_ID}/snapshots`, { method: "POST", headers: { ...json, cookie }, body: JSON.stringify({ publish: true }), }); expect(published.status === 201, "publish", published.body); const created = await req(`${studio}/api/agent-keys`, { method: "POST", headers: { ...json, cookie }, body: JSON.stringify({ name: "render smoke" }), }); const key = (created.body as { key?: string }).key; expect(created.status === 201 && typeof key === "string", "the agent key", created.status); return { cookie, key: key as string }; } async function main(env: Record): Promise { await start(env); const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; await until("the instance did not create its site", 180, async () => { const r = await req(`${studio}/api/admin/sites`, { headers: admin }); const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; return sites.some((s) => s.id === env.CLOUDHAL_SITE_ID) ? true : undefined; }); step("an instance with CLOUDHAL_BROWSER_URL and the Chrome sidecar are up"); const { cookie, key } = await ownerAndKey(env); const list = await req(`${studio}/api/sites/${env.CLOUDHAL_SITE_ID}/entries?collection=posts`, { headers: { cookie }, }); const entry = (list.body as { id: string; slug: string }[]).find?.( (e) => e.slug === "hello-world", ); expect(entry !== undefined, "the starter post", list.status); step("the owner published and made an agent key"); const init = await rpc(key, undefined, { id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "render-smoke", version: "1.0.0" }, }, }); await rpc(key, init.session, { method: "notifications/initialized" }); const { answer } = await rpc(key, init.session, { id: 2, method: "tools/call", params: { name: "render_page", arguments: { siteId: env.CLOUDHAL_SITE_ID, entryId: entry?.id, widths: [1440] }, }, }); const result = answer?.result as | { isError?: boolean; content?: { type: string; mimeType?: string; data?: string; text?: string }[]; } | undefined; const content = result?.content ?? []; expect(result !== undefined && !result.isError, "render_page answered", answer); const jpeg = content.find((c) => c.type === "image" && c.mimeType === "image/jpeg"); const bytes = Buffer.from(jpeg?.data ?? "", "base64"); expect(bytes.length > 2000 && bytes[0] === 0xff && bytes[1] === 0xd8, "a JPEG screenshot", { bytes: bytes.length, text: content.filter((c) => c.type === "text").map((c) => c.text?.slice(0, 300)), }); step(`render_page returned a ${bytes.length}-byte JPEG through the sidecar`); // the render's context is disposed: only the browser's own first page is left const contexts = await docker([ ...["run", "--rm", "--network", nets.render, "curlimages/curl:8.11.1"], ...["-s", "-m", "10", "-H", "Host: localhost", "http://chrome:9222/json/list"], ]); const pages = (JSON.parse(contexts) as { type: string; url: string }[]).filter( (p) => p.type === "page" && p.url !== "about:blank", ); expect(pages.length === 0, "the render's tabs and context are gone", pages); step("no page of the render is left in the browser"); console.log("\nrender_page smoke test passed."); } const env = Object.fromEntries( (await docker(["run", "--rm", image, "secrets"])) .split("\n") .filter((l) => l.includes("=") && !l.startsWith("#")) .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), ) as Record; try { await main(env); } catch (e) { console.error(`\nāœ— ${e instanceof Error ? e.message : String(e)}`); for (const name of Object.values(names)) { const text = await dockerLogs(name).catch((d: Error) => `error: ${d.message}`); console.error(`--- ${name} logs\n${text.slice(-12_000)}`); } process.exitCode = 1; } finally { for (const name of Object.values(names)) await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); for (const n of Object.values(nets)) await docker(["network", "rm", n], 30_000).catch(() => undefined); rmSync(work, { recursive: true, force: true }); }