fix(race-day): keep local state while starting or timing a heat, keep count-down voice on time (1.46.1)

This commit is contained in:
larssand committed 2026-11-01 16:16:46 +01:00
1 parent 8d27072567
commit c4163441fc
8 files changed
+119 -10

No files matched your search

+8
View File
@@ -8,6 +8,14 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.46.1 - 2026-11-01
### Fixed
- A heat sometimes didn't start after its count-down, or started and then fell back to the green Start button. The browser refreshed its data from the server in the middle of the start sequence and started a copy of the heat that was no longer in use. The browser that runs the count-down, the start or a live heat on its decoder now keeps its own data, and a refresh never replaces changes made while it was loading.
- Opening Overlay during a race could stop it or lose laps: Overlay reloaded the data from the server every 0.8 s and could overwrite laps that had just come in.
- The count-down voice fell behind the clock (it said "8" after the start) when the voice was slow, for example Piper on an older laptop. Each count-down call now replaces the previous one, and a call that can't be said on time is skipped. Cancel and Go stop any count-down call still waiting.
## 1.46.0 - 2026-11-01
### Changed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.46.0",
"version": "1.46.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.46.0",
"version": "1.46.1",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.46.0",
"version": "1.46.1",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+24 -3
View File
@@ -154,7 +154,14 @@ const refreshAmmcStatus = () => refreshAmmcStatusHelper({ ammc, t, getBackendUrl
const startManagedAmmc = () => startManagedAmmcHelper({ ammc, t, getBackendUrl });
const stopManagedAmmc = () => stopManagedAmmcHelper({ ammc, t, getBackendUrl });
const applyPersistedState = (persisted) => applyPersistedStateHelper(persisted, { state, backend, t, getDefaultBackendUrl, DEFAULT_LANGUAGE, DEFAULT_THEME, AVAILABLE_THEMES, normalizeDriver, normalizeCar, normalizeEvent, normalizeSession, normalizeStoredRacePreset, normalizeObsOverlaySettings, normalizeTrainingState, normalizeRaceAudioSettings, normalizeTrackLayouts: (value) => normalizeTrackLayouts(value, { uid }), applyTheme });
const hydrateFromBackend = () => hydrateFromBackendHelper({ backend, t, getBackendUrl, applyPersistedState, saveState });
const hydrateFromBackend = ({ initial = false } = {}) => hydrateFromBackendHelper({
backend, t, getBackendUrl, applyPersistedState, saveState,
// The first load at page start always takes the server's state.
...(initial ? {} : { getLocalStateVersion: () => localStateVersion, getLocalStateDirty: () => localStateDirty, keepLocal: isRunningRaceHere }),
});
// This browser is starting or timing a heat: its own state is the newest.
const isRunningRaceHere = () => Boolean(getPrologueSession() || pendingStartSessionId || startsInProgress > 0
|| (state.decoder?.connected && state.sessions.some((session) => ["running", "paused"].includes(session.status))));
const scheduleBackendSync = () => scheduleBackendSyncHelper({ getBackendSyncTimer: () => backendSyncTimer, setBackendSyncTimer: (value) => { backendSyncTimer = value; }, syncStateToBackend });
const syncStateToBackend = () => syncStateToBackendHelper({ backend, t, getBackendUrl, buildPersistableState, getLocalStateVersion: () => localStateVersion, getSyncedStateVersion: () => syncedStateVersion, setSyncedStateVersion: (value) => { syncedStateVersion = value; }, getLocalStateDirty: () => localStateDirty, setLocalStateDirty: (value) => { localStateDirty = value; } });
const pingBackend = () => pingBackendHelper({ backend, t, getBackendUrl });
@@ -284,8 +291,10 @@ function getDefaultPrologueSec(session) {
const config = state.events.find((item) => item.id === session?.eventId)?.raceConfig || {};
return normalizePrologueSec(session?.type === "qualification" ? config.qualPrologueSec : config.finalPrologueSec);
}
// Count-down calls replace each other (group) and are dropped when late: a second-by-second
// call more than 1.2 s late, any other call after 4 s.
function speakPrologue(eventKey, session, variables = {}) {
triggerRaceAudio(eventKey, { interrupt: true, force: true, variables, logData: { raceId: session.eventId, sessionId: session.id } });
triggerRaceAudio(eventKey, { interrupt: true, force: true, variables, group: "prologue", maxDelayMs: eventKey === "prologue_count" ? 1200 : 4000, logData: { raceId: session.eventId, sessionId: session.id } });
}
function setRacePrologue(next) {
racePrologue = next;
@@ -317,6 +326,7 @@ function tickRacePrologue() {
// calls ("drivers, stand by"); a count-down that ran out has already called 10..3.
let pendingStartSessionId = null;
async function launchFromPrologue(session, { countedDown }) {
raceAudioEngine.dropVoiceGroup("prologue");
pendingStartSessionId = session.id;
renderView();
const result = await startOperationalSession(session, {
@@ -4926,7 +4936,7 @@ async function init() {
document.getElementById("appUpdateAvailable")?.addEventListener("click", navigateToSettings);
setInterval(() => refreshUpdateStatus({ render: currentView === "settings" }), 20 * 60 * 1000);
Promise.allSettled([hydrateFromBackend(), loadAmmcConfigFromBackend(), refreshServerBackups({ render: false }), refreshUpdateStatus({ render: false })]).finally(() => {
Promise.allSettled([hydrateFromBackend({ initial: true }), loadAmmcConfigFromBackend(), refreshServerBackups({ render: false }), refreshUpdateStatus({ render: false })]).finally(() => {
initialLoadDone = true;
applyTheme();
renderNav();
@@ -5272,6 +5282,15 @@ async function startOperationalSession(session, callbacks = {}) {
}
ensureAudioContext();
startsInProgress += 1;
try {
return await runOperationalStart(session, sequenceCallbacks, onTone);
} finally {
startsInProgress -= 1;
}
}
let startsInProgress = 0;
async function runOperationalStart(session, sequenceCallbacks, onTone) {
let backup = null;
try {
backup = await createServerBackup("pre_start", session);
@@ -5286,6 +5305,8 @@ async function startOperationalSession(session, callbacks = {}) {
const commitStart = () => {
if (committed) return;
committed = true;
// The state may have been reloaded during the start sequence: start the heat that is in it.
session = state.sessions.find((item) => item.id === session.id) || session;
state.activeSessionId = session.id;
beginSessionControl(session);
session.trackLayoutId = getTrackLayoutIdAt(state.trackLayouts);
+23 -2
View File
@@ -212,6 +212,8 @@ export function createRaceAudioEngine(options = {}) {
if (currentVoice || !voiceQueue.length) return;
voiceQueue.sort((a, b) => b.priority - a.priority || a.sequence - b.sequence);
const task = voiceQueue.shift();
// A count-down call that could not be said on time is skipped: "8" after the start is wrong.
if (task.expiresAt && now() > task.expiresAt) { task.resolve(false); pumpVoiceQueue(); return; }
currentVoice = task;
Promise.resolve(speak(task.text, { language: task.language, volume: task.volume, interrupt: task.interrupt }))
.catch(() => false).finally(() => {
@@ -225,7 +227,18 @@ export function createRaceAudioEngine(options = {}) {
const voice = await resolveVoice(key, eventOptions);
if (!voice) return false;
return new Promise((resolve) => {
const task = { ...voice, sequence: voiceSequence += 1, resolve };
const group = String(eventOptions.group || "");
const task = { ...voice, group, sequence: voiceSequence += 1, resolve, expiresAt: eventOptions.maxDelayMs ? Number(eventOptions.queuedAt ?? now()) + Number(eventOptions.maxDelayMs) : 0 };
// A newer call in the same group (the count-down) replaces the older one instead of
// queueing behind it, so the voice never falls behind the clock.
if (group) {
dropQueuedGroup(group);
if (currentVoice?.group === group) {
currentVoice.resolve(false);
currentVoice = null;
task.interrupt = true;
}
}
if (task.interrupt && currentVoice && task.priority > currentVoice.priority) {
currentVoice.resolve(false);
currentVoice = null;
@@ -235,6 +248,12 @@ export function createRaceAudioEngine(options = {}) {
});
}
function dropQueuedGroup(group) {
for (let index = voiceQueue.length - 1; index >= 0; index -= 1) {
if (voiceQueue[index].group === group) voiceQueue.splice(index, 1)[0].resolve(false);
}
}
function isCoolingDown(key, eventOptions, definition) {
if (eventOptions.force) return false;
const cooldownMs = Number(eventOptions.cooldownMs ?? definition?.cooldownMs ?? 0);
@@ -251,7 +270,8 @@ export function createRaceAudioEngine(options = {}) {
const definition = EVENT_BY_KEY.get(key);
if (!definition || isCoolingDown(key, eventOptions, definition)) return { effectDone: Promise.resolve(false), voiceDone: Promise.resolve(false) };
const effectDone = playEffect(key, eventOptions);
const voiceDone = effectDone.catch(() => false).then(() => enqueueVoice(key, eventOptions));
const queuedAt = now();
const voiceDone = effectDone.catch(() => false).then(() => enqueueVoice(key, { ...eventOptions, queuedAt }));
try { log({ timestamp: now(), event: key, audioFile: safeEffectPath(eventOptions.effectPath || definition.effect), priority: definition.priority, language: normalizeRaceAudioSettings(getSettings()).language, ...eventOptions.logData }); } catch { /* non-critical */ }
return { effectDone, voiceDone };
}
@@ -336,6 +356,7 @@ export function createRaceAudioEngine(options = {}) {
loadManifest, playEffect, trigger, runStartSequence,
subscribeStartLights(listener) { lightSubscribers.add(listener); listener(lightState, {}); return () => lightSubscribers.delete(listener); },
cancelStartSequence() { startSequenceGeneration += 1; emitLightState("IDLE"); },
dropVoiceGroup(group) { dropQueuedGroup(String(group || "")); },
resetStartLights() { emitLightState("IDLE"); },
getStartLightState: () => lightState,
getStatus: () => ({ loaded: Boolean(manifest), missingEffects: [...missingEffects], queuedVoices: voiceQueue.length, currentVoice: currentVoice?.key || "", lightState }),
+9 -2
View File
@@ -156,12 +156,19 @@ export function applyPersistedStateHelper(persisted, deps) {
applyTheme();
}
export async function hydrateFromBackendHelper({ backend, t, getBackendUrl, applyPersistedState, saveState }) {
// keepLocal: true while this browser is running the race (count-down, start sequence, a
// live heat on its decoder). Then this browser's copy is the newest, and replacing it would
// turn a heat that just started back to "ready" or drop laps that came in meanwhile.
export async function hydrateFromBackendHelper({ backend, t, getBackendUrl, applyPersistedState, saveState, getLocalStateVersion = () => 0, getLocalStateDirty = () => false, keepLocal = () => false }) {
if (keepLocal()) return;
const versionAtFetch = getLocalStateVersion();
try {
const res = await fetch(`${getBackendUrl()}/api/state`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const payload = await res.json();
if (payload && payload.state && typeof payload.state === "object") {
// Something changed here while the request was out (a lap, a start): this copy is older.
const staleCopy = getLocalStateVersion() !== versionAtFetch || getLocalStateDirty() || keepLocal();
if (!staleCopy && payload && payload.state && typeof payload.state === "object") {
applyPersistedState(payload.state);
saveState({ skipBackend: true });
backend.lastSyncAt = payload.updatedAt || new Date().toISOString();
+30
View File
@@ -261,3 +261,33 @@ test("fastest lap, track record and leader events use mapped effects and dynamic
assert.deepEqual(played, ["/race-sounds/sounds/effects/fastest.wav", "/race-sounds/sounds/effects/record.wav"]);
assert.deepEqual(spoken, ["Snabbast Kim 16.200", "Rekord Kim 16.200", "Ledare Kim"]);
});
test("count-down calls replace each other instead of queueing, and late ones are dropped", async () => {
const spoken = [];
const resolvers = [];
let clock = 1000;
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: (text) => new Promise((resolve) => { spoken.push(text); resolvers.push(resolve); }),
now: () => clock,
getSettings: () => normalizeRaceAudioSettings(),
});
const tick = async () => { for (let i = 0; i < 20; i += 1) await new Promise((resolve) => setImmediate(resolve)); };
const count = (seconds) => engine.trigger("prologue_count", { interrupt: true, force: true, group: "prologue", maxDelayMs: 1200, voiceText: String(seconds) });
// A slow voice: "9" is still being said when "8" and "7" are due.
count(9); await tick();
count(8); await tick();
count(7); await tick();
assert.deepEqual(spoken, ["9", "8", "7"], "each new call cuts the previous one");
// A call that waited longer than its limit is never said.
// Another call holds the voice past the limit: the waiting "6" is skipped.
engine.trigger("prologue_hold", { interrupt: true, force: true, priority: "critical", voiceText: "Håll" });
await tick();
const late = count(6);
await tick();
clock += 5000;
resolvers.forEach((resolve) => resolve(true));
assert.equal(await late.voiceDone, false);
assert.ok(!spoken.includes("6"));
});
+22
View File
@@ -183,6 +183,28 @@ test("successful backend hydration applies state without scheduling a write-back
assert.equal(backend.lastSyncAt, "2026-08-24T10:00:00.000Z");
});
test("hydration never replaces a newer local state: a lap or start made while the request was out, or a race run here", async () => {
const run = async ({ keepLocal = () => false, bumpDuringFetch = false }) => {
let version = 1;
const applied = [];
await withMockFetch(
async () => {
if (bumpDuringFetch) version += 1; // e.g. a passing saved while the request was out
return { ok: true, json: async () => ({ state: { sessions: [{ id: "q1", status: "ready" }] } }) };
},
() => hydrateFromBackendHelper({
backend: { available: true }, t: (key) => key, getBackendUrl: () => "http://race:8081",
applyPersistedState: (state) => applied.push(state), saveState: () => {},
getLocalStateVersion: () => version, keepLocal,
})
);
return applied.length;
};
assert.equal(await run({}), 1, "an idle browser is refreshed");
assert.equal(await run({ bumpDuringFetch: true }), 0, "a change made during the request wins");
assert.equal(await run({ keepLocal: () => true }), 0, "a browser starting or timing a heat keeps its own state");
});
test("failed hydration preserves local state and reports backend offline", async () => {
const backend = { available: true, lastError: "" };
let applied = false;