// Real Chromium regression checks for the integrated 9web views. No npm deps.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import net from 'node:net';
const binary = path.resolve(process.argv[2] || 'zig-out/bin/9web');
const work = await fs.mkdtemp(path.join(os.tmpdir(), '9web-ui-'));
const children = [], exceptions = [], pending = new Map();
let socket, serial = 0;
function start(command, args, env = process.env) {
const p = spawn(command, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
p.output = ''; p.stdout.on('data', b => { p.output += b; }); p.stderr.on('data', b => { p.output += b; });
p.on('error', e => { p.output += e.message; }); children.push(p); return p;
}
async function port() {
const s = net.createServer(); s.listen(0, '127.0.0.1'); await once(s, 'listening');
const n = s.address().port; await new Promise(resolve => s.close(resolve)); return n;
}
async function wait(fn, message, timeout = 15000) {
const until = Date.now() + timeout;
while (Date.now() < until) { try { const value = await fn(); if (value) return value; } catch {} await new Promise(r => setTimeout(r, 50)); }
throw new Error('timeout: ' + message);
}
function cdp(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++serial;
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 10000);
pending.set(id, { resolve, reject, timer }); socket.send(JSON.stringify({ id, method, params }));
});
}
async function evaluate(expression) {
const r = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails));
return r.result.value;
}
async function click(selector) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); }
async function view(name) {
await click(`#view-${name}`);
await wait(() => evaluate(`!document.getElementById('${name}-view').hidden`), name + ' view');
}
async function readySites() { await wait(() => evaluate(`document.querySelectorAll('#sites-entries tr').length === 1`), 'site row'); }
try {
const root = path.join(work, 'public'); await fs.mkdir(root);
await fs.writeFile(path.join(root, 'index.html'), '
Fixture
');
await fs.writeFile(path.join(work, 'large.txt'), 'x'.repeat(180000));
const dashboard = await port(), sitePort = await port(), debugPort = await port();
const runtime = path.join(work, 'runtime');
await fs.mkdir(path.join(runtime, '9p'), { recursive: true });
start(path.resolve('zig-out/bin/9proc-demo'), ['--unix', path.join(runtime, '9p', 'fixture')]);
await wait(() => fs.stat(path.join(runtime, '9p', 'fixture')), '9P fixture posted');
await fs.writeFile(path.join(work, 'config.json'), JSON.stringify({ filesystem: '/', sites: [{ name: 'fixture', title: 'Fixture notes', cwd: work, root, port: sitePort, build: ['sh', '-c', 'echo integrated-build'], inputs: ['public/index.html'] }] }));
const startWeb = () => start(path.resolve('zig-out/bin/9ns'), ['--mntgen', '--', binary, '--listen', `127.0.0.1:${dashboard}`, '--catalog', path.join(work, 'config.json'), '--catalog-socket', path.join(work, 'catalog.sock'), '--state-dir', path.join(work, 'state')], { ...process.env, XDG_RUNTIME_DIR: runtime });
const web = startWeb();
const url = `http://127.0.0.1:${dashboard}`;
await wait(async () => (await fetch(url)).ok, 'server ready');
assert.equal((await (await fetch(url + '/_cloud9/config.json')).json()).catalog, true);
assert.equal((await fetch(url + '/_cloud9/catalog.js')).status, 404, 'standalone JS removed');
start(process.env.CLOUD9_CHROME || 'google-chrome-stable', ['--headless=new', '--no-sandbox', '--disable-dev-shm-usage', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${work}/chrome`, `--remote-debugging-port=${debugPort}`, 'about:blank']);
const target = await wait(async () => (await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, { method: 'PUT' })).json(), 'browser ready');
socket = new WebSocket(target.webSocketDebuggerUrl); await once(socket, 'open');
socket.addEventListener('message', ({ data }) => {
const m = JSON.parse(data);
if (m.id) {
const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id);
if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result);
} else if (m.method === 'Runtime.exceptionThrown') exceptions.push(m.params.exceptionDetails);
});
await cdp('Runtime.enable'); await cdp('Page.enable');
await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false });
await cdp('Page.navigate', { url });
await wait(() => evaluate(`document.getElementById('status')?.textContent.includes('entries')`), 'files loaded');
assert.equal(await evaluate(`document.querySelectorAll('header').length`), 1);
assert.equal(await evaluate(`document.querySelector('#sidebar')`), null);
assert.equal(await evaluate(`document.querySelector('.brand').textContent`), '9web');
assert.equal(await evaluate(`document.querySelector('footer').textContent`), 'served by 9web');
assert.equal(await evaluate(`document.title`), '/ — 9web');
assert.equal(await evaluate(`Boolean(document.querySelector('#entries a[data-path="/etc"]'))`), true);
assert.equal(await evaluate(`getComputedStyle(document.documentElement).backgroundColor`), 'rgb(255, 255, 255)');
assert.equal(await evaluate(`document.getElementById('view-files').getAttribute('aria-current')`), 'page');
// Browse a real mounted 9P tree, including finite zero-stat-length files.
async function browse(path) {
await evaluate(`document.getElementById('path').value = ${JSON.stringify(path)}; document.getElementById('path-form').requestSubmit()`);
await wait(() => evaluate(`document.getElementById('status').textContent === 'File loaded.' || document.getElementById('status').textContent.includes('entries')`), 'mounted path loaded');
}
await browse('/mnt/9p/fixture/build');
assert.equal(await evaluate(`Boolean(document.querySelector('#entries a[data-path="/mnt/9p/fixture/build/zig_version"]'))`), true);
await browse('/mnt/9p/fixture/runtime/pid');
assert.match(await evaluate(`document.getElementById('editor').value`), /^\d+/);
await browse('/mnt/9p/fixture/runtime/ctl');
assert.equal(await evaluate(`document.getElementById('editor').value`), '');
await browse(path.join(work, 'large.txt'));
assert.equal(await evaluate(`document.getElementById('editor').value.length`), 180000, 'full-msize browser reads across several frames');
await browse('/_9web/sites/fixture');
await click('#entries a[data-path="/_9web/sites/fixture/events"][data-follow]');
await wait(() => evaluate(`document.getElementById('stream').textContent.includes('revision')`), 'direct follow of blocking events');
assert.equal(await evaluate(`document.getElementById('go').disabled`), false, 'stream does not block navigation');
await click('#follow');
assert.equal(await evaluate(`document.getElementById('status').textContent`), 'Stream stopped.');
await browse('/');
await fs.mkdir('.zig-cache/catalog-ui', { recursive: true });
await fs.writeFile('.zig-cache/catalog-ui/files.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
await view('sites'); await readySites();
assert.equal(await evaluate(`document.title`), 'sites — 9web');
assert.equal(await evaluate(`document.querySelector('#sites-entries .site-name').href`), `http://127.0.0.1:${sitePort}/`);
assert.equal(await evaluate(`document.querySelectorAll('link[rel=stylesheet]').length`), 1);
assert.equal(await evaluate(`document.querySelector('link[rel=stylesheet]').getAttribute('href')`), '/_cloud9/style.css');
// Build button writes through the same /fs tree as the normal file browser.
await click('#sites-entries button');
await wait(() => evaluate(`document.querySelector('#sites-entries .site-phase').textContent.includes('exit 0')`), 'build complete');
await evaluate(`document.querySelector('#sites-entries button').focus()`);
await click('#sites-reload');
await evaluate(`document.querySelector('#sites-entries button').focus()`);
await wait(() => evaluate(`!document.getElementById('sites-reload').disabled`), 'refresh complete');
assert.equal(await evaluate(`document.activeElement === document.querySelector('#sites-entries button')`), true, 'refresh preserves focused control');
await click('#sites-entries a[data-path$="/log"]');
await wait(() => evaluate(`document.getElementById('editor').value.includes('integrated-build')`), 'log in file viewer');
assert.equal(await evaluate(`document.getElementById('files-view').hidden`), false);
// Switching views preserves the existing file editor and its unsaved contents.
await evaluate(`document.getElementById('editor').value = 'unsaved note'; document.getElementById('editor').dispatchEvent(new Event('input'))`);
await view('sites'); await view('services');
await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services loaded');
await evaluate('history.back()');
await wait(() => evaluate(`!document.getElementById('sites-view').hidden`), 'back to sites');
await evaluate('history.back()');
await wait(() => evaluate(`!document.getElementById('files-view').hidden`), 'back to files');
assert.equal(await evaluate(`document.getElementById('editor').value`), 'unsaved note');
assert.equal(await evaluate(`document.getElementById('edit-status').textContent`), 'Unsaved changes.');
// Reload/deep-link into a tab; no synthetic 9P path is reserved for the tab.
await evaluate(`window.onbeforeunload = null; window.confirm = () => true`);
// A fresh target avoids bypassing the intentional beforeunload prompt.
const target2 = await (await fetch(`http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(url + '/?view=sites')}`, { method: 'PUT' })).json();
socket.close(); socket = new WebSocket(target2.webSocketDebuggerUrl); await once(socket, 'open');
socket.addEventListener('message', ({ data }) => {
const m = JSON.parse(data); if (!m.id) return;
const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id);
if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result);
});
await cdp('Runtime.enable'); await cdp('Page.enable'); await readySites();
assert.equal(await evaluate(`document.getElementById('view-sites').getAttribute('aria-current')`), 'page');
await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false });
await fs.mkdir('.zig-cache/catalog-ui', { recursive: true });
await fs.writeFile('.zig-cache/catalog-ui/sites.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
await view('services');
await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services ready');
await fs.writeFile('.zig-cache/catalog-ui/services.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
await view('sites');
await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
assert.equal(await evaluate(`document.documentElement.scrollWidth <= innerWidth`), true, 'mobile page does not overflow');
await fs.writeFile('.zig-cache/catalog-ui/mobile.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
assert.deepEqual(exceptions, []);
// A live port remains exclusive, but TIME_WAIT must not break a restart.
const competitor = start(binary, ['--listen', `127.0.0.1:${dashboard}`]);
await wait(() => competitor.exitCode !== null, 'competing listener refused');
assert.notEqual(competitor.exitCode, 0);
assert.match(competitor.output, /address already in use/);
web.kill('SIGTERM'); await once(web, 'exit');
await fs.unlink(path.join(work, 'catalog.sock'));
startWeb();
await wait(async () => (await fetch(url)).ok && (await fetch(`http://127.0.0.1:${sitePort}`)).ok, 'immediate restart with recent HTTP traffic');
// Opt-in, read-only smoke navigation against an installed workstation.
if (process.env.NINE_WEB_LIVE) {
for (const pathname of ['/mnt/9p', '/mnt/9p/agents', '/mnt/9p/agents/codex/history', '/mnt/9p/zmx/daybreak/command', '/mnt/9p/zmx/daybreak/cwd', '/usr/bin']) {
await cdp('Page.navigate', { url: process.env.NINE_WEB_LIVE + pathname });
await wait(() => evaluate(`document.getElementById('path')?.value === ${JSON.stringify(pathname)} && (document.getElementById('status').textContent === 'File loaded.' || document.getElementById('status').textContent.includes('entries'))`), 'live navigation: ' + pathname, 30000).catch(async error => {
throw new Error(error.message + ': ' + await evaluate(`document.getElementById('status')?.textContent`));
});
console.log('live browser navigation passed:', pathname);
}
}
console.log('catalog_ui: shared shell/style, tab history, file/log navigation, build control, focus, dirty edits and mobile layout passed');
} catch (e) {
for (const child of children) console.error(child.output.slice(-5000));
throw e;
} finally {
socket?.close();
for (const p of children.reverse()) {
if (p.exitCode === null) { p.kill('SIGTERM'); await Promise.race([once(p, 'exit'), new Promise(r => setTimeout(r, 3000))]); if (p.exitCode === null) p.kill('SIGKILL'); }
}
await fs.rm(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}