Skip to content

Visual Studio Code, rebuilt in Rust

Rust
27.7 KB
Raw Blame
#!/usr/bin/env bun
// End-to-end check of the in-app updater (port/notes.md "Update feed") on the Studio, after a release build and
// port/tools/build-exthost. Packages N (1.147.0), N+1 (1.148.0), a pre-release P (1.149.0-insider) and a foreign-signed
// N+1 with package-app, serves them with port/tools/update-feed laid out like GitHub releases, and runs N from a
// folder of its own:
//   latest: N checks, downloads N+1, the Manage menu's Show Update Release Notes opens its notes, Restart to Update relaunches N+1 from the same path and arguments, settings
//     kept, then the release notes editor with the release's body.
//   metered: N on a metered connection skips its automatic check until the connection is not metered, then the title
//     bar's Update entry restarts to N+1.
//   pre-release: N on the pre-release channel gets P and installs it on Quit; P switched to latest stays (no downgrade).
//   failures: wrong sha256, ad-hoc signed, foreign-signed, a download cut midway, then a swap that fails after the
//     installed app moved aside (the staged bundle made immutable): N is put back and relaunched.
//   read-only: N on a mounted disk image: Check for Updates shows Squirrel's read-only message in the title bar tooltip.
//   port/tools/studio 'IDENTITY="Developer ID Application: ..." FOREIGN_IDENTITY="Apple Development: ..." ONLY=package port/tools/update-check'
//   then the GUI part in a lane: port/tools/studio --lane 'SCRATCH=/tmp/update-check SKIP_PACKAGE=1 IDENTITY="Developer ID Application: ..." FOREIGN_IDENTITY=- timeout 600 port/tools/update-check'
//   env ONLY="latest metered pre-release failures read-only" picks scenarios; SKIP_PACKAGE=1 reuses the packages of the last run
//   (packaging takes about 10 minutes before the GUI lock; the GUI part about 6, every wait ends within 90 s, a download with its verification 150 s).
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { basename, join, resolve } from 'node:path';

const identity = process.env.IDENTITY;
const foreignIdentity = process.env.FOREIGN_IDENTITY;
if (!identity?.startsWith('Developer ID Application') || !foreignIdentity) {
	console.log('update-check: needs IDENTITY (a Developer ID Application) and FOREIGN_IDENTITY (another signing identity)');
	process.exit(2);
}
// Name it in the command (SCRATCH=/tmp/update-check) so a VM lane copies the packages in.
const scratch = process.env.SCRATCH ?? '/tmp/update-check';
const packages = join(scratch, 'packages');
const feed = join(scratch, 'feed');
const port = 47321;
const updateUrl = `http://127.0.0.1:${port}`;
// The feeds of the arch package-app builds for by default, this host's (update.rs reads the one it was built for).
const platform = `darwin-${process.arch === 'arm64' ? 'arm64' : 'x64'}`;
const shipit = join(process.env.HOME!, 'Library/Caches/com.rokartur.vsrustium.ShipIt');
const only = process.env.ONLY?.split(' ');
const results: string[] = [];
const failures: string[] = [];
// The app of the running scenario, for the diagnosis of a failed check.
let current: { pid: number; log: string } | undefined;

