~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
507 lines · 25.8 KB Raw History
// A look at the workspace as this checkout draws it, in any state, as
// pictures to open: /workspace from web/dist/workspace.html, in front of a
// stand-in for HUD's appview, which answers its XRPC methods from the world
// in look/world.mjs and the tool answers recorded in look/tools.json (their
// trusted views as this checkout has them now, bundled in views/ or the
// operator's, harness/apps.mjs, each answer given its `_meta.ui` by
// `target/debug/hud resolve` with those as HUD_APPS, as the server would
// answer it), so no PDS and no HUD server is needed. As knotless's
// harness/shots/look.mjs.
//
//   node harness/look.mjs <name> [options]    `just look <name> ...`
//
// `name` names the pictures: target/look/<name>-<desktop|phone>-<light|dark>.png.
// Options, the steps among them taken in turn once the page has drawn:
//
//   --set <method>.<field>=<json>   change what a query answers, as
//                                   getWorkspace.open=[] or
//                                   listCanvases.canvases.0.viewer.role="viewer";
//                                   a value that is not JSON is a string,
//                                   @file.json is the file's JSON, null
//                                   takes the field out
//   --events <name>                 what the stream then says, from the
//                                   world's events (badges, arrival)
//   --click <selector>              click it (a step)
//   --hover <selector>              rest the pointer on it (a step)
//   --type <selector>=<text>        type into it, emptied (a step)
//   --press <key>                   press it, as Playwright names keys:
//                                   t, Shift+ArrowLeft, Meta+k (a step)
//   --eval <js>                     print what the expression gives in
//                                   the page, to see why it looks so (a step)
//   --signed-out                    no session: every method but
//                                   searchActors answers 401, so the
//                                   page shows what HUD is, signed out
//   --later <ms>                    the clock moved on so far, and the page
//                                   shown again, as its browser tab coming
//                                   back (a step)
//   --newer                         a list newest first, read the first
//                                   time, says its newest item was not
//                                   drawn, so the next ask finds it newer
//   --desktop --phone --light --dark   only those; desktop light and
//                                   phone dark if none is given
//   --all                           all four
//
// Every answer the stand-in gives is held to its method's lexicon
// (schemas/), --set's too: one that is not is said, and the run fails, so
// the workspace is never judged on an answer the server could not give.
// A page wider than the screen is said. The pictures go to target/look,
// each path printed.

import { execFileSync } from 'node:child_process';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
import { apps, appViews } from './apps.mjs';
import { world as makeWorld } from './look/world.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '..');
const out = join(root, 'target/look');
const say = (line) => console.log(`==> ${line}`);
const fail = (why) => {
	say(why);
	process.exit(2);
};

let name;
const sets = [];
const steps = [];
const sides = new Set();
let events = null;
let signedOut = false;
let newer = false;
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
	const a = argv[i];
	const next = () => argv[++i] ?? fail(`${a} needs a value`);
	if (a === '--set') {
		const v = next();
		const [, method, path, value] = v.match(/^([^.=]+)\.([^=]+)=(.*)$/s) ?? fail(`--set ${v}: not <method>.<field>=<value>`);
		let parsed;
		if (value.startsWith('@')) parsed = JSON.parse(readFileSync(value.slice(1), 'utf8'));
		else {
			try {
				parsed = JSON.parse(value);
			} catch {
				parsed = value;
			}
		}
		sets.push({ method, path: path.split('.'), value: parsed });
	} else if (a === '--events') events = next();
	else if (a === '--signed-out') signedOut = true;
	else if (a === '--click') steps.push({ click: next() });
	else if (a === '--hover') steps.push({ hover: next() });
	else if (a === '--type') {
		const [, sel, text] = next().match(/^([^=]+)=(.*)$/s) ?? fail('--type takes <selector>=<text>');
		steps.push({ sel, text });
	} else if (a === '--press') steps.push({ key: next() });
	else if (a === '--eval') steps.push({ js: next() });
	else if (a === '--later') steps.push({ later: Number(next()) });
	else if (a === '--newer') newer = true;
	else if (a === '--all') for (const s of ['desktop', 'phone', 'light', 'dark']) sides.add(s);
	else if (/^--(desktop|phone|light|dark)$/.test(a)) sides.add(a.slice(2));
	else if (a.startsWith('--')) fail(`${a}: no such option`);
	else name = a;
}
if (!name) fail('what to call the pictures? `node harness/look.mjs <name> [options]`');

