uci: the engine as a Web Worker in a browser, on the same protocol machine; game-review: the process job is native

On WebAssembly the engine is a Web Worker: a line of UCI is one message each
way, the protocol machine is driven by the worker's messages and by timers set
for its deadlines; the handshake does not block (Engine::start_worker gives a
Starting, polled until readyok). EngineHandle has the same methods as the
process one, minus those that block or name a process. Option and search
checks are shared by both transports.

tests/worker.rs runs the worker transport against a fake engine in JavaScript
in headless Firefox (apps/web/check/uci-worker.mjs: wasm-bindgen-test-runner
serves, a WebDriver BiDi client reads the outcome): handshake, analysis and
stop, coalescing of rapid requests without mixing output, an engine hung on
stop, a crash, and every handshake failure. 5 of 5 pass.

game-review: the job in engine processes (run and its workers) moves to
job/engines.rs, built where there are processes. .cargo/config.toml: the
getrandom backend of WebAssembly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 14:29:12 +03:00
parent a66d1016d9
commit 2703e5de38
16 changed files with 1369 additions and 339 deletions

78
apps/web/check/bidi.mjs Normal file
View file

@ -0,0 +1,78 @@
// A minimal WebDriver BiDi client for headless Firefox (Node 22+: global WebSocket).
// Used by the web checks (docs/dev/web.md, «Проверки»); no windows are opened.
export async function connect(port) {
const ws = new WebSocket(`ws://127.0.0.1:${port}/session`);
let id = 0;
const pending = new Map();
const listeners = [];
ws.onmessage = (m) => {
const d = JSON.parse(m.data);
if (d.id && pending.has(d.id)) {
const p = pending.get(d.id);
pending.delete(d.id);
if (d.type === 'error') p.rej(new Error(`${d.error}: ${d.message}`));
else p.res(d.result);
} else if (d.method) {
for (const l of listeners) l(d.method, d.params);
}
};
await new Promise((res, rej) => {
ws.onopen = res;
ws.onerror = () => rej(new Error('cannot connect to Firefox'));
});
const send = (method, params) =>
new Promise((res, rej) => {
const i = ++id;
pending.set(i, { res, rej });
ws.send(JSON.stringify({ id: i, method, params }));
});
await send('session.new', { capabilities: {} });
return {
send,
on: (f) => listeners.push(f),
close: async () => {
await send('session.end', {}).catch(() => {});
ws.close();
},
};
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// A tab of `width`×`height` CSS pixels with the console forwarded to `log`.
export async function tab(b, width, height, log = console.log) {
await b.send('session.subscribe', { events: ['log.entryAdded'] });
b.on((method, p) => {
if (method === 'log.entryAdded') log(`[${p.level}] ${p.text}`);
});
const { context } = await b.send('browsingContext.create', { type: 'tab' });
await b.send('browsingContext.setViewport', { context, viewport: { width, height } });
const evaluate = async (expression) => {
const r = await b.send('script.evaluate', {
expression,
target: { context },
awaitPromise: true,
});
if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed');
return r.result?.value;
};
return {
context,
evaluate,
navigate: (url) => b.send('browsingContext.navigate', { context, url, wait: 'complete' }),
screenshot: async () =>
Buffer.from((await b.send('browsingContext.captureScreenshot', { context })).data, 'base64'),
actions: (actions) => b.send('input.performActions', { context, actions }),
// Waits until `expression` is truthy (polled), or throws after `ms`.
waitFor: async (expression, ms = 10000) => {
const end = Date.now() + ms;
for (;;) {
const v = await evaluate(expression).catch(() => undefined);
if (v) return v;
if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`);
await sleep(100);
}
},
};
}

View file

@ -0,0 +1,51 @@
// Starts a headless Firefox with a temporary profile and WebDriver BiDi; stops it by
// its PID. No window is ever shown (MOZ_HEADLESS).
import { spawn } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connect, sleep } from './bidi.mjs';
export async function launch(port = 19222) {
const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-firefox-'));
writeFileSync(
join(profile, 'user.js'),
[
'user_pref("remote.active-protocols", 1);',
'user_pref("browser.shell.checkDefaultBrowser", false);',
'user_pref("datareporting.policy.dataSubmissionEnabled", false);',
'user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);',
// Downloads go to the profile without asking.
'user_pref("browser.download.folderList", 2);',
`user_pref("browser.download.dir", "${join(profile, 'downloads')}");`,
'user_pref("browser.download.useDownloadDir", true);',
'user_pref("browser.download.always_ask_before_handling_new_types", false);',
'',
].join('\n'),
);
const log = join(profile, 'firefox.log');
const out = (await import('node:fs')).openSync(log, 'a');
const ff = spawn(
'firefox',
['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', String(port), 'about:blank'],
{ env: { ...process.env, MOZ_HEADLESS: '1' }, stdio: ['ignore', out, out] },
);
for (let i = 0; i < 100; i++) {
if (readFileSync(log, 'utf8').includes('WebDriver BiDi listening')) break;
await sleep(100);
}
const browser = await connect(port);
return {
browser,
profile,
downloads: join(profile, 'downloads'),
stop: async () => {
await browser.close().catch(() => {});
try {
process.kill(ff.pid);
} catch {}
await sleep(300);
rmSync(profile, { recursive: true, force: true });
},
};
}

View file

@ -0,0 +1,60 @@
// The tests of uci's worker transport (crates/uci/tests/worker.rs) in headless
// Firefox. wasm-bindgen-test-runner serves them (NO_HEADLESS: it does not look for a
// WebDriver) and this script opens its page and reads the outcome.
//
// node apps/web/check/uci-worker.mjs
//
// Needs wasm-bindgen-test-runner of the wasm-bindgen version in Cargo.lock in PATH
// or in WASM_BINDGEN_TEST_RUNNER.
import { spawn } from 'node:child_process';
import { launch } from './firefox.mjs';
import { sleep, tab } from './bidi.mjs';
const runner = process.env.WASM_BINDGEN_TEST_RUNNER || 'wasm-bindgen-test-runner';
const address = '127.0.0.1:18731';
const cargo = spawn(
'cargo',
['test', '-p', 'uci', '--target', 'wasm32-unknown-unknown', '--test', 'worker'],
{
env: {
...process.env,
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: runner,
NO_HEADLESS: '1',
WASM_BINDGEN_TEST_ADDRESS: address,
},
stdio: ['ignore', 'pipe', 'inherit'],
// Its own process group: the runner it starts is stopped with it.
detached: true,
},
);
const stopCargo = () => {
try {
process.kill(-cargo.pid);
} catch {}
};
let served = false;
cargo.stdout.on('data', (d) => {
if (String(d).includes(address)) served = true;
});
for (let i = 0; i < 1200 && !served; i++) await sleep(100);
if (!served) {
console.error('the test runner did not start');
stopCargo();
process.exit(1);
}
const ff = await launch();
let failed = true;
try {
const t = await tab(ff.browser, 1000, 800, () => {});
await t.navigate(`http://${address}/`);
const text = await t.waitFor(
`(() => { const t = document.body.innerText; return /test result: /.test(t) && t; })()`,
60000,
);
console.log(text.trim());
failed = !/test result: ok\./.test(text);
} finally {
await ff.stop();
stopCargo();
}
process.exit(failed ? 1 : 0);