if (process.env.SKIP_PACKAGE !== '1') {
	rmSync(scratch, { recursive: true, force: true });
	await pack('N', { VERSION: '1.147.0', IDENTITY: identity });
	await pack('N1', { VERSION: '1.148.0', IDENTITY: identity });
	await pack('P', { VERSION: '1.149.0', IDENTITY: identity, PRERELEASE: '1' });
	await pack('foreign', { VERSION: '1.148.0', IDENTITY: foreignIdentity, TAG: 'foreign' });
	// N+1 re-signed ad hoc, as an unsigned build would be.
	cpSync(join(packages, 'N1/VSRustium.app'), join(packages, 'adhoc/VSRustium.app'), { recursive: true, verbatimSymlinks: true });
	await Bun.$`codesign --force --deep --sign - ${join(packages, 'adhoc/VSRustium.app')}`;
	await Bun.$`ditto -c -k --keepParent ${join(packages, 'adhoc/VSRustium.app')} ${join(packages, `adhoc/VSRustium-1.148.0-${platform}.zip`)}`;
}
rmSync(feed, { recursive: true, force: true });
for (const [name, tag] of [['N1', 'v1.148.0'], ['P', 'v1.149.0-insider'], ['foreign', 'foreign'], ['adhoc', 'adhoc']]) {
	mkdirSync(join(feed, 'download', tag), { recursive: true });
	cpSync(zipOf(name), join(feed, 'download', tag, basename(zipOf(name))));
}
const entry = (name: string, file = `${platform}.json`) => JSON.parse(readFileSync(join(packages, name, file), 'utf8'));
const n1 = entry('N1');
const server = Bun.spawn([resolve('port/tools/update-feed'), feed, String(port)], { stdout: Bun.file(join(scratch, 'feed.log')), stderr: 'inherit' });
await Bun.sleep(500);

await takeGuiLock();
// The helper's log outlives runs and names the same paths each run: start it empty.
rmSync(join(shipit, 'ShipIt_stderr.log'), { force: true });
try {
	for (const [name, scenario] of [['latest', latest], ['metered', metered], ['pre-release', preRelease], ['failures', failureCases], ['read-only', readOnly]] as const) {
		if (only && !only.includes(name)) {
			continue;
		}
		// A failed step ends its scenario, so no later wait runs on a state that cannot come.
		await scenario().catch(error => console.log(`${name}: stopped at ${error.message}`));
		await Bun.$`pkill -f ${scratch}/run`.nothrow().quiet();
	}
} finally {
	server.kill();
	await Bun.$`pkill -f ${scratch}/run`.nothrow().quiet();
}
console.log(failures.length ? `update-check: FAILED ${failures.join('; ')}` : 'update-check: ok');
process.exit(failures.length ? 1 : 0);

