From 0b33bdc1243ce46a70da50edc19d1a01344a6ea8 Mon Sep 17 00:00:00 2001 From: Nirmith Victor Date: Sat, 21 Nov 2026 20:05:52 -0500 Subject: [PATCH 1/4] Add fictional driver recruiting, custom builds and lineup swaps --- README.md | 1 + docs/DEMO.md | 2 +- docs/FOLLOW-UP-PLAN.md | 2 + docs/TESTING.md | 5 +- docs/USER-GUIDE.md | 20 +++- docs/flows.json | 116 ++++++++++++++++++++ docs/guide/05-race-sandbox.md | 2 + docs/guide/06-maintenance.md | 1 + docs/guide/08-driver-recruitment.md | 99 ++++++++++++++++++ frontend/e2e/recruitment.spec.ts | 128 +++++++++++++++++++++++ frontend/src/App.tsx | 9 +- frontend/src/CircuitSandbox.tsx | 4 + frontend/src/DriverRecruitment.tsx | 124 ++++++++++++++++++++++ frontend/src/lab.css | 9 ++ frontend/src/recruitment.test.ts | 88 ++++++++++++++++ frontend/src/recruitment.ts | 157 ++++++++++++++++++++++++++++ 16 files changed, 762 insertions(+), 5 deletions(-) create mode 100644 docs/guide/08-driver-recruitment.md create mode 100644 frontend/e2e/recruitment.spec.ts create mode 100644 frontend/src/DriverRecruitment.tsx create mode 100644 frontend/src/recruitment.test.ts create mode 100644 frontend/src/recruitment.ts diff --git a/README.md b/README.md index b75773f..df9a3fb 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ 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). - 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 3c200c7..8377dd3 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -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): 73 frontend unit checks, nine Node checks, 54 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..a5b6e2a 100644 --- a/docs/FOLLOW-UP-PLAN.md +++ b/docs/FOLLOW-UP-PLAN.md @@ -49,6 +49,8 @@ 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. + ## 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..50d92b5 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: 54 browser scenarios | Area | Coverage | | --- | --- | @@ -33,6 +33,7 @@ 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 | | 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 +41,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. +- 73 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..6799f87 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -15,6 +15,7 @@ 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). 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 +30,7 @@ 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 | ```mermaid flowchart LR @@ -41,6 +43,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 +64,7 @@ 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 | 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 +86,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser -76 documented flows. Each ID links directly to its instructions. +84 documented flows. Each ID links directly to its instructions. ### Start Pitwall and choose a race @@ -193,6 +198,19 @@ 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 | ## How this stays current diff --git a/docs/flows.json b/docs/flows.json index c1ec25a..b6286be 100644 --- a/docs/flows.json +++ b/docs/flows.json @@ -30,6 +30,10 @@ { "path": "docs/guide/07-multiplayer.md", "title": "Private multiplayer races" + }, + { + "path": "docs/guide/08-driver-recruitment.md", + "title": "Fictional driver recruitment and builds" } ], "sharedComponents": [ @@ -902,6 +906,118 @@ "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" + ] } ] } diff --git a/docs/guide/05-race-sandbox.md b/docs/guide/05-race-sandbox.md index d734f56..8164f79 100644 --- a/docs/guide/05-race-sandbox.md +++ b/docs/guide/05-race-sandbox.md @@ -37,6 +37,8 @@ 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. + ## SANDBOX-03 — Attach and edit the pit lane diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md index f0ab8a7..a4802ae 100644 --- a/docs/guide/06-maintenance.md +++ b/docs/guide/06-maintenance.md @@ -16,6 +16,7 @@ | 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 | | 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..a4ded89 --- /dev/null +++ b/docs/guide/08-driver-recruitment.md @@ -0,0 +1,99 @@ +# 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. 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. 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/src/App.tsx b/frontend/src/App.tsx index 5533191..32b9745 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -48,6 +48,7 @@ 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")); import "./lab.css"; import { momentLink, readMoment } from "./replay-link"; import { ensureTiming } from "./import-job"; @@ -91,7 +92,8 @@ function App() { 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 activeTool = showRecruitment ? "recruitment" : showRooms ? "rooms" : showLibrary ? "library" : shareLink ? "share" @@ -105,6 +107,7 @@ function App() { ? "backtest" : "none"; const closeTools = () => { + setShowRecruitment(false); setShowRooms(false); setShowLibrary(false); setShareLink(null); @@ -193,6 +196,7 @@ function App() { showAnalysis || showBacktest || showRooms || + showRecruitment || document.querySelector("dialog[open]") ) return; @@ -222,6 +226,7 @@ function App() { showAnalysis, showBacktest, showRooms, + showRecruitment, ]); useEffect(() => { if (!notice) return; @@ -419,6 +424,7 @@ function App() {
REPLAY TOOLS +
+ + {showRecruitment && Loading recruitment…

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

}> setShowRoom(false)} />
}