diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 49e6791..d7d172c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,7 @@ The [user guide](docs/USER-GUIDE.md) is the current behavior contract. Release n - For a new flow, choose a new stable ID and explicit anchor, write its complete section and add its guide/source entry to `docs/flows.json`. Do not renumber existing IDs for cosmetic reorganization. - Register new UI view components as flow sources. Classify truly reusable helpers under `sharedComponents` only when they do not represent their own user flow. - For a removed flow, remove/update its index entry and explain the replacement in release notes. Do not leave a current guide pointing at a retired control. -- When the product version changes, review the handbook and update `productVersion` / `lastReviewed` in the registry. Review dates reflect actual review, not automatic timestamps. +- When the product version changes, update the frontend package/root lockfile versions and API project version together, review the handbook, and update `productVersion` / `lastReviewed` in the registry. The header and API status derive their versions from those build metadata fields. Review dates reflect actual review, not automatic timestamps. - Run `node scripts/update-guide-index.mjs` to regenerate the index/version header, then `node scripts/check-docs.mjs`. - Update the short demo, README, test guide and release notes only where the change affects them. Do not rewrite historical release behavior as if it always existed. diff --git a/README.md b/README.md index b75773f..bfb1c80 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# Pitwall v1.3 — Race Replay Lab +# Pitwall v1.4 — Race Replay Lab An independent motorsport replay prototype built with React, TypeScript, ASP.NET Core 10, and PostgreSQL 17. Start with recorded races; later, branch into player-controlled strategy simulations. -[Complete user guide](docs/USER-GUIDE.md) · [Three-minute demo](docs/DEMO.md) · [v1.3 release notes](docs/V1.3.md) · [Testing](docs/TESTING.md) · [Roadmap](docs/FOLLOW-UP-PLAN.md) +[Complete user guide](docs/USER-GUIDE.md) · [Three-minute demo](docs/DEMO.md) · [v1.4 release notes](docs/V1.4.md) · [Testing](docs/TESTING.md) · [Roadmap](docs/FOLLOW-UP-PLAN.md) The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, defaults, saved data, exports, resets and recovery. For future upgrades, follow [CONTRIBUTING](CONTRIBUTING.md) and update the affected flows alongside the implementation. CI checks the registry, links, required sections, UI component coverage and product version. @@ -26,6 +26,9 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def - 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). - Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md). +- Fictional driver recruitment: generated stat-based prospects, a 12,000-credit budget, six-driver roster, custom 210-point builds, two swappable race seats, browser persistence and lineup application to local/new multiplayer races. See [recruiting flows](docs/guide/08-driver-recruitment.md). +- Live signed-roster availability in the sandbox, per-slot build selection and partial-lineup sync. **Race this circuit** starts a separate fictional race on the current replay's approximate outline with your selected signed drivers; generated pit lanes are validated before use. +- A local three-race championship with a frozen signed lineup and four rivals, saved calendar/results, points/countback, team score and resumable in-race checkpoints. Entry is free; recruiting prizes/training and multiplayer championships remain future increments. See [championship flows](docs/guide/09-championship.md). - 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/backend/Pitwall.Api/Pitwall.Api.csproj b/backend/Pitwall.Api/Pitwall.Api.csproj index d651170..d8cce0e 100644 --- a/backend/Pitwall.Api/Pitwall.Api.csproj +++ b/backend/Pitwall.Api/Pitwall.Api.csproj @@ -1,5 +1,5 @@ - net10.0enableenabletrue1.3.0 + net10.0enableenabletrue1.4.0 diff --git a/backend/Pitwall.Api/Program.cs b/backend/Pitwall.Api/Program.cs index 38f5c7a..d6c84df 100644 --- a/backend/Pitwall.Api/Program.cs +++ b/backend/Pitwall.Api/Program.cs @@ -45,7 +45,7 @@ app.MapGet("/health", async (RaceStore data, CancellationToken ct) => await data.ReadyAsync(ct) ? Results.Ok(new { status = "healthy", storage = data.Storage }) : Results.StatusCode(503)); -app.MapGet("/api/status", (RaceStore data) => new { storage = data.Storage, bookmarkScope = "shared-local-development", version = "1.3.0" }); +app.MapGet("/api/status", (RaceStore data) => new { storage = data.Storage, bookmarkScope = "shared-local-development", version = typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "unknown" }); app.MapGet("/api/sessions", async (RaceCatalog catalog, RaceStore store, CancellationToken ct) => { var cached = await store.CachedIdsAsync(ct); return Results.Ok(new { catalog.Current.RefreshedAt, catalog.Refreshing, catalog.LastError, sessions = catalog.Current.Sessions.Select(s => new { s.Id, s.SessionKey, s.Title, s.Circuit, s.Country, s.CountryCode, s.Year, s.Date, s.Kind, cached = cached.Contains(s.Id) }) }); diff --git a/docs/DEMO.md b/docs/DEMO.md index 3c200c7..43c9bd2 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -8,7 +8,7 @@ For all controls, save/reset behavior, limits and recovery paths, use the [compl From the repository root, run `node scripts/doctor.mjs`. If the frontend/API are built and PostgreSQL is running, use `node scripts/preview.mjs`. Otherwise follow the README's Docker or development setup first. `--snapshot` runs without PostgreSQL, with temporary bookmarks/imports. -Open [Monza at 30 minutes](http://127.0.0.1:5080/?race=monza-2024&t=1800). The header reports v1.3 and the storage indicator shows the current mode. +Open [Monza at 30 minutes](http://127.0.0.1:5080/?race=monza-2024&t=1800). The header reports v1.4.0 and the storage indicator shows the current mode. ## Replay and analysis @@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select ## Engineering evidence -- [Testing guide](TESTING.md): 66 frontend unit checks, nine Node checks, 49 browser scenarios, real API/database integration and dedicated storage/room concurrency checks. +- [Testing guide](TESTING.md): 84 frontend unit checks, nine Node checks, 62 browser scenarios, real API/database integration and dedicated storage/room 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 94df30a..94da922 100644 --- a/docs/FOLLOW-UP-PLAN.md +++ b/docs/FOLLOW-UP-PLAN.md @@ -49,6 +49,12 @@ The first v1.4 increment implements finite fictional sessions (1–50 laps), det The private-room increment adds a server-owned C# simulation, SignalR guest connections, exclusive driver claims/readiness, shared host controls, live calls, spectator support, reconnect and explicit driver/host handover. See [multiplayer flows](guide/07-multiplayer.md). Room storage is in memory, independent of PostgreSQL; public hosting, durable room recovery and multiple-instance coordination remain future scope. +Fictional recruiting now adds generated prospects/fees, a browser-local budget and six-driver roster, custom stat allocation and two selected/swappable builds. Applying a lineup copies bounded pace/service values into the local sandbox and future room definitions. See [recruitment](guide/08-driver-recruitment.md). Training, wages, seasons, protected server economies and car-part upgrades remain future scope. + +Roster/venue integration now fills empty team seats on signing, keeps signed choices current in an open sandbox, applies selected profiles to new unsaved grids and supports explicit partial sync/per-slot swaps without silently resetting active runs. **Race this circuit** prepares the open replay's approximate outline as a validated independent race venue, with a generated connected pit route and the selected signed drivers. Historical results remain separate; public hosting and a protected cross-device team economy are still later work. + +The next local-career increment implements a three-round championship using saved/custom and cached replay venues, two frozen signed builds plus four rivals, exact classified results, points/countback, team totals and saved race checkpoints. See [championship flows](guide/09-championship.md). Next: integrate carefully bounded prize credits, then capped driver training, then consider multiplayer championships. The current cup does not change recruiting credits. + ## Branch and validation workflow Use a focused feature branch for each milestone, run timing/camera unit tests and browser tests, and review into `develop`. Promote to `master` once the integration branch is ready. Container delivery continues through the existing GitHub Actions workflow. diff --git a/docs/TESTING.md b/docs/TESTING.md index 4d0507d..06ce5cd 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: 49 browser scenarios +## Playwright: 62 browser scenarios | Area | Coverage | | --- | --- | @@ -33,6 +33,9 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s | 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 | | Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal | +| Fictional recruitment | Generated sign/release/scouting fees and persistence, custom point limits, saved seat swaps and applied performance, new multiplayer room copies, mobile/failed-write behavior, stale-tab protection, raw backup and confirmed corrupted-profile recovery | +| Roster/venue integration | Same-window/cross-tab signed-roster availability without resetting an active run, explicit partial sync and per-slot swaps, saved-grid preservation, replay-outline racing, valid pit geometry, new-room hosting and historical replay isolation | +| Local championship | Complete three-venue season/results/standings, between-round reload, frozen recruiting budget, live checkpoint and pit-call restore, animation pause/close persistence, stale-tab locking/reload, mobile failed-write preservation and backed-up corrupted-save recovery | | 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 | @@ -40,7 +43,7 @@ These scenarios run against the production frontend build in Chromium. Historica ## Other checks -- 66 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. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results. +- 84 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. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results. - `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass. - 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. diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index 36491f2..766a307 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -1,6 +1,6 @@ # Pitwall user guide -**Product version:** 1.3.0 +**Product version:** 1.4.0 **Last reviewed:** 2026-11-21 @@ -15,6 +15,8 @@ This is the current handbook for what each flow does, how to use it, what is sav 5. [Configure drivers and pit stops in the race sandbox](guide/05-race-sandbox.md). 6. [Understand storage, maintenance and guide updates](guide/06-maintenance.md). 7. [Host, join and hand over a private multiplayer race](guide/07-multiplayer.md). +8. [Recruit fictional drivers, create builds and swap your lineup](guide/08-driver-recruitment.md). +9. [Run a saved local three-race championship](guide/09-championship.md). Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Recovery and limits** section. Use these IDs in issues and pull requests instead of relying on a screenshot or an old chat. @@ -29,6 +31,9 @@ Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Re | Can I design my own circuit? | Custom circuit studio → Circuit editor | Fictional geometry, separate from real replays | | Can I run a custom grid with scheduled stops? | Circuit race sandbox | Fictional pace/route/service animation | | Can friends control drivers in the same race? | Multiplayer rooms | One server-owned fictional race with guest driver ownership | +| Can I sign and customize fictional drivers? | Driver recruitment | Browser-local roster/budget with two selected race builds | +| Can my signed drivers race on an existing track? | Race this circuit | Separate fictional race using the current replay's approximate outline | +| Can my team compete over several races? | Local championship | Three saved fictional rounds, points/countback and resumable race checkpoints | ```mermaid flowchart LR @@ -41,6 +46,8 @@ flowchart LR Replay --> Editor[Fictional circuit editor] Editor --> Sandbox[Driver and pit sandbox] Sandbox --> Room[Private multiplayer room] + Editor --> Team[Recruit and build drivers] + Team --> Sandbox ``` ![Recorded race analysis desk](images/v1.3-analysis.png) @@ -60,6 +67,8 @@ Saving to PostgreSQL, saving in your browser and downloading a file are differen | Combined sandbox session JSON | No session importer yet | Contains geometry/setup/runtime for inspection | | Share link | Yes, if its server/session is available | Encodes replay settings, not private saves or custom workspaces | | Multiplayer room | Reconnect while that API process retains it | Guest token in tab session storage; rooms are in server memory even with PostgreSQL | +| Recruiting team | Yes, same browser origin | Autosaved market, roster, lineup and credits; applying to a grid is separate | +| Local championship | Yes, same browser origin | One frozen calendar/lineup, results and latest saved race checkpoint; no importer | Closing a studio or scenario without saving can lose its draft. Clearing browser data, changing browser/profile, or using another hostname/port can change which browser saves you see. A normal database-backed API restart does not erase server caches/bookmarks. @@ -81,7 +90,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser -76 documented flows. Each ID links directly to its instructions. +94 documented flows. Each ID links directly to its instructions. ### Start Pitwall and choose a race @@ -156,6 +165,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [STUDIO-07](guide/04-circuit-studio.md#studio-07) | Save and load a circuit | | [STUDIO-08](guide/04-circuit-studio.md#studio-08) | Delete a saved circuit | | [STUDIO-09](guide/04-circuit-studio.md#studio-09) | Import or export circuit JSON | +| [STUDIO-10](guide/04-circuit-studio.md#studio-10) | Race signed drivers on an existing replay circuit | ### Configure and run a fictional race @@ -193,6 +203,33 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [ROOM-06](guide/07-multiplayer.md#room-06) | Hand over a driver without resetting | | [ROOM-07](guide/07-multiplayer.md#room-07) | Reconnect, leave and remove guests | | [ROOM-08](guide/07-multiplayer.md#room-08) | Run a two-player trial and prepare outside access | + +### Fictional driver recruitment and builds + +| Flow | What you can do | +| --- | --- | +| [TEAM-01](guide/08-driver-recruitment.md#team-01) | Open and initialize your team | +| [TEAM-02](guide/08-driver-recruitment.md#team-02) | Scout generated prospects | +| [TEAM-03](guide/08-driver-recruitment.md#team-03) | Sign and release roster drivers | +| [TEAM-04](guide/08-driver-recruitment.md#team-04) | Build and sign a custom driver | +| [TEAM-05](guide/08-driver-recruitment.md#team-05) | Select and swap race seats | +| [TEAM-06](guide/08-driver-recruitment.md#team-06) | Apply recruited builds and host them in a new room | +| [TEAM-07](guide/08-driver-recruitment.md#team-07) | Recover from storage failures or another tab's changes | +| [TEAM-08](guide/08-driver-recruitment.md#team-08) | Export a record or explicitly start fresh | +| [TEAM-09](guide/08-driver-recruitment.md#team-09) | Sync signed drivers directly into a sandbox | + +### Local three-race championships + +| Flow | What you can do | +| --- | --- | +| [CUP-01](guide/09-championship.md#cup-01) | Enter a championship with your signed lineup | +| [CUP-02](guide/09-championship.md#cup-02) | Choose the three-round calendar | +| [CUP-03](guide/09-championship.md#cup-03) | Start, run and make team pit decisions | +| [CUP-04](guide/09-championship.md#cup-04) | Read results and championship standings | +| [CUP-05](guide/09-championship.md#cup-05) | Save and resume a race or between-round progress | +| [CUP-06](guide/09-championship.md#cup-06) | Recover from failed saves or another editing tab | +| [CUP-07](guide/09-championship.md#cup-07) | Export a cup or replace it with a new championship | +| [CUP-08](guide/09-championship.md#cup-08) | Recover an unreadable saved championship | ## How this stays current diff --git a/docs/V1.4.md b/docs/V1.4.md new file mode 100644 index 0000000..3588b56 --- /dev/null +++ b/docs/V1.4.md @@ -0,0 +1,31 @@ +# v1.4.0 — Playable races, multiplayer and recruited drivers + +Release date: 2026-11-21. The [current handbook](USER-GUIDE.md) documents 86 flows across eight chapters. [v1.3 notes](V1.3.md) remain the record of the previous release. + +## Race sessions and live decisions + +The fictional sandbox runs 1–50 lap sessions with exact simulated finish times, final order and a frozen finishing clock. Select a driver, call a stop before the next eligible entry, cancel before entry, and schedule repeat visits. Setup changes restart the local race; live calls preserve it. A pit lane spanning start/finish uses a mapped crossing, rather than a surveyed timing line. + +## Private multiplayer rooms + +ASP.NET Core owns the shared simulation clock and validates decisions; SignalR sends snapshots to guests. Rooms support up to six driver seats and twelve guests including spectators, exclusive claims, lobby readiness, host controls, reconnect, driver/host handover and guest removal. Invitation URLs contain the room code; private guest credentials stay in tab session storage. [Multiplayer guide](guide/07-multiplayer.md). + +## Recruiting and custom builds + +A browser-local team starts with 12,000 fictional credits. Scout generated prospects, sign/release up to six roster drivers, create 210-point custom builds, and select or swap two race seats. Pace/consistency produce a steady synthetic pace offset; pit discipline changes service time. Fees, partial refunds, stat caps, storage failures and stale-tab writes are explicit. [Recruiting guide](guide/08-driver-recruitment.md). + +## Synced rosters and existing circuits + +Signings fill empty selected team seats and appear in an open sandbox. New unsaved grids use selected signed builds; stored grids and running races wait for explicit sync/selection. Per-slot selection can swap builds while keeping each slot's scheduled pit lap. + +**Race this circuit** fits/simplifies the current replay's approximate outline into an independent fictional venue. New pit lanes try validated connected routes; Monza and Interlagos are covered by geometry and browser checks. The historical replay retains its original clock/data. These are approximate venues with fictional sectors, pit geometry, base pace and distance. + +## Release validation and versioning + +The feature batch passed 78 Vitest checks and 57 Playwright scenarios, plus the authoritative C# room/permission checks and shared browser/server model fixture during room development. The maintained guide has structural/link/version checks in CI. See [TESTING](TESTING.md) for actual coverage and commands. + +The header derives its semantic version from the frontend package; `/api/status` derives it from the API assembly. CI's guide checker compares package, lockfile, API project and handbook metadata. The release uses an annotated `v1.4.0` Git tag; publishing a tag is separate from creating a hosted GitHub Release. + +## Storage and operating limits + +Historical caches/bookmarks use PostgreSQL when configured. Recruiting, custom definitions and local preferences remain browser-origin data. Multiplayer rooms remain in one API process's memory even with PostgreSQL: an API restart/redeployment ends rooms. Guest credentials do not provide account recovery. Public hosting, multi-instance room coordination, durable room resume, protected online economies, tyre physics, wages, seasons and vehicle-part upgrades remain future work. diff --git a/docs/flows.json b/docs/flows.json index c1ec25a..9fe49ab 100644 --- a/docs/flows.json +++ b/docs/flows.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "productVersion": "1.3.0", + "productVersion": "1.4.0", "lastReviewed": "2026-11-21", "chapters": [ { @@ -30,6 +30,14 @@ { "path": "docs/guide/07-multiplayer.md", "title": "Private multiplayer races" + }, + { + "path": "docs/guide/08-driver-recruitment.md", + "title": "Fictional driver recruitment and builds" + }, + { + "path": "docs/guide/09-championship.md", + "title": "Local three-race championships" } ], "sharedComponents": [ @@ -902,6 +910,254 @@ "backend/Pitwall.RoomChecks/Program.cs", "frontend/e2e/multiplayer.spec.ts" ] + }, + { + "id": "TEAM-01", + "title": "Open and initialize your team", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-01", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-02", + "title": "Scout generated prospects", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-02", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-03", + "title": "Sign and release roster drivers", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-03", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-04", + "title": "Build and sign a custom driver", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-04", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-05", + "title": "Select and swap race seats", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-05", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-06", + "title": "Apply recruited builds and host them in a new room", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-06", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-07", + "title": "Recover from storage failures or another tab's changes", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-07", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "TEAM-08", + "title": "Export a record or explicitly start fresh", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-08", + "sources": [ + "frontend/src/DriverRecruitment.tsx", + "frontend/src/recruitment.ts", + "frontend/src/recruitment.test.ts", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/e2e/recruitment.spec.ts" + ] + }, + { + "id": "STUDIO-10", + "title": "Race signed drivers on an existing replay circuit", + "guide": "docs/guide/04-circuit-studio.md", + "anchor": "studio-10", + "sources": [ + "frontend/src/App.tsx", + "frontend/src/TrackEditor.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/src/recruitment.ts", + "frontend/src/sandbox.ts", + "frontend/src/replay-circuit.ts", + "frontend/src/replay-circuit.test.ts", + "frontend/e2e/roster-tracks.spec.ts" + ] + }, + { + "id": "TEAM-09", + "title": "Sync signed drivers directly into a sandbox", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-09", + "sources": [ + "frontend/src/App.tsx", + "frontend/src/TrackEditor.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/src/recruitment.ts", + "frontend/src/sandbox.ts", + "frontend/src/replay-circuit.ts", + "frontend/src/replay-circuit.test.ts", + "frontend/e2e/roster-tracks.spec.ts" + ] + }, + { + "id": "CUP-01", + "title": "Enter a championship with your signed lineup", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-01", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-02", + "title": "Choose the three-round calendar", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-02", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-03", + "title": "Start, run and make team pit decisions", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-03", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-04", + "title": "Read results and championship standings", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-04", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-05", + "title": "Save and resume a race or between-round progress", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-05", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-06", + "title": "Recover from failed saves or another editing tab", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-06", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-07", + "title": "Export a cup or replace it with a new championship", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-07", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] + }, + { + "id": "CUP-08", + "title": "Recover an unreadable saved championship", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-08", + "sources": [ + "frontend/src/LocalChampionship.tsx", + "frontend/src/championship.ts", + "frontend/src/championship.test.ts", + "frontend/e2e/championship.spec.ts", + "frontend/src/App.tsx" + ] } ] } diff --git a/docs/guide/04-circuit-studio.md b/docs/guide/04-circuit-studio.md index 37fbb99..00c0ab2 100644 --- a/docs/guide/04-circuit-studio.md +++ b/docs/guide/04-circuit-studio.md @@ -11,10 +11,21 @@ The studio holds a draft. Saving/exporting is explicit; closing it is not an aut **How:** Open **Custom circuit studio**. Edit the starter circuit, choose **New circuit** for a new starter/ID, or **Copy replay outline as draft** when the open race has enough outline points. Enter **Circuit name**. -**Result and storage:** The default is a ten-point **Midnight circuit**, not a blank canvas. An outline copy is resampled/scaled as a new independent draft named **My outline remix**. Names are 1–48 trimmed characters. +**Result and storage:** The default is a ten-point **Midnight circuit**, not a blank canvas. An outline copy is fitted with its aspect ratio retained, simplified if necessary to 6–120 separated valid points, and created as an independent draft named **My outline remix**. Copies use zero extra corner rounding to retain the sampled shape; you can change it later. Names are 1–48 trimmed characters. **Recovery and limits:** Copying an outline does not copy telemetry, drivers or race timing. Validate the new shape before saving. New/copy replaces the working draft; recorded edit history may allow Undo until the studio closes, but explicit saved/exported copies are safer. + +## STUDIO-10 — Race signed drivers on an existing replay circuit + +**What:** Use an existing race's approximate circuit outline as a venue for a separate fictional race. + +**How:** Open/import a race through **Browse races**, then choose **Race this circuit** in the replay toolbar. The studio opens directly in sandbox mode with a new **[Circuit] [Year] · sandbox** draft. From an existing studio, **Race on [Circuit] [Year]** prepares the open replay's outline and replaces the working draft. Save an edited draft before switching. + +**Result and storage:** The new draft has its own ID, fitted outline and fictional sector divisions. A new unsaved grid uses available selected signed drivers automatically. The pit lane is generated and validated separately; concave outlines can choose another short connected entry/exit route. Set base pace, distance and pit plans as desired, run locally, or host this setup in a new multiplayer room. Saving the circuit/race setup is explicit. + +**Recovery and limits:** This does not reproduce real driver performance, measured sector boundaries, an official pit lane or the original race distance/time. Base pace and race distance use sandbox defaults. Missing outlines disable the shortcut. Outlines outside 6–5,000 finite samples or unable to simplify safely are rejected; a failed toolbar launch reports the failure and shows an editable starter rather than pretending it is the requested venue. Inspect pit validation and edit a lane if no generated route fits. The historical replay remains paused at its previous time with its recorded geometry/results unchanged. + ## STUDIO-02 — Add, move and remove control points diff --git a/docs/guide/05-race-sandbox.md b/docs/guide/05-race-sandbox.md index d734f56..559f932 100644 --- a/docs/guide/05-race-sandbox.md +++ b/docs/guide/05-race-sandbox.md @@ -37,6 +37,10 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip **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. +Use **Recruit and manage drivers** for [fictional recruiting and custom stat builds](08-driver-recruitment.md). Applying that lineup replaces the first two grid drivers with derived pace/service settings and restarts this sandbox; it is separate from real players controlling multiplayer seats. + +The signed roster also appears directly in each grid slot. [TEAM-09](08-driver-recruitment.md#team-09) covers automatic availability, fresh-grid defaults, partial-lineup sync and swapping existing signed builds. [STUDIO-10](04-circuit-studio.md#studio-10) opens a fictional race on the current replay's circuit outline. New default pit lanes try another short connected route if the initial lane crosses a concave circuit; a saved invalid lane still needs explicit editing/recovery. + ## SANDBOX-03 — Attach and edit the pit lane diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md index f0ab8a7..1a7d83d 100644 --- a/docs/guide/06-maintenance.md +++ b/docs/guide/06-maintenance.md @@ -16,6 +16,8 @@ | Replay bookmarks | Database, shared by visitors to that instance | API memory | Not private browser/account data | | Theme/default map/named map layouts | Browser only | Browser only | Hostname + port + scheme + browser/profile | | Saved circuits/sandbox setups/strategy scenarios | Browser only | Browser only | Same origin isolation | +| Recruiting roster/market/lineup/credits | Browser only, autosaved on successful transactions | Browser only | Same origin; separate from server rooms and guest ownership | +| Local championship/results/race checkpoint | Browser only | Browser only | One cup per origin; independent of recruiting credits and server rooms | | Unsaved drafts, tool selections, simulation clock | Current page/tool session | Current page/tool session | Not automatically restored | | Multiplayer rooms/shared race clock | API process memory; lost on restart | API process memory; lost on restart | Guest credential in tab session storage, no token in invitation | | Exported files | Download location you choose | Download location you choose | Not automatically re-imported | diff --git a/docs/guide/08-driver-recruitment.md b/docs/guide/08-driver-recruitment.md new file mode 100644 index 0000000..a9dc1e2 --- /dev/null +++ b/docs/guide/08-driver-recruitment.md @@ -0,0 +1,110 @@ +# Fictional driver recruitment and builds + +[Guide home](../USER-GUIDE.md) · [Local sandbox](05-race-sandbox.md) · [Multiplayer](07-multiplayer.md) + +Recruitment manages fictional driver profiles. It is separate from real players claiming multiplayer seats. Ratings and credits are local game values; no real money, accounts, training, contracts or season rewards are implemented. + + +## TEAM-01 — Open and initialize your team + +**What:** Create a browser-local team with a budget, prospect market and roster. + +**How:** Open **Driver recruitment** from the replay toolbar, or **Custom circuit studio → Circuit race sandbox → Recruit and manage drivers**. The sandbox pauses when opening its manager. Read your credits and roster count at the top. + +**Result and storage:** A fresh team starts with 12,000 credits, six generated prospects, an empty six-driver-capacity roster and two unassigned race seats. The first successful initialization saves that market; reopening does not reroll it. The same team is shared across fictional circuits on this browser origin. An unsaved custom-driver draft is separate from the saved team. + +**Recovery and limits:** Storage errors show a warning; unreadable existing data is not silently replaced. **Load latest team** rereads saved state without changing the custom draft or current race. Different browsers/profiles, schemes, hostnames and ports have separate teams. There is no server-synchronized budget or competitive economy verification. + + +## TEAM-02 — Scout generated prospects + +**What:** Compare randomly generated fictional names, colours, stats, fees and effective race settings. + +**How:** Inspect **Scout market** cards. Each shows overall rating, pace, consistency, pit discipline, derived pace offset/service duration and signing fee. **Scout new market · 250 credits** replaces all unsigned prospects with another six. + +**Result and storage:** Each prospect stat is an integer from 45–90. A saved seed/generation gives a stable market between visits; scouting generates the next market and spends 250 credits only after the save succeeds. Signed drivers and lineup stay intact. Overall is the rounded arithmetic mean of the three stats, not a race prediction. + +**Recovery and limits:** Scouting disables below 250 credits. Replaced prospects cannot be recovered through undo. Signing removes a prospect from that market; when it is empty, scout another. Random generation belongs to the market, not per-frame race movement or changes to a signed driver's ratings. + + +## TEAM-03 — Sign and release roster drivers + +**What:** Spend a limited budget on up to six signed drivers. + +**How:** Choose **Sign [name] · [fee] credits**. The prospect moves to **Your roster**. **Release [name] · +[refund]** removes a signed driver and returns the displayed amount. A roster driver outside the two selected seats is a reserve. + +**Result and storage:** Signing deducts the fee and saves the roster/market/budget together. A signing fills the first empty selected race seat automatically; further signings become reserves when both are occupied. The fee is `500 + round((pace² × 0.45 + consistency² × 0.25 + pitDiscipline² × 0.15) / 25) × 25`. Release refunds 40% of that driver's signing fee, rounded down, and clears its selected seats. Release does not return a driver to the market. Existing race copies retain that driver until replaced. + +**Recovery and limits:** Insufficient funds or a full roster disable signing. Re-signing a removed market ID is rejected. Signed names must be distinct ignoring case. Releases are immediate and have no undo; the refund is smaller than the signing cost. There are no recurring wages or race income yet. + + +## TEAM-04 — Build and sign a custom driver + +**What:** Choose your own stat tradeoffs, name and colour. + +**How:** In **Build a custom driver**, set a name (1–24 trimmed characters), colour and integer stats from 10–100. Use at most 210 total stat points; the default is 70 in each stat. Inspect the point total, fee and effective settings, then **Create and sign custom driver**. + +| Stat | Current model effect | +| --- | --- | +| Pace | 60% of the weighted pace rating | +| Consistency | 40% of the weighted pace rating; a steady modifier, not random lap variation | +| Pit discipline | Service seconds = `5 − stat × 0.04` | + +**Result and storage:** Pace offset is `(70 − (pace × 0.6 + consistency × 0.4)) × 0.12`, rounded to hundredths of a second/lap; negative is faster. Service is also rounded to hundredths. Custom stat limits give offsets from −3.60 to +7.20 seconds/lap and service from 1.00–4.60 seconds. Successful creation charges the same fee formula as the market and saves the signed profile. Each created driver gets its own identity. + +**Recovery and limits:** Over-budget points, insufficient credits and full rosters disable signing; invalid/duplicate names are rejected. You may leave stat points unused for a cheaper build. Ratings of signed drivers are fixed in this version; editing the builder creates another profile. Closing loses the unsaved draft. These stats do not simulate tyre wear, mistakes, traffic or physical vehicle dynamics. + + +## TEAM-05 — Select and swap race seats + +**What:** Choose two different signed drivers for the next fictional lineup. + +**How:** Set **Race seat 1** and **Race seat 2**. Selecting the driver already occupying the other seat swaps their assignments. With two assigned seats, **Swap race seats** reverses them directly. Choose **Choose signed driver** to clear a seat. + +**Result and storage:** Assignments save with the team, preserving profiles, stats and credits. Swapping affects the selected lineup only; it does not alter a running sandbox or an existing multiplayer room. Remaining roster drivers stay in reserve. + +**Recovery and limits:** Unsigned drivers cannot occupy seats and one driver cannot occupy both. Releasing a selected profile clears its seat. Assign both seats before applying. This is fictional lineup selection; real-player control handover is documented in [ROOM-06](07-multiplayer.md#room-06). + + +## TEAM-06 — Apply recruited builds and host them in a new room + +**What:** Turn your selected profiles into a race grid with their derived performance. + +**How:** Open the manager from **Recruit and manage drivers** inside the sandbox. Assign two seats and choose **Apply lineup and restart sandbox**. Inspect grid slots 1–2, then run locally or use **Host this setup with friends** to create a multiplayer copy. Use **Save circuit and race setup** if you also want that grid stored with the circuit. + +**Result and storage:** Applying copies names, colours, identities, pace offsets and service times into the first two grid slots. It retains those slots' scheduled pit laps (new slots use no scheduled stop), geometry, distance and other opponents. A one-driver grid grows to two. Duplicate copies of a selected recruited ID in later slots are removed. Applying resets clock, positions, live calls and results through the normal setup-change flow. The manager closes; sandbox undo can restore the previous grid. + +**Recovery and limits:** Applying requires both signed seats and no unresolved stale/storage warning. It does not automatically save the circuit setup. Existing multiplayer rooms keep their frozen definitions, ownership and current race; only a newly created room receives the changed lineup. Room validation bounds the copied pace/service settings but does not verify browser-local recruiting credits or ratings. Manual sandbox edits can subsequently override copied values. + + +## TEAM-07 — Recover from storage failures or another tab's changes + +**What:** Avoid silently losing purchases or overwriting a newer team. + +**How:** Read warnings and use **Load latest team** before retrying a stale transaction. If storage is blocked, restore permission/access and retry. **Back up stored team data** downloads a wrapper containing the raw saved string when a warning is present, if storage can be read. + +**Result and storage:** Successful operations save one versioned team JSON record. UI credits/roster change only after storage accepts that record. A saved revision/identity check rejects stale writes. Browsers with Web Locks serialize recruiting transactions across tabs; a storage event also warns open screens about external changes. + +**Recovery and limits:** Failed writes leave the displayed previous budget and roster intact. Without Web Locks, revision checks are best effort; use one active recruiting tab. **Load latest team** keeps the unsaved custom draft. Unreadable storage displays a fresh fallback with a warning but cannot overwrite the old record through an ordinary purchase. Backups/exports are inspection files, not automatically restorable through the app. + + +## TEAM-08 — Export a record or explicitly start fresh + +**What:** Download the displayed team or reset your local recruiting progress. + +**How:** **Export team JSON** downloads the currently displayed team, including seed/market, roster, lineup and credits. **Start fresh team** opens an explanation; **Confirm fresh team** replaces saved recruiting data with a new 12,000-credit team, or **Keep current team** cancels. + +**Result and storage:** A confirmed reset replaces this browser origin's recruiting record. Existing circuits, local race grid copies and multiplayer rooms remain separate. Resetting does not save or clear those copies. If you are viewing an unreadable saved record's fallback, back up the raw stored data before resetting; exporting the displayed fallback does not recover the old record. + +**Recovery and limits:** There is no team importer or reset undo. A failed reset write retains the old record and reports an error. Other recruiting tabs must load the latest team after a reset. Credits are fictional, so a fresh-team reset is allowed; this is not a protected online economy. + + +## TEAM-09 — Sync signed drivers directly into a sandbox + +**What:** Access the signed roster from the race grid without reopening recruitment or assembling a full two-driver team. + +**How:** Inspect **Signed team drivers** in the sandbox. Signings/releases/seat selections update its available roster in the same window or another tab. Use **Sync team lineup and restart** to apply all available selected seats, or choose a profile from **Signed driver** in an individual grid slot. One signed/selected driver is enough for this flow. + +**Result and storage:** New unsaved grids automatically use available selected team seats; a stored circuit/race setup retains its own grid until explicitly synced. Signing itself never resets a running race. A grid selection copies the profile's name, colour, derived pace and service duration. Choosing a build already in another slot swaps the builds while keeping each slot's planned pit lap. Sync/selection records ordinary sandbox undo history and restarts its local run; geometry, base pace and distance stay intact. Selecting team seat two can grow a one-driver grid to two. + +**Recovery and limits:** Save circuit/race setup separately to persist a copied grid. Unreadable roster storage disables selection/sync while leaving the manual grid usable. Releasing a profile removes it from available choices but does not erase an already copied grid driver. Existing multiplayer rooms keep their frozen driver definitions. Shared browser storage does not synchronize across devices or different origins/profiles. diff --git a/docs/guide/09-championship.md b/docs/guide/09-championship.md new file mode 100644 index 0000000..fa95501 --- /dev/null +++ b/docs/guide/09-championship.md @@ -0,0 +1,93 @@ +# Local three-race championships + +[Guide home](../USER-GUIDE.md) · [Recruiting](08-driver-recruitment.md) · [Race sandbox](05-race-sandbox.md) + +This cup is a local fictional career loop. It uses the sandbox pace/pit model, keeps a frozen six-driver field and saves one championship per browser origin. Prize credits, driver training, seasons and multiplayer championships are later increments. + + +## CUP-01 — Enter a championship with your signed lineup + +**What:** Create a three-round cup with your two selected signed drivers and four rivals. + +**How:** Sign/select both race seats in **Driver recruitment**, then open **Local championship** in the replay toolbar. Set **Championship name**, **Laps per round** (1–50) and **Base lap seconds** (30–300). Entry is free. Defaults are **Midnight Cup**, three laps and 60 seconds. + +**Result and storage:** Creation freezes driver identities, names, colours, pace, service and scheduled pit assumptions for all three rounds. The four rivals have fixed, differing pace; one has a scheduled visit. Later recruiting purchases, releases, seat changes or resets do not modify an existing cup. The recruiting budget remains separate and unchanged. + +**Recovery and limits:** Missing/incomplete signed seats reject entry without creating a save. There are no prize credits, training, entry fees, wages or income in this first increment. It is a local game, not a server-verified competitive economy. Close the panel to manage recruiting, then reopen and create the cup. + + +## CUP-02 — Choose the three-round calendar + +**What:** Combine existing replay venues and saved custom circuits. + +**How:** Set **Round 1 venue**, **Round 2 venue** and **Round 3 venue** to three different entries, then **Create three-race championship**. Options include the starter circuit, saved custom circuits, the current replay and other cached replay sessions. Import additional replays through **Browse races** before opening the cup panel. + +**Result and storage:** Each chosen definition, connected pit route and race setup is validated and stored with the cup. Replay outlines are fitted as independent approximate venues. The same six drivers, lap count and base pace apply throughout. Later edits/deletions of saved custom circuits do not alter the frozen cup copies. Different cached sessions are distinct entries even if their circuit name repeats. + +**Recovery and limits:** Duplicate entries disable creation. Missing/unsafe replay outlines, failed cache loads or invalid pit geometry reject creation and preserve the previous save. A failed catalog lookup leaves current/saved options available but may leave too few entries; restore the API or save additional valid custom circuits. Reopen the panel to refresh the available list. No provider import is silently started by choosing a venue. + + +## CUP-03 — Start, run and make team pit decisions + +**What:** Race one round with control over your two team drivers. + +**How:** Choose **Begin round [n]**, then **Run championship race** / **Pause championship race**. Set **Race speed** to 1×/5×/10×/25× or **Advance championship lap** by one base-lap duration. Choose **Your driver**, then **Box championship this lap** / **Box championship next lap** or **Cancel championship pit call** before entry. + +**Result and storage:** The cup uses the same deterministic movement, service and exact finish model as the local sandbox. Only your two frozen drivers accept player calls; rivals retain their planned settings. Calls preserve positions/clock, and pit entry commits the visit. Finished drivers freeze until every car finishes; every car covers the full distance. + +**Recovery and limits:** Advancing a base-lap duration does not guarantee every car completes a lap. Pit/service/finished phases lock calls, and no entry remains after the final eligible entry. Setup/geometry cannot be edited mid-cup. Missing physical tyre/traffic/fuel dynamics remain the sandbox's limits; a pit route spanning the finish uses its mapped crossing. + + +## CUP-04 — Read results and championship standings + +**What:** Accumulate points and countback across three consecutive rounds. + +**How:** Finish the round and read **Round complete**, its classified finish times and awarded points. **Driver standings** and **Team points** update. Use **Begin round [n+1]** after the result saves. After the third result, **Championship complete** replaces further round entry. + +**Result and storage:** Places 1–6 earn 25/18/15/12/10/8 points. Your team score sums its two driver scores. Equal points use wins, then second-place counts, thirds and later places, then initial grid order. A round records automatically once, in calendar order, only after all six finish. A saved final result cannot be awarded again by reloading. + +**Recovery and limits:** There is no skip, replay-for-more-points or result editing UI. Exact race-time ties retain grid order. Standings are driver standings plus your team total, not a multi-constructor championship. Results do not pay recruiting credits yet. + + +## CUP-05 — Save and resume a race or between-round progress + +**What:** Keep completed results, standings and an active race checkpoint between visits. + +**How:** Use **Save championship checkpoint**, pause the race or close the panel normally. Autosave also checks for changed progress about every two seconds and saves completed-round results immediately. Wait for a **Saved** message before refreshing. Reopen **Local championship** to load the stored cup; use **Load saved championship** to explicitly replace the in-memory view with the saved record. + +**Result and storage:** The versioned JSON record contains the frozen calendar/field, classified results and any current clock, positions, pit decisions, visits and finish states. A restored race always opens paused. Normal panel close waits for an in-flight save and saves the latest progress before closing. The historical replay remains at its prior paused time. + +**Recovery and limits:** A hard reload, browser crash or closing the tab can lose the last unsaved seconds; there is no unload-time guarantee. Storage is origin/profile local, including port and hostname isolation. One saved cup exists per origin. Server/database restarts do not erase the browser record, but clearing browser storage can. There is no cross-device/account sync or championship multiplayer yet. + + +## CUP-06 — Recover from failed saves or another editing tab + +**What:** Keep the previous checkpoint intact when saving cannot safely complete. + +**How:** Read **Save failed** errors. Restore browser storage access and retry **Save championship checkpoint**. If another tab changes the cup, export unsaved progress if needed, then **Load saved championship**; this replaces the current in-memory progress and resumes paused. + +**Result and storage:** A failed write pauses the race, preserves the previous stored record and leaves the latest in-memory state available. A revision/identity check rejects stale writes. Browsers supporting Web Locks serialize writes, while storage events lock stale screens. Begin/run/advance/pit controls remain locked until the failure/conflict is resolved. **Close without saving** explicitly exits despite a failed save. + +**Recovery and limits:** Use only one active editing tab. Without Web Locks, revision checks are best effort. Loading the stored cup discards unsaved progress in that view; exported JSON is an inspection record, not a supported import path. Never clear all browser data to repair one cup. + + +## CUP-07 — Export a cup or replace it with a new championship + +**What:** Keep an inspection record and choose when to replace the saved cup. + +**How:** **Export championship JSON** downloads the displayed snapshot, including unsaved progress. **Create another championship → Choose new championship calendar** opens a replacement form. **Replace saved championship** writes the new cup only after its lineup/calendar validates. **Keep this cup** / **Keep current championship** cancels the replacement flow. + +**Result and storage:** Replacement changes only the championship key. Recruiting, custom circuit saves, ordinary sandbox setups and multiplayer rooms remain independent. The old cup stays stored until a valid replacement is successfully written. A new cup freezes the then-current selected signed lineup. + +**Recovery and limits:** There is no archive list, JSON importer or replacement undo. Export before replacing if you want an inspection copy of the old season. Leaving the replacement form without creating a new cup retains the old cup; unsaved old-race progress still needs a checkpoint before a hard refresh. + + +## CUP-08 — Recover an unreadable saved championship + +**What:** Preserve malformed or unsupported saved data until you explicitly discard it. + +**How:** When a save cannot be read, use **Back up unreadable championship** first. **Discard unreadable championship → Confirm discard championship** removes that record, then allows creating a fresh cup. + +**Result and storage:** The backup wraps the original raw saved string. Reads and failed creation attempts do not overwrite it. Discard checks that the saved string has not changed since it was shown, so a newer save from another tab is not silently removed. + +**Recovery and limits:** Discard has no undo/import UI. If storage itself is unavailable, restore access before retrying; a backup cannot be read from blocked storage. The operation removes only the championship record, not signed drivers or custom circuits. diff --git a/frontend/e2e/championship.spec.ts b/frontend/e2e/championship.spec.ts new file mode 100644 index 0000000..ce22ebb --- /dev/null +++ b/frontend/e2e/championship.spec.ts @@ -0,0 +1,108 @@ +import {test,expect,type Page} from "@playwright/test"; +import {createDriver,newTeam,teamKey} from "../src/recruitment"; +import {championshipKey} from "../src/championship"; +async function enter(page:Page){ + const team={...createDriver(createDriver(newTeam(42),{id:"cup-one",name:"Cup One",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"cup-two",name:"Cup Two",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1}; + await page.addInitScript(({key,team})=>{if(!localStorage.getItem(key))localStorage.setItem(key,JSON.stringify(team));},{key:teamKey,team}); + await page.goto("/?race=monza-2024&t=120"); + await page.getByRole("button",{name:"Local championship",exact:true}).click(); + return page.getByRole("dialog",{name:"Local championship",exact:true}); +} +async function create(page:Page,laps=1){ + const panel=await enter(page); + await panel.getByLabel("Championship laps",{exact:true}).fill(String(laps)); + await panel.getByLabel("Championship base lap seconds",{exact:true}).fill("30"); + await panel.getByLabel("Round 1 venue",{exact:true}).selectOption("replay:monza-2024"); + await panel.getByLabel("Round 2 venue",{exact:true}).selectOption("replay:session-11412"); + await panel.getByLabel("Round 3 venue",{exact:true}).selectOption("starter"); + await panel.getByRole("button",{name:"Create three-race championship",exact:true}).click(); + await expect(panel.getByTestId("cup-progress")).toHaveText("0/3 rounds complete"); + return panel; +} +test("completes a three-venue championship, saves standings and resumes between rounds",async({page})=>{ + const panel=await create(page); + const initialBudget=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).credits,teamKey); + for(let round=1;round<=3;round++){ + await panel.getByRole("button",{name:`Begin round ${round}`,exact:true}).click(); + await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click(); + await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click(); + await expect(panel.getByTestId("cup-progress")).toHaveText(`${round}/3 rounds complete`); + await expect(panel.getByRole("status")).toContainText(`Saved ${round}/3 results`); + const state=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),championshipKey); + expect(state.results).toHaveLength(round);expect(state.session).toBeNull(); + if(round===1){ + await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByTestId("cup-progress")).toHaveText("1/3 rounds complete"); + } + } + await expect(panel.getByRole("heading",{name:/Championship complete/})).toBeVisible(); + await expect(panel.getByRole("button",{name:/Begin round/})).toHaveCount(0); + const before=await panel.getByRole("region",{name:"Championship standings",exact:true}).innerText(); + await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByRole("region",{name:"Championship standings",exact:true})).toHaveText(before,{useInnerText:true}); + expect(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).credits,teamKey)).toBe(initialBudget); + await panel.getByRole("button",{name:"Close Local championship",exact:true}).click(); + await expect(page.getByTestId("elapsed-time")).toContainText("00:02:00"); +}); + +test("another tab's championship change locks stale controls until the saved checkpoint is loaded",async({page,context})=>{ + const panel=await create(page); + const other=await context.newPage(); + try{ + await other.goto("/?race=monza-2024");await other.getByRole("button",{name:"Local championship",exact:true}).click(); + const viewer=other.getByRole("dialog",{name:"Local championship",exact:true}); + await expect(viewer.getByTestId("cup-progress")).toHaveText("0/3 rounds complete"); + await panel.getByRole("button",{name:"Begin round 1",exact:true}).click(); + await expect(viewer.getByRole("alert")).toContainText("another tab"); + await expect(viewer.getByRole("button",{name:"Begin round 1",exact:true})).toBeDisabled(); + await viewer.getByRole("button",{name:"Load saved championship",exact:true}).click(); + await expect(viewer.getByRole("button",{name:"Run championship race",exact:true})).toBeEnabled(); + await expect(viewer.getByTestId("cup-clock")).toHaveText("00:00:00"); + }finally{await other.close();} +}); +test("restores a saved live checkpoint and pit decision paused, and persists animation on close",async({page})=>{ + const panel=await create(page,4); + await panel.getByRole("button",{name:"Begin round 1",exact:true}).click(); + await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click(); + await expect(panel.getByTestId("cup-clock")).toHaveText("00:00:30"); + await panel.getByRole("button",{name:"Box championship this lap",exact:true}).click(); + await panel.getByRole("button",{name:"Save championship checkpoint",exact:true}).click(); + await expect(panel.getByRole("status")).toContainText("checkpoint 00:00:30"); + await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByTestId("cup-clock")).toHaveText("00:00:30"); + await expect(panel.getByText("Your driver's pit entry is queued on lap 2.",{exact:true})).toBeVisible(); + await panel.getByRole("button",{name:"Run championship race",exact:true}).click(); + await expect(panel.getByTestId("cup-clock")).not.toHaveText("00:00:30"); + await panel.getByRole("button",{name:"Pause championship race",exact:true}).click(); + const clock=await panel.getByTestId("cup-clock").innerText(); + await panel.getByRole("button",{name:"Close Local championship",exact:true}).click(); + await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByTestId("cup-clock")).toHaveText(clock); + await expect(panel.getByRole("button",{name:"Run championship race",exact:true})).toBeVisible(); +}); +test("failed checkpoint writes preserve the previous save and the championship fits mobile",async({page})=>{ + await page.setViewportSize({width:390,height:844});await page.emulateMedia({colorScheme:"light"}); + const panel=await create(page); + const before=await page.evaluate(key=>localStorage.getItem(key),championshipKey); + await page.evaluate(()=>{Storage.prototype.setItem=()=>{throw new Error("Storage denied");};}); + await panel.getByRole("button",{name:"Begin round 1",exact:true}).click(); + await expect(panel.getByRole("alert")).toContainText("Storage denied"); + expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBe(before); + await expect(panel.getByRole("button",{name:"Run championship race",exact:true})).toBeDisabled(); + expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true); +}); +test("unreadable championship data is preserved until explicitly backed up and discarded",async({page})=>{ + const raw="{bad-cup-save"; + await page.addInitScript(({key,raw})=>localStorage.setItem(key,raw),{key:championshipKey,raw}); + const panel=await enter(page); + await expect(panel.getByRole("alert")).toContainText("kept intact"); + expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBe(raw); + const download=page.waitForEvent("download"); + await panel.getByRole("button",{name:"Back up unreadable championship",exact:true}).click(); + const stream=await(await download).createReadStream(),chunks=[];for await(const chunk of stream!)chunks.push(chunk); + expect(JSON.parse(Buffer.concat(chunks).toString()).raw).toBe(raw); + await panel.getByRole("button",{name:"Discard unreadable championship",exact:true}).click(); + await panel.getByRole("button",{name:"Confirm discard championship",exact:true}).click(); + await expect(panel.getByRole("alert")).toHaveCount(0); + expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBeNull(); +}); diff --git a/frontend/e2e/recruitment.spec.ts b/frontend/e2e/recruitment.spec.ts new file mode 100644 index 0000000..29f6e0a --- /dev/null +++ b/frontend/e2e/recruitment.spec.ts @@ -0,0 +1,128 @@ +import {test,expect} from "@playwright/test"; +import {newTeam,signingFee,releaseRefund,teamKey} from "../src/recruitment"; + +test("recruits generated prospects, preserves the market and budget on reload, scouts and releases", async ({page}) => { + const initial={...newTeam(42),revision:1}, prospect=initial.market[0]; + await page.addInitScript(({key,team})=>{if(!localStorage.getItem(key))localStorage.setItem(key,JSON.stringify(team));},{key:teamKey,team:initial}); + await page.goto("/?race=monza-2024&t=120"); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await panel.getByRole("article",{name:`Market ${prospect.name}`,exact:true}).getByRole("button",{name:/^Sign /}).click(); + const remaining=12000-signingFee(prospect.stats); + await expect(panel.getByTestId("team-credits")).toHaveText(`${remaining.toLocaleString("en-US")} credits`); + await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers"); + await page.reload(); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + await expect(panel.getByRole("article",{name:`Signed ${prospect.name}`,exact:true})).toBeVisible(); + await expect(panel.getByRole("article",{name:`Market ${prospect.name}`,exact:true})).toHaveCount(0); + await expect(panel.getByTestId("team-credits")).toHaveText(`${remaining.toLocaleString("en-US")} credits`); + await panel.getByRole("button",{name:/^Release /}).click(); + await expect(panel.getByTestId("roster-count")).toHaveText("0/6 drivers"); + const after=remaining+releaseRefund(prospect)-250; + await panel.getByRole("button",{name:"Scout new market · 250 credits",exact:true}).click(); + await expect(panel.getByTestId("team-credits")).toHaveText(`${after.toLocaleString("en-US")} credits`); + await expect(panel.getByRole("region",{name:"Driver market",exact:true}).getByRole("article")).toHaveCount(6); + const download=page.waitForEvent("download"); + await panel.getByRole("button",{name:"Export team JSON",exact:true}).click(); + const stream=await(await download).createReadStream(),chunks=[]; + for await(const chunk of stream!)chunks.push(chunk); + const exported=JSON.parse(Buffer.concat(chunks).toString()); + expect(exported.credits).toBe(after);expect(exported.roster).toHaveLength(0); +}); + +test("custom builds respect points and swapping the lineup changes the sandbox and new room setup", 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(); + await page.getByRole("button",{name:"Advance one lap",exact:true}).click(); + await page.getByRole("button",{name:"Recruit and manage drivers",exact:true}).click(); + const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + const custom=panel.getByRole("region",{name:"Custom driver builder",exact:true}); + await custom.getByLabel("Custom driver name",{exact:true}).fill("Apex"); + await custom.getByLabel("Custom pace",{exact:true}).fill("100"); + await expect(custom.getByRole("button",{name:"Create and sign custom driver",exact:true})).toBeDisabled(); + await custom.getByLabel("Custom consistency",{exact:true}).fill("60"); + await custom.getByLabel("Custom pit discipline",{exact:true}).fill("50"); + await custom.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers"); + await custom.getByLabel("Custom driver name",{exact:true}).fill("Crew"); + await custom.getByLabel("Custom pace",{exact:true}).fill("50"); + await custom.getByLabel("Custom consistency",{exact:true}).fill("50"); + await custom.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(panel.getByTestId("roster-count")).toHaveText("2/6 drivers"); + const state=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + await panel.getByLabel("Race seat 1",{exact:true}).selectOption(state.roster[0].id); + await panel.getByLabel("Race seat 2",{exact:true}).selectOption(state.roster[1].id); + await panel.getByRole("button",{name:"Swap race seats",exact:true}).click(); + await panel.getByRole("button",{name:"Apply lineup and restart sandbox",exact:true}).click(); + const sandbox=page.getByRole("region",{name:"Circuit race sandbox",exact:true}); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Crew"); + await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Apex"); + await expect(sandbox.getByLabel("Grid 1 pace offset",{exact:true})).toHaveValue("2.4"); + await expect(sandbox.getByLabel("Grid 2 pace offset",{exact:true})).toHaveValue("-1.68"); + await expect(sandbox.getByLabel("Grid 2 service seconds",{exact:true})).toHaveValue("3"); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:00:00"); + await expect(sandbox.getByLabel("Grid 3 driver name",{exact:true})).toHaveValue("Driver 3"); + await sandbox.getByRole("button",{name:"Host this setup with friends",exact:true}).click(); + const room=page.getByRole("dialog",{name:"Multiplayer rooms",exact:true}); + await room.getByLabel("Guest name",{exact:true}).fill("Recruiter"); + await room.getByRole("button",{name:"Create private room",exact:true}).click(); + await expect(room.getByRole("button",{name:"Claim Crew",exact:true})).toBeVisible(); + await expect(room.getByRole("button",{name:"Claim Apex",exact:true})).toBeVisible(); +}); + +test("recruitment is usable on mobile and failed storage writes do not spend credits", async ({page}) => { + await page.setViewportSize({width:390,height:844}); + await page.emulateMedia({colorScheme:"light"}); + await page.addInitScript(()=>{Storage.prototype.setItem=()=>{throw new Error("Storage denied");};}); + await page.goto("/?race=monza-2024"); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await expect(panel.getByRole("alert")).toBeVisible(); + await panel.getByRole("region",{name:"Custom driver builder",exact:true}).getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(panel.getByTestId("team-credits")).toHaveText("12,000 credits"); + await expect(panel.getByTestId("roster-count")).toHaveText("0/6 drivers"); + expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true); +}); + +test("another tab's purchase cannot be overwritten by a stale team screen", async ({page,context}) => { + await page.goto("/?race=monza-2024"); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await expect(panel.getByRole("button",{name:"Create and sign custom driver",exact:true})).toBeEnabled(); + const other=await context.newPage(); + try { + await other.goto("/?race=monza-2024"); + await other.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + await other.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(panel.getByRole("alert")).toContainText("another tab"); + await panel.getByRole("button",{name:"Scout new market · 250 credits",exact:true}).click(); + await expect(panel.getByRole("alert")).toContainText("another tab"); + await panel.getByRole("button",{name:"Load latest team",exact:true}).click(); + await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers"); + await expect(panel.getByTestId("team-credits")).toHaveText("7,325 credits"); + } finally {await other.close();} +}); + +test("unreadable team data stays intact until a fresh-team reset is explicitly confirmed", async ({page}) => { + const raw="{broken-team-json"; + await page.addInitScript(({key,raw})=>localStorage.setItem(key,raw),{key:teamKey,raw}); + await page.goto("/?race=monza-2024"); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await expect(panel.getByRole("alert")).toContainText("could not be read"); + expect(await page.evaluate(key=>localStorage.getItem(key),teamKey)).toBe(raw); + const download=page.waitForEvent("download"); + await panel.getByRole("button",{name:"Back up stored team data",exact:true}).click(); + const stream=await(await download).createReadStream(),chunks=[]; + for await(const chunk of stream!)chunks.push(chunk); + expect(JSON.parse(Buffer.concat(chunks).toString()).raw).toBe(raw); + await panel.getByRole("button",{name:"Start fresh team",exact:true}).click(); + await panel.getByRole("button",{name:"Keep current team",exact:true}).click(); + expect(await page.evaluate(key=>localStorage.getItem(key),teamKey)).toBe(raw); + await panel.getByRole("button",{name:"Start fresh team",exact:true}).click(); + await panel.getByRole("button",{name:"Confirm fresh team",exact:true}).click(); + await expect(panel.getByRole("alert")).toHaveCount(0); + const saved=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + expect(saved.credits).toBe(12000);expect(saved.roster).toEqual([]);expect(saved.market).toHaveLength(6); +}); diff --git a/frontend/e2e/roster-tracks.spec.ts b/frontend/e2e/roster-tracks.spec.ts new file mode 100644 index 0000000..96a37fe --- /dev/null +++ b/frontend/e2e/roster-tracks.spec.ts @@ -0,0 +1,78 @@ +import {test,expect} from "@playwright/test"; +import {createDriver,newTeam,teamKey} from "../src/recruitment"; + +test("a signing appears in an open sandbox and can be synced or swapped without reopening the studio",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.getByRole("button",{name:"Advance one lap",exact:true}).click(); + await sandbox.getByRole("button",{name:"Recruit and manage drivers",exact:true}).click(); + const recruit=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await recruit.getByLabel("Custom driver name",{exact:true}).fill("Synced rookie"); + await recruit.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(recruit.getByTestId("roster-count")).toHaveText("1/6 drivers"); + await recruit.getByRole("button",{name:"Close Driver recruitment",exact:true}).click(); + await expect(sandbox.getByRole("heading",{name:"Signed team drivers · 1 available",exact:true})).toBeVisible(); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30"); + await sandbox.getByRole("button",{name:"Sync team lineup and restart",exact:true}).click(); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Synced rookie"); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:00:00"); + await sandbox.getByLabel("Signed driver for grid 2",{exact:true}).selectOption({label:"Synced rookie"}); + await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Synced rookie"); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Driver 2"); +}); + +test("race this circuit uses the current replay outline and signed lineup, then hosts the copied venue",async({page})=>{ + const team={...createDriver(createDriver(newTeam(42),{id:"apex",name:"Venue Apex",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"crew",name:"Venue Crew",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1}; + await page.addInitScript(({key,team})=>localStorage.setItem(key,JSON.stringify(team)),{key:teamKey,team}); + await page.goto("/?race=monza-2024&t=120"); + await page.getByRole("button",{name:"Race this circuit",exact:true}).click(); + const studio=page.getByRole("dialog",{name:"Custom circuit studio",exact:true}); + const sandbox=studio.getByRole("region",{name:"Circuit race sandbox",exact:true}); + await expect(sandbox).toBeVisible(); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Venue Apex"); + await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Venue Crew"); + await sandbox.getByRole("button",{name:"Advance one lap",exact:true}).click(); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30"); + await studio.getByRole("button",{name:"Circuit editor",exact:true}).click(); + await expect(studio.getByLabel("Circuit name",{exact:true})).toHaveValue("Monza 2024 · sandbox"); + await expect(studio.getByRole("alert")).toHaveCount(0); + await studio.getByRole("button",{name:"Circuit race sandbox",exact:true}).click(); + await sandbox.getByRole("button",{name:"Host this setup with friends",exact:true}).click(); + const room=page.getByRole("dialog",{name:"Multiplayer rooms",exact:true}); + await room.getByLabel("Guest name",{exact:true}).fill("Venue host"); + await room.getByRole("button",{name:"Create private room",exact:true}).click(); + await expect(room.getByRole("status",{exact:true})).toHaveText("Connected"); + await expect(room.getByRole("button",{name:"Claim Venue Apex",exact:true})).toBeVisible(); + await room.getByRole("button",{name:"Close Multiplayer rooms",exact:true}).click(); + await studio.getByRole("button",{name:"Close Custom circuit studio",exact:true}).click(); + await expect(page.getByTestId("elapsed-time")).toContainText("00:02:00"); +}); + +test("saved custom grids keep their setup while roster changes arrive from another tab",async({page,context})=>{ + await page.goto("/?race=monza-2024"); + await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click(); + await page.getByLabel("Circuit name",{exact:true}).fill("Retained custom grid"); + 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("Grid 1 driver name",{exact:true}).fill("Keep my grid"); + await sandbox.getByRole("button",{name:"Save circuit and race setup",exact:true}).click(); + await sandbox.getByRole("button",{name:"Advance one lap",exact:true}).click(); + const other=await context.newPage(); + try{ + await other.goto("/?race=monza-2024"); + await other.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + await other.getByLabel("Custom driver name",{exact:true}).fill("New signing"); + await other.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(sandbox.getByRole("heading",{name:"Signed team drivers · 1 available",exact:true})).toBeVisible(); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Keep my grid"); + await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30"); + await page.reload(); + await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click(); + await page.getByLabel("Saved circuits",{exact:true}).selectOption({label:"Retained custom grid"}); + await page.getByRole("button",{name:"Load circuit",exact:true}).click(); + await page.getByRole("button",{name:"Circuit race sandbox",exact:true}).click(); + await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Keep my grid"); + }finally{await other.close();} +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e3bf5d6..0d7b9bd 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "pitwall-web", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pitwall-web", - "version": "1.3.0", + "version": "1.4.0", "dependencies": { "@microsoft/signalr": "^10.0.11", "lucide-react": "^0.468.0", diff --git a/frontend/package.json b/frontend/package.json index 003749a..611bd60 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "pitwall-web", "private": true, - "version": "1.3.0", + "version": "1.4.0", "type": "module", "scripts": { "dev": "vite --configLoader native --host 127.0.0.1", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 5533191..de9cd3b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,6 +6,7 @@ import { useMemo, useState, } from "react"; +import {version as appVersion} from "../package.json"; import { Activity, ArrowLeft, @@ -48,6 +49,8 @@ const StrategyLab = lazy(() => import("./StrategyLab")); const RaceAnalysis = lazy(() => import("./RaceAnalysis")); const PaceBacktest = lazy(() => import("./PaceBacktest")); const MultiplayerRooms = lazy(() => import("./MultiplayerRooms")); +const DriverRecruitment = lazy(() => import("./DriverRecruitment")); +const LocalChampionship = lazy(() => import("./LocalChampionship")); import "./lab.css"; import { momentLink, readMoment } from "./replay-link"; import { ensureTiming } from "./import-job"; @@ -87,11 +90,14 @@ function App() { const [shareLink, setShareLink] = useState(null); const [positionSource, setPositionSource] = useState("lap"); const [showTrackEditor, setShowTrackEditor] = useState(false); + const [raceOnReplay, setRaceOnReplay] = useState(false); const [showStrategy, setShowStrategy] = useState(false); const [showAnalysis, setShowAnalysis] = useState(false); const [showBacktest, setShowBacktest] = useState(false); const [showRooms, setShowRooms] = useState(() => new URLSearchParams(location.search).has("room")); - const activeTool = showRooms ? "rooms" : showLibrary + const [showRecruitment, setShowRecruitment] = useState(false); + const [showChampionship, setShowChampionship] = useState(false); + const activeTool = showChampionship ? "championship" : showRecruitment ? "recruitment" : showRooms ? "rooms" : showLibrary ? "library" : shareLink ? "share" @@ -105,6 +111,8 @@ function App() { ? "backtest" : "none"; const closeTools = () => { + setShowChampionship(false); + setShowRecruitment(false); setShowRooms(false); setShowLibrary(false); setShareLink(null); @@ -193,6 +201,8 @@ function App() { showAnalysis || showBacktest || showRooms || + showRecruitment || + showChampionship || document.querySelector("dialog[open]") ) return; @@ -222,6 +232,8 @@ function App() { showAnalysis, showBacktest, showRooms, + showRecruitment, + showChampionship, ]); useEffect(() => { if (!notice) return; @@ -317,7 +329,7 @@ function App() { pitwall╱
- RACE REPLAY LAB V1.3 + RACE REPLAY LAB V{appVersion}
@@ -419,6 +431,9 @@ function App() {
REPLAY TOOLS + + +
+ + {showRecruitment && Loading recruitment…

}> setShowRecruitment(false)} />
} {showRoom && Loading multiplayer…

}> setShowRoom(false)} />
} +
+

Signed team drivers · {signed.team.roster.length} available

+

Your signed roster updates here automatically. New unsaved grids use your selected team seats. Existing grids and running races change only when you apply a signed build or sync the lineup; doing so restarts this local run.

+ {signed.warning &&

Could not load the signed roster. Open recruitment to recover it; your current grid stays available.

} + +