async function latest() {
	serveFeeds(n1, n1);
	// The GitHub API's release, at the path release_notes.rs asks for under product.json's releaseNotesUrl.
	mkdirSync(join(feed, 'notes/tags'), { recursive: true });
	writeFileSync(join(feed, 'notes/tags/v1.148.0'), JSON.stringify({ name: 'v1.148.0', body: 'Notes of the update-check release.' }));
	const run = install('latest', { 'update.mode': 'default', 'editor.fontSize': 17 });
	const first = launch(run);
	// The download, sha256, extraction and codesign --verify --deep of an 800 MB bundle: up to 2 minutes on a busy host.
	check('latest: N downloads and verifies N+1', await waitFor(run.log, 'update#setState ready', 150_000));
	// update.ts: a stable build's Manage menu has Show Update Release Notes above Restart to Update, the menu's last item.
	check('latest: N is a stable build', JSON.parse(readFileSync(join(run.app, 'Contents/Resources/app/product.json'), 'utf8')).quality === 'stable');
	// The Manage button's title carries the update badge's description.
	const manage = await buttonOf(first.pid, 'Manage[^"]*');
	check('latest: the Manage button is in the accessibility tree', manage !== undefined);
	await cua('click', { pid: first.pid, window_id: manage!.window_id, element_token: manage!.token });
	await Bun.sleep(1000);
	await cua('get_window_state', { pid: first.pid, window_id: manage!.window_id, include_accessibility_tree: false, max_image_dimension: 2048, screenshot_out_file: join(scratch, 'manage-menu.png') });
	const item = await buttonOf(first.pid, 'Show Update Release Notes', 'AXMenuItem');
	check('latest: the Manage menu has Show Update Release Notes', item !== undefined);
	await cua('click', { pid: first.pid, window_id: item!.window_id, element_token: item!.token });
	check('latest: Show Update Release Notes fetches the notes of N+1', await waitUntil(() => count(join(scratch, 'feed.log'), 'GET /notes/tags/v1.148.0') > 0, 30_000));
	let menuNotes = false;
	for (const start = Date.now(); !menuNotes && Date.now() - start < 20_000; await Bun.sleep(1000)) {
		menuNotes = (await windowTree(first.pid)).includes('Release Notes: 1.148.0');
	}
	check('latest: Show Update Release Notes opens the release notes editor', menuNotes);
	await screenshot(first.pid, 'latest-update-release-notes');
	// Closed, so the notes after the update are ProductContribution's, not a restored editor's.
	await key(first.pid, 'hotkey', { keys: ['cmd', 'w'] });
	const fetchedBefore = count(join(scratch, 'feed.log'), 'GET /notes/tags/v1.148.0');
	const settings = readFileSync(join(run.data, 'User/settings.json'), 'utf8');
	await palette(first.pid, 'Restart to Update');
	check('latest: N quit', await waitUntil(() => first.exitCode !== null || first.signalCode !== null, 30_000));
	check('latest: the helper installed N+1', await waitFor(join(shipit, 'ShipIt_stderr.log'), `installed ${shipit}/update/extracted/VSRustium.app at ${run.app}`, 60_000));
	check('latest: N+1 relaunched', await waitFor(join(shipit, 'ShipIt_stderr.log'), `relaunched ${run.app}/Contents/MacOS/vsrustium`, 10_000));
	check('latest: N+1 runs from the same path', version(run.app) === '1.148.0', version(run.app));
	check('latest: N+1 signature valid', (await Bun.$`codesign --verify --deep --strict ${run.app}`.nothrow().quiet()).exitCode === 0);
	check('latest: the old copy is deleted', !existsSync(join(run.app, '../.VSRustium.app.old')));
	const relaunched = await processesOf(run.data);
	check('latest: N+1 runs with the same arguments', relaunched.some(command => command.startsWith(`${run.app}/Contents/MacOS/vsrustium --user-data-dir ${run.data}`)), relaunched.join(' | '));
	check('latest: settings kept', readFileSync(join(run.data, 'User/settings.json'), 'utf8') === settings);
	await Bun.sleep(2000);
	const pid = Number((await Bun.$`pgrep -f ${`${run.app}/Contents/MacOS/vsrustium --user-data-dir ${run.data}`}`.text()).trim().split('\n')[0]);
	current = { pid, log: join(shipit, 'ShipIt_stderr.log') };
	await windowOf(pid);
	check('latest: the release notes fetched', await waitUntil(() => count(join(scratch, 'feed.log'), 'GET /notes/tags/v1.148.0') > fetchedBefore, 30_000));
	let shown = false;
	for (const start = Date.now(); !shown && Date.now() - start < 20_000; await Bun.sleep(1000)) {
		shown = (await windowTree(pid)).includes('Release Notes: 1.148.0');
	}
	check('latest: the release notes editor after the update', shown);
	await screenshot(pid, 'latest-after');
	await Bun.$`pkill -f ${run.data}`.nothrow().quiet();
}

