import { test, expect } from '@playwright/test' // The e2e server runs with BOXBOX_DISABLE_LIVE=1, so the real feed is silent. // These tests mock /api/v1/live/state with a race snapshot to exercise the // full timing page: flag banner, weather strip, battles, stints, and pinning. const driver = ( num: string, pos: number, interval: string, gap: string, overrides: Record = {}, ) => ({ RacingNumber: num, Position: pos, PrevPosition: pos, GapToLeader: gap, Interval: interval, LastLapTime: '1:21.345', LastLapPB: false, LastLapOB: false, BestLapTime: '1:20.987', BestLapPB: true, BestLapOB: false, BestLapNum: 22, InPit: false, PitOut: false, Retired: false, KnockedOut: false, Cutoff: false, OnFlyingLap: false, NumberOfLaps: 30, SpeedTrap: '312', Sectors: [], ...overrides, }) const info = (num: string, tla: string, first: string, last: string, team: string, colour: string) => ({ RacingNumber: num, BroadcastName: `${first[0]} ${last.toUpperCase()}`, Tla: tla, TeamName: team, TeamColour: colour, FirstName: first, LastName: last, }) const raceSnapshot = { is_live: true, data: { Drivers: { '1': driver('1', 1, '', '', { NumberOfLaps: 30 }), '4': driver('4', 2, '+0.523', '+0.523'), '44': driver('44', 3, '+3.214', '+3.737'), '63': driver('63', 4, '+12.001', '+15.738', { InPit: true }), }, DriverInfo: { '1': info('1', 'VER', 'Max', 'Verstappen', 'Red Bull Racing', '3671C6'), '4': info('4', 'NOR', 'Lando', 'Norris', 'McLaren', 'FF8000'), '44': info('44', 'HAM', 'Lewis', 'Hamilton', 'Ferrari', 'E80020'), '63': info('63', 'RUS', 'George', 'Russell', 'Mercedes', '27F4D2'), }, Tyres: { '1': { Compound: 'HARD', New: false, Age: 12 }, '4': { Compound: 'MEDIUM', New: false, Age: 8 }, '44': { Compound: 'MEDIUM', New: true, Age: 3 }, '63': { Compound: 'HARD', New: true, Age: 0 }, }, Stints: { '1': [ { Compound: 'MEDIUM', New: true, Laps: 18 }, { Compound: 'HARD', New: false, Laps: 12 }, ], '4': [ { Compound: 'SOFT', New: true, Laps: 14 }, { Compound: 'MEDIUM', New: true, Laps: 16 }, ], }, RCMessages: [ { Time: '2026-07-03T14:05:00Z', Category: 'Flag', Flag: 'YELLOW', Message: 'YELLOW IN SECTOR 2', Lap: 29 }, ], Weather: { AirTemp: 22.5, TrackTemp: 41.3, Humidity: 58, WindSpeed: 3.4, WindDir: 180, Rainfall: false, }, Session: { MeetingName: 'Testonia Grand Prix', CircuitName: 'Testring', SessionType: 'Race', SessionName: 'Race', }, SessionStatus: 'Started', TrackStatus: '2', CurrentLap: 30, TotalLaps: 57, Clock: '', ClockRefTime: '', ClockExtrapolating: false, }, } const sprintQualifyingSnapshot = { is_live: true, data: { ...raceSnapshot.data, Drivers: Object.fromEntries( Array.from({ length: 22 }, (_, index) => { const num = String(index + 1) return [ num, driver(num, index + 1, index === 0 ? '' : `+${(index * 0.123).toFixed(3)}`, index === 0 ? '' : `+${(index * 0.123).toFixed(3)}`, { LastLapTime: index < 2 ? '1:29.273' : '', BestLapTime: `1:${String(29 + Math.floor(index / 10)).padStart(2, '0')}.${String(273 + index).padStart(3, '0')}`, NumberOfLaps: 4, Sectors: index === 7 ? [{ Value: '28.573', PersonalFastest: false, OverallFastest: false }, { Value: '', PersonalFastest: false, OverallFastest: false }, { Value: '', PersonalFastest: false, OverallFastest: false }] : [], OnFlyingLap: index === 7, }), ] }), ), DriverInfo: Object.fromEntries( Array.from({ length: 22 }, (_, index) => { const num = String(index + 1) return [num, info(num, `D${index + 1}`, 'Driver', String(index + 1), 'Test Team', index % 2 ? 'FF8000' : '27F4D2')] }), ), Tyres: Object.fromEntries( Array.from({ length: 22 }, (_, index) => [String(index + 1), { Compound: 'MEDIUM', New: false, Age: index % 4 }]), ), Session: { MeetingName: 'British Grand Prix', CircuitName: 'Silverstone', SessionType: 'Sprint Qualifying', SessionName: 'Sprint Qualifying', }, SessionStatus: 'Started', TrackStatus: '1', CurrentLap: 0, TotalLaps: 0, Clock: '00:02:11', ClockRefTime: '2026-07-03T15:39:49Z', ClockExtrapolating: false, }, } test.describe('Live Timing (mocked snapshot)', () => { test.beforeEach(async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(raceSnapshot) }), ) // A single heartbeat then EOF; the page keeps the query snapshot either way. await page.route('**/api/v1/live/stream', (route) => route.fulfill({ contentType: 'text/event-stream', body: 'event: heartbeat\ndata: {}\n\n', }), ) await page.goto('/live') }) test('renders timing tower with drivers from the snapshot', async ({ page }) => { await expect(page.getByTestId('live-page')).toBeVisible() // The hermetic SSE mock ends after a heartbeat, so transport may drop to // disconnected while the session snapshot remains active — both phases keep // the LIVE SESSION chrome and timing tower. await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', /^(live|disconnected)$/) await expect(page.getByTestId('live-session-flag')).toContainText('LIVE SESSION') await expect(page.getByTestId('live-feed-health')).toBeVisible() const tower = page.locator('.live-tower') await expect(tower).toBeVisible() await expect(tower).toContainText('VER') await expect(tower).toContainText('NOR') await expect(tower).toContainText('HAM') await expect(tower.locator('tr.in-pit')).toContainText('RUS') }) test('shows yellow flag banner from TrackStatus', async ({ page }) => { const banner = page.getByTestId('track-banner') await expect(banner).toBeVisible() await expect(banner).toContainText('YELLOW FLAG') }) test('shows weather strip with track temperature', async ({ page }) => { const weather = page.getByTestId('weather-strip') await expect(weather).toBeVisible() await expect(weather).toContainText('41°C') }) test('detects the VER/NOR battle and highlights it', async ({ page }) => { const chips = page.getByTestId('battle-chips') await expect(chips).toBeVisible() await expect(chips).toContainText('VER ⚔ NOR') // The in-pit car must never be part of a battle group. await expect(chips).not.toContainText('RUS') }) test('renders stint history for drivers that have stints', async ({ page }) => { await page.locator('.live-tower tbody tr', { hasText: 'VER' }).click() await expect(page.getByTestId('stint-seq').first()).toBeVisible() }) test('clicking a pin button pins the driver to the focus strip', async ({ page }) => { await page.locator('.live-tower tbody tr', { hasText: 'VER' }).locator('.pin-btn').click() const pinned = page.getByTestId('pinned-strip') await expect(pinned).toBeVisible() await expect(pinned).toContainText('VER') // Unpin restores the empty strip. await page.locator('.live-tower tbody tr', { hasText: 'VER' }).locator('.pin-btn').click() await expect(page.getByTestId('pinned-strip')).toHaveCount(0) }) }) test.describe('Live Timing (mocked Sprint Qualifying)', () => { test.beforeEach(async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(sprintQualifyingSnapshot) }), ) await page.route('**/api/v1/live/stream', (route) => route.fulfill({ contentType: 'text/event-stream', body: 'event: heartbeat\ndata: {}\n\n', }), ) await page.goto('/live') }) test('shows SQ1 phase, large clock, and 22-car cutoff after P17', async ({ page }) => { await expect(page.getByText('SQ1', { exact: true })).toBeVisible() await expect(page.getByTestId('live-clock')).toContainText('00:02:11') await expect(page.getByTestId('qualifying-cutoff')).toContainText('P17 advance') await expect(page.getByTestId('qualifying-cutoff')).toContainText('P18-P22 at risk') await expect(page.locator('.live-tower tbody tr', { hasText: 'D18' })).toHaveClass(/danger-row/) await expect(page.locator('.live-tower tbody tr', { hasText: 'D8' })).toHaveClass(/flying-row/) }) }) const weekendContext = (localAnalysis: string) => ({ temporal_state: 'session_settling', focus_meeting: { meeting_key: 1, meeting_name: 'Testonia Grand Prix', meeting_official_name: 'Testonia Grand Prix', location: 'Testring', country_name: 'Testonia', country_code: 'TS', country_flag: '', circuit_short_name: 'Testring', date_start: '2026-07-03T09:00:00Z', date_end: '2026-07-05T16:00:00Z', year: 2026, }, // Just-finished session lives in previous_completed_session (canonical contract). previous_completed_session: { session: { session_key: 9472, session_name: 'Race', session_type: 'Race', meeting_key: 1, date_start: '2026-07-05T14:00:00Z', date_end: '2026-07-05T16:00:00Z', gmt_offset: '', }, availability: { schedule: 'available', live_transport: 'unknown', live_session: 'inactive', archive: 'available', local_analysis: localAnalysis, freshness: 'fresh', limitations: [], }, }, championship_round: 1, total_championship_rounds: 1, }) /** Archive-only just-finished Race + older already-ready Practice default. */ const archiveOnlySettlingContext = (previousAnalysis: string) => ({ ...weekendContext(previousAnalysis), default_analysis_session: { session: { session_key: 9001, session_name: 'Practice 1', session_type: 'Practice', meeting_key: 1, date_start: '2026-07-04T12:00:00Z', date_end: '2026-07-04T13:00:00Z', gmt_offset: '', }, availability: { schedule: 'available', live_transport: 'unknown', live_session: 'inactive', archive: 'available', local_analysis: 'complete', freshness: 'fresh', limitations: [], }, }, }) const heartbeatStream = (route: import('@playwright/test').Route) => route.fulfill({ contentType: 'text/event-stream', body: 'event: heartbeat\ndata: {}\n\n' }) test.describe('Live Timing (no session)', () => { test('shows the inactive weekend-context handoff when the feed has no snapshot', async ({ page }) => { await page.route('**/api/v1/live/stream', heartbeatStream) await page.goto('/live') // The e2e server (BOXBOX_DISABLE_LIVE=1) exposes a real /api/v1/weekend-context. await expect(page.getByTestId('live-inactive')).toBeVisible() await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', 'inactive') await expect(page.getByText('NO LIVE SESSION')).toBeVisible() }) test('enters settling (not archive) when a finished session is retained', async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ is_live: false, data: null, last_snapshot: { ...raceSnapshot.data, SessionStatus: 'Finished' }, last_positions: { '1': { x: 100, y: -50, z: 2, status: 'OnTrack' } }, last_snapshot_at: '2026-07-04T14:00:00Z', }), }), ) await page.route('**/api/v1/weekend-context', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(weekendContext('complete')) }), ) await page.route('**/api/v1/live/stream', heartbeatStream) await page.goto('/live') await expect(page.getByTestId('live-settling')).toBeVisible() await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', 'settling') await expect(page.getByText('SESSION SETTLING')).toBeVisible() await expect(page.getByText('Timing Tower')).toHaveCount(0) // Canonical weekend-context drives the analysis target + readiness. const analysis = page.getByTestId('live-handoff-analysis') await expect(analysis).toHaveAttribute('href', '/race-hub?session_key=9472') await expect(analysis).toHaveAttribute('data-ready', 'true') // Opening the read-only archive reveals the frozen tower, never LIVE chrome. await page.getByTestId('live-handoff-archive').click() await expect(page.getByTestId('live-archive-strip')).toContainText('read-only') await expect(page.getByText('Timing Tower')).toBeVisible() await expect(page.locator('.live-state')).toContainText('archive') await expect(page.getByText('LIVE SESSION')).toHaveCount(0) }) test('settling shows pending analysis until weekend-context reports complete', async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ is_live: false, data: null, last_snapshot: { ...raceSnapshot.data, SessionStatus: 'Finished' }, last_snapshot_at: '2026-07-04T14:00:00Z', }), }), ) await page.route('**/api/v1/weekend-context', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(weekendContext('pending')) }), ) await page.route('**/api/v1/live/stream', heartbeatStream) await page.goto('/live') await expect(page.getByTestId('live-settling')).toBeVisible() const analysis = page.getByTestId('live-handoff-analysis') await expect(analysis).toHaveAttribute('data-ready', 'false') await expect(analysis).toContainText(/analysis will fill in as data ingests/i) }) test('settling targets archive-only previous_completed_session over older default', async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ is_live: false, data: null, last_snapshot: { ...raceSnapshot.data, SessionStatus: 'Finished' }, last_snapshot_at: '2026-07-04T14:00:00Z', }), }), ) await page.route('**/api/v1/weekend-context', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(archiveOnlySettlingContext('pending')), }), ) await page.route('**/api/v1/live/stream', heartbeatStream) await page.goto('/live') await expect(page.getByTestId('live-settling')).toBeVisible() const analysis = page.getByTestId('live-handoff-analysis') await expect(analysis).toHaveAttribute('href', '/race-hub?session_key=9472') await expect(analysis).toHaveAttribute('data-ready', 'false') await expect(analysis).toContainText('Open Race analysis') await expect(analysis).not.toContainText('Practice 1') }) test('retains the last live snapshot with a disconnected warning on a feed drop', async ({ page }) => { // is_live=false but SessionStatus is still "Started": the FIA feed dropped // mid-session. The page must warn + retain the live tower, never settle. // Keep the browser SSE open via a long-lived stream so transport stays connected // while phase is disconnected — health must still say Reconnecting. await page.route('**/api/v1/live/state', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ is_live: false, data: null, last_snapshot: { ...raceSnapshot.data, SessionStatus: 'Started' }, last_snapshot_at: '2026-07-04T13:30:00Z', }), }), ) await page.route('**/api/v1/weekend-context', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(weekendContext('pending')) }), ) await page.route('**/api/v1/live/stream', async (route) => { const body = [ 'event: heartbeat', 'data: {}', '', 'event: heartbeat', 'data: {}', '', ].join('\n') await route.fulfill({ contentType: 'text/event-stream', headers: { 'Cache-Control': 'no-cache' }, body, }) }) await page.goto('/live') await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', 'disconnected') await expect(page.getByTestId('live-disconnected-strip')).toContainText('last live data') await expect(page.getByText('Timing Tower')).toBeVisible() await expect(page.getByTestId('live-settling')).toHaveCount(0) await expect(page.getByTestId('live-archive-strip')).toHaveCount(0) await expect(page.getByTestId('live-feed-health')).toContainText(/reconnecting/i) await expect(page.getByTestId('live-feed-health')).not.toContainText(/feed healthy/i) }) test('clears fatal initial error once SSE supplies a live snapshot', async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'API 503: live state unavailable' }), }), ) await page.route('**/api/v1/live/stream', (route) => route.fulfill({ contentType: 'text/event-stream', headers: { 'Cache-Control': 'no-cache' }, body: `event: snapshot\ndata: ${JSON.stringify(raceSnapshot)}\n\n`, }), ) await page.goto('/live') await expect(page.getByText('Timing Tower')).toBeVisible({ timeout: 15_000 }) await expect(page.getByTestId('live-initial-error')).toHaveCount(0) await expect(page.getByText(/Live timing unavailable/i)).toHaveCount(0) await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', /^(live|disconnected)$/) await expect(page.locator('.live-tower')).toContainText('VER') }) test('clears fatal initial error once SSE supplies an inactive null state', async ({ page }) => { await page.route('**/api/v1/live/state', (route) => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'API 503: live state unavailable' }), }), ) await page.route('**/api/v1/live/stream', (route) => route.fulfill({ contentType: 'text/event-stream', headers: { 'Cache-Control': 'no-cache' }, body: `event: snapshot\ndata: ${JSON.stringify({ is_live: false, data: null, last_snapshot: null, })}\n\n`, }), ) await page.goto('/live') await expect(page.getByTestId('live-inactive')).toBeVisible({ timeout: 15_000 }) await expect(page.getByTestId('live-initial-error')).toHaveCount(0) await expect(page.getByText(/Live timing unavailable/i)).toHaveCount(0) await expect(page.getByTestId('live-page')).toHaveAttribute('data-phase', 'inactive') }) })