From b096b45975b0a0b13296e7ce8d2068b5d4be2b14 Mon Sep 17 00:00:00 2001 From: Nirmith Victor Date: Sat, 21 Nov 2026 13:51:57 -0500 Subject: [PATCH] Add finite sandbox races and live driver pit calls --- README.md | 1 + docs/DEMO.md | 4 +- docs/FOLLOW-UP-PLAN.md | 4 +- docs/TESTING.md | 5 +- docs/USER-GUIDE.md | 6 +- docs/flows.json | 26 +++++++- docs/guide/05-race-sandbox.md | 35 ++++++++-- frontend/e2e/sandbox.spec.ts | 61 ++++++++++++++++++ frontend/src/CircuitSandbox.tsx | 111 +++++++++++++++++++++----------- frontend/src/sandbox.test.ts | 56 ++++++++++++++++ frontend/src/sandbox.ts | 104 ++++++++++++++++++++++++++---- 11 files changed, 351 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index e68ad08..b41dff3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def - Approximate sector markers aligned to a completed lap's recorded sector clock and location samples; missing references stay hidden. - A held-out pace backtest comparing past-only flat and trend baselines with later recorded laps, with explicit errors and pit-free/data-quality requirements. - A circuit race sandbox with editable connected pit lanes, one to six named/coloured drivers, individual pace, scheduled service stops, a simulated running order and browser-saved setups. +- Finite 1–50 lap fictional races with exact finish times/results, plus selected-driver live pit calls, cancellation before entry and repeat visits. See [race sessions](docs/guide/05-race-sandbox.md#sandbox-08). - On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview. - Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races. - Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL. diff --git a/docs/DEMO.md b/docs/DEMO.md index adeb16f..b6ff926 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -24,9 +24,11 @@ Open [Monza at 30 minutes](http://127.0.0.1:5080/?race=monza-2024&t=1800). The h 3. Edit pit handles or entry/exit percentages. Invalid crossing routes disable simulation until fixed; undo recovers. Save the circuit/race setup, reload it and export a session JSON. 4. Close the studio. The historical replay is still at its original race/time and retains its own map geometry. +The next session increment also lets you choose **Race distance (laps)**, select **Your driver**, cancel its scheduled call or **Box this lap**, and advance to **FINAL RESULTS**. Live calls preserve time; setup edits reset it. See [the full race-session flow](guide/05-race-sandbox.md#sandbox-08). + ## Engineering evidence -- [Testing guide](TESTING.md): 61 frontend unit checks, nine Node checks, 44 browser scenarios, real API/database integration and dedicated concurrency checks. +- [Testing guide](TESTING.md): 65 frontend unit checks, nine Node checks, 46 browser scenarios, real API/database integration and dedicated concurrency checks. - [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions. - `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions. - GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope. diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md index d1116f9..80d70be 100644 --- a/docs/FOLLOW-UP-PLAN.md +++ b/docs/FOLLOW-UP-PLAN.md @@ -43,7 +43,9 @@ The v1.2 studio implements local save/load, validated JSON import/export, dragga The v1.2 lab is an explicit deterministic comparison of two plans for one driver, sampled from recorded laps up to a chosen branch point. Users control pace adjustment, degradation, pit lap/loss and fresh-tyre gain; results include a cumulative difference plot, per-lap totals, local saved scenarios and JSON export. It does not model opponents, traffic, fuel, flags, weather, regulations or finishing positions. Historical validation and a physical/multi-driver model are still required before calling it a race predictor. -v1.3 adds held-out pace-baseline evaluation: past-only training within the current stint, later recorded evaluation laps, missing/pit-window exclusions and visible prediction errors. This is a first diagnostic for pace assumptions, not validation of counterfactual pit decisions. Next: benchmark multiple windows, add player-triggered decisions in the fictional sandbox, then evaluate richer models. +v1.3 adds held-out pace-baseline evaluation: past-only training within the current stint, later recorded evaluation laps, missing/pit-window exclusions and visible prediction errors. This is a first diagnostic for pace assumptions, not validation of counterfactual pit decisions. + +The first v1.4 increment implements finite fictional sessions (1–50 laps), deterministic finishing order/times, live selected-driver pit calls, cancellation before entry and repeat visits. See [the current sandbox guide](guide/05-race-sandbox.md). Next increments: explicit game-model tyre tradeoffs, a balanced upgrade budget, then complete session save/resume. These are planned; current setup saves do not restore runtime. ## Branch and validation workflow diff --git a/docs/TESTING.md b/docs/TESTING.md index 6a9e091..4fa7c1c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally. -## Playwright: 44 browser scenarios +## Playwright: 46 browser scenarios | Area | Coverage | | --- | --- | @@ -31,6 +31,7 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s | Analysis desk | Measured sector/pit views, replay jumps, retrospective vs replay scope, CSV exports, queued enrichment, failure/retry, refresh retaining cached data, mobile light layout | | Pace backtest | Past/holdout separation in exports, eligible-window search, invalid-window explanations, branch replay jumps, mobile layout | | Circuit race sandbox | Pit entry/service/exit, running order, driver settings, persistent setup/session export, pit validation and undo, keyboard handles, animation, tab isolation and storage/mobile recovery | +| Race sessions and live calls | Exact finite-race results/frozen clock, reset/distance preservation, cancellation without resetting, entry commitment, next-lap targeting and selected-driver/mobile controls | | Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode | | Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay | @@ -38,7 +39,7 @@ These scenarios run against the production frontend build in Chromium. Historica ## Other checks -- 61 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, and sandbox route/service transitions. +- 65 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. - Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping. - `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows. - Python integration checks cover the real API, input validation, race-specific bookmarks, SQL migrations, PostgreSQL restart persistence, and bundled trace ordering/bounds. A real cache upgrade was also checked against the development database to verify bookmark preservation. diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index 1081a7f..0329dac 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -2,7 +2,7 @@ **Product version:** 1.3.0 -**Last reviewed:** 2026-11-16 +**Last reviewed:** 2026-11-21 This is the current handbook for what each flow does, how to use it, what is saved, and how to recover. The [three-minute demo](DEMO.md) is a quick tour; release notes describe historical changes. This guide describes the current app. @@ -77,7 +77,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser -66 documented flows. Each ID links directly to its instructions. +68 documented flows. Each ID links directly to its instructions. ### Start Pitwall and choose a race @@ -164,6 +164,8 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [SANDBOX-05](guide/05-race-sandbox.md#sandbox-05) | Undo, reset the lane or reset the run | | [SANDBOX-06](guide/05-race-sandbox.md#sandbox-06) | Save and reopen a circuit/race setup | | [SANDBOX-07](guide/05-race-sandbox.md#sandbox-07) | Export a sandbox session | +| [SANDBOX-08](guide/05-race-sandbox.md#sandbox-08) | Choose a race distance and read final results | +| [SANDBOX-09](guide/05-race-sandbox.md#sandbox-09) | Make and cancel live pit calls | ### Storage, validation and keeping the guide current diff --git a/docs/flows.json b/docs/flows.json index 5bc4375..f836c6f 100644 --- a/docs/flows.json +++ b/docs/flows.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "productVersion": "1.3.0", - "lastReviewed": "2026-11-16", + "lastReviewed": "2026-11-21", "chapters": [ { "path": "docs/guide/01-start-library.md", @@ -738,6 +738,30 @@ "scripts/check-docs.mjs", "scripts/update-guide-index.mjs" ] + }, + { + "id": "SANDBOX-08", + "title": "Choose a race distance and read final results", + "guide": "docs/guide/05-race-sandbox.md", + "anchor": "sandbox-08", + "sources": [ + "frontend/src/CircuitSandbox.tsx", + "frontend/src/sandbox.ts", + "frontend/src/sandbox.test.ts", + "frontend/e2e/sandbox.spec.ts" + ] + }, + { + "id": "SANDBOX-09", + "title": "Make and cancel live pit calls", + "guide": "docs/guide/05-race-sandbox.md", + "anchor": "sandbox-09", + "sources": [ + "frontend/src/CircuitSandbox.tsx", + "frontend/src/sandbox.ts", + "frontend/src/sandbox.test.ts", + "frontend/e2e/sandbox.spec.ts" + ] } ] } diff --git a/docs/guide/05-race-sandbox.md b/docs/guide/05-race-sandbox.md index f840249..d734f56 100644 --- a/docs/guide/05-race-sandbox.md +++ b/docs/guide/05-race-sandbox.md @@ -31,10 +31,11 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip | Pace offset | −10 to +10 seconds added to base lap; negative is faster | | Pit on lap | 0 = no visit; 1–10 = one scheduled visit on that driver lap | | Service seconds | 0–15 stationary seconds at the pit route's midpoint | +| Race distance | 1–50 laps; default ten; old saved setups without this field open as ten laps | **Result and storage:** Configuration changes pause/reset the simulation clock and grid. Defaults use offsets 0, +2 and −1; only the first driver is scheduled to pit, on lap one, with 2.5-second service. Names/colours do not affect pace. Save to persist the configuration. -**Recovery and limits:** Empty/invalid driver settings block running/saving. Numeric inputs accept incomplete typing and apply bounds on blur/Enter. There are no compound, car-part, race-length or multiple-stop controls yet. +**Recovery and limits:** Empty/invalid driver settings block running/saving. Numeric inputs accept incomplete typing and apply bounds on blur/Enter. Scheduled stops at/beyond the finish have no effect. Live calls can add visits; there are no compound or car-part controls yet. ## SANDBOX-03 — Attach and edit the pit lane @@ -50,13 +51,13 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip ## SANDBOX-04 — Run, pause and advance the fictional race -**What:** Observe the configured pace and one optional pit/service visit per driver. +**What:** Observe the configured pace, scheduled/live pit visits and a fixed-distance race finish. **How:** Choose **Run sandbox** / **Pause sandbox**, set **Preview speed** to 1×, 5×, 10× or 25×, or use **Advance one lap** for a deterministic jump of one base-lap duration. **Result and storage:** The clock/order/markers advance. Drivers start on a staggered grid, enter the pit lane when scheduled, stop for service and rejoin at the configured exit. Pit speed is fixed at 35% of each driver's synthetic main-track speed. Speed changes do not reset the race; manual advance leaves it paused. -**Recovery and limits:** One base-lap jump does not mean every driver completed exactly one lap; pace and pit visits differ. **GRID**, **TRACK**, **PIT**, **SERVICE** and completed-stop labels explain state. There is no automatic fixed-distance finish or live “box now” control. Runtime clock/state is not restored by a saved setup. +**Recovery and limits:** One base-lap jump does not mean every driver completed exactly one lap; pace and pit visits differ. **GRID**, **TRACK**, **PIT**, **SERVICE** and **FINISHED** labels explain state. Finished drivers stop moving; advance/run disable when everyone finishes. Runtime clock/state is not restored by a saved setup. ## SANDBOX-05 — Undo, reset the lane or reset the run @@ -65,7 +66,7 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip **How:** Use **Undo sandbox edit** for a recorded configuration change, **Reset pit lane** for default lane geometry, or **Reset sandbox** to restart the current grid/run. -**Result and storage:** Undo uses a bounded in-memory setup history and resets the run. Reset pit lane keeps driver/base settings while restoring default entry/exit/handles. Reset sandbox keeps configuration but resets clock, positions and visits. None is an automatic persistence update. +**Result and storage:** Undo uses a bounded in-memory setup history and resets the run. Reset pit lane keeps driver/base settings while restoring default entry/exit/handles. Reset sandbox keeps configuration/distance but resets clock, positions, visits, finish times and live calls; configured scheduled stops return. None is an automatic persistence update. **Recovery and limits:** This history has no redo button and is not retained after closing. Saving/deleting circuit entries is outside sandbox undo. Resetting a run does not remove a browser-saved setup. @@ -76,7 +77,7 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip **How:** Choose **Save circuit and race setup**. On a later visit, use the editor's **Saved circuits → Load circuit**, then reopen **Circuit race sandbox**. -**Result and storage:** The circuit definition and its separately keyed setup are saved in this browser origin. Circuit capacity is 20. The setup restores driver and pit assumptions for that circuit ID, with a fresh run rather than the previous clock/order. +**Result and storage:** The circuit definition and its separately keyed setup are saved in this browser origin. Circuit capacity is 20. The setup restores driver/pit assumptions and race distance for that circuit ID, with a fresh run rather than the previous clock/order or live calls. Older v1 setups default to ten laps without losing their other settings. **Recovery and limits:** A failed setup save does not guarantee all settings were persisted; read its message and retry before closing. Circuit geometry may have been saved before a later setup write failed. There is no separate saved-setup list/delete button. Deleting a circuit does not necessarily purge its keyed sandbox setup. @@ -87,6 +88,28 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip **How:** Choose **Export sandbox session JSON** while the setup is valid. -**Result and storage:** The file contains its sandbox kind/version, circuit geometry, setup, elapsed clock and driver states. It does not write server data or save browser settings. +**Result and storage:** The file contains its sandbox kind/version, circuit geometry, setup/distance, elapsed clock and driver states including queued calls, completed visits and finish times. It does not write server data or save browser settings. **Recovery and limits:** There is no sandbox-session importer or resume-from-file flow yet. The editor's circuit importer accepts a circuit definition, not this combined session file. Use explicit browser saves to reopen configuration through the current UI. + + +## SANDBOX-08 — Choose a race distance and read final results + +**What:** Run a finite fictional race with deterministic finishing times and order. + +**How:** Set **Race distance (laps)** to 1–50 before running (default ten). Use **Run sandbox** or **Advance one lap**. The order panel becomes **FINAL RESULTS** once every driver finishes. Read each driver's finish time in seconds to three decimal places and completed pit visits. Choose **Reset sandbox** for another run. + +**Result and storage:** Every driver completes the full distance; this model does not flag lapped drivers early when the leader finishes. Finish times are computed at the exact simulated crossing, including staggered starting positions, pace and pit/service time. Finished drivers freeze, classify ahead of unfinished drivers, and sort by finish time. Exact ties retain grid order. The clock freezes at the last finish instead of the end of a manual time jump. Distance saves with the setup; results remain transient or can be exported. + +**Recovery and limits:** Changing setup/geometry restarts the run and discards results. A pit route spanning start/finish uses its proportional mapped circuit crossing, which can happen before service; an unfinished pit visit is not counted as a completed stop. This is a synthetic route model, not a surveyed timing line or regulation simulation. Read the export limitation in SANDBOX-07 before closing. + + +## SANDBOX-09 — Make and cancel live pit calls + +**What:** Change one selected driver's next visit without restarting the race. + +**How:** Under **Live pit strategy**, choose **Your driver**. Use **Box this lap** before the next entry; after entry has passed the button becomes **Box next lap**. Read the queued lap in the status message. Choose **Cancel pit call** while the driver is on track to stay out; this can cancel its original scheduled stop too. Once a visit is complete, another live call can schedule a further visit. + +**Result and storage:** Calls preserve the clock, running/paused state, other drivers and positions. A live call replaces the selected driver's pending scheduled/live target. At entry the visit locks: pit/service state cannot be cancelled or redirected. Repeated visits use that driver's configured service duration and the same lane/speed. Calls apply while paused or running, including from the grid. They are transient runtime decisions, included in session exports but not setup saves. + +**Recovery and limits:** No valid entry remains after the final eligible entry, so the box button disables. Calls also disable during lane editing or invalid setup, and finished drivers cannot receive them. A reset/setup change removes live calls and reinstates configured scheduled stops. There is no undo of a committed visit, tyre choice, race engineer AI or session importer yet. diff --git a/frontend/e2e/sandbox.spec.ts b/frontend/e2e/sandbox.spec.ts index b2c0f00..aa3adf7 100644 --- a/frontend/e2e/sandbox.spec.ts +++ b/frontend/e2e/sandbox.spec.ts @@ -1,4 +1,62 @@ import { test, expect } from "@playwright/test"; +test("finite race results freeze at exact finish times and reset retains distance", async ({page}) => { + await page.goto("/?race=monza-2024&t=120"); + await page.getByRole("button", {name: "Custom circuit studio", exact: true}).click(); + await page.getByRole("button", {name: "Circuit race sandbox", exact: true}).click(); + const sandbox = page.getByRole("region", {name: "Circuit race sandbox", exact: true}); + await sandbox.getByLabel("Sandbox driver count").selectOption("2"); + await sandbox.getByLabel("Race distance laps", {exact: true}).fill("2"); + await sandbox.getByLabel("Sandbox base lap seconds", {exact: true}).fill("30"); + await sandbox.getByRole("button", {name: "Cancel pit call", exact: true}).click(); + for (let i = 0; i < 3; i++) await sandbox.getByRole("button", {name: "Advance one lap", exact: true}).click(); + const results = sandbox.getByRole("region", {name: "Race results", exact: true}); + await expect(results).toContainText("60.000s"); + await expect(results).toContainText("64.192s"); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:04"); + await expect(sandbox.getByRole("button", {name: "Race finished", exact: true})).toBeDisabled(); + await expect(sandbox.getByRole("button", {name: "Advance one lap", exact: true})).toBeDisabled(); + await expect(sandbox.getByRole("button", {name: "Box this lap", exact: true})).toBeDisabled(); + await sandbox.getByRole("button", {name: "Reset sandbox", exact: true}).click(); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:00:00"); + await expect(sandbox.getByLabel("Race distance laps", {exact: true})).toHaveValue("2"); + await expect(sandbox.getByTestId("pit-call-status")).toContainText("queued on lap 1"); + await sandbox.getByLabel("Race distance laps", {exact: true}).fill("1"); + await sandbox.getByLabel("Sandbox speed", {exact: true}).selectOption("25"); + await sandbox.getByRole("button", {name: "Run sandbox", exact: true}).click(); + await expect(sandbox.getByRole("button", {name: "Race finished", exact: true})).toBeDisabled({timeout:10000}); + await expect(sandbox.getByRole("region", {name: "Race results", exact: true})).toBeVisible(); + await expect(page.getByTestId("elapsed-time")).toContainText("00:02:00"); +}); + +test("live calls queue and cancel without resetting, lock on entry and target the selected driver", async ({page}) => { + await page.setViewportSize({width: 390, height: 844}); + await page.goto("/?race=monza-2024"); + await page.getByRole("button", {name: "Custom circuit studio", exact: true}).click(); + await page.getByRole("button", {name: "Circuit race sandbox", exact: true}).click(); + const sandbox = page.getByRole("region", {name: "Circuit race sandbox", exact: true}); + const status = sandbox.getByTestId("pit-call-status"); + await sandbox.getByRole("button", {name: "Cancel pit call", exact: true}).click(); + await expect(status).toContainText("stay out"); + await sandbox.getByRole("button", {name: "Advance one lap", exact: true}).click(); + await sandbox.getByRole("button", {name: "Box this lap", exact: true}).click(); + await expect(status).toContainText("queued on lap 2"); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30"); + await sandbox.getByRole("button", {name: "Edit pit-lane handles", exact: true}).click(); + await expect(sandbox.getByRole("button", {name: "Cancel pit call", exact: true})).toBeDisabled(); + await expect(sandbox.getByRole("button", {name: "Box this lap", exact: true})).toBeDisabled(); + await sandbox.getByRole("button", {name: "Finish pit-lane editing", exact: true}).click(); + await sandbox.getByRole("button", {name: "Cancel pit call", exact: true}).click(); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30"); + await sandbox.getByRole("button", {name: "Box this lap", exact: true}).click(); + await sandbox.getByRole("button", {name: "Advance one lap", exact: true}).click(); + await expect(status).toContainText("committed"); + await expect(sandbox.getByRole("button", {name: "Cancel pit call", exact: true})).toBeDisabled(); + await sandbox.getByLabel("Controlled driver", {exact: true}).selectOption({label:"Driver 2"}); + await expect(status).toContainText("Driver 2: stay out"); + await sandbox.getByRole("button", {name: "Box next lap", exact: true}).click(); + await expect(status).toContainText("Driver 2: pit entry queued on lap 3"); + expect(await page.getByRole("dialog").evaluate(e => e.scrollWidth <= e.clientWidth)).toBe(true); +}); test("fictional drivers use the pit lane, save their setup and export a portable session", async ({ page, }) => { @@ -15,6 +73,7 @@ test("fictional drivers use the pit lane, save their setup and export a portable exact: true, }); await sandbox.getByLabel("Grid 1 driver name", { exact: true }).fill("Apex"); + await sandbox.getByLabel("Race distance laps", {exact: true}).fill("7"); await sandbox .getByRole("button", { name: "Advance one lap", exact: true }) .click(); @@ -44,6 +103,7 @@ test("fictional drivers use the pit lane, save their setup and export a portable const exported = JSON.parse(Buffer.concat(chunks).toString()); expect(exported.kind).toBe("pitwall-circuit-sandbox"); expect(exported.setup.drivers[0].name).toBe("Apex"); + expect(exported.setup.raceLaps).toBe(7); expect(exported.states[0].visited).toBe(true); await page .getByRole("button", { name: "Circuit editor", exact: true }) @@ -73,6 +133,7 @@ test("fictional drivers use the pit lane, save their setup and export a portable await expect( sandbox.getByLabel("Grid 1 driver name", { exact: true }), ).toHaveValue("Apex"); + await expect(sandbox.getByLabel("Race distance laps", {exact: true})).toHaveValue("7"); }); test("pit settings validate, undo recovers and editable pit handles change the route", async ({ page, diff --git a/frontend/src/CircuitSandbox.tsx b/frontend/src/CircuitSandbox.tsx index fe9e0cd..3ef471d 100644 --- a/frontend/src/CircuitSandbox.tsx +++ b/frontend/src/CircuitSandbox.tsx @@ -9,7 +9,10 @@ import { } from "./custom-track"; import NumberField from "./NumberField"; import { - advancePreview, + advanceRace, + nextPitEntry, + pendingPit, + raceOrder, initialGrid, newSandboxDriver, parseSandbox, @@ -33,10 +36,14 @@ export default function CircuitSandbox({ active: boolean; }) { const [setup, setSetup] = useState(() => readSandbox(track)); - const [states, setStates] = useState(() => initialGrid(setup.drivers)); + const [session, setSession] = useState(() => ({ + states: initialGrid(setup.drivers), elapsed: 0, + })); + const { states, elapsed } = session; + const complete = states.every((s) => s.phase === "finished"); + const [controlled, setControlled] = useState(setup.drivers[0].id); const [running, setRunning] = useState(false), - [speed, setSpeed] = useState(10), - [elapsed, setElapsed] = useState(0); + [speed, setSpeed] = useState(10); const [editing, setEditing] = useState(false), [selected, setSelected] = useState(0), [message, setMessage] = useState(""); @@ -46,23 +53,21 @@ export default function CircuitSandbox({ const errors = useMemo(() => validateSandbox(track, setup), [track, setup]), valid = !errors.length; useEffect(() => { - if (!active || !running || !valid) return; + if (!active || !running || !valid || complete) return; let frame = 0, previous = performance.now(); const tick = (now: number) => { const seconds = Math.min((now - previous) / 1000, 0.1) * speed; previous = now; - setStates((old) => - old.map((s, i) => - advancePreview(s, setup.drivers[i], setup, geometry, seconds), - ), - ); - setElapsed((t) => t + seconds); + setSession(old => advanceRace(old, setup, geometry, seconds)); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); - }, [active, running, speed, setup, geometry, valid]); + }, [active, running, speed, setup, geometry, valid, complete]); + useEffect(() => { + if (complete) setRunning(false); + }, [complete]); useEffect(() => { if (!active) setRunning(false); }, [active]); @@ -71,8 +76,8 @@ export default function CircuitSandbox({ }, [track.points, track.cornerRadius]); function reset(next = setup) { setRunning(false); - setElapsed(0); - setStates(initialGrid(next.drivers)); + setSession({elapsed: 0, states: initialGrid(next.drivers)}); + setControlled(id => next.drivers.some(d => d.id === id) ? id : next.drivers[0].id); } function change(next: SandboxSetup, remember = true) { if (remember) setHistory((h) => [...h.slice(-29), setup]); @@ -94,20 +99,23 @@ export default function CircuitSandbox({ } function advance(seconds: number) { setRunning(false); - setStates((old) => - old.map((s, i) => - advancePreview(s, setup.drivers[i], setup, geometry, seconds), + setSession(old => advanceRace(old, setup, geometry, seconds)); + } + const order = raceOrder(states, setup); + const controlledState = states.find(s => s.id === controlled) ?? states[0]; + const controlledDriver = setup.drivers.find(d => d.id === controlledState.id)!; + const nextEntry = nextPitEntry(controlledState, setup); + const pending = pendingPit(controlledState, controlledDriver, setup); + function pitCall(queue: boolean) { + setSession((old) => ({ + ...old, + states: old.states.map((s) => + s.id === controlledState.id && s.phase === "track" + ? { ...s, pitTarget: queue ? nextPitEntry(s, setup) : null } + : s, ), - ); - setElapsed((t) => t + seconds); + })); } - const order = [...states].sort((a, b) => { - const progress = (s: typeof a) => - s.phase === "track" - ? s.raceProgress - : s.raceProgress + s.pitProgress * ((setup.exit - setup.entry + 1) % 1); - return progress(b) - progress(a); - }); const box = pointOnRoute(geometry.pit, 0.5); return (
@@ -120,6 +128,11 @@ export default function CircuitSandbox({

+
+
+

Live pit strategy

+

{complete ? "Race complete" : elapsed === 0 ? "Grid ready" : running ? "Race running" : "Race paused"} · {setup.raceLaps} laps

+
+ + + +
+

+ {controlledState.phase === "finished" ? `${controlledDriver.name} has finished.` : controlledState.phase !== "track" + ? `${controlledDriver.name} is committed to the pit lane. Service: ${controlledDriver.serviceSeconds} seconds.` + : pending !== null ? `${controlledDriver.name}: pit entry queued on lap ${Math.floor(pending) + 1}.` + : nextEntry === null ? "No pit entry remains before the finish." : `${controlledDriver.name}: stay out. No pit call queued.`} +

+

Live calls keep the clock and positions. After passing entry, the call targets the next lap. Cancel before entry; once in the lane, the visit is committed. Setup edits restart the race.

+