async function metered() {
	serveFeeds(n1, n1);
	const settings = { 'update.mode': 'default', 'network.meteredConnection': 'on' };
	const run = install('metered', settings);
	const child = launch(run);
	check('metered: the automatic check is skipped', await waitFor(run.log, 'skipping automatic check because connection is metered', 60_000));
	await Bun.sleep(5000);
	check('metered: nothing checked', count(run.log, 'update#setState checking for updates') === 0);
	writeFileSync(join(run.data, 'User/settings.json'), JSON.stringify({ 'workbench.startupEditor': 'none', ...settings, 'network.meteredConnection': 'off' }));
	check('metered: not metered resumes the check and download', await waitFor(run.log, 'update#setState ready', 150_000));
	await windowOf(child.pid);
	const entry = await buttonOf(child.pid, 'Update');
	check('title bar: the Update entry shows', entry !== undefined);
	await screenshot(child.pid, 'title-bar-ready');
	await cua('click', { pid: child.pid, window_id: entry!.window_id, element_token: entry!.token });
	check('title bar: the entry restarts to update', await waitFor(join(shipit, 'ShipIt_stderr.log'), `installed ${shipit}/update/extracted/VSRustium.app at ${run.app}`, 60_000));
	check('title bar: N+1 installed', await waitUntil(() => version(run.app) === '1.148.0', 10_000), version(run.app));
	await Bun.sleep(2000);
	await Bun.$`pkill -f ${run.data}`.nothrow().quiet();
}

async function preRelease() {
	const p = entry('P', `${platform}-prerelease.json`);
	check('pre-release: package-app wrote no latest entry for a pre-release', !existsSync(join(packages, `P/${platform}.json`)));
	// The latest feed offers N itself (no update); the pre-release feed offers P.
	serveFeeds(entry('N'), p);
	const run = install('pre-release', { 'update.mode': 'default', 'update.releaseChannel': 'pre-release' });
	const child = launch(run);
	check('pre-release: N downloads P', await waitFor(run.log, 'update#setState ready', 150_000));
	check('pre-release: from the pre-release feed', readFileSync(join(scratch, 'feed.log'), 'utf8').includes(`GET /download/pre-release/${platform}-prerelease.json`));
	await quit(child.pid);
	check('pre-release: N quit', await waitUntil(() => child.exitCode !== null || child.signalCode !== null, 30_000));
	check('pre-release: P installed on quit', await waitUntil(() => version(run.app) === '1.149.0-insider', 60_000), version(run.app));
	check('pre-release: P is an Insiders build', JSON.parse(readFileSync(join(run.app, 'Contents/Resources/app/product.json'), 'utf8')).quality === 'insider');
	check('pre-release: no relaunch on quit', (await processesOf(run.data)).length === 0);
	// P switched to latest, where N+1 (1.148.0, built later) is the newest stable: no downgrade.
	serveFeeds(n1, p);
	writeFileSync(join(run.data, 'User/settings.json'), JSON.stringify({ 'workbench.startupEditor': 'none', 'update.mode': 'default', 'update.releaseChannel': 'latest' }));
	const log = join(run.root, 'p.log');
	const second = launch({ ...run, log });
	check('latest after pre-release: checked', await waitFor(log, 'update#setState checking for updates', 60_000));
	await Bun.sleep(3000);
	const text = readFileSync(log, 'utf8');
	check('latest after pre-release: no downgrade', text.includes('update#setState idle') && !text.includes('update#setState downloading'), text.split('\n').filter(line => line.includes('[update]')).join(' / '));
	second.kill('SIGKILL');
	// P as VS Code Insiders, with port/fixtures/extensions/insider-tests. First without tests: it installs the pre-release
	// of rust-analyzer from the gallery and the publisher trust dialog gets its answer here, as extension tests refuse it.
	const tests = join(process.cwd(), 'port/fixtures/extensions/insider-tests');
	const insiderArgs = [join(run.app, 'Contents/MacOS/vsrustium'), '--user-data-dir', join(run.root, 'insider-data'), '--skip-welcome', `--extensionDevelopmentPath=${tests}`];
	const done = join(run.root, 'insider-gallery-done');
	const galleryLog = join(run.root, 'insider-gallery.log');
	const gallery = Bun.spawn(insiderArgs, { env: { ...process.env, INSIDER_GALLERY_DONE: done }, stdout: Bun.file(galleryLog), stderr: Bun.file(galleryLog) });
	let trust: Awaited<ReturnType<typeof buttonOf>>;
	for (const start = Date.now(); !trust && Date.now() - start < 60_000; await Bun.sleep(1000)) {
		trust = await buttonOf(gallery.pid, 'Trust Publisher & Install');
	}
	check('insider: a gallery install asks to trust the publisher', trust !== undefined, existsSync(done) ? readFileSync(done, 'utf8') : readFileSync(galleryLog, 'utf8').slice(-1500));
	await screenshot(gallery.pid, 'insider-trust-publisher');
	await cua('click', { pid: gallery.pid, window_id: trust!.window_id, element_token: trust!.token });
	check('insider: the pre-release of rust-analyzer installed', await waitUntil(() => existsSync(done), 120_000) && readFileSync(done, 'utf8') === 'installed', existsSync(done) ? readFileSync(done, 'utf8') : 'no answer');
	gallery.kill('SIGKILL');
	await gallery.exited;
	// Then the tests, with an Open VSX VSIX whose engines.vscode is an `-insider` range.
	const vsix = join(run.root, 'ms-vscode.hexeditor-1.11.1.vsix');
	await Bun.write(vsix, await fetch('https://open-vsx.org/api/ms-vscode/hexeditor/1.11.1/file/ms-vscode.hexeditor-1.11.1.vsix'));
	const insider = Bun.spawnSync([...insiderArgs, `--extensionTestsPath=${tests}/tests`], { timeout: 180_000, env: { ...process.env, INSIDER_VSIX: vsix } });
	const results = insider.stdout.toString() + insider.stderr.toString();
	for (const line of results.split('\n').filter(line => /^(ok|FAILED) /.test(line))) {
		check(`insider: ${line.replace(/^(ok|FAILED) /, '')}`, line.startsWith('ok '), line);
	}
	check('insider: tests ran', insider.exitCode === 0 && results.includes('ok the host sees'), results.slice(-2000));
}

