# Hotlap — TODO / next-session roadmap

Feature requests captured 2026-10-07. Grouped by area, with data sources, likely
code locations, approach, and open questions so it can be executed directly.

## Known issues (as of 2026-10-17)

- [ ] **F1 historical archive is geo-gated** (new ~Oct 2026). A CloudFront edge
  function returns `401` for `…/static/` from blocked regions (not rate limiting
  — that's `429`; this is region/IP-based and began only after the gate was
  deployed). Live `/signalrcore` is fine; cached sessions load fully. Mitigated
  by: `HOTLAP_ARCHIVE_PROXY` (manual, reliable), auto proxy-discovery (free
  proxies rarely beat F1's extra datacenter-IP WAF `403`), and a prompted Ergast
  basic replay. *Open: is the gate permanent (→ needs an authed-archive path) or
  a geo rollout that lifts?*
- [ ] **Timeline size** — a race compiles to ~50 MB; add keyframes (faster
  backward seek) and/or HTTP compression for remote hosting.
- [ ] **Phantom loads** — an idle browser tab has issued stray session loads
  (server log, no user action); root-cause and fix.

## Requested (2026-10-08, round 6) — done

- [x] **Telemetry graph** reverted to the smooth, time-based trace (restored the
  committed version; x = seconds into lap, raw samples plotted).
- [x] **Elevation for all 40 circuits** baked into `web/public/circuits.geojson`
  (`[lng, lat, elevation]`) from open topography APIs — Open-Meteo, with
  Open-Elevation as the fallback for the last 4 that hit rate limits.
- [x] **Interactive 3D track** (`web/src/panels/Track3D.tsx`, three.js +
  OrbitControls) built from circuit geo + baked elevation (no longer car
  position); rotate / zoom / pan. three.js is lazy-loaded.
- [x] **Yellow / double-yellow area highlight** on 2D + 3D maps — net
  per-marshalling-sector state (YELLOW sets, CLEAR resets) → highlight every
  active sector. *Approx: assumes the outline starts at S/F and runs in point
  order (geo data has no marshalling-sector labels).*
- [x] **Start/finish line** marked on every map (2D white bar, 3D white gate) at
  the outline's first point.
- [x] **Liquid-glass UI** (iOS-style translucent + blurred panels/chrome with a
  specular hairline) over a themed F1 background. Tokens in `theme.css`, applied
  at the end of `panels.css`.
- [x] **Landing / home page** (`web/src/components/Landing.tsx`) — F1-themed,
  mouse parallax, next-race **countdown in the viewer's local time zone**, full
  season calendar as cards. Calendar proxied by the core via new
  `GET /api/calendar/:year` (Jolpica/Ergast; it sends no CORS header).

## Requested (2026-10-09, round 9) — done

- [x] **Use the ungated live topics** found on `/signalrcore`. Plumbed through
  schema → parser (robust to array/index-keyed deltas) → live subscribe →
  historical `STREAM_TOPICS` → generated TS types, and surfaced in the UI:
  - **`LapSeries`** → new **Race Chart** panel (position-by-lap graph).
  - **`TopThree`** → podium strip atop the Race Chart.
  - **`CurrentTyres`** → current-compound chip in the Strategy panel.
  - **`PitLaneTimeCollection`** → pit-lane time badge in Strategy (fills in
    during races).
  - **`WeatherDataSeries`** → track/air-temp sparklines in the Weather panel.
  - **`AudioStreams`** → live-audio player in the Commentary panel (native HLS;
    plays in Safari, may not in Chrome without hls.js).
  - Verified live against Singapore Sprint Qualifying. Only `CarData.z` /
    `Position.z` remain F1-TV-gated.

## Requested (2026-10-09, round 8) — done

- [x] **Live ingestion fixed** — F1 retired the legacy ASP.NET SignalR hub
  (`/signalr`, now 401) in 2025 and moved to ASP.NET **Core** SignalR
  (`/signalrcore`). Rewrote `crates/hotlap-signalr` for the new protocol
  (POST negotiate → `wss://…/signalrcore?id=<token>` with the affinity cookie →
  `{"protocol":"json","version":1}` handshake → Subscribe invocation → `␞`-
  delimited frames: type 3 snapshot, type 1 `feed`, type 6 ping). **Verified live**
  against Singapore 2026 Sprint Qualifying: 22 drivers, live timing/weather/race
  control, no auth. `CarData.z`/`Position.z` (car telemetry + positions) still
  need an F1 TV cookie (`--auth` / `$HOTLAP_F1_COOKIE`).
- [ ] *(Follow-on)* let `hotlap serve` attach a **live source at runtime** (a Hub
  "go live" action + endpoint) so the landing **Live session** button lights up
  and works, instead of needing the separate `hotlap live` command. (The button
  currently gates on `replay.source === "live"`, which `serve` never sets.)

## Requested (2026-10-08, round 7) — done

- [x] **Two landing entry points** replacing "Enter Telemetry": **Live session**
  (gated on `replay?.source === "live"` from the store — disabled/greyed with a
  live dot when no live source) and **Replay session** (enters the workspace /
  picker flow). *(Round 8 fixed live ingestion, but `serve` doesn't attach a live
  source yet — see the round-8 follow-on.)*
- [x] **Calendar shows every weekend session** — FP1/FP2/FP3, Sprint Quali,
  Sprint, Quali, Race — each with its own local-zone date/time; sprint weekends
  omit FP2/FP3. The **countdown targets the next *session*** across the whole
  calendar, not just the next race.
- [x] **Live, breathing red orb** that roams the screen — a blurred radial blob
  with a CSS breathe animation, repositioned to a random spot every ~6.5 s (CSS
  eases the glide); respects `prefers-reduced-motion`.
- [x] User-facing framing simplified to **"live & historical"** (dropped
  "recorded" from the tagline); entry points named **Live session** /
  **Replay session**. *(The architecture docs keep "recorded" where it names the
  real recording adapter.)*
- [ ] *(Optional follow-on, not done)* make the calendar/next-session cards
  clickable to jump straight into that race's historical session (map Jolpica
  `raceName` → the archive event name used by `GET /api/index/:year`).

