Web version, stage 2: Stockfish 19 in workers, live analysis, game review on N workers, My games, files, keys

game-review: what the job does for one target (the full search, the second
best without the move played, the shallow ones) becomes a machine without I/O
(job/work.rs), driven by the engine processes on a computer (job/engines.rs,
the same searches as before) and by Web Workers in a browser
(job/workers.rs: a dispatcher polled from the frames, never blocking). The
analysis cache goes through a CacheStore (a folder, or the program's files of
the platform).

The browser's engine: Stockfish.js 19.0.1 (npm stockfish, GPL-3.0), its
single-threaded build served beside /app/ (engine/, build.sh checks the
package's sha512), its 99 MB wasm downloaded only through the engine offer,
checked against its SHA-256 and kept in Cache Storage; workers get it as a
blob: address. Live analysis (lines, arrows, the bar) and the review run on it;
the review uses one worker per logical CPU, at most 8.

My games (the web version): a PGN in the browser's storage, always on the
shelf; Ctrl+S puts a game there (its own record, or a new one); deleting with
undo. chess-core's store gives the bytes of append/replace/remove/restore, so
the platform writes them into the browser's files; on a computer the files
are written as before. Settings: Browser data (used and free space, keeping
the data for good, Download all as PGN, deleting the engine).

Files: a file of the last visit offers Choose the file again; Keep a copy in
the browser (refused with the room it needs when the browser gives too
little); files over 1 GB are not opened, with a word on why. No reference tab
and no search by position in the web version. Keys: Alt+Left, plain 1-6,
Ctrl+C, N in the library (the browser keeps Ctrl+W/N/1-6/Shift+C).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 16:35:16 +03:00
parent 4ccf8099a5
commit 61ccd763bc
34 changed files with 2063 additions and 253 deletions

View file

@ -37,6 +37,27 @@ if command -v wasm-opt >/dev/null 2>&1; then
fi
cp "$here/page/device.js" "$here/page/page.js" "$out/"
# The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build,
# checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points
# at a copy of the package; otherwise it is downloaded once into target/web/.
sf_url=https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz
sf_sha512=bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ==
tgz=${STOCKFISH_TGZ:-$root/target/web/stockfish-19.0.1.tgz}
if [ ! -f "$tgz" ]; then
mkdir -p "$(dirname "$tgz")"
curl -fsSL --retry 3 -o "$tgz.part" "$sf_url"
mv "$tgz.part" "$tgz"
fi
have_sha=$(openssl dgst -sha512 -binary "$tgz" | base64 -w0)
if [ "$have_sha" != "$sf_sha512" ]; then
echo "$tgz is not stockfish@19.0.1 (sha512 $have_sha)" >&2
exit 1
fi
mkdir -p "$out/engine"
tar -xzf "$tgz" -C "$out/engine" --strip-components=2 \
package/bin/stockfish-19-single.js package/bin/stockfish-19-single.wasm
tar -xzf "$tgz" -C "$out/engine" --strip-components=1 package/Copying.txt
for size in 32 64 180; do
cp "$root/website/static/img/icon-$size.png" "$out/"
done

99
apps/web/check/review.mjs Normal file
View file

@ -0,0 +1,99 @@
// The game review of the web version against the desktop program's, on games of the
// chess.com check set (crates/game-review/chesscom/): the browser reviews them (Stockfish
// 19 wasm in workers), its evaluations are read out of its storage and compared with the
// ones `chesscom_check` keeps (target/chesscom-check/v1): the same search must give the
// same evaluations, so the same !!/!.
//
// node apps/web/check/review.mjs <app-dir> <out-dir> <native-cache-dir> <game.pgn>...
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
import { basename, join } from 'node:path';
import { session } from './steps.mjs';
import { sleep } from './bidi.mjs';
const [appDir, outDir, nativeDir, ...games] = process.argv.slice(2);
mkdirSync(outDir, { recursive: true });
const all = join(outDir, 'chesscom-games.pgn');
writeFileSync(all, games.map((g) => readFileSync(g, 'utf8').trim()).join('\n\n') + '\n');
const s = await session(appDir);
const { t } = s;
const stored = `new Promise((ok, no) => {
const q = indexedDB.open('chesspenguin');
q.onerror = () => no('no db');
q.onsuccess = () => {
const st = q.result.transaction('files').objectStore('files');
const keys = st.getAllKeys(), values = st.getAll();
values.onsuccess = () => ok(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i])])
.filter(([k]) => k.startsWith('/cache/analysis/')));
};
})`;
let failed = 0;
try {
await s.run({ url: '?lang=en' }, outDir);
await sleep(2000);
// The games in one file, reviewed one by one.
await s.run({ key: 'o', mods: ['ctrl'] }, outDir);
await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000);
const input = await s.ff.browser.send('script.evaluate', {
expression: `document.getElementById('cp-open-files')`, target: { context: t.context }, awaitPromise: false,
});
await s.ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: input.result.sharedId }, files: [all] });
await sleep(3000);
await s.run({ shot: 'review-0-opened.png' }, outDir);
for (let i = 0; i < games.length; i++) {
const before = (await t.evaluate(stored)).length;
await s.run({ click: [300, 214 + 27 * i], double: true }, outDir);
await sleep(1500);
await s.run({ key: 'a', mods: ['shift'] }, outDir);
// The first time the engine is offered: downloaded, the review starts by itself.
if (i === 0) {
await sleep(1000);
await s.run({ shot: 'review-0-offer.png' }, outDir);
await s.run({ key: 'enter' }, outDir);
await sleep(5000);
await s.run({ shot: 'review-0-downloading.png' }, outDir);
}
const t0 = Date.now();
for (;;) {
await sleep(2000);
if ((await t.evaluate(stored)).length > before) break;
if (Date.now() - t0 > 600000) throw new Error(`no review of ${games[i]}`);
}
console.log(`${basename(games[i])}: reviewed in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
await s.run({ shot: `review-${i + 1}.png` }, outDir);
await s.run({ click: [55, 15] }, outDir);
await sleep(1000);
}
// The comparison.
const fromBrowser = await t.evaluate(stored);
for (const [key, text] of fromBrowser) {
const name = basename(key);
writeFileSync(join(outDir, name), text);
const web = JSON.parse(text);
const nativePath = join(nativeDir, name);
if (!existsSync(nativePath)) {
console.log(`FAIL ${name}: no native evaluations to compare with`);
failed++;
continue;
}
const native = new Map(JSON.parse(readFileSync(nativePath, 'utf8')).evals);
let same = 0, differ = 0, missing = 0;
for (const [k, e] of web.evals) {
const n = native.get(k);
if (!n) { missing++; continue; }
if (JSON.stringify(n) === JSON.stringify(e)) same++;
else {
differ++;
if (differ <= 3) console.log(' differs', k.slice(-40), JSON.stringify(n).slice(0, 160), '|', JSON.stringify(e).slice(0, 160));
}
}
const ok = differ === 0 && missing === 0 && same > 0;
if (!ok) failed++;
console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${same} positions the same${differ ? `, ${differ} differ` : ''}${missing ? `, ${missing} not in the native set` : ''} (engine ${web.meta.engine}, ${web.meta.nodes} nodes)`);
}
} finally {
await s.stop();
}
for (const e of s.errors) console.log('console:', e);
console.log(failed ? `${failed} failed` : 'all the same');
process.exit(failed ? 1 : 0);