async function failureCases() {
	serveFeeds({ ...n1, sha256hash: '0'.repeat(64) }, n1);
	const run = install('failures', { 'update.mode': 'default' });
	const child = launch(run);
	check('wrong sha256: refused', await waitFor(run.log, "is not the feed's", 90_000));
	const attempts: [string, object, string][] = [
		['ad-hoc signed: refused', { ...n1, url: `${updateUrl}/download/adhoc/${basename(zipOf('adhoc'))}`, sha256hash: sha256(zipOf('adhoc')) }, 'does not satisfy'],
		['foreign-signed: refused', entry('foreign'), 'does not satisfy'],
		['download cut midway: refused', { ...n1, url: `${n1.url}?cut` }, 'Could not download the update'],
	];
	for (const [name, attempt, error] of attempts) {
		serveFeeds(attempt, n1);
		const before = count(run.log, error);
		await palette(child.pid, 'Check for Updates');
		// A download with its verification: 150 s, as for latest.
		check(name, await waitUntil(() => count(run.log, error) > before, 150_000));
	}
	check('failures: N unchanged', version(run.app) === '1.147.0' && !existsSync(join(shipit, 'update/extracted')));
	serveFeeds(n1, n1);
	await palette(child.pid, 'Check for Updates');
	check('swap failure: N+1 ready', await waitFor(run.log, 'update#setState ready', 150_000));
	const staged = join(shipit, 'update/extracted/VSRustium.app');
	await Bun.$`chflags uchg ${staged}`;
	try {
		await palette(child.pid, 'Restart to Update');
		check('swap failure: rolled back', await waitFor(join(shipit, 'ShipIt_stderr.log'), 'the installed app was put back', 60_000));
		check('swap failure: N relaunched', await waitFor(join(shipit, 'ShipIt_stderr.log'), `relaunched ${run.app}/Contents/MacOS/vsrustium`, 10_000));
	} finally {
		await Bun.$`chflags nouchg ${staged}`.nothrow();
	}
	check('swap failure: N still installed and valid', version(run.app) === '1.147.0' && (await Bun.$`codesign --verify --deep --strict ${run.app}`.nothrow().quiet()).exitCode === 0);
	await Bun.sleep(5000);
	check('swap failure: N runs', (await processesOf(run.data)).length > 0);
	await Bun.$`pkill -f ${run.data}`.nothrow().quiet();
}