const html = join(root, 'web/dist/workspace.html');
if (!existsSync(html)) fail('no web/dist/workspace.html: `just web`');
const recorded = JSON.parse(readFileSync(join(here, 'look/tools.json'), 'utf8'));
const w = makeWorld(recorded);
if (events && !w.events[events]) fail(`--events ${events}: one of ${Object.keys(w.events).join(', ')}`);

// The lexicons, to hold every answer to its method's.
const { Lexicons } = createRequire(import.meta.url)('@atproto/lexicon');
const docs = readdirSync(join(root, 'schemas'))
	.filter((f) => f.endsWith('.json'))
	.map((f) => JSON.parse(readFileSync(join(root, 'schemas', f), 'utf8')))
	.filter((d) => d.defs?.main?.type !== 'space');
const lexicons = new Lexicons(docs);
const invalid = new Set();
const used = new Set();

// The world as the stand-in keeps it, changed by what the page asks; as
// the world has it again for each picture, so what one picture's steps
// changed (a canvas opened from the + menu) is not there for the next.
let views, tiles, open, current, held;
const reset = () => {
	views = new Map(w.canvases.map((c) => [c.view.key, structuredClone(c.view)]));
	tiles = new Map(w.canvases.map((c) => [c.view.key, structuredClone(c.tiles)]));
	open = [...w.open];
	current = w.current;
	held = new Set();
};
let made = 0;

/** `body` with each --set for `method` made. */
function changed(method, body) {
	for (const s of sets.filter((s) => s.method === method)) {
		used.add(s.method);
		let at = body;
		for (const [i, key] of s.path.entries()) {
			if (i === s.path.length - 1 && s.value === null) delete at[key];
			else if (i === s.path.length - 1) at[key] = s.value;
			else at = at[key] ??= {};
		}
	}
	return body;
}

const tab = (key) => ({ canvas: view(key) });
function view(key) {
	const v = views.get(key);
	return { ...v, tileCount: tiles.get(key)?.length ?? 0 };
}
const ordered = (key) => {
	const list = tiles.get(key) ?? [];
	const n = (t) => Number(t.record.order);
	const heads = list.filter((t) => !t.record.stack).sort((a, b) => n(a) - n(b));
	return heads.flatMap((h) => [h, ...list.filter((t) => t.record.stack === h.key).sort((a, b) => n(a) - n(b))]);
};

/** The trusted views as this checkout has them, by the method or collection each draws: the bundled ones (views/) and the operator's (harness/apps.mjs). */
const bundled = new Map(
	[
		...readdirSync(join(root, 'views'))
			.filter((f) => f.endsWith('.json'))
			.map((f) => JSON.parse(readFileSync(join(root, 'views', f), 'utf8'))),
		...appViews().map(([, doc]) => doc)
	].map((doc) => [doc.method ?? doc.collection, doc])
);

const hud = join(root, 'target/debug/hud');
if (!existsSync(hud)) fail('no target/debug/hud: `cargo build -p hud`');

/** A recorded answer, with `_meta.view`, as the server answers it now: its `_meta.ui` built by `hud resolve`, given the operator's apps. */
const resolved = (name, args, answer) => JSON.parse(execFileSync(hud, ['resolve', name, JSON.stringify(args ?? {})], { input: JSON.stringify(answer), encoding: 'utf8', env: { ...process.env, HUD_APPS: apps } }));

