Compare commits

...
14 Commits
Author SHA1 Message Date
kamilkrzywda e18d39edd0 Merge pull request 'v0.23.0 — Move Refuel-to-full from market into left pane next to Relocate (#35)' (#42) from ui/move-refuel-to-left-pane into master
CI / build + unit + e2e (push) Successful in 7m58s
2026-09-20 10:34:43 +02:00
kamilkrzywda a7150a1062 Move Refuel-to-full from market into left pane next to Relocate (#35)
CI / build + unit + e2e (pull_request) Successful in 6m52s
2026-09-20 08:25:57 +00:00
kamilkrzywda 8eeef401ae Merge pull request 'v0.22.2 — commit ORCHESTRATOR.md manual' (#38) from docs/orchestrator-md-v2 into master
CI / build + unit + e2e (push) Successful in 6m9s
2026-09-20 09:57:56 +02:00
kamilkrzywda f273d385c2 docs: make ORCHESTRATOR.md durable — drop specifics that rot (test counts, CI run numbers, paint values)
CI / build + unit + e2e (pull_request) Successful in 6m29s
2026-09-20 07:50:11 +00:00
kamilkrzywda 3b02c7feac docs: document GITEA_TOKEN in .env.example
CI / build + unit + e2e (pull_request) Failing after 7m17s
2026-09-20 07:41:55 +00:00
kamilkrzywda 1ba70ebbf3 docs: commit ORCHESTRATOR.md manual (token via gitignored .env)
CI / build + unit + e2e (pull_request) Successful in 6m32s
2026-09-20 07:34:04 +00:00
kamilkrzywda 08a819e44c Merge pull request 'v0.22.1 — gitignore local-only ORCHESTRATOR.md' (#37) from fix/gitignore-local-docs into master
CI / build + unit + e2e (push) Successful in 6m27s
2026-09-20 09:06:59 +02:00
kamilkrzywda 50a9147665 chore: gitignore local-only ORCHESTRATOR.md manual
CI / build + unit + e2e (pull_request) Successful in 6m30s
2026-09-20 06:58:42 +00:00
kamilkrzywda 5391636979 Merge pull request 'v0.22.0 — ISS-022/025/027 hover route trace (job list, on-board rows, relocation panel)' (#34) from feat/hover-trace into master
CI / build + unit + e2e (push) Failing after 7m10s
2026-09-20 03:58:03 +02:00
kamilkrzywda ab79d9b17f fix(e2e): renderedFeatures — evaluate maplibre geometry getter in-page before Playwright serialization drops it
CI / build + unit + e2e (pull_request) Successful in 7m28s
2026-09-20 01:50:23 +00:00
kamilkrzywda 505a58b4fe fix(e2e): expectHoverRoute — ignore queryRenderedFeatures artifacts without LineString geometry (CI run #70)
CI / build + unit + e2e (pull_request) Failing after 7m49s
2026-09-20 01:22:23 +00:00
kamilkrzywda 2655ef81c8 fix: hover-route line not drawn in e2e — MapLibre clips queried lines across tiles and quantizes their coordinates (strict single-feature equality never matched)
CI / build + unit + e2e (pull_request) Failing after 6m44s
2026-09-19 22:52:12 +00:00
kamilkrzywda ac4e3fa316 feat: v0.22.0 — ISS-022 target airport distinct-color ring on job-list / relocation hover
CI / build + unit + e2e (pull_request) Failing after 8m51s
2026-09-19 22:01:02 +00:00
kamilkrzywda f2dbad5e03 feat: v0.22.0 — ISS-022/025/027 hover route trace on job list, on-board rows and relocation panel 2026-09-19 21:47:00 +00:00
13 changed files with 539 additions and 63 deletions
+1
View File
@@ -1 +1,2 @@
# No environment variables required yet. # No environment variables required yet.
GITEA_TOKEN=gitea-api-token
+21
View File
@@ -1,5 +1,26 @@
# Changelog # Changelog
## 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 ## 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 - **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) - 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)
+69
View File
@@ -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).
+85 -2
View File
@@ -102,6 +102,11 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null); const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
const [relocateDestIcao, setRelocateDestIcao] = 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 // 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; // 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 // on failure airportOptions stays null and the Relocate button simply remains disabled. Moved here
@@ -205,6 +210,16 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
const relocateDest = const relocateDest =
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null; 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 // 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 // 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 // user releases the slider (browsers fire a native 'change' on release). The server's
@@ -385,7 +400,17 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
{cargo.map((pkg) => { {cargo.map((pkg) => {
const penalty = abandonPenalty(pkg, clockMs); const penalty = abandonPenalty(pkg, clockMs);
return ( return (
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row"> // 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 <button
type="button" type="button"
data-testid={`fly-to-${pkg.id}`} data-testid={`fly-to-${pkg.id}`}
@@ -438,7 +463,21 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
{/* ISS-023 (v0.21.0): moved here from the right-pane market row — it belongs with {/* 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. */} everything else about our planes, between On board and Time. */}
<section className="pane-section"> {/* 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> <h3 className="pane-heading">Relocate</h3>
{/* ISS-010 (v0.18.0): relocate a grounded plane — the fly endpoint already allows pure {/* 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. */} repositioning, this row just exposes it for planes with nothing on board. */}
@@ -483,6 +522,50 @@ export default function LeftPane({ state, loading, error, onRefresh, applySnapsh
</div> </div>
</section> </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"> <section className="pane-section">
<h3 className="pane-heading">Time</h3> <h3 className="pane-heading">Time</h3>
<p data-testid="sim-clock" className="sim-clock"> <p data-testid="sim-clock" className="sim-clock">
+78 -6
View File
@@ -8,7 +8,7 @@ import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvai
import type { GeoJsonFeatureCollection } from '../lib/airports'; import type { GeoJsonFeatureCollection } from '../lib/airports';
import type { StateSnapshot } from '../lib/game/state'; import type { StateSnapshot } from '../lib/game/state';
import type { HoverTarget } from './hoverTypes'; import type { HoverTarget } from './hoverTypes';
import { planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData'; import { hoverRouteGeoJson, planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
import { weatherFor } from '../lib/weather'; import { weatherFor } from '../lib/weather';
import { approxLocalTime } from '../lib/localTime'; import { approxLocalTime } from '../lib/localTime';
@@ -33,6 +33,15 @@ const ROUTES_LEGS_LAYER_ID = 'routes-legs';
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight'; const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight'; const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-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 { function escapeHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -43,7 +52,8 @@ interface MapProps {
// route lines. Null until the first successful poll. // route lines. Null until the first successful poll.
state?: StateSnapshot | null; state?: StateSnapshot | null;
// ISS-002 (v0.15.0): the side panels' hover target — highlights the matching plane // 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; hovered?: HoverTarget | null;
// ISS-010 (v0.18.0): push an action endpoint's full response snapshot into the shared // 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. // shell state — same callback RightPane receives, used by the airport popup's Relocate row.
@@ -101,22 +111,49 @@ export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
const map = mapRef.current; const map = mapRef.current;
if (!map) return; if (!map) return;
const h = hoveredRef.current; const h = hoveredRef.current;
// The empty-string sentinel matches nothing: no feature has id/icao ''. // The empty-string sentinel matches nothing: no feature has id/icao ''. A package hover may
const planeId = h && h.kind === 'plane' ? h.id : ''; // 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)) { if (map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]); map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]);
} }
if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) { if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]); map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]);
} }
const originIcao = h && h.kind === 'package' ? h.originIcao : ''; // ISS-022/025/027: the hover route trace — one great-circle line for any target carrying two
const destIcao = h && h.kind === 'package' ? h.destIcao : ''; // 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) {
void hoverSource.setData(hoverRouteGeoJson(fromIcao, toIcao, airportsIndexRef.current ?? new Map()));
}
// 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)) { if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
map.setFilter( map.setFilter(
AIRPORTS_HIGHLIGHT_LAYER_ID, AIRPORTS_HIGHLIGHT_LAYER_ID,
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]], ['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(() => { useEffect(() => {
@@ -384,6 +421,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 // Layer-scoped listeners survive setStyle (they filter by layer id at event
// time), so off+on with the same reference re-wires without duplicating. // time), so off+on with the same reference re-wires without duplicating.
map.off('click', AIRPORTS_LAYER_ID, onAirportClick); map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
+3 -44
View File
@@ -116,10 +116,11 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane). // user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
const [buyModelId, setBuyModelId] = useState<string | null>(null); const [buyModelId, setBuyModelId] = useState<string | null>(null);
const [sellPlaneId, setSellPlaneId] = useState<string | null>(null); const [sellPlaneId, setSellPlaneId] = useState<string | null>(null);
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
// ISS-023 (v0.21.0): the Relocate row moved to the left pane — it belongs with everything else // 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. // 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) { if (loading && !state) {
return ( return (
@@ -139,15 +140,9 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
const grounded = state.planes.filter((p) => p.status === 'available'); 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 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;
// Previews computed client-side from the snapshot's catalog + economy constants (v0.10.0). // 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 sellEntry = sellPlane ? catalog.find((e) => e.model === sellPlane.model) : undefined;
const sellPayout = sellEntry ? Math.round(sellEntry.price * state.sellFraction * 100) / 100 : null; const sellPayout = sellEntry ? Math.round(sellEntry.price * state.sellFraction * 100) / 100 : null;
const refuelCost = refuelPlane ? (refuelPlane.maxFuel - refuelPlane.fuel) * state.fuelPricePerL : null;
return ( return (
<aside data-testid="right-pane" className="pane right-pane"> <aside data-testid="right-pane" className="pane right-pane">
@@ -262,44 +257,8 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
</button> </button>
</div> </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-023 (v0.21.0): the Relocate row moved to the left pane's "Relocate" section. */} {/* 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> </section>
{actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>} {actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>}
+6 -1
View File
@@ -1,7 +1,12 @@
// ISS-002 — what a side-panel hover highlights on the map (v0.15.0): a plane marker // 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 // (+ 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. // 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 = export type HoverTarget =
| { kind: 'plane'; id: string } | { kind: 'plane'; id: string }
| { kind: 'package'; originIcao: string; destIcao: string }; | { kind: 'package'; originIcao: string; destIcao: string; planeId?: string }
| { kind: 'route'; fromIcao: string; toIcao: string };
+193 -2
View File
@@ -6,6 +6,10 @@ import { test, expect, type Page } from '@playwright/test';
// highlight layers (planes-highlight / routes-highlight / airports-highlight), each filtered // 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 // 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. // 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 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 const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
@@ -113,12 +117,30 @@ async function waitForAirportCount(page: Page): Promise<void> {
} }
// Rendered features of the given layers in the current viewport, [] until the map exists. // 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[]) => { return page.evaluate((ls: string[]) => {
const m = (window as any).__flightMap; const m = (window as any).__flightMap;
if (!m) return []; if (!m) return [];
try { 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 { } catch {
return []; return [];
} }
@@ -160,6 +182,56 @@ async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
await page.waitForTimeout(300); 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('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 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 await flyHomeViaApi(page); // deterministic: the starter sits at EDDF, inside the initial view
@@ -230,6 +302,7 @@ test('hovering an open package highlights its endpoint airports', async ({ page
await fitToAirports(page, [HUB, DEST]); await fitToAirports(page, [HUB, DEST]);
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0); expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
expect(await renderedFeatures(page, ['airports-target-highlight'])).toHaveLength(0);
await row.hover(); await row.hover();
await expect.poll(async () => { await expect.poll(async () => {
@@ -238,11 +311,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' }) }, { timeout: 15_000, message: 'waiting for the airports-highlight layer to show both endpoints' })
.toBe(JSON.stringify([HUB, DEST].sort())); .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 unhover(page);
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, { await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
timeout: 15_000, timeout: 15_000,
message: 'waiting for the highlight to clear after mouseleave', message: 'waiting for the highlight to clear after mouseleave',
}).toBe(0); }).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 }) => { test('hovering an on-board block of a flying plane highlights its route', async ({ page }) => {
+8
View File
@@ -75,6 +75,14 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toBeVisible(); await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toBeVisible();
// …and no longer in the right pane. // …and no longer in the right pane.
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0); 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 }) => { test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
+9 -5
View File
@@ -5,8 +5,9 @@ import { expect, test } from '@playwright/test';
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list // 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 + // (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 // abandon buttons (penalty preview from the same
// formula as the server); flying planes show their current leg; market buy/sell/refuel previews // formula as the server); flying planes show their current leg; market buy/sell previews match
// match the catalog + economy constants exposed in /api/state. Packages are created via // 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. // 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 const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
@@ -300,7 +301,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
.toBe(true); .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 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) await flyHomeViaApi(page); // grounded starter at EDDF (tank partial after the previous test's flight)
@@ -325,6 +326,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; const payout = Math.round(entry.price * body.sellFraction * 100) / 100;
await expect(page.getByTestId('market-sell-payout')).toContainText(eur(payout)); 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… // Refuel through the pane: the flight genuinely burned fuel…
if (starter.fuel < starter.maxFuel) { if (starter.fuel < starter.maxFuel) {
const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * 100) / 100; const expectedCost = Math.round((starter.maxFuel - starter.fuel) * body.fuelPricePerL * 100) / 100;
@@ -348,7 +352,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 test.setTimeout(300_000); // self-heal + one long flight each way at scale 1000
await flyHomeViaApi(page); await flyHomeViaApi(page);
@@ -403,7 +407,7 @@ 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.account.cash).toBeCloseTo(cashBefore - expectedCost, 6);
expect(post.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(fuelBefore + liters, 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'); 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 // Restore: fly home — pkg2's destination IS the hub, so it delivers on arrival. The tank holds
+37 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import type { StateSnapshot } from './game/state'; import type { StateSnapshot } from './game/state';
import { planesGeoJson, routesGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData'; import { planesGeoJson, routesGeoJson, hoverRouteGeoJson, greatCircleArc, ROUTE_ARC_SEGMENTS, type AirportCoord } from './mapData';
import { haversineKm } from './geo'; import { haversineKm } from './geo';
const AIRPORTS = new Map<string, AirportCoord>([ const AIRPORTS = new Map<string, AirportCoord>([
@@ -140,6 +140,42 @@ 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('greatCircleArc (v0.12.2 — curved route traces)', () => { describe('greatCircleArc (v0.12.2 — curved route traces)', () => {
it('samples >2 points with the endpoints exactly at the airport coords', () => { it('samples >2 points with the endpoints exactly at the airport coords', () => {
const arc = greatCircleArc(AIRPORTS.get('EDDF')!, AIRPORTS.get('EHAM')!); const arc = greatCircleArc(AIRPORTS.get('EDDF')!, AIRPORTS.get('EHAM')!);
+27
View File
@@ -85,6 +85,33 @@ export function greatCircleArc(from: AirportCoord, to: AirportCoord): [number, n
return coords; 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
},
],
};
}
// One LineString per FLYING plane — its current leg from locationIcao to dest_icao. // 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 // 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 // dataset is skipped, never guessed. The line is sampled along the great circle
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "flight-ops", "name": "flight-ops",
"version": "0.21.0", "version": "0.23.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev -p 3000", "dev": "next dev -p 3000",