async function readOnly() {
	serveFeeds(n1, n1);
	const image = join(scratch, 'readonly.dmg');
	rmSync(image, { force: true });
	await Bun.$`hdiutil create -quiet -srcfolder ${join(packages, 'N/VSRustium.app')} -volname VSRustiumReadOnly -format UDZO ${image}`;
	const mount = join(scratch, 'run-readonly');
	mkdirSync(mount, { recursive: true });
	await Bun.$`hdiutil attach -quiet -nobrowse -readonly -mountpoint ${join(mount, 'volume')} ${image}`;
	try {
		const run = { root: mount, app: join(mount, 'volume/VSRustium.app'), data: userData(mount, { 'update.mode': 'manual' }), log: join(mount, 'app.log') };
		const child = launch(run);
		// update.ts registers Check for Updates for the idle state; under load the window takes longer than any fixed sleep.
		check('read-only: idle', await waitFor(run.log, 'update#setState idle', 90_000));
		await palette(child.pid, 'Check for Updates');
		check('read-only: refused', await waitFor(run.log, 'Cannot update while running on a read-only volume', 30_000));
		await Bun.sleep(1000);
		const tree = await windowTree(child.pid);
		// The title bar tooltip shows the error as updateTooltip.ts does, without updateUtils.ts preprocessError.
		check('read-only: message shown', tree.includes('Cannot update while running on a read-only volume.') && tree.includes('Squirrel/Squirrel.Mac/issues/182'));
		await screenshot(child.pid, 'read-only');
		child.kill('SIGKILL');
		await Bun.sleep(1000);
	} finally {
		await Bun.$`hdiutil detach -quiet -force ${join(mount, 'volume')}`.nothrow();
	}
}

async function pack(name: string, env: Record<string, string>) {
	const out = join(packages, name, 'VSRustium.app');
	const product = JSON.stringify({ updateUrl, releaseNotesUrl: `${updateUrl}/notes` });
	const result = await Bun.$`port/tools/package-app`.env({ ...process.env, ...env, OUT: out, PRODUCT: product }).nothrow();
	// package-app exits 3 where Gatekeeper assessments are disabled; the zip is written once codesign verified.
	if (!readdirSync(join(packages, name)).some(file => file.endsWith('.zip'))) {
		throw new Error(`package-app ${name} exited ${result.exitCode} without an update zip`);
	}
}

function serveFeeds(latestEntry: object, preReleaseEntry: object) {
	mkdirSync(join(feed, 'latest/download'), { recursive: true });
	mkdirSync(join(feed, 'download/pre-release'), { recursive: true });
	writeFileSync(join(feed, `latest/download/${platform}.json`), JSON.stringify(latestEntry));
	writeFileSync(join(feed, `download/pre-release/${platform}-prerelease.json`), JSON.stringify(preReleaseEntry));
}

// package-app names the zip by version and platform: the one zip in the package's folder.
function zipOf(name: string) {
	return join(packages, name, readdirSync(join(packages, name)).find(file => file.endsWith('.zip'))!);
}

function install(name: string, settings: object) {
	const root = join(scratch, `run-${name}`);
	rmSync(root, { recursive: true, force: true });
	mkdirSync(join(root, 'Applications'), { recursive: true });
	const app = join(root, 'Applications/VSRustium.app');
	Bun.spawnSync(['ditto', join(packages, 'N/VSRustium.app'), app]);
	return { root, app, data: userData(root, settings), log: join(root, 'app.log') };
}

