From 3a6789f42fb5ecfba51fba3c46b350402d171ba8 Mon Sep 17 00:00:00 2001 From: larssand Date: Sat, 17 Oct 2026 17:31:59 +0200 Subject: [PATCH] fix(timing): keep timing the running session when another one is selected Passings and the session clock followed only the selected session, so selecting another practice or the next heat while one was running dropped every lap. They now go to the running session, and Timing and Race Day show where laps are being recorded. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++++ ROADMAP.md | 17 ++++++++++ package-lock.json | 4 +-- package.json | 2 +- src/app.js | 25 +++++++++----- src/race_day_view.js | 7 +++- src/runtime_services.js | 2 +- src/styles.css | 3 ++ src/timing_logic.js | 12 +++++++ src/timing_views.js | 6 ++++ tests/browser_live_session.js | 48 +++++++++++++++++++++++++++ tests/browser_smoke.js | 2 ++ tests/overlay_position_change.test.js | 12 +++++++ 13 files changed, 137 insertions(+), 13 deletions(-) create mode 100644 tests/browser_live_session.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fb7490..3563165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.40.0 - 2026-10-17 + +### Fixed + +- Passings were thrown away when a session other than the running one was selected, e.g. another Open Practice opened while one was still running, or the next heat picked on Race Day during the current one. The decoder then looked dead although it was connected. The heat's clock (automatic finish, time calls) only followed the selected session too. Passings and the clock now go to the selected session when it runs, otherwise to the session that is actually running (the most recently started). The finish announcement names the session that finished. + +### Added + +- Timing and Race Day show a notice when laps are being recorded on another running session than the selected one, with a **Show it** button. + ## 1.39.2 - 2026-10-17 ### Fixed diff --git a/ROADMAP.md b/ROADMAP.md index 8429fb1..15106bd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -937,6 +937,23 @@ Checked: Verified: 265 unit and 75 browser scenarios pass. +### Follow-up: laps dropped when another session was selected (2026-10-17) + +The user noticed that the decoder "came alive" only when they started the other Open Practice. + +The cause: +- `processDecoderMessage` and the timer tick used `getActiveSession()`, which is the *selected* session. +- With another Open Practice selected (ready) while one still ran, every passing was reported as `no_running_session` and dropped. +- The same happened on Race Day when the next heat was picked during the current one. That heat would also not have finished automatically. + +- [x] `getLiveSession` in `timing_logic.js` returns the selected session if it is running or paused, otherwise the most recently started running/paused session, otherwise the selected one. Decoder processing, the session timer tick and the race-calls check use it. `announceRaceFinished(session)` receives the finished session. +- [x] A notice on Timing and Race Day ("Laps are being recorded on X, which is running") with a Show it button. + +Verified: +- 266 unit tests pass (selected running, next heat picked, most recent of several, paused, nothing running, empty). +- `tests/browser_live_session.js` runs practice A while B is selected, and sends a real decoder passing. It checks that the passing is counted on A and nothing on B, that the notice shows A, and that Show it selects A and removes the notice. +- The test fails with the old routing ("the passing is counted on the running practice, not dropped") and passes with the fix. 76 browser scenarios pass. + ## Documentation maintenance - [x] Update the architecture's module/dependency inventory as modules change. diff --git a/package-lock.json b/package-lock.json index e61ca72..2c13586 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.39.2", + "version": "1.40.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.39.2", + "version": "1.40.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index c3adb9e..aac6093 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.39.2", + "version": "1.40.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/src/app.js b/src/app.js index 2f377dd..5ed1e04 100644 --- a/src/app.js +++ b/src/app.js @@ -17,7 +17,7 @@ import { renderRaceFormatField, renderRaceFormatContextCard, getRaceSummaryItems import { normalizeRaceTeam as normalizeRaceTeamLogic, normalizeStoredRacePreset as normalizeStoredRacePresetLogic, getRaceFormatPresets as getRaceFormatPresetsLogic, applyRaceFormatPreset as applyRaceFormatPresetLogic, buildRaceFormatConfigFromForm as buildRaceFormatConfigFromFormLogic, normalizeEvent as normalizeEventLogic, normalizeBrandingConfig as normalizeBrandingConfigLogic, resolveEventBranding as resolveEventBrandingLogic, getRaceManageStatuses as getRaceManageStatusesLogic, buildDefaultRaceWizardDraft as buildDefaultRaceWizardDraftLogic, getRaceWizardPreset as getRaceWizardPresetLogic, applyRaceWizardPresetDefaults as applyRaceWizardPresetDefaultsLogic, ensureRaceParticipantsConfigured as ensureRaceParticipantsConfiguredLogic, buildRaceSession as buildRaceSessionLogic, buildOpenPracticeBundle as buildOpenPracticeBundleLogic, buildTrackSession as buildTrackSessionLogic, createSponsorRounds as createSponsorRoundsLogic, buildRaceSessionsFromWizard as buildRaceSessionsFromWizardLogic, getRaceWizardSessionPlan as getRaceWizardSessionPlanLogic, getEventDrivers as getEventDriversLogic, getEventTeams as getEventTeamsLogic, getTeamDriverPool as getTeamDriverPoolLogic, reassignTeamMembers as reassignTeamMembersLogic, findEventTeamForPassing as findEventTeamForPassingLogic, generateQualifyingForRace as generateQualifyingForRaceLogic, reseedUpcomingQualifying as reseedUpcomingQualifyingLogic, moveDriversIntoQualifyingHeat as moveDriversIntoQualifyingHeatLogic, parseQualifyingHeatName as parseQualifyingHeatNameLogic, generateFinalsForRace as generateFinalsForRaceLogic, applyBumpsForRace as applyBumpsForRaceLogic, buildEventSchedule as buildEventScheduleLogic } from "./event_race_logic.js"; -import { getSessionTypeLabel as getSessionTypeLabelLogic, getStatusLabel as getStatusLabelLogic, isUntimedSession as isUntimedSessionLogic, getActiveSession as getActiveSessionLogic, getSessionTargetMs as getSessionTargetMsLogic, getSessionLapWindow as getSessionLapWindowLogic, isCountedPassing as isCountedPassingLogic, getVisiblePassings as getVisiblePassingsLogic, getPassingValidationLabel as getPassingValidationLabelLogic, getSessionTiming as getSessionTimingLogic, ensureSessionResult as ensureSessionResultLogic, buildLeaderboard as buildLeaderboardLogic, formatLapDelta as formatLapDeltaLogic, formatLeaderboardGap as formatLeaderboardGapLogic, getCompetitorElapsedMs as getCompetitorElapsedMsLogic, getCompetitorPassings as getCompetitorPassingsLogic, getCompetitorSeedMetric as getCompetitorSeedMetricLogic, getSessionEntrants as getSessionEntrantsLogic, buildPracticeStandings as buildPracticeStandingsLogic, getQualifyingPointsValue as getQualifyingPointsValueLogic, isHighPointsTable as isHighPointsTableLogic, compareNumberSet as compareNumberSetLogic, buildQualifyingTieBreakNote as buildQualifyingTieBreakNoteLogic, hasQualifyingPrimaryTie as hasQualifyingPrimaryTieLogic, buildQualifyingStandings as buildQualifyingStandingsLogic, formatTeamActiveMemberLabel as formatTeamActiveMemberLabelLogic, buildTeamRaceStandings as buildTeamRaceStandingsLogic, buildSessionChannelStats as buildSessionChannelStatsLogic, buildTeamStintLog as buildTeamStintLogLogic, getSessionGridEntries as getSessionGridEntriesLogic, getSessionGridOrder as getSessionGridOrderLogic, ensureSessionDriverOrder as ensureSessionDriverOrderLogic, buildFinalStandings as buildFinalStandingsLogic, getTrackRecordMs as getTrackRecordMsLogic } from "./timing_logic.js"; +import { getSessionTypeLabel as getSessionTypeLabelLogic, getStatusLabel as getStatusLabelLogic, isUntimedSession as isUntimedSessionLogic, getActiveSession as getActiveSessionLogic, getLiveSession as getLiveSessionLogic, getSessionTargetMs as getSessionTargetMsLogic, getSessionLapWindow as getSessionLapWindowLogic, isCountedPassing as isCountedPassingLogic, getVisiblePassings as getVisiblePassingsLogic, getPassingValidationLabel as getPassingValidationLabelLogic, getSessionTiming as getSessionTimingLogic, ensureSessionResult as ensureSessionResultLogic, buildLeaderboard as buildLeaderboardLogic, formatLapDelta as formatLapDeltaLogic, formatLeaderboardGap as formatLeaderboardGapLogic, getCompetitorElapsedMs as getCompetitorElapsedMsLogic, getCompetitorPassings as getCompetitorPassingsLogic, getCompetitorSeedMetric as getCompetitorSeedMetricLogic, getSessionEntrants as getSessionEntrantsLogic, buildPracticeStandings as buildPracticeStandingsLogic, getQualifyingPointsValue as getQualifyingPointsValueLogic, isHighPointsTable as isHighPointsTableLogic, compareNumberSet as compareNumberSetLogic, buildQualifyingTieBreakNote as buildQualifyingTieBreakNoteLogic, hasQualifyingPrimaryTie as hasQualifyingPrimaryTieLogic, buildQualifyingStandings as buildQualifyingStandingsLogic, formatTeamActiveMemberLabel as formatTeamActiveMemberLabelLogic, buildTeamRaceStandings as buildTeamRaceStandingsLogic, buildSessionChannelStats as buildSessionChannelStatsLogic, buildTeamStintLog as buildTeamStintLogLogic, getSessionGridEntries as getSessionGridEntriesLogic, getSessionGridOrder as getSessionGridOrderLogic, ensureSessionDriverOrder as ensureSessionDriverOrderLogic, buildFinalStandings as buildFinalStandingsLogic, getTrackRecordMs as getTrackRecordMsLogic } from "./timing_logic.js"; import { normalizeTrackLayouts, getTrackLayoutIdAt, getTrackLayoutLabel, nextTrackLayoutLabel, findRaceSessionBlockingLayoutChange, isPracticeSessionType, isTrackLayoutInUse } from "./track_layouts_logic.js"; import { renderDashboardView, renderClassesView, renderDriversView, renderCarsView } from "./core_views.js"; @@ -90,6 +90,7 @@ const getSessionTypeLabel = (type) => getSessionTypeLabelLogic(type, { t }); const getStatusLabel = (status) => getStatusLabelLogic(status, { t }); const isUntimedSession = (session) => isUntimedSessionLogic(session); const getActiveSession = () => getActiveSessionLogic({ state }); +const getLiveSession = () => getLiveSessionLogic({ state }); const normalizeSeriesList = (list) => (Array.isArray(list) ? list : []).map((series) => normalizeSeries(series, { uid })).filter((series) => series.id); const getSessionTargetMs = (session) => getSessionTargetMsLogic(session, { isUntimedSession }); const getSessionLapWindow = (session) => getSessionLapWindowLogic(session, { state }); @@ -180,7 +181,7 @@ const getSpeechVoices = () => getSpeechVoicesHelper(); const speakText = (text, options = {}) => speakTextHelper(text, { state, currentLanguage }, options); const triggerRaceAudio = (eventKey, options = {}) => { // The Settings test buttons use force: they must sound even with no session running. - if (!options.force && isSilencedDuringRace(eventKey, state.settings.raceAudio, getActiveSession())) return { skipped: true, voiceDone: Promise.resolve(false) }; + if (!options.force && isSilencedDuringRace(eventKey, state.settings.raceAudio, getLiveSession())) return { skipped: true, voiceDone: Promise.resolve(false) }; return raceAudioEngine.trigger(eventKey, options); }; const getPassingSoundProfile = (entry) => { @@ -194,9 +195,11 @@ const announcePassing = (entry) => { } }; const announceRaceStarted = (session) => announceRaceStartedHelper(session, { t, pushOverlayEvent }); -const announceRaceFinished = () => { - const session = getActiveSession(); - announceRaceFinishedHelper({ t, getActiveSession, pushOverlayEvent }); +// `finished` is the session that just ended (the timer may finish a running heat while the +// next one is already selected); manual finish selects the session first, so the default holds. +const announceRaceFinished = (finished = null) => { + const session = finished || getActiveSession(); + announceRaceFinishedHelper({ t, getActiveSession: () => session, pushOverlayEvent }); if (!session || !state.settings.raceAudio?.enabled) return; triggerRaceAudio(session.type === "qualification" ? "qualifying_finished" : "race_finished", { interrupt: true, logData: { raceId: session.eventId, sessionId: session.id } }); const podium = buildLeaderboard(session).slice(0, 3); @@ -204,7 +207,7 @@ const announceRaceFinished = () => { if (podium.length > 1) triggerRaceAudio("podium", { variables: { podium: podium.map((row) => row.displayName || row.driverName).join(", ") } }); }; const announceRaceClockEvent = (eventKey, session) => triggerRaceAudio(eventKey, { logData: { raceId: session.eventId, sessionId: session.id } }); -const handleSessionTimerTick = () => handleSessionTimerTickHelper({ getActiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, announceRaceFinished, announceRaceClockEvent }); +const handleSessionTimerTick = () => handleSessionTimerTickHelper({ getActiveSession: getLiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, announceRaceFinished, announceRaceClockEvent }); const cancelRaceStart = () => raceAudioEngine.cancelStartSequence(); const startSessionWithAudio = (session, callbacks) => { // Only the casual, come-and-go practice modes (open_practice - the standalone "Quick @@ -383,7 +386,8 @@ function setDriverTransponder(driverId, transponder) { const processDecoderMessage = (msg, decoderRole = "main") => processDecoderMessageHelper(msg, { state, t, - getActiveSession, + // Passings go to the session actually running (see getLiveSession), not only the selected one. + getActiveSession: getLiveSession, ensureSessionResult, normalizeStartMode, getSessionLapWindow, @@ -420,6 +424,7 @@ const renderRaceDay = () => renderRaceDayView({ getRaceDayWarmupCheck, setDriverTransponder, getDefaultPrologueSec, startRacePrologue, holdRacePrologue, resumeRacePrologue, setRacePrologueRemaining, cancelRacePrologue, goRacePrologue, isStartPending: (session) => Boolean(session && pendingStartSessionId === session.id), + getLiveSession, renderSuspectLapsPanel: (session) => renderSuspectLapsPanelView(session, { t, escapeHtml, formatLap, ensureSessionResult }), setCompetitorLapStatus, addTrackLayout, renderView, state, dom, t, escapeHtml, formatLap, formatCountdown, formatElapsedClock, @@ -478,7 +483,7 @@ const refreshTimingDynamics = () => { node.textContent = clock; }); }; -const renderTiming = () => renderTimingView({ state, dom, t, escapeHtml, formatLap, formatCountdown, formatElapsedClock, formatRaceClock, renderTable, uid, getActiveSession, ensureSessionResult, buildLeaderboard, getSessionTiming, getVisiblePassings, getEventName, getSessionTypeLabel, getStatusLabel, normalizeStartMode, getStartModeLabel, renderPositionGrid, renderSessionChannelAnalysis, connectDecoder, disconnectDecoder, applyCompetitorCorrection, invalidateCompetitorLastLap, restoreCompetitorLastInvalidLap, startOperationalSession, finishOperationalSession, cancelRaceStart, triggerRaceAudio, getStartLightState: () => raceAudioEngine.getStartLightState(), saveState, updateHeaderState, renderView, normalizeDriver, normalizeCar, processDecoderMessage, getSelectedLeaderboardKey: () => selectedLeaderboardKey, setSelectedLeaderboardKey: (value) => { selectedLeaderboardKey = value; }, getQuickAddDraft: () => quickAddDraft, setQuickAddDraft: (value) => { quickAddDraft = value; }, getPassingValidationLabel, isCountedPassing, getCompetitorPassings, getManualCorrectionSummary, formatTeamActiveMemberLabel, lastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, lastOverlayLeaderKeyBySession, lastOverlayTop3BySession, overlayEvents: () => overlayEvents, setOverlayEvents: (value) => { overlayEvents = value; }, sessionReplay, syncTrainingLedger, setCompetitorLapStatus, openJudging: (rowKey) => { selectedJudgeKey = rowKey; selectedLeaderboardKey = null; navigateToView("judging"); } }); +const renderTiming = () => renderTimingView({ state, dom, t, escapeHtml, formatLap, formatCountdown, formatElapsedClock, formatRaceClock, renderTable, uid, getActiveSession, ensureSessionResult, buildLeaderboard, getSessionTiming, getVisiblePassings, getEventName, getSessionTypeLabel, getStatusLabel, normalizeStartMode, getStartModeLabel, renderPositionGrid, renderSessionChannelAnalysis, connectDecoder, disconnectDecoder, applyCompetitorCorrection, invalidateCompetitorLastLap, restoreCompetitorLastInvalidLap, startOperationalSession, finishOperationalSession, cancelRaceStart, triggerRaceAudio, getStartLightState: () => raceAudioEngine.getStartLightState(), saveState, updateHeaderState, renderView, normalizeDriver, normalizeCar, processDecoderMessage, getSelectedLeaderboardKey: () => selectedLeaderboardKey, setSelectedLeaderboardKey: (value) => { selectedLeaderboardKey = value; }, getQuickAddDraft: () => quickAddDraft, setQuickAddDraft: (value) => { quickAddDraft = value; }, getPassingValidationLabel, isCountedPassing, getCompetitorPassings, getManualCorrectionSummary, formatTeamActiveMemberLabel, lastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, lastOverlayLeaderKeyBySession, lastOverlayTop3BySession, overlayEvents: () => overlayEvents, setOverlayEvents: (value) => { overlayEvents = value; }, sessionReplay, syncTrainingLedger, setCompetitorLapStatus, getLiveSession, selectLiveSession: (id) => selectOperationalSession(id), openJudging: (rowKey) => { selectedJudgeKey = rowKey; selectedLeaderboardKey = null; navigateToView("judging"); } }); const renderJudging = () => renderJudgingView({ state, dom, t, escapeHtml, formatLap, renderTable, getActiveSession, ensureSessionResult, buildLeaderboard, getSessionTypeLabel, getJudgeFilteredRows, getJudgeFilteredLog, getCompetitorPassings, isCountedPassing, getPassingValidationLabel, undoJudgingAdjustment, applyCompetitorCorrection, invalidateCompetitorLastLap, restoreCompetitorLastInvalidLap, renderView, getSelectedJudgeKey: () => selectedJudgeKey, setSelectedJudgeKey: (value) => { selectedJudgeKey = value; }, getJudgingCompetitorFilter: () => judgingCompetitorFilter, setJudgingCompetitorFilter: (value) => { judgingCompetitorFilter = value; }, getJudgingLogFilter: () => judgingLogFilter, setJudgingLogFilter: (value) => { judgingLogFilter = value; } , setCompetitorLapStatus }); const normalizeTrainingState = (training) => normalizeTrainingStateLogic(training, { uid }); const syncTrainingLedger = () => { @@ -794,6 +799,8 @@ const TRANSLATIONS = { "series.step3": "3 · Deltävlingar ({count})", "series.step4": "4 · Ställning", "series.classes_all": "Alla", + "timing.live_elsewhere": "Varv registreras just nu på \"{name}\", som pågår - inte på den valda sessionen.", + "timing.show_live": "Visa den", "overlay.obs_show_position_change": "Placering sedan start (▲/▼) i race", "overlay.position_change_title": "Placeringar vunna (▲) eller förlorade (▼) sedan starten", "settings.public_address_title": "Publik adress (domän / DynDNS)", @@ -2600,6 +2607,8 @@ const TRANSLATIONS = { "series.step3": "3 · Rounds ({count})", "series.step4": "4 · Standings", "series.classes_all": "All", + "timing.live_elsewhere": "Laps are being recorded on \"{name}\", which is running - not on the selected session.", + "timing.show_live": "Show it", "overlay.obs_show_position_change": "Places since the start (▲/▼) in races", "overlay.position_change_title": "Places gained (▲) or lost (▼) since the start", "settings.public_address_title": "Public address (domain / DynDNS)", diff --git a/src/race_day_view.js b/src/race_day_view.js index 967e9ca..a8cd629 100644 --- a/src/race_day_view.js +++ b/src/race_day_view.js @@ -174,7 +174,7 @@ export function renderRaceDayView(deps) { saveLapWindow, navigateTo, getStartLightState, addTrackLayout, renderView, getRaceDayWarmupCheck, setDriverTransponder, getDefaultPrologueSec, startRacePrologue, holdRacePrologue, resumeRacePrologue, setRacePrologueRemaining, cancelRacePrologue, goRacePrologue, - isStartPending, renderSuspectLapsPanel = () => "", setCompetitorLapStatus = () => false, + isStartPending, renderSuspectLapsPanel = () => "", setCompetitorLapStatus = () => false, getLiveSession = () => null, } = deps; const queue = buildRaceDayQueue(state); const session = queue.current; @@ -197,7 +197,11 @@ export function renderRaceDayView(deps) { const isSelected = Boolean(session && state.activeSessionId === session.id); const canStart = Boolean(session && preflight.ready && !["running", "paused"].includes(session.status) && !isStartPending?.(session)); + // Another session is running while a different one is selected: say where laps go. + const liveSession = getLiveSession(); + const liveElsewhere = liveSession && session && liveSession.id !== session.id && ["running", "paused"].includes(liveSession.status) ? liveSession : null; dom.view.innerHTML = ` + ${liveElsewhere ? `
⏱ ${escapeHtml(t("timing.live_elsewhere", { name: liveElsewhere.name }))}
` : ""}
${t("race_day.current")} @@ -334,6 +338,7 @@ export function renderRaceDayView(deps) { if (!result.ok && result.message) alert(result.message); if (!result.ok && button) button.disabled = false; }); + dom.view.querySelector("[data-show-live]")?.addEventListener("click", (event) => selectSession(event.currentTarget.dataset.showLive)); dom.view.querySelectorAll("[data-lap-action]").forEach((button) => button.addEventListener("click", () => { if (session && setCompetitorLapStatus(session, button.dataset.lapRow, Number(button.dataset.lapTs), button.dataset.lapAction)) renderView(); })); diff --git a/src/runtime_services.js b/src/runtime_services.js index ac88556..364d71f 100644 --- a/src/runtime_services.js +++ b/src/runtime_services.js @@ -439,7 +439,7 @@ export function handleSessionTimerTickHelper({ getActiveSession, isUntimedSessio active.endedAt = Date.now(); active.finishedByTimer = true; active.followUpStartedAt = null; - if (getLastFinishAnnouncementSessionId() !== active.id) { announceRaceFinished(); setLastFinishAnnouncementSessionId(active.id); } + if (getLastFinishAnnouncementSessionId() !== active.id) { announceRaceFinished(active); setLastFinishAnnouncementSessionId(active.id); } saveState(); return { changed: true }; } diff --git a/src/styles.css b/src/styles.css index a938073..db303d0 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4631,3 +4631,6 @@ tr.is-removed td.lap-actions { .overlay-position-change { font-weight: 800; font-variant-numeric: tabular-nums; } .overlay-position-change.is-up { color: #3ddc84; } .overlay-position-change.is-down { color: #ff6b6b; } + +/* Laps are going to a running session other than the selected one */ +.live-elsewhere-banner { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; padding: 10px 14px; border: 1px solid #f5a623; border-radius: 10px; background: color-mix(in srgb, #f5a623 14%, transparent); font-weight: 600; } diff --git a/src/timing_logic.js b/src/timing_logic.js index 53ac9a0..58ec28a 100644 --- a/src/timing_logic.js +++ b/src/timing_logic.js @@ -25,6 +25,18 @@ export function getActiveSession({ state }) { return state.sessions.find((s) => s.id === state.activeSessionId) || null; } +// The session that is actually being timed. Normally the selected one; but if the selected +// session isn't running or paused (the next heat picked on Race Day, another Open Practice +// opened) while another session still runs, that running one - the most recently started - +// keeps getting the passings and its clock, instead of every lap being dropped. +export function getLiveSession({ state }) { + const isLive = (session) => ["running", "paused"].includes(String(session?.status || "")); + const active = getActiveSession({ state }); + if (isLive(active)) return active; + const live = state.sessions.filter(isLive).sort((a, b) => Number(b.startedAt || 0) - Number(a.startedAt || 0)); + return live[0] || active; +} + export function getSessionTargetMs(session, { isUntimedSession }) { diff --git a/src/timing_views.js b/src/timing_views.js index 794a8aa..2a32698 100644 --- a/src/timing_views.js +++ b/src/timing_views.js @@ -411,6 +411,7 @@ export function renderTimingView(deps) { getManualCorrectionSummary, formatTeamActiveMemberLabel, formatRaceClock, renderSessionChannelAnalysis, setLastFinishAnnouncementSessionId, lastOverlayLeaderKeyBySession, lastOverlayTop3BySession, overlayEvents, setOverlayEvents, sessionReplay, syncTrainingLedger = () => {}, setCompetitorLapStatus = () => false, openJudging = () => {}, + getLiveSession = () => null, selectLiveSession = () => {}, } = deps; const helperDeps = { @@ -442,8 +443,12 @@ export function renderTimingView(deps) { if (getSelectedLeaderboardKey() && !selectedRow) { setSelectedLeaderboardKey(null); } + // Another session is running while a different one is selected: say where laps go. + const liveSession = getLiveSession(); + const liveElsewhere = liveSession && liveSession.id !== active?.id && ["running", "paused"].includes(liveSession.status) ? liveSession : null; dom.view.innerHTML = ` + ${liveElsewhere ? `
⏱ ${escapeHtml(t("timing.live_elsewhere", { name: liveElsewhere.name }))}
` : ""}