/** What a tool answers: as recorded, getProfiles from the profiles recorded; a bundled view in it as this checkout has it, so a change to one shows without recording again. */
function tool(name, args) {
	if (name === 'query' && args?.method === 'app.bsky.actor.getProfiles') {
		const asked = new Set(args.params?.actors ?? []);
		return resolved(name, args, { content: [], structuredContent: { method: args.method, response: { profiles: recorded.profiles.filter((p) => asked.has(p.did) || asked.has(p.handle)) } }, _meta: {} });
	}
	const canonical = (v) =>
		Array.isArray(v)
			? `[${v.map(canonical).join(',')}]`
			: typeof v === 'object' && v !== null
				? `{${Object.keys(v)
						.sort()
						.map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)
						.join(',')}}`
				: JSON.stringify(v);
	const key = `${name} ${canonical(args ?? {})}`;
	const found = recorded.calls[key];
	// An app's page needs no recording: its head and entry points come from the bundled views (no account's part, offline).
	if (!found && name === 'describe_app' && typeof args?.domain === 'string') {
		const domain = args.domain.toLowerCase();
		const named = [...bundled.values()].find((doc) => doc.app && (doc.method ?? doc.collection)?.split('.').slice(0, 2).reverse().join('.') === domain);
		return resolved(name, args, { content: [], structuredContent: { domain, name: named?.app ?? domain, icon: `http://localhost:8790/icon/${domain}` }, _meta: {} });
	}
	if (!found) return { isError: true, content: [{ type: 'text', text: `Not recorded: ${name}.` }] };
	const doc = found._meta?.view?.doc;
	const now = doc && bundled.get(doc.method ?? doc.collection);
	const answer = resolved(name, args, now ? { ...found, _meta: { ...found._meta, view: { ...found._meta.view, doc: now } } } : found);
	// --newer: its newest item held back the first time, as if it came after.
	const latest = answer._meta?.ui?.latest;
	if (newer && latest?.items.length && !held.has(key)) {
		held.add(key);
		latest.items = latest.items.slice(1);
	}
	return answer;
}

const tileView = (canvas, input, extra) => ({
	key: `t${String(++made).padStart(11, '0')}`,
	author: w.me.did,
	record: { $type: 'place.hud.tile', tool: input.tool, arguments: input.arguments ?? {}, title: input.title ?? input.tool, order: '0', by: 'person', createdAt: new Date().toISOString(), ...extra }
});

/** What the bundled views offer the New tile, as getWorkspace answers it. */
const LAUNCHERS = [
	['Repositories', 'dev.knotless.getActorRepos', { actor: 'did:plc:alice' }],
	['Activity', 'dev.knotless.getFeed', { actor: 'did:plc:alice' }],
	['Everyone’s activity', 'dev.knotless.getFeed', {}],
	['Notifications', 'dev.knotless.listNotifications', {}]
].map(([title, method, params]) => ({ app: 'knotless', domain: 'knotless.dev', title, method, service: 'did:web:knotless.dev#knotless_appview', params }));

/** The themes, as getWorkspace lists them (hud_core::theme): light and dark, then the palettes, light ones first, by name. */
const THEMES = readdirSync(join(root, 'themes'))
	.filter((f) => f.endsWith('.json'))
	.map((f) => JSON.parse(readFileSync(join(root, 'themes', f), 'utf8')))
	.sort((a, b) => !!a.palette - !!b.palette || (a.colorScheme === 'dark') - (b.colorScheme === 'dark') || a.name.localeCompare(b.name));