function userData(root: string, settings: object) {
	const data = join(root, 'data');
	mkdirSync(join(data, 'User'), { recursive: true });
	writeFileSync(join(data, 'User/settings.json'), JSON.stringify({ 'workbench.startupEditor': 'none', ...settings }));
	return data;
}

function launch(run: { app: string; data: string; log: string }) {
	const child = Bun.spawn([join(run.app, 'Contents/MacOS/vsrustium'), '--user-data-dir', run.data], { stdout: 'ignore', stderr: Bun.file(run.log) });
	current = { pid: child.pid, log: run.log };
	return child;
}

function version(app: string) {
	return Bun.spawnSync(['plutil', '-extract', 'CFBundleShortVersionString', 'raw', join(app, 'Contents/Info.plist')]).stdout.toString().trim();
}

async function processesOf(data: string) {
	return (await Bun.$`pgrep -lf ${data}`.nothrow().text()).trim().split('\n').filter(Boolean).map(line => line.slice(line.indexOf(' ') + 1));
}

function sha256(file: string) {
	return new Bun.CryptoHasher('sha256').update(readFileSync(file)).digest('hex');
}

function count(file: string, text: string) {
	return existsSync(file) ? readFileSync(file, 'utf8').split(text).length - 1 : 0;
}

async function waitFor(file: string, text: string, timeout: number) {
	return waitUntil(() => count(file, text) > 0, timeout);
}

async function waitUntil(condition: () => boolean, timeout: number) {
	for (const start = Date.now(); Date.now() - start < timeout; await Bun.sleep(500)) {
		if (condition()) {
			return true;
		}
	}
	return condition();
}