${t("timing.decoder_connection")}

@@ -780,6 +785,7 @@ export function renderTimingView(deps) { if (session) finishOperationalSession(session); }); + dom.view.querySelector("[data-show-live]")?.addEventListener("click", (event) => selectLiveSession(event.currentTarget.dataset.showLive)); // Remove / restore / approve one lap - from the suspect panel or a driver's lap list. dom.view.querySelectorAll("[data-lap-action]").forEach((button) => button.addEventListener("click", () => { const session = getActiveSession(); diff --git a/tests/browser_live_session.js b/tests/browser_live_session.js new file mode 100644 index 0000000..b97ffff --- /dev/null +++ b/tests/browser_live_session.js @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import { startFakeDecoder } from "./browser_fake_decoder.js"; + +// The user's case: an Open Practice is running, another session gets selected (another +// practice, or the next heat on Race Day). Passings used to be dropped as "no running +// session"; they must keep going to the running one, and the page must say so. +export async function runLiveSessionSmoke({ evaluate, navigate, savedState, waitFor, base }) { + const patchState = async (patch) => { + const current = await savedState(); + Object.assign(current, patch); + const response = await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(current) }); + assert.equal(response.ok, true); + }; + const decoder = await startFakeDecoder(); + const seeded = await savedState(); + const startedAt = Date.now() - 60000; + const running = { id: "ls_running", eventId: "ls_event", name: "LS Practice A", type: "open_practice", status: "running", startedAt, durationMin: 600 }; + const selected = { id: "ls_selected", eventId: "ls_event", name: "LS Practice B", type: "open_practice", status: "ready", durationMin: 600 }; + await patchState({ + events: [...seeded.events, { id: "ls_event", name: "LS Club", mode: "race", raceConfig: { practiceOnly: true } }], + drivers: [...seeded.drivers, { id: "ls_driver", name: "LS Driver", transponder: "8880001" }], + sessions: [...seeded.sessions.map((session) => (["running", "paused"].includes(session.status) ? { ...session, status: "finished", endedAt: Date.now() } : session)), running, selected], + activeSessionId: selected.id, + settings: { ...seeded.settings, autoReconnect: true, wsUrl: `ws://127.0.0.1:${decoder.port}` }, + }); + try { + await navigate("timing", "resetSession"); + await waitFor(async () => evaluate('document.getElementById("connectionBadge")?.classList.contains("badge-online")'), "decoder connected"); + await waitFor(async () => (await evaluate(`document.getElementById("liveElsewhereBanner")?.textContent || ""`)).includes("LS Practice A"), "the page says laps go to the running practice"); + decoder.sendPassing("8880001", startedAt + 20000); + await waitFor(async () => ((await savedState()).resultsBySession?.ls_running?.passings || []).length === 1, "the passing is counted on the running practice, not dropped"); + assert.equal(((await savedState()).resultsBySession?.ls_selected?.passings || []).length, 0, "nothing on the selected, not-started one"); + await evaluate(`document.querySelector("[data-show-live]").click()`); + await waitFor(async () => (await savedState()).activeSessionId === running.id, "Show it selects the running session"); + await waitFor(async () => !(await evaluate(`Boolean(document.getElementById("liveElsewhereBanner"))`)), "notice gone once it is selected"); + console.log("PASS passings keep going to the running session when another one is selected, and the page says so"); + } finally { + const current = await savedState(); + await patchState({ + settings: { ...current.settings, autoReconnect: false }, + sessions: current.sessions.filter((session) => !session.id.startsWith("ls_")), + events: current.events.filter((event) => event.id !== "ls_event"), + drivers: current.drivers.filter((driver) => driver.id !== "ls_driver"), + activeSessionId: "", + }); + await decoder.close(); + } +} diff --git a/tests/browser_smoke.js b/tests/browser_smoke.js index edce185..dbdcb4a 100644 --- a/tests/browser_smoke.js +++ b/tests/browser_smoke.js @@ -18,6 +18,7 @@ import { runDriversPageSmoke } from "./browser_drivers_page.js"; import { runSeriesSmoke } from "./browser_series.js"; import { runTrainingSourceSmoke } from "./browser_training_source.js"; import { runDecoderUrlSmoke } from "./browser_decoder_url.js"; +import { runLiveSessionSmoke } from "./browser_live_session.js"; import { runObsPopupSmoke } from "./browser_obs_popup.js"; import { runDecoderReconnectSmoke } from "./browser_decoder_reconnect.js"; import assert from "node:assert/strict"; @@ -166,6 +167,7 @@ try { await runSeriesSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs }); await runTrainingSourceSmoke({ evaluate, navigate, savedState, waitFor, base }); await runDecoderUrlSmoke({ evaluate, navigate, savedState, waitFor, base }); + await runLiveSessionSmoke({ evaluate, navigate, savedState, waitFor, base }); await runRaceDaySmoke({ evaluate, navigate, fill, savedState, waitFor, pause, base, dialogs }); await runRaceDayStartSequencesSmoke({ evaluate, navigate, waitFor, pause, base, dialogs }); await runObsPopupSmoke({ evaluate, navigate, fill, savedState, waitFor, pause, base, debugPort, dialogs, realClick }); diff --git a/tests/overlay_position_change.test.js b/tests/overlay_position_change.test.js index f90f1b4..2467ce2 100644 --- a/tests/overlay_position_change.test.js +++ b/tests/overlay_position_change.test.js @@ -16,3 +16,15 @@ test("places gained or lost since the start - only for heats and finals started assert.equal(getPositionChange({ ...final, startMode: "flying" }, order, "e", 2), null, "no common start order"); assert.equal(getPositionChange(null, order, "e", 2), null); }); + +test("laps go to the session actually running when another one is selected", async () => { + const { getLiveSession } = await import("../src/timing_logic.js"); + const session = (id, status, startedAt = 0) => ({ id, status, startedAt }); + const state = (activeSessionId, sessions) => ({ activeSessionId, sessions }); + assert.equal(getLiveSession({ state: state("b", [session("a", "running", 1), session("b", "running", 2)]) }).id, "b", "the selected session when it runs"); + assert.equal(getLiveSession({ state: state("next", [session("heat", "running", 5), session("next", "ready")]) }).id, "heat", "next heat picked while the current one runs"); + assert.equal(getLiveSession({ state: state("op2", [session("op1", "running", 5), session("op2", "ready"), session("old", "running", 1)]) }).id, "op1", "the most recently started running session"); + assert.equal(getLiveSession({ state: state("b", [session("a", "paused", 3), session("b", "finished")]) }).id, "a", "a paused session still counts as live"); + assert.equal(getLiveSession({ state: state("b", [session("a", "finished"), session("b", "ready")]) }).id, "b", "nothing running: the selected one"); + assert.equal(getLiveSession({ state: state("", []) }), null); +});