const palette = (key, change = {}) => ({ ...THEMES.find((t) => t.key === key).palette, ...change });
const theirs = (did, handle, rkey, name, colorScheme, palette) => ({ uri: `at://${did}/place.hud.theme/${rkey}`, creator: { did, handle }, name, colorScheme, palette });
/** People's themes, as listThemes answers them: this person's own, then others'. */
let mine = [theirs(w.me.did, w.me.handle, '3lmatcha', 'Matcha', 'light', palette('frost', { accent: '#2f6b3a', primary: '#2f6b3a', accentSoft: '#e1efe1' }))];
const others = [
	theirs('did:plc:dan', 'danabra.mov', '3lsand', 'Sand', 'light', palette('paper', { canvas: '#e6dcc6', accent: '#8a4b14', primary: '#8a4b14' })),
	theirs('did:plc:paul', 'pfrazee.com', '3lnight', 'Night shift', 'dark', palette('blueprint', { canvas: '#060b18', background: '#0c1630' })),
	theirs('did:plc:bryan', 'bnewbold.net', '3lterm', 'Terminal', 'dark', palette('phosphor', { accent: '#7fffa0' }))
];
/** The theme chosen here; none, the system's. */
let theme;
let rkeys = 0;

/** Each method the page asks, as the appview answers it here. */
const methods = {
	getWorkspace: () => ({ me: w.me, open: open.map(tab), current, launchers: LAUNCHERS, themes: THEMES, ...(theme ? { theme } : {}) }),
	// Who the sign-in field offers, from the profiles recorded, as HUD's typeahead answers.
	searchActors: ({ q, limit }) => {
		const text = q.trim().replace(/^@/, '').toLowerCase();
		const found = text.length < 2 ? [] : recorded.profiles.filter((p) => p.handle.startsWith(text) || p.displayName?.toLowerCase().startsWith(text));
		return { actors: found.slice(0, Number(limit ?? 6)).map(({ did, handle, displayName, avatar }) => ({ did, handle, ...(displayName ? { displayName } : {}), ...(avatar ? { avatar } : {}) })) };
	},
	setTheme: ({ key, uri }) => ((theme = key ? THEMES.find((t) => t.key === key) : uri ? [...mine, ...others].find((t) => t.uri === uri) : undefined), theme ? { theme } : {}),
	listThemes: ({ actor }) => ({ themes: actor === w.me.did ? mine : actor ? others.filter((t) => t.creator.handle === actor || t.creator.did === actor) : [...others, ...mine] }),
	createTheme: ({ name, colorScheme, palette }) => {
		const theme = theirs(w.me.did, w.me.handle, `3lnew${++rkeys}`, name, colorScheme, palette);
		mine = [theme, ...mine];
		return { theme };
	},
	// What deleting this person's data would delete, from the world as it is now: the canvases they own, each with the others in it; the others' they are in, and invitations; their themes.
	getAccountData: () => {
		const all = [...views.values()];
		return {
			did: w.me.did,
			canvases: all.filter((v) => v.owner === w.me.did).map((v) => ({ canvas: v.key, name: v.record.name, members: v.members.filter((m) => m.did !== w.me.did).length })),
			shared: all.filter((v) => v.owner !== w.me.did && !v.viewer?.invitedBy).length,
			invitations: all.filter((v) => v.owner !== w.me.did && v.viewer?.invitedBy).length,
			themes: mine.length,
			chosenTheme: !!theme
		};
	},
	deleteTheme: ({ uri }) => ((mine = mine.filter((t) => t.uri !== uri)), {}),
	// The stand-in finds no text too faint; --set checkTheme.problems=[…] says otherwise.
	checkTheme: () => ({ problems: [] }),
	listCanvases: () => ({ canvases: [...views.keys()].map(view) }),
	getCanvas: (q) => (views.has(q.canvas) ? { canvas: view(q.canvas), tiles: ordered(q.canvas) } : null),
	openCanvas: ({ canvas }) => {
		const v = views.get(canvas);
		if (v.viewer?.invitedBy) {
			delete v.viewer.invitedBy;
			for (const m of v.members) if (m.did === w.me.did) delete m.pending;
		}
		if (!open.includes(canvas)) open.push(canvas);
		current = canvas;
		return { canvas: view(canvas), open: open.map(tab), current };
	},
	closeCanvas: ({ canvas }) => {
		open = open.filter((k) => k !== canvas);
		if (current === canvas) current = open[0];
		return { open: open.map(tab), current };
	},
	setTabOrder: ({ tabs }) => ((open = tabs.map((t) => t.canvas)), { open: open.map(tab), current }),
	createCanvas: ({ name }) => {
		const key = `c${String(++made).padStart(11, '9')}`;
		views.set(key, { key, owner: w.me.did, record: { $type: 'place.hud.canvas', name, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }, members: [{ did: w.me.did, handle: w.me.handle, role: 'owner' }], storage: { kind: 'file' }, viewer: { role: 'owner' } });
		tiles.set(key, []);
		open.push(key);
		current = key;
		return { canvas: view(key) };
	},
	updateCanvas: ({ canvas, name }) => ((views.get(canvas).record.name = name), { canvas: view(canvas) }),
	deleteCanvas: ({ canvas }) => (views.delete(canvas), (open = open.filter((k) => k !== canvas)), {}),
	declineInvite: ({ canvas }) => (views.delete(canvas), {}),
	leaveCanvas: ({ canvas }) => (views.delete(canvas), (open = open.filter((k) => k !== canvas)), {}),
	inviteMember: ({ canvas, actor, role }) => (views.get(canvas).members.push({ did: `did:plc:${actor.replace(/[^a-z0-9]/g, '').padEnd(24, 'x').slice(0, 24)}`, handle: actor, role, pending: true, invitedBy: w.me.did }), { canvas: view(canvas) }),
	setMemberRole: ({ canvas, did, role }) => ((views.get(canvas).members.find((m) => m.did === did).role = role), { canvas: view(canvas) }),
	removeMember: ({ canvas, did }) => ((views.get(canvas).members = views.get(canvas).members.filter((m) => m.did !== did)), { canvas: view(canvas) }),
	addTile: (input) => {
		const list = ordered(input.canvas).filter((t) => !t.record.stack);
		const at = input.after ?? input.from;
		const i = at ? list.findIndex((t) => t.key === at) : list.length - 1;
		const before = Number(list[i]?.record.order ?? 0);
		const after = list[i + 1] ? Number(list[i + 1].record.order) : before + 2;
		const tile = tileView(input.canvas, input, { order: String((before + after) / 2), ...(input.from ? { from: input.from } : {}), ...(input.width ? { width: input.width } : {}) });
		tiles.get(input.canvas).push(tile);
		return { tile };
	},
	removeTile: ({ canvas, tile }) => (tiles.set(canvas, tiles.get(canvas).filter((t) => t.key !== tile)), {}),
	placeTile: ({ canvas, tile, before, after }) => {
		const list = ordered(canvas).filter((t) => !t.record.stack && t.key !== tile);
		const i = list.findIndex((t) => t.key === (before ?? after));
		const [lo, hi] = before ? [list[i - 1], list[i]] : [list[i], list[i + 1]];
		const t = tiles.get(canvas).find((x) => x.key === tile);
		t.record.order = String(((lo ? Number(lo.record.order) : Number(hi.record.order) - 2) + (hi ? Number(hi.record.order) : Number(lo.record.order) + 2)) / 2);
		return { tile: t };
	},
	setTileWidth: ({ canvas, tile, width }) => {
		const t = tiles.get(canvas).find((x) => x.key === tile);
		t.record.width = width;
		return { tile: t };
	},
	stackTile: ({ canvas, tile, into }) => {
		const t = tiles.get(canvas).find((x) => x.key === tile);
		t.record.stack = into;
		t.record.order = String(Math.max(...tiles.get(canvas).filter((x) => x.record.stack === into).map((x) => Number(x.record.order)), 0) + 1);
		return { tile: t };
	},
	unstackTile: ({ canvas, tile }) => {
		const t = tiles.get(canvas).find((x) => x.key === tile);
		const head = tiles.get(canvas).find((x) => x.key === t.record.stack);
		delete t.record.stack;
		t.record.order = String(Number(head.record.order) + 0.5);
		return { tile: t };
	},
	updateTile: ({ canvas, tile, title, tool: name, arguments: args }) => {
		const t = tiles.get(canvas).find((x) => x.key === tile);
		if (title !== undefined) t.record.title = title;
		if (name !== undefined) t.record = { ...t.record, tool: name, arguments: args ?? {} };
		return { tile: t };
	},
	callTool: ({ name, arguments: args }) => ({ result: tool(name, args) })
};