69
apps/web/check/steps.mjs Normal file
View file

@ -0,0 +1,69 @@
// Runs a list of steps in the web version in headless Firefox and keeps screenshots —
// for finding the places of buttons, and for the scenario checks built on it.
//
// node apps/web/check/steps.mjs <app-dir> <out-dir> <steps.json>
//
// A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true}
// | {"key": "l", "mods": ["ctrl"]} | {"shot": "name.png"} | {"eval": "js expression"}
// | {"until": "js expression", "ms": 60000}
import { spawn } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { launch } from './firefox.mjs';
import { sleep, tab } from './bidi.mjs';
export const KEYS = { ctrl: '', shift: '', alt: '', esc: '', right: '', left: '', enter: '' };
export async function session(appDir, port = 18767) {
const root = fileURLToPath(new URL('../../..', import.meta.url));
const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' });
const ff = await launch(19224);
const errors = [];
const t = await tab(ff.browser, 1400, 860, (line) => {
if (/panicked|RuntimeError|\[error\]/.test(line)) errors.push(line);
if (process.env.CONSOLE) console.log(line);
});
const base = `http://127.0.0.1:${port}/app/`;
const run = async (step, outDir) => {
if (step.url !== undefined) {
await t.navigate(base + step.url);
await t.waitFor(`document.getElementById('cp-status').hidden || !document.getElementById('cp-device').hidden`, 30000);
}
if (step.wait) await sleep(step.wait);
if (step.click) {
const [x, y] = step.click;
const acts = [{ type: 'pointerMove', x, y }];
for (let i = 0; i < (step.double ? 2 : 1); i++) acts.push({ type: 'pointerDown', button: step.right ? 2 : 0 }, { type: 'pointerUp', button: step.right ? 2 : 0 });
await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]);
await sleep(300);
}
if (step.key) {
const mods = (step.mods || []).map((m) => KEYS[m]);
const v = KEYS[step.key] || step.key;
const acts = [...mods.map((m) => ({ type: 'keyDown', value: m })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...mods.reverse().map((m) => ({ type: 'keyUp', value: m }))];
for (let i = 0; i < (step.times || 1); i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]);
await sleep(300);
}
if (step.eval) console.log('eval:', JSON.stringify(await t.evaluate(step.eval)).slice(0, 2000));
if (step.until) await t.waitFor(step.until, step.ms || 60000);
if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot());
};
return {
t, ff, errors, run,
stop: async () => { await ff.stop(); server.kill(); },
};
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [appDir, outDir, stepsFile] = process.argv.slice(2);
mkdirSync(outDir, { recursive: true });
const steps = JSON.parse(readFileSync(stepsFile, 'utf8'));
const s = await session(appDir);
try {
for (const step of steps) await s.run(step, outDir);
} finally {
await s.stop();
}
for (const e of s.errors) console.log('console:', e);
}