## Requested (2026-10-07, round 3) — done

- [x] Commentary **time-synced** to the replay (anchor post times to a feed
  Utc+offset; reveals as the playhead reaches each post).
- [x] **Fast seek** — rebuild applies only the latest CarData/Position before the
  target (no mass re-inflation); ~0.3s scrubs.
- [x] **Timeline event markers** — core::compute_events → Hub → GET /api/events →
  coloured ticks on the slider (start/flags/SC/VSC/red/finish).
- [x] **Track Details compact** — map | (weather + race control) inline.
- [x] **SVG track map** (clean line from an ordered reference-car path) + **2D/3D**
  toggle (CSS perspective).
- [x] **Static circuit SVGs** — f1-circuits GeoJSON bundled (web/public), matched
  by circuit name (stopword-filtered), drawn in Track Details when no position
  data is present; 2D/3D toggle applies.
- [x] **Cleaner traced line** — reference car is now the leader (clean racing
  laps). *Still partial until a full lap traces; a multi-car ordered outline, or
  always-use-static-outline-with-aligned-dots, would be the next step.*
- [ ] Commentary for `hotlap live` (fetch ContentStreams on connect) — now
  testable (live ingestion works via `/signalrcore`, round 8).

## Requested next (2026-10-07 — partly done)

- [x] **Telemetry fixed** — responsive layout; compare now **lap-aligned** (x =
  seconds into each driver's own lap, reset on lap increment).
- [x] **Default layout** — Team Radio in the old Weather slot; Weather closed by
  default (also inline in Track Details) + on the taskbar.
- [x] **Session picker** (`hotlap serve` + top-bar dropdowns): a server **Hub**
  swaps the current replay at runtime; REST `GET /api/years`,
  `GET /api/index/:year`, `POST /api/session/load`, `GET /api/session/status`;
  control routes to the current replay; WS resyncs on the new snapshot. Verified
  loading 2024 Spanish GP Race from the dropdowns.
- [x] **Commentary** = F1's real live-blog. ContentStreams → the Monterosa
  commentary URI (2024+; 2023- used the dead ScribbleLive) → that event's static
  `https://{host}/events/{id[:2]}/{id}/history.json` timeline. `fetch_commentary`
  in core/historical pulls + HTML-strips the posts into `SessionState.commentary`
  (title + text); shown in the Commentary window. *Later: (1) time-sync posts to
  the replay playhead (currently all at offset 0) by anchoring post timestamps to
  a feed Utc+offset pair; (2) Monterosa WebSocket (`edgeservers-nlb-europe`,
  subscribe `Live-{projectId}`) for live deltas; (3) commentary for `hotlap live`
  (fetch ContentStreams on connect).*

## Progress (2026-10-07, same day)

- [x] **P5 — `historical` in core** (`hotlap historical <year> <gp> <session>`):
  Rust port of the export tool in `hotlap-core::historical` — resolves the
  session from the season Index, downloads the archived `.jsonStream` topics
  (percent-encoding + exact-name matching), parses + windows/downsamples into a
  Recording, caches raw downloads under the OS cache dir, and replays through
  both UIs. **Verified end-to-end** on 2023 Monaco Qualifying (public archive, no
  login). *Later: Jolpica/Ergast for nicer event lookup; a historical browser
  panel.*
- [x] **P4 — Live ingest** (`hotlap live`): F1 Live Timing **SignalR client**
  (negotiate → ws connect → Subscribe → parse `R`/`M` frames → RawMessage),
  wired to the engine + optional recorder, decoupled via an mpsc channel.
  Frame parsing unit-tested. **Caveat**: since 2025 the live feed returns **401**
  without an authenticated F1 TV session — handled gracefully with a clear
  message; `--auth`/`$HOTLAP_F1_COOKIE` forwards a session cookie. Could not be
  end-to-end verified here (no F1 TV creds / no guaranteed live session); the
  static archive path it shares *is* verified. *Later: real F1 TV OAuth login
  flow (`hotlap login`), reconnect/backoff.*
- [x] **P3 — TUI** (`hotlap tui --replay <dir>`): ratatui dashboard sharing the
  engine in-process — timing tower (team colours, lap/sector colours, tyres),
  track-map braille canvas, telemetry (gauges), conditions, race control, and
  keyboard transport (play/pause/seek/speed/driver-focus). *Later: resizable
  panels/workspaces, `--live`/`--connect`, Sixel track map, prediction pane.*


- [x] **#1 Telemetry throttle/brake graphs** — Speed+Throttle+Brake traces.
- [x] **#1b Multi-driver telemetry compare** — overlay up to 3 drivers' speed
  (time-aligned on the primary's cadence). *Later: distance-aligned lap compare.*
- [x] **#4 Track Details** — weather inline (map left, weather right) + flag-state
  map highlighting (red/yellow/double/SC/VSC/green + sector badge).
  *Later: per-sector map-region tinting (needs marshal-sector → map mapping).*
- [x] **#5 Team radio** — SessionInfo `path` exposed; TeamRadio exported; clips
  play inline from F1's static host.
- [x] **#2 Timing-tower live sector delta** — per-driver running delta vs the
  session-best cumulative at the latest completed sector (S1/S2/Lap).
- [~] **#3 Prediction window** — deterministic v1 done for **both modes**:
  - Quali: cut-off predictor (segment inference, cut line, SAFE/DANGER/OUT,
    bubble narrative).
  - Race: projected podium + threats, undercut-window flags (~2.5s of car
    ahead), tyre/pit/interval table, templated summary. Pit loss hardcoded 22s.
    Verified on real 2023 São Paulo GP.
  - *Remaining: tyre-degradation model for smarter undercut/overcut + pace-based
    finish projection; per-track pit-loss table; then the **SLM narrative**
    (phase 2 — user chose deterministic-first); consider moving the math into a
    Rust `predict.rs` so the TUI/SLM share it.*
  - Race data is large (~10MB full race) so it's exported to the gitignored
    `data/` dir, not committed: `tools/export_session.py 2023 "Paulo" Race data/…`.
    The committed default stays Monaco quali.

## Where the project stands (context for next session)

- Branch `feat/core-pipeline` (not pushed). Commits: P0 scaffold → P1 core
  pipeline → P2 web GUI → polish → **window manager + real data** → quali polish.
- **Core (Rust)**: `crates/hotlap-{schema,core,signalr,server,tui,cli}`. Pipeline =
  source → `parser` → `engine` (state + RFC7386 merge-patch broadcast) → axum WS/REST.
  Replay clock with play/pause/seek/speed. 22 tests green.
- **Web (`web/`)**: React + TS, **free-floating window manager** (react-rnd,
  `src/windows.ts` + `src/components/WindowManager.tsx`), zustand store
  (`src/store.ts`, applies merge patches, keeps a position `trail`). Panels in
  `src/panels/`: TimingTower, Telemetry (uPlot speed trace), TrackDetails (map +
  status + race control), Strategy, Weather. Types generated from Rust schema
  (`src/types.gen.ts`, `npm run gen:types`).
- **Data**: real sessions via `tools/export_session.py` (pulls F1 archived
  `.jsonStream` from `livetiming.formula1.com/static/...`). Default fixture
  `fixtures/monaco-2023-quali/`. `fixtures/sample/` is the tiny test fixture.
- Run: `cd web && npm run build`, then `cargo run -p hotlap-cli -- replay fixtures/monaco-2023-quali/`.
  Stop a running core: `pkill -f 'hotlap replay'`.
- Still unbuilt from the original plan: **P3 TUI**, **P4 live ingest**, **P5
  `hotlap historical` as a first-class command** (fold `export_session.py` into Rust).

---

## 1. Telemetry graphs — throttle & braking, multi-driver compare

- **Add throttle + brake traces** to the Telemetry window (today it only plots
  speed). Data already in state: `car[num].throttle`, `.brake` (`CarTelemetry`).
  Extend the rolling buffer in `web/src/panels/Telemetry.tsx` to also buffer
  throttle/brake; render as a second uPlot (0–100 scale) or stacked panels, or a
  shared uPlot with multiple y-scales. Consider adding gear/RPM too.
- **Compare with other drivers**: overlay 2–3 drivers' speed/throttle/brake for
  the current lap.
  - Need per-driver channel history (buffer multiple drivers, not just focus).
  - Alignment: by **lap distance** is ideal but we have no distance channel —
    options: integrate speed over time to approximate distance, or align by
    time-into-lap (detect lap start from `TimingData.NumberOfLaps` increment /
    sector 1 start). Start with time-into-current-lap alignment; note it's
    approximate.
  - UI: a compare mode with a driver multi-select; colour traces by team.
- Open Q: live (streaming) compare vs lap-over-lap compare. Start with live
  current-lap overlay.

## 2. Timing tower — live lap-time delta between all drivers

- Add a **delta** indicator per row: how each driver's pace compares live
  (gaining/losing vs the car ahead or vs leader), and/or last-lap delta to their
  own best / to the session best.
- Data: track a short history of `gapToLeader` / `intervalToAhead` (race) or
  best-lap deltas (quali). Compute trend (▲/▼ + tenths) over the last N updates.
- Code: `web/src/panels/TimingTower.tsx`; may need the store to keep a small
  rolling history of gaps per driver (like `trail`), or compute from successive
  patches. Colour green when gaining, red when losing.

## 3. Prediction window (analytics + SLM narrative) — BIG, phase it

**DONE (2026-11-03): ML predictive models.** Trained offline in `ml/build_models.py`
and shipped as JSON (`web/public/ml/{winner,strategy}_model.json`), evaluated in
`web/src/ml.ts` — no runtime Python/ONNX (see `ml/README.md` for why coefficients
beat `tract` here). The **Prediction** panel race mode now shows win/podium
probabilities (trained grid→result curves + rating adjustment, sharpened by race
progress) and per-driver strategy calls; the **Strategy** panel shows a tyre-loss
meter + pit window from a one-stop-from-here simulation over learned tyre-deg +
pit-loss curves. Quali cut-off predictor already existed. Verified in-browser
against the São Paulo replay (box-now for shot tyres early, run-to-end late).

Remaining in this section:

- **Race podium (P1/P2/P3)**: ✅ win/podium probabilities now model-based.
  *Future:* lap-by-lap mid-race training for a fit (not chosen) progress term.
- **Quali cut-off (Q1/Q2)**: ✅ segment inference + cut line + SAFE/DANGER/OUT.
- **Tyre strategy**: ✅ pit-window + undercut from learned deg + per-circuit pit
  loss. *Future:* fit fresh-compound offsets properly (currently a prior); model
  the field's response to a stop so the call prices in track position, not just
  pace.
- **Natural-language predictions via a small LM (SLM)**: feed the structured
  predictions + race state into an SLM to produce readable summaries, including
  **edge cases: weather change, SC, VSC**. 
  - Open Q: which SLM and how to host — local (llama.cpp / Ollama, a small
    Qwen/Llama/Gemma) for offline, or the Claude API. Decide hosting; keep the
    numeric predictions deterministic and use the LM only for phrasing/reasoning
    over the computed facts (avoid hallucinated numbers).
  - Core: add `crates/hotlap-core/src/predict.rs` (deterministic) + an optional
    predictions feed/endpoint; LM integration likely a separate service/crate.
- Big feature — build in stages: (a) quali cut-off (simplest, deterministic),
  (b) race podium projection, (c) undercut/overcut, (d) SLM narrative.

## 4. Track Details — weather inline + flag highlighting + sectors

- **Layout**: restructure Track Details to **map on the left, weather on the
  right** (move/duplicate the Weather content in), with race control below.
  (The standalone Weather window can stay as an option, or be removed — decide.)
- **Flag-state map highlighting** driven by `TrackStatus.status` + sector info
  from `RaceControlMessages` (Flag + Scope=Sector + Sector N; distinguish
  `YELLOW` vs `DOUBLE YELLOW`). Visual states on the map:
  | Condition | Visual |
  |-----------|--------|
  | Red flag (status 5) | gentle **blinking red** overlay |
  | Single yellow (RC Flag YELLOW) | **steady yellow**, + show which sector |
  | Double yellow (RC Flag DOUBLE YELLOW) | gentle **blinking yellow** |
  | Safety Car (status 4) | **steady orange-yellow** |
  | Virtual SC (status 6) | gentle **blinking orange-yellow** |
  | Back to green (status 1) | flash **green for ~1s** then clear |
  - Implement as a CSS overlay on the map container with keyframe blink
    animations; a small state machine maps TrackStatus/RC → visual state.
  - Sector-specific tinting on the map geometry needs marshal-sector → map-region
    mapping, which we don't have. **Start with**: whole-map tint + a text badge
    ("Yellow — Sector 7"). Per-sector map regions = later (needs marshal sector
    position data / track segmentation).

## 5. Team radio

- Show **team radio** clips. We already parse `TeamRadioClip { utc, racingNumber,
  path }` (`TeamRadio` topic). Add a radio feed (new window or inside Track
  Details / Race Control) listing clips with driver + timestamp + a play button.
- Audio URL: `https://livetiming.formula1.com/static/<session-path>/<path>` — the
  session path is in `meta.json` (`path`) for exported sessions. For live it's the
  current session base. Play via an HTML `<audio>` element.
- Open Q: expose the session base path to the web (add to SessionInfo/state or a
  REST endpoint) so the client can build audio URLs. For replay/historical the
  clips exist on the F1 static host; confirm CORS (may need the core to proxy the
  audio).

---

## Suggested order next session
1. Quick wins: throttle/brake graphs (#1 first half), team radio feed (#5),
   weather-into-Track-Details + flag highlighting whole-map tint (#4).
2. Timing-tower live delta (#2).
3. Multi-driver telemetry compare (#1 second half).
4. Prediction window in stages (#3): quali cut-off → podium → undercut/overcut →
   SLM narrative.