const icons = join(here, 'look/icons');
const streams = new Set();

/** A minute of silence as a WAV (8 kHz, 8-bit, mono). */
const silence = (() => {
	const n = 8000 * 60;
	const wav = Buffer.alloc(44 + n, 128);
	wav.write('RIFF', 0);
	wav.writeUInt32LE(36 + n, 4);
	wav.write('WAVEfmt ', 8);
	wav.writeUInt32LE(16, 16);
	wav.writeUInt16LE(1, 20);
	wav.writeUInt16LE(1, 22);
	wav.writeUInt32LE(8000, 24);
	wav.writeUInt32LE(8000, 28);
	wav.writeUInt16LE(1, 32);
	wav.writeUInt16LE(8, 34);
	wav.write('data', 36);
	wav.writeUInt32LE(n, 40);
	return wav;
})();

const server = createServer(async (req, res) => {
	const url = new URL(req.url, 'http://look');
	if (url.pathname === '/workspace') return res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(readFileSync(html));
	// HUD's icon, the sign-in dialog's logos and the landing's picture, as hud-server serves them.
	if (url.pathname === '/favicon.svg') return res.writeHead(200, { 'content-type': 'image/svg+xml' }).end(readFileSync(join(root, 'web/public/favicon.svg')));
	const atmo = url.pathname.match(/^\/workspace\/(atmo|hero)\/([a-z-]+\.(jpg|png|webp))$/);
	if (atmo) {
		const file = join(root, 'crates/hud-server', atmo[1], atmo[2]);
		return existsSync(file) ? res.writeHead(200, { 'content-type': `image/${atmo[3] === 'jpg' ? 'jpeg' : atmo[3]}` }).end(readFileSync(file)) : res.writeHead(404).end();
	}
	// A blob, as the server that recorded the answers proxied it: Bluesky's CDN has an image of every account's. One
	// a player asks for (media asks by a range) is a minute of silence, so a track plays.
	const blob = url.pathname.match(/^\/blob\/(did:[^/]+)\/([a-z0-9]+)$/);
	if (blob && req.headers.range) return res.writeHead(200, { 'content-type': 'audio/wav', 'content-length': silence.length }).end(silence);
	if (blob) return res.writeHead(302, { location: `https://cdn.bsky.app/img/feed_fullsize/plain/${blob[1]}/${blob[2]}@jpeg` }).end();
	const icon = url.pathname.match(/^\/icon\/([a-z0-9.-]+)$/);
	if (icon) {
		const file = join(icons, `${icon[1]}.png`);
		return existsSync(file) ? res.writeHead(200, { 'content-type': 'image/png' }).end(readFileSync(file)) : res.writeHead(404).end();
	}
	const nsid = url.pathname.match(/^\/xrpc\/place\.hud\.(\w+)$/)?.[1];
	if (nsid === 'getWorkspaceEvents') {
		res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
		for (const e of w.presence) res.write(`data: ${JSON.stringify(e)}\n\n`);
		streams.add(res);
		req.on('close', () => streams.delete(res));
		return;
	}
	const method = nsid && methods[nsid];
	if (!method) return res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'MethodNotImplemented', message: `No ${url.pathname} here.` }));
	if (signedOut && nsid !== 'searchActors') return res.writeHead(401, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'AuthRequired', message: 'Sign in.' }));
	let input = Object.fromEntries(url.searchParams);
	if (req.method === 'POST') {
		let body = '';
		for await (const chunk of req) body += chunk;
		input = JSON.parse(body || '{}');
	}
	const answer = method(input);
	if (!answer) return res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'NotFound', message: 'No such canvas.' }));
	// A tile's icon is an absolute URL, this stand-in's; and so is a recorded blob's, and an app's icon in a tree.
	const body = changed(
		nsid,
		JSON.parse(
			JSON.stringify(answer)
				.replaceAll('"icon":"/icon/', `"icon":"${base}/icon/`)
				.replace(/https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?\/(blob|icon)\//g, (_, _host, _port, path) => `${base}/${path}/`)
		)
	);
	const id = `place.hud.${nsid}`;
	try {
		lexicons.assertValidXrpcOutput(id, body);
	} catch (e) {
		if (!invalid.has(id)) say(`${id}: the answer is not as its lexicon says, so no server could give it: ${e.message}`);
		invalid.add(id);
	}
	res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(body));
});
await new Promise((done) => server.listen(0, '127.0.0.1', done));
const base = `http://127.0.0.1:${server.address().port}`;

