Files
Live_RC/scripts/record-video-guides.mjs
T

1197 lines
71 KiB
JavaScript

// Records short, narrated MKV screen-capture clips of RaceCore's UI for use as new-user
// video guides, driven against a real, isolated instance of the app (own temp SQLite dir,
// own headless Chrome profile) exactly like the tests/browser_*.js suite - nothing here
// ever touches a real installation's data.
//
// Each clip is a list of steps ({ text, action }). For every step, the narration line's
// audio is synthesized up front (Piper, a small local neural TTS - far more intelligible
// than espeak-ng's formant synthesis, which is what this used before) so its real duration
// is known, the on-screen action runs, and the recording pauses for exactly that duration
// before moving to the next line - the actual wall-clock time each action took is recorded
// too, so the final narration track is built from real measured offsets (via ffmpeg's
// adelay/amix), not an idealized schedule that would drift out of sync with page-load/
// network latency.
//
// Usage: node scripts/record-video-guides.mjs [clip-name ...]
// With no arguments, records every clip below. Pass one or more names (e.g.
// "settings-tabs") to record only those. Output lands in docs/videos/<name>.mkv,
// alongside docs/screenshots - these are committed, linked from README.md/README.sv.md
// and the in-app Guide page, so re-run this and commit the result whenever a clip's
// flow changes enough that the recording no longer matches reality.
//
// Requires ffmpeg and Piper (`pipx install piper-tts`) on PATH, plus a downloaded voice
// model - by default ~/.local/share/piper-voices/en_US-lessac-medium.onnx (get it from
// https://huggingface.co/rhasspy/piper-voices, the .onnx and its matching .onnx.json).
// Override the model with the PIPER_MODEL env var.
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { homedir, tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { startFakeDecoder } from "../tests/browser_fake_decoder.js";
import { RACE_AUDIO_EVENT_DEFINITIONS } from "../src/race_audio.js";
// Silences every race-audio event's effect/voice so a clip that actually runs a start
// sequence (countdown, lights, "drivers ready"/"go" cues) never tries to play a real sound
// or call speechSynthesis in headless Chrome - only the timers driving the visuals run.
const SILENCED_EVENTS = Object.fromEntries(RACE_AUDIO_EVENT_DEFINITIONS.map((definition) => [definition.key, { effect: false, voice: false }]));
const projectDir = dirname(dirname(fileURLToPath(import.meta.url)));
const outputDir = join(projectDir, "docs", "videos");
const chrome = [process.env.CHROME_PATH, "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"].find((p) => p && existsSync(p));
if (!chrome) throw new Error("Chrome/Chromium not found. Set CHROME_PATH to the browser executable.");
try { execFileSync("piper", ["--help"], { stdio: "ignore" }); } catch { throw new Error("piper not found on PATH (used for narration audio). Install with: pipx install piper-tts"); }
const PIPER_MODEL = process.env.PIPER_MODEL || join(homedir(), ".local", "share", "piper-voices", "en_US-lessac-medium.onnx");
if (!existsSync(PIPER_MODEL)) throw new Error(`Piper voice model not found at ${PIPER_MODEL}. Download it from https://huggingface.co/rhasspy/piper-voices (both the .onnx and .onnx.json files), or set PIPER_MODEL.`);
const LEAD_MS = 600; // silence before the first line, so the opening frame settles first
const GAP_MS = 450; // silence between narration lines
const TAIL_MS = 1400; // hold on the final frame after the last line finishes
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitFor(check, label, timeout = 15000) {
const until = Date.now() + timeout;
while (Date.now() < until) {
try { if (await check()) return; } catch {}
await pause(100);
}
throw new Error("Timed out: " + label);
}
async function freePort() {
const server = createServer();
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
const port = server.address().port;
await new Promise((resolve) => server.close(resolve));
return port;
}
function wavDurationMs(wavPath) {
const out = execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", wavPath]).toString().trim();
return Math.round(parseFloat(out) * 1000);
}
function synthesizeNarration(steps, narrationDir) {
return steps.map((step, index) => {
const wavPath = join(narrationDir, `line_${String(index).padStart(2, "0")}.wav`);
execFileSync("piper", ["-m", PIPER_MODEL, "-f", wavPath], { input: step.text, stdio: ["pipe", "ignore", "ignore"] });
return { ...step, wavPath, durationMs: wavDurationMs(wavPath) };
});
}
// Places each narration line at its own real measured start offset (via adelay) and mixes
// them onto one track (amix, normalize=0 since lines never overlap - normalizing would
// quietly halve/third the volume for no reason). `normalize=0` is an amix filter option
// available since ffmpeg 4.x.
function mixNarrationTrack(narrated, outputPath) {
const inputs = narrated.flatMap((line) => ["-i", line.wavPath]);
const delayed = narrated.map((line, i) => `[${i}]adelay=${Math.max(0, Math.round(line.startMs))}|${Math.max(0, Math.round(line.startMs))}[a${i}]`);
const mixInputs = narrated.map((_, i) => `[a${i}]`).join("");
const filter = `${delayed.join(";")};${mixInputs}amix=inputs=${narrated.length}:duration=longest:normalize=0[aout]`;
execFileSync("ffmpeg", ["-y", ...inputs, "-filter_complex", filter, "-map", "[aout]", "-c:a", "pcm_s16le", outputPath], { stdio: "inherit" });
}
// A single recording session: isolated server + headless Chrome + CDP screencast capture,
// narrated by stepping through `steps` in order. `prepare()` is an optional async hook
// (for clips that need a live dependency, e.g. a fake decoder socket, before the server is
// seeded) returning { seedState, teardown, extra } - `extra` is merged into the context
// object passed to `setup` and every step's `action`, and `teardown` always runs, even if
// the recording fails partway through.
async function recordClip(name, { prepare, seedState, setup, steps }) {
const temporary = mkdtempSync(join(tmpdir(), "racecore-recguide-"));
const framesDir = join(temporary, "frames");
const narrationDir = join(temporary, "narration");
mkdirSync(framesDir, { recursive: true });
mkdirSync(narrationDir, { recursive: true });
const children = [];
let socket;
const launch = (command, args, options = {}) => {
const child = spawn(command, args, { cwd: projectDir, stdio: "ignore", ...options });
children.push(child);
child.on("error", (e) => console.error(e.message));
return child;
};
let prepared;
try {
console.log(`[${name}] synthesizing narration (${steps.length} lines)...`);
const narrationSteps = synthesizeNarration(steps, narrationDir);
prepared = await prepare?.();
const seedFn = prepared?.seedState || seedState;
const port = await freePort();
const debugPort = await freePort();
const base = `http://127.0.0.1:${port}`;
launch(process.execPath, ["server.js"], { env: { ...process.env, HOST: "127.0.0.1", PORT: String(port), RC_TIMING_DATA_DIR: join(temporary, "data"), RC_TIMING_PID_FILE: "" } });
await waitFor(async () => (await fetch(base + "/api/health")).ok, "isolated server");
const initial = {
classes: [], drivers: [], cars: [], events: [], sessions: [], resultsBySession: {},
settings: { language: "en", autoReconnect: false, backendUrl: base, raceAudio: { enabled: false, decoderAlarm: false } },
training: {},
};
seedFn?.(initial);
await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(initial) });
launch(chrome, [
"--headless", "--disable-gpu", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
...(process.env.RC_BROWSER_NO_SANDBOX === "1" ? ["--no-sandbox"] : []),
"--window-size=1600,900", `--user-data-dir=${join(temporary, "browser")}`, `--remote-debugging-port=${debugPort}`, "about:blank",
]);
let target;
await waitFor(async () => {
target = (await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json()).find((p) => p.type === "page");
return target;
}, "headless browser");
socket = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => { socket.addEventListener("open", resolve, { once: true }); socket.addEventListener("error", reject, { once: true }); });
let nextId = 0;
const requests = new Map();
let frameCount = 0;
// Chrome only sends a frame when the page changes, so each frame is shown for as long as it
// was really on screen - spreading them evenly would drift away from the narration.
const frameTimes = [];
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.id) {
const request = requests.get(message.id);
requests.delete(message.id);
if (message.error) request?.reject(new Error(message.error.message)); else request?.resolve(message.result);
} else if (message.method === "Page.screencastFrame") {
const { data, sessionId } = message.params;
frameCount += 1;
const file = `frame_${String(frameCount).padStart(6, "0")}.jpg`;
writeFileSync(join(framesDir, file), Buffer.from(data, "base64"));
frameTimes.push({ file, at: Date.now() });
send("Page.screencastFrameAck", { sessionId });
} else if (message.method === "Page.javascriptDialogOpening") {
// A confirm (e.g. "Disqualify ...?") would block headless Chrome: answer yes, as the clip shows.
send("Page.handleJavaScriptDialog", { accept: true });
}
});
function send(method, params = {}) {
return new Promise((resolve, reject) => { const id = ++nextId; requests.set(id, { resolve, reject }); socket.send(JSON.stringify({ id, method, params })); });
}
async function evaluate(expression) {
const result = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || JSON.stringify(result.exceptionDetails));
return result.result.value;
}
async function navigate(view, form) {
await send("Page.navigate", { url: base + "/?view=" + view });
await waitFor(async () =>
Boolean(await evaluate(`document.getElementById(${JSON.stringify(form)})`)) &&
(await evaluate(`document.getElementById("syncStatusDetail")?.textContent`) || "").includes("Data loaded"),
view + " hydrated");
}
async function fill(form, fields) {
await evaluate(`(() => { const form = document.getElementById(${JSON.stringify(form)}); for (const [name,value] of Object.entries(${JSON.stringify(fields)})) { const field=form.elements.namedItem(name); if (!field) throw new Error("Missing field "+name); field.value=value; field.dispatchEvent(new Event("input", {bubbles:true})); } })()`);
}
const click = (selector) => evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);
const scrollTo = (selector, block = "start") => evaluate(`document.querySelector(${JSON.stringify(selector)})?.scrollIntoView({block: ${JSON.stringify(block)}})`);
// Clicks a real sidebar nav item by its (English) label, exercising the app's actual
// client-side view switch (see renderNav in src/app.js) instead of a full Page.navigate
// reload - matches what a real user's click does, and looks like it in the recording.
const clickNav = (label) => evaluate(`Array.from(document.querySelectorAll(".nav-item")).find((b) => b.textContent.trim() === ${JSON.stringify(label)})?.click()`);
const state = async () => (await (await fetch(base + "/api/state")).json()).state;
await send("Runtime.enable");
await send("Page.enable");
await send("Emulation.setDeviceMetricsOverride", { width: 1600, height: 900, deviceScaleFactor: 1, mobile: false });
const ctx = { evaluate, navigate, fill, click, scrollTo, clickNav, state, pause, send, ...(prepared?.extra || {}) };
// Setup (navigation, opening the right event, scrolling to the starting point) happens
// before the screencast starts, so the recording opens already on the right view
// instead of capturing the page load itself.
await setup?.(ctx);
console.log(`[${name}] recording...`);
const captureStart = Date.now();
await send("Page.startScreencast", { format: "jpeg", quality: 80, maxWidth: 1600, maxHeight: 900, everyNthFrame: 1 });
await pause(LEAD_MS);
const narrated = [];
for (const step of narrationSteps) {
await step.action?.(ctx);
narrated.push({ ...step, startMs: Date.now() - captureStart });
await pause(step.durationMs);
await pause(GAP_MS);
}
await pause(TAIL_MS);
await send("Page.stopScreencast");
await pause(300);
const elapsedSec = (Date.now() - captureStart) / 1000;
console.log(`[${name}] captured ${frameCount} frames over ${elapsedSec.toFixed(1)}s`);
mkdirSync(outputDir, { recursive: true });
const silentVideoPath = join(temporary, "silent.mkv");
const captureEnd = captureStart + elapsedSec * 1000;
const listLines = frameTimes.flatMap((frame, index) => {
const from = index === 0 ? captureStart : frame.at;
const until = frameTimes[index + 1]?.at ?? captureEnd;
return [`file '${join(framesDir, frame.file)}'`, `duration ${Math.max(0.001, (until - from) / 1000).toFixed(3)}`];
});
// The concat demuxer needs the last file listed again for its duration to count.
listLines.push(`file '${join(framesDir, frameTimes.at(-1).file)}'`);
const listPath = join(temporary, "frames.txt");
writeFileSync(listPath, listLines.join("\n") + "\n");
execFileSync("ffmpeg", [
"-y", "-f", "concat", "-safe", "0", "-i", listPath,
"-vf", "fps=30,format=yuv420p", "-c:v", "libx264", silentVideoPath,
], { stdio: "inherit" });
const audioPath = join(temporary, "narration.wav");
mixNarrationTrack(narrated, audioPath);
const outputPath = join(outputDir, `${name}.mkv`);
execFileSync("ffmpeg", [
"-y", "-i", silentVideoPath, "-i", audioPath,
"-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "96k",
outputPath,
], { stdio: "inherit" });
console.log(`[${name}] wrote ${outputPath}`);
} finally {
try { socket?.close(); } catch {}
for (const child of children.reverse()) { try { child.kill(); } catch {} }
await pause(300);
try { await prepared?.teardown?.(); } catch {}
rmSync(temporary, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
}
}
const clips = {
"settings-tabs": {
async setup({ navigate }) {
await navigate("settings", "settingsForm");
},
steps: [
{ text: "This is the Settings page, split into four tabs: Connection, Audio, Appearance, and System." },
{ text: "Audio controls race sound announcements, volume, and which events get a spoken callout.", async action({ click }) { await click('[data-settings-tab="audio"]'); } },
{ text: "Appearance and Overlay covers club branding, track layouts, and the OBS overlay setup.", async action({ click }) { await click('[data-settings-tab="appearance"]'); } },
{ text: "System and Backup handles software updates, backups, race presets, and the club's House of RC key.", async action({ click }) { await click('[data-settings-tab="system"]'); } },
{ text: "And Connection, where we started, is where you link up the decoder.", async action({ click }) { await click('[data-settings-tab="connection"]'); } },
],
},
// House of RC: the page talks to a stand-in for the House of RC routes (installed before
// every page load), so no key, club or real event is ever used or shown.
"house-of-rc": {
seedState(state) {
const classId = "vid_hor_class";
state.classes.push({ id: classId, name: "2WD Buggy" });
state.drivers.push({ id: "vid_hor_alex", name: "Alex Karlsson", classId, transponder: "7970001", houseOfRcId: "501" });
},
async setup({ send, navigate, click, scrollTo }) {
await send("Page.addScriptToEvaluateOnNewDocument", { source: `(() => {
const realFetch = window.fetch;
const json = (data) => new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } });
const event = { id: 9001, name: "Club Cup Round 3", start: "2026-12-05T08:00:00Z", city: "Hometown", country: "SE", url: "https://houseofrc.com/events/9001" };
const first = [
{ entryId: 1, classId: 71, houseOfRcId: 501, name: "Alex Karlsson", number: 7, transponders: ["7970001"], club: "Hometown RC", car: "Xray XB2" },
{ entryId: 2, classId: 71, houseOfRcId: 502, name: "Sam Nilsson", number: 12, transponders: ["7970002"], club: "Hometown RC", car: "Associated B7" },
{ entryId: 3, classId: 71, houseOfRcId: 503, name: "Jamie Lee", number: 3, transponders: ["7970003"], club: "Lakeside RC", car: "Schumacher Cougar" },
{ entryId: 4, classId: 72, houseOfRcId: 504, name: "Robin Berg", number: 9, transponders: ["7970004"], club: "Lakeside RC", car: "Mugen MSB1" },
];
const later = [first[0], first[1], { entryId: 5, classId: 71, houseOfRcId: 505, name: "Kim Holm", number: 21, transponders: ["7970005"], club: "Hometown RC", car: "TLR 22 5.0" }];
window.fetch = async (url, options) => {
const path = String(url);
if (path.includes("/api/houseofrc/status")) return json({ configured: true, source: "file", keyHint: "…demo" });
if (path.includes("/api/houseofrc/test")) return json({ ok: true, organization: { id: 1, name: "Hometown RC" }, rateLimit: 60 });
if (path.includes("/api/houseofrc/events")) return json({ ok: true, organizationId: 1, events: [event, { id: 9002, name: "Winter Indoor", start: "2027-01-16T08:00:00Z", city: "Hometown", country: "SE" }] });
if (path.includes("/api/houseofrc/entries")) return json({ ok: true, event, classes: [{ id: 71, name: "2wd" }, { id: 72, name: "4wd" }], entries: sessionStorage.getItem("vidHorLater") ? later : first });
if (path.includes("/api/houseofrc/results")) return json({ ok: true, updated: JSON.parse(options.body).entries.length, entries: [] });
return realFetch(url, options);
};
})();` });
await navigate("settings", "settingsForm");
await click('[data-settings-tab="system"]');
await waitFor(async () => true, "settings");
await pause(400);
await scrollTo("#houseOfRcSettings", "center");
},
steps: [
{ text: "RaceCore works with House of RC. Under Settings, System, the club saves its House of RC key once. It stays on the server and is never shown again." },
{
text: "Test connection shows which club the key belongs to.",
async action({ click }) { await click("#houseOfRcTest"); },
},
{
text: "In Race Setup, the race wizard can fetch an event from House of RC. Drivers sign up there, with their transponders.",
async action({ navigate, click, evaluate }) {
await navigate("race_setup", "raceWizardStepForm");
await click("#raceWizardHouseOfRc");
await waitFor(async () => Boolean(await evaluate(`document.querySelector('[data-hor-event="9001"]')`)), "event list");
},
},
{
text: "Pick the event and one of its classes, and say which of our classes it is. Drivers we already have are linked, new ones are added.",
async action({ click, evaluate }) {
await click('[data-hor-event="9001"]');
await waitFor(async () => Boolean(await evaluate(`document.querySelector("[data-hor-apply]")`)), "entries");
await evaluate(`(() => { const select = document.querySelector("[data-hor-class]"); select.value = "vid_hor_class"; select.dispatchEvent(new Event("change", { bubbles: true })); })()`);
},
},
{
text: "One click fills the wizard: name, date, class, and the entered drivers. Then choose the format and create the race as usual.",
async action({ click, evaluate }) {
await click("[data-hor-apply]");
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".wizard-participant:checked")`)), "wizard filled");
},
},
{
text: "The race keeps the event and each driver's entry. Late entries or a withdrawal? Fetch changes from House of RC under Manage, Participants. Only heats that haven't run are changed.",
async action({ click, evaluate }) {
await click("#raceWizardNext");
await click("#raceWizardNext");
await click("#raceWizardCreate");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("houseOfRcRefreshEntries")`)), "manage view");
await evaluate(`document.getElementById("houseOfRcRefreshEntries").scrollIntoView({ block: "center" })`);
await pause(1200);
await evaluate(`sessionStorage.setItem("vidHorLater", "1")`);
await click("#houseOfRcRefreshEntries");
await waitFor(async () => Boolean(await evaluate(`document.querySelector("#houseOfRcRefreshOverlay [data-hor-apply]")`)), "changes");
},
},
{
text: "During the day, Send results shows what goes to each entry: qualifying, every heat, and once the finals have run, the final placings.",
async action({ click, evaluate }) {
await click("#houseOfRcRefreshOverlay [data-hor-apply]");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("houseOfRcSendResults")`)), "manage again");
await pause(800);
await click("#houseOfRcSendResults");
await waitFor(async () => Boolean(await evaluate(`document.querySelector("#houseOfRcResultsOverlay [data-hor-send]")`)), "results preview");
},
},
{
text: "Send, and the results are on House of RC. Drivers only sign up in one place.",
async action({ click }) { await click("#houseOfRcResultsOverlay [data-hor-send]"); },
},
],
},
"event-manager-tabs": {
seedState(state) {
const classId = "vid_class";
const driverA = { id: "vid_driver_a", name: "Alex Karlsson", classId, transponder: "7910001" };
const driverB = { id: "vid_driver_b", name: "Sam Nilsson", classId, transponder: "7910002" };
const raceEvent = {
id: "vid_event", name: "Club Race Night", classId, mode: "race",
raceConfig: { participantsConfigured: true, driverIds: [driverA.id, driverB.id], teams: [] },
};
const practice = { id: "vid_practice", eventId: raceEvent.id, name: "Practice 1", type: "practice", durationMin: 10, status: "ready" };
const qualifying = { id: "vid_quali", eventId: raceEvent.id, name: "Qualifying 1", type: "qualification", startMode: "position", durationMin: 5, status: "ready" };
state.classes.push({ id: classId, name: "2WD Buggy" });
state.drivers.push(driverA, driverB);
state.events.push(raceEvent);
state.sessions.push(practice, qualifying);
},
async setup({ navigate, click, evaluate, scrollTo }) {
await navigate("race_setup", "raceWizardStepForm");
await click("#event-manage-vid_event");
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".manage-tabs")`)), "manage tabs rendered");
await scrollTo(".manage-tabs");
},
steps: [
{ text: "Opening Manage on a race event splits the page into four tabs: Participants and teams, Format, Live and results, and Schedule and print." },
{
text: "Format is where you configure practice, qualifying, and finals, and generate the session plan.",
async action({ click, scrollTo }) { await click('[data-manage-tab="format"]'); await scrollTo('[data-manage-panel="format"]'); },
},
{
text: "Live and results shows the grid editor and every standings table while the race is running.",
async action({ click, scrollTo }) { await click('[data-manage-tab="live"]'); await scrollTo('[data-manage-panel="live"]'); },
},
{
text: "Schedule and print lets you set a start time, see the whole day's running order and print start lists.",
async action({ click, scrollTo }) { await click('[data-manage-tab="schedule"]'); await scrollTo('[data-manage-panel="schedule"]'); },
},
{
text: "And Participants and teams, where we started, is for choosing who races.",
async action({ click, scrollTo }) { await click('[data-manage-tab="setup"]'); await scrollTo('[data-manage-panel="setup"]'); },
},
{
text: "The Open Grid button on any session jumps straight to its grid editor on the Live tab.",
async action({ click, scrollTo, pause: pauseFn }) {
await scrollTo("#session-grid-vid_quali", "center");
await pauseFn(500);
await click("#session-grid-vid_quali");
await pauseFn(300);
await scrollTo('[data-manage-panel="live"]');
},
},
],
},
"event-schedule": {
seedState(state) {
const classId = "vid_sched_class";
const driverA = { id: "vid_sched_driver_a", name: "Alex Karlsson", classId, transponder: "7920001" };
const raceEvent = {
id: "vid_sched_event", name: "Club Race Night", classId, mode: "race",
raceConfig: { participantsConfigured: true, driverIds: [driverA.id], teams: [] },
};
const practice = { id: "vid_sched_practice", eventId: raceEvent.id, name: "Practice 1", type: "practice", durationMin: 10, status: "ready" };
const qualifying = { id: "vid_sched_quali", eventId: raceEvent.id, name: "Qualifying 1", type: "qualification", durationMin: 5, status: "ready" };
state.classes.push({ id: classId, name: "2WD Buggy" });
state.drivers.push(driverA);
state.events.push(raceEvent);
state.sessions.push(practice, qualifying);
},
async setup({ navigate, click, evaluate, scrollTo }) {
await navigate("race_setup", "raceWizardStepForm");
await click("#event-manage-vid_sched_event");
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".manage-tabs")`)), "manage tabs rendered");
await scrollTo(".manage-tabs");
},
steps: [
{
text: "Let's set up a time-based schedule for race day.",
async action({ click, scrollTo }) { await click('[data-manage-tab="schedule"]'); await scrollTo("#scheduleForm"); },
},
{
text: "Enter a start time, and the gap you want between sessions, in minutes.",
async action({ fill }) { await fill("scheduleForm", { scheduleStartAt: "2026-09-12T12:30", scheduleGapMin: "3" }); },
},
{
text: "Save it, and RaceCore works out every session's planned clock time automatically.",
async action({ evaluate, scrollTo, pause: pauseFn }) {
await evaluate(`document.getElementById("scheduleForm").requestSubmit()`);
await pauseFn(500);
await scrollTo('[data-manage-panel="schedule"] table');
},
},
{ text: "If a session starts late or runs long, everything after it shifts forward on its own." },
],
},
"connect-decoder": {
async prepare() {
// A real AMMC decoder isn't available here - a socket that completes only the
// WebSocket handshake is enough to exercise the app's real connect path end to end
// (src/decoder_runtime.js doesn't need decoder frames to reach "connected").
const decoder = await startFakeDecoder();
return {
seedState(state) {
state.settings.wsUrl = `ws://127.0.0.1:${decoder.port}`;
state.settings.autoReconnect = true;
},
teardown: () => decoder.close(),
extra: { decoder },
};
},
async setup({ navigate }) {
await navigate("settings", "settingsForm");
},
steps: [
{ text: "This is the Connection tab, where you link RaceCore to your race timing decoder." },
{
text: "Enter the decoder's address, then click Connect now.",
async action({ click, evaluate }) {
await click("#settingsConnect");
await waitFor(async () => await evaluate('document.getElementById("connectionBadge")?.classList.contains("badge-online")'), "decoder connects");
},
},
{ text: "Once connected, the badge in the sidebar turns green and shows Decoder Online." },
{
text: "If the connection ever drops, RaceCore automatically reconnects for you.",
async action({ decoder, evaluate }) {
decoder.dropConnections();
await waitFor(async () => (await evaluate('document.getElementById("connectionBadge")?.classList.contains("badge-online")')) === false, "badge goes offline after drop");
},
},
],
},
"add-drivers-cars": {
async setup({ navigate }) {
await navigate("classes", "classForm");
},
steps: [
{ text: "Every driver and car belongs to a class - let's start there." },
{
text: "Give the class a name, like 2WD Buggy, and save it.",
async action({ fill, evaluate }) {
await fill("classForm", { name: "2WD Buggy" });
await evaluate('document.getElementById("classForm").requestSubmit()');
},
},
{
text: "Switch to Drivers to register your racers.",
async action({ clickNav }) { await clickNav("Drivers"); },
},
{
text: "Give them a name, pick their class, and enter their transponder number.",
async action({ fill, evaluate, state }) {
const classId = (await state()).classes.find((item) => item.name === "2WD Buggy")?.id;
await fill("driverForm", { name: "Alex Karlsson", classId, transponder: "7930001" });
await evaluate('document.getElementById("driverForm").requestSubmit()');
},
},
{ text: "One person can race in several classes on the same transponder. Within one class a transponder can only be used once, because the decoder could not tell the laps apart." },
{
text: "Entered someone twice? Edit one of them and open Merge with another driver.",
async action({ fill, evaluate, state, click }) {
const classId = (await state()).classes.find((item) => item.name === "2WD Buggy")?.id;
await fill("driverForm", { name: "Alex Karlsson", classId, transponder: "7930009" });
await evaluate('document.getElementById("driverForm").requestSubmit()');
let copy;
await waitFor(async () => { copy = (await state()).drivers.find((item) => item.transponder === "7930009"); return copy; }, "second entry saved");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("driver-edit-${copy.id}")`)), "second entry listed");
await click(`#driver-edit-${copy.id}`);
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".driver-merge")`)), "edit window");
await evaluate(`(() => { const box = document.querySelector(".driver-merge"); box.open = true; const select = document.getElementById("driverMergeTarget"); select.value = select.options[1]?.value || ""; box.scrollIntoView({ block: "center" }); })()`);
},
},
{
text: "Pick the driver to keep and merge. Heats, laps, results, series points and training laps all move over, and the duplicate is gone.",
async action({ click }) { await click("#driverMergeGo"); },
},
{
text: "And Cars, if you want to track a car separately from its driver.",
async action({ clickNav }) { await clickNav("Cars"); },
},
{
text: "Same idea - a name and a transponder number.",
async action({ fill, evaluate }) {
await fill("carForm", { name: "Red Buggy #7", transponder: "7930002" });
await evaluate('document.getElementById("carForm").requestSubmit()');
},
},
],
},
"create-race": {
seedState(state) {
const classId = "vid_wizard_class";
state.classes.push({ id: classId, name: "2WD Buggy" }, { id: "vid_wizard_4wd", name: "4WD Buggy" });
["Alex Karlsson", "Sam Nilsson", "Jamie Lee", "Robin Berg"].forEach((name, index) => {
state.drivers.push({ id: `vid_wizard_driver_${index}`, name, classId, transponder: `794000${index}` });
});
["Kim Holm", "Noa Ek"].forEach((name, index) => {
state.drivers.push({ id: `vid_wizard_4wd_${index}`, name, classId: "vid_wizard_4wd", transponder: `794100${index}` });
});
},
async setup({ navigate }) {
await navigate("race_setup", "raceWizardStepForm");
},
steps: [
{ text: "Creating a race has four steps. Let's start with the basics: name, date, and class. A race can also be fetched from House of RC with the house button." },
{
text: "Give the race a name and pick a class. Whole race days come as presets: EFRA off-road, touring, nitro, ROAR, a quick club day or rookies. The text under the choice says what it sets.",
async action({ fill, evaluate }) {
await fill("raceWizardStepForm", { name: "Friday Night Race", date: "2026-11-20", classId: "vid_wizard_class" });
await evaluate(`(() => { const select = document.querySelector('#raceWizardStepForm [name="presetId"]'); select.value = "efra_offroad"; select.dispatchEvent(new Event("change", { bubbles: true })); })()`);
},
},
{
text: "Continue to the drivers. They are grouped by class, with All and None per class, a search on name or transponder, and Same drivers as, to copy an earlier race.",
async action({ click }) { await click("#raceWizardNext"); },
},
{
text: "Tick the whole class with All, then move on.",
async action({ click, evaluate }) {
await evaluate(`document.querySelector('[data-picker-group="vid_wizard_class"] [data-picker-group-all]')?.click() ?? document.querySelector("[data-picker-group-all]")?.click()`);
await pause(700);
await click("#raceWizardNext");
},
},
{ text: "The session plan is generated from your preset - practice, qualifying, and finals - ready to fine-tune." },
{
text: "One more click to confirm everything.",
async action({ click }) { await click("#raceWizardNext"); },
},
{
text: "And the race is created, ready to manage.",
async action({ click }) { await click("#raceWizardCreate"); },
},
],
},
"run-a-session": {
async prepare() {
const decoder = await startFakeDecoder();
return {
seedState(state) {
const classId = "vid_run_class";
const driverA = { id: "vid_run_driver_a", name: "Alex Karlsson", classId, transponder: "7950001" };
const driverB = { id: "vid_run_driver_b", name: "Sam Nilsson", classId, transponder: "7950002" };
const raceEvent = { id: "vid_run_event", name: "Friday Night Race", classId, mode: "race", raceConfig: { minLapMs: 3000, maxLapMs: 60000 } };
const session = { id: "vid_run_session", eventId: raceEvent.id, name: "Heat 1", type: "heat", durationMin: 3, status: "ready" };
state.classes.push({ id: classId, name: "2WD Buggy" });
state.drivers.push(driverA, driverB);
state.events.push(raceEvent);
state.sessions.push(session);
state.activeSessionId = session.id;
state.settings.wsUrl = `ws://127.0.0.1:${decoder.port}`;
state.settings.autoReconnect = true;
// A real countdown+start-lights sequence (not the instant-start practice
// shortcut), sped up just enough to keep the clip short, with every event's own
// sound silenced so nothing tries to play audio in headless Chrome.
state.settings.raceAudio = {
...state.settings.raceAudio,
enabled: true, muted: false, startLights: true, lightIntervalMs: 150,
randomStartDelay: false, minStartDelay: 0, maxStartDelay: 0,
startCountdownSeconds: 5, events: SILENCED_EVENTS,
};
},
teardown: () => decoder.close(),
};
},
async setup({ navigate, evaluate }) {
await navigate("race_day", "raceDayStart");
await waitFor(async () => await evaluate('document.getElementById("connectionBadge")?.classList.contains("badge-online")'), "decoder connected");
await waitFor(async () => (await evaluate('document.getElementById("raceDayStart")?.disabled')) === false, "start enabled once preflight is ready");
},
steps: [
{ text: "This is Race Day, where every session is run. The green bar says this computer is the Race Controller Master: it runs the decoder, and other screens only follow." },
{
text: "Pick a count-down - here thirty seconds - and press Start. The track opens and the announcer calls the time.",
async action({ evaluate, click }) {
await evaluate(`document.getElementById("raceDayPrologueLength").value = "30"`);
await click("#raceDayStart");
},
},
{
text: "Cars on the grid? Jump to the last ten seconds, or hold the count-down while they line up.",
async action({ click }) { await click('[data-prologue="to10"]'); },
},
{
text: "At three seconds the start lights take over, and the heat starts by itself.",
async action({ evaluate }) {
await waitFor(async () => Boolean(await evaluate('document.getElementById("raceDayPause")')), "heat running", 20000);
},
},
{
text: "Pause any time - lap timing stops without losing the session.",
async action({ click }) { await click("#raceDayPause"); },
},
{
text: "Resume picks up right where you left off.",
async action({ evaluate, click }) {
await waitFor(async () => Boolean(await evaluate('document.getElementById("raceDayResume")')), "paused");
await click("#raceDayResume");
},
},
{
text: "And Finish locks in the results for this session.",
async action({ evaluate, click }) {
await waitFor(async () => Boolean(await evaluate('document.getElementById("raceDayFinish")')), "running again");
await click("#raceDayFinish");
},
},
{
text: "Timing is for following: the leaderboard and lap-by-lap results.",
async action({ click }) { await click("#raceDayTiming"); },
},
],
},
"sponsor-event": {
seedState(state) {
state.cars.push(
{ id: "vid_sp_car1", name: "Rental 1", transponder: "7960001" },
{ id: "vid_sp_car2", name: "Rental 2", transponder: "7960002" },
);
state.events.push({ id: "vid_sp_event", name: "Company Day", date: "2026-09-19", mode: "track", sponsor: {}, raceConfig: {} });
},
async setup({ navigate, click, evaluate, scrollTo }) {
await navigate("events", "eventForm");
await click("#event-manage-vid_sp_event");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("sponsorSetupForm")`)), "sponsor setup");
await scrollTo("#sponsorSetupForm", "center");
},
steps: [
{ text: "A sponsor event is set up in three steps, at the top of Manage: guests, cars and format." },
{
text: "Paste the guests' names, one per line. They are not added to the club's driver list.",
async action({ evaluate }) {
await evaluate(`(() => { const area = document.querySelector("#sponsorSetupForm textarea[name=guests]"); area.value = "Anna\\nBosse\\nCissi\\nDavid\\nEmma\\nFilip"; area.dispatchEvent(new Event("input", { bubbles: true })); })()`);
},
},
{
text: "Tick the rental cars, or add a new one with its transponder.",
async action({ evaluate, fill, click }) {
await evaluate(`document.querySelectorAll("#sponsorSetupForm input[name=car]").forEach((box) => { if (!box.checked) box.click(); })`);
await fill("sponsorSetupForm", { newCarName: "Rental 3", newCarTp: "7960003" });
await click("#sponsorAddCar");
},
},
{
text: "Create the heats: practice and qualifying in groups, and the drivers swap cars between rounds.",
async action({ evaluate, scrollTo, pause: pauseFn }) {
await waitFor(async () => (await evaluate(`document.querySelectorAll("#sponsorSetupForm input[name=car]:checked").length`)) === 3, "three cars ticked");
await evaluate(`(() => { const area = document.querySelector("#sponsorSetupForm textarea[name=guests]"); if (!area.value.trim()) area.value = "Anna\\nBosse\\nCissi\\nDavid\\nEmma\\nFilip"; document.getElementById("sponsorSetupForm").requestSubmit(); })()`);
await pauseFn(700);
await scrollTo("#manage-session-plan");
},
},
{ text: "When qualifying is done, one click creates the finals. Everything is then run from Race Day." },
],
},
"team-race": {
seedState(state) {
const classId = "vid_team_class";
state.classes.push({ id: classId, name: "1:10 Touring" });
const names = ["Alex Karlsson", "Sam Nilsson", "Jamie Lee", "Robin Berg", "Kim Ek", "Charlie Lund"];
names.forEach((name, index) => state.drivers.push({ id: `vid_team_driver_${index}`, name, classId, transponder: `797000${index}` }));
["Team car red", "Team car blue", "Team car green"].forEach((name, index) => state.cars.push({ id: `vid_team_car_${index}`, name, transponder: `797100${index}` }));
state.events.push({
id: "vid_team_event", name: "Endurance Night", classId, mode: "race",
raceConfig: { presetId: "endurance", participantsConfigured: true, driverIds: names.map((_, index) => `vid_team_driver_${index}`), teams: [] },
});
},
async setup({ navigate, click, evaluate, scrollTo }) {
await navigate("race_setup", "raceWizardStepForm");
await click("#event-manage-vid_team_event");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("teamSetupSplit")`)), "team setup");
await scrollTo("#manage-setup-teams");
},
steps: [
{ text: "A team race is set up in three steps: teams, cars, and the length of the race." },
{
text: "Choose how many teams, and split the drivers. Names and drivers can be changed by hand.",
async action({ evaluate, click }) {
await evaluate(`document.getElementById("teamSetupCount").value = "3"`);
await click("#teamSetupSplit");
await waitFor(async () => (await evaluate(`document.querySelectorAll(".team-setup-card").length`)) === 3, "three teams");
},
},
{
text: "Give each team its car. The car's transponder counts for every driver on the team.",
async action({ evaluate, pause: pauseFn }) {
for (let index = 0; index < 3; index += 1) {
await evaluate(`(() => { const select = document.querySelectorAll("[data-team-car]")[${index}]; select.value = "vid_team_car_${index}"; select.dispatchEvent(new Event("change")); })()`);
await pauseFn(500);
}
},
},
{
text: "Pick the length, here four hours. The checks below show anything that would stop the start.",
async action({ click, scrollTo }) {
await click('[data-team-length="240"]');
await scrollTo("#teamSetupCreate", "center");
},
},
{
text: "Create the team race. Teams can still be changed while it runs, if a transponder or a car has to be swapped.",
async action({ click, scrollTo }) { await click("#teamSetupCreate"); await pause(400); await scrollTo("#teamSetupLength", "center"); },
},
],
},
"practice-ranking": {
seedState(state) {
const startedAt = Date.now() - 600000;
const event = { id: "vid_rank_event", name: "Thursday Practice", date: new Date().toISOString().slice(0, 10), classId: "", mode: "race", raceConfig: { practiceOnly: true } };
const practice = { id: "vid_rank_practice", eventId: event.id, name: "Open Practice", type: "open_practice", durationMin: 600, status: "running", startedAt };
const drivers = [["Alex Karlsson", [16900, 24500, 23800, 24100]], ["Sam Nilsson", [17600, 17700, 17650, 17800]], ["Jamie Lee", [18200, 18100, 18300, 18000]], ["Robin Berg", [17300, 21000, 19500, 22000]]];
const passings = [];
const competitors = {};
drivers.forEach(([name, lapTimes], index) => {
const id = `vid_rank_driver_${index}`;
const tp = `798000${index}`;
state.drivers.push({ id, name, classId: "", transponder: tp });
let ts = startedAt + 4000 + index * 900;
passings.push({ driverId: id, driverName: name, competitorKey: id, transponder: tp, lapMs: 0, timestamp: ts, validLap: true });
lapTimes.forEach((lapMs) => { ts += lapMs; passings.push({ driverId: id, driverName: name, competitorKey: id, transponder: tp, lapMs, timestamp: ts, validLap: true }); });
competitors[id] = { key: id, driverId: id, driverName: name, transponder: tp, laps: lapTimes.length, bestLapMs: Math.min(...lapTimes), lastLapMs: lapTimes.at(-1), startTimestamp: startedAt };
});
state.events.push(event);
state.sessions.push(practice);
state.resultsBySession[practice.id] = { passings: passings.sort((a, b) => a.timestamp - b.timestamp), competitors };
state.activeSessionId = practice.id;
},
async setup({ navigate }) {
await navigate("overlay", "overlayFullscreen");
},
steps: [
{ text: "Open practice ranks drivers by their single best lap. One lucky lap puts you on top." },
{
text: "In Race Setup, the practice's Settings button lets you change that.",
async action({ navigate, evaluate, scrollTo }) {
await navigate("race_setup", "raceWizardStepForm");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("event-edit-vid_rank_event")`)), "practice in the list");
await scrollTo("#event-edit-vid_rank_event", "center");
},
},
{
text: "Rank by the best three laps in a row, or the most laps in a set number of minutes. The lap time window is here too.",
async action({ click, evaluate }) {
await click("#event-edit-vid_rank_event");
await waitFor(async () => Boolean(await evaluate(`document.querySelector('#eventEditForm [name="practiceRanking"]')`)), "settings window");
await evaluate(`(() => { const form = document.getElementById("eventEditForm"); form.elements.practiceRanking.value = "consecutive"; form.elements.practiceRanking.dispatchEvent(new Event("change", { bubbles: true })); form.elements.practiceRankLaps.value = "3"; })()`);
},
},
{
text: "Save, and the results and the overlay follow at once. Now the steadiest driver leads.",
async action({ evaluate, clickNav }) {
await evaluate(`(() => { const form = document.getElementById("eventEditForm"); if (!form.elements.date.value) form.elements.date.value = "2026-09-17"; form.requestSubmit(); })()`);
await pause(600);
await clickNav("Overlay");
},
},
],
},
"race-overview": {
seedState(state) {
const classId = "vid_ov_class";
state.classes.push({ id: classId, name: "2WD Buggy" });
const names = ["Alex Karlsson", "Sam Nilsson", "Jamie Lee", "Robin Berg"];
const ids = names.map((name, index) => { const id = `vid_ov_driver_${index}`; state.drivers.push({ id, name, classId, transponder: `799000${index}` }); return id; });
const dayStart = Date.now() - 4 * 3600000;
const date = new Date(dayStart).toISOString().slice(0, 10);
const event = { id: "vid_ov_event", name: "Club Race Night", date, classId, mode: "race", raceConfig: { participantsConfigured: true, driverIds: ids } };
state.events.push(event);
// Each heat: who finished where; every lap is a passing, so the lap chart has places to
// draw (the drivers swap places along the way).
const heats = [
["vid_ov_p1", "Practice 1", "practice", [2, 0, 1, 3]],
["vid_ov_q1", "Q1 H1", "qualification", [0, 2, 1, 3]],
["vid_ov_q2", "Q2 H1", "qualification", [0, 1, 2, 3]],
["vid_ov_a", "A Final", "final", [1, 0, 2, 3]],
];
heats.forEach(([id, name, type, order], heatIndex) => {
const startedAt = dayStart + heatIndex * 1800000;
state.sessions.push({ id, eventId: event.id, name, type, durationMin: 5, status: "finished", startedAt, endedAt: startedAt + 310000, driverIds: ids });
const competitors = {};
const passings = [];
order.forEach((driverIndex, place) => {
const key = ids[driverIndex];
const laps = 17 - place;
let ts = startedAt;
let best = Infinity;
for (let lap = 1; lap <= laps; lap += 1) {
// Early laps favour the drivers at the back, so the order changes before it settles.
const lapMs = Math.round(17600 + place * 260 + Math.sin(lap * 1.7 + driverIndex) * 650 - (lap < 6 ? (3 - place) * -180 : 0));
ts += lapMs;
best = Math.min(best, lapMs);
passings.push({ driverId: key, driverName: names[driverIndex], competitorKey: key, transponder: `799000${driverIndex}`, lapMs, timestamp: ts, validLap: true });
}
competitors[key] = { key, driverId: key, driverName: names[driverIndex], displayName: names[driverIndex], transponder: `799000${driverIndex}`, laps, bestLapMs: best, lastLapMs: 18000, startTimestamp: startedAt, lastTimestamp: ts };
});
state.resultsBySession[id] = { passings: passings.sort((a, b) => a.timestamp - b.timestamp), adjustments: [], competitors };
});
state.activeSessionId = "vid_ov_a";
},
async setup({ navigate, scrollTo }) {
await navigate("race_day", "raceDayOverview");
await scrollTo("#raceDayOverview");
},
steps: [
{ text: "When a race is run, Race Day shows the whole race in one place: the podium, then practice, qualifying and finals." },
{
text: "Open a part to see its standings, and every heat with laps, result and best lap.",
async action({ evaluate }) { await evaluate(`document.querySelector('.race-overview-phase[data-phase="qualification"]')?.setAttribute("open", "")`); },
},
{
text: "Every qualifying heat and final has a lap chart: each driver's place after every lap.",
async action({ evaluate }) {
await evaluate(`(() => { document.querySelector('.race-overview-phase[data-phase="qualification"]')?.removeAttribute("open"); const final = document.querySelector('.race-overview-phase[data-phase="final"]'); final?.setAttribute("open", ""); const chart = final?.querySelector(".lap-chart-box"); if (chart) { chart.open = true; chart.scrollIntoView({ block: "end" }); } })()`);
},
},
{
text: "Print it, or export the whole race as PDF or CSV. The chart is in the print too.",
async action({ scrollTo }) { await scrollTo("#raceDayOverview"); },
},
{
text: "The results archive is sorted by race. Pick one, and the same overview and export are there.",
async action({ clickNav, evaluate, click, scrollTo }) {
await clickNav("Results archive");
await waitFor(async () => Boolean(await evaluate(`document.querySelector('[data-archive-event="vid_ov_event"]')`)), "race in the archive");
await click('[data-archive-event="vid_ov_event"]');
await pause(500);
await scrollTo("#archiveEventClose", "center");
},
},
{
text: "Pick one date in From and To, and CSV for the race day gives every lap of that day, with a summary per heat, ready for Excel.",
async action({ evaluate, scrollTo }) {
const date = await evaluate(`document.querySelector('[data-archive-event="vid_ov_event"]')?.closest("tr")?.children[0]?.textContent.trim()`);
for (const id of ["archiveDateFrom", "archiveDateTo"]) {
await evaluate(`(() => { const input = document.getElementById("${id}"); input.value = ${JSON.stringify(date)}; input.dispatchEvent(new Event("change")); })()`);
await pause(200);
}
await scrollTo("#archiveDayCsv", "center");
},
},
],
},
// A cup day: the series hub, check-in, protected heats, a duplicate fixed in the standings and
// the day's CSV. Round 1's results sit on a driver entry that was deleted afterwards, so Sam
// shows on two rows until the row is linked.
"cup-day": {
seedState(state) {
const classId = "vid_cup_class";
state.classes.push({ id: classId, name: "2WD Buggy" });
const people = [["vid_cup_alex", "Alex Karlsson"], ["vid_cup_sam", "Sam Nilsson"], ["vid_cup_jamie", "Jamie Lee"], ["vid_cup_robin", "Robin Berg"], ["vid_cup_kim", "Kim Holm"]];
people.forEach(([id, name], index) => state.drivers.push({ id, name, classId, transponder: `797100${index}` }));
const today = new Date().toISOString().slice(0, 10);
const round = (eventId, date, samId, startedAt, orderQ, orderA) => {
const ids = people.map(([id]) => (id === "vid_cup_sam" ? samId : id));
state.events.push({ id: eventId, name: `Winter Cup 2WD`, date, classId, mode: "race", raceConfig: { participantsConfigured: true, driverIds: ids, ...(date === today ? { checkIn: { vid_cup_alex: { present: true, paid: true }, vid_cup_sam: { present: true, paid: false }, vid_cup_jamie: { present: true, paid: true } } } : {}) } });
[["q1", "Q1 H1", "qualification", orderQ, 0], ["a1", "A Final 1", "final", orderA, 1800000]].forEach(([suffix, name, type, order, offset]) => {
const id = `${eventId}_${suffix}`;
const start = startedAt + offset;
state.sessions.push({ id, eventId, name, type, generated: true, durationMin: 5, status: "finished", startedAt: start, endedAt: start + 310000, driverIds: ids });
const competitors = {};
const passings = [];
order.forEach((index, place) => {
const key = ids[index];
const laps = 17 - place;
// Every lap as a passing: the series only scores drivers with a registered lap.
for (let lap = 1; lap <= laps; lap += 1) passings.push({ driverId: key, driverName: people[index][1], competitorKey: key, transponder: `797100${index}`, lapMs: 17600 + place * 210, timestamp: start + lap * (17600 + place * 210), validLap: true });
competitors[key] = { key, driverId: key, driverName: people[index][1], displayName: people[index][1], transponder: `797100${index}`, laps, bestLapMs: 17200 + place * 210, lastLapMs: 18000, startTimestamp: start, lastTimestamp: start + laps * (17600 + place * 210) };
});
state.resultsBySession[id] = { passings: passings.sort((a, b) => a.timestamp - b.timestamp), adjustments: [], competitors };
});
};
round("vid_cup_r1", "2026-11-01", "vid_cup_sam_old", Date.now() - 14 * 86400000, [1, 0, 2, 3, 4], [1, 0, 2, 3, 4]);
round("vid_cup_r2", today, "vid_cup_sam", Date.now() - 3 * 3600000, [0, 1, 2, 4, 3], [0, 1, 2, 4, 3]);
state.series = [{ id: "vid_cup_series", name: "Winter Cup", classIds: [classId], eventIds: ["vid_cup_r1", "vid_cup_r2"] }];
},
async setup({ navigate, evaluate }) {
await navigate("series", "seriesNew");
await waitFor(async () => Boolean(await evaluate(`document.querySelector('[data-round="vid_cup_r2"]')`)), "rounds listed");
},
steps: [
{ text: "A cup runs from the series page: the rounds, and each class's standings. Each round has one button for its next step - seeding, qualifying, then the finals." },
{
text: "In the morning, open the race and use Check-in: present and paid, and whether the transponder has been seen on the decoder today.",
async action({ click, evaluate, clickNav }) {
await clickNav("Race Setup");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("event-manage-vid_cup_r2")`)), "race listed");
await click("#event-manage-vid_cup_r2");
await waitFor(async () => Boolean(await evaluate(`document.querySelector('[data-manage-tab="checkin"]')`)), "manage race");
await click('[data-manage-tab="checkin"]');
await pause(400);
await evaluate(`document.querySelector('[data-manage-tab="checkin"]')?.scrollIntoView({ block: "start" })`);
},
},
{ text: "Remove no-shows before qualifying starts, and print the list. Without a check-in everyone simply counts as present." },
{
text: "Heats that have run are protected. Making qualifying or finals again is refused until you clear them, and clearing names the heats and asks first.",
async action({ click, evaluate }) {
await click('[data-manage-tab="live"]');
await pause(400);
await evaluate(`document.querySelector('[data-manage-tab="live"]')?.scrollIntoView({ block: "start" })`);
},
},
{
text: "Back in the series, Sam is on two rows: a duplicate entry was deleted after round one, and its points stayed behind.",
async action({ clickNav, evaluate }) {
await clickNav("Series / cup");
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".series-link-driver")`)), "link picker");
await evaluate(`document.querySelector(".series-link-driver").scrollIntoView({ block: "center" })`);
},
},
{
text: "Pick the right driver in the link box, and the two rows become one.",
async action({ evaluate }) {
await evaluate(`(() => { const select = document.querySelector(".series-link-driver"); select.value = "vid_cup_sam"; select.dispatchEvent(new Event("change", { bubbles: true })); })()`);
await pause(800);
await evaluate(`document.querySelector(".series-standings, .series-rounds-table")?.scrollIntoView({ block: "center" })`);
},
},
{
text: "And the page button on a round downloads the day's CSV: a summary per heat and every lap, ready for Excel.",
async action({ evaluate }) {
await evaluate(`document.querySelector('[data-round="vid_cup_r2"] [data-round-action="day_csv"]')?.scrollIntoView({ block: "center" })`);
},
},
],
},
// The driver's own page: Training stats, then the mobile profile (Standard and Pro) shown in a
// phone-sized frame, with "My race today" from a race day in progress.
"driver-page": {
seedState(state) {
const classId = "vid_dp_class";
state.classes.push({ id: classId, name: "2WD Buggy" });
const people = [["vid_dp_alex", "Alex Karlsson"], ["vid_dp_sam", "Sam Nilsson"], ["vid_dp_jamie", "Jamie Lee"], ["vid_dp_robin", "Robin Berg"]];
people.forEach(([id, name], index) => state.drivers.push({ id, name, classId, transponder: `797200${index}` }));
const today = new Date().toISOString().slice(0, 10);
// This morning's open practice: two stints for Alex, a few laps for the others.
const practiceStart = Date.now() - 3 * 3600000;
const event = { id: "vid_dp_practice", name: "Open Practice", date: today, classId: "", mode: "race", raceConfig: { practiceOnly: true } };
const practice = { id: "vid_dp_open", eventId: event.id, name: "Open Practice", type: "open_practice", durationMin: 600, status: "finished", startedAt: practiceStart, endedAt: practiceStart + 3600000 };
const passings = [];
const competitors = {};
people.forEach(([id, name], index) => {
const tp = `797200${index}`;
let ts = practiceStart + 60000 + index * 7000;
let laps = 0;
let best = Infinity;
const stints = index === 0 ? [18, 22] : [12];
stints.forEach((count, stint) => {
if (stint) ts += 6 * 60000;
passings.push({ driverId: id, driverName: name, competitorKey: id, transponder: tp, lapMs: 0, timestamp: ts, validLap: true });
for (let lap = 0; lap < count; lap += 1) {
const lapMs = Math.round(17300 + index * 250 - stint * 240 + Math.sin(lap * 1.3 + index) * 420);
ts += lapMs; laps += 1; best = Math.min(best, lapMs);
passings.push({ driverId: id, driverName: name, competitorKey: id, transponder: tp, lapMs, timestamp: ts, validLap: true });
}
});
competitors[id] = { key: id, driverId: id, driverName: name, transponder: tp, laps, bestLapMs: best, lastLapMs: 17800, startTimestamp: practiceStart };
});
state.events.push(event);
state.sessions.push(practice);
state.resultsBySession[practice.id] = { passings: passings.sort((a, b) => a.timestamp - b.timestamp), competitors };
// This afternoon's race: Q1 run, Q2 and the final still to come.
const ids = people.map(([id]) => id);
const race = { id: "vid_dp_race", name: "Club Race", date: today, classId, mode: "race", raceConfig: { participantsConfigured: true, driverIds: ids } };
state.events.push(race);
const q1Start = Date.now() - 40 * 60000;
state.sessions.push(
{ id: "vid_dp_q1", eventId: race.id, name: "Q1 H1", type: "qualification", durationMin: 5, status: "finished", startedAt: q1Start, endedAt: q1Start + 310000, driverIds: ids },
{ id: "vid_dp_q2", eventId: race.id, name: "Q2 H1", type: "qualification", durationMin: 5, status: "ready", driverIds: ids },
{ id: "vid_dp_a1", eventId: race.id, name: "A Final", type: "final", durationMin: 5, status: "ready", driverIds: ids },
);
state.resultsBySession.vid_dp_q1 = { passings: [], adjustments: [], competitors: Object.fromEntries(people.map(([id, name], place) => [id, { key: id, driverId: id, driverName: name, displayName: name, transponder: `797200${place}`, laps: 17 - place, bestLapMs: 17150 + place * 220, lastLapMs: 18000, startTimestamp: q1Start, lastTimestamp: q1Start + 300000 + place * 800 }])) };
},
async setup({ navigate }) {
await navigate("training&driver=vid_dp_alex", "trainingGoalsSharing");
},
steps: [
{ text: "Training stats follow every driver: total laps, practice days, personal best, consistency, the next goal, and today's session." },
{
text: "More stats has the stints, pace per half hour, splits and set-up changes. In the stint cards, the stint's fastest lap is green and the day's fastest is purple.",
async action({ evaluate }) {
await evaluate(`(() => { const more = document.getElementById("trainingMoreStats"); if (more) { more.open = true; more.scrollIntoView({ block: "start" }); } })()`);
},
},
{
text: "Under Goals and mobile profile, enable the driver's own page. The driver scans the QR code once, and has it on the phone. No account is needed.",
async action({ evaluate }) {
await evaluate(`(() => { const more = document.getElementById("trainingMoreStats"); if (more) more.open = false; const box = document.getElementById("trainingGoalsSharing"); box.open = true; document.getElementById("trainingPublicProfileEnable")?.click(); })()`);
await waitFor(async () => Boolean(await evaluate(`document.querySelector(".training-profile-qr img")`)), "QR code");
await pause(500);
await evaluate(`document.querySelector(".training-profile-qr")?.scrollIntoView({ block: "center" })`);
},
},
{
text: "This is the phone. On a race day, My race today sits at the top: the next heat, with its time and grid place, marshal duties, and today's results.",
async action({ send, evaluate, state }) {
const origin = await evaluate("location.origin");
let token = "";
await waitFor(async () => { token = ((await state()).training?.shares || []).find((share) => share.enabled !== false)?.token || ""; return token; }, "profile saved");
// The race controller posts today's schedule every 15 s; make sure the phone has it.
const hasRaceToday = async () => Boolean((await (await fetch(`${origin}/public-training/api/${token}`)).json()).raceToday);
try { await waitFor(hasRaceToday, "my race today", 20000); } catch {
// No schedule posted (no first start set for today): post the same small snapshot the
// race controller would - ids only.
const now = Date.now();
const ids = ["vid_dp_alex", "vid_dp_sam", "vid_dp_jamie", "vid_dp_robin"];
await fetch(`${origin}/api/public-race-day`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ date: new Date(now - new Date(now).getTimezoneOffset() * 60000).toISOString().slice(0, 10), sessions: [
{ id: "vid_dp_q1", label: "2WD Buggy · Q1 H1", start: now - 40 * 60000, state: "done", entries: ids, results: ids.map((driverId, index) => ({ driverId, position: index + 1, laps: 17 - index, result: `${17 - index} laps` })) },
{ id: "vid_dp_q2", label: "2WD Buggy · Q2 H1", start: now + 12 * 60000, state: "upcoming", gridStart: true, entries: ["vid_dp_sam", "vid_dp_alex", "vid_dp_jamie", "vid_dp_robin"] },
{ id: "vid_dp_open2", label: "4WD Buggy · Q2 H1", start: now + 20 * 60000, state: "upcoming", entries: [], marshals: ["vid_dp_alex"] },
{ id: "vid_dp_a1", label: "2WD Buggy · A Final", start: now + 75 * 60000, state: "upcoming", gridStart: true, entries: ids },
] }) });
await waitFor(hasRaceToday, "my race today (posted)", 10000);
}
const phone = (mode) => `${origin}/public-training/${token}?lang=en&mode=${mode}`;
const page = `<!doctype html><html><body style="margin:0;height:100vh;display:flex;align-items:center;justify-content:center;gap:48px;background:#10151c;font:600 22px system-ui;color:#cfd8e3">
<div style="max-width:420px;line-height:1.5">${"Alex's own page"}<br><small style="font-weight:400;color:#8a97a8">Scanned once from the QR code</small></div>
<iframe id="phone" src="${phone("standard")}" style="width:400px;height:820px;border:12px solid #2a323d;border-radius:36px;background:#fff"></iframe></body></html>`;
// A plain page from the same server (its 404), filled with the phone frame - Chrome
// won't load the local server inside a data: page.
await send("Page.navigate", { url: `${origin}/phone-frame` });
await pause(800);
await evaluate(`document.open(); document.write(${JSON.stringify(page)}); document.close();`);
await pause(3500);
},
},
{
text: "Standard shows everything: goals, challenges, guided exercises and a timer for a practice session.",
},
{
text: "Pro is a clean practice view: today's laps, stints, drive time, best and average lap, and the stint cards. The phone remembers the choice.",
async action({ evaluate }) {
await evaluate(`(() => { const frame = document.getElementById("phone"); frame.src = frame.src.replace("mode=standard", "mode=pro"); })()`);
await pause(2500);
},
},
{ text: "Only the driver's own numbers are sent to the phone. Contact details and other drivers' data never are." },
],
},
judging: {
seedState(state) {
const classId = "vid_judge_class";
state.classes.push({ id: classId, name: "2WD Buggy" });
const names = ["Alex Karlsson", "Sam Nilsson", "Jamie Lee"];
const ids = names.map((name, index) => { const id = `vid_judge_driver_${index}`; state.drivers.push({ id, name, classId, transponder: `796100${index}` }); return id; });
const event = { id: "vid_judge_event", name: "Club Race Night", classId, mode: "race", raceConfig: { participantsConfigured: true, driverIds: ids } };
state.events.push(event);
const now = Date.now();
const qualiStart = now - 1800000;
const heatStart = now - 90000;
state.sessions.push(
{ id: "vid_judge_q1", eventId: event.id, name: "Q1 H1", type: "qualification", durationMin: 5, status: "finished", startedAt: qualiStart, endedAt: qualiStart + 305000, driverIds: ids },
{ id: "vid_judge_q2", eventId: event.id, name: "Q2 H1", type: "qualification", durationMin: 5, status: "running", startedAt: heatStart, driverIds: ids },
);
const competitors = (startedAt, laps) => Object.fromEntries(ids.map((key, index) => [key, { key, driverId: key, driverName: names[index], displayName: names[index], transponder: `796100${index}`, laps: laps - index, bestLapMs: 17200 + index * 300, lastLapMs: 18000, startTimestamp: startedAt, lastTimestamp: startedAt + laps * 17800 + index * 900 }]));
state.resultsBySession.vid_judge_q1 = { passings: [], adjustments: [], competitors: competitors(qualiStart, 17) };
state.resultsBySession.vid_judge_q2 = { passings: [], adjustments: [], competitors: competitors(heatStart, 5) };
state.activeSessionId = "vid_judge_q2";
state.settings.raceAudio = { ...state.settings.raceAudio, events: SILENCED_EVENTS };
},
async setup({ navigate }) {
await navigate("judging", "speakerPanel");
},
steps: [
{ text: "Judging is the race controller's page. The speaker panel has the track calls, marshal warning and quick sound switches." },
{
text: "Pick a driver to see the penalties, and write the reason. It is saved in the judging log.",
async action({ click, evaluate, scrollTo }) {
await click("#judge-select-vid_judge_driver_1");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("judgeReason")`)), "driver selected");
await evaluate(`document.getElementById("judgeReason").value = "Pushed another car off"`);
await scrollTo("#judgeReason", "center");
},
},
{
text: "During the heat, call the driver: attention, an official warning, a stop and go, or a drive through. The speaker reads out the driver's name.",
async action({ click, scrollTo }) { await scrollTo('[data-judge-call="stop_and_go"]', "center"); await click('[data-judge-call="stop_and_go"]'); },
},
{
text: "Finished heats can be judged afterwards too, after a protest or a car check. Pick the heat here.",
async action({ evaluate, scrollTo }) {
await evaluate(`(() => { const select = document.getElementById("judgingSessionSelect"); select.value = "vid_judge_q1"; select.dispatchEvent(new Event("change")); })()`);
await waitFor(async () => Boolean(await evaluate(`document.getElementById("judge-select-vid_judge_driver_0")`)), "finished heat");
await scrollTo("#judgingSessionSelect", "center");
},
},
{
text: "Give a time penalty with a reason, or disqualify. Following the EFRA rules, a disqualified driver goes last.",
async action({ click, evaluate, scrollTo }) {
await click("#judge-select-vid_judge_driver_0");
await waitFor(async () => Boolean(await evaluate(`document.getElementById("judgeDsq")`)), "penalty buttons");
await evaluate(`document.getElementById("judgeReason").value = "Car under weight"`);
await click("#judgeDsq");
await pause(600);
await scrollTo("#judgingCompetitorFilter", "center");
},
},
{ text: "Everything follows straight away: results, standings, the race overview and the archive. And every change can be undone from the log." },
],
},
};
const requested = process.argv.slice(2);
const names = requested.length ? requested : Object.keys(clips);
for (const name of names) {
const clip = clips[name];
if (!clip) { console.error(`Unknown clip "${name}". Available: ${Object.keys(clips).join(", ")}`); process.exitCode = 1; continue; }
await recordClip(name, clip);
}