// Every wait ends within 90 s (a download with its verification 150 s); a failed check throws and ends its scenario.
function check(name: string, ok: boolean, detail = '') {
	results.push(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? ` (${detail})` : ''}`);
	console.log(results.at(-1));
	if (!ok) {
		failures.push(name);
		diagnose();
		throw new Error(name);
	}
}

// Whether the app still runs, whether the screen is locked (App Nap and System Events depend on it), its last
// update log lines.
function diagnose() {
	if (!current) {
		return;
	}
	const alive = Bun.spawnSync(['kill', '-0', String(current.pid)]).exitCode === 0;
	const locked = Bun.spawnSync(['ioreg', '-n', 'Root', '-d1']).stdout.toString().match(/"CGSSessionScreenIsLocked"=(\w+)/)?.[1] ?? 'No';
	const lines = existsSync(current.log) ? readFileSync(current.log, 'utf8').split('\n').filter(line => line.includes('[update]') || line.includes('panicked')).slice(-5) : [];
	console.log(`  pid ${current.pid} ${alive ? 'running' : 'gone'}, screen locked: ${locked}, log: ${lines.join(' / ')}`);
}

// Keys through cua-driver to the app's window, which need neither focus nor System Events (a VM lane grants
// Accessibility to cua-driver only). The window shows up once the app finished launching: retry for up to 30 s.
async function windowOf(pid: number) {
	for (let attempt = 0; ; attempt++) {
		const { windows } = await cua('list_windows', { pid });
		// The workbench window: on screen and the widest (popups, hovers and the palette are other windows).
		const shown = windows.filter((w: { is_on_screen: boolean; bounds: { width: number } }) => w.is_on_screen && w.bounds.width >= 400);
		const main = shown.sort((a: { bounds: { width: number } }, b: { bounds: { width: number } }) => b.bounds.width - a.bounds.width)[0];
		if (main) {
			const target = { pid, window_id: main.window_id };
			// cua-driver refuses background keys to a window AX has not resolved yet; in front it has.
			await cua('bring_to_front', target).catch(() => {});
			await Bun.sleep(500);
			return target;
		}
		if (attempt === 30) {
			throw new Error(`no window of pid ${pid}`);
		}
		await Bun.sleep(1000);
	}
}

// The Command Palette: Shift+Cmd+P, the title, Return.
async function palette(pid: number, title: string) {
	await key(pid, 'hotkey', { keys: ['cmd', 'shift', 'p'] });
	await Bun.sleep(1000);
	for (const char of title.toLowerCase()) {
		await key(pid, 'press_key', { key: char === ' ' ? 'space' : char });
	}
	await Bun.sleep(1000);
	await key(pid, 'press_key', { key: 'return' });
}

async function quit(pid: number) {
	await key(pid, 'hotkey', { keys: ['cmd', 'q'] });
}

// cua-driver refuses a key while AX has not resolved the window (off_space_or_ax_unresolved): in front again, retry.
async function key(pid: number, tool: string, args: object) {
	for (let attempt = 1; ; attempt++) {
		try {
			return await cua(tool, { ...(await windowOf(pid)), ...args });
		} catch (error) {
			if (attempt === 3 || !String(error).includes('off_space_or_ax_unresolved')) {
				throw error;
			}
			await Bun.sleep(1000);
		}
	}
}

async function screenshot(pid: number, name: string) {
	const { windows } = await cua('list_windows', { pid });
	if (windows[0]) {
		mkdirSync('port/results/raw', { recursive: true });
		Bun.spawnSync(['screencapture', '-o', '-x', '-l', String(windows[0].window_id), `port/results/raw/update-${name}.png`]);
	}
}

// The AX element of a label (a button unless `role` says) in the main window, as the element token of a fresh read.
async function buttonOf(pid: number, label: string, role = 'AXButton') {
	const { window_id } = await windowOf(pid);
	await cua('get_window_state', { pid, window_id, max_image_dimension: 1 });
	await Bun.sleep(500);
	const state = await cua('get_window_state', { pid, window_id, max_image_dimension: 1 });
	const row = (state.tree_markdown as string).match(new RegExp(`\\[(\\d+)\\] ${role} "${label}"`))?.[1];
	return row ? { window_id, token: `${state.snapshot_id}:${row}` } : undefined;
}

// Every window's accessibility tree; the first read wakes AccessKit, so read twice.
async function windowTree(pid: number) {
	const { windows } = await cua('list_windows', { pid });
	let text = '';
	for (const window of windows) {
		await cua('get_window_state', { pid, window_id: window.window_id, max_image_dimension: 1 });
		await Bun.sleep(500);
		text += (await cua('get_window_state', { pid, window_id: window.window_id, max_image_dimension: 1 })).tree_markdown;
	}
	return text;
}

// ui-pair's lock: /tmp/port-gui.lock holds the owner's pid; a dead owner's lock is taken over. gui-lane holds it for
// its host lane (PORT_GUI_LOCK_HELD).
async function takeGuiLock() {
	if (process.env.PORT_GUI_LOCK_HELD) {
		return;
	}
	const lock = '/tmp/port-gui.lock';
	while (true) {
		try {
			mkdirSync(lock);
			writeFileSync(join(lock, 'pid'), String(process.pid));
			process.on('exit', () => rmSync(lock, { recursive: true, force: true }));
			return;
		} catch {
			const owner = Number(await Bun.file(join(lock, 'pid')).text().catch(() => '0'));
			const alive = (() => {
				try {
					process.kill(owner, 0);
					return true;
				} catch {
					return false;
				}
			})();
			if (owner && !alive) {
				rmSync(lock, { recursive: true, force: true });
				continue;
			}
			await Bun.sleep(5000);
		}
	}
}

async function cua(tool: string, args: object) {
	const child = Bun.spawn(['timeout', '30', 'cua-driver', 'call', tool, JSON.stringify({ session: 'update-check', ...args })], { stderr: 'pipe' });
	const [stdout, stderr] = [await new Response(child.stdout).text(), await new Response(child.stderr).text()];
	if (await child.exited) {
		throw new Error(`cua-driver ${tool}: ${stderr}${stdout}`);
	}
	return JSON.parse(stdout);
}