const projects = (() => {
	const widths = ['desktop', 'phone'].filter((s) => sides.has(s));
	const schemes = ['light', 'dark'].filter((s) => sides.has(s));
	if (!widths.length && !schemes.length) return ['desktop-light', 'phone-dark'];
	return (widths.length ? widths : ['desktop', 'phone']).flatMap((wd) => (schemes.length ? schemes : ['light', 'dark']).map((s) => `${wd}-${s}`));
})();
const devices = {
	desktop: { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 },
	phone: { viewport: { width: 390, height: 844 }, deviceScaleFactor: 3, isMobile: true, hasTouch: true }
};

mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
let shot = 0;
try {
	for (const project of projects) {
		reset();
		const [device, scheme] = project.split('-');
		const context = await browser.newContext({ ...devices[device], colorScheme: scheme, locale: 'en-US', timezoneId: 'America/Los_Angeles', reducedMotion: 'reduce' });
		const page = await context.newPage();
		let now = new Date('2026-11-14T19:00:00.000Z').getTime();
		await page.clock.setFixedTime(now);
		await page.goto(`${base}/workspace`, { waitUntil: 'load' });
		await page.locator(signedOut ? '.signed-out' : '.strip.shown').waitFor();
		const settle = async () => {
			await page.waitForTimeout(500);
			await page.waitForFunction(() => !document.querySelector('.strip.shown [aria-busy="true"]'), null, { timeout: 5000 }).catch(() => {});
			await page.waitForTimeout(300);
		};
		await settle();
		if (events) {
			for (const res of streams) for (const e of w.events[events]) res.write(`data: ${JSON.stringify(e)}\n\n`);
			await settle();
		}
		for (const s of steps) {
			if (s.js) console.log(JSON.stringify(await page.evaluate(s.js)));
			else if (s.later) {
				now += s.later;
				await page.clock.setFixedTime(now);
				await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')));
			} else if (s.key) await page.keyboard.press(s.key);
			else if (s.sel) {
				const it = page.locator(s.sel).first();
				await it.fill('');
				await it.pressSequentially(s.text);
			} else if (s.hover) await page.locator(s.hover).first().hover();
			else await page.locator(s.click).first().click();
			await settle();
		}
		const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
		if (wide > 0) say(`${name}-${project}: ${wide}px wider than the screen`);
		const file = join(out, `${name}-${project}.png`);
		await page.screenshot({ path: file, animations: 'disabled', caret: 'hide' });
		console.log(file);
		shot++;
		await context.close();
	}
} finally {
	await browser.close();
	for (const res of streams) res.end();
	server.close();
}
const unused = [...new Set(sets.map((s) => s.method))].filter((m) => !used.has(m));
for (const m of unused) say(`--set ${m}: the page never asked it, so it changed nothing`);
say(`${shot} pictures in ${out}`);
process.exit(unused.length || invalid.size ? 1 : 0);