Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3395fb4f90 | ||
|
|
537c494daa | ||
|
|
69b708dad3 | ||
|
|
e109e003c0 | ||
|
|
cbe0cda15d | ||
|
|
4620707abc | ||
|
|
3024606ac8 | ||
|
|
f44e7aa0f5 | ||
|
|
58d05f5287 | ||
|
|
e18d39edd0 | ||
|
|
a7150a1062 | ||
|
|
8eeef401ae | ||
|
|
f273d385c2 | ||
|
|
3b02c7feac | ||
|
|
1ba70ebbf3 | ||
|
|
08a819e44c | ||
|
|
50a9147665 | ||
|
|
5391636979 | ||
|
|
ab79d9b17f | ||
|
|
505a58b4fe | ||
|
|
2655ef81c8 | ||
|
|
ac4e3fa316 | ||
|
|
f2dbad5e03 | ||
|
|
096a6bfe61 | ||
|
|
71ee63b38a | ||
|
|
a4f7947666 | ||
|
|
570ad52d47 | ||
|
|
59974d1b79 | ||
|
|
af5176354a | ||
|
|
f5468bb640 |
@@ -1 +1,2 @@
|
||||
# No environment variables required yet.
|
||||
GITEA_TOKEN=gitea-api-token
|
||||
@@ -1,7 +1,7 @@
|
||||
# Flight Simulator — Workflow Rules
|
||||
|
||||
## Change process (mandatory)
|
||||
1. **Small, incremental changes** — work is done one change at a time, in smaller parts; each part must be tested thoroughly with unit and e2e tests covering it before moving on.
|
||||
1. **Small, incremental changes** — work is done one change at a time, in smaller parts; each part must be tested thoroughly with unit and e2e tests covering it before moving on. Connected issues/tasks that reference the same part of code MAY be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel).
|
||||
2. **Feature branch + PR** — every change lands on a feature branch off `master` (no direct pushes to master). The branch carries the commits below; open a pull request to `master`.
|
||||
3. **Changelog entry** — every such change is listed in `CHANGELOG.md` with date, time and version (format: `## v<version> — YYYY-MM-DD HH:MM`, then bullet points of what changed).
|
||||
4. **Version bump** — the version is updated in `package.json`.
|
||||
@@ -9,10 +9,8 @@
|
||||
6. **Tag + manual deploy after merge** — once merged, tag the version on `master` (e.g. `v0.13.0`). Production (`https://flight.dev.kkhost.pl`) is updated manually afterwards: `docker compose up -d --build` on the host.
|
||||
|
||||
## E2E tests (mandatory)
|
||||
1. **Docker compose instance is the app under test** — e2e always runs against a docker-compose build, never a local `next dev` on :3000 (dev builds don't render for non-loopback clients, and a second instance splits state). Locally that means the Traefik-routed instance at `https://flight.dev.kkhost.pl`; in CI it is an isolated stack inside dind (`docker-compose.ci.yml`) — **CI never deploys to or modifies production**.
|
||||
2. **Update before testing (local)** — deploy current code first: `docker compose up -d --build`, then run the suite with plain `npx playwright test`. The config's webServer block is off by default; set `E2E_DEPLOY_CMD` to have Playwright itself run a deploy command and wait for readiness.
|
||||
3. **Remote browsers** — local runs drive browsers through the shared Playwright server at `192.168.1.4:3000` (Docker image tag must match this repo's @playwright/test version, pinned in devDependencies). Set `PW_REMOTE_BROWSER=0` to run local chromium instead — CI does, because the remote server cannot reach a stack inside dind.
|
||||
4. **CI env vars** (`playwright.config.ts`, all optional; defaults preserve the local flow) — `E2E_BASE_URL` (app under test), `E2E_DEPLOY_CMD` (webServer deploy command), `PW_REMOTE_BROWSER=0` (local browsers); `e2e/state.spec.ts` reads `E2E_COMPOSE_ARGS` for its mid-run container restart.
|
||||
1. **CI-only** — e2e runs ONLY in CI, against an isolated docker stack inside dind built from `docker-compose.ci.yml` (project name `flight-ci`, app container on a static IP; see `.gitea/workflows/ci.yml`). There are NO local e2e runs at all: locally you verify with `tsc --noEmit` + `npx vitest run` + `npx playwright test --list` (typecheck, unit suite, specs compile and list), and the full e2e suite is verified by CI on every PR. **CI never deploys to or modifies production.**
|
||||
2. **CI env vars** (`playwright.config.ts`, all optional) — `E2E_BASE_URL` (app under test; CI sets it to the in-network app host, so the config's default of the live Traefik instance at `https://flight.dev.kkhost.pl` is never used), `E2E_DEPLOY_CMD` (runs as Playwright webServer: deploys the stack and waits for readiness before tests start; CI uses build + `up -d` + `logs -f`), `PW_REMOTE_BROWSER=0` (CI runs local chromium because the shared remote browser server at 192.168.1.4 cannot reach a stack inside dind — when unset, the config defaults to that remote server and to the live instance as baseURL), and `E2E_COMPOSE_ARGS`, read by `e2e/state.spec.ts` for its mid-run `docker compose restart flight` (CI points it at `-f docker-compose.ci.yml -p flight-ci`).
|
||||
|
||||
## API
|
||||
1. **Live base URL** — `https://flight.dev.kkhost.pl` (the docker-compose build behind Traefik).
|
||||
|
||||
@@ -1,5 +1,66 @@
|
||||
# Changelog
|
||||
|
||||
## v0.25.0 — 2026-09-20 10:36
|
||||
- **Planes now hold a queue of upcoming flight legs (ISS-043, part 1 — backend).** One new column on `planes`: `queue TEXT NOT NULL DEFAULT '[]'` (`lib/db/schema.ts`, DDL + guarded `ALTER TABLE` migration in `lib/db/client.ts`) storing an ordered JSON array of ICAO strings = the legs NOT yet started. The active leg stays exactly as before (`destIcao` + `departureSimTime`); full path = `[locationIcao, destIcao, ...queue]`. No new table — queues are short, per-plane, always read/written whole
|
||||
- **Auto-chain on landing (ISS-043).** In `deliverPackages()` (`lib/sim/engine.ts`) a plane that arrives now reads its queue: if it holds legs AND fuel covers the first one (same `requiredFuelFor` feasibility rule as `/fly`), it immediately starts that leg from the arrival airport — stays `'flying'`, `departureSimTime` = the arrival instant, queue shortened. If fuel is short it grounds safely with the remaining queue kept intact for refuel + re-dispatch; an empty queue grounds exactly as before. Cargo delivery for the reached airport runs first and is unaffected by chaining. Ordering preserved on purpose: delivery runs BEFORE tickOnce's pause check (ISS-041), so a chained plane counts as still flying there — chaining never triggers the last-plane pause
|
||||
- **New endpoints (ISS-043).** `POST /api/planes/{planeId}/queue` body `{destIcao}` appends a not-yet-started leg (works grounded or flying — pre-build a route; nothing auto-starts, 400 unknown ICAO/bad body, 404 unknown plane); `POST /api/planes/{planeId}/queue/cancel` body `{index}` removes a queued leg by index (only queued legs are cancellable — the active in-flight leg is never touched; 400 non-integer/out-of-range index, 404 unknown plane). Both run through `performAction()` like every other action and return the full state snapshot. New actions `queueLeg`/`cancelQueuedLeg` in `lib/game/actions.ts`; routes under `app/api/planes/[planeId]/queue/`
|
||||
- **Snapshot + spec (ISS-043).** `PlaneState.queue: string[]` added to the `/api/state` snapshot (`lib/game/state.ts`, parsed with a null/malformed-safe helper shared by the engine); OpenAPI updated — `PlaneState.queue`, `QueueLegRequest`, `CancelQueuedLegRequest`, both new paths (200→snapshot, 400, 404)
|
||||
- Tests: unit — `lib/sim/engine.test.ts`: auto-chain block in `deliverPackages` (lands with queue + enough fuel → `'flying'` to the next dest at the arrival instant with the queue shortened; lands short on fuel → grounds with the queue intact; empty queue → unchanged grounding) plus a pause-on-landing regression guard — a chained plane does NOT trigger the last-plane pause. `lib/game/actions.test.ts`: `queueLeg` (appends in order, works while flying without touching the active leg, 404 unknown plane, 400 unknown ICAO) and `cancelQueuedLeg` (removes the right index keeping order, 400 out-of-range/negative/empty-queue, 404 unknown plane). `lib/openapi.test.ts`: endpoint count ten → twelve, PlaneState keys + both request schemas. Type-compat only: `queue: []` added to the `PlaneState`/seed fixtures in `deriveEvents`, `right-pane`, `mapData`, `seed` tests
|
||||
- Part 1 of ISS-043 (backend) — UI/map rendering of queued legs lands in a follow-up part. Verified: `tsc --noEmit` clean; unit suite green locally; `npx playwright test --list` unchanged at 42 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.24.0 — 2026-09-20 09:48
|
||||
- **Landing now pauses the sim instead of auto-slowing to 1× (ISS-041).** When the LAST plane in flight lands, `tickOnce` (`lib/sim/engine.ts`) sets `sim_state.paused = true` WITHOUT touching `timeScale` — speed is preserved. The trigger condition carries over from ISS-011's auto-slow unchanged: ≥1 landing this tick AND no `'flying'` planes remain (a landing while another plane is still airborne does not pause — there would be nothing to auto-resume it). No idle-enforcement or auto-restore of the pause exists
|
||||
- **Starting a flight auto-resumes a paused sim (ISS-041).** `flyPlane()` (`lib/game/actions.ts`) writes `sim_state.paused = false` before persisting — inside `runAction()`, so tick + unpause + dispatch are atomic under the sim lock. The cycle: dispatch unpauses → last landing pauses (speed preserved) → next dispatch unpauses again
|
||||
- Tests: unit — `lib/sim/engine.test.ts`: the auto-slow describe block rewritten for pause semantics (last plane lands → `paused === true` AND stored `timeScale` UNCHANGED, persisted on the DB row; a landing while another plane is still flying → no pause; last landing at scale 1 → pauses anyway; paused tick with a fully grounded fleet → trigger never fires). `lib/game/actions.test.ts`: new test — dispatching on a paused sim clears `paused` and leaves `timeScale` untouched. E2E — `e2e/auto-slow.spec.ts` renamed to `e2e/pause-on-landing.spec.ts` and reworked: after the starter lands, asserts `simState.paused === true` AND `timeScale` still 1000 (NOT reset), then a subsequent `/fly` dispatch clears `paused` on its own post-action snapshot. Cross-cutting fix for the new pause: every per-spec `setScale` helper (`actions`, `hover`, `map-interactions`, `relocation`, `right-pane`) now POSTs `{ timeScale, paused: false }` — a landing pauses the sim, so a scale-only fast-forward after one would leave the clock frozen and hang the next wait; no caller relied on it NOT clearing pause (verified per call site). Deliberate mid-test pauses (`sim.spec.ts` / `panes.spec.ts` freeze tests, marker-click freezes) are untouched
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally (291); `npx playwright test --list` = 42 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.23.2 — 2026-09-20 09:15
|
||||
- **On-board package hover previews the route from the carrier's current position (ISS-040).** Hovering a loaded package in the left pane used to draw the great-circle trace from the package's ORIGIN airport; it now starts at the carrying plane's live lat/lon — identical while grounded at the pickup, correct once the plane has departed with cargo still loaded. New pure builder `hoverTraceGeoJson(from: AirportCoord, toIcao, airportsByIcao)` in `lib/mapData.ts` (sibling of `hoverRouteGeoJson`, same shape/conventions; empty collection when the destination is missing); `components/Map.tsx`'s `applyHoverRef` looks up the carrier via the hover's `planeId` and uses it, falling back to the ICAO trace when no carrier is in state. The `[state]` effect now also re-applies the hover so the trace follows a moving carrier between polls while hovered (idempotent: one small setData + ring filters). Endpoint rings untouched — still ICAO-filtered origin/dest circles
|
||||
- Tests: unit — `lib/mapData.test.ts` gains a `hoverTraceGeoJson` block (exact endpoints from an arbitrary start coord; empty on missing dest). E2E — `e2e/hover.spec.ts`: new test loads a package at EDDF, dispatches the starter to LEMD via API, waits until its live position is >0.2° away from the hub, pauses the sim, hovers the on-board row and asserts some rendered trace segment starts within EPS of the carrier's live lat/lon AND some ends within EPS of LEMD AND no segment starts near EDDF (per-tile clipping handled via the existing cross-segment endpoint pattern); cleanup resumes + fast-forwards to arrival (auto-delivery) and flies home
|
||||
|
||||
## v0.23.1 — 2026-09-20 08:42
|
||||
- **Toasts repositioned to the map's right edge (ISS-039).** The `.toasts` stack was `position: fixed` at the viewport bottom-right, overlapping the 280px right pane; its `right` changed 12px → 292px (= 280px right pane + 12px inset) so it now sits flush against the map's right edge with the same 12px margin. No JSX/endpoint changes — all positioning lives in that one CSS value
|
||||
- Tests: e2e wording only — `toasts.spec.ts` header comment, test title, and toast visibility assertion message updated from "bottom-right" to "map right edge / clear of the right pane"; no position assertions added (none existed), suite unchanged at 41 tests in 12 files
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.23.0 — 2026-09-20 08:25
|
||||
- **Refuel-to-full row moves to the left pane (ISS-035).** Refueling a grounded plane is "anything with our plane", so it belongs in the left pane next to Relocate, not as a market row on the right. The `.market-row` JSX (`market-refuel-none` "All tanks full." span / `market-refuel-plane` select of grounded planes labeled `{planeName} — {fuel}/{maxFuel} L`, `market-refuel-cost` preview, `market-refuel` button → `POST /api/planes/{id}/refuel`) moved verbatim from the Market section in `components/RightPane.tsx` into a new "Refuel" `<section data-testid="refuel-section">` in `components/LeftPane.tsx`, inserted between Relocate and Time. Its state (`refuelPlaneId`) + derived values (`refuelable`, effective-selection `refuelPlane`, `refuelCost`) moved with it, reusing LeftPane's existing `grounded` list; busy gating rewired from RightPane's `busy` to LeftPane's own `useGameAction` instance (`actionsBusy`). Testids kept byte-identical so all e2e locators are unchanged. The per-package "Refuel" button in the On board section (`refuel-for-{pkg.id}`, mode 'forFlight') is a different feature and stays put; exported helpers `slotsUsedFor` / `loadEligiblePlanes` untouched
|
||||
- Tests: e2e — `right-pane.spec.ts`: the market test keeps its buy/sell assertions, renamed to reflect that the refuel row now renders inside `[data-testid="left-pane"]` (asserted before the click); functional cash/tank assertions unchanged; the for-leg test's title/comment updated from "market button" to left pane. `panes.spec.ts`: first test gains structural assertions — Refuel heading + `market-refuel` visible in the left pane, both absent from the right pane (same present-in-left / absent-from-right pattern as On board). No unit-test changes (suite stays at 288)
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests in 12 files; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.22.2 — 2026-09-20 07:32
|
||||
- Docs: ORCHESTRATOR.md successor-agent manual committed to the repo; its token reference now points to the gitignored local .env (GITEA_TOKEN, rotated after the Sept 2026 incident); §9 rewritten as durable 'how to find current state' guidance instead of a stale snapshot; no code changes
|
||||
|
||||
## v0.22.1 — 2026-09-20 06:57
|
||||
- Hygiene: gitignore the local-only ORCHESTRATOR.md successor-agent manual (it references host-specific setup and must never be version-controlled); no code changes
|
||||
|
||||
## v0.22.0 — 2026-09-19 21:42
|
||||
- **Hover route trace on job-list rows (ISS-022).** Hovering an open package in the right pane now draws the ENTIRE great-circle trace between origin and destination, not just the two endpoint rings. Zero pane edits — the rows already sent `{kind:'package', originIcao, destIcao}`; `components/Map.tsx` now derives from/to for any hover target carrying two ICAOs and pushes a new pure builder's output (`hoverRouteGeoJson(fromIcao, toIcao, airportsByIcao)` in `lib/mapData.ts`: one LineString via the existing `greatCircleArc` slerp, empty FeatureCollection when either endpoint is missing from the airport index or the `''` no-hover sentinel) into a NEW dedicated `hover-routes` GeoJSON source + top-most dashed `hover-route` LineLayer (paint: `#facc15` matching the airports-highlight ring, width 4, `line-dasharray [2,2]`). The shared `routes` source can't carry this — it only holds FLYING legs, so an open package's or a grounded relocation's planned route was never in it. The layer is added in `ensureLayers` after the highlight layers so style switches keep it; `applyHoverRef` re-pushes data on every hover
|
||||
- **Same trace on On-board cargo rows (ISS-025).** Each `onboard-package-{id}` row in the left pane's On board section now reports `{kind:'package', originIcao, destIcao, planeId: plane.id}` on mouseenter — same full trace as job-list rows PLUS the carrying plane's halo stays lit via the new optional `planeId` field (Map uses `h.planeId ?? ''` for the planes/routes-highlight filters). Mouseleave restores the block's plain `{kind:'plane', id}` highlight; leaving the whole block still ends at null because React fires the child's mouseleave before the parent's
|
||||
- **Relocate panel hover previews the planned flight (ISS-027).** The left pane's Relocate section gains `data-testid="relocate-section"` + enter/leave handlers: with a grounded plane AND destination selected it reports `{kind:'route', fromIcao: relocatePlane.locationIcao, toIcao: relocateDest.icao}` (else null), and Map draws the planned trace AND rings ONLY the target airport in airports-highlight (origin stays unmarked — the destination is what the issue asks to see). `HoverTarget` (`components/hoverTypes.ts`) extends to `{kind:'plane';id} | {kind:'package';originIcao;destIcao;planeId?} | {kind:'route';fromIcao;toIcao}`. Existing semantics unchanged: plane hovers filter the three highlight layers exactly as before, package hovers keep BOTH endpoint rings (now plus the trace)
|
||||
- **Target airport highlighted in a distinct color on job-list / relocation hover (ISS-022).** The destination of any two-endpoint hover now gets its own ring in a NEW top-most `airports-target-highlight` circle layer (`components/Map.tsx`, same `airports` source and r=9 transparent-fill geometry as airports-highlight, but green `#4ade80` stroke width 3 vs the yellow `#facc15` endpoint rings) — added last in `ensureLayers` so it also sits above the hover-route line at its endpoint; `applyHoverRef` filters it to the destination icao for BOTH `'package'` and `'route'` hovers (empty-string sentinel otherwise). airports-highlight itself is untouched, so the existing both-endpoints / target-only assertions stay valid
|
||||
- Tests: unit — new `describe('hoverRouteGeoJson …')` in `lib/mapData.test.ts`: no-hover sentinel → empty; two known airports → one arc with exact dataset endpoints; reversed-input symmetry; missing from/to ICAO → empty (baseline 283 → 288). e2e (`e2e/hover.spec.ts`) — open-package test extended with hover-route endpoint assertions (line geometry first/last coords compared against `/api/airports` lookups) + trace-clear check; new `hovering an on-board cargo row draws its trace and keeps the plane halo` (load via API, hover the row, assert trace endpoints + planes-highlight for that plane, abandon the package afterwards to leave a clean instance); new `hovering the Relocate section previews the planned route and target airport` (selects starter + LEMD via the existing testids, hovers `[data-testid="relocate-section"]`, asserts trace endpoints + target-only ring). New helpers: `airportLonLat(page, icao)` and `expectHoverRoute(page, fromIcao, toIcao)`; all new/extended assertions call `fitToAirports` first since `queryRenderedFeatures` is viewport-scoped
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally (288); `npx playwright test --list` = 41 tests (was 39, +2 new in hover.spec.ts); e2e not run locally by design — CI verifies against an isolated stack
|
||||
- **Fix: hover-route e2e timeouts (CI run #69).** All three trace tests failed at `expectHoverRoute` with the 15 s "waiting for the hover-route line EDDF → LEMD" timeout although the dashed trace WAS drawn correctly — the helper assumed `queryRenderedFeatures(undefined, {layers:['hover-route']})` returns exactly one feature whose endpoints are bit-identical to the `/api/airports` dataset coords. MapLibre GL JS stores GeoJSON geometry in per-tile INTEGER grids (`Math.round(extent·(x·2^z − tx))`, maplibre-gl 6.10) and clips long lines across tiles, so a 1420 km leg comes back as one feature PER intersecting tile (empirically 4 at z=4 / 5 at z=5 for EDDF→LEMD, verified against the installed build's GeoJSONVT) with endpoints quantized by up to ~half a grid step (~0.001° observed at z≥4, ~0.02° worst case at z=0): both the `feats.length !== 1` guard and the strict `===` coordinate comparisons could never be true. The helper now accepts any number of segments and matches endpoints within 0.05° (~5 km — above worst-case quantization at any zoom, below the distance between any two EU airports): some segment must start at origin and some end at destination; all other assertions unchanged. App side verified correct (no race: `ensureLayers` awaits the airport fetch before creating sources/layers and re-applies hover afterwards; layer/source ids match) — no app changes
|
||||
- **Fix: hover-route e2e — evaluate maplibre geometry in-page before Playwright serialization (CI runs #69–#71).** All three trace tests failed for a serialization reason, not a data one: `renderedFeatures` returned live `GeoJSONFeature` instances from `queryRenderedFeatures`, whose `geometry` is a lazy PROTOTYPE getter — and Playwright's evaluate serialization copies only own enumerable properties (verified empirically), so every feature arrived in test context WITHOUT geometry. Run #69 timed out on the strict length guard before touching it, run #70 threw `TypeError: Cannot read properties of undefined (reading 'coordinates')`, run #71's defensive filter found nothing and timed out. The helper now maps each feature to a plain object inside page.evaluate so the getter is evaluated in-page; the endpoint-matching predicate keeps its degenerate-segment filter as belt-and-braces — no app changes
|
||||
|
||||
## v0.21.0 — 2026-09-19 21:01
|
||||
- **Relocate panel moves to the left pane (ISS-023).** Flying an empty/grounded plane to another airport is "anything with our plane", so it belongs in the left pane, not as a market row on the right. The `.market-row.market-row-relocate` JSX (`relocate-plane` select of grounded planes labeled `{planeName} — {icao}`, `relocate-dest` name-sorted select, `relocate-go` button → `POST /api/planes/{id}/fly {destIcao}`) moved verbatim from `components/RightPane.tsx` into a new "Relocate" `<section>` in `components/LeftPane.tsx`, inserted between On board and Time. Its state (`relocatePlaneId` / `relocateDestIcao`) and the one-time `/api/airports` fetch (promise-ref pattern, GeoJSON → `{name, icao}[]` sorted by name) moved with it — the relocate-dest select was that fetch's only consumer in RightPane, so nothing else there changed. Busy gating rewired from RightPane's `busy` to LeftPane's own `useGameAction` instance (`actionsBusy`); a grounded-plane filter was added next to the existing `onboard` compute; plane labels reuse the expression already inlined in the Fleet rows. Testids kept byte-identical (`relocate-plane` / `relocate-dest` / `relocate-go`) and the row keeps its `.market-row market-row-relocate` classes (global CSS, works in the 360 px left pane); stale "280 px right pane" comment updated in `app/globals.css`. The map-popup relocation controls (`airport-popup-*`, Map.tsx) are a separate surface fed by the snapshot only — untouched
|
||||
- Tests: e2e — only `relocation.spec.ts` touches these testids and all locators are global, so no locator changes; the first test's title (which mentioned "right pane") and the file header comments now say left-pane Relocate section. No unit-test changes (baseline 283)
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.20.0 — 2026-09-19 19:21
|
||||
- **On board moved to the left pane (ISS-021).** The "On board" section (per-plane blocks with loaded/expired cargo rows, Refuel-for-leg / Fly-to / Abandon + penalty preview) now renders in `components/LeftPane.tsx` between Fleet and Time — wallet stays on top. The JSX moved verbatim (same testids: `onboard-{planeId}`, `onboard-package-{pkg.id}`, `refuel-for-*`, `fly-to-*`, `abandon-*` + penalty preview), along with the `onboard` computation (`planes.filter(flying || slotsUsedFor > 0)`) and per-plane cargo filter. All onboard e2e locators are global testids, so existing specs work unchanged
|
||||
- **Left pane widened: grid swapped to 360/1fr/280.** `.app-shell` in `app/globals.css` goes from `280px minmax(0, 1fr) 360px` to `360px minmax(0, 1fr) 280px` — total fixed width stays 640 px, so the map column is pixel-identical (map.spec.ts clicks via dynamic `map.project()`). Stale comments updated (on-board blocks now in the left pane; Relocate row comment reflects the 280 px right pane)
|
||||
- **Shared action runner hook.** RightPane's local `runAction` (busy gate, inline pane error + shell toast on failure, full post-action snapshot pushed via `applySnapshot`) extracted to new `lib/useGameAction.ts`: `useGameAction(state, applySnapshot, onError) → { runAction, busy, actionError }`, exact semantics kept incl. the non-2xx throw/catch and inline-error auto-clear on the next snapshot. Used in BOTH panes; LeftPane receives `applySnapshot` from the shell (`app/page.tsx`). RightPane keeps `[data-testid="right-error"]`; LeftPane gains a matching `[data-testid="left-action-error"]`. Pure helpers `slotsUsedFor` / `loadEligiblePlanes` stay exported from RightPane (unit tests import them there; LeftPane imports `slotsUsedFor` from it); the Market Relocate row + `/api/airports` fetch stay in RightPane
|
||||
- Tests: e2e — `panes.spec.ts` first test now also asserts the "On board" heading is visible inside `[data-testid="left-pane"]` and absent from the right pane; stale header comments updated in `actions.spec.ts` / `right-pane.spec.ts`. No unit-test changes (baseline 283)
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||
- **On-board cargo rows are two lines (ISS-028).** Each `onboard-package-*` row now stacks a full-width "Fly to <airport>" button on its own line above Refuel + Abandon side by side: `components/LeftPane.tsx` moves the fly-to button out of `.contract-main` into the row root and wraps refuel-for + abandon in a new `.onboard-actions` div — all testids, label text, penalty preview and disabled states unchanged. Long destination names in the fly-to label truncate with an ellipsis instead of overflowing: the label's inner span gets `min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap`, full name preserved via a `title` attribute (CSS in `app/globals.css`: `.onboard-block .contract-row` becomes flex-column, new `.onboard-fly-btn` / `.onboard-fly-label` / `.onboard-actions`). No e2e changes — specs locate everything by testid and assert no layout or button order; no version bump (part 2 of v0.20.0)
|
||||
|
||||
## v0.19.2 — 2026-09-19 20:06
|
||||
- **AGENTS.md "Change process" item 1** — connected issues/tasks that reference the same part of code may now be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel)
|
||||
- **AGENTS.md "E2E tests" section rewritten to match current reality** — e2e runs ONLY in CI, against an isolated docker stack inside dind (`docker-compose.ci.yml`); there are NO local e2e runs at all (local verification = `tsc --noEmit` + `npx vitest run` + `npx playwright test --list`; the full suite is verified by CI on every PR). Dropped the stale local-run instructions (deploying to the Traefik-routed instance before testing, driving browsers through the remote Playwright server at 192.168.1.4:3000); kept and reworded the CI env vars that actually exist in `playwright.config.ts` (`E2E_BASE_URL`, `E2E_DEPLOY_CMD`, `PW_REMOTE_BROWSER=0`, `E2E_COMPOSE_ARGS`)
|
||||
|
||||
## v0.19.1 — 2026-09-19 18:48
|
||||
- AGENTS.md: document that CI-green is enforced on master by branch protection (required status check) and that merges use auto-merge (`merge_when_checks_succeed`) so PRs merge automatically once CI passes
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# ORCHESTRATOR.md — Operating Manual for Successor Agents
|
||||
|
||||
You are taking over the autonomous development loop on **Flight-Ops** (browser game: run an airplane transport company in Europe; server-authoritative sim, MapLibre GL JS map). This document captures operational knowledge that is NOT written down in AGENTS.md. Read AGENTS.md first — it defines the mandatory change process and this file complements it.
|
||||
|
||||
Credentials are deliberately NOT stored in this file — see §1 for where they live. Never paste token values into any tracked file.
|
||||
|
||||
## 1. Project identity
|
||||
- Repo: Gitea at https://git.kkhost.pl → org **OpenCode**, repo **Flight-Ops** (full name `OpenCode/Flight-Ops`). Every Gitea API/MCP call uses owner=`OpenCode`, repo=`Flight-Ops`.
|
||||
- Local workdir + prod deploy dir: `/home/krzyw/projects/sandbox/flight` (git checkout; `docker compose up -d --build` deploys from here).
|
||||
- Prod URL: https://flight.dev.kkhost.pl (Traefik → docker-compose stack on this host). `GET /api/version` reports the running version.
|
||||
- Gitea API access for git.kkhost.pl: prefer the gitea MCP tools — they are already configured with a token. For raw REST/curl, read the current token from the local .env file at repo root (variable `GITEA_TOKEN`; .env is gitignored and must never be committed): `source .env && curl -s -H "Authorization: token $GITEA_TOKEN" https://git.kkhost.pl/api/v1/user`. (Incident note, Sept 2026: an early draft of this doc committed a live token to the repo; that commit was purged from all refs and the token has since been rotated — never repeat this.)
|
||||
- Current user: kamilkrzywda (id 1).
|
||||
|
||||
## 2. The loop (per issue)
|
||||
1. Small incremental change on a feature branch off `master`; connected issues may share one branch/PR with a single version bump.
|
||||
2. Bump `package.json` version + add CHANGELOG.md entry at top: `## v<version> — YYYY-MM-DD HH:MM` then bullet points of what changed (docs-only changes get patch bumps too — precedent v0.19.1/v0.19.2).
|
||||
3. Local verification ONLY (there are NO local e2e runs): `npx tsc --noEmit`, `npx vitest run` (the whole unit suite must pass — the test count grows over time, so compare against the previous green run, never a hardcoded number), `npx playwright test --list` (all specs compile and list).
|
||||
4. Push → CI (~7 min) → **auto-merge on green** (PRs have auto-merge configured; no manual merge needed — verify via `GET /pulls/{n}` that state=closed and merged_at is set). Note: if a PR was created via API rather than create-on-push, double-check auto-merge actually fires.
|
||||
5. Tag the version on master: `git tag v<version> origin/master && git push origin v<version>` (after `git fetch origin master`).
|
||||
6. Deploy prod in a PTY (long task): `cd /home/krzyw/projects/sandbox/flight && git checkout master && git reset --hard origin/master && docker compose up -d --build`; then verify `curl https://flight.dev.kkhost.pl/api/version` returns the new version and the root page is HTTP 200.
|
||||
7. Close each issue with a comment: what changed, version, PR number, merge commit SHA, deployed URL.
|
||||
8. Repeat for the next open issue: `GET /issues?state=open&type=issues` — note Gitea lists pull requests in this endpoint too; filter out entries with a `pull_request` key.
|
||||
|
||||
## 3. Gitea API + MCP quirks (learned the hard way)
|
||||
- The gitea MCP tools work for issues/PRs/files/tags, and Actions endpoints work IF you pass owner=`OpenCode`, repo=`Flight-Ops`. A wrong owner/repo makes EVERY call return `{"message":"not found","url":"https://git.kkhost.pl/api/swagger"}` — that swagger URL inside a 404 is the signature of "wrong path", not "Gitea is down".
|
||||
- MCP merge endpoint 405s → don't bother; auto-merge handles merging. Manual fallback if ever needed: `POST /repos/OpenCode/Flight-Ops/pulls/{n}/merge` with body `{"do":"merge","merge_style":"merge"}`.
|
||||
- Gitea REST shapes (NOT GitHub's): list runs → `{workflow_runs:[...]}`; run jobs → `/actions/runs/{id}/jobs` returns `{"jobs":[...]}`; single job log via MCP `get_job_log_preview` (param tail_lines) or `download_job_log` to a file, then grep.
|
||||
- Failure anatomy in CI logs: the Playwright summary at the end lists "N failed" + test titles; each failure block has a code frame with line numbers plus an "Error Context:" path. The e2e step is the only one that can fail flakily; unit failures are real regressions.
|
||||
- CI watcher pattern that works: `run_background_process` (notify=true) running a loop that polls `GET /actions/runs/{id}` every 60 s and exits when status=completed, printing status+conclusion each tick. Don't poll in the foreground; don't sleep-loop on pty_read.
|
||||
|
||||
## 4. CI facts (.gitea/workflows/ci.yml + docker-compose.ci.yml)
|
||||
- Single job "build + unit + e2e" on runner gitea-runner (docker-in-docker). Fresh DB per run (volume removed); compose project `flight-ci`; app container on a static IP → `E2E_BASE_URL=http://172.39.0.10:3000`; `PW_REMOTE_BROWSER=0` (CI runs local chromium — the shared remote browser server at 192.168.1.4 cannot reach a stack inside dind); `E2E_COMPOSE_ARGS="-f docker-compose.ci.yml -p flight-ci"` is read by e2e/state.spec.ts for its mid-run `docker compose restart flight`.
|
||||
- Flaky uplink → retry loops in ci.yml; an occasional "flaky" test (failed once, passed on retry) does NOT fail the run.
|
||||
- Branch protection requires status check `CI / build + unit + e2e (pull request)` — PRs cannot merge until green; CI never deploys to production.
|
||||
|
||||
## 5. E2E conventions (e2e/*.spec.ts) — read before touching tests
|
||||
- Sim scale in tests: SCALE=1000; hub `HUB='EDDF'` (Frankfurt); typical destination LEMD.
|
||||
- `flyHomeViaApi(page)` self-heal at test start — interrupted runs can leave planes mid-flight; landing waits up to 240 s.
|
||||
- Pause-sim pattern for deterministic marker clicks: pause, act, assert, resume.
|
||||
- Dev hook: `window.__flightMap` exposes the live MapLibre map instance in dev builds (also `__flightLastSnapshot`).
|
||||
- `queryRenderedFeatures` is viewport-scoped → fitBounds/fitToAirports before asserting on far features; give the renderer ~300 ms after a camera jump.
|
||||
- **expect.poll callbacks must be total** — a throw inside fails the test instantly instead of retrying. Guard/filter everything you dereference.
|
||||
|
||||
## 6. ⚠️ The big one: Playwright evaluate serialization drops prototype getters
|
||||
MapLibre's `queryRenderedFeatures` returns live `GeoJSONFeature` class instances whose `geometry` is a **lazy PROTOTYPE getter** (own properties are only type/properties/id/source/state plus private fields). Playwright serializes evaluate results by copying **own enumerable properties only**, so every feature arriving in test context has NO geometry — silently.
|
||||
- Verified empirically: `page.evaluate(() => { class A{constructor(){this.own=1} get geo(){return 42}} return [new A()] })` → `[{"own":1}]`.
|
||||
- Symptom matrix (how it masqueraded as "the line isn't drawn" while the trace rendered fine on screen, across three consecutive failed CI runs in Sept 2026): strict length guard → timeout; direct `.geometry.coordinates` access → `TypeError: Cannot read properties of undefined (reading 'coordinates')`; defensive filter → clean 15 s timeout.
|
||||
- **Rule: never return maplibre feature instances across page.evaluate — always map to plain objects in-page** (`{type, id, properties, geometry: f.geometry}` forces the getter to evaluate). Canonical pattern: `renderedFeatures()` in e2e/hover.spec.ts. Other specs that touch `.geometry` do so inside evaluate (safe) or only read array length (safe).
|
||||
|
||||
## 7. MapLibre rendering facts (for map assertions)
|
||||
- GeoJSON geometry is stored per-tile in INTEGER grids; long lines are clipped → `queryRenderedFeatures` returns ONE FEATURE PER TILE the line crosses (the EDDF→LEMD leg ≈ 4–5 segments at z=4/5).
|
||||
- Coordinates are quantized to the grid: error up to ~half a grid step (~0.001° observed at z≥4, worst ~0.02° at z=0 with extent 8192). Endpoint assertions must use an EPS sized for this (the hover tests define one in `expectHoverRoute` in e2e/hover.spec.ts — ~5 km: above worst-case quantization at any zoom, below the distance between any two EU airports) and check endpoints ACROSS ALL SEGMENTS: some segment must START within EPS of origin AND some must END within EPS of destination. Never strict equality on a single feature.
|
||||
- The true line endpoints survive clipping verbatim in whichever tile contains them.
|
||||
|
||||
## 8. App architecture quick map
|
||||
- `components/Map.tsx` — the MapLibre layer: sources/layers created in ensureLayers (dedicated `hover-routes` GeoJSON source + top-most dashed `hover-route` LineLayer, plus an `airports-target-highlight` ring layer added last so it sits above the line at its endpoint — current colors/widths live in Map.tsx, don't trust this doc for exact paint values); applyHoverRef re-pushes data on every hover; `window.__flightMap` dev hook.
|
||||
- `lib/mapData.ts` — pure GeoJSON builders (`hoverRouteGeoJson`, `routesGeoJson`, `greatCircleArc` slerp) + unit tests in lib/mapData.test.ts.
|
||||
- Hover protocol: panes report a HoverTarget via mouseenter/leave (`components/hoverTypes.ts`): `{kind:'plane';id} | {kind:'package';originIcao;destIcao;planeId?} | {kind:'route';fromIcao;toIcao}`; the `''` sentinel means no hover.
|
||||
- Server: sim ticks server-side, client polls /api/state; OpenAPI spec generated from lib/openapi.ts and served at /api/openapi — update it whenever an endpoint changes.
|
||||
|
||||
## 9. Finding current state (this file keeps no snapshots)
|
||||
This manual is meant to stay valid long-term, so it deliberately contains NO version or issue snapshots — they rot. To orient yourself when you take over: `git log --oneline -10` + CHANGELOG.md for what has shipped; `GET /issues?state=open&type=issues` (filter out entries with a `pull_request` key) for what is left to do; PLAN.md's "Later" section for the roadmap backlog.
|
||||
|
||||
## 10. Standing user instruction & etiquette
|
||||
- The user's standing order for this project: work through the issue list autonomously — implement → PR → CI green → merge → tag → deploy prod → close with comment → next — until told to stop.
|
||||
- Small incremental changes; each part fully tested (unit + e2e) before moving on.
|
||||
- Long terminal tasks → pty_* tools (deploys, builds). Background watchers → run_background_process with notify=true.
|
||||
- Never push directly to master; never deploy from a feature branch; CI never touches prod — production deploys are manual only (`docker compose up -d --build` after tagging).
|
||||
- **Never commit credentials.** Tokens/secrets live in the MCP server config or with the user, never in tracked files (see incident note in §1).
|
||||
@@ -0,0 +1,34 @@
|
||||
import { cancelQueuedLeg, performAction } from '@/lib/game/actions';
|
||||
|
||||
// POST /api/planes/:planeId/queue/cancel (v0.25.0, ISS-043) — body { index: number }.
|
||||
// Removes a NOT-yet-started leg from the plane's queue by index; only queued legs
|
||||
// are cancellable, the active in-flight leg is never affected. 400 missing/
|
||||
// non-integer index, unknown fields, or an index outside [0, queue.length); 404
|
||||
// unknown plane id. On success returns the full state snapshot (plane.queue updated).
|
||||
|
||||
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||
const { planeId } = await ctx.params;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const text = await req.text();
|
||||
body = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
||||
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
||||
}
|
||||
const input = body as Record<string, unknown>;
|
||||
for (const key of Object.keys(input)) {
|
||||
if (key !== 'index') {
|
||||
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||
}
|
||||
}
|
||||
if (!Number.isInteger(input.index)) {
|
||||
return Response.json({ error: 'index must be an integer' }, { status: 400 });
|
||||
}
|
||||
|
||||
const index = input.index as number;
|
||||
return performAction((inst) => cancelQueuedLeg(inst, planeId, index));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { performAction, queueLeg } from '@/lib/game/actions';
|
||||
|
||||
// POST /api/planes/:planeId/queue (v0.25.0, ISS-043) — body { destIcao: string }.
|
||||
// Appends a NOT-yet-started leg to the plane's flight queue; works whether the
|
||||
// plane is grounded or flying (pre-building a route). Nothing auto-starts here —
|
||||
// queued legs chain on landing when fuel covers them. 400 missing/non-string
|
||||
// destIcao, unknown fields, or an ICAO not in the airport dataset; 404 unknown
|
||||
// plane id. On success returns the full state snapshot (plane.queue updated).
|
||||
|
||||
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||
const { planeId } = await ctx.params;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const text = await req.text();
|
||||
body = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
||||
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
||||
}
|
||||
const input = body as Record<string, unknown>;
|
||||
for (const key of Object.keys(input)) {
|
||||
if (key !== 'destIcao') {
|
||||
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||
}
|
||||
}
|
||||
if (typeof input.destIcao !== 'string' || input.destIcao.length === 0) {
|
||||
return Response.json({ error: 'destIcao must be a non-empty string' }, { status: 400 });
|
||||
}
|
||||
|
||||
const destIcao = input.destIcao;
|
||||
return performAction((inst) => queueLeg(inst, planeId, destIcao));
|
||||
}
|
||||
+34
-5
@@ -102,10 +102,12 @@ body {
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market */
|
||||
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market.
|
||||
ISS-021 (v0.20.0): left widened to 360px (it now carries the On board section), right
|
||||
narrowed to 280px — total fixed width stays 640px, so the map column is unchanged. */
|
||||
.app-shell {
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr) 360px;
|
||||
grid-template-columns: 360px minmax(0, 1fr) 280px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
@@ -362,7 +364,7 @@ body {
|
||||
}
|
||||
|
||||
/* ISS-010 (v0.18.0) — the Relocate row carries TWO selects, so let it wrap instead of
|
||||
squeezing both below their readable width in the 360 px pane. */
|
||||
squeezing both below their readable width in the 360 px left pane (moved there in ISS-023 v0.21.0). */
|
||||
.market-row-relocate {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
@@ -374,7 +376,7 @@ body {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* v0.12.0 — on-board blocks (per plane) in the right pane */
|
||||
/* v0.12.0 — on-board blocks (per plane); moved to the left pane in ISS-021 (v0.20.0) */
|
||||
.onboard-block {
|
||||
background: rgba(30, 41, 59, 0.6);
|
||||
border-radius: 6px;
|
||||
@@ -382,17 +384,44 @@ body {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
/* ISS-028 (v0.20.0 part 2) — on-board cargo rows are two lines: a full-width fly-to button,
|
||||
then refuel + abandon side by side below it; long destination names truncate with an ellipsis. */
|
||||
.onboard-block .contract-row {
|
||||
background: transparent;
|
||||
padding: 6px 0 0;
|
||||
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.onboard-block .contract-row .contract-sub {
|
||||
margin-top: 0; /* row spacing comes from the container's gap */
|
||||
}
|
||||
|
||||
.onboard-fly-btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.onboard-fly-label {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.onboard-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* v0.17.0 — ISS-008: bottom-right toast stack (action errors + game events) */
|
||||
.toasts {
|
||||
position: fixed;
|
||||
bottom: 12px;
|
||||
right: 12px;
|
||||
/* 280px right pane + 12px inset — sits flush against the map's right edge, clear of the right pane */
|
||||
right: 292px;
|
||||
z-index: 50; /* above map popups/controls and the app header */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
+3
-1
@@ -43,7 +43,9 @@ export default function Home() {
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} onError={onError} />
|
||||
{/* ISS-021 (v0.20.0) — applySnapshot also reaches the left pane: its On board section's
|
||||
refuel/fly/abandon actions push their response snapshot into the shared state */}
|
||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
||||
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
||||
action response into the shared state, exactly like RightPane does */}
|
||||
|
||||
+276
-2
@@ -1,11 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import type { GeoJsonFeatureCollection } from '@/lib/airports';
|
||||
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
||||
import { abandonPenalty } from '@/lib/game/penalty';
|
||||
import { formatCash, formatDeadlineRelative, formatFuel, formatSimClock } from '@/lib/format';
|
||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||
import { useGameAction } from '@/lib/useGameAction';
|
||||
import { useSimClock } from '@/lib/useSimClock';
|
||||
import { slotsUsedFor } from './RightPane';
|
||||
import type { HoverTarget } from './hoverTypes';
|
||||
|
||||
interface LeftPaneProps {
|
||||
@@ -14,6 +18,9 @@ interface LeftPaneProps {
|
||||
error: string | null;
|
||||
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
|
||||
onRefresh: () => void;
|
||||
// ISS-021 (v0.20.0): push the full snapshot returned by an action endpoint into the shared shell
|
||||
// state — needed now that the On board section's refuel/fly/abandon actions live in this pane.
|
||||
applySnapshot: (snapshot: StateSnapshot) => void;
|
||||
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
|
||||
onHover: (target: HoverTarget | null) => void;
|
||||
// ISS-008 (v0.17.0): report a failed sim-control POST to the shell as an error toast.
|
||||
@@ -83,9 +90,45 @@ export async function retrySimPost(
|
||||
return { ok: false, reason: 'exhausted', error: lastError };
|
||||
}
|
||||
|
||||
export default function LeftPane({ state, loading, error, onRefresh, onHover, onError }: LeftPaneProps) {
|
||||
export default function LeftPane({ state, loading, error, onRefresh, applySnapshot, onHover, onError }: LeftPaneProps) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
// ISS-021 (v0.20.0): shared action runner for the On board section (moved here from RightPane).
|
||||
const { runAction, busy: actionsBusy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||
|
||||
// ISS-023 (v0.21.0): Relocate selections — moved here from the right-pane market row; same
|
||||
// "effective selection" pattern as there: the user's pick while it stays valid, else a sensible
|
||||
// default (first grounded plane / first airport).
|
||||
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
|
||||
const [relocateDestIcao, setRelocateDestIcao] = useState<string | null>(null);
|
||||
|
||||
// ISS-035 (v0.23.0): Refuel-to-full selection — moved here from the right-pane market row; same
|
||||
// "effective selection" pattern as Relocate above: the user's pick while it stays refuelable, else
|
||||
// a sensible default (first grounded plane with fuel below max).
|
||||
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
|
||||
|
||||
// ISS-010 (v0.18.0): one-time /api/airports fetch per page life — destination options for the
|
||||
// Relocate section, sorted by name so e2e selection is stable. Same promise-ref pattern as Map.tsx;
|
||||
// on failure airportOptions stays null and the Relocate button simply remains disabled. Moved here
|
||||
// from RightPane in ISS-023 (v0.21.0) — the relocate-dest select was its only consumer there.
|
||||
const [airportOptions, setAirportOptions] = useState<Array<{ name: string; icao: string }> | null>(null);
|
||||
const airportsPromiseRef = useRef<Promise<Array<{ name: string; icao: string }>> | null>(null);
|
||||
useEffect(() => {
|
||||
if (!airportsPromiseRef.current) {
|
||||
airportsPromiseRef.current = fetch('/api/airports', { cache: 'no-store' })
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
|
||||
return res.json() as Promise<GeoJsonFeatureCollection>;
|
||||
})
|
||||
.then((fc) =>
|
||||
fc.features
|
||||
.map((f) => ({ name: f.properties.name, icao: f.properties.icao }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'en')),
|
||||
);
|
||||
}
|
||||
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// POST /api/sim (retried up to SIM_POST_MAX_ATTEMPTS× on failure — CI runs #44/#47), then
|
||||
// refetch the full snapshot immediately so the pane reflects the new controls without waiting
|
||||
// for the next poll tick. After the final attempt fails keep the stale UI and surface an error
|
||||
@@ -153,6 +196,30 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
||||
const paused = state?.simState.paused ?? false;
|
||||
const timeScale = state?.simState.timeScale ?? 1;
|
||||
|
||||
// On board (v0.12.0, moved from the right pane in ISS-021 v0.20.0): every plane that carries
|
||||
// cargo or is mid-flight gets a block — its loaded/expired packages with fly-to-destination +
|
||||
// abandon controls, and flying planes show their current leg.
|
||||
const clockMs = state?.simState.clockMs ?? 0;
|
||||
const onboard = state ? state.planes.filter((p) => p.status === 'flying' || slotsUsedFor(state, p.id) > 0) : [];
|
||||
|
||||
// ISS-023 (v0.21.0): Relocate — any GROUNDED plane can be repositioned to any airport via the
|
||||
// existing fly endpoint (pure repositioning, no package needed since v0.12.0). Moved here from
|
||||
// the right-pane market row; with state null both fall back to null and the section isn't rendered.
|
||||
const grounded = state ? state.planes.filter((p) => p.status === 'available') : [];
|
||||
const relocatePlane = grounded.find((p) => p.id === relocatePlaneId) ?? grounded[0] ?? null;
|
||||
const relocateDest =
|
||||
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
|
||||
|
||||
// ISS-035 (v0.23.0): Refuel-to-full — any GROUNDED plane with fuel below max can be topped up via the
|
||||
// existing refuel endpoint (no body → server defaults to mode 'full'). Moved here from the right-pane
|
||||
// market row; reuses `grounded` above, and with state null falls back to null.
|
||||
const refuelable = grounded.filter((p) => p.fuel < p.maxFuel);
|
||||
const refuelPlane =
|
||||
(state?.planes.find((p) => p.id === refuelPlaneId && p.status === 'available' && p.fuel < p.maxFuel)) ??
|
||||
refuelable[0] ??
|
||||
null;
|
||||
const refuelCost = refuelPlane && state ? (refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL : null;
|
||||
|
||||
// Slider commit (v0.9.1): the displayed value follows the drag optimistically via
|
||||
// pendingScale; POST /api/sim fires after a 250 ms debounce, or immediately when the
|
||||
// user releases the slider (browsers fire a native 'change' on release). The server's
|
||||
@@ -294,6 +361,211 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* ISS-021 (v0.20.0): moved here from the right pane — between Fleet and Time. */}
|
||||
<section className="pane-section">
|
||||
<h3 className="pane-heading">On board</h3>
|
||||
{onboard.length === 0 ? (
|
||||
<p className="pane-muted">Nothing on board.</p>
|
||||
) : (
|
||||
onboard.map((plane) => {
|
||||
const cargo = state.packages.filter(
|
||||
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
||||
);
|
||||
return (
|
||||
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
||||
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
||||
// child, so this covers the whole block without flicker between sub-elements.
|
||||
<div
|
||||
key={plane.id}
|
||||
data-testid={`onboard-${plane.id}`}
|
||||
className="onboard-block"
|
||||
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
||||
onMouseLeave={() => onHover(null)}
|
||||
>
|
||||
<div className="contract-main">
|
||||
<span className="plane-model">{PLANE_TYPES[plane.model]?.name ?? plane.model}</span>
|
||||
{plane.status === 'flying' ? (
|
||||
<>
|
||||
<span className="plane-status status-flying">in flight</span>
|
||||
{plane.destName && (
|
||||
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
||||
{plane.locationName} → {plane.destName}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="plane-status status-available">{plane.locationIcao}</span>
|
||||
)}
|
||||
</div>
|
||||
{cargo.map((pkg) => {
|
||||
const penalty = abandonPenalty(pkg, clockMs);
|
||||
return (
|
||||
// ISS-025 (v0.22.0): hovering a loaded package draws its full origin→dest trace on the map —
|
||||
// same as job-list rows — and keeps this plane's halo lit via planeId. Leaving the row restores
|
||||
// the block's plain plane highlight; leaving the whole block still ends at null (the child's
|
||||
// mouseleave fires before the parent's).
|
||||
<div
|
||||
key={pkg.id}
|
||||
data-testid={`onboard-package-${pkg.id}`}
|
||||
className="contract-row"
|
||||
onMouseEnter={() => onHover({ kind: 'package', originIcao: pkg.originIcao, destIcao: pkg.destIcao, planeId: plane.id })}
|
||||
onMouseLeave={() => onHover({ kind: 'plane', id: plane.id })}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`fly-to-${pkg.id}`}
|
||||
className="pane-btn onboard-fly-btn"
|
||||
disabled={actionsBusy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
||||
>
|
||||
<span className="onboard-fly-label" title={`Fly to ${pkg.destName}`}>
|
||||
Fly to {pkg.destName}
|
||||
</span>
|
||||
</button>
|
||||
<div className="onboard-actions">
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`refuel-for-${pkg.id}`}
|
||||
className="pane-btn"
|
||||
disabled={actionsBusy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/planes/${plane.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
||||
>
|
||||
Refuel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`abandon-${pkg.id}`}
|
||||
className="pane-btn"
|
||||
disabled={actionsBusy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
||||
>
|
||||
Abandon{' '}
|
||||
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="contract-sub">
|
||||
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||
<span>{formatCash(pkg.reward)}</span>
|
||||
{pkg.status === 'expired' ? (
|
||||
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
||||
) : (
|
||||
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* ISS-023 (v0.21.0): moved here from the right-pane market row — it belongs with
|
||||
everything else about our planes, between On board and Time. */}
|
||||
{/* ISS-027 (v0.22.0): hovering the section previews the planned relocation on the map —
|
||||
dashed trace from the selected plane's airport to the destination + a ring on the target.
|
||||
With no grounded plane or no loaded airport options there is nothing to preview → null. */}
|
||||
<section
|
||||
className="pane-section"
|
||||
data-testid="relocate-section"
|
||||
onMouseEnter={() =>
|
||||
onHover(
|
||||
relocatePlane && relocateDest
|
||||
? { kind: 'route', fromIcao: relocatePlane.locationIcao, toIcao: relocateDest.icao }
|
||||
: null,
|
||||
)
|
||||
}
|
||||
onMouseLeave={() => onHover(null)}
|
||||
>
|
||||
<h3 className="pane-heading">Relocate</h3>
|
||||
{/* ISS-010 (v0.18.0): relocate a grounded plane — the fly endpoint already allows pure
|
||||
repositioning, this row just exposes it for planes with nothing on board. */}
|
||||
<div className="market-row market-row-relocate">
|
||||
<select
|
||||
data-testid="relocate-plane"
|
||||
aria-label="Plane to relocate"
|
||||
value={relocatePlane?.id ?? ''}
|
||||
onChange={(e) => setRelocatePlaneId(e.target.value || null)}
|
||||
>
|
||||
{grounded.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{PLANE_TYPES[p.model]?.name ?? p.model} — {p.locationIcao}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
data-testid="relocate-dest"
|
||||
aria-label="Relocation destination airport"
|
||||
value={relocateDest?.icao ?? ''}
|
||||
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
|
||||
>
|
||||
{airportOptions?.map((a) => (
|
||||
<option key={a.icao} value={a.icao}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="relocate-go"
|
||||
className="pane-btn"
|
||||
disabled={actionsBusy || relocatePlane === null || relocateDest === null}
|
||||
onClick={() => {
|
||||
if (relocatePlane && relocateDest) {
|
||||
void runAction(`/api/planes/${relocatePlane.id}/fly`, { destIcao: relocateDest.icao });
|
||||
}
|
||||
}}
|
||||
>
|
||||
Relocate
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ISS-035 (v0.23.0): moved here from the right-pane market row — it belongs with everything else
|
||||
about our planes, next to Relocate. Plain section: no hover handlers (refuel is not a route). */}
|
||||
<section className="pane-section" data-testid="refuel-section">
|
||||
<h3 className="pane-heading">Refuel</h3>
|
||||
{/* Moved verbatim from the right-pane Market section — same testids/labels; the per-package
|
||||
"Refuel" button in On board (mode 'forFlight') is a different feature and stays there. */}
|
||||
<div className="market-row">
|
||||
{refuelable.length === 0 ? (
|
||||
<span data-testid="market-refuel-none" className="pane-muted">
|
||||
All tanks full.
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<select
|
||||
data-testid="market-refuel-plane"
|
||||
aria-label="Plane to refuel"
|
||||
value={refuelPlane?.id ?? ''}
|
||||
onChange={(e) => setRefuelPlaneId(e.target.value || null)}
|
||||
>
|
||||
{refuelable.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{PLANE_TYPES[p.model]?.name ?? p.model} — {Math.round(p.fuel)} / {p.maxFuel} L
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span data-testid="market-refuel-cost" className="market-preview">
|
||||
{refuelCost !== null ? formatCash(refuelCost) : ''}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-testid="market-refuel"
|
||||
className="pane-btn"
|
||||
disabled={actionsBusy || refuelPlane === null}
|
||||
onClick={() => {
|
||||
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
||||
}}
|
||||
>
|
||||
Refuel to full
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="pane-section">
|
||||
<h3 className="pane-heading">Time</h3>
|
||||
<p data-testid="sim-clock" className="sim-clock">
|
||||
@@ -347,6 +619,8 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{/* ISS-021 (v0.20.0): inline error from a failed On board action — mirrors right-error. */}
|
||||
{actionError && <p data-testid="left-action-error" className="pane-error">{actionError}</p>}
|
||||
</>
|
||||
) : null}
|
||||
</aside>
|
||||
|
||||
+88
-6
@@ -8,7 +8,7 @@ import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvai
|
||||
import type { GeoJsonFeatureCollection } from '../lib/airports';
|
||||
import type { StateSnapshot } from '../lib/game/state';
|
||||
import type { HoverTarget } from './hoverTypes';
|
||||
import { planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
||||
import { hoverRouteGeoJson, hoverTraceGeoJson, planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
||||
import { weatherFor } from '../lib/weather';
|
||||
import { approxLocalTime } from '../lib/localTime';
|
||||
|
||||
@@ -33,6 +33,15 @@ const ROUTES_LEGS_LAYER_ID = 'routes-legs';
|
||||
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
|
||||
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
|
||||
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-highlight';
|
||||
// ISS-022/025/027 (v0.22.0): the hover route trace — its OWN source + top-most dashed line,
|
||||
// because the shared `routes` source only holds FLYING legs: an open package's or a grounded
|
||||
// relocation's planned route is never in it. applyHoverRef pushes data into it on every hover.
|
||||
const HOVER_ROUTES_SOURCE_ID = 'hover-routes';
|
||||
const HOVER_ROUTE_LAYER_ID = 'hover-route';
|
||||
// ISS-022 (v0.22.0): the DESTINATION airport's ring — a second, differently-colored circle over
|
||||
// the same `airports` source so the target stands out from the origin's plain yellow ring.
|
||||
// applyHoverRef filters it to the hovered target's destination icao only.
|
||||
const AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID = 'airports-target-highlight';
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
@@ -43,7 +52,8 @@ interface MapProps {
|
||||
// route lines. Null until the first successful poll.
|
||||
state?: StateSnapshot | null;
|
||||
// ISS-002 (v0.15.0): the side panels' hover target — highlights the matching plane
|
||||
// (+ its route leg if flying) or a package's endpoint airports. Null = nothing hovered.
|
||||
// (+ its route leg if flying) or a package's endpoint airports, and (ISS-022/025/027 v0.22.0)
|
||||
// draws the full great-circle trace between any hovered target's two endpoints. Null = nothing hovered.
|
||||
hovered?: HoverTarget | null;
|
||||
// ISS-010 (v0.18.0): push an action endpoint's full response snapshot into the shared
|
||||
// shell state — same callback RightPane receives, used by the airport popup's Relocate row.
|
||||
@@ -90,6 +100,9 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
||||
useEffect(() => {
|
||||
stateRef.current = state ?? null;
|
||||
applyDynamicRef.current();
|
||||
// ISS-040 (v0.23.2): re-apply the hover too, so an on-board package's trace follows a moving
|
||||
// carrier between polls while hovered — idempotent and cheap (one small setData + ring filters).
|
||||
applyHoverRef.current();
|
||||
}, [state]);
|
||||
|
||||
// ISS-002 (v0.15.0): hover highlight — same ref + effect pattern as the snapshot above.
|
||||
@@ -101,22 +114,56 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
const h = hoveredRef.current;
|
||||
// The empty-string sentinel matches nothing: no feature has id/icao ''.
|
||||
const planeId = h && h.kind === 'plane' ? h.id : '';
|
||||
// The empty-string sentinel matches nothing: no feature has id/icao ''. A package hover may
|
||||
// name its plane (ISS-025 on-board cargo rows), so that plane's halo stays lit too.
|
||||
let planeId = '';
|
||||
let fromIcao = '';
|
||||
let toIcao = '';
|
||||
if (h) {
|
||||
if (h.kind === 'plane') planeId = h.id;
|
||||
else if (h.kind === 'package') {
|
||||
planeId = h.planeId ?? '';
|
||||
fromIcao = h.originIcao;
|
||||
toIcao = h.destIcao;
|
||||
} else {
|
||||
// 'route' — the Relocate panel's planned flight: trace + target airport only.
|
||||
fromIcao = h.fromIcao;
|
||||
toIcao = h.toIcao;
|
||||
}
|
||||
}
|
||||
if (map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
||||
map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]);
|
||||
}
|
||||
if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
||||
map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]);
|
||||
}
|
||||
const originIcao = h && h.kind === 'package' ? h.originIcao : '';
|
||||
const destIcao = h && h.kind === 'package' ? h.destIcao : '';
|
||||
// ISS-022/025/027: the hover route trace — one great-circle line for any target carrying two
|
||||
// ICAOs (package origin→dest / relocate fromIcao→toIcao); empty when either endpoint is unknown.
|
||||
const hoverSource = map.getSource(HOVER_ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined;
|
||||
if (hoverSource) {
|
||||
// ISS-040 (v0.23.2): an on-board package's trace starts from the carrier plane's LIVE position,
|
||||
// not its origin airport — identical to before while grounded at the pickup, different once it
|
||||
// has departed with cargo still loaded. No carrier in state yet → fall back to the ICAO trace.
|
||||
const idx = airportsIndexRef.current ?? new Map();
|
||||
const carrier = h?.kind === 'package' && h.planeId ? stateRef.current?.planes.find((p) => p.id === h.planeId) : undefined;
|
||||
void hoverSource.setData(
|
||||
carrier ? hoverTraceGeoJson({ lat: carrier.lat, lon: carrier.lon }, toIcao, idx) : hoverRouteGeoJson(fromIcao, toIcao, idx),
|
||||
);
|
||||
}
|
||||
// Package hovers ring BOTH endpoints (v0.15.0 behavior); 'route' hovers ring the TARGET only —
|
||||
// the relocation's destination is what ISS-027 asks to see. Plane hovers ring nothing.
|
||||
const originIcao = h?.kind === 'package' ? fromIcao : '';
|
||||
const destIcao = h?.kind === 'package' || h?.kind === 'route' ? toIcao : '';
|
||||
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
||||
map.setFilter(
|
||||
AIRPORTS_HIGHLIGHT_LAYER_ID,
|
||||
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
|
||||
);
|
||||
}
|
||||
// ISS-022: the destination gets its own distinct-colored ring on top (package AND route hovers).
|
||||
if (map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
|
||||
map.setFilter(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID, ['==', ['get', 'icao'], destIcao]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -384,6 +431,41 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
|
||||
},
|
||||
});
|
||||
}
|
||||
// ISS-022/025/027 (v0.22.0): the hover route trace — added LAST so it sits above every
|
||||
// other layer, including the highlight rings at its endpoints. Own source: the shared
|
||||
// `routes` source only holds flying legs, never a planned one. Empty until a hover sets data.
|
||||
if (!map.getSource(HOVER_ROUTES_SOURCE_ID)) {
|
||||
map.addSource(HOVER_ROUTES_SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
}
|
||||
if (!map.getLayer(HOVER_ROUTE_LAYER_ID)) {
|
||||
map.addLayer({
|
||||
id: HOVER_ROUTE_LAYER_ID,
|
||||
type: 'line',
|
||||
source: HOVER_ROUTES_SOURCE_ID,
|
||||
paint: {
|
||||
'line-color': '#facc15', // matches the airports-highlight ring — one "trace" color
|
||||
'line-width': 4,
|
||||
'line-dasharray': [2, 2], // dashed = planned route, distinct from solid flying legs
|
||||
},
|
||||
});
|
||||
}
|
||||
// ISS-022 (v0.22.0): the destination's ring — same geometry as airports-highlight but a
|
||||
// DIFFERENT color so the target stands out over the origin's yellow ring; added last so it
|
||||
// also sits above the hover-route line at its endpoint. Starts filtered to match nothing.
|
||||
if (!map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
|
||||
map.addLayer({
|
||||
id: AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID,
|
||||
type: 'circle',
|
||||
source: AIRPORTS_SOURCE_ID,
|
||||
filter: ['==', ['get', 'icao'], ''],
|
||||
paint: {
|
||||
'circle-radius': 9, // same ring size as airports-highlight (r=5 base circles)
|
||||
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
||||
'circle-stroke-width': 3,
|
||||
'circle-stroke-color': '#4ade80', // green — distinct from the yellow endpoint rings
|
||||
},
|
||||
});
|
||||
}
|
||||
// Layer-scoped listeners survive setStyle (they filter by layer id at event
|
||||
// time), so off+on with the same reference re-wires without duplicating.
|
||||
map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
|
||||
|
||||
+12
-249
@@ -1,11 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { GeoJsonFeatureCollection } from '@/lib/airports';
|
||||
import { useState } from 'react';
|
||||
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { abandonPenalty } from '@/lib/game/penalty';
|
||||
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
||||
import { useGameAction } from '@/lib/useGameAction';
|
||||
import type { HoverTarget } from './hoverTypes';
|
||||
|
||||
interface RightPaneProps {
|
||||
@@ -109,75 +108,19 @@ function LoadControls({
|
||||
}
|
||||
|
||||
export default function RightPane({ state, loading, applySnapshot, onHover, onError }: RightPaneProps) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
||||
// snapshot prop changes every tick) or the next successful action.
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (state !== null) setActionError(null);
|
||||
}, [state]);
|
||||
// ISS-021 (v0.20.0): shared action runner — busy gate, inline pane error + shell toast on
|
||||
// failure, full post-action snapshot pushed into the shared state on success.
|
||||
const { runAction, busy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||
|
||||
// Market picker selections — same "effective selection" pattern as LoadControls: the
|
||||
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
|
||||
const [buyModelId, setBuyModelId] = useState<string | null>(null);
|
||||
const [sellPlaneId, setSellPlaneId] = useState<string | null>(null);
|
||||
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
|
||||
|
||||
// ISS-010 (v0.18.0): Relocate row selections — same "effective selection" pattern as the rows above:
|
||||
// the user's pick while it stays valid, else a sensible default (first grounded plane / first airport).
|
||||
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
|
||||
const [relocateDestIcao, setRelocateDestIcao] = useState<string | null>(null);
|
||||
|
||||
// ISS-010 (v0.18.0): one-time /api/airports fetch per page life — destination options for the
|
||||
// Relocate row, sorted by name so e2e selection is stable. Same promise-ref pattern as Map.tsx;
|
||||
// on failure airportOptions stays null and the Relocate button simply remains disabled.
|
||||
const [airportOptions, setAirportOptions] = useState<Array<{ name: string; icao: string }> | null>(null);
|
||||
const airportsPromiseRef = useRef<Promise<Array<{ name: string; icao: string }>> | null>(null);
|
||||
useEffect(() => {
|
||||
if (!airportsPromiseRef.current) {
|
||||
airportsPromiseRef.current = fetch('/api/airports', { cache: 'no-store' })
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
|
||||
return res.json() as Promise<GeoJsonFeatureCollection>;
|
||||
})
|
||||
.then((fc) =>
|
||||
fc.features
|
||||
.map((f) => ({ name: f.properties.name, icao: f.properties.icao }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'en')),
|
||||
);
|
||||
}
|
||||
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// POST an action endpoint. Every success returns the FULL post-action snapshot (v0.8.0
|
||||
// convention) — pushed into the shared state immediately; a 4xx {error} body becomes the
|
||||
// inline pane error and the stale UI stays until the next poll. Buttons are disabled while
|
||||
// a request is in flight, so at most one action runs at a time.
|
||||
const runAction = useCallback(
|
||||
async (path: string, body?: unknown) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
const data = (await res.json()) as StateSnapshot & { error?: string };
|
||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||
setActionError(null);
|
||||
applySnapshot(data);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setActionError(message); // inline pane error stays…
|
||||
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[applySnapshot, busy, onError],
|
||||
);
|
||||
// ISS-023 (v0.21.0): the Relocate row moved to the left pane — it belongs with everything else
|
||||
// about our planes, not in the market. Its state + /api/airports fetch went with it.
|
||||
// ISS-035 (v0.23.0): same for the Refuel-to-full row — its state + derived values moved to the
|
||||
// left pane's "Refuel" section next to Relocate.
|
||||
|
||||
if (loading && !state) {
|
||||
return (
|
||||
@@ -192,33 +135,14 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
||||
const clockMs = state.simState.clockMs;
|
||||
const open = state.packages.filter((p) => p.status === 'open');
|
||||
|
||||
// On board (v0.12.0): every plane that carries cargo or is mid-flight gets a block —
|
||||
// its loaded/expired packages with fly-to-destination + abandon controls, and flying
|
||||
// planes show their current leg.
|
||||
const onboard = state.planes.filter(
|
||||
(p) => p.status === 'flying' || slotsUsedFor(state, p.id) > 0,
|
||||
);
|
||||
|
||||
const catalog = state.catalog;
|
||||
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
||||
|
||||
const grounded = state.planes.filter((p) => p.status === 'available');
|
||||
const sellPlane = state.planes.find((p) => p.id === sellPlaneId && p.status === 'available') ?? grounded[0] ?? null;
|
||||
const refuelable = grounded.filter((p) => p.fuel < p.maxFuel);
|
||||
const refuelPlane =
|
||||
state.planes.find((p) => p.id === refuelPlaneId && p.status === 'available' && p.fuel < p.maxFuel) ??
|
||||
refuelable[0] ??
|
||||
null;
|
||||
// ISS-010 (v0.18.0): Relocate — any GROUNDED plane can be repositioned to any airport via the
|
||||
// existing fly endpoint (pure repositioning, no package needed since v0.12.0).
|
||||
const relocatePlane = grounded.find((p) => p.id === relocatePlaneId) ?? grounded[0] ?? null;
|
||||
const relocateDest =
|
||||
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
|
||||
|
||||
// Previews computed client-side from the snapshot's catalog + economy constants (v0.10.0).
|
||||
const sellEntry = sellPlane ? catalog.find((e) => e.model === sellPlane.model) : undefined;
|
||||
const sellPayout = sellEntry ? Math.round(sellEntry.price * state.sellFraction * 100) / 100 : null;
|
||||
const refuelCost = refuelPlane ? (refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL : null;
|
||||
|
||||
return (
|
||||
<aside data-testid="right-pane" className="pane right-pane">
|
||||
@@ -270,92 +194,7 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="pane-section">
|
||||
<h3 className="pane-heading">On board</h3>
|
||||
{onboard.length === 0 ? (
|
||||
<p className="pane-muted">Nothing on board.</p>
|
||||
) : (
|
||||
onboard.map((plane) => {
|
||||
const cargo = state.packages.filter(
|
||||
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
||||
);
|
||||
return (
|
||||
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
||||
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
||||
// child, so this covers the whole block without flicker between sub-elements.
|
||||
<div
|
||||
key={plane.id}
|
||||
data-testid={`onboard-${plane.id}`}
|
||||
className="onboard-block"
|
||||
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
||||
onMouseLeave={() => onHover(null)}
|
||||
>
|
||||
<div className="contract-main">
|
||||
<span className="plane-model">{planeName(plane)}</span>
|
||||
{plane.status === 'flying' ? (
|
||||
<>
|
||||
<span className="plane-status status-flying">in flight</span>
|
||||
{plane.destName && (
|
||||
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
||||
{plane.locationName} → {plane.destName}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="plane-status status-available">{plane.locationIcao}</span>
|
||||
)}
|
||||
</div>
|
||||
{cargo.map((pkg) => {
|
||||
const penalty = abandonPenalty(pkg, clockMs);
|
||||
return (
|
||||
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
||||
<div className="contract-main">
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`refuel-for-${pkg.id}`}
|
||||
className="pane-btn"
|
||||
disabled={busy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/planes/${plane.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
||||
>
|
||||
Refuel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`fly-to-${pkg.id}`}
|
||||
className="pane-btn"
|
||||
disabled={busy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
||||
>
|
||||
Fly to {pkg.destName}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`abandon-${pkg.id}`}
|
||||
className="pane-btn"
|
||||
disabled={busy || plane.status !== 'available'}
|
||||
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
||||
>
|
||||
Abandon{' '}
|
||||
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="contract-sub">
|
||||
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||
<span>{formatCash(pkg.reward)}</span>
|
||||
{pkg.status === 'expired' ? (
|
||||
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
||||
) : (
|
||||
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
{/* ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time). */}
|
||||
|
||||
<section className="pane-section">
|
||||
<h3 className="pane-heading">Market</h3>
|
||||
@@ -418,84 +257,8 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="market-row">
|
||||
{refuelable.length === 0 ? (
|
||||
<span data-testid="market-refuel-none" className="pane-muted">
|
||||
All tanks full.
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<select
|
||||
data-testid="market-refuel-plane"
|
||||
aria-label="Plane to refuel"
|
||||
value={refuelPlane?.id ?? ''}
|
||||
onChange={(e) => setRefuelPlaneId(e.target.value || null)}
|
||||
>
|
||||
{refuelable.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{planeName(p)} — {Math.round(p.fuel)} / {p.maxFuel} L
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span data-testid="market-refuel-cost" className="market-preview">
|
||||
{refuelCost !== null ? formatCash(refuelCost) : ''}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-testid="market-refuel"
|
||||
className="pane-btn"
|
||||
disabled={busy || refuelPlane === null}
|
||||
onClick={() => {
|
||||
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
||||
}}
|
||||
>
|
||||
Refuel to full
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* ISS-010 (v0.18.0): relocate a grounded plane — the fly endpoint already allows pure
|
||||
repositioning, this row just exposes it for planes with nothing on board. */}
|
||||
<div className="market-row market-row-relocate">
|
||||
<select
|
||||
data-testid="relocate-plane"
|
||||
aria-label="Plane to relocate"
|
||||
value={relocatePlane?.id ?? ''}
|
||||
onChange={(e) => setRelocatePlaneId(e.target.value || null)}
|
||||
>
|
||||
{grounded.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{planeName(p)} — {p.locationIcao}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
data-testid="relocate-dest"
|
||||
aria-label="Relocation destination airport"
|
||||
value={relocateDest?.icao ?? ''}
|
||||
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
|
||||
>
|
||||
{airportOptions?.map((a) => (
|
||||
<option key={a.icao} value={a.icao}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="relocate-go"
|
||||
className="pane-btn"
|
||||
disabled={busy || relocatePlane === null || relocateDest === null}
|
||||
onClick={() => {
|
||||
if (relocatePlane && relocateDest) {
|
||||
void runAction(`/api/planes/${relocatePlane.id}/fly`, { destIcao: relocateDest.icao });
|
||||
}
|
||||
}}
|
||||
>
|
||||
Relocate
|
||||
</button>
|
||||
</div>
|
||||
{/* ISS-023 (v0.21.0): the Relocate row moved to the left pane's "Relocate" section. */}
|
||||
{/* ISS-035 (v0.23.0): the Refuel-to-full row moved to the left pane's "Refuel" section, next to Relocate. */}
|
||||
</section>
|
||||
|
||||
{actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
// ISS-002 — what a side-panel hover highlights on the map (v0.15.0): a plane marker
|
||||
// (+ its route leg if flying) or both endpoint airports of an open package. The shell
|
||||
// owns this state and passes it to <Map>; panes report it via their onHover callback.
|
||||
// ISS-022/025/027 (v0.22.0): any target carrying two ICAOs also makes the map draw the full
|
||||
// great-circle trace between them — package hovers carry origin→dest, 'route' hovers (the
|
||||
// Relocate panel) carry fromIcao→toIcao; a package hover may additionally name its plane so
|
||||
// that plane's halo stays lit alongside the trace.
|
||||
|
||||
export type HoverTarget =
|
||||
| { kind: 'plane'; id: string }
|
||||
| { kind: 'package'; originIcao: string; destIcao: string };
|
||||
| { kind: 'package'; originIcao: string; destIcao: string; planeId?: string }
|
||||
| { kind: 'route'; fromIcao: string; toIcao: string };
|
||||
|
||||
@@ -24,6 +24,7 @@ function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
||||
departureSimTime: null,
|
||||
lat: 50,
|
||||
lon: 8.5,
|
||||
queue: [],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
+13
-10
@@ -3,7 +3,8 @@ import { expect, test } from '@playwright/test';
|
||||
|
||||
// v0.12.0 package model against the live origin (https://flight.dev.kkhost.pl):
|
||||
// the full core loop through the UI — hook creates a short package at EDDF → Load
|
||||
// via the right pane → click its destination in the on-board list → fly at 1000× →
|
||||
// via the right pane → click its destination in the on-board list (left pane since
|
||||
// v0.20.0, ISS-021) → fly at 1000× →
|
||||
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
||||
// penalty while grounded; expired packages deliver/abandon with no reward and no
|
||||
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
|
||||
@@ -65,8 +66,10 @@ async function postSim(page: Page, body: Record<string, unknown>): Promise<void>
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||
// resume it or the clock stays frozen and the next wait hangs.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as { timeScale: number };
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
@@ -117,7 +120,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||
}
|
||||
if (plane.locationIcao !== HUB) {
|
||||
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||
// fast-forwards instead of taking real-time hours.
|
||||
await setScale(page, SCALE);
|
||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||
@@ -224,8 +227,8 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
||||
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
||||
expect(s.account.cash).toBeCloseTo(before.account.cash + pkg.reward - refuelCost, 6);
|
||||
|
||||
// Restore: fly home (repositioning — no package needed in the v0.12.0 model). ISS-011: the
|
||||
// arrival above auto-slown the sim to 1×, so re-set SCALE for the return leg.
|
||||
// Restore: fly home (repositioning — no package needed in the v0.12.0 model). ISS-041: the
|
||||
// arrival above paused the sim, so re-set SCALE for the return leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
const homeRes = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
||||
expect(homeRes.ok()).toBeTruthy();
|
||||
@@ -313,8 +316,8 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
||||
expect(s.packages.find((p) => p.id === pkgB.id)!.status).toBe('abandoned');
|
||||
expect(s.account.cash).toBe(cashBeforeAbandon); // free — expired abandons cost nothing
|
||||
|
||||
// Restore: refuel + fly home. ISS-011: the LEMD arrival above auto-slown the sim to 1×, so
|
||||
// re-set SCALE for the return leg (the expiry wait's scale no longer persists past a landing).
|
||||
// Restore: refuel + fly home. ISS-041: the LEMD arrival above paused the sim, so
|
||||
// re-set SCALE for the return leg (setScale clears pause; the expiry wait's scale is kept).
|
||||
await page.request.post('/api/planes/plane-starter/refuel');
|
||||
await setScale(page, SCALE);
|
||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
@@ -354,8 +357,8 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
||||
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||
expect(res.status()).toBe(409);
|
||||
|
||||
// Fly home from the hop so the fuel section starts at the hub. ISS-011: the hop arrival above
|
||||
// auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||
// Fly home from the hop so the fuel section starts at the hub. ISS-041: the hop arrival above
|
||||
// paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(res.ok()).toBeTruthy();
|
||||
@@ -379,7 +382,7 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
||||
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
||||
expect(atFar.locationIcao).toBe(FAR);
|
||||
// The return leg fits: the weighted burn over it is less than what's left in the tank.
|
||||
// ISS-011: the FAR arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||
// ISS-041: the FAR arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(backRes.ok()).toBeTruthy();
|
||||
|
||||
+3
-1
@@ -13,7 +13,7 @@ test('GET /api/version returns the app version from package.json', async ({ page
|
||||
expect(body.version).toBe(pkg.version);
|
||||
});
|
||||
|
||||
test('GET /api/openapi serves the spec with all ten endpoints and the package.json version', async ({ page }) => {
|
||||
test('GET /api/openapi serves the spec with all twelve endpoints and the package.json version', async ({ page }) => {
|
||||
const res = await page.request.get('/api/openapi');
|
||||
expect(res.status()).toBe(200);
|
||||
expect(res.headers()['content-type']).toContain('application/json');
|
||||
@@ -28,6 +28,8 @@ test('GET /api/openapi serves the spec with all ten endpoints and the package.js
|
||||
'/api/packages/{id}/abandon',
|
||||
'/api/packages/{id}/load',
|
||||
'/api/planes/{planeId}/fly',
|
||||
'/api/planes/{planeId}/queue',
|
||||
'/api/planes/{planeId}/queue/cancel',
|
||||
'/api/planes/{planeId}/refuel',
|
||||
'/api/sim',
|
||||
'/api/state',
|
||||
|
||||
+292
-6
@@ -6,6 +6,10 @@ import { test, expect, type Page } from '@playwright/test';
|
||||
// highlight layers (planes-highlight / routes-highlight / airports-highlight), each filtered
|
||||
// to match nothing until a hover sets the filter — asserted here via window.__flightMap's
|
||||
// queryRenderedFeatures, same pattern as e2e/map.spec.ts and e2e/map-interactions.spec.ts.
|
||||
// ISS-022/025/027 (v0.22.0): any hover carrying two endpoints ALSO draws the full great-circle
|
||||
// trace between them in a fourth top-most layer (`hover-route`, dashed) — job-list rows, on-board
|
||||
// cargo rows and the Relocate section; the relocate preview rings only its TARGET airport, which
|
||||
// additionally gets a distinct green ring in `airports-target-highlight` (ISS-022).
|
||||
|
||||
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||
@@ -20,6 +24,8 @@ interface PlaneState {
|
||||
maxFuel: number;
|
||||
locationIcao: string;
|
||||
destIcao: string | null;
|
||||
lat: number; // live position — interpolated per snapshot while flying, airport coords when grounded
|
||||
lon: number;
|
||||
}
|
||||
|
||||
interface PackageState {
|
||||
@@ -49,9 +55,10 @@ async function postSim(page: Page, body: unknown) {
|
||||
}
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||
// otherwise surface as an unexplained landing-wait timeout.
|
||||
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as { timeScale: number };
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
@@ -89,7 +96,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
||||
.toBe(true);
|
||||
}
|
||||
if (starter.locationIcao !== HUB) {
|
||||
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||
// fast-forwards instead of taking real-time hours.
|
||||
await setScale(page, SCALE);
|
||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
@@ -113,12 +120,30 @@ async function waitForAirportCount(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
// Rendered features of the given layers in the current viewport, [] until the map exists.
|
||||
function renderedFeatures(page: Page, layers: string[]) {
|
||||
function renderedFeatures(
|
||||
page: Page,
|
||||
layers: string[],
|
||||
): Promise<Array<{ type?: unknown; id?: unknown; properties?: unknown; geometry?: unknown }>> {
|
||||
return page.evaluate((ls: string[]) => {
|
||||
const m = (window as any).__flightMap;
|
||||
if (!m) return [];
|
||||
try {
|
||||
return m.queryRenderedFeatures(undefined, { layers: ls });
|
||||
// queryRenderedFeatures returns live GeoJSONFeature instances whose `geometry` is a lazy
|
||||
// PROTOTYPE getter — Playwright's evaluate serialization copies only own enumerable props,
|
||||
// so geometry silently vanishes across the page boundary (CI runs #69–#71: strict-equality
|
||||
// timeouts → TypeError on f.geometry.coordinates → filter-found-nothing timeouts). Map to
|
||||
// plain objects IN-PAGE so the getter is evaluated before serialization.
|
||||
return (m.queryRenderedFeatures(undefined, { layers: ls }) as Array<{
|
||||
type?: unknown;
|
||||
id?: unknown;
|
||||
properties?: unknown;
|
||||
geometry?: unknown;
|
||||
}>).map((f) => ({
|
||||
type: f.type,
|
||||
id: f.id,
|
||||
properties: f.properties,
|
||||
geometry: f.geometry,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -160,6 +185,56 @@ async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
// [lon, lat] of an airport from the same /api/airports dataset the map draws its traces from.
|
||||
async function airportLonLat(page: Page, icao: string): Promise<[number, number]> {
|
||||
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||
};
|
||||
const f = fc.features.find((x) => x.properties.icao === icao);
|
||||
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
|
||||
return [f.properties.lon, f.properties.lat];
|
||||
}
|
||||
|
||||
// ISS-022/025/027: the hover-route layer must hold the great-circle trace from origin to dest.
|
||||
// MapLibre stores GeoJSON geometry in per-tile INTEGER grids and clips long lines across tiles, so
|
||||
// queryRenderedFeatures returns ONE FEATURE PER TILE the line crosses (the 1420 km EDDF→LEMD leg is
|
||||
// 4 segments at z=4 / 5 at z=5) with coordinates quantized to the rendered zoom's grid — up to ~half
|
||||
// a grid step off (~0.001° observed at z≥4, ~0.02° worst case at z=0). A strict single-feature +
|
||||
// exact-coords comparison can therefore never match even when the line is drawn correctly (CI run #69:
|
||||
// all three hover-route timeouts while the trace was visibly rendered), so we accept any number of
|
||||
// segments and require some segment to START within EPS of `from` and some to END within EPS of `to`.
|
||||
// The true endpoints survive clipping verbatim in whichever tile contains them. (CI runs #69–#71:
|
||||
// features could arrive WITHOUT a usable geometry because Playwright's evaluate serialization drops
|
||||
// the lazy prototype getter — not MapLibre artifacts; renderedFeatures now maps to plain objects
|
||||
// in-page.) The helper still filters to real LineString segments and treats "none yet" as keep-polling
|
||||
// instead of throwing inside the poll callback. Call fitToAirports([from, to]) first — rendered
|
||||
// features are viewport-scoped.
|
||||
const HOVER_ROUTE_EPS_DEG = 0.05; // ~5 km: above worst-case quantization at any zoom, below the distance between any two EU airports
|
||||
|
||||
async function expectHoverRoute(page: Page, fromIcao: string, toIcao: string): Promise<void> {
|
||||
const [from, to] = await Promise.all([airportLonLat(page, fromIcao), airportLonLat(page, toIcao)]);
|
||||
const near = (a: [number, number], b: [number, number]) =>
|
||||
Math.abs(a[0] - b[0]) <= HOVER_ROUTE_EPS_DEG && Math.abs(a[1] - b[1]) <= HOVER_ROUTE_EPS_DEG;
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
||||
// Features are plain objects with in-page-evaluated geometry (see renderedFeatures). The filter
|
||||
// guards against degenerate/zero-length clipped segments and keeps this poll callback total — a
|
||||
// throw inside expect.poll fails the test instantly instead of retrying. "None yet" → keep polling.
|
||||
const segs = feats.filter(
|
||||
(f): f is { geometry: { type: 'LineString'; coordinates: [number, number][] } } =>
|
||||
!!f.geometry && f.geometry.type === 'LineString' && Array.isArray(f.geometry.coordinates) && f.geometry.coordinates.length >= 2,
|
||||
);
|
||||
if (!segs.length) return false;
|
||||
// The line may be clipped into several per-tile segments — check the endpoints across all of them.
|
||||
const startsAtFrom = segs.some((f) => near(f.geometry.coordinates[0], from));
|
||||
const endsAtTo = segs.some((f) => {
|
||||
const c = f.geometry.coordinates;
|
||||
return near(c[c.length - 1], to);
|
||||
});
|
||||
return startsAtFrom && endsAtTo;
|
||||
}, { timeout: 15_000, message: `waiting for the hover-route line ${fromIcao} → ${toIcao}` }).toBe(true);
|
||||
}
|
||||
|
||||
test('hovering a fleet row highlights the plane on the map', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||
await flyHomeViaApi(page); // deterministic: the starter sits at EDDF, inside the initial view
|
||||
@@ -230,6 +305,7 @@ test('hovering an open package highlights its endpoint airports', async ({ page
|
||||
await fitToAirports(page, [HUB, DEST]);
|
||||
|
||||
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
||||
expect(await renderedFeatures(page, ['airports-target-highlight'])).toHaveLength(0);
|
||||
|
||||
await row.hover();
|
||||
await expect.poll(async () => {
|
||||
@@ -238,11 +314,129 @@ test('hovering an open package highlights its endpoint airports', async ({ page
|
||||
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to show both endpoints' })
|
||||
.toBe(JSON.stringify([HUB, DEST].sort()));
|
||||
|
||||
// ISS-022 (v0.22.0): the ENTIRE trace is drawn too — a great-circle line from origin to dest,
|
||||
// not just the endpoint rings.
|
||||
await expectHoverRoute(page, HUB, DEST);
|
||||
|
||||
// And the TARGET airport gets its own distinct-colored ring — only the destination, never the origin.
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['airports-target-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||
}, { timeout: 15_000, message: 'waiting for the airports-target-highlight layer to ring only the destination' })
|
||||
.toBe(JSON.stringify([DEST]));
|
||||
|
||||
await unhover(page);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the highlight to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['airports-target-highlight'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the target ring to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
});
|
||||
|
||||
test('hovering an on-board cargo row draws its trace and keeps the plane halo', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||
|
||||
// Load a package onto the grounded starter so it shows up in the On board section.
|
||||
const pkg = await createPackage(page, HUB, DEST);
|
||||
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||
expect(load.status()).toBe(200);
|
||||
|
||||
await page.goto('/');
|
||||
await waitForAirportCount(page);
|
||||
|
||||
const row = page.locator(`[data-testid="onboard-package-${pkg.id}"]`);
|
||||
await expect(row, 'the loaded package appears in the On board section').toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||
await fitToAirports(page, [HUB, DEST]);
|
||||
|
||||
await row.hover();
|
||||
// ISS-025 (v0.22.0): same full origin→dest trace as job-list rows…
|
||||
await expectHoverRoute(page, HUB, DEST);
|
||||
// …and the package's plane keeps its halo lit (the hover carries planeId).
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['planes-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||
return feats.length > 0 && feats[0].properties.id === 'plane-starter';
|
||||
}, { timeout: 15_000, message: 'waiting for the planes-highlight layer to show plane-starter' }).toBe(true);
|
||||
|
||||
await unhover(page);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['planes-highlight'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the highlight to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
|
||||
// Leave the instance clean: abandon the loaded package so later specs start with an empty starter.
|
||||
const res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||
expect(res.status()).toBe(200);
|
||||
});
|
||||
|
||||
test('hovering the Relocate section previews the planned route and target airport', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||
|
||||
await page.goto('/');
|
||||
await waitForAirportCount(page);
|
||||
|
||||
const section = page.getByTestId('relocate-section');
|
||||
await expect(section, 'the Relocate section is visible').toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// LeftPane fetches /api/airports on its own (separate from the map header count) — wait for
|
||||
// the destination options to populate before selecting.
|
||||
await expect(page.getByTestId('relocate-dest').locator(`option[value="${DEST}"]`)).toHaveCount(1, { timeout: 15_000 });
|
||||
|
||||
// Pick the starter + a known destination explicitly (the effective-selection defaults already do this).
|
||||
await page.getByTestId('relocate-plane').selectOption('plane-starter');
|
||||
await page.getByTestId('relocate-dest').selectOption(DEST);
|
||||
|
||||
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||
await fitToAirports(page, [HUB, DEST]);
|
||||
|
||||
expect(await renderedFeatures(page, ['hover-route'])).toHaveLength(0);
|
||||
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
||||
expect(await renderedFeatures(page, ['airports-target-highlight'])).toHaveLength(0);
|
||||
|
||||
// ISS-027 (v0.22.0): hovering the panel with a plane + destination selected previews the flight —
|
||||
// dashed trace from the plane's airport to the destination…
|
||||
await section.hover();
|
||||
await expectHoverRoute(page, HUB, DEST);
|
||||
// …and rings ONLY the target airport (the origin stays unmarked).
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['airports-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to ring only the target' })
|
||||
.toBe(JSON.stringify([DEST]));
|
||||
// …plus the destination's own distinct-colored ring (ISS-022) — same single icao.
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['airports-target-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
|
||||
}, { timeout: 15_000, message: 'waiting for the airports-target-highlight layer to ring only the target' })
|
||||
.toBe(JSON.stringify([DEST]));
|
||||
|
||||
await unhover(page);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the highlight to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['airports-target-highlight'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the target ring to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
});
|
||||
|
||||
test('hovering an on-board block of a flying plane highlights its route', async ({ page }) => {
|
||||
@@ -294,7 +488,99 @@ test('hovering an on-board block of a flying plane highlights its route', async
|
||||
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
||||
.toBe(true);
|
||||
|
||||
// ISS-011: the arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(home.status()).toBe(200);
|
||||
await expect
|
||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||
timeout: 120_000,
|
||||
message: 'waiting for plane-starter to land back at the hub',
|
||||
})
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test('hovering an on-board package while its carrier is mid-flight traces from current position', async ({ page }) => {
|
||||
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
|
||||
await flyHomeViaApi(page);
|
||||
|
||||
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank.
|
||||
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||
expect(refuel.status()).toBe(200);
|
||||
|
||||
await page.goto('/');
|
||||
await waitForAirportCount(page);
|
||||
|
||||
// Load + fly via the API (same pattern as e2e/map-interactions.spec.ts), then speed up.
|
||||
const pkg = await createPackage(page, HUB, DEST);
|
||||
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||
expect(load.status()).toBe(200);
|
||||
const fly = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
|
||||
expect(fly.status()).toBe(200);
|
||||
await setScale(page, SCALE);
|
||||
|
||||
// Wait until the starter is GENUINELY mid-flight — its live position clearly away from EDDF in
|
||||
// both axes (well past HOVER_ROUTE_EPS_DEG) so "the trace starts at the plane" and "it starts at
|
||||
// the pickup airport" are distinguishable. The ~10 s leg at scale 1000 gives a wide window.
|
||||
const hubLonLat = await airportLonLat(page, HUB);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||
if (!p || p.status !== 'flying') return false;
|
||||
return Math.abs(p.lon - hubLonLat[0]) > 0.2 && Math.abs(p.lat - hubLonLat[1]) > 0.2;
|
||||
}, { timeout: 60_000, message: 'waiting for plane-starter to be clearly away from the hub' })
|
||||
.toBe(true);
|
||||
|
||||
// Freeze mid-flight so the position is stable while we assert (same pause pattern as the
|
||||
// flying-plane hover test above): paused, every /api/state snapshot reports the same lat/lon.
|
||||
await postSim(page, { paused: true });
|
||||
|
||||
const row = page.locator(`[data-testid="onboard-package-${pkg.id}"]`);
|
||||
await expect(row, 'the loaded package appears in the On board section').toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Both endpoints must be in-viewport for queryRenderedFeatures to see the trace.
|
||||
await fitToAirports(page, [HUB, DEST]);
|
||||
|
||||
const live = (await getState(page)).planes.find((x) => x.id === 'plane-starter')!;
|
||||
const liveLonLat: [number, number] = [live.lon, live.lat]; // stable — the sim is paused
|
||||
const destLonLat = await airportLonLat(page, DEST);
|
||||
|
||||
await row.hover();
|
||||
// ISS-040 (v0.23.2): the trace starts at the carrier's LIVE position and ends at the destination,
|
||||
// and NO segment may start near the pickup airport (the old origin-based behavior). Same per-tile
|
||||
// clipping/quantization caveats as expectHoverRoute — check endpoints across all segments with EPS.
|
||||
await expect.poll(async () => {
|
||||
const feats = (await renderedFeatures(page, ['hover-route'])) as Array<{ geometry?: { type: string; coordinates: [number, number][] } }>;
|
||||
const segs = feats.filter(
|
||||
(f): f is { geometry: { type: 'LineString'; coordinates: [number, number][] } } =>
|
||||
!!f.geometry && f.geometry.type === 'LineString' && Array.isArray(f.geometry.coordinates) && f.geometry.coordinates.length >= 2,
|
||||
);
|
||||
if (!segs.length) return false;
|
||||
const near = (a: [number, number], b: [number, number]) =>
|
||||
Math.abs(a[0] - b[0]) <= HOVER_ROUTE_EPS_DEG && Math.abs(a[1] - b[1]) <= HOVER_ROUTE_EPS_DEG;
|
||||
const startsAtLive = segs.some((f) => near(f.geometry.coordinates[0], liveLonLat));
|
||||
const endsAtDest = segs.some((f) => near(f.geometry.coordinates[f.geometry.coordinates.length - 1], destLonLat));
|
||||
const noneStartsAtHub = !segs.some((f) => near(f.geometry.coordinates[0], hubLonLat));
|
||||
return startsAtLive && endsAtDest && noneStartsAtHub;
|
||||
}, { timeout: 15_000, message: 'waiting for the hover-route trace to run from the live position to the destination' }).toBe(true);
|
||||
|
||||
await unhover(page);
|
||||
await expect.poll(async () => (await renderedFeatures(page, ['hover-route'])).length, {
|
||||
timeout: 15_000,
|
||||
message: 'waiting for the hover route trace to clear after mouseleave',
|
||||
}).toBe(0);
|
||||
|
||||
// Resume and fast-forward to arrival — landing at DEST auto-delivers the package (v0.12.0), so
|
||||
// flying home afterwards leaves the starter clean for the other specs.
|
||||
await postSim(page, { timeScale: SCALE, paused: false });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||
return !!p && p.status === 'available' && p.locationIcao === DEST;
|
||||
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
||||
.toBe(true);
|
||||
|
||||
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(home.status()).toBe(200);
|
||||
|
||||
@@ -69,9 +69,10 @@ async function postSim(page: Page, body: unknown) {
|
||||
}
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||
// otherwise surface as an unexplained landing-wait timeout.
|
||||
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as { timeScale: number };
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
|
||||
@@ -69,6 +69,20 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
|
||||
|
||||
// Sim clock renders (UTC wall-clock of the game time).
|
||||
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
||||
|
||||
// ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time) —
|
||||
// its heading renders here…
|
||||
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toBeVisible();
|
||||
// …and no longer in the right pane.
|
||||
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
||||
|
||||
// ISS-035 (v0.23.0): the Refuel-to-full row moved to the left pane next to Relocate — its section
|
||||
// heading and button render here…
|
||||
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'Refuel', exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId('left-pane').getByTestId('market-refuel')).toBeVisible();
|
||||
// …and neither the heading nor the row remains in the right pane.
|
||||
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'Refuel', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByTestId('right-pane').getByTestId('market-refuel')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
// v0.19.0 — ISS-011: when the LAST plane lands (no plane remains in flight) the sim auto-slows
|
||||
// to 1×, server-side and persisted on the sim_state row so the UI slider reflects it on the next
|
||||
// snapshot. Arrival-triggered by design: a grounded fleet at high scale is left alone, there is no
|
||||
// auto-restore — the player speeds up manually again (asserted below).
|
||||
// v0.24.0 — ISS-041: when the LAST plane lands (no plane remains in flight) the sim pauses
|
||||
// server-side WITHOUT touching timeScale (speed is preserved), and starting a flight
|
||||
// (POST /api/planes/{id}/fly) auto-resumes a paused sim. The cycle: dispatch unpauses →
|
||||
// last landing pauses → next dispatch unpauses again. Arrival-triggered by design: a grounded
|
||||
// fleet at high scale is left alone, there is no idle-enforcement or auto-restore of pause.
|
||||
|
||||
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||
@@ -33,8 +34,10 @@ async function postSim(page: Page, body: Record<string, unknown>): Promise<void>
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||
// resume it or the clock stays frozen and the next wait hangs.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as SimState;
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
@@ -75,7 +78,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||
}
|
||||
if (plane.locationIcao !== HUB) {
|
||||
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||
// fast-forwards instead of taking real-time hours.
|
||||
await setScale(page, SCALE);
|
||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||
@@ -93,8 +96,8 @@ test.afterEach(async ({ page }) => {
|
||||
|
||||
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||
|
||||
test('auto-slow to 1× when the last plane lands; manual speed-up still works (ISS-011)', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
||||
test('last landing pauses the sim without changing speed; dispatch auto-resumes (ISS-041)', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short legs
|
||||
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||
|
||||
const nearest = await nearestToHub(page);
|
||||
@@ -117,14 +120,19 @@ test('auto-slow to 1× when the last plane lands; manual speed-up still works (I
|
||||
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${nearest.icao}` })
|
||||
.toBe(true);
|
||||
|
||||
// …and the server has auto-slown to 1× — persisted on sim_state, so this very snapshot shows it.
|
||||
expect(landedBody!.simState.timeScale).toBe(1);
|
||||
// …and the server paused the sim — persisted on sim_state, so this very snapshot shows it…
|
||||
expect(landedBody!.simState.paused).toBe(true);
|
||||
// …with timeScale UNCHANGED (no auto-slow anymore): speed is preserved for the next dispatch.
|
||||
expect(landedBody!.simState.timeScale).toBe(SCALE);
|
||||
|
||||
// Manual override still works: POST /api/sim {timeScale: 1000} → confirmed by the response…
|
||||
const post = await page.request.post('/api/sim', { data: { timeScale: SCALE } });
|
||||
expect(post.status()).toBe(200);
|
||||
expect(((await post.json()) as SimState).timeScale).toBe(SCALE);
|
||||
// …and by a fresh snapshot (no auto-restore of the previous scale — and no re-slow either,
|
||||
// since nothing is in flight: the trigger is arrival-based, not idle-enforcement).
|
||||
expect((await getState(page)).simState.timeScale).toBe(SCALE);
|
||||
// A subsequent /fly dispatch auto-resumes a paused sim — asserted on the endpoint's OWN full
|
||||
// post-action snapshot, so no poll race with the client's next tick.
|
||||
const fly2 = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(fly2.status()).toBe(200);
|
||||
const resumedBody = (await fly2.json()) as StateBody;
|
||||
expect(resumedBody.simState.paused).toBe(false); // ISS-041 auto-unpause…
|
||||
expect(resumedBody.simState.timeScale).toBe(SCALE); // …with the preserved speed still in effect
|
||||
|
||||
// Let the return leg finish so cleanup starts from a grounded plane.
|
||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 120_000 }).toBe('available');
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { expect, test } from '@playwright/test';
|
||||
|
||||
// v0.18.0 — ISS-010: relocating a GROUNDED (empty) plane to any airport against the live origin.
|
||||
// Two UI surfaces drive the EXISTING POST /api/planes/{id}/fly endpoint (pure repositioning has
|
||||
// been allowed since v0.12.0 — no API change): the right-pane market row
|
||||
// been allowed since v0.12.0 — no API change): the left-pane Relocate section (ISS-023, v0.21.0)
|
||||
// (relocate-plane / relocate-dest / relocate-go) and the Relocate row inside the airport popup on
|
||||
// the map (airport-popup-plane / airport-popup-relocate). Marker-size regression is covered by
|
||||
// the existing e2e/map.spec.ts click tests, not here.
|
||||
@@ -31,8 +31,10 @@ async function postSim(page: Page, body: Record<string, unknown>): Promise<void>
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||
// ISS-041 also clears pause: a landing pauses the sim, so any fast-forward after one must
|
||||
// resume it or the clock stays frozen and the next wait hangs.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as { timeScale: number };
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
@@ -72,7 +74,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||
}
|
||||
if (plane.locationIcao !== HUB) {
|
||||
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||
// fast-forwards instead of taking real-time hours.
|
||||
await setScale(page, SCALE);
|
||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||
@@ -90,7 +92,7 @@ test.afterEach(async ({ page }) => {
|
||||
|
||||
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||
|
||||
test('market row relocates a grounded plane via the right pane', async ({ page }) => {
|
||||
test('left pane Relocate section relocates a grounded plane', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
||||
await flyHomeViaApi(page);
|
||||
|
||||
|
||||
+19
-13
@@ -2,10 +2,12 @@ import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
// v0.12.0 — right Jobs & Market pane against the live origin: open packages render with
|
||||
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list shows
|
||||
// loaded packages with fly-to-destination + abandon buttons (penalty preview from the same
|
||||
// formula as the server); flying planes show their current leg; market buy/sell/refuel previews
|
||||
// match the catalog + economy constants exposed in /api/state. Packages are created via
|
||||
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list
|
||||
// (moved to the left pane in v0.20.0, ISS-021) shows loaded packages with fly-to-destination +
|
||||
// abandon buttons (penalty preview from the same
|
||||
// formula as the server); flying planes show their current leg; market buy/sell previews match
|
||||
// the catalog + economy constants exposed in /api/state, and the Refuel-to-full row (moved to the
|
||||
// left pane in v0.23.0, ISS-035) deducts exactly its cost. Packages are created via
|
||||
// POST /api/test/create-package (FLIGHT_TEST_HOOKS=1), same pattern as e2e/actions.spec.ts.
|
||||
|
||||
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
|
||||
@@ -67,9 +69,10 @@ async function postSim(page: Page, body: unknown) {
|
||||
}
|
||||
|
||||
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||
// otherwise surface as an unexplained landing-wait timeout.
|
||||
// otherwise surface as an unexplained landing-wait timeout. ISS-041 also clears pause: a
|
||||
// landing pauses the sim, so any fast-forward after one must resume it or the clock stays frozen.
|
||||
async function setScale(page: Page, scale: number): Promise<void> {
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||
const res = await page.request.post('/api/sim', { data: { timeScale: scale, paused: false } });
|
||||
expect(res.status()).toBe(200);
|
||||
const body = (await res.json()) as { timeScale: number };
|
||||
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||
@@ -174,7 +177,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
||||
.toBe(true);
|
||||
}
|
||||
if (starter.locationIcao !== HUB) {
|
||||
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||
// ISS-041: the landing above paused the sim — setScale clears pause so the return leg
|
||||
// fast-forwards instead of taking real-time hours.
|
||||
await setScale(page, SCALE);
|
||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
@@ -287,7 +290,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
||||
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Restore: fly home so the live instance stays in its onboarding state for the next run.
|
||||
// ISS-011: the arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||
// ISS-041: the arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||
expect(homeRes.status()).toBe(200);
|
||||
@@ -299,7 +302,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test('market buy/sell/refuel render with previews from the catalog in /api/state; refuel deducts exactly', async ({ page }) => {
|
||||
test('market buy/sell render with previews from the catalog in /api/state; left-pane Refuel deducts exactly', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||
await flyHomeViaApi(page); // grounded starter at EDDF (tank partial after the previous test's flight)
|
||||
|
||||
@@ -324,6 +327,9 @@ test('market buy/sell/refuel render with previews from the catalog in /api/state
|
||||
const payout = Math.round(entry.price * body.sellFraction * 100) / 100;
|
||||
await expect(page.getByTestId('market-sell-payout')).toContainText(eur(payout));
|
||||
|
||||
// ISS-035 (v0.23.0): the Refuel-to-full row now lives in the LEFT pane next to Relocate — same global testids.
|
||||
await expect(page.getByTestId('left-pane').getByTestId('market-refuel')).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Refuel through the pane: the flight genuinely burned fuel…
|
||||
if (starter.fuel < starter.maxFuel) {
|
||||
const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * 100) / 100;
|
||||
@@ -347,7 +353,7 @@ test('market buy/sell/refuel render with previews from the catalog in /api/state
|
||||
}
|
||||
});
|
||||
|
||||
test('on-board row Refuel tops up just enough for the package leg; market button says "Refuel to full"', async ({ page }) => {
|
||||
test('on-board row Refuel tops up just enough for the package leg; left-pane button says "Refuel to full"', async ({ page }) => {
|
||||
test.setTimeout(300_000); // self-heal + one long flight each way at scale 1000
|
||||
await flyHomeViaApi(page);
|
||||
|
||||
@@ -402,12 +408,12 @@ test('on-board row Refuel tops up just enough for the package leg; market button
|
||||
expect(post.account.cash).toBeCloseTo(cashBefore - expectedCost, 6);
|
||||
expect(post.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(fuelBefore + liters, 6);
|
||||
|
||||
// Market row: the fill-up button is labeled "Refuel to full" (testid unchanged).
|
||||
// Left pane (moved from the market in v0.23.0, ISS-035): the fill-up button is labeled "Refuel to full" (testid unchanged).
|
||||
await expect(page.getByTestId('market-refuel')).toHaveText('Refuel to full');
|
||||
|
||||
// Restore: fly home — pkg2's destination IS the hub, so it delivers on arrival. The tank holds
|
||||
// exactly the leg requirement, so this also proves "just enough" is enough. ISS-011: the far-end
|
||||
// arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||
// exactly the leg requirement, so this also proves "just enough" is enough. ISS-041: the far-end
|
||||
// arrival above paused the sim, so re-set SCALE for this leg (setScale clears pause).
|
||||
await setScale(page, SCALE);
|
||||
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
||||
await expect
|
||||
|
||||
+6
-5
@@ -1,9 +1,10 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
// v0.17.0 — ISS-008: action errors surface as bottom-right toasts (in addition to the inline
|
||||
// pane error) and game events appear as info toasts via snapshot diffing; the left-pane Time
|
||||
// section offers an explicit "Enable notifications" opt-in for browser notifications.
|
||||
// v0.17.0 — ISS-008: action errors surface as toasts at the map's right edge (clear of the
|
||||
// right pane, in addition to the inline pane error) and game events appear as info toasts via
|
||||
// snapshot diffing; the left-pane Time section offers an explicit "Enable notifications" opt-in
|
||||
// for browser notifications.
|
||||
|
||||
interface CatalogEntry {
|
||||
model: string;
|
||||
@@ -22,7 +23,7 @@ async function getState(page: Page): Promise<StateBody> {
|
||||
return (await res.json()) as StateBody;
|
||||
}
|
||||
|
||||
test('failed actions toast bottom-right (inline error stays) and the Time section offers a notifications opt-in', async ({ page }) => {
|
||||
test('failed actions toast at the map right edge, clear of the right pane (inline error stays), and the Time section offers a notifications opt-in', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
const buyModel = page.getByTestId('market-buy-model');
|
||||
await expect(buyModel, 'the market section renders once the first snapshot lands').toBeVisible({ timeout: 15_000 });
|
||||
@@ -38,7 +39,7 @@ test('failed actions toast bottom-right (inline error stays) and the Time sectio
|
||||
|
||||
// The toast appears with the server's error message and the error variant class…
|
||||
const toast = page.locator('[data-testid="toast"]').filter({ hasText: /insufficient funds/i });
|
||||
await expect(toast, 'the error toast appears bottom-right').toBeVisible({ timeout: 10_000 });
|
||||
await expect(toast, 'the error toast appears at the map right edge').toBeVisible({ timeout: 10_000 });
|
||||
await expect(toast).toHaveClass(/toast-error/);
|
||||
|
||||
// …and the inline pane error still shows (both surfaces by design). It auto-clears on the
|
||||
|
||||
+9
-2
@@ -30,7 +30,8 @@ CREATE TABLE IF NOT EXISTS planes (
|
||||
dest_icao TEXT,
|
||||
lat REAL NOT NULL,
|
||||
lon REAL NOT NULL,
|
||||
departure_sim_time INTEGER
|
||||
departure_sim_time INTEGER,
|
||||
queue TEXT NOT NULL DEFAULT '[]'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS packages (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
@@ -72,6 +73,10 @@ function migrateColumns(raw: RawSqlJsDatabase): void {
|
||||
if (!cols('planes').has('dest_icao')) {
|
||||
raw.exec('ALTER TABLE planes ADD COLUMN dest_icao TEXT');
|
||||
}
|
||||
// v0.25.0 (ISS-043): the flight queue — ordered JSON array of not-yet-started leg ICACs.
|
||||
if (!cols('planes').has('queue')) {
|
||||
raw.exec(`ALTER TABLE planes ADD COLUMN queue TEXT NOT NULL DEFAULT '[]'`);
|
||||
}
|
||||
}
|
||||
|
||||
// v0.12.0 one-time migration: contracts world → packages world. Detected by the
|
||||
@@ -159,7 +164,9 @@ async function seedEmpty(instance: GameDb): Promise<void> {
|
||||
const rng = mulberry32(randomInt(0, 2 ** 31));
|
||||
const data = buildSeed({ airports, rng, nowMs: Date.now() });
|
||||
|
||||
await instance.db.insert(schema.planes).values(data.plane);
|
||||
// SeedPlane.queue is a string[]; the column stores it as JSON text.
|
||||
const { queue, ...planeCols } = data.plane;
|
||||
await instance.db.insert(schema.planes).values({ ...planeCols, queue: JSON.stringify(queue ?? []) });
|
||||
await instance.db.insert(schema.packages).values(data.packages);
|
||||
await instance.db.insert(schema.account).values(data.account);
|
||||
await instance.db.insert(schema.simState).values(data.simState);
|
||||
|
||||
@@ -20,6 +20,10 @@ export const planes = sqliteTable('planes', {
|
||||
// flying, `fuel` is frozen at its departure value — live position/fuel are pure
|
||||
// functions of the clock (lib/sim/movement.ts), recomputed on read.
|
||||
departureSimTime: integer('departure_sim_time'),
|
||||
// Queue of upcoming legs NOT yet started (v0.25.0, ISS-043) — ordered JSON array
|
||||
// of ICAO strings ('[]' when empty). The ACTIVE leg stays destIcao +
|
||||
// departureSimTime; on landing the engine auto-chains queue[0] if fuel covers it.
|
||||
queue: text('queue').notNull().default('[]'),
|
||||
});
|
||||
|
||||
// Cargo packages (v0.12.0) replace the old contracts table end-to-end: a package
|
||||
|
||||
@@ -22,6 +22,7 @@ const basePlane = (id: string): PlaneState => ({
|
||||
departureSimTime: null,
|
||||
lat: 50.03,
|
||||
lon: 8.56,
|
||||
queue: [],
|
||||
});
|
||||
|
||||
const basePackage = (id: string): PackageState => ({
|
||||
|
||||
@@ -13,9 +13,11 @@ import { HUB_ICAO } from './seed';
|
||||
import {
|
||||
abandonPackage,
|
||||
buyPlane,
|
||||
cancelQueuedLeg,
|
||||
flyPlane,
|
||||
GameActionError,
|
||||
loadPackage,
|
||||
queueLeg,
|
||||
refuelPlane,
|
||||
sellPlane,
|
||||
} from './actions';
|
||||
@@ -167,6 +169,18 @@ describe('flyPlane', () => {
|
||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||
});
|
||||
|
||||
it('clears paused on dispatch (ISS-041) — speed is left untouched', async () => {
|
||||
const inst = await freshDb('fly-unpause.db');
|
||||
// The last landing pauses the sim at whatever scale was in use.
|
||||
await inst.db.update(schema.simState).set({ paused: true, timeScale: 250 });
|
||||
|
||||
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||
|
||||
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||
expect(sim.paused).toBe(false); // dispatch auto-resumes…
|
||||
expect(sim.timeScale).toBe(250); // …with the stored speed preserved
|
||||
});
|
||||
|
||||
it('rejects a flying plane with 409', async () => {
|
||||
const inst = await freshDb('fly-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
@@ -194,6 +208,75 @@ describe('flyPlane', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('queueLeg (v0.25.0, ISS-043)', () => {
|
||||
it('appends legs to the queue in order and persists them as JSON', async () => {
|
||||
const inst = await freshDb('qleg-ok.db');
|
||||
|
||||
await queueLeg(inst, 'plane-starter', 'LEMD');
|
||||
let plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(JSON.parse(plane.queue)).toEqual(['LEMD']);
|
||||
|
||||
await queueLeg(inst, 'plane-starter', 'EHAM'); // pre-building a route
|
||||
plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(JSON.parse(plane.queue)).toEqual(['LEMD', 'EHAM']); // order preserved
|
||||
});
|
||||
|
||||
it('works on a flying plane too — the active leg is untouched, nothing auto-starts', async () => {
|
||||
const inst = await freshDb('qleg-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', departureSimTime: T0, destIcao: 'LEMD' })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
await queueLeg(inst, 'plane-starter', 'EHAM');
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying'); // still on its active leg…
|
||||
expect(plane.destIcao).toBe('LEMD'); // …unchanged — queueing never starts a flight
|
||||
expect(JSON.parse(plane.queue)).toEqual(['EHAM']);
|
||||
});
|
||||
|
||||
it('rejects an unknown plane id with 404', async () => {
|
||||
const inst = await freshDb('qleg-ghost.db');
|
||||
await expectActionError(queueLeg(inst, 'ghost', 'LEMD'), 404);
|
||||
});
|
||||
|
||||
it('rejects an ICAO not in the airport dataset with 400', async () => {
|
||||
const inst = await freshDb('qleg-unknownicao.db');
|
||||
await expectActionError(queueLeg(inst, 'plane-starter', 'ZZZZ'), 400, /unknown airport/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancelQueuedLeg (v0.25.0, ISS-043)', () => {
|
||||
it('removes the leg at the given index and keeps the rest in order', async () => {
|
||||
const inst = await freshDb('qcancel-ok.db');
|
||||
await queueLeg(inst, 'plane-starter', 'LEMD');
|
||||
await queueLeg(inst, 'plane-starter', 'EHAM');
|
||||
await queueLeg(inst, 'plane-starter', 'EDDV');
|
||||
|
||||
await cancelQueuedLeg(inst, 'plane-starter', 1); // drop EHAM (the middle leg)
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(JSON.parse(plane.queue)).toEqual(['LEMD', 'EDDV']);
|
||||
});
|
||||
|
||||
it('rejects an out-of-range index with 400', async () => {
|
||||
const inst = await freshDb('qcancel-oob.db');
|
||||
await queueLeg(inst, 'plane-starter', 'LEMD'); // one leg → only index 0 is valid
|
||||
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', 1), 400);
|
||||
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', -1), 400);
|
||||
});
|
||||
|
||||
it('rejects cancelling from an empty queue with 400', async () => {
|
||||
const inst = await freshDb('qcancel-empty.db'); // seeded starter has no queued legs
|
||||
await expectActionError(cancelQueuedLeg(inst, 'plane-starter', 0), 400);
|
||||
});
|
||||
|
||||
it('rejects an unknown plane id with 404', async () => {
|
||||
const inst = await freshDb('qcancel-ghost.db');
|
||||
await expectActionError(cancelQueuedLeg(inst, 'ghost', 0), 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('abandonPackage', () => {
|
||||
// A loaded package created at T0 with a 10h window; the seeded sim clock is T0.
|
||||
const REWARD = 1_000;
|
||||
|
||||
+46
-1
@@ -6,7 +6,7 @@ import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||
import { runAction } from '@/lib/sim/engine';
|
||||
import { getStateSnapshot } from './state';
|
||||
import { getStateSnapshot, parseIcaoQueue } from './state';
|
||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||
import { abandonPenalty } from './penalty';
|
||||
import { HUB_ICAO } from './seed';
|
||||
@@ -125,6 +125,51 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
||||
lon: origin.lon,
|
||||
})
|
||||
.where(eq(schema.planes.id, planeId));
|
||||
// ISS-041: starting a flight resumes a paused sim (the last landing pauses it). Runs inside
|
||||
// runAction(), so tick + unpause + dispatch are atomic under the sim lock.
|
||||
await inst.db.update(schema.simState).set({ paused: false });
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
// --- Queue (POST /api/planes/:id/queue {destIcao}) — ISS-043 part 1 ---
|
||||
|
||||
// Append a NOT-yet-started leg to the plane's queue. Works whether the plane is
|
||||
// grounded or flying (you can pre-build a route); nothing auto-starts here — the
|
||||
// active leg still starts via flyPlane, and queued legs chain on landing when fuel
|
||||
// covers them (lib/sim/engine.ts deliverPackages). Validation: known plane, ICAO
|
||||
// in the airport dataset.
|
||||
export async function queueLeg(inst: GameDb, planeId: string, destIcao: string): Promise<void> {
|
||||
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||
const plane = planeRows[0];
|
||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||
|
||||
const fc = await loadAirportsGeoJson();
|
||||
if (!fc.features.some((f) => f.properties.icao === destIcao)) {
|
||||
throw new GameActionError(400, `unknown airport ${destIcao}`);
|
||||
}
|
||||
|
||||
const queue = parseIcaoQueue(plane.queue);
|
||||
queue.push(destIcao);
|
||||
await inst.db.update(schema.planes).set({ queue: JSON.stringify(queue) }).where(eq(schema.planes.id, planeId));
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
// --- Queue cancel (POST /api/planes/:id/queue/cancel {index}) — ISS-043 part 1 ---
|
||||
|
||||
// Remove a NOT-yet-started leg from the queue by index. Only queued legs are
|
||||
// cancellable — the active in-flight leg (destIcao) is never affected. Validation:
|
||||
// known plane, integer index within [0, queue.length).
|
||||
export async function cancelQueuedLeg(inst: GameDb, planeId: string, index: number): Promise<void> {
|
||||
const planeRows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||
const plane = planeRows[0];
|
||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||
|
||||
const queue = parseIcaoQueue(plane.queue);
|
||||
if (index < 0 || index >= queue.length) {
|
||||
throw new GameActionError(400, `queue index ${index} out of range — the queue holds ${queue.length} legs`);
|
||||
}
|
||||
queue.splice(index, 1);
|
||||
await inst.db.update(schema.planes).set({ queue: JSON.stringify(queue) }).where(eq(schema.planes.id, planeId));
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ describe('buildSeed', () => {
|
||||
destIcao: null,
|
||||
lat: 50.0333,
|
||||
lon: 8.5706,
|
||||
queue: [], // v0.25.0 (ISS-043) — no queued legs on first run
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -38,6 +38,9 @@ export interface SeedPlane {
|
||||
destIcao: null;
|
||||
lat: number;
|
||||
lon: number;
|
||||
// Upcoming legs not yet started (v0.25.0, ISS-043) — serialized to the queue
|
||||
// column as JSON text on insert; defaults to an empty queue.
|
||||
queue?: string[];
|
||||
}
|
||||
|
||||
export interface SeedPackage {
|
||||
@@ -182,6 +185,7 @@ export function buildSeed(input: {
|
||||
destIcao: null,
|
||||
lat: hub.lat,
|
||||
lon: hub.lon,
|
||||
queue: [], // no queued legs on first run (v0.25.0)
|
||||
};
|
||||
|
||||
const count = PACKAGE_COUNT_MIN + Math.floor(rng() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||
|
||||
@@ -24,6 +24,21 @@ export interface PlaneState {
|
||||
departureSimTime: number | null;
|
||||
lat: number;
|
||||
lon: number;
|
||||
// Upcoming legs NOT yet started (v0.25.0, ISS-043) — ordered ICAOs; the active
|
||||
// leg is destIcao. The engine auto-chains queue[0] on landing when fuel covers it.
|
||||
queue: string[];
|
||||
}
|
||||
|
||||
// Parse the planes.queue JSON column into an ICAO list (v0.25.0). Guards against
|
||||
// null/empty/malformed values so a corrupt cell can never break a snapshot or tick.
|
||||
export function parseIcaoQueue(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const v: unknown = JSON.parse(raw);
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export interface PackageState {
|
||||
@@ -108,6 +123,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
||||
departureSimTime: p.departureSimTime,
|
||||
lat: live?.lat ?? p.lat,
|
||||
lon: live?.lon ?? p.lon,
|
||||
queue: parseIcaoQueue(p.queue),
|
||||
};
|
||||
}),
|
||||
packages: packageRows.map((p) => ({
|
||||
|
||||
+63
-10
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { StateSnapshot } from './game/state';
|
||||
import { planesGeoJson, routesGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData';
|
||||
import { planesGeoJson, routesGeoJson, hoverRouteGeoJson, hoverTraceGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData';
|
||||
import { haversineKm } from './geo';
|
||||
|
||||
const AIRPORTS = new Map<string, AirportCoord>([
|
||||
@@ -34,8 +34,8 @@ describe('planesGeoJson', () => {
|
||||
const fc = planesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
||||
{ id: 'plane-2', model: 'atr72', status: 'flying', fuel: 4000, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: 'EDDV', destName: 'Hannover Airport', departureSimTime: 1000, lat: 51.2, lon: 9.1 },
|
||||
{ id: 'plane-starter', model: 'atr72', status: 'available', fuel: 6300, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, queue: [] },
|
||||
{ id: 'plane-2', model: 'atr72', status: 'flying', fuel: 4000, maxFuel: 6300, locationIcao: 'EDDF', locationName: 'Frankfurt Main Airport', destIcao: 'EDDV', destName: 'Hannover Airport', departureSimTime: 1000, lat: 51.2, lon: 9.1, queue: [] },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -61,7 +61,7 @@ describe('planesGeoJson', () => {
|
||||
snapshot({
|
||||
catalog: [],
|
||||
planes: [
|
||||
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0 },
|
||||
{ id: 'p1', model: 'mystery', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: null, lat: 0, lon: 0, queue: [] },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -72,7 +72,7 @@ describe('planesGeoJson', () => {
|
||||
const fc = planesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'x', destIcao: null, destName: null, departureSimTime: 0, lat: 0, lon: 0, queue: [] },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -89,7 +89,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56 },
|
||||
{ id: 'p1', model: 'atr72', status: 'available', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: null, destName: null, departureSimTime: null, lat: 50.03, lon: 8.56, queue: [] },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
@@ -101,7 +101,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 51, lon: 9, queue: [] },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
@@ -118,7 +118,7 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'ZZZZ', locationName: '?', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 0, lon: 0, queue: [] },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
@@ -130,8 +130,8 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
||||
const fc = routesGeoJson(
|
||||
snapshot({
|
||||
planes: [
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9 },
|
||||
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDV', locationName: 'H', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 52.4, lon: 9.6 },
|
||||
{ id: 'p1', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDF', locationName: 'F', destIcao: 'EDDV', destName: 'H', departureSimTime: 0, lat: 51, lon: 9, queue: [] },
|
||||
{ id: 'p2', model: 'atr72', status: 'flying', fuel: 1, maxFuel: 2, locationIcao: 'EDDV', locationName: 'H', destIcao: 'EHAM', destName: 'A', departureSimTime: 0, lat: 52.4, lon: 9.6, queue: [] },
|
||||
],
|
||||
}),
|
||||
AIRPORTS,
|
||||
@@ -140,6 +140,59 @@ describe('routesGeoJson (v0.12.0 — one line per flying plane\'s current leg)',
|
||||
});
|
||||
});
|
||||
|
||||
describe('hoverRouteGeoJson (ISS-022/025/027 v0.22.0 — hover route trace)', () => {
|
||||
it('returns an empty collection for the no-hover "" sentinel', () => {
|
||||
expect(hoverRouteGeoJson('', '', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
});
|
||||
|
||||
it('draws one great-circle line between two known airports with exact endpoints', () => {
|
||||
const fc = hoverRouteGeoJson('EDDF', 'EHAM', AIRPORTS);
|
||||
expect(fc.features).toHaveLength(1);
|
||||
expect(fc.features[0].properties).toEqual({ planeId: '' }); // pure overlay — no owning plane
|
||||
const coords = fc.features[0].geometry.coordinates;
|
||||
expect(coords.length).toBe(ROUTE_ARC_SEGMENTS + 1); // sampled arc, not a 2-point chord
|
||||
expect(coords[0]).toEqual([8.56, 50.03]); // EDDF [lon, lat] — exact endpoint
|
||||
expect(coords[coords.length - 1]).toEqual([4.76, 52.31]); // EHAM — exact endpoint
|
||||
});
|
||||
|
||||
it('draws the same trace reversed (endpoints swapped, arc mirrored)', () => {
|
||||
const ab = hoverRouteGeoJson('EDDF', 'EHAM', AIRPORTS).features[0].geometry.coordinates;
|
||||
const ba = hoverRouteGeoJson('EHAM', 'EDDF', AIRPORTS).features[0].geometry.coordinates;
|
||||
expect(ba.length).toBe(ab.length);
|
||||
// The slerp is symmetric up to floating-point rounding (1 − t ≠ (N−t)/N bit-exactly), so
|
||||
// compare with a tolerance: each reversed point sits on the forward arc within ~1e-9 degrees.
|
||||
for (let i = 0; i < ab.length; i++) {
|
||||
expect(Math.abs(ba[i][0] - ab[ab.length - 1 - i][0])).toBeLessThan(1e-9);
|
||||
expect(Math.abs(ba[i][1] - ab[ab.length - 1 - i][1])).toBeLessThan(1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns an empty collection when the from airport is missing from the dataset', () => {
|
||||
expect(hoverRouteGeoJson('ZZZZ', 'EDDV', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
});
|
||||
|
||||
it('returns an empty collection when the to airport is missing from the dataset', () => {
|
||||
expect(hoverRouteGeoJson('EDDF', 'ZZZZ', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('hoverTraceGeoJson (ISS-040 v0.23.2 — on-board package trace from the carrier\'s live position)', () => {
|
||||
it('draws one great-circle line from the given start coord to the dest airport with exact endpoints', () => {
|
||||
const from = { lat: 51.2, lon: 9.1 }; // a mid-flight position — not an airport
|
||||
const fc = hoverTraceGeoJson(from, 'EHAM', AIRPORTS);
|
||||
expect(fc.features).toHaveLength(1);
|
||||
expect(fc.features[0].properties).toEqual({ planeId: '' }); // pure overlay — no owning plane
|
||||
const coords = fc.features[0].geometry.coordinates;
|
||||
expect(coords.length).toBe(ROUTE_ARC_SEGMENTS + 1); // sampled arc, not a 2-point chord
|
||||
expect(coords[0]).toEqual([9.1, 51.2]); // live start — exact endpoint
|
||||
expect(coords[coords.length - 1]).toEqual([4.76, 52.31]); // EHAM — exact endpoint
|
||||
});
|
||||
|
||||
it('returns an empty collection when the dest airport is missing from the dataset', () => {
|
||||
expect(hoverTraceGeoJson({ lat: 0, lon: 0 }, 'ZZZZ', AIRPORTS)).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
|
||||
it('samples >2 points with the endpoints exactly at the airport coords', () => {
|
||||
const arc = greatCircleArc(AIRPORTS.get('EDDF')!, AIRPORTS.get('EHAM')!);
|
||||
|
||||
@@ -85,6 +85,59 @@ export function greatCircleArc(from: AirportCoord, to: AirportCoord): [number, n
|
||||
return coords;
|
||||
}
|
||||
|
||||
// ISS-022/025/027 (v0.22.0): the hover route trace — one great-circle LineString between two
|
||||
// airports, drawn top-most while a panel row hovers (job-list rows, on-board cargo rows, the
|
||||
// Relocate section). Empty collection when either endpoint is missing from the dataset — never
|
||||
// guessed; the '' sentinel (no hovered target) resolves to nothing and yields the same.
|
||||
export function hoverRouteGeoJson(
|
||||
fromIcao: string,
|
||||
toIcao: string,
|
||||
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||
): FeatureCollection<MapLineFeature> {
|
||||
const from = airportsByIcao.get(fromIcao);
|
||||
const to = airportsByIcao.get(toIcao);
|
||||
if (!from || !to) return EMPTY_LINES;
|
||||
return {
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: greatCircleArc(from, to),
|
||||
},
|
||||
properties: { planeId: '' }, // no owning plane — a pure hover overlay
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// ISS-040 (v0.23.2): the on-board package hover trace — same shape as hoverRouteGeoJson but the
|
||||
// start is a live COORDINATE (the carrier plane's current position), not an airport ICAO: once the
|
||||
// plane has departed with cargo still loaded, the preview must begin where it actually is. Empty
|
||||
// collection when the destination is missing from the dataset — never guessed.
|
||||
export function hoverTraceGeoJson(
|
||||
from: AirportCoord,
|
||||
toIcao: string,
|
||||
airportsByIcao: ReadonlyMap<string, AirportCoord>,
|
||||
): FeatureCollection<MapLineFeature> {
|
||||
const to = airportsByIcao.get(toIcao);
|
||||
if (!to) return EMPTY_LINES;
|
||||
return {
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: greatCircleArc(from, to),
|
||||
},
|
||||
properties: { planeId: '' }, // no owning plane — a pure hover overlay
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// One LineString per FLYING plane — its current leg from locationIcao to dest_icao.
|
||||
// Grounded planes draw nothing; a flying plane missing either endpoint from the
|
||||
// dataset is skipped, never guessed. The line is sampled along the great circle
|
||||
|
||||
+24
-2
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import { openApiSpec } from './openapi';
|
||||
|
||||
describe('OpenAPI spec', () => {
|
||||
it('documents exactly the ten public endpoints (4 read + 6 player actions)', () => {
|
||||
it('documents exactly the twelve public endpoints (4 read + 8 player actions)', () => {
|
||||
expect(Object.keys(openApiSpec.paths).sort()).toEqual([
|
||||
'/api/airports',
|
||||
'/api/market/buy-plane',
|
||||
@@ -11,6 +11,8 @@ describe('OpenAPI spec', () => {
|
||||
'/api/packages/{id}/abandon',
|
||||
'/api/packages/{id}/load',
|
||||
'/api/planes/{planeId}/fly',
|
||||
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||
'/api/planes/{planeId}/refuel',
|
||||
'/api/sim',
|
||||
'/api/state',
|
||||
@@ -120,6 +122,7 @@ describe('OpenAPI spec', () => {
|
||||
'lon',
|
||||
'maxFuel',
|
||||
'model',
|
||||
'queue', // v0.25.0 (ISS-043) — upcoming legs not yet started
|
||||
'status',
|
||||
]);
|
||||
|
||||
@@ -169,7 +172,7 @@ describe('OpenAPI spec', () => {
|
||||
expect(Object.keys(error)).toEqual(['error']);
|
||||
});
|
||||
|
||||
it('documents the six action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||
it('documents the eight action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||
// The spec object is a literal type; these helpers view it as plain JSON.
|
||||
const post = (p: string) =>
|
||||
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
||||
@@ -183,6 +186,8 @@ describe('OpenAPI spec', () => {
|
||||
'/api/packages/{id}/load',
|
||||
'/api/packages/{id}/abandon',
|
||||
'/api/planes/{planeId}/fly',
|
||||
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||
'/api/market/buy-plane',
|
||||
'/api/market/sell-plane',
|
||||
'/api/planes/{planeId}/refuel',
|
||||
@@ -196,6 +201,8 @@ describe('OpenAPI spec', () => {
|
||||
expect(errorCodes('/api/packages/{id}/load')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/packages/{id}/abandon')).toEqual(['404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/queue')).toEqual(['400', '404']); // v0.25.0 — no 409: queueing works grounded or flying
|
||||
expect(errorCodes('/api/planes/{planeId}/queue/cancel')).toEqual(['400', '404']); // v0.25.0
|
||||
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
||||
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
||||
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['400', '404', '409']); // v0.16.0 optional body
|
||||
@@ -208,6 +215,12 @@ describe('OpenAPI spec', () => {
|
||||
expect(post('/api/planes/{planeId}/fly').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/FlyPlaneRequest',
|
||||
);
|
||||
expect(post('/api/planes/{planeId}/queue').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/QueueLegRequest', // v0.25.0 (ISS-043)
|
||||
);
|
||||
expect(post('/api/planes/{planeId}/queue/cancel').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/CancelQueuedLegRequest', // v0.25.0 (ISS-043)
|
||||
);
|
||||
expect(post('/api/market/buy-plane').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||
'#/components/schemas/BuyPlaneRequest',
|
||||
);
|
||||
@@ -224,6 +237,8 @@ describe('OpenAPI spec', () => {
|
||||
expect(paramNames('/api/packages/{id}/load')).toEqual(['id']);
|
||||
expect(paramNames('/api/packages/{id}/abandon')).toEqual(['id']);
|
||||
expect(paramNames('/api/planes/{planeId}/fly')).toEqual(['planeId']);
|
||||
expect(paramNames('/api/planes/{planeId}/queue')).toEqual(['planeId']); // v0.25.0 (ISS-043)
|
||||
expect(paramNames('/api/planes/{planeId}/queue/cancel')).toEqual(['planeId']); // v0.25.0 (ISS-043)
|
||||
expect(paramNames('/api/planes/{planeId}/refuel')).toEqual(['planeId']);
|
||||
|
||||
// Request schema shapes.
|
||||
@@ -233,6 +248,13 @@ describe('OpenAPI spec', () => {
|
||||
const fly = openApiSpec.components.schemas.FlyPlaneRequest;
|
||||
expect(fly.required).toEqual(['destIcao']);
|
||||
expect(fly.properties.destIcao.type).toBe('string');
|
||||
// v0.25.0 (ISS-043): the queue request schemas mirror fly's destIcao shape.
|
||||
const queueLeg = openApiSpec.components.schemas.QueueLegRequest;
|
||||
expect(queueLeg.required).toEqual(['destIcao']);
|
||||
expect(queueLeg.properties.destIcao.type).toBe('string');
|
||||
const cancelQueuedLeg = openApiSpec.components.schemas.CancelQueuedLegRequest;
|
||||
expect(cancelQueuedLeg.required).toEqual(['index']);
|
||||
expect(cancelQueuedLeg.properties.index.type).toBe('integer');
|
||||
const buy = openApiSpec.components.schemas.BuyPlaneRequest;
|
||||
expect(buy.required).toEqual(['model']);
|
||||
expect(buy.properties.model.type).toBe('string');
|
||||
|
||||
@@ -204,6 +204,74 @@ export const openApiSpec = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/planes/{planeId}/queue': {
|
||||
post: {
|
||||
summary: 'Queue a flight leg for a plane',
|
||||
description:
|
||||
'Append a NOT-yet-started leg to the plane\'s flight queue (v0.25.0, ISS-043). Works whether the plane is grounded or flying — you can pre-build a route; the active leg still starts via /fly and nothing auto-starts here. On landing, the engine auto-chains the first queued leg when fuel covers it (otherwise the plane grounds with the queue kept intact for refuel + re-dispatch).',
|
||||
operationId: 'queueLeg',
|
||||
parameters: [
|
||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/QueueLegRequest' },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Queued — full state snapshot (plane.queue now includes the new leg)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||
},
|
||||
400: {
|
||||
description:
|
||||
'Invalid body (not an object, unknown field, or missing/non-string destIcao) or the ICAO is not in the airport dataset',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
404: {
|
||||
description: 'Unknown plane id',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/planes/{planeId}/queue/cancel': {
|
||||
post: {
|
||||
summary: 'Cancel a queued flight leg',
|
||||
description:
|
||||
'Remove a NOT-yet-started leg from the plane\'s queue by index (v0.25.0, ISS-043). Only queued legs are cancellable — the active in-flight leg (destIcao) is never affected.',
|
||||
operationId: 'cancelQueuedLeg',
|
||||
parameters: [
|
||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/CancelQueuedLegRequest' },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Cancelled — full state snapshot (plane.queue without the removed leg)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||
},
|
||||
400: {
|
||||
description:
|
||||
'Invalid body (not an object, unknown field, or non-integer index) or the index is outside [0, queue.length)',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
404: {
|
||||
description: 'Unknown plane id',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/market/buy-plane': {
|
||||
post: {
|
||||
summary: 'Buy a plane from the market',
|
||||
@@ -441,6 +509,20 @@ export const openApiSpec = {
|
||||
},
|
||||
required: ['destIcao'],
|
||||
},
|
||||
QueueLegRequest: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
destIcao: { type: 'string', description: 'Any airport ICAO from the dataset — appended to the queue as a not-yet-started leg (v0.25.0).' },
|
||||
},
|
||||
required: ['destIcao'],
|
||||
},
|
||||
CancelQueuedLegRequest: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
index: { type: 'integer', description: 'Zero-based position of the queued (not-yet-started) leg to remove; must be within [0, queue.length) (v0.25.0).' },
|
||||
},
|
||||
required: ['index'],
|
||||
},
|
||||
BuyPlaneRequest: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -502,6 +584,12 @@ export const openApiSpec = {
|
||||
},
|
||||
lat: { type: 'number' },
|
||||
lon: { type: 'number' },
|
||||
queue: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description:
|
||||
'Upcoming flight legs NOT yet started (v0.25.0) — ordered ICAOs; the active leg is destIcao. The engine auto-chains queue[0] on landing when fuel covers it.',
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'id',
|
||||
@@ -516,6 +604,7 @@ export const openApiSpec = {
|
||||
'departureSimTime',
|
||||
'lat',
|
||||
'lon',
|
||||
'queue',
|
||||
],
|
||||
},
|
||||
PackageState: {
|
||||
|
||||
+96
-14
@@ -9,7 +9,7 @@ import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||
import { arrivalTimeFor, fuelAtWeighted } from './movement';
|
||||
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
|
||||
import {
|
||||
clampTimeScale,
|
||||
deliverPackages,
|
||||
@@ -235,9 +235,71 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
||||
.set({ status: 'flying', departureSimTime: T0 });
|
||||
expect(await deliverPackages(inst, T0 + 3_600_000)).toBe(0);
|
||||
});
|
||||
|
||||
// --- Auto-chain on landing (v0.25.0, ISS-043) ---
|
||||
|
||||
it('auto-chains to the next queued leg when fuel covers it', async () => {
|
||||
const { inst, to, km, type } = await setupFlight('chain-ok.db'); // full tank EDDF→LEMD
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||
const nextKm = haversineKm(to.lat, to.lon, nextP.lat, nextP.lon);
|
||||
|
||||
// Precondition sanity: a full-tank departure leaves enough for the LEMD→EHAM hop.
|
||||
const landedFuel = fuelAtWeighted(type.maxFuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, km, 1);
|
||||
expect(requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, nextKm)).toBeLessThanOrEqual(landedFuel);
|
||||
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ queue: JSON.stringify(['EHAM', 'EDDV']) })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying'); // chained — still airborne, no ground stop
|
||||
expect(plane.destIcao).toBe('EHAM'); // first queued leg is now the active one
|
||||
expect(plane.departureSimTime).toBe(clock); // departed at the arrival instant…
|
||||
expect(plane.locationIcao).toBe(TO); // …from the airport just landed at
|
||||
expect(plane.lat).toBe(to.lat);
|
||||
expect(plane.lon).toBe(to.lon);
|
||||
expect(JSON.parse(plane.queue)).toEqual(['EDDV']); // first leg consumed, rest kept in order
|
||||
});
|
||||
|
||||
it('grounds when fuel cannot cover the next queued leg, keeping the queue intact', async () => {
|
||||
const { inst, km, type } = await setupFlight('chain-nofuel.db');
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const nextP = fc.features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||
|
||||
// Depart with exactly the fuel for EDDF→LEMD → lands empty, cannot start LEMD→EHAM.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({
|
||||
fuel: requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km),
|
||||
queue: JSON.stringify(['EHAM']),
|
||||
})
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('available'); // grounded safely…
|
||||
expect(plane.destIcao).toBeNull();
|
||||
expect(plane.departureSimTime).toBeNull();
|
||||
expect(JSON.parse(plane.queue)).toEqual(['EHAM']); // …queue kept for refuel + re-dispatch
|
||||
});
|
||||
|
||||
it('grounds as before when the queue is empty', async () => {
|
||||
const { inst, km } = await setupFlight('chain-empty.db'); // seeded default queue '[]'
|
||||
|
||||
expect(await deliverPackages(inst, T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh))).toBe(1);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('available'); // unchanged landing behavior…
|
||||
expect(JSON.parse(plane.queue)).toEqual([]); // …and the queue stays empty
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto-slow to 1× when the last plane lands (ISS-011)', () => {
|
||||
describe('pause on landing when the last plane lands (ISS-041)', () => {
|
||||
const FROM = 'EDDF';
|
||||
const TO = 'LEMD';
|
||||
|
||||
@@ -259,19 +321,20 @@ describe('auto-slow to 1× when the last plane lands (ISS-011)', () => {
|
||||
return { inst, from, km, type };
|
||||
}
|
||||
|
||||
it('last plane lands → stored timeScale becomes 1', async () => {
|
||||
const { inst } = await setupLanding('autoslow-last.db', 1000);
|
||||
it('last plane lands → sim pauses and stored timeScale is UNCHANGED', async () => {
|
||||
const { inst } = await setupLanding('pause-last.db', 1000);
|
||||
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.timeScale).toBe(1); // persisted on the sim_state row…
|
||||
expect((await inst.db.select().from(schema.simState))[0].timeScale).toBe(1); // …and visible to the next snapshot
|
||||
expect(sim.paused).toBe(true); // persisted on the sim_state row…
|
||||
expect((await inst.db.select().from(schema.simState))[0].paused).toBe(true); // …and visible to the next snapshot
|
||||
expect(sim.timeScale).toBe(1000); // speed preserved — no auto-slow anymore (ISS-041)
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available'); // landing itself unchanged
|
||||
});
|
||||
|
||||
it('a landing while another plane is still flying → no change', async () => {
|
||||
const { inst, from, type } = await setupLanding('autoslow-other.db', 1000);
|
||||
it('a landing while another plane is still flying → no pause', async () => {
|
||||
const { inst, from, type } = await setupLanding('pause-other.db', 1000);
|
||||
// A second plane on the same route departing at T0 — arrives far after this tick's clock.
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'p-b', model: 'atr72', status: 'flying', fuel: type.maxFuel, maxFuel: type.maxFuel,
|
||||
@@ -281,32 +344,51 @@ describe('auto-slow to 1× when the last plane lands (ISS-011)', () => {
|
||||
vi.setSystemTime(T0 + 2_000);
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.timeScale).toBe(1000); // p-b still in flight — no auto-slow
|
||||
expect(sim.paused).toBe(false); // p-b still in flight — no pause (nothing would auto-unpause it)
|
||||
expect(sim.timeScale).toBe(1000);
|
||||
const byId = new Map((await inst.db.select().from(schema.planes)).map((p) => [p.id, p.status]));
|
||||
expect(byId.get('plane-starter')).toBe('available'); // the starter did land…
|
||||
expect(byId.get('p-b')).toBe('flying'); // …but the fleet is not idle
|
||||
});
|
||||
|
||||
it('already at 1× → stays 1', async () => {
|
||||
const { inst } = await setupLanding('autoslow-one.db', 1);
|
||||
it('last plane lands at scale 1 → pauses anyway, scale untouched', async () => {
|
||||
const { inst } = await setupLanding('pause-one.db', 1);
|
||||
vi.setSystemTime(T0 + 2_000); // one tick at scale 1 advances 2e3 game ms — past the T0 arrival
|
||||
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(true);
|
||||
expect(sim.timeScale).toBe(1);
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||
});
|
||||
|
||||
it('a chained plane does NOT trigger the last-plane pause (ISS-043)', async () => {
|
||||
const { inst } = await setupLanding('pause-chain.db', 1000); // full tank, arrival exactly T0
|
||||
// A queued next hop with plenty of fuel → chains on landing instead of grounding.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ queue: JSON.stringify(['EDDV']) })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(false); // still flying after the chain — no premature pause…
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying'); // …the fresh select in tickOnce counts it as airborne
|
||||
expect(plane.destIcao).toBe('EDDV');
|
||||
});
|
||||
|
||||
it('paused sim with all planes landed → no change', async () => {
|
||||
const inst = await freshDb('autoslow-paused.db');
|
||||
const inst = await freshDb('pause-paused.db');
|
||||
// The fleet is fully grounded (the seeded starter) — a paused tick must not touch the
|
||||
// scale even though "no plane in flight" holds: the trigger requires a landing this tick.
|
||||
// controls even though "no plane in flight" holds: the trigger requires a landing this tick.
|
||||
await inst.db.update(schema.simState).set({ timeScale: 1000, paused: true });
|
||||
|
||||
vi.setSystemTime(T0 + 5_000);
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.timeScale).toBe(1000); // no landing processed while paused → trigger never fires
|
||||
expect(sim.paused).toBe(true); // no landing processed while paused → trigger never fires
|
||||
expect(sim.timeScale).toBe(1000);
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||
});
|
||||
});
|
||||
|
||||
+67
-28
@@ -5,6 +5,7 @@ import * as schema from '@/lib/db/schema';
|
||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { parseIcaoQueue } from '@/lib/game/state';
|
||||
import {
|
||||
generatePackage,
|
||||
MARKET_TARGET_OPEN_PACKAGES,
|
||||
@@ -12,7 +13,7 @@ import {
|
||||
type Rng,
|
||||
type SeedAirport,
|
||||
} from '@/lib/game/seed';
|
||||
import { arrivalTimeFor, fuelAtWeighted } from './movement';
|
||||
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor } from './movement';
|
||||
|
||||
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
|
||||
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
|
||||
@@ -74,8 +75,8 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
let landedThisTick = 0;
|
||||
if (advanceMs > 0) {
|
||||
await expirePackages(inst, clockMs);
|
||||
// ISS-011: remember the landings so the tick can auto-slow to 1× when this was
|
||||
// the last plane in flight.
|
||||
// ISS-041: remember the landings so the tick can pause when this was the last
|
||||
// plane in flight.
|
||||
landedThisTick = await deliverPackages(inst, clockMs);
|
||||
await spawnOpenPackages(inst, clockMs);
|
||||
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
||||
@@ -83,17 +84,18 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
await spawnCoveragePackages(inst, clockMs);
|
||||
}
|
||||
|
||||
const sets: Partial<Pick<schema.SimStateRow, 'clockMs' | 'lastRealTickMs' | 'timeScale'>> = {
|
||||
const sets: Partial<Pick<schema.SimStateRow, 'clockMs' | 'lastRealTickMs' | 'timeScale' | 'paused'>> = {
|
||||
clockMs,
|
||||
lastRealTickMs: nowMs,
|
||||
};
|
||||
// Auto-slow (ISS-011): when ≥1 plane landed this tick and NO plane remains in flight,
|
||||
// drop the stored timeScale to 1× — persisted here so the UI slider reflects it on the
|
||||
// next snapshot. Arrival-triggered by design: a grounded fleet at high scale is left
|
||||
// alone (the player speeds up manually again; there is no auto-restore).
|
||||
if (landedThisTick > 0 && !sim.paused) {
|
||||
// Pause on landing (ISS-041): when ≥1 plane landed this tick and NO plane remains in flight,
|
||||
// pause the sim WITHOUT touching timeScale — speed is preserved for the next dispatch.
|
||||
// Arrival-triggered by design: a grounded fleet at high scale is left alone (there is no
|
||||
// auto-resume except starting a flight; see flyPlane). A paused tick never processes landings
|
||||
// (advanceMs === 0), so the trigger can only fire on an advancing tick.
|
||||
if (landedThisTick > 0) {
|
||||
const flying = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'flying'));
|
||||
if (flying.length === 0) sets.timeScale = MIN_TIME_SCALE;
|
||||
if (flying.length === 0) sets.paused = true;
|
||||
}
|
||||
|
||||
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
||||
@@ -121,12 +123,17 @@ export async function expirePackages(inst: GameDb, clockMs: number): Promise<num
|
||||
}
|
||||
|
||||
// Finalize in-flight planes whose arrival time has passed (v0.12.0 delivery):
|
||||
// ground the plane at its dest_icao with its remaining fuel, then for every
|
||||
// package bound to it and destined for that airport — 'loaded' ones still inside
|
||||
// their deadline are delivered (cash += reward + reputation gain per package),
|
||||
// 'expired' ones just unbind (no reward). Packages destined elsewhere stay loaded
|
||||
// on the plane for a later leg. Idempotent — a finalized plane leaves the
|
||||
// 'flying' state, so it can never be awarded twice. Returns planes landed.
|
||||
// for every package bound to the plane and destined for its dest_icao — 'loaded'
|
||||
// ones still inside their deadline are delivered (cash += reward + reputation
|
||||
// gain per package), 'expired' ones just unbind (no reward). Packages destined
|
||||
// elsewhere stay loaded on the plane for a later leg. Then (v0.25.0, ISS-043)
|
||||
// auto-chain: if the queue holds legs and fuel covers the first one, start it
|
||||
// immediately from the arrival airport; otherwise ground the plane there with
|
||||
// its remaining fuel (a short tank keeps the queue intact for refuel + re-dispatch).
|
||||
// Idempotent — a finalized plane either leaves the 'flying' state or starts a NEW
|
||||
// leg whose own arrival is in the future, so it can never be awarded twice.
|
||||
// Returns planes landed. NOTE: runs BEFORE tickOnce's pause check on purpose —
|
||||
// a chained plane counts as still flying there, so chaining never pauses early.
|
||||
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const [planeRows, packageRows] = await Promise.all([
|
||||
inst.db.select().from(schema.planes),
|
||||
@@ -148,19 +155,10 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
||||
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
||||
|
||||
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({
|
||||
status: 'available',
|
||||
locationIcao: to.icao,
|
||||
lat: to.lat,
|
||||
lon: to.lon,
|
||||
fuel: fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1),
|
||||
departureSimTime: null,
|
||||
destIcao: null,
|
||||
})
|
||||
.where(eq(schema.planes.id, p.id));
|
||||
const landedFuel = fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1);
|
||||
|
||||
// Deliver every bound package whose destination is the airport just reached.
|
||||
// Deliver every bound package whose destination is the airport just reached —
|
||||
// runs whether or not a queued leg chains next (ISS-043).
|
||||
const onBoard = packageRows.filter((pk) => pk.planeId === p.id && pk.destIcao === to.icao);
|
||||
for (const pk of onBoard) {
|
||||
if (pk.status === 'loaded' && clockMs <= pk.deadlineSimTime) {
|
||||
@@ -177,6 +175,47 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
||||
await inst.db.update(schema.packages).set({ planeId: null }).where(eq(schema.packages.id, pk.id));
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-chain (ISS-043): with a non-empty queue and enough fuel for the first
|
||||
// queued leg, start it immediately from `to` — same feasibility rule as flyPlane
|
||||
// (requiredFuelFor is independent of current load). Otherwise ground here; an
|
||||
// unknown ICAO in the queue simply cannot chain. The remaining queue is kept
|
||||
// intact either way so a grounded plane can refuel and re-dispatch.
|
||||
const queue = parseIcaoQueue(p.queue);
|
||||
let chainedTo: string | null = null;
|
||||
if (queue.length > 0) {
|
||||
const nextDest = queue[0];
|
||||
const next = byIcao.get(nextDest); // unknown ICAO in the queue → cannot chain
|
||||
if (next && requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, haversineKm(to.lat, to.lon, next.lat, next.lon)) <= landedFuel) {
|
||||
queue.shift();
|
||||
chainedTo = nextDest;
|
||||
}
|
||||
}
|
||||
await inst.db.update(schema.planes)
|
||||
.set(
|
||||
chainedTo
|
||||
? {
|
||||
status: 'flying',
|
||||
locationIcao: to.icao,
|
||||
lat: to.lat,
|
||||
lon: to.lon,
|
||||
fuel: landedFuel,
|
||||
destIcao: chainedTo,
|
||||
departureSimTime: clockMs, // the arrival instant — position is exactly `to`
|
||||
queue: JSON.stringify(queue),
|
||||
}
|
||||
: {
|
||||
status: 'available',
|
||||
locationIcao: to.icao,
|
||||
lat: to.lat,
|
||||
lon: to.lon,
|
||||
fuel: landedFuel,
|
||||
departureSimTime: null,
|
||||
destIcao: null,
|
||||
queue: JSON.stringify(queue),
|
||||
},
|
||||
)
|
||||
.where(eq(schema.planes.id, p.id));
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { StateSnapshot } from '@/lib/game/state';
|
||||
|
||||
// ISS-021 (v0.20.0) — shared action runner for the side panes (extracted verbatim from
|
||||
// RightPane.runAction when the On board section moved to LeftPane). POSTs an action endpoint;
|
||||
// every success returns the FULL post-action snapshot (v0.8.0 convention), pushed into the
|
||||
// shared shell state immediately via applySnapshot so the UI updates without waiting for the
|
||||
// next poll tick. A non-2xx {error} body becomes the pane's inline error AND is mirrored to
|
||||
// the shell as a bottom-right toast via onError (ISS-008 — both surfaces by design). Buttons
|
||||
// are disabled while a request is in flight, so at most one action runs per pane at a time.
|
||||
export function useGameAction(
|
||||
state: StateSnapshot | null,
|
||||
applySnapshot: (snapshot: StateSnapshot) => void,
|
||||
onError?: (message: string) => void,
|
||||
): { runAction: (path: string, body?: unknown) => Promise<void>; busy: boolean; actionError: string | null } {
|
||||
const [busy, setBusy] = useState(false);
|
||||
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
||||
// snapshot prop changes every tick) or the next successful action.
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (state !== null) setActionError(null);
|
||||
}, [state]);
|
||||
|
||||
const runAction = useCallback(
|
||||
async (path: string, body?: unknown) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
const data = (await res.json()) as StateSnapshot & { error?: string };
|
||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||
setActionError(null);
|
||||
applySnapshot(data);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setActionError(message); // inline pane error stays…
|
||||
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[applySnapshot, busy, onError],
|
||||
);
|
||||
|
||||
return { runAction, busy, actionError };
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "flight-ops",
|
||||
"version": "0.19.1",
|
||||
"version": "0.25.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3000",
|
||||
|
||||
Reference in New Issue
Block a user