Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb69359a38 | ||
|
|
3acf471295 | ||
|
|
7d2f8f07c8 | ||
|
|
05d956f71b | ||
|
|
ae1cb93a4f | ||
|
|
687e4f2169 | ||
|
|
a801311fc5 | ||
|
|
1dc5beb0dd | ||
|
|
b6bfcedaf6 | ||
|
|
4c99dbe550 | ||
|
|
e6d7e03934 | ||
|
|
08094a00e2 | ||
|
|
eff934a1cc | ||
|
|
3209dea425 | ||
|
|
3b6506832f | ||
|
|
7db8fcc549 | ||
|
|
d65d4e45b9 | ||
|
|
bd00b2b4c4 | ||
|
|
0c9279818a | ||
|
|
eb2e7a7430 | ||
|
|
97f82dd464 | ||
|
|
aa5eabeb78 | ||
|
|
35493f92f0 | ||
|
|
e694011302 | ||
|
|
0bfbd2a2e8 | ||
|
|
b112339dd3 | ||
|
|
f89f0407ae | ||
|
|
14aaf26900 | ||
|
|
c30f5f650f | ||
|
|
54c7a0c5f5 | ||
|
|
d0149c6ab3 | ||
|
|
579d425b64 | ||
|
|
543aad310c | ||
|
|
5ee0d89826 | ||
|
|
47381f2011 | ||
|
|
775b0e479a | ||
|
|
0c921556fb | ||
|
|
db998a9dfb |
+5
-2
@@ -1,4 +1,6 @@
|
|||||||
node_modules
|
# node_modules is intentionally IN the build context: the Dockerfile copies it straight
|
||||||
|
# into the image (deps are installed by the CI job / dev host, which have working network;
|
||||||
|
# the runner's dind daemon has broken outbound DNS for build containers).
|
||||||
.next
|
.next
|
||||||
data/*.db
|
data/*.db
|
||||||
# game state DB (v0.6.0): host-side, volume-mounted at runtime — never baked in
|
# game state DB (v0.6.0): host-side, volume-mounted at runtime — never baked in
|
||||||
@@ -8,7 +10,8 @@ test-results
|
|||||||
.git
|
.git
|
||||||
.env
|
.env
|
||||||
.codenomad
|
.codenomad
|
||||||
# e2e harness: @playwright/test is a host-global install, not a project dependency
|
# e2e harness: the suite runs on the host / CI job, never inside the image
|
||||||
|
# (@playwright/test is a devDependency of the runner, excluded from prod-deps)
|
||||||
e2e
|
e2e
|
||||||
playwright.config.ts
|
playwright.config.ts
|
||||||
# docs/deployment files never affect the app build — excluding them keeps
|
# docs/deployment files never affect the app build — excluding them keeps
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
pull_request:
|
||||||
|
branches: [master]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ci:
|
||||||
|
name: build + unit + e2e
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# The runner provides a working docker CLI out of the box (full-dind) — no endpoint
|
||||||
|
# resolution needed. Job and app containers share the daemon, so put them on one
|
||||||
|
# user-defined network with a pinned subnet; the app gets a STATIC IP (172.39.0.10,
|
||||||
|
# declared in docker-compose.ci.yml) because Chromium got ERR_SSL_PROTOCOL_ERROR via
|
||||||
|
# the DNS alias while node-side HTTP to the same name worked — bypassing DNS removes
|
||||||
|
# that variable entirely. A stale network with a different subnet is recreated.
|
||||||
|
- name: Prepare e2e network
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
# Interrupted runs skip the end-of-run cleanup, leaking a USED DB volume into later
|
||||||
|
# runs (tests assume seeded state) — drop it so every run starts fresh.
|
||||||
|
docker volume rm flight-ci_flight-db 2>/dev/null || true
|
||||||
|
SUBNET=172.39.0.0/24
|
||||||
|
if docker network inspect flight-ci-e2e >/dev/null 2>&1; then
|
||||||
|
cur=$(docker network inspect flight-ci-e2e --format '{{(index .IPAM.Config 0).Subnet}}')
|
||||||
|
if [ "$cur" != "$SUBNET" ]; then
|
||||||
|
echo "stale flight-ci-e2e with subnet $cur — recreating with $SUBNET"
|
||||||
|
docker network rm flight-ci-e2e || true
|
||||||
|
docker network create --subnet "$SUBNET" flight-ci-e2e
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
docker network create --subnet "$SUBNET" flight-ci-e2e
|
||||||
|
fi
|
||||||
|
if ! docker network connect flight-ci-e2e "$(hostname)"; then
|
||||||
|
echo "::error::failed to attach job container '$(hostname)' to flight-ci-e2e — the job must run in a container on the shared daemon (check runner config)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
docker network inspect flight-ci-e2e --format 'containers on flight-ci-e2e: {{range .Containers}}{{.Name}} {{end}}'
|
||||||
|
echo "E2E_BASE_URL=http://172.39.0.10:3000" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Setup Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
|
||||||
|
# bun drives installs (repo ships bun.lock, no package-lock.json); pinned to 1.4.2.
|
||||||
|
# Retried: the runner's outbound network/DNS is flaky (transient EAI_AGAIN seen in CI).
|
||||||
|
- name: Install bun
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
ok=0
|
||||||
|
for i in 1 2 3; do
|
||||||
|
if npm i -g bun@1.4.2; then ok=1; break; fi
|
||||||
|
echo "::warning::bun install attempt $i/3 failed (likely transient network) — retrying in 5s" >&2
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
[ "$ok" = "1" ] || { echo "::error::bun install failed after 3 attempts" >&2; exit 1; }
|
||||||
|
bun --version
|
||||||
|
|
||||||
|
# Job-level dep cache via the runner's built-in cache server. continue-on-error on
|
||||||
|
# both steps: an unreachable/broken cache server must never break the run.
|
||||||
|
- name: Restore deps cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
node_modules
|
||||||
|
$HOME/.bun/install/cache
|
||||||
|
key: ${{ runner.os }}-deps-bun-${{ hashFiles('bun.lock') }}
|
||||||
|
|
||||||
|
# Retried: the runner's outbound network/DNS is flaky (transient EAI_AGAIN seen in CI).
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
ok=0
|
||||||
|
for i in 1 2 3; do
|
||||||
|
if bun install --frozen-lockfile; then ok=1; break; fi
|
||||||
|
echo "::warning::dependency install attempt $i/3 failed (likely transient network) — retrying in 5s" >&2
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
[ "$ok" = "1" ] || { echo "::error::dependency install failed after 3 attempts" >&2; exit 1; }
|
||||||
|
|
||||||
|
# No explicit save step: caches marked by the restore steps are uploaded automatically at job end.
|
||||||
|
|
||||||
|
# Map e2e tests abort ALL *.openfreemap.org traffic (page.route → route.abort()), assuming
|
||||||
|
# styles/fonts/sprites are SELF-HOSTED from /styles, /fonts, /sprites — locally that pack is
|
||||||
|
# produced by `npm run assets:download` and reaches the app via the compose volume mount.
|
||||||
|
# CI must reproduce it or lib/mapStyles.ts probes /map-assets-manifest.json, finds nothing,
|
||||||
|
# falls back to remote OFM styles — which the tests abort → style never loads (the
|
||||||
|
# deterministic map.spec.ts wheel-zoom + style-switcher failures). The script needs no env
|
||||||
|
# vars/args and writes into ./public (git-ignored, docker-excluded; the app container gets
|
||||||
|
# it via the volume mount in docker-compose.ci.yml).
|
||||||
|
- name: Restore map assets cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
path: public/
|
||||||
|
key: ${{ runner.os }}-map-assets-${{ hashFiles('scripts/download-map-assets.mjs') }}
|
||||||
|
|
||||||
|
# Retried: the runner's uplink is flaky (same transient EAI_AGAIN pattern as dep install).
|
||||||
|
# The job-end cache upload seeds public/ for future runs; a partial pack without
|
||||||
|
# map-assets-manifest.json is harmless — the app probes that manifest and falls back to
|
||||||
|
# remote styles when it's missing.
|
||||||
|
- name: Download map assets (retries)
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
ok=0
|
||||||
|
for i in 1 2 3 4 5 6; do
|
||||||
|
if npm run assets:download; then ok=1; break; fi
|
||||||
|
echo "::warning::map assets download attempt $i/6 failed (likely transient network) — retrying in 5s" >&2
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
[ "$ok" = "1" ] || { echo "::error::map assets download failed after 6 attempts" >&2; exit 1; }
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: npm run build
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: npx vitest run
|
||||||
|
|
||||||
|
# Browsers run locally in CI (PW_REMOTE_BROWSER=0 below): the shared remote browser
|
||||||
|
# server at 192.168.1.4 cannot reach a stack inside dind, and local chromium keeps
|
||||||
|
# the job self-contained.
|
||||||
|
# Browser binaries (~187 MiB) cached across runs: the runner's uplink is flaky and
|
||||||
|
# cdn.playwright.dev downloads time out mid-transfer; once seeded, installs skip the download.
|
||||||
|
- name: Restore browser cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
path: $HOME/.cache/ms-playwright
|
||||||
|
key: ${{ runner.os }}-pw-browsers-${{ hashFiles('package.json') }}
|
||||||
|
|
||||||
|
# Retried: cdn.playwright.dev is flaky from this runner — Playwright's internal 5-retry
|
||||||
|
# window (~40-90s) is often not enough, but runs get through with a longer one. Progress
|
||||||
|
# accumulates across attempts: playwright skips already-installed browsers.
|
||||||
|
- name: Install browsers (local)
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
ok=0
|
||||||
|
for i in 1 2 3 4 5 6; do
|
||||||
|
if npx playwright install --with-deps chromium; then ok=1; break; fi
|
||||||
|
echo "::warning::browser install attempt $i/6 failed (flaky cdn.playwright.dev) — retrying in 5s" >&2
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
[ "$ok" = "1" ] || { echo "::error::browser install failed after 6 attempts" >&2; exit 1; }
|
||||||
|
|
||||||
|
# Cache the base image on the shared daemon up front: a single loud failure here
|
||||||
|
# beats a 6-minute BuildKit "failed to solve" when the daemon's outbound net is down.
|
||||||
|
- name: Pull e2e base image
|
||||||
|
run: docker pull node:22-slim
|
||||||
|
|
||||||
|
# Pre-build the e2e image with retries (flaky runner network); the E2E step's own
|
||||||
|
# build then becomes a fast no-op. Plain progress keeps BuildKit output visible.
|
||||||
|
- name: Build e2e image (retries)
|
||||||
|
run: |
|
||||||
|
set -u
|
||||||
|
ok=0
|
||||||
|
for i in 1 2 3; do
|
||||||
|
if docker compose -f docker-compose.ci.yml -p flight-ci build --progress=plain; then ok=1; break; fi
|
||||||
|
echo "::warning::e2e image build attempt $i/3 failed (likely transient network) — retrying in 5s" >&2
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
[ "$ok" = "1" ] || { echo "::error::e2e image build failed after 3 attempts" >&2; exit 1; }
|
||||||
|
|
||||||
|
# E2E against an isolated stack on the shared daemon — never the production instance.
|
||||||
|
# docker-compose.ci.yml joins the flight-ci-e2e network prepared above; project name
|
||||||
|
# flight-ci keeps it distinct from production. E2E_DEPLOY_CMD makes the config's
|
||||||
|
# webServer block deploy + wait for readiness (http://app:3000 via service DNS);
|
||||||
|
# E2E_COMPOSE_ARGS points state.spec.ts' mid-run `docker compose restart flight` at
|
||||||
|
# the same file + project. E2E_BASE_URL comes from GITHUB_ENV (Prepare e2e network).
|
||||||
|
- name: E2E (isolated stack in dind)
|
||||||
|
env:
|
||||||
|
PW_REMOTE_BROWSER: "0"
|
||||||
|
# Build separately with plain progress so BuildKit step output is visible in the
|
||||||
|
# job log (auto progress hides it). Playwright's webServer needs a long-running
|
||||||
|
# command — `up -d` returns immediately and triggers "exited early"; `logs -f`
|
||||||
|
# keeps it alive, streams app logs into CI output for debugging, and is killed with
|
||||||
|
# the job (an orphaned `logs -f` dies on its own when cleanup removes the container).
|
||||||
|
E2E_DEPLOY_CMD: "docker compose -f docker-compose.ci.yml -p flight-ci build --progress=plain && docker compose -f docker-compose.ci.yml -p flight-ci up -d && docker compose -f docker-compose.ci.yml -p flight-ci logs -f"
|
||||||
|
E2E_COMPOSE_ARGS: "-f docker-compose.ci.yml -p flight-ci"
|
||||||
|
# Chromium honors proxy env vars on Linux (node-side HTTP does not) — keep the
|
||||||
|
# in-network app host out of any proxy path.
|
||||||
|
NO_PROXY: app,localhost,127.0.0.1,.kkhost.pl
|
||||||
|
no_proxy: app,localhost,127.0.0.1,.kkhost.pl
|
||||||
|
# Connectivity diagnostics now run post-deploy in e2e/ci-diagnostics.ts (globalSetup).
|
||||||
|
# --reporter=list prints each test as it completes (name + ✓/× + duration) for progress
|
||||||
|
# visibility in the job log; failure error context/snapshots are unchanged.
|
||||||
|
run: npx playwright test --reporter=list
|
||||||
|
|
||||||
|
# The daemon is shared with production — never leave our stack or network behind.
|
||||||
|
# -v drops the named DB volume so every run seeds fresh (no schema drift between PRs).
|
||||||
|
- name: Cleanup e2e stack + network
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
docker compose -f docker-compose.ci.yml -p flight-ci down --remove-orphans -v || true
|
||||||
|
docker network remove flight-ci-e2e 2>/dev/null || true
|
||||||
@@ -2,14 +2,17 @@
|
|||||||
|
|
||||||
## Change process (mandatory)
|
## 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.
|
||||||
2. **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).
|
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. **Version bump** — the version is updated in `package.json`.
|
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. **Commit + tag** — a commit is created for each change, tagged with the version (e.g. `v0.1.0`), push it to remote repo.
|
4. **Version bump** — the version is updated in `package.json`.
|
||||||
|
5. **CI must pass** — the PR's pipeline (build → unit tests → e2e, `.gitea/workflows/ci.yml`) must be green before merging. CI never deploys to production; its e2e runs against an isolated stack inside dind.
|
||||||
|
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)
|
## E2E tests (mandatory)
|
||||||
1. **Docker compose instance is the app under test** — e2e always runs against the docker-compose build behind Traefik (`https://flight.dev.kkhost.pl`), never a local `next dev` on :3000 (dev builds don't render for non-loopback clients, and a second instance splits state).
|
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** — deploy current code first: `docker compose up -d --build`.
|
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** — tests run through the shared Playwright server at `192.168.1.4:3000` (Docker image tag must match this repo's @playwright/test version); plain `npx playwright test` handles deploy + readiness + remote connect (see `playwright.config.ts`).
|
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.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
1. **Live base URL** — `https://flight.dev.kkhost.pl` (the docker-compose build behind Traefik).
|
1. **Live base URL** — `https://flight.dev.kkhost.pl` (the docker-compose build behind Traefik).
|
||||||
|
|||||||
@@ -1,5 +1,74 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.16.1 — 2026-09-19 14:00
|
||||||
|
- **Smooth client-side sim clock with per-snapshot re-sync (ISS-007).** The left-pane "Time" display used to jump once per 1 s poll because it rendered the snapshot's `clockMs` verbatim. It now ticks smoothly on the client between polls: new hook `lib/useSimClock.ts` keeps an anchor `{clockMs, at, timeScale, paused}` and re-derives the display clock every ~100 ms as `anchor.clockMs + (now − at) × timeScale` — exactly the server's own tick model (`tickOnce`: real-time × timeScale), so client extrapolation mirrors authoritative game time. Every new snapshot re-anchors to server truth, bounding any drift by network latency only; while paused the display is frozen at the anchor value (advance 0). The pure core `advanceSimClock(anchor, nowMs)` is exported and unit-tested in node
|
||||||
|
- **LeftPane consumes it for the `sim-clock` paragraph ONLY** (`components/LeftPane.tsx`): fed with EFFECTIVE controls `{timeScale: pendingScale ?? snapshot scale, paused}` so a slider drag or pause click takes effect on click/drag without waiting for a confirming snapshot; the `(paused)` suffix keeps coming from the effective paused flag. Right-pane deadline/penalty previews are untouched — they stay computed from the snapshot's `clockMs` (deterministic against server truth)
|
||||||
|
- No server or OpenAPI changes — display-only client work
|
||||||
|
- Tests: unit — new suite in `lib/useSimClock.test.ts` pins the extrapolation math (exact elapsed × scale advance, frozen while paused at any scale, zero-elapsed identity, clock-skew clamp never goes backwards, mirrors the tickOnce formula under the 2 s clamp). e2e (`panes.spec.ts`) — new test: at scale 1000 sample `sim-clock` three times ~1.3 s apart real time and assert the displayed clock strictly advances between CONSECUTIVE samples (with poll-only rendering a pair could straddle zero snapshots and not change), plus format check and a total-advance sanity bound
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
|
## v0.16.0 — 2026-09-19 12:18
|
||||||
|
- **Weight-proportional fuel burn (ISS-005, part A).** Fuel no longer burns at a constant L/km — the instantaneous rate is proportional to total weight, `r(F) = k·(We + ρF)` L/km with We the empty weight and ρ = 0.8 kg/L (Jet-A1), so a heavier plane burns more per km and a tank gets lighter as it empties. The constant `k` is calibrated so a FULL tank burns exactly the catalog's old `burnPerKm`, keeping full-tank departure behavior identical to before; divergence only grows in flight as fuel drops off. Closed forms of `dF/dx = −k(We + ρF)` live in `lib/sim/movement.ts` (single source of truth):
|
||||||
|
- `fuelAtWeighted(startFuel, burnPerKm, emptyWeightKg, maxFuel, distanceKm, progress)` — fuel remaining after flying `progress` of the leg (replaces the old constant-rate `fuelAt`, which is removed)
|
||||||
|
- `requiredFuelFor(burnPerKm, emptyWeightKg, maxFuel, distanceKm)` — liters needed to cover the distance arriving empty, independent of starting load; a leg is flyable iff current fuel ≥ this and fits at all iff it ≤ tank capacity
|
||||||
|
- `burnRateConstant(...)` + exported `FUEL_DENSITY_KG_PER_L` (0.8)
|
||||||
|
- **Catalog gains `emptyWeightKg`** (`lib/game/catalog.ts`, ATR 72-600 OEW ≈ 9300 kg), exposed in the snapshot's `catalog[]` so clients can mirror the model; OpenAPI `CatalogEntry` follows
|
||||||
|
- **All three burn call sites moved to the weighted model**: landing fuel on arrival (`lib/sim/engine.ts`), live in-flight fuel in the state snapshot (`lib/game/state.ts`), and fly validation (`lib/game/actions.ts` — a leg now needs `requiredFuelFor`, not `burnPerKm × km`)
|
||||||
|
- **Refuel "just enough for the loaded package" (ISS-005, part B).** `POST /api/planes/{planeId}/refuel` takes an OPTIONAL JSON body `{ mode?: 'full' | 'forFlight', packageId?: string }`: no body or `mode:'full'` is exactly today's fill-to-max behavior; `mode:'forFlight'` adds just enough fuel to fly that loaded package's destination leg — liters = `requiredFuelFor(haversine(plane → pkg.destIcao)) − current fuel`, 409 if the package isn't loaded on this plane / is expired, or the leg doesn't fit even a full tank; bad bodies (unknown field/mode, forFlight without packageId) are 400. OpenAPI gains `RefuelRequest` + the 400
|
||||||
|
- **UI** (`components/RightPane.tsx`): each on-board cargo row gets a "Refuel" button (`refuel-for-{pkg.id}` → `{mode:'forFlight', packageId}`, disabled while flying or busy, mirroring fly-to/abandon); the market fill-up button is renamed **"Refuel to full"** (testid `market-refuel` and behavior unchanged)
|
||||||
|
- Tests: unit — new weighted-burn suite in `lib/sim/movement.test.ts` (full-tank calibration ≈ old constant, closed form vs numeric integration of r(F), F_req monotonic + empty-arrival identity, lighter-start burns less, clamping); `refuelPlane` forFlight cases in `lib/game/actions.test.ts` (exact liters/cost, no-op when enough, 409 not-loaded/expired/doesn't-fit via the ~7670 km UNNT↔LPPD pair, 404 unknown package, 400 missing packageId); refuel route body-validation tests; `lib/openapi.test.ts` updated (optional RefuelRequest, errorCodes `['400','404','409']`, CatalogEntry.emptyWeightKg). Adjusted where the model legitimately shifts numbers: landing-fuel assertions in `lib/sim/engine.test.ts` and `e2e/actions.spec.ts` now use the weighted closed form; the e2e "return leg unfuelable" scenario is reworked — under weight-proportional burn a full tank covers the EDDF↔LEZL round trip (the plane lightens as it flies), so the 409 insufficient-fuel assertion moves to the SECOND outbound after landing back with a partial tank
|
||||||
|
- e2e (`right-pane.spec.ts`): new test — fly the longest hub leg on a full tank, load a package back to the hub at the far end, click the row "Refuel" and assert via the endpoint's own response snapshot that cash drops by exactly L×price and fuel rises by exactly L (L from the mirrored closed form); also asserts the market button label is "Refuel to full". `e2e/api.spec.ts` path list unchanged
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Fix (CI run #40): forFlight refuel leaves an exactly-feasible tank, and the new e2e's premise corrected.** The right-pane e2e picked the dataset's absolute farthest airport from EDDF — UNNT at ~4803 km, whose leg needs ~6955 L > the 6300 L tank (max range from empty is ~4436 km) — so the full-tank fly rightly 409'd; `farthestToHub` becomes `farthestFlyableToHub`, picking the farthest airport whose leg still fits a full tank (UWUU, ~3195 km). Server hardening in the same area: forFlight now sets fuel to EXACTLY `requiredFuelFor(...)` instead of `fuel + liters` — that sum is not guaranteed ≥ R in IEEE754 (`f + fl(R − f)` can round a hair below), and flyPlane's strict comparison would then 409 on an otherwise-feasible leg; cost math unchanged (still the added liters × price). New unit regression test: forFlight on an empty-ish tank → immediate `flyPlane` to the package destination succeeds
|
||||||
|
- **E2e flake hardening (runs #36/#41): full-core-loop Load/Fly precondition races** — test mechanics only, no app code changes. Two independent races in `e2e/actions.spec.ts`: (1) the Fly click fires its POST asynchronously (`runAction` is fire-and-forget from the test's view), so the immediate `getState` could race ahead of it and still see status 'available' — now an `expect.poll` waits until the server shows 'flying' with the expected destIcao before proceeding; (2) `flyHomeViaApi` made its repositioning decision from a snapshot taken BEFORE waiting for a leftover in-flight leg to land — while flying, locationIcao stays at the departure airport, so a plane that landed away from home was still believed to be home and never repositioned (run #41 retry: starter stranded at EDFH) — state is now re-read after landing; plus an explicit server-side precondition poll (starter grounded at the package origin) before clicking Load
|
||||||
|
|
||||||
|
## v0.15.1 — 2026-09-19 11:04
|
||||||
|
- **Right pane widened, "On board" wrapping fixed (ISS-004).** The 3-pane shell grid (`app/globals.css` `.app-shell`) moves from `300px / 1fr / 320px` to `280px / 1fr / 360px` — the map column absorbs the delta (MapLibre sizes itself from its container, no JS change). Three wrap offenders in the right pane's "On board" blocks are fixed:
|
||||||
|
- In-flight leg header (`components/RightPane.tsx`, `.contract-route` span): the class already had `white-space: nowrap; overflow: hidden; text-overflow: ellipsis`, but as a flex item with default `min-width: auto` it could not shrink below its full text width, so long routes (e.g. "Frankfurt → Madrid–Barajas") overflowed instead of ellipsizing — `.contract-route` now has `min-width: 0`
|
||||||
|
- Cargo-row buttons ("Fly to {dest}" / "Abandon −€X" in `.contract-main`): labels wrapped mid-text at the old width — `.pane-btn` now has `white-space: nowrap`
|
||||||
|
- Cargo sub-line route span had no white-space rule and wrapped mid-route — it now carries the existing `contract-route` class (nowrap + ellipsis)
|
||||||
|
- **Left pane sanity-checked at its new 280px**: fleet-row location span (`.plane-loc`) already had nowrap+ellipsis but lacked `min-width: 0`, so a long in-flight leg would have overflowed instead of truncating — same one-line guard added. Fuel/loadout spans are short fixed strings and need no guard
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite **238/238** green locally (no lib changes); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **Unrelated test-stability fix included on this branch to unblock the pipeline** (`e2e/map-interactions.spec.ts`, no app changes): the mid-flight marker click now targets the plane's RENDERED position — it polls up to ~5 s for the rendered feature via `window.__flightMap.queryRenderedFeatures` on layers `planes-flying`/`planes-grounded` and projects that feature's coordinates, instead of fetching a fresh `/api/state`. With the sim paused the server position is static, but the map renders from its own ~1 s poll — right after the freeze confirmation the last rendered frame can still be up to one poll interval stale (tens of px at scale 1000 on EDDF→LEMD), so a click projected from a fresh fetch misses the small circle layer: the render-lag race that flaked CI run #37. Pause + freeze confirmation, popup assertions and resume are unchanged
|
||||||
|
|
||||||
|
## v0.15.0 — 2026-09-19 09:35
|
||||||
|
- **Hover visualization from the side panels (ISS-002).** Hovering a fleet row in the left pane, an "On board" block (including its cargo rows) or an open-package row in the right pane now highlights the matching object on the map. The shared `HoverTarget` type (`components/hoverTypes.ts`: `{kind:'plane', id}` | `{kind:'package', originIcao, destIcao}`) is owned by the shell as a single `useState` and prop-drilled down — panes report via an `onHover` callback, `<Map>` consumes it. No React contexts introduced; the established prop-drilling pattern is kept
|
||||||
|
- **Three top-most highlight layers** (`components/Map.tsx`, added inside idempotent `ensureLayers()` so they survive every `setStyle`): `planes-highlight` (circle over both plane layers, filter `['==',['get','id'],<planeId>]`, r=10, #38bdf8 fill + white stroke), `routes-highlight` (line over `routes-legs`, filter on the leg's `planeId`, width 6, #ef4444) and `airports-highlight` (circle ring over `airports-circles`, filter matching the hovered package's two ICAOs via `['any', …]`, r=8 stroke-only). All start filtered to match nothing — an empty-string sentinel no feature can have. Consumption follows the existing ref + effect pattern: a `[hovered]` effect calls `map.setFilter(...)` on the three layers (guarded by `getLayer`), and `ensureLayers` re-applies the current filter at its end so a hover outliving a style switch stays highlighted
|
||||||
|
- e2e — new `e2e/hover.spec.ts` (3 tests, same SCALE/self-heal/`window.__flightMap` conventions as the other specs): fleet-row hover → `planes-highlight` renders exactly plane-starter, clears on mouseleave; open-package hover → `airports-highlight` shows both endpoint ICAOs (hook-created EDDF→LEMD package), clears on mouseleave; on-board block of a flying plane → `routes-highlight` shows the leg's planeId (sim paused mid-flight so the ~10 s leg can't land under the assertions, then resumed + fly-home cleanup)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite **238/238** green locally (no lib changes); e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **E2e hover spec mechanics fixed after CI run #32** (`e2e/hover.spec.ts`, no app changes): the fleet-row wait now polls up to 30 s with a diagnostic that distinguishes "server has no plane-starter" from "DOM didn't render" (the browser's /api/state poll can lag node-side requests right after page load, leaving the pane in its loading state); the open-package test fits the map to both endpoint airports before asserting — `queryRenderedFeatures` only returns features inside the current viewport and the default Frankfurt-centered view leaves LEMD off-screen
|
||||||
|
- **Decisive hover test-1 diagnostics (run #33 transient)**: the fleet-row poll now reports on every failed attempt what the NODE side sees (`/api/state` plane ids + cash via `page.request`) vs what the BROWSER last polled — new dev hook `window.__flightLastSnapshot` set in `lib/useGameState.ts` after each successful fetch (planeIds/cash/timeScale/timestamp, client-only) — plus the fleet section's HTML (`fleet-list` outerHTML or left-pane text), so a future failure can distinguish server divergence from a render bug
|
||||||
|
- **CI removes the stale e2e DB volume at run start** (`.gitea/workflows/ci.yml`, "Prepare e2e network"): `docker volume rm flight-ci_flight-db 2>/dev/null || true` — an interrupted run skips the end-of-run cleanup and leaks its used game state into later runs (run #33's instance showed spent cash from a pre-#26 seed), while tests assume seeded state
|
||||||
|
- **Hover e2e test 1 used the wrong fleet-row testid** (`e2e/hover.spec.ts`): it waited for `data-testid="plane-starter"`, but rows are rendered as `plane-${p.id}` and the server id already carries the `plane-` prefix — so the real testid is **`plane-plane-starter`** and the "missing row" failures in runs #32–#34 were deterministic selector misses, not transient state (run #34's diagnostics proved it: the fleet-list HTML contained `<li data-testid="plane-plane-starter">`). The selector is now derived from `/api/state` (starter plane id, or the single plane) and used for both the visibility poll and the hover
|
||||||
|
|
||||||
|
## v0.14.0 — 2026-09-19 08:45
|
||||||
|
- **Time-scale slider reworked to a 10-step ladder up to 1000× (ISS-006).** The old power-of-two ladder `1/2/4/8/16/32/64` is replaced by the discrete values `1, 2, 5, 10, 25, 50, 100, 250, 500, 1000` (each step roughly doubles the speed). The server clamp range widens from `[1, 64]` to `[1, 1000]` (`MAX_TIME_SCALE` in `lib/sim/engine.ts`, enforced by `clampTimeScale`; out-of-range values are still clamped, never rejected), and the OpenAPI spec's `timeScale` bounds + description follow. The slider mapping helpers in `lib/timeScale.ts` now place off-ladder scales at the nearest ladder step **by log distance** (the old `log2` formula assumed a pure power-of-two ladder); round-trip, monotonicity and endpoint-exactness are preserved
|
||||||
|
- **E2e suite runs at the fastest time.** Every spec's fast-forward scale moves from 60× to the new top of 1000× (`sim`, `actions`, `right-pane`, `map-interactions`), so flights/expiries resolve in seconds instead of minutes. The map mid-flight test (`map-interactions.spec.ts`) needed a longer leg to keep its click assertions inside the flight window at 1000×: destination moves EDDV (Hannover, ~2 s real) → LEMD (Madrid–Barajas, ~10 s real), with a full-tank refuel before departure so the ~4970 L round trip always fits the 6300 L tank. The slider e2e (`panes.spec.ts`) now asserts End→`1000×` / Home→`1×`, and the clamp tests post `2000` → expect `1000` (500 is a valid ladder value, so it passes through unclamped)
|
||||||
|
- Tests: unit — `lib/timeScale.test.ts` covers the 10-position ladder + log-distance nearest-step mapping; new `clampTimeScale` boundary suite in `lib/sim/engine.test.ts` (`[1, 1000]`, full ladder pass-through); `app/api/sim/route.test.ts` and `lib/openapi.test.ts` updated to the new bounds. Verified: unit suite **238/238** green locally (was 234 before this change)
|
||||||
|
- e2e `map-interactions.spec.ts`: the plane-popup test now pauses the sim around the marker click — at 1000× the rendered marker lags a fresh `/api/state` fetch by up to one map poll (~1 s), tens of px of drift on the EDDF→LEMD leg, so `page.mouse.click` missed the small circle layer (CI run #29); the sim is paused until the popup assertions pass, then resumed
|
||||||
|
|
||||||
|
## v0.13.1 — 2026-09-19 08:09
|
||||||
|
- CI e2e step now uses Playwright's list reporter so every test prints as it runs in the job log (progress visibility); failures still get full error context
|
||||||
|
|
||||||
|
## v0.12.3 — 2026-09-19 07:36
|
||||||
|
- **e2e: removed the unreliable curved-route assertion from `map-interactions.spec.ts`.** The "route line has >2 coordinates in the routes source" check (added with v0.12.2) failed in CI and against the live instance even though the arc renders correctly — MapLibre's `querySourceFeatures` returns tile-simplified geometry at low zoom, so coordinate counts from it are not a reliable signal for what was pushed into the source. The curved arc remains fully covered by unit tests (`lib/mapData.test.ts`: 25 sampled coordinates, exact endpoints, curvature on long routes); the spec keeps all other steps (grounded plane draws no line, marker moves across polls, plane popup with status + route)
|
||||||
|
|
||||||
|
## v0.13.0 — 2026-09-18 15:31
|
||||||
|
- **CI + pull-request workflow** (process/infra): new `.gitea/workflows/ci.yml` runs build → unit tests → e2e on every PR to master and on push to master, in one job with a `docker:dind` service. E2E isolation: the suite targets a fresh compose stack inside dind (`docker-compose.ci.yml` — mirrors docker-compose.yml minus Traefik/dev_net; app served directly on port 3000 of the dind container; game state in a named volume so it is fresh per run and survives `state.spec.ts`'s mid-run restart) — **CI never deploys to or touches production**. The dind endpoint is resolved at job start (tries `tcp://localhost:2375`, then `tcp://docker:2375` — Gitea services are sibling containers reachable by service id on the job network) and exported as `DOCKER_HOST` + `E2E_BASE_URL`; build context is tarred by the compose client in the job, so nothing needs to be visible from inside dind
|
||||||
|
- **Playwright config made CI-aware, backward-compatible** (`playwright.config.ts`): new optional env vars — `PW_REMOTE_BROWSER=0` (local chromium instead of the shared remote server at 192.168.1.4:3000), `E2E_DEPLOY_CMD` (runs as webServer + readiness wait; unset = current local behavior with no auto-deploy); `E2E_BASE_URL` already existed. `e2e/state.spec.ts` reads `E2E_COMPOSE_ARGS` for its mid-run `docker compose restart flight` (default empty → unchanged locally)
|
||||||
|
- **@playwright/test pinned as devDependency** (`1.63.0`, matching the shared remote browser server image and the global install) so CI is self-contained; still excluded from the runtime image via .dockerignore (comment updated), prod-deps stage unaffected
|
||||||
|
- `AGENTS.md`: "Change process" + "E2E tests" rewritten for the PR workflow — feature branch off master → commits with CHANGELOG entry + version bump → PR to master → CI (build→unit→e2e) green → merge → tag on master → manual production deploy via `docker compose up -d --build`; no direct pushes to master, CI never deploys
|
||||||
|
- **CI build reliability + caching** (after first dind runs): the e2e image is now built with `--progress=plain` before `up -d` so BuildKit step output lands in job logs instead of being hidden by auto progress; Dockerfile bun installs use a BuildKit cache mount (`/root/.bun/install/cache`) that persists on the runner's shared daemon, and CI restores/saves node_modules + the bun cache via actions/cache around dependency install (both steps `continue-on-error` — safe while the runner's cache server is being fixed)
|
||||||
|
- **CI flaky-network handling settled on retry wrappers** (transient EAI_AGAIN failures seen in runs #10/#11): bun install, dependency install and the e2e image build each retry up to 3× with 5s between attempts before failing — run #12 with this setup got furthest (build + unit + browsers green). A short-lived "DNS diagnostics" step was tried but removed: its daemon-side probe pulled an image not present on the runner's docker daemon and stalled runs #13/#14 at Setup Node
|
||||||
|
- **E2e image build needs no outbound network from dind build containers** (DNSResolveFailed in `RUN bun install` across runs #10/#12/#15): node_modules is now installed in the CI job / dev host and copied into the build context (.dockerignore no longer excludes it; Dockerfile COPYs it instead of running any install inside the image); base images switched alpine → node:22-slim (glibc) for native-module ABI compatibility with the job-installed tree (@next/swc-*, sharp are prebuilt per platform — CI job and prod host are x86_64 glibc linux); a "Pull e2e base image" step fails fast if the daemon can't fetch node:22-slim
|
||||||
|
- **CI e2e deploy command stays alive** (`E2E_DEPLOY_CMD` now ends with `docker compose … logs -f`): Playwright's webServer requires a long-running process — `up -d` returns immediately and triggered "Process from config.webServer exited early" (run #16); `logs -f` also streams app logs into CI output for debugging
|
||||||
|
- **CI e2e step bypasses proxies for the in-network app host** (`NO_PROXY`/`no_proxy=app,localhost,127.0.0.1,.kkhost.pl`) and prints proxy/DNS/curl diagnostics before the suite — run #18 showed Chromium getting `ERR_SSL_PROTOCOL_ERROR` on http://app:3000 while node-side HTTP worked (9 API-only tests passed), pointing at a TLS-terminating proxy env var that Chromium honors but Node's HTTP client ignores
|
||||||
|
- **CI e2e targets the app at a static in-network IP** (`172.39.0.10`, pinned subnet `172.39.0.0/24` created by "Prepare e2e network"; stale networks with other subnets are recreated) instead of the DNS alias — Chromium got `ERR_SSL_PROTOCOL_ERROR` via the hostname while node-side HTTP worked, so DNS is removed from the equation; post-deploy connectivity diagnostics added as a CI-gated globalSetup (`e2e/ci-diagnostics.ts`, no-op locally) comparing node resolution/HTTP against Chromium navigation on both hostname and static IP
|
||||||
|
- **CI caches Playwright browser binaries across runs** (`$HOME/.cache/ms-playwright` via actions/cache): the flaky runner uplink makes the ~187 MiB Chrome-for-Testing download unreliable (runs #20/#21 died mid-download at "Install browsers"); also removed the no-op "Save deps cache" step — on this runner caches marked by a restore step are uploaded automatically at job end, so an explicit save never did anything
|
||||||
|
- **CI browser install runs in a bounded 6-attempt loop** — cdn.playwright.dev is flaky from the runner and Playwright's internal retry window (~40–90s) was often insufficient (runs #21–#23), while longer windows get through (runs #12/#18); already-installed browsers are skipped so progress accumulates across attempts
|
||||||
|
- Verified: unit suite 234 green locally; e2e not run locally by design (would deploy to production) — first real pass happens in the PR's CI run
|
||||||
|
- **CI e2e now runs in self-hosted map-assets mode** — the workflow downloads the OpenFreeMap asset pack (`npm run assets:download` → styles/fonts/sprites into git-ignored `./public`, bounded 6-attempt retry like the other flaky-network steps) and caches it via actions/cache keyed on the download script (job-end upload seeds future runs; a partial pack without manifest is harmless — app falls back to remote); `docker-compose.ci.yml` mounts `./public:/app/public` mirroring docker-compose.yml, so map tests that abort all *.openfreemap.org traffic get self-hosted styles/fonts/sprites like local dev (fixes the deterministic map.spec.ts wheel-zoom + style-switcher failures)
|
||||||
|
|
||||||
## v0.12.2 — 2026-09-18 14:06
|
## v0.12.2 — 2026-09-18 14:06
|
||||||
- **Bugfix (ISS-003): route leg lines were drawn as straight two-point chords instead of following the curved great-circle path planes actually fly.** Root cause in `lib/mapData.ts`: `routesGeoJson` built each flying plane's leg LineString from only its origin and destination airport coordinates, so on long routes the drawn line cut across the chord (up to ~40 km off the true arc for a ~1400 km leg) while the plane marker moved along the curved path. Fix: new pure `greatCircleArc(from, to)` samples the same slerp used by the sim (`positionAt` in `lib/sim/movement.ts`) at t = i/24 for i = 0..24 — **25 coordinates** (exact endpoints + 23 intermediate points, `ROUTE_ARC_SEGMENTS = 24`) — so the drawn line matches the curved flight path; `routesGeoJson` now uses it instead of the two-point chord
|
- **Bugfix (ISS-003): route leg lines were drawn as straight two-point chords instead of following the curved great-circle path planes actually fly.** Root cause in `lib/mapData.ts`: `routesGeoJson` built each flying plane's leg LineString from only its origin and destination airport coordinates, so on long routes the drawn line cut across the chord (up to ~40 km off the true arc for a ~1400 km leg) while the plane marker moved along the curved path. Fix: new pure `greatCircleArc(from, to)` samples the same slerp used by the sim (`positionAt` in `lib/sim/movement.ts`) at t = i/24 for i = 0..24 — **25 coordinates** (exact endpoints + 23 intermediate points, `ROUTE_ARC_SEGMENTS = 24`) — so the drawn line matches the curved flight path; `routesGeoJson` now uses it instead of the two-point chord
|
||||||
- Tests: unit — `lib/mapData.test.ts` updated (route feature is a sampled arc with exact endpoints) + new `greatCircleArc` suite (endpoint exactness, long-route midpoint deviates >5 km from the straight chord proving curvature, short route stays <5 km off). e2e — `map-interactions.spec.ts` now asserts the flying plane's route line has **>2 coordinates** in the routes source (curved arc, not a two-point chord)
|
- Tests: unit — `lib/mapData.test.ts` updated (route feature is a sampled arc with exact endpoints) + new `greatCircleArc` suite (endpoint exactness, long-route midpoint deviates >5 km from the straight chord proving curvature, short route stays <5 km off). e2e — `map-interactions.spec.ts` now asserts the flying plane's route line has **>2 coordinates** in the routes source (curved arc, not a two-point chord)
|
||||||
|
|||||||
+13
-18
@@ -1,21 +1,14 @@
|
|||||||
# Multi-stage build: bun for installs (fast), node for build + runtime.
|
# Two-stage build needing ZERO outbound network at image-build time:
|
||||||
# No BuildKit type=cache mounts: they don't persist across builds on this daemon
|
# (a) deps are installed by the CI job / dev host (`bun install`) and copied in via the
|
||||||
# (Docker 29 + containerd image store), and bun install is fast enough (~3s cold)
|
# build context — the runner's dind daemon has broken outbound DNS for build containers,
|
||||||
# that cross-build tarball caching isn't worth the complexity.
|
# so any RUN that fetches packages fails;
|
||||||
FROM oven/bun:1.4.2-alpine AS deps
|
# (b) base images must be glibc (node:22-slim), NOT alpine/musl: native modules (@next/swc-*,
|
||||||
|
# sharp) are prebuilt for the platform that ran `bun install` — CI job and prod host are
|
||||||
|
# x86_64 glibc linux. Building on another platform requires reinstalling node_modules there first.
|
||||||
|
FROM node:22-slim AS build
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json bun.lock ./
|
COPY package.json bun.lock ./
|
||||||
RUN bun install --frozen-lockfile
|
COPY node_modules ./node_modules
|
||||||
|
|
||||||
# Production dependencies only — devDeps (typescript, vitest, @types) are build-time only.
|
|
||||||
FROM oven/bun:1.4.2-alpine AS prod-deps
|
|
||||||
WORKDIR /app
|
|
||||||
COPY package.json bun.lock ./
|
|
||||||
RUN bun install --production --frozen-lockfile
|
|
||||||
|
|
||||||
FROM node:22-alpine AS build
|
|
||||||
WORKDIR /app
|
|
||||||
COPY --from=deps /app/node_modules ./node_modules
|
|
||||||
COPY . .
|
COPY . .
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
@@ -23,10 +16,12 @@ RUN npm run build
|
|||||||
# No `output: 'standalone'`: the runtime stage keeps node_modules because
|
# No `output: 'standalone'`: the runtime stage keeps node_modules because
|
||||||
# /api/mlworker/[file] reads maplibre-gl dist files from disk at runtime, and
|
# /api/mlworker/[file] reads maplibre-gl dist files from disk at runtime, and
|
||||||
# /api/airports reads data/*.csv — both resolved relative to process.cwd().
|
# /api/airports reads data/*.csv — both resolved relative to process.cwd().
|
||||||
FROM node:22-alpine AS runtime
|
FROM node:22-slim AS runtime
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1
|
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1
|
||||||
COPY --from=prod-deps /app/node_modules ./node_modules
|
# Full tree (dev+prod deps): a prod-only slimmed copy would need an extra install step,
|
||||||
|
# revisit if image size matters.
|
||||||
|
COPY --from=build /app/node_modules ./node_modules
|
||||||
COPY --from=build /app/.next ./.next
|
COPY --from=build /app/.next ./.next
|
||||||
COPY --from=build /app/package.json ./package.json
|
COPY --from=build /app/package.json ./package.json
|
||||||
COPY --from=build /app/data ./data
|
COPY --from=build /app/data ./data
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ Accept job → dispatch a plane → watch it fly the route on the map → earn m
|
|||||||
|
|
||||||
## Simulation engine
|
## Simulation engine
|
||||||
- Server-authoritative state: sim ticks on the server, client polls and renders
|
- Server-authoritative state: sim ticks on the server, client polls and renders
|
||||||
- Time scale 1x–60x + pause; sim clock persisted across sessions
|
- Time scale 1x–1000x (discrete ladder 1/2/5/10/25/50/100/250/500/1000) + pause; sim clock persisted across sessions
|
||||||
- SQLite via Drizzle ORM — schema designed to switch to Postgres later
|
- SQLite via Drizzle ORM — schema designed to switch to Postgres later
|
||||||
- Demand/revenue/cost formulas per contract leg; fuel burn by distance/plane type
|
- Demand/revenue/cost formulas per contract leg; fuel burn by distance/plane type
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import { eq } from 'drizzle-orm';
|
|||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { getGameDb } from '@/lib/db/client';
|
import { getGameDb } from '@/lib/db/client';
|
||||||
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES } from '@/lib/game/catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
|
import { HUB_ICAO } from '@/lib/game/seed';
|
||||||
import { POST } from './route';
|
import { POST } from './route';
|
||||||
|
|
||||||
let dir: string;
|
let dir: string;
|
||||||
@@ -22,7 +26,15 @@ afterAll(async () => {
|
|||||||
await fs.rm(dir, { recursive: true, force: true });
|
await fs.rm(dir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
const post = (planeId: string) => POST(new Request(`http://localhost/api/planes/${planeId}/refuel`), { params: Promise.resolve({ planeId }) });
|
const post = (planeId: string, body?: unknown) =>
|
||||||
|
POST(
|
||||||
|
new Request(`http://localhost/api/planes/${planeId}/refuel`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
{ params: Promise.resolve({ planeId }) },
|
||||||
|
);
|
||||||
|
|
||||||
describe('POST /api/planes/:planeId/refuel', () => {
|
describe('POST /api/planes/:planeId/refuel', () => {
|
||||||
it('rejects an unknown id with 404', async () => {
|
it('rejects an unknown id with 404', async () => {
|
||||||
@@ -74,4 +86,76 @@ describe('POST /api/planes/:planeId/refuel', () => {
|
|||||||
expect(res.status).toBe(409);
|
expect(res.status).toBe(409);
|
||||||
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient funds/i);
|
expect(((await res.json()) as { error: string }).error).toMatch(/insufficient funds/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('accepts an explicit {mode:"full"} body exactly like no body', async () => {
|
||||||
|
const { db } = await getGameDb();
|
||||||
|
await db.update(schema.account).set({ cash: 50_000 }); // previous test left the account poor
|
||||||
|
await db.update(schema.planes).set({ fuel: 1_000 }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
const res = await post('plane-starter', { mode: 'full' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { planes: Array<{ id: string; fuel: number }> };
|
||||||
|
expect(body.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown mode with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { mode: 'half' });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/mode/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects forFlight without a packageId with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { mode: 'forFlight' });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/packageId/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown body field with 400', async () => {
|
||||||
|
const res = await post('plane-starter', { liters: 100 });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as { error: string }).error).toMatch(/unknown field/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid JSON with 400', async () => {
|
||||||
|
const res = await POST(
|
||||||
|
new Request(`http://localhost/api/planes/plane-starter/refuel`, { method: 'POST', body: '{nope' }),
|
||||||
|
{ params: Promise.resolve({ planeId: 'plane-starter' }) },
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight tops up exactly the liters needed for the loaded package leg', async () => {
|
||||||
|
const { db } = await getGameDb();
|
||||||
|
await db.update(schema.account).set({ cash: 50_000 });
|
||||||
|
// A loaded EDDF → LEMD package on the starter (direct row — loadPackage is covered in actions tests).
|
||||||
|
await db.insert(schema.packages).values({
|
||||||
|
id: 'p-ff-api', originIcao: HUB_ICAO, destIcao: 'LEMD', reward: 1_000, cargoType: 'Mail', cargoCount: 4,
|
||||||
|
deadlineSimTime: Date.now() + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
const startFuel = Math.round(required / 2); // partial tank so L > 0
|
||||||
|
await db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
const cashBefore = (await db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const res = await post('plane-starter', { mode: 'forFlight', packageId: 'p-ff-api' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const body = (await res.json()) as {
|
||||||
|
account: { cash: number };
|
||||||
|
planes: Array<{ id: string; fuel: number }>;
|
||||||
|
};
|
||||||
|
const cost = Math.round((required - startFuel) * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
|
expect(body.account.cash).toBeCloseTo(cashBefore - cost, 6);
|
||||||
|
expect(body.planes.find((p) => p.id === 'plane-starter')!.fuel).toBeCloseTo(required, 6);
|
||||||
|
|
||||||
|
// Clean up the test package.
|
||||||
|
await db.delete(schema.packages).where(eq(schema.packages.id, 'p-ff-api'));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,47 @@
|
|||||||
import { performAction, refuelPlane } from '@/lib/game/actions';
|
import { performAction, refuelPlane } from '@/lib/game/actions';
|
||||||
|
|
||||||
// POST /api/planes/:planeId/refuel (v0.8.0) — no body. Fills a grounded plane to
|
// POST /api/planes/:planeId/refuel (v0.8.0; optional body v0.16.0) — fills a grounded
|
||||||
// maxFuel at the fuel price per missing liter; deducts the cost from cash. 404
|
// plane at the fuel price per added liter and deducts the cost from cash. The body is
|
||||||
// unknown id; 409 if the plane is flying or cash is insufficient. On success
|
// OPTIONAL: no body, {} or {mode:'full'} fill to maxFuel (the original behavior);
|
||||||
// returns the full state snapshot (fuel back to max, cash reduced by the cost).
|
// {mode:'forFlight', packageId} adds just enough for that loaded package's destination
|
||||||
|
// leg. 400 bad body (unknown field, unknown mode, forFlight without packageId); 404
|
||||||
|
// unknown plane/package id; 409 if the plane is flying, the package isn't loaded on it
|
||||||
|
// (or is expired), the leg doesn't fit a full tank, or cash is insufficient. On success
|
||||||
|
// returns the full state snapshot (fuel raised by exactly the added liters).
|
||||||
|
|
||||||
export async function POST(_req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
export async function POST(req: Request, ctx: { params: Promise<{ planeId: string }> }) {
|
||||||
const { planeId } = await ctx.params;
|
const { planeId } = await ctx.params;
|
||||||
return performAction((inst) => refuelPlane(inst, planeId));
|
|
||||||
|
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 !== 'mode' && key !== 'packageId') {
|
||||||
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mode = input.mode ?? 'full';
|
||||||
|
if (mode !== 'full' && mode !== 'forFlight') {
|
||||||
|
return Response.json({ error: 'mode must be "full" or "forFlight"' }, { status: 400 });
|
||||||
|
}
|
||||||
|
let packageId: string | undefined;
|
||||||
|
if (input.packageId !== undefined) {
|
||||||
|
if (typeof input.packageId !== 'string' || input.packageId.length === 0) {
|
||||||
|
return Response.json({ error: 'packageId must be a non-empty string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
packageId = input.packageId;
|
||||||
|
}
|
||||||
|
if (mode === 'forFlight' && !packageId) {
|
||||||
|
return Response.json({ error: 'packageId is required when mode is "forFlight"' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return performAction((inst) => refuelPlane(inst, planeId, { mode, packageId }));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,19 +31,24 @@ describe('POST /api/sim', () => {
|
|||||||
expect(body.paused).toBe(false);
|
expect(body.paused).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sets and clamps timeScale into [1, 64]', async () => {
|
it('sets and clamps timeScale into [1, 1000]', async () => {
|
||||||
const hi = await post({ timeScale: 500 });
|
const hi = await post({ timeScale: 2000 });
|
||||||
expect(hi.status).toBe(200);
|
expect(hi.status).toBe(200);
|
||||||
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(64);
|
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(1000);
|
||||||
|
|
||||||
const lo = await post({ timeScale: 0.1 });
|
const lo = await post({ timeScale: 0.1 });
|
||||||
expect(lo.status).toBe(200);
|
expect(lo.status).toBe(200);
|
||||||
expect(((await lo.json()) as { timeScale: number }).timeScale).toBe(1);
|
expect(((await lo.json()) as { timeScale: number }).timeScale).toBe(1);
|
||||||
|
|
||||||
// The top of the power-of-two ladder passes through unclamped (v0.9.2).
|
// The top of the ladder passes through unclamped (v0.14.0).
|
||||||
const max = await post({ timeScale: 64 });
|
const max = await post({ timeScale: 1000 });
|
||||||
expect(max.status).toBe(200);
|
expect(max.status).toBe(200);
|
||||||
expect(((await max.json()) as { timeScale: number }).timeScale).toBe(64);
|
expect(((await max.json()) as { timeScale: number }).timeScale).toBe(1000);
|
||||||
|
|
||||||
|
// In-range values pass through unclamped — ladder and off-ladder alike.
|
||||||
|
const ladder = await post({ timeScale: 500 });
|
||||||
|
expect(ladder.status).toBe(200);
|
||||||
|
expect(((await ladder.json()) as { timeScale: number }).timeScale).toBe(500);
|
||||||
|
|
||||||
const mid = await post({ timeScale: 37 });
|
const mid = await post({ timeScale: 37 });
|
||||||
expect(mid.status).toBe(200);
|
expect(mid.status).toBe(200);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { applyTimeControls } from '@/lib/sim/engine';
|
import { applyTimeControls } from '@/lib/sim/engine';
|
||||||
|
|
||||||
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–64, paused?: boolean }.
|
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–1000, paused?: boolean }.
|
||||||
// Ticks the clock first (so the response reflects current game time), then applies
|
// Ticks the clock first (so the response reflects current game time), then applies
|
||||||
// and persists the new controls. Returns the updated simState.
|
// and persists the new controls. Returns the updated simState.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ export async function POST(req: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (input.timeScale !== undefined && (typeof input.timeScale !== 'number' || !Number.isFinite(input.timeScale))) {
|
if (input.timeScale !== undefined && (typeof input.timeScale !== 'number' || !Number.isFinite(input.timeScale))) {
|
||||||
return Response.json({ error: 'timeScale must be a finite number (1–64)' }, { status: 400 });
|
return Response.json({ error: 'timeScale must be a finite number (1–1000)' }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (input.paused !== undefined && typeof input.paused !== 'boolean') {
|
if (input.paused !== undefined && typeof input.paused !== 'boolean') {
|
||||||
return Response.json({ error: 'paused must be a boolean' }, { status: 400 });
|
return Response.json({ error: 'paused must be a boolean' }, { status: 400 });
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import { tickNow } from '@/lib/sim/engine';
|
|||||||
// (game time) so the next fast tick expires it; 404 if unknown/not open.
|
// (game time) so the next fast tick expires it; 404 if unknown/not open.
|
||||||
// - without: creates a fresh open package with the same short deadline.
|
// - without: creates a fresh open package with the same short deadline.
|
||||||
|
|
||||||
const HOOK_DEADLINE_MS = 10_000; // game ms past the current clock (~0.2 s real at 60×)
|
const HOOK_DEADLINE_MS = 10_000; // game ms past the current clock (≈ 0.01 s real at the fastest 1000×)
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
|
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
|
||||||
|
|||||||
+4
-1
@@ -71,7 +71,7 @@ body {
|
|||||||
/* 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 */
|
||||||
.app-shell {
|
.app-shell {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 300px minmax(0, 1fr) 320px;
|
grid-template-columns: 280px minmax(0, 1fr) 360px;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,6 +201,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.plane-loc {
|
.plane-loc {
|
||||||
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -265,6 +266,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.contract-route {
|
.contract-route {
|
||||||
|
min-width: 0;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #f1f5f9;
|
color: #f1f5f9;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -284,6 +286,7 @@ body {
|
|||||||
|
|
||||||
.pane-btn {
|
.pane-btn {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
white-space: nowrap;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
padding: 3px 10px;
|
padding: 3px 10px;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
|
|||||||
+9
-3
@@ -1,8 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import dynamic from 'next/dynamic';
|
import dynamic from 'next/dynamic';
|
||||||
|
import { useState } from 'react';
|
||||||
import LeftPane from '@/components/LeftPane';
|
import LeftPane from '@/components/LeftPane';
|
||||||
import RightPane from '@/components/RightPane';
|
import RightPane from '@/components/RightPane';
|
||||||
|
import type { HoverTarget } from '@/components/hoverTypes';
|
||||||
import { useGameState } from '@/lib/useGameState';
|
import { useGameState } from '@/lib/useGameState';
|
||||||
|
|
||||||
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
|
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
|
||||||
@@ -13,12 +15,16 @@ export default function Home() {
|
|||||||
// lets a pane push an action endpoint's full response snapshot in immediately.
|
// lets a pane push an action endpoint's full response snapshot in immediately.
|
||||||
const { state, loading, error, refresh, applySnapshot } = useGameState(1000);
|
const { state, loading, error, refresh, applySnapshot } = useGameState(1000);
|
||||||
|
|
||||||
|
// ISS-002 (v0.15.0): the side panels' hover target — shared here so hovering a row in
|
||||||
|
// either pane highlights the matching plane/route/airports on the map.
|
||||||
|
const [hovered, setHovered] = useState<HoverTarget | null>(null);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} />
|
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} />
|
||||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines */}
|
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines */}
|
||||||
<Map state={state} />
|
<Map state={state} hovered={hovered} />
|
||||||
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} />
|
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"sql.js": "^1.14.2",
|
"sql.js": "^1.14.2",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "1.63.0",
|
||||||
"@types/node": "^22.20.3",
|
"@types/node": "^22.20.3",
|
||||||
"@types/react": "^19.3.0",
|
"@types/react": "^19.3.0",
|
||||||
"@types/react-dom": "^19.3.0",
|
"@types/react-dom": "^19.3.0",
|
||||||
@@ -123,6 +124,8 @@
|
|||||||
|
|
||||||
"@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],
|
"@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],
|
||||||
|
|
||||||
|
"@playwright/test": ["@playwright/test@1.63.0", "", { "dependencies": { "playwright": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ=="],
|
||||||
|
|
||||||
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.9", "", { "os": "android", "cpu": "arm" }, "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw=="],
|
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.9", "", { "os": "android", "cpu": "arm" }, "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw=="],
|
||||||
|
|
||||||
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.9", "", { "os": "android", "cpu": "arm64" }, "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg=="],
|
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.9", "", { "os": "android", "cpu": "arm64" }, "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg=="],
|
||||||
@@ -299,6 +302,10 @@
|
|||||||
|
|
||||||
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
|
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
|
||||||
|
|
||||||
|
"playwright": ["playwright@1.63.0", "", { "dependencies": { "playwright-core": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg=="],
|
||||||
|
|
||||||
|
"playwright-core": ["playwright-core@1.63.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg=="],
|
||||||
|
|
||||||
"postcss": ["postcss@8.5.23", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
|
"postcss": ["postcss@8.5.23", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
|
||||||
|
|
||||||
"potpack": ["potpack@2.1.0", "", {}, "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ=="],
|
"potpack": ["potpack@2.1.0", "", {}, "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ=="],
|
||||||
|
|||||||
+26
-8
@@ -5,6 +5,8 @@ import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
|||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
||||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||||
|
import { useSimClock } from '@/lib/useSimClock';
|
||||||
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface LeftPaneProps {
|
interface LeftPaneProps {
|
||||||
state: StateSnapshot | null;
|
state: StateSnapshot | null;
|
||||||
@@ -12,11 +14,14 @@ interface LeftPaneProps {
|
|||||||
error: string | null;
|
error: string | null;
|
||||||
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
|
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
|
||||||
onRefresh: () => void;
|
onRefresh: () => 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Power-of-two slider (v0.9.2): position t ∈ [0,1] → nearest step of the ladder
|
// Discrete ladder slider (v0.9.2, values reworked in v0.14.0): position t ∈ [0,1] → nearest
|
||||||
// 1×/2×/4×/8×/16×/32×/64× — each of the 7 positions doubles the speed.
|
// step of the ladder 1×/2×/5×/10×/25×/50×/100×/250×/500×/1000× — each of the 10 positions
|
||||||
const SCALE_SLIDER_STEP = 1 / (TIME_SCALES.length - 1); // one doubling per keyboard-arrow step
|
// roughly doubles the speed.
|
||||||
|
const SCALE_SLIDER_STEP = 1 / (TIME_SCALES.length - 1); // one ladder step per keyboard-arrow step
|
||||||
const SCALE_COMMIT_DEBOUNCE_MS = 250;
|
const SCALE_COMMIT_DEBOUNCE_MS = 250;
|
||||||
|
|
||||||
// Flying planes show their current leg from the snapshot's dest fields (v0.12.0).
|
// Flying planes show their current leg from the snapshot's dest fields (v0.12.0).
|
||||||
@@ -41,14 +46,14 @@ export function pendingScaleConfirmed(pendingScale: number | null, serverTimeSca
|
|||||||
return pendingScale !== null && serverTimeScale === pendingScale;
|
return pendingScale !== null && serverTimeScale === pendingScale;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneProps) {
|
export default function LeftPane({ state, loading, error, onRefresh, onHover }: LeftPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
// POST /api/sim, then refetch the full snapshot immediately so the pane reflects the new
|
// POST /api/sim, then refetch the full snapshot immediately so the pane reflects the new
|
||||||
// controls without waiting for the next poll tick. On failure keep the stale UI — the
|
// controls without waiting for the next poll tick. On failure keep the stale UI — the
|
||||||
// running poll retries on its own and surfaces the error state. A commit that lands while
|
// running poll retries on its own and surfaces the error state. A commit that lands while
|
||||||
// another POST is in flight is held in a single slot (last intent wins) and flushed by the
|
// another POST is in flight is held in a single slot (last intent wins) and flushed by the
|
||||||
// in-flight call, so every user intent reaches the server (the [1,64] clamp stays as backstop).
|
// in-flight call, so every user intent reaches the server (the [1,1000] clamp stays as backstop).
|
||||||
// The gate is a REF, not React state: closures never see a stale "busy" value, which used to
|
// The gate is a REF, not React state: closures never see a stale "busy" value, which used to
|
||||||
// let a flush re-queue instead of send and silently drop a commit.
|
// let a flush re-queue instead of send and silently drop a commit.
|
||||||
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
|
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
|
||||||
@@ -101,7 +106,7 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
|||||||
// 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
|
||||||
// [1,64] clamp stays as the backstop.
|
// [1,1000] clamp stays as the backstop.
|
||||||
const [pendingScale, setPendingScaleState] = useState<number | null>(null);
|
const [pendingScale, setPendingScaleState] = useState<number | null>(null);
|
||||||
const pendingRef = useRef<number | null>(null);
|
const pendingRef = useRef<number | null>(null);
|
||||||
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
@@ -163,6 +168,12 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
|||||||
|
|
||||||
const displayedScale = pendingScale ?? timeScale;
|
const displayedScale = pendingScale ?? timeScale;
|
||||||
|
|
||||||
|
// ISS-007: the clock ticks client-side between polls, re-syncing to server truth on every
|
||||||
|
// snapshot. Fed with EFFECTIVE controls so a scale drag / pause click takes effect immediately,
|
||||||
|
// not when the confirming snapshot lands. Only the sim-clock paragraph uses this — deadline and
|
||||||
|
// penalty previews stay snapshot-based (deterministic against the server clock).
|
||||||
|
const simClockMs = useSimClock(state, { timeScale: displayedScale, paused });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside data-testid="left-pane" className="pane left-pane">
|
<aside data-testid="left-pane" className="pane left-pane">
|
||||||
<h2 className="pane-title">Assets</h2>
|
<h2 className="pane-title">Assets</h2>
|
||||||
@@ -188,7 +199,14 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
|||||||
) : (
|
) : (
|
||||||
<ul data-testid="fleet-list" className="fleet-list">
|
<ul data-testid="fleet-list" className="fleet-list">
|
||||||
{state.planes.map((p) => (
|
{state.planes.map((p) => (
|
||||||
<li key={p.id} data-testid={`plane-${p.id}`} className="plane-row">
|
// ISS-002: hovering a fleet row highlights the plane on the map.
|
||||||
|
<li
|
||||||
|
key={p.id}
|
||||||
|
data-testid={`plane-${p.id}`}
|
||||||
|
className="plane-row"
|
||||||
|
onMouseEnter={() => onHover({ kind: 'plane', id: p.id })}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
>
|
||||||
<div className="plane-main">
|
<div className="plane-main">
|
||||||
<span className="plane-model">{PLANE_TYPES[p.model]?.name ?? p.model}</span>
|
<span className="plane-model">{PLANE_TYPES[p.model]?.name ?? p.model}</span>
|
||||||
<span className={`plane-status status-${p.status}`}>{p.status}</span>
|
<span className={`plane-status status-${p.status}`}>{p.status}</span>
|
||||||
@@ -210,7 +228,7 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
|||||||
<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">
|
||||||
{formatSimClock(state.simState.clockMs)}
|
{simClockMs !== null && formatSimClock(simClockMs)}
|
||||||
{paused ? ' (paused)' : ''}
|
{paused ? ' (paused)' : ''}
|
||||||
</p>
|
</p>
|
||||||
<div className="time-controls">
|
<div className="time-controls">
|
||||||
|
|||||||
+88
-2
@@ -7,6 +7,7 @@ import pkg from '../package.json';
|
|||||||
import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvailable, styleUrlFor } from '../lib/mapStyles';
|
import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvailable, styleUrlFor } from '../lib/mapStyles';
|
||||||
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 { planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
import { 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';
|
||||||
@@ -27,6 +28,11 @@ const PLANES_GROUNDED_LAYER_ID = 'planes-grounded';
|
|||||||
const PLANES_FLYING_LAYER_ID = 'planes-flying';
|
const PLANES_FLYING_LAYER_ID = 'planes-flying';
|
||||||
const ROUTES_SOURCE_ID = 'routes';
|
const ROUTES_SOURCE_ID = 'routes';
|
||||||
const ROUTES_LEGS_LAYER_ID = 'routes-legs';
|
const ROUTES_LEGS_LAYER_ID = 'routes-legs';
|
||||||
|
// ISS-002 (v0.15.0): top-most hover-highlight layers, added after the base layers so they
|
||||||
|
// render above them. Each starts filtered to match nothing; applyHoverRef drives the filters.
|
||||||
|
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
|
||||||
|
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
|
||||||
|
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-highlight';
|
||||||
|
|
||||||
function escapeHtml(s: string): string {
|
function escapeHtml(s: string): string {
|
||||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
@@ -36,11 +42,14 @@ interface MapProps {
|
|||||||
// The shell's polled /api/state snapshot (v0.11.0) — drives the plane markers and
|
// The shell's polled /api/state snapshot (v0.11.0) — drives the plane markers and
|
||||||
// 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
|
||||||
|
// (+ its route leg if flying) or a package's endpoint airports. Null = nothing hovered.
|
||||||
|
hovered?: HoverTarget | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
||||||
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
||||||
export default function FlightMap({ state }: MapProps) {
|
export default function FlightMap({ state, hovered }: MapProps) {
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||||
// /api/airports is fetched at most once per page life: every styledata event
|
// /api/airports is fetched at most once per page life: every styledata event
|
||||||
@@ -74,6 +83,38 @@ export default function FlightMap({ state }: MapProps) {
|
|||||||
applyDynamicRef.current();
|
applyDynamicRef.current();
|
||||||
}, [state]);
|
}, [state]);
|
||||||
|
|
||||||
|
// ISS-002 (v0.15.0): hover highlight — same ref + effect pattern as the snapshot above.
|
||||||
|
// No-op until the layers exist; ensureLayers re-applies the current filter after every
|
||||||
|
// styledata re-establish, so a hover that outlives a style switch stays highlighted.
|
||||||
|
const hoveredRef = useRef<HoverTarget | null>(null);
|
||||||
|
const applyHoverRef = useRef<() => void>(() => {});
|
||||||
|
applyHoverRef.current = () => {
|
||||||
|
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 : '';
|
||||||
|
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 : '';
|
||||||
|
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.setFilter(
|
||||||
|
AIRPORTS_HIGHLIGHT_LAYER_ID,
|
||||||
|
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
hoveredRef.current = hovered ?? null;
|
||||||
|
applyHoverRef.current();
|
||||||
|
}, [hovered]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!containerRef.current) return;
|
if (!containerRef.current) return;
|
||||||
|
|
||||||
@@ -240,6 +281,49 @@ export default function FlightMap({ state }: MapProps) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// ISS-002 (v0.15.0): hover-highlight layers — added last so they sit top-most over
|
||||||
|
// both plane layers / the route line / the airport circles. Each starts filtered to
|
||||||
|
// match nothing; applyHoverRef sets the real filter on hover and re-applies it here.
|
||||||
|
if (!map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: PLANES_HIGHLIGHT_LAYER_ID,
|
||||||
|
type: 'circle',
|
||||||
|
source: PLANES_SOURCE_ID,
|
||||||
|
filter: ['==', ['get', 'id'], ''],
|
||||||
|
paint: {
|
||||||
|
'circle-radius': 10, // halo well above the base circles (3 grounded / 6 flying)
|
||||||
|
'circle-color': '#38bdf8',
|
||||||
|
'circle-stroke-width': 2.5,
|
||||||
|
'circle-stroke-color': '#ffffff',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: ROUTES_HIGHLIGHT_LAYER_ID,
|
||||||
|
type: 'line',
|
||||||
|
source: ROUTES_SOURCE_ID,
|
||||||
|
filter: ['==', ['get', 'planeId'], ''],
|
||||||
|
paint: {
|
||||||
|
'line-color': '#ef4444', // red — distinct from the amber routes-legs line
|
||||||
|
'line-width': 6,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
||||||
|
map.addLayer({
|
||||||
|
id: AIRPORTS_HIGHLIGHT_LAYER_ID,
|
||||||
|
type: 'circle',
|
||||||
|
source: AIRPORTS_SOURCE_ID,
|
||||||
|
filter: ['any', ['==', ['get', 'icao'], ''], ['==', ['get', 'icao'], '']],
|
||||||
|
paint: {
|
||||||
|
'circle-radius': 8, // ring around the base airport circles (r=3)
|
||||||
|
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
||||||
|
'circle-stroke-width': 2.5,
|
||||||
|
'circle-stroke-color': '#facc15',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
// 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);
|
||||||
@@ -248,8 +332,10 @@ export default function FlightMap({ state }: MapProps) {
|
|||||||
map.on('click', PLANES_GROUNDED_LAYER_ID, onPlaneClick);
|
map.on('click', PLANES_GROUNDED_LAYER_ID, onPlaneClick);
|
||||||
map.off('click', PLANES_FLYING_LAYER_ID, onPlaneClick);
|
map.off('click', PLANES_FLYING_LAYER_ID, onPlaneClick);
|
||||||
map.on('click', PLANES_FLYING_LAYER_ID, onPlaneClick);
|
map.on('click', PLANES_FLYING_LAYER_ID, onPlaneClick);
|
||||||
// Sources were (re)created above — push the latest game state into them.
|
// Sources were (re)created above — push the latest game state into them, and re-apply
|
||||||
|
// the current hover filter to the (re-created) highlight layers.
|
||||||
applyDynamicRef.current();
|
applyDynamicRef.current();
|
||||||
|
applyHoverRef.current();
|
||||||
};
|
};
|
||||||
|
|
||||||
if (map.isStyleLoaded()) void ensureLayers();
|
if (map.isStyleLoaded()) void ensureLayers();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
|||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { abandonPenalty } from '@/lib/game/penalty';
|
import { abandonPenalty } from '@/lib/game/penalty';
|
||||||
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
||||||
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface RightPaneProps {
|
interface RightPaneProps {
|
||||||
state: StateSnapshot | null;
|
state: StateSnapshot | null;
|
||||||
@@ -12,6 +13,9 @@ interface RightPaneProps {
|
|||||||
// Push the full snapshot returned by an action endpoint into the shared shell state (v0.10.0),
|
// Push the full snapshot returned by an action endpoint into the shared shell state (v0.10.0),
|
||||||
// so the pane updates on click without waiting for the next poll tick.
|
// so the pane updates on click without waiting for the next poll tick.
|
||||||
applySnapshot: (snapshot: StateSnapshot) => void;
|
applySnapshot: (snapshot: StateSnapshot) => void;
|
||||||
|
// ISS-002 (v0.15.0): report row hovers to the shell so the map can highlight the plane or
|
||||||
|
// the package's endpoint airports.
|
||||||
|
onHover: (target: HoverTarget | null) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
|
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
|
||||||
@@ -100,7 +104,7 @@ function LoadControls({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RightPane({ state, loading, applySnapshot }: RightPaneProps) {
|
export default function RightPane({ state, loading, applySnapshot, onHover }: RightPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
// 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.
|
// snapshot prop changes every tick) or the next successful action.
|
||||||
@@ -192,7 +196,14 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
|
|||||||
{open.map((pkg) => {
|
{open.map((pkg) => {
|
||||||
const eligible = loadEligiblePlanes(state, pkg);
|
const eligible = loadEligiblePlanes(state, pkg);
|
||||||
return (
|
return (
|
||||||
<li key={pkg.id} data-testid={`open-package-${pkg.id}`} className="contract-row">
|
// ISS-002: hovering an open package highlights its two endpoint airports on the map.
|
||||||
|
<li
|
||||||
|
key={pkg.id}
|
||||||
|
data-testid={`open-package-${pkg.id}`}
|
||||||
|
className="contract-row"
|
||||||
|
onMouseEnter={() => onHover({ kind: 'package', originIcao: pkg.originIcao, destIcao: pkg.destIcao })}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
>
|
||||||
<div className="contract-main">
|
<div className="contract-main">
|
||||||
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||||
{eligible.length > 0 ? (
|
{eligible.length > 0 ? (
|
||||||
@@ -232,7 +243,16 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
|
|||||||
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<div key={plane.id} data-testid={`onboard-${plane.id}`} className="onboard-block">
|
// 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">
|
<div className="contract-main">
|
||||||
<span className="plane-model">{planeName(plane)}</span>
|
<span className="plane-model">{planeName(plane)}</span>
|
||||||
{plane.status === 'flying' ? (
|
{plane.status === 'flying' ? (
|
||||||
@@ -253,6 +273,15 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
|
|||||||
return (
|
return (
|
||||||
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
||||||
<div className="contract-main">
|
<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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid={`fly-to-${pkg.id}`}
|
data-testid={`fly-to-${pkg.id}`}
|
||||||
@@ -274,7 +303,7 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="contract-sub">
|
<div className="contract-sub">
|
||||||
<span>{pkg.originName} → {pkg.destName}</span>
|
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||||
<span>{formatCash(pkg.reward)}</span>
|
<span>{formatCash(pkg.reward)}</span>
|
||||||
{pkg.status === 'expired' ? (
|
{pkg.status === 'expired' ? (
|
||||||
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
||||||
@@ -385,7 +414,7 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
|
|||||||
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
if (refuelPlane) void runAction(`/api/planes/${refuelPlane.id}/refuel`);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Refuel
|
Refuel to full
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// 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.
|
||||||
|
|
||||||
|
export type HoverTarget =
|
||||||
|
| { kind: 'plane'; id: string }
|
||||||
|
| { kind: 'package'; originIcao: string; destIcao: string };
|
||||||
@@ -8,7 +8,7 @@ import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
|||||||
// directly on the single eligible plane, or shows a picker when several qualify.
|
// directly on the single eligible plane, or shows a picker when several qualify.
|
||||||
|
|
||||||
const CATALOG = [
|
const CATALOG = [
|
||||||
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510, capacity: 6 },
|
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9_300, speedKmh: 510, capacity: 6 },
|
||||||
];
|
];
|
||||||
|
|
||||||
function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
function plane(over: Partial<PlaneState> & Pick<PlaneState, 'id'>): PlaneState {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Isolated e2e stack for CI (.gitea/workflows/ci.yml) — runs on the runner's shared dind
|
||||||
|
# daemon under project name flight-ci (distinct from production). Joins the external
|
||||||
|
# network flight-ci-e2e that the workflow attaches the job container to; the app is reached
|
||||||
|
# at its STATIC IP http://172.39.0.10:3000 — DNS bypassed for the browser because Chromium
|
||||||
|
# got ERR_SSL_PROTOCOL_ERROR via the hostname while node-side HTTP worked (the `app` alias
|
||||||
|
# stays as a convenience). Single deterministic address; survives `docker compose restart flight`.
|
||||||
|
# The build context is tarred by the compose client in the job and sent over DOCKER_HOST,
|
||||||
|
# so nothing here needs to be visible from inside dind; game state lives in a named volume
|
||||||
|
# (fresh per run — CI cleanup removes it — survives `docker compose restart flight` for
|
||||||
|
# e2e/state.spec.ts).
|
||||||
|
services:
|
||||||
|
flight:
|
||||||
|
build: .
|
||||||
|
image: flight-ops-ci
|
||||||
|
environment:
|
||||||
|
FLIGHT_TEST_HOOKS: "1"
|
||||||
|
volumes:
|
||||||
|
# Self-hosted map-asset pack (styles/fonts/sprites): the workflow downloads it into ./public
|
||||||
|
# before build; absent/empty → app falls back to remote OFM styles. Mirrors docker-compose.yml's
|
||||||
|
# mount so e2e runs in self-hosted mode like local dev (map tests abort openfreemap.org traffic).
|
||||||
|
- "./public:/app/public"
|
||||||
|
- flight-db:/app/db
|
||||||
|
networks:
|
||||||
|
flight-ci-e2e:
|
||||||
|
aliases:
|
||||||
|
- app
|
||||||
|
ipv4_address: 172.39.0.10
|
||||||
|
|
||||||
|
networks:
|
||||||
|
flight-ci-e2e:
|
||||||
|
name: flight-ci-e2e
|
||||||
|
external: true
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
flight-db:
|
||||||
+68
-29
@@ -3,21 +3,30 @@ import { expect, test } from '@playwright/test';
|
|||||||
|
|
||||||
// v0.12.0 package model against the live origin (https://flight.dev.kkhost.pl):
|
// 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
|
// 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 60× →
|
// via the right pane → click its destination in the on-board list → fly at 1000× →
|
||||||
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
||||||
// penalty while grounded; expired packages deliver/abandon with no reward and no
|
// penalty while grounded; expired packages deliver/abandon with no reward and no
|
||||||
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
|
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
|
||||||
|
|
||||||
const SCALE = 60; // fastest sim speed — 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'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
const FAR = 'LEZL'; // Seville — one-way burn 3174 L > half tank, so the return leg is unfuelable
|
const FAR = 'LEZL'; // Seville — a long leg: under the v0.16.0 weighted model a full tank covers the
|
||||||
|
// round trip, but the return leaves too little for another outbound
|
||||||
|
|
||||||
// Mirrors lib/sim/movement.ts + lib/game/catalog.ts (atr72).
|
// Mirrors lib/sim/movement.ts (v0.16.0 weight-proportional burn) + lib/game/catalog.ts (atr72).
|
||||||
const BURN_PER_KM = 1.75;
|
const FUEL_DENSITY_KG_PER_L = 0.8; // Jet-A1 density — must match FUEL_DENSITY_KG_PER_L in movement.ts
|
||||||
const FUEL_PRICE_PER_L = 0.8;
|
const FUEL_PRICE_PER_L = 0.8; // must match catalog.ts
|
||||||
const REP_BASE = 1; // lib/sim/engine.ts
|
const REP_BASE = 1; // lib/sim/engine.ts
|
||||||
const REP_PER_KM = 0.0005;
|
const REP_PER_KM = 0.0005;
|
||||||
|
|
||||||
|
// Fuel remaining after distanceKm from startFuel — closed form of dF/dx = −k(We + ρF),
|
||||||
|
// k calibrated so a full tank burns exactly burnPerKm (mirrors fuelAtWeighted).
|
||||||
|
function fuelAfter(startFuel: number, burnPerKm: number, emptyWeightKg: number, maxFuel: number, distanceKm: number): number {
|
||||||
|
const k = burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return Math.max(0, (startFuel + emptyWeightKg / rho) * Math.exp(-k * rho * distanceKm) - emptyWeightKg / rho);
|
||||||
|
}
|
||||||
|
|
||||||
// Mirrors lib/game/penalty.ts — the exact abandon penalty at a given game clock.
|
// Mirrors lib/game/penalty.ts — the exact abandon penalty at a given game clock.
|
||||||
function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: number, clockMs: number): number {
|
function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: number, clockMs: number): number {
|
||||||
const span = deadlineSimTime - createdSimTime;
|
const span = deadlineSimTime - createdSimTime;
|
||||||
@@ -33,6 +42,7 @@ interface StateBody {
|
|||||||
id: string; originIcao: string; destIcao: string; reward: number; cargoType: string; cargoCount: number;
|
id: string; originIcao: string; destIcao: string; reward: number; cargoType: string; cargoCount: number;
|
||||||
deadlineSimTime: number; status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned'; planeId: string | null; createdSimTime: number;
|
deadlineSimTime: number; status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned'; planeId: string | null; createdSimTime: number;
|
||||||
}>;
|
}>;
|
||||||
|
catalog: Array<{ model: string; burnPerKm: number; emptyWeightKg: number; maxFuel: number }>; // v0.16.0 weighted burn inputs
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getState(page: Page): Promise<StateBody> {
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
@@ -90,15 +100,21 @@ test.describe.configure({ mode: 'serial' }); // shared live DB — order matters
|
|||||||
// (repositioning needs no package — v0.12.0 manual flight), and abandon any leftover cargo so
|
// (repositioning needs no package — v0.12.0 manual flight), and abandon any leftover cargo so
|
||||||
// exact cash/rep assertions start from a clean baseline even after an interrupted previous run.
|
// exact cash/rep assertions start from a clean baseline even after an interrupted previous run.
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
const s0 = await getState(page);
|
let s = await getState(page);
|
||||||
const plane = s0.planes.find((p) => p.id === 'plane-starter')!;
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
// Fast-forward any leftover leg / repositioning flight (~3 min real time worst case at 60×).
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
}
|
}
|
||||||
if (plane.status === 'flying') {
|
if (plane.status === 'flying') {
|
||||||
// Let the in-flight leg finish before repositioning.
|
// Let the in-flight leg finish before repositioning. While flying, locationIcao stays at the
|
||||||
|
// DEPARTURE airport, so the pre-landing snapshot can't tell us where the plane ends up — re-read
|
||||||
|
// state after landing before deciding whether a repositioning flight is needed (run #41 retry: a
|
||||||
|
// leftover EDDF→EDFH leg landed away from home but the helper still believed it was home and
|
||||||
|
// skipped the fly-home).
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.status), { timeout: 240_000 }).toBe('available');
|
||||||
|
s = await getState(page);
|
||||||
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
}
|
}
|
||||||
if (plane.locationIcao !== HUB) {
|
if (plane.locationIcao !== HUB) {
|
||||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
@@ -119,7 +135,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
|
|
||||||
|
|
||||||
test('full core loop via UI: load → fly to destination → exact reward + rep on arrival', async ({ page }) => {
|
test('full core loop via UI: load → fly to destination → exact reward + rep on arrival', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal (worst case ~3 min at 60×) + two short flights + refuel
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short flights + refuel
|
||||||
// Self-heal: the starter plane may be anywhere from a previous run/spec.
|
// Self-heal: the starter plane may be anywhere from a previous run/spec.
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
const before = await getState(page);
|
const before = await getState(page);
|
||||||
@@ -133,6 +149,14 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
expect(pkg.originIcao).toBe(HUB);
|
expect(pkg.originIcao).toBe(HUB);
|
||||||
expect(pkg.destIcao).toBe(nearest.icao);
|
expect(pkg.destIcao).toBe(nearest.icao);
|
||||||
|
|
||||||
|
// Precondition (server truth) before clicking Load: the starter must be grounded at the package's
|
||||||
|
// origin — that is exactly what makes it load-eligible, and a stale pane snapshot can't prove it.
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
return p.status === 'available' && p.locationIcao === pkg.originIcao;
|
||||||
|
}, { timeout: 30_000, message: 'waiting for plane-starter to be grounded at the package origin (self-heal incomplete?)' }).toBe(true);
|
||||||
|
|
||||||
// LOAD via the UI: exactly one eligible plane (the starter at EDDF) → direct button.
|
// LOAD via the UI: exactly one eligible plane (the starter at EDDF) → direct button.
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
const loadBtn = page.getByTestId(`load-${pkg.id}`);
|
const loadBtn = page.getByTestId(`load-${pkg.id}`);
|
||||||
@@ -149,12 +173,19 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
await expect(flyBtn).toBeEnabled();
|
await expect(flyBtn).toBeEnabled();
|
||||||
await flyBtn.click();
|
await flyBtn.click();
|
||||||
|
|
||||||
let s = await getState(page);
|
|
||||||
const planeId = 'plane-starter';
|
const planeId = 'plane-starter';
|
||||||
expect(s.planes.find((p) => p.id === planeId)!.status).toBe('flying');
|
// The click fires the fly POST asynchronously (runAction is fire-and-forget from the test's view),
|
||||||
expect(s.planes.find((p) => p.id === planeId)!.destIcao).toBe(nearest.icao);
|
// so a getState issued immediately can race ahead of it and still see 'available' — poll until the
|
||||||
|
// fly actually took effect on the server (the run #36/#41 flake).
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === planeId)!;
|
||||||
|
return p.status === 'flying' && p.destIcao === nearest.icao;
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the fly click to take effect (status "flying" + dest set)' }).toBe(true);
|
||||||
|
|
||||||
// Fast-forward to arrival (≤ ~10 min game time at 60× → seconds of real time).
|
let s = await getState(page);
|
||||||
|
|
||||||
|
// Fast-forward to arrival (a few seconds of real time at 1000×).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.status), { timeout: 120_000 }).toBe('available');
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.status), { timeout: 120_000 }).toBe('available');
|
||||||
|
|
||||||
@@ -174,8 +205,12 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
const repGain = Math.round((REP_BASE + REP_PER_KM * exactKm) * 100) / 100;
|
const repGain = Math.round((REP_BASE + REP_PER_KM * exactKm) * 100) / 100;
|
||||||
expect(s.account.reputation).toBeCloseTo(Math.round((before.account.reputation + repGain) * 100) / 100, 9);
|
expect(s.account.reputation).toBeCloseTo(Math.round((before.account.reputation + repGain) * 100) / 100, 9);
|
||||||
|
|
||||||
// Fuel burned exactly burnPerKm × km (analytic movement — no rounding drift).
|
// Fuel burned per the v0.16.0 weight-proportional model (closed form — no rounding drift).
|
||||||
expect(landed.fuel).toBeCloseTo(Math.max(0, before.planes.find((p) => p.id === planeId)!.fuel - BURN_PER_KM * exactKm), 6);
|
const entry = before.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
expect(landed.fuel).toBeCloseTo(
|
||||||
|
fuelAfter(before.planes.find((p) => p.id === planeId)!.fuel, entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, exactKm),
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
|
||||||
// Refuel via the API: cost = (maxFuel − fuel) × FUEL_PRICE_PER_L, deducted exactly.
|
// Refuel via the API: cost = (maxFuel − fuel) × FUEL_PRICE_PER_L, deducted exactly.
|
||||||
const refuelRes = await page.request.post(`/api/planes/${planeId}/refuel`);
|
const refuelRes = await page.request.post(`/api/planes/${planeId}/refuel`);
|
||||||
@@ -230,7 +265,7 @@ test('abandon while grounded deducts exactly the formula penalty', async ({ page
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('expired packages deliver and abandon with no reward and no penalty', async ({ page }) => {
|
test('expired packages deliver and abandon with no reward and no penalty', async ({ page }) => {
|
||||||
test.setTimeout(480_000); // two ~3 min real-time legs at 60× (HUB↔LEMD) plus expiry wait
|
test.setTimeout(480_000); // two ~10 s real-time legs at 1000× (HUB↔LEMD) plus expiry wait
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
const before = await getState(page);
|
const before = await getState(page);
|
||||||
|
|
||||||
@@ -281,7 +316,7 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
||||||
test.setTimeout(600_000); // the FAR round trip alone is ~7.5 min real time at 60×
|
test.setTimeout(600_000); // the FAR round trip alone is ~30 s real time at 1000×
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Load a package whose origin the plane is not at → 409.
|
// Load a package whose origin the plane is not at → 409.
|
||||||
@@ -317,12 +352,14 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
||||||
|
|
||||||
// Insufficient fuel: a full-tank one-way burn of > half the tank makes the return leg unfuelable.
|
// Insufficient fuel (v0.16.0 weighted burn): a full tank covers the FAR round trip —
|
||||||
|
// the plane gets lighter as fuel burns off, so both legs fit — but landing back at the
|
||||||
|
// hub leaves too little for ANOTHER long leg: the second outbound must 409.
|
||||||
const s0 = await getState(page);
|
const s0 = await getState(page);
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect(starter.locationIcao).toBe(HUB); // landed back at the hub from the hop above
|
expect(starter.locationIcao).toBe(HUB); // landed back at the hub from the hop above
|
||||||
if (starter.fuel < starter.maxFuel) {
|
if (starter.fuel < starter.maxFuel) {
|
||||||
await page.request.post('/api/planes/plane-starter/refuel'); // ensure a full tank for the long leg
|
await page.request.post('/api/planes/plane-starter/refuel'); // ensure a full tank for the long legs
|
||||||
}
|
}
|
||||||
const farRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
const farRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
||||||
expect(farRes.ok()).toBeTruthy();
|
expect(farRes.ok()).toBeTruthy();
|
||||||
@@ -332,16 +369,18 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
const sFar = await getState(page);
|
const sFar = await getState(page);
|
||||||
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect(atFar.locationIcao).toBe(FAR);
|
expect(atFar.locationIcao).toBe(FAR);
|
||||||
// The return leg needs the same burn as the outbound — more than what's left.
|
// The return leg fits: the weighted burn over it is less than what's left in the tank.
|
||||||
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(backRes.status()).toBe(409);
|
expect(backRes.ok()).toBeTruthy();
|
||||||
expect(((await backRes.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
|
||||||
|
|
||||||
// Restore: refuel + fly home.
|
|
||||||
await page.request.post('/api/planes/plane-starter/refuel');
|
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
|
|
||||||
|
// …but the tank is now too light for another FAR leg.
|
||||||
|
const againFar = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: FAR } });
|
||||||
|
expect(againFar.status()).toBe(409);
|
||||||
|
expect(((await againFar.json()) as { error: string }).error).toMatch(/insufficient fuel/i);
|
||||||
|
|
||||||
|
// Restore: refuel (the plane is already home).
|
||||||
|
await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Great-circle distance in km — mirrors lib/geo.ts (same formula, same R).
|
// Great-circle distance in km — mirrors lib/geo.ts (same formula, same R).
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// CI-only connectivity diagnostics (globalSetup runs after the e2e stack is ready).
|
||||||
|
// Evidence for the Chromium ERR_SSL_PROTOCOL_ERROR hunt: compares node-side resolution/HTTP
|
||||||
|
// against Chromium's own navigation, hostname vs static IP. Never fails the run.
|
||||||
|
import { promises as dnsPromises } from 'node:dns';
|
||||||
|
import { chromium } from '@playwright/test';
|
||||||
|
|
||||||
|
export default async function ciDiagnostics() {
|
||||||
|
if (process.env.PW_REMOTE_BROWSER !== '0') return; // local runs: no-op
|
||||||
|
const base = process.env.E2E_BASE_URL ?? '';
|
||||||
|
try {
|
||||||
|
console.log('[diag] node resolve4(app):', JSON.stringify(await dnsPromises.resolve4('app').catch((e) => `failed: ${e.code}`)));
|
||||||
|
try {
|
||||||
|
const r = await fetch(`${base}/api/version`);
|
||||||
|
console.log('[diag] node fetch', base, '->', r.status, JSON.stringify(await r.json().catch(() => null)));
|
||||||
|
} catch (e) {
|
||||||
|
console.log('[diag] node fetch failed:', String(e));
|
||||||
|
}
|
||||||
|
const browser = await chromium.launch();
|
||||||
|
try {
|
||||||
|
for (const url of ['http://app:3000/', base]) {
|
||||||
|
const page = await (await browser.newContext()).newPage();
|
||||||
|
try {
|
||||||
|
await page.goto(url, { timeout: 15_000 });
|
||||||
|
console.log('[diag] chromium goto', url, '-> OK, title:', await page.title().catch(() => '?'));
|
||||||
|
} catch (e) {
|
||||||
|
console.log('[diag] chromium goto', url, '-> FAILED:', String(e).split('\n')[0]);
|
||||||
|
}
|
||||||
|
await page.context().close();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('[diag] diagnostics error (non-fatal):', String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
import { test, expect, type Page } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.15.0 — ISS-002: hovering a plane or package in either side panel highlights it on the map.
|
||||||
|
// Fleet rows + on-board blocks highlight the plane marker (and its route leg while flying);
|
||||||
|
// open-package rows highlight both endpoint airports. The map exposes three top-most
|
||||||
|
// 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.
|
||||||
|
|
||||||
|
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
|
||||||
|
// Madrid–Barajas — same long leg as e2e/map-interactions.spec.ts: ~1420 km → ~10 s at scale 1000.
|
||||||
|
const DEST = 'LEMD';
|
||||||
|
|
||||||
|
interface PlaneState {
|
||||||
|
id: string;
|
||||||
|
model: string;
|
||||||
|
status: 'available' | 'flying';
|
||||||
|
fuel: number;
|
||||||
|
maxFuel: number;
|
||||||
|
locationIcao: string;
|
||||||
|
destIcao: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PackageState {
|
||||||
|
id: string;
|
||||||
|
originName: string;
|
||||||
|
destName: string;
|
||||||
|
reward: number;
|
||||||
|
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
|
||||||
|
planeId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
account: { cash: number; reputation: number };
|
||||||
|
simState: { clockMs: number; timeScale: number; paused: boolean };
|
||||||
|
planes: PlaneState[];
|
||||||
|
packages: PackageState[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postSim(page: Page, body: unknown) {
|
||||||
|
return page.request.post('/api/sim', { data: body });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
|
||||||
|
// otherwise surface as an unexplained landing-wait timeout.
|
||||||
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave the live instance in a sane state for the other specs (scale 1, running).
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
const res = await postSim(page, { timeScale: 1, paused: false });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
||||||
|
async function createPackage(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
||||||
|
const created = await page.request.post('/api/test/create-package', {
|
||||||
|
data: { originIcao: fromIcao, destIcao: toIcao, deadlineOffsetMs: 24 * 3_600_000 },
|
||||||
|
});
|
||||||
|
expect(created.status()).toBe(201);
|
||||||
|
return (await created.json()) as PackageState;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
||||||
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
|
const s0 = await getState(page);
|
||||||
|
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (starter.status === 'flying') {
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.status === 'available', {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for an in-flight plane-starter to land',
|
||||||
|
})
|
||||||
|
.toBe(true);
|
||||||
|
}
|
||||||
|
if (starter.locationIcao !== HUB) {
|
||||||
|
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForAirportCount(page: Page): Promise<void> {
|
||||||
|
const countEl = page.getByTestId('airport-count');
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const text = (await countEl.textContent()) ?? '';
|
||||||
|
const m = text.match(/(\d+)/);
|
||||||
|
return m ? parseInt(m[1], 10) : -1;
|
||||||
|
}).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rendered features of the given layers in the current viewport, [] until the map exists.
|
||||||
|
function renderedFeatures(page: Page, layers: string[]) {
|
||||||
|
return page.evaluate((ls: string[]) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) return [];
|
||||||
|
try {
|
||||||
|
return m.queryRenderedFeatures(undefined, { layers: ls });
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}, layers);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move the pointer to a neutral element with no hover handler — leaves any hovered row/block.
|
||||||
|
async function unhover(page: Page): Promise<void> {
|
||||||
|
await page.getByTestId('wallet-cash').hover();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fit the map so all given airports are in-viewport — queryRenderedFeatures only returns
|
||||||
|
// features rendered inside the CURRENT viewport, and the default Frankfurt-centered view leaves
|
||||||
|
// far endpoints (LEMD) off-screen even when they match a layer filter.
|
||||||
|
async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const points = icaos.map((icao) => {
|
||||||
|
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] as [number, number];
|
||||||
|
});
|
||||||
|
await page.evaluate((pts: [number, number][]) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) throw new Error('map not ready');
|
||||||
|
const lons = pts.map((p) => p[0]);
|
||||||
|
const lats = pts.map((p) => p[1]);
|
||||||
|
// duration 0 → instant camera jump, no animation to wait out.
|
||||||
|
m.fitBounds(
|
||||||
|
[
|
||||||
|
[Math.min(...lons), Math.min(...lats)],
|
||||||
|
[Math.max(...lons), Math.max(...lats)],
|
||||||
|
],
|
||||||
|
{ padding: 40, duration: 0 },
|
||||||
|
);
|
||||||
|
}, points);
|
||||||
|
// Give the renderer a beat after the camera jump before asserting on rendered features.
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
// Fleet rows are <li data-testid={`plane-${p.id}`}> and the server id already carries the "plane-"
|
||||||
|
// prefix (run #34: the real testid is plane-plane-starter) — derive it from /api/state, never hardcode.
|
||||||
|
const planes = (await getState(page)).planes;
|
||||||
|
const starterId = planes.find((p) => p.id.endsWith('starter'))?.id ?? (planes.length === 1 ? planes[0].id : undefined);
|
||||||
|
expect(starterId).toBeDefined();
|
||||||
|
const row = page.locator(`li[data-testid="plane-${starterId}"]`);
|
||||||
|
// The browser's /api/state polls can lag node-side requests right after a fresh page load
|
||||||
|
// (useGameState keeps loading=true until the first success → no fleet rows yet), so poll with
|
||||||
|
// diagnostics: on timeout the message compares what the NODE side sees vs what the BROWSER
|
||||||
|
// last polled, plus the fleet section's HTML — distinguishing server divergence from a render
|
||||||
|
// bug. (The value is returned, not thrown — expect.poll fails immediately on a callback throw
|
||||||
|
// instead of retrying.)
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
if ((await row.count()) > 0 && (await row.isVisible())) return 'visible';
|
||||||
|
const body = await getState(page);
|
||||||
|
const browserSnap = await page.evaluate(() => (window as any).__flightLastSnapshot ?? null);
|
||||||
|
const fleetHtml = await page.evaluate(() => {
|
||||||
|
const el = document.querySelector('[data-testid="fleet-list"]');
|
||||||
|
if (el) return `fleet-list HTML: ${(el.outerHTML ?? '').slice(0, 300)}`;
|
||||||
|
const pane = document.querySelector<HTMLElement>('[data-testid="left-pane"]');
|
||||||
|
return `no fleet-list — left-pane text: ${(pane?.innerText ?? '').slice(0, 200)}`;
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
`not visible — node /api/state planes=[${body.planes.map((p) => p.id).join(', ')}] cash=${body.account.cash}; ` +
|
||||||
|
`browser __flightLastSnapshot=${JSON.stringify(browserSnap)}; ${fleetHtml}`
|
||||||
|
);
|
||||||
|
}, { timeout: 30_000 })
|
||||||
|
.toBe('visible');
|
||||||
|
|
||||||
|
// No highlight before hovering (the layers start filtered to match nothing).
|
||||||
|
expect(await renderedFeatures(page, ['planes-highlight'])).toHaveLength(0);
|
||||||
|
|
||||||
|
await row.hover();
|
||||||
|
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 === starterId;
|
||||||
|
}, { timeout: 15_000, message: `waiting for the planes-highlight layer to show ${starterId}` }).toBe(true);
|
||||||
|
|
||||||
|
await unhover(page);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['planes-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the highlight to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hovering an open package highlights its endpoint airports', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
const row = page.locator(`li[data-testid="open-package-${pkg.id}"]`);
|
||||||
|
await expect(row, 'the hook-created package appears in the list').toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Both endpoints must be in-viewport for queryRenderedFeatures to see them (LEMD is off-screen
|
||||||
|
// at the default Frankfurt-centered view).
|
||||||
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
|
||||||
|
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
|
||||||
|
|
||||||
|
await row.hover();
|
||||||
|
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 show both endpoints' })
|
||||||
|
.toBe(JSON.stringify([HUB, DEST].sort()));
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hovering an on-board block of a flying plane highlights its route', 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);
|
||||||
|
|
||||||
|
// The on-board block shows the plane in flight once a snapshot with status 'flying' lands.
|
||||||
|
const block = page.getByTestId('onboard-plane-starter');
|
||||||
|
await expect(block).toContainText(/in flight/i, { timeout: 15_000 });
|
||||||
|
|
||||||
|
// Freeze mid-flight so the ~10 s leg can't land under us while we assert (same pattern as
|
||||||
|
// e2e/map-interactions.spec.ts' marker click): the route line stays drawn while paused.
|
||||||
|
await postSim(page, { paused: true });
|
||||||
|
|
||||||
|
await block.hover();
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const feats = (await renderedFeatures(page, ['routes-highlight'])) as Array<{ properties: Record<string, unknown> }>;
|
||||||
|
return feats.length > 0 && feats[0].properties.planeId === 'plane-starter';
|
||||||
|
}, { timeout: 15_000, message: 'waiting for the routes-highlight layer to show the plane-starter leg' }).toBe(true);
|
||||||
|
|
||||||
|
await unhover(page);
|
||||||
|
await expect.poll(async () => (await renderedFeatures(page, ['routes-highlight'])).length, {
|
||||||
|
timeout: 15_000,
|
||||||
|
message: 'waiting for the highlight to clear after mouseleave',
|
||||||
|
}).toBe(0);
|
||||||
|
|
||||||
|
// Resume and fast-forward to arrival, then fly home so the live instance stays in its
|
||||||
|
// onboarding state (starter grounded at EDDF) 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);
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -5,14 +5,16 @@ import { test, expect, type Page } from '@playwright/test';
|
|||||||
// deterministic generated weather), plane markers whose positions come from the
|
// deterministic generated weather), plane markers whose positions come from the
|
||||||
// /api/state polls, each FLYING plane's current leg as a route line (origin →
|
// /api/state polls, each FLYING plane's current leg as a route line (origin →
|
||||||
// dest_icao; grounded planes draw nothing), and the plane status popup. Packages
|
// dest_icao; grounded planes draw nothing), and the plane status popup. Packages
|
||||||
// are created on a known EDDF→EDDV route via POST /api/test/create-package
|
// are created on a known EDDF→LEMD route via POST /api/test/create-package
|
||||||
// (FLIGHT_TEST_HOOKS=1).
|
// (FLIGHT_TEST_HOOKS=1).
|
||||||
|
|
||||||
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||||
// Hannover — ~282 km from EDDF → ~33 min game time ≈ 33 s at scale 60, a comfortable
|
// Madrid–Barajas — ~1420 km from EDDF → ~2.8 h game time ≈ 10 s at scale 1000, a comfortable
|
||||||
// window for the click assertions below (the nearest airport would land too fast).
|
// window for the mid-flight click assertions below (at 1000× even Hannover's 33-min leg would
|
||||||
const DEST = 'EDDV';
|
// land in ~2 s — shorter than the map poll + click pipeline). Round-trip burn (~4970 L) fits
|
||||||
const SCALE = 60;
|
// the 6300 L tank, so a full-tank departure always makes it home.
|
||||||
|
const DEST = 'LEMD';
|
||||||
|
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top)
|
||||||
|
|
||||||
interface PlaneState {
|
interface PlaneState {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -91,7 +93,7 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string): Prom
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Load a package onto plane-starter and fly it from → to via the API, then poll at
|
// Load a package onto plane-starter and fly it from → to via the API, then poll at
|
||||||
// scale 60 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
|
// scale 1000 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
|
||||||
async function loadAndFly(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
async function loadAndFly(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
|
||||||
const pkg = await createPackage(page, fromIcao, toIcao);
|
const pkg = await createPackage(page, fromIcao, toIcao);
|
||||||
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
@@ -170,8 +172,8 @@ test('airport popup shows name, ICAO, local time and generated weather', async (
|
|||||||
expect(wText).toMatch(/\d+ kt/); // wind speed in knots
|
expect(wText).toMatch(/\d+ kt/); // wind speed in knots
|
||||||
});
|
});
|
||||||
|
|
||||||
test('plane markers move while flying, the current leg draws a route line, and the plane popup shows status + route', async ({ page }) => {
|
test('plane markers move while flying and the plane popup shows status + route', async ({ page }) => {
|
||||||
test.setTimeout(600_000); // self-heal from a far airport (~4 min worst case at 60×) + main flight + cleanup
|
test.setTimeout(600_000); // self-heal from a far airport (~20 s worst case at 1000×) + main flight + cleanup
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await waitForAirportCount(page);
|
await waitForAirportCount(page);
|
||||||
@@ -195,6 +197,11 @@ test('plane markers move while flying, the current leg draws a route line, and t
|
|||||||
await loadAndFly(page, starterLoc, HUB);
|
await loadAndFly(page, starterLoc, HUB);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank,
|
||||||
|
// so a partially drained plane left by an earlier spec could not make it home.
|
||||||
|
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
expect(refuel.status()).toBe(200);
|
||||||
|
|
||||||
// 1) Load the hook-created package — a GROUNDED plane draws no route line yet.
|
// 1) Load the hook-created package — a GROUNDED plane draws no route line yet.
|
||||||
const pkg = await createPackage(page, HUB, DEST);
|
const pkg = await createPackage(page, HUB, DEST);
|
||||||
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
|
||||||
@@ -238,35 +245,56 @@ test('plane markers move while flying, the current leg draws a route line, and t
|
|||||||
const p2 = (await getState(page)).planes.find((p) => p.id === 'plane-starter')!;
|
const p2 = (await getState(page)).planes.find((p) => p.id === 'plane-starter')!;
|
||||||
expect(haversineKm(p1.lat, p1.lon, p2.lat, p2.lon)).toBeGreaterThan(0);
|
expect(haversineKm(p1.lat, p1.lon, p2.lat, p2.lon)).toBeGreaterThan(0);
|
||||||
|
|
||||||
// 4) The route line for this flight exists in the routes source (v0.12.0: one line
|
// (No map-side assertion on the drawn leg here: MapLibre's querySourceFeatures returns
|
||||||
// per flying plane's current leg, keyed by planeId) and is a CURVED arc — >2
|
// tile-simplified geometry at low zoom, so coordinate counts from it are unreliable —
|
||||||
// coordinates along the great circle, not a straight two-point chord (v0.12.2).
|
// the v0.12.2 curved-arc check failed in CI and live while the arc rendered correctly.
|
||||||
|
// The arc itself stays covered by unit tests: lib/mapData.test.ts.)
|
||||||
|
|
||||||
|
// 4) Click the flying plane → status popup with model, status, fuel and the leg.
|
||||||
|
// Freeze the sim so the click can't miss a fast-moving marker: at scale 1000 the rendered
|
||||||
|
// marker lags our fresh /api/state fetch by up to one map poll (~1 s) — tens of px of drift
|
||||||
|
// on this leg. Pausing makes the position static; we resume right after the popup checks.
|
||||||
|
await postSim(page, { paused: true });
|
||||||
|
let prevPos: { lat: number; lon: number } | null = null;
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => {
|
.poll(async () => {
|
||||||
const feats = (await sourceFeatures(page, 'routes')) as Array<{
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
|
||||||
properties: Record<string, unknown>;
|
if (!p || p.status !== 'flying') return false;
|
||||||
geometry?: { type: string; coordinates: [number, number][] };
|
if (prevPos && prevPos.lat === p.lat && prevPos.lon === p.lon) return true;
|
||||||
}>;
|
prevPos = { lat: p.lat, lon: p.lon };
|
||||||
const f = feats.find((x) => x.properties.planeId === 'plane-starter');
|
return false;
|
||||||
return !!f && (f.geometry?.coordinates.length ?? 0) > 2;
|
}, { timeout: 15_000, message: 'waiting for the paused clock to freeze the plane position' })
|
||||||
}, { timeout: 15_000, message: 'waiting for the curved route line in the routes source' })
|
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
// 5) Click the flying plane → status popup with model, status, fuel and the leg.
|
// Click the RENDERED marker position, not a fresh /api/state fetch. With the sim paused
|
||||||
// Fetch + project in one evaluate so the click lands on a fresh position (the
|
// above the server's analytic position is static — but the map renders from its own ~1 s
|
||||||
// marker drifts only ~1 px/s of screen space at scale 60).
|
// poll, so right after the freeze confirmation the last rendered frame can still be up to
|
||||||
|
// one poll interval stale (tens of px at scale 1000 on this leg) and a click projected
|
||||||
|
// from a fresh fetch misses the small circle layer (CI run #37). Poll for the plane's
|
||||||
|
// rendered feature instead and project ITS coordinates — exactly what the map draws.
|
||||||
|
// Find + project in one evaluate so nothing can change between the two steps.
|
||||||
const pt = await page.evaluate(async () => {
|
const pt = await page.evaluate(async () => {
|
||||||
const m = (window as any).__flightMap;
|
const m = (window as any).__flightMap;
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
const res = await fetch('/api/state', { cache: 'no-store' });
|
const deadline = Date.now() + 5_000;
|
||||||
const body = (await res.json()) as StateBody;
|
for (;;) {
|
||||||
const p = body.planes.find((x) => x.id === 'plane-starter');
|
let feats: Array<{ properties?: Record<string, unknown>; geometry?: { coordinates: number[] } }> = [];
|
||||||
if (!p || p.status !== 'flying') return null;
|
try {
|
||||||
const projected = m.project([p.lon, p.lat]);
|
feats = m.queryRenderedFeatures(undefined, { layers: ['planes-flying', 'planes-grounded'] });
|
||||||
const rect = m.getContainer().getBoundingClientRect();
|
} catch {
|
||||||
return { x: rect.left + projected.x, y: rect.top + projected.y };
|
// map not ready yet — keep polling
|
||||||
|
}
|
||||||
|
const f = feats.find((x) => x.properties?.id === 'plane-starter');
|
||||||
|
if (f && f.geometry) {
|
||||||
|
const projected = m.project(f.geometry.coordinates);
|
||||||
|
const rect = m.getContainer().getBoundingClientRect();
|
||||||
|
return { x: rect.left + projected.x, y: rect.top + projected.y };
|
||||||
|
}
|
||||||
|
if (Date.now() >= deadline) return null;
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
expect(pt).not.toBeNull(); // the flight (~33 s at scale 60) is still in progress here
|
expect(pt, 'plane marker not rendered after pause').not.toBeNull();
|
||||||
|
|
||||||
await page.mouse.click(pt!.x, pt!.y);
|
await page.mouse.click(pt!.x, pt!.y);
|
||||||
const popup = page.getByTestId('plane-popup');
|
const popup = page.getByTestId('plane-popup');
|
||||||
@@ -279,7 +307,10 @@ test('plane markers move while flying, the current leg draws a route line, and t
|
|||||||
// The popup's route line is the plane's own leg: origin name → destination name.
|
// The popup's route line is the plane's own leg: origin name → destination name.
|
||||||
await expect(page.getByTestId('plane-route')).toContainText(`${live.locationName} → ${live.destName}`);
|
await expect(page.getByTestId('plane-route')).toContainText(`${live.locationName} → ${live.destName}`);
|
||||||
|
|
||||||
// 6) Let the flight finish, then fly home so the live instance stays in its
|
// Resume before step 5 — the landing wait needs a running clock.
|
||||||
|
await postSim(page, { timeScale: SCALE, paused: false });
|
||||||
|
|
||||||
|
// 5) Let the flight finish, then fly home so the live instance stays in its
|
||||||
// onboarding state (starter grounded at EDDF) for the other specs. The loaded
|
// onboarding state (starter grounded at EDDF) for the other specs. The loaded
|
||||||
// package is delivered on arrival (in-deadline).
|
// package is delivered on arrival (in-deadline).
|
||||||
await expect
|
await expect
|
||||||
|
|||||||
+44
-8
@@ -4,6 +4,8 @@ import { test, expect, type Page } from '@playwright/test';
|
|||||||
// The panes render from the shell's single /api/state poll (lib/useGameState.ts); time
|
// The panes render from the shell's single /api/state poll (lib/useGameState.ts); time
|
||||||
// controls POST to /api/sim and refetch immediately, so UI assertions settle within a tick.
|
// controls POST to /api/sim and refetch immediately, so UI assertions settle within a tick.
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||||
|
|
||||||
interface SimState {
|
interface SimState {
|
||||||
clockMs: number;
|
clockMs: number;
|
||||||
timeScale: number;
|
timeScale: number;
|
||||||
@@ -69,7 +71,7 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
|
|||||||
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('time controls: pause freezes the sim and the power-of-two slider sets timeScale', async ({ page }) => {
|
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
const pauseBtn = page.getByTestId('pause-toggle');
|
const pauseBtn = page.getByTestId('pause-toggle');
|
||||||
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
|
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
|
||||||
@@ -80,13 +82,13 @@ test('time controls: pause freezes the sim and the power-of-two slider sets time
|
|||||||
// …and in the pane itself (the refetch after POST flips the button to Resume).
|
// …and in the pane itself (the refetch after POST flips the button to Resume).
|
||||||
await expect(pauseBtn).toHaveText('Resume');
|
await expect(pauseBtn).toHaveText('Resume');
|
||||||
|
|
||||||
// Scale via the power-of-two slider. End jumps to max (t=1 → 64×): the label updates
|
// Scale via the ladder slider. End jumps to max (t=1 → 1000×): the label updates
|
||||||
// optimistically on input, and release flushes the debounced POST immediately.
|
// optimistically on input, and release flushes the debounced POST immediately.
|
||||||
const slider = page.getByTestId('time-scale-slider');
|
const slider = page.getByTestId('time-scale-slider');
|
||||||
await slider.focus();
|
await slider.focus();
|
||||||
await page.keyboard.press('End');
|
await page.keyboard.press('End');
|
||||||
await expect(page.getByTestId('time-scale-value')).toHaveText('64×', { timeout: 10_000 });
|
await expect(page.getByTestId('time-scale-value')).toHaveText('1000×', { timeout: 10_000 });
|
||||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(64);
|
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1000);
|
||||||
|
|
||||||
// Home jumps to min (t=0 → 1×).
|
// Home jumps to min (t=0 → 1×).
|
||||||
await page.keyboard.press('Home');
|
await page.keyboard.press('Home');
|
||||||
@@ -104,6 +106,40 @@ test('time controls: pause freezes the sim and the power-of-two slider sets time
|
|||||||
expect(after.simState.paused).toBe(false);
|
expect(after.simState.paused).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('sim clock ticks smoothly between polls — seconds advance without waiting for a snapshot (ISS-007)', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
const clock = page.getByTestId('sim-clock');
|
||||||
|
await expect(clock).toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
|
// Fastest scale so game seconds move visibly inside the sampling window.
|
||||||
|
const post = await page.request.post('/api/sim', { data: { timeScale: SCALE, paused: false } });
|
||||||
|
expect(post.status()).toBe(200);
|
||||||
|
|
||||||
|
// "YYYY-MM-DD HH:MM:SS UTC" → epoch ms (UTC). While running there is no "(paused)" suffix.
|
||||||
|
const sample = async () => {
|
||||||
|
const text = ((await clock.textContent()) ?? '').trim();
|
||||||
|
expect(text, `clock format: ${text}`).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/);
|
||||||
|
return Date.parse(text.replace(' ', 'T').replace(' UTC', 'Z'));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Three samples ~1.3 s apart real time: at scale 1000 each gap is ≈1300 game seconds, so the
|
||||||
|
// displayed clock must strictly advance between CONSECUTIVE samples — with the old poll-only
|
||||||
|
// rendering a sample pair could straddle zero snapshot updates and show no change at all.
|
||||||
|
const t0 = await sample();
|
||||||
|
await new Promise((r) => setTimeout(r, 1_300));
|
||||||
|
const t1 = await sample();
|
||||||
|
await new Promise((r) => setTimeout(r, 1_300));
|
||||||
|
const t2 = await sample();
|
||||||
|
|
||||||
|
expect(t1).toBeGreaterThan(t0);
|
||||||
|
expect(t2).toBeGreaterThan(t1);
|
||||||
|
// Sanity: ~2.6 s real × 1000 ≈ 2.6 M game ms — generous bounds keep slow CI boxes safe while
|
||||||
|
// still catching a frozen or wildly mis-scaled clock.
|
||||||
|
const total = t2 - t0;
|
||||||
|
expect(total).toBeGreaterThanOrEqual(1_000_000);
|
||||||
|
expect(total).toBeLessThanOrEqual(6_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
test('slider commit keeps the chosen scale on screen until confirmed — no snap-back (ISS-001)', async ({ page }) => {
|
test('slider commit keeps the chosen scale on screen until confirmed — no snap-back (ISS-001)', async ({ page }) => {
|
||||||
test.setTimeout(60_000);
|
test.setTimeout(60_000);
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
@@ -116,19 +152,19 @@ test('slider commit keeps the chosen scale on screen until confirmed — no snap
|
|||||||
|
|
||||||
// …and sample the displayed value rapidly across the whole commit→confirm window. With the
|
// …and sample the displayed value rapidly across the whole commit→confirm window. With the
|
||||||
// ISS-001 fix the optimistic value stays until a snapshot confirms it, so EVERY sample must
|
// ISS-001 fix the optimistic value stays until a snapshot confirms it, so EVERY sample must
|
||||||
// be '64×' — never snapping back to the previous scale for one poll cycle (the old bug).
|
// be '1000×' — never snapping back to the previous scale for one poll cycle (the old bug).
|
||||||
const seen: string[] = [];
|
const seen: string[] = [];
|
||||||
for (let i = 0; i < 30; i++) {
|
for (let i = 0; i < 30; i++) {
|
||||||
seen.push(((await page.getByTestId('time-scale-value').textContent()) ?? '').trim());
|
seen.push(((await page.getByTestId('time-scale-value').textContent()) ?? '').trim());
|
||||||
await new Promise((r) => setTimeout(r, 25));
|
await new Promise((r) => setTimeout(r, 25));
|
||||||
}
|
}
|
||||||
expect(
|
expect(
|
||||||
seen.every((v) => v === '64×'),
|
seen.every((v) => v === '1000×'),
|
||||||
`displayed scale must stay 64× during the commit window (saw: ${[...new Set(seen)].join(', ')})`,
|
`displayed scale must stay 1000× during the commit window (saw: ${[...new Set(seen)].join(', ')})`,
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
|
|
||||||
// …and the server confirms it.
|
// …and the server confirms it.
|
||||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(64);
|
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1000);
|
||||||
|
|
||||||
// Restore to min for later tests (afterEach restores scale anyway).
|
// Restore to min for later tests (afterEach restores scale anyway).
|
||||||
await page.keyboard.press('Home');
|
await page.keyboard.press('Home');
|
||||||
|
|||||||
+110
-5
@@ -8,7 +8,7 @@ import { expect, test } from '@playwright/test';
|
|||||||
// match the catalog + economy constants exposed in /api/state. Packages are created via
|
// match the catalog + economy constants exposed in /api/state. 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 = 60;
|
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
|
||||||
|
|
||||||
interface PlaneState {
|
interface PlaneState {
|
||||||
@@ -38,6 +38,7 @@ interface CatalogEntry {
|
|||||||
price: number;
|
price: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
emptyWeightKg: number; // v0.16.0 weighted burn input
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
capacity: number;
|
capacity: number;
|
||||||
}
|
}
|
||||||
@@ -98,7 +99,7 @@ function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: num
|
|||||||
return Math.round(reward * (0.15 + 0.45 * frac) * 100) / 100;
|
return Math.round(reward * (0.15 + 0.45 * frac) * 100) / 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 60.
|
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 1000.
|
||||||
async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lon: number }> {
|
async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lon: number }> {
|
||||||
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
@@ -114,6 +115,39 @@ async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lo
|
|||||||
return nearest;
|
return nearest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Farthest airport from EDDF whose leg still FITS A FULL TANK — the longest flyable leg (v0.16.0
|
||||||
|
// refuel-for-flight test). The dataset's absolute farthest can exceed the aircraft's range (UNNT is
|
||||||
|
// ~4803 km out and needs ~6955 L > the 6300 L tank), so a full-tank fly there would rightly 409;
|
||||||
|
// this test wants a long-but-flyable leg instead.
|
||||||
|
async function farthestFlyableToHub(
|
||||||
|
page: Page,
|
||||||
|
entry: CatalogEntry,
|
||||||
|
): Promise<{ icao: string; lat: number; lon: number; hubLat: number; hubLon: number }> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const hub = fc.features.find((f) => f.properties.icao === HUB)!.properties;
|
||||||
|
let farthest: { icao: string; lat: number; lon: number; d: number } | null = null;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
const d = haversineKm(hub.lat, hub.lon, f.properties.lat, f.properties.lon);
|
||||||
|
if (requiredFuelFor(entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, d) > entry.maxFuel) continue; // beyond range
|
||||||
|
if (!farthest || d > farthest.d) {
|
||||||
|
farthest = { icao: f.properties.icao, lat: f.properties.lat, lon: f.properties.lon, d };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!farthest) throw new Error('no full-tank-flyable airport found in the dataset');
|
||||||
|
return { ...farthest, hubLat: hub.lat, hubLon: hub.lon };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors lib/sim/movement.ts (v0.16.0): fuel required to cover distanceKm arriving empty —
|
||||||
|
// closed form of the weight-proportional burn model, k calibrated so a full tank burns burnPerKm.
|
||||||
|
const FUEL_DENSITY_KG_PER_L = 0.8; // must match FUEL_DENSITY_KG_PER_L in lib/sim/movement.ts
|
||||||
|
function requiredFuelFor(burnPerKm: number, emptyWeightKg: number, maxFuel: number, distanceKm: number): number {
|
||||||
|
const k = burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
return (emptyWeightKg / FUEL_DENSITY_KG_PER_L) * (Math.exp(k * FUEL_DENSITY_KG_PER_L * distanceKm) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
|
||||||
async function createPackage(page: Page, fromIcao: string, toIcao: string, deadlineOffsetMs?: number): Promise<PackageState> {
|
async function createPackage(page: Page, fromIcao: string, toIcao: string, deadlineOffsetMs?: number): Promise<PackageState> {
|
||||||
const created = await page.request.post('/api/test/create-package', {
|
const created = await page.request.post('/api/test/create-package', {
|
||||||
@@ -128,7 +162,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
const s0 = await getState(page);
|
const s0 = await getState(page);
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
||||||
// Fast-forward any leftover leg / repositioning flight (~3 min real time worst case at 60×).
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
}
|
}
|
||||||
if (starter.status === 'flying') {
|
if (starter.status === 'flying') {
|
||||||
@@ -197,7 +231,7 @@ test('Load is disabled when no plane sits at the package origin', async ({ page
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('on-board list: fly-to-destination + abandon with penalty preview; flying planes show their leg', async ({ page }) => {
|
test('on-board list: fly-to-destination + abandon with penalty preview; flying planes show their leg', async ({ page }) => {
|
||||||
test.setTimeout(240_000); // one short flight at scale 60 plus UI steps — typical run well under three minutes
|
test.setTimeout(240_000); // one short flight at scale 1000 (seconds of real time) plus UI steps
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
const nearest = await nearestToHub(page);
|
const nearest = await nearestToHub(page);
|
||||||
@@ -241,7 +275,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
|||||||
const b = await getState(page);
|
const b = await getState(page);
|
||||||
const p = b.planes.find((x) => x.id === 'plane-starter');
|
const p = b.planes.find((x) => x.id === 'plane-starter');
|
||||||
return !!p && p.status === 'available' && p.locationIcao === nearest.icao;
|
return !!p && p.status === 'available' && p.locationIcao === nearest.icao;
|
||||||
}, { timeout: 120_000, message: `waiting for arrival at ${nearest.icao} (scale 60)` })
|
}, { timeout: 120_000, message: `waiting for arrival at ${nearest.icao} (scale 1000)` })
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
// The in-deadline package was delivered on arrival — it leaves the on-board list…
|
// The in-deadline package was delivered on arrival — it leaves the on-board list…
|
||||||
@@ -307,3 +341,74 @@ test('market buy/sell/refuel render with previews from the catalog in /api/state
|
|||||||
expect(after.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(starter.maxFuel);
|
expect(after.planes.find((p) => p.id === 'plane-starter')!.fuel).toBe(starter.maxFuel);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('on-board row Refuel tops up just enough for the package leg; market button says "Refuel to full"', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal + one long flight each way at scale 1000
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
|
const body = await getState(page);
|
||||||
|
const entry = body.catalog.find((e) => e.model === 'atr72')!;
|
||||||
|
|
||||||
|
// Deterministic baseline: a full tank.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
||||||
|
|
||||||
|
// Longest FLYABLE leg from the hub (fits a full tank) — long enough that "just enough" for it
|
||||||
|
// exceeds what's left on arrival.
|
||||||
|
const farthest = await farthestFlyableToHub(page, entry);
|
||||||
|
const pkg1 = await createPackage(page, HUB, farthest.icao, 24 * 3_600_000);
|
||||||
|
expect((await page.request.post(`/api/packages/${pkg1.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
||||||
|
|
||||||
|
// Fly there (delivers pkg1 on arrival) — the tank is now partial.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: farthest.icao } })).status()).toBe(200);
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter');
|
||||||
|
return !!p && p.status === 'available' && p.locationIcao === farthest.icao;
|
||||||
|
}, { timeout: 240_000, message: `waiting for arrival at ${farthest.icao} (scale 1000)` })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// New work at the far end: a package back to the hub — its leg is exactly what we refuel for.
|
||||||
|
const pkg2 = await createPackage(page, farthest.icao, HUB, 24 * 3_600_000);
|
||||||
|
expect((await page.request.post(`/api/packages/${pkg2.id}/load`, { data: { planeId: 'plane-starter' } })).status()).toBe(200);
|
||||||
|
|
||||||
|
// Expected "just enough" from the snapshot constants (mirrors requiredFuelFor in lib/sim/movement.ts).
|
||||||
|
const pre = await getState(page);
|
||||||
|
const fuelBefore = pre.planes.find((p) => p.id === 'plane-starter')!.fuel;
|
||||||
|
const cashBefore = pre.account.cash;
|
||||||
|
const km = haversineKm(farthest.hubLat, farthest.hubLon, farthest.lat, farthest.lon); // symmetric: hub ↔ far end
|
||||||
|
const liters = Math.max(0, requiredFuelFor(entry.burnPerKm, entry.emptyWeightKg, entry.maxFuel, km) - fuelBefore);
|
||||||
|
expect(liters).toBeGreaterThan(0); // the long leg genuinely needs more than what's left
|
||||||
|
const expectedCost = Math.round(liters * pre.fuelPricePerL * 100) / 100;
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
const refuelBtn = page.getByTestId(`refuel-for-${pkg2.id}`);
|
||||||
|
await expect(refuelBtn, 'row Refuel button appears for the loaded package').toBeVisible({ timeout: 15_000 });
|
||||||
|
// Capture the endpoint's OWN response — the full post-action snapshot at the action's clock.
|
||||||
|
const [res] = await Promise.all([
|
||||||
|
page.waitForResponse((r) => r.url().includes(`/api/planes/plane-starter/refuel`), { timeout: 15_000 }),
|
||||||
|
refuelBtn.click(),
|
||||||
|
]);
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const post = (await res.json()) as StateBody;
|
||||||
|
|
||||||
|
// Cash dropped by exactly L × price and fuel rose by exactly L.
|
||||||
|
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).
|
||||||
|
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.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
|
timeout: 240_000,
|
||||||
|
message: 'waiting for plane-starter to land back at the hub',
|
||||||
|
})
|
||||||
|
.toBe(true);
|
||||||
|
// Top the tank back up so later specs start with a full tank.
|
||||||
|
expect((await page.request.post('/api/planes/plane-starter/refuel')).status()).toBe(200);
|
||||||
|
});
|
||||||
|
|||||||
+12
-8
@@ -6,8 +6,8 @@ import { test, expect, type Page } from '@playwright/test';
|
|||||||
|
|
||||||
// Must match lib/sim/engine.ts — kept in sync manually (same pattern as MIN_ZOOM/MAX_ZOOM in map.spec.ts).
|
// Must match lib/sim/engine.ts — kept in sync manually (same pattern as MIN_ZOOM/MAX_ZOOM in map.spec.ts).
|
||||||
const MAX_TICK_ELAPSED_MS = 2_000;
|
const MAX_TICK_ELAPSED_MS = 2_000;
|
||||||
const SCALE = 60;
|
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder
|
||||||
const MAX_DELTA_PER_TICK = MAX_TICK_ELAPSED_MS * SCALE; // 120_000 game ms per tick at scale 60
|
const MAX_DELTA_PER_TICK = MAX_TICK_ELAPSED_MS * SCALE; // 2_000_000 game ms per tick at scale 1000
|
||||||
// Must match MARKET_TARGET_OPEN_PACKAGES in lib/game/seed.ts.
|
// Must match MARKET_TARGET_OPEN_PACKAGES in lib/game/seed.ts.
|
||||||
const MARKET_TARGET = 10;
|
const MARKET_TARGET = 10;
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ test.afterEach(async ({ page }) => {
|
|||||||
expect(res.status()).toBe(200);
|
expect(res.status()).toBe(200);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('timeScale 60 advances the clock by roughly real-time × 60 between polls', async ({ page }) => {
|
test('timeScale 1000 advances the clock by roughly real-time × 1000 between polls', async ({ page }) => {
|
||||||
const post = await postSim(page, { timeScale: SCALE });
|
const post = await postSim(page, { timeScale: SCALE });
|
||||||
expect(post.status()).toBe(200);
|
expect(post.status()).toBe(200);
|
||||||
const s1 = (await post.json()) as SimState;
|
const s1 = (await post.json()) as SimState;
|
||||||
@@ -51,11 +51,11 @@ test('timeScale 60 advances the clock by roughly real-time × 60 between polls',
|
|||||||
|
|
||||||
let prev = s1.clockMs;
|
let prev = s1.clockMs;
|
||||||
for (let i = 0; i < 3; i++) {
|
for (let i = 0; i < 3; i++) {
|
||||||
await sleep(1_000); // one real second ≈ 60 game seconds at scale 60 — well under the clamp
|
await sleep(1_000); // one real second ≈ 1000 game seconds at scale 1000 — well under the clamp
|
||||||
const body = await getState(page);
|
const body = await getState(page);
|
||||||
const now = body.simState.clockMs;
|
const now = body.simState.clockMs;
|
||||||
expect(now).toBeGreaterThan(prev); // strictly advances while actively polled
|
expect(now).toBeGreaterThan(prev); // strictly advances while actively polled
|
||||||
expect(now - prev).toBeGreaterThanOrEqual(30_000); // ≥ ~500 ms real × 60
|
expect(now - prev).toBeGreaterThanOrEqual(500_000); // ≥ ~500 ms real × 1000
|
||||||
expect(now - prev).toBeLessThanOrEqual(MAX_DELTA_PER_TICK + 60); // clamp bounds each tick
|
expect(now - prev).toBeLessThanOrEqual(MAX_DELTA_PER_TICK + 60); // clamp bounds each tick
|
||||||
prev = now;
|
prev = now;
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ test('an open package past its short deadline expires and the market stays toppe
|
|||||||
expect(victim).toBeDefined(); // steady state always has open packages
|
expect(victim).toBeDefined(); // steady state always has open packages
|
||||||
|
|
||||||
// Test-only hook (FLIGHT_TEST_HOOKS=1 in docker-compose): move an existing open
|
// Test-only hook (FLIGHT_TEST_HOOKS=1 in docker-compose): move an existing open
|
||||||
// package's deadline ~10 game-seconds out so expiry is observable at scale 60.
|
// package's deadline ~10 game-seconds out so expiry is observable at scale 1000.
|
||||||
const hook = await page.request.post('/api/test/expire-package', { data: { packageId: victim!.id } });
|
const hook = await page.request.post('/api/test/expire-package', { data: { packageId: victim!.id } });
|
||||||
expect(hook.status()).toBe(200);
|
expect(hook.status()).toBe(200);
|
||||||
const moved = (await hook.json()) as { id: string; deadlineSimTime: number };
|
const moved = (await hook.json()) as { id: string; deadlineSimTime: number };
|
||||||
@@ -132,9 +132,13 @@ test('the hook can also create a fresh short-deadline package, which then expire
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('POST /api/sim validates and clamps its input', async ({ page }) => {
|
test('POST /api/sim validates and clamps its input', async ({ page }) => {
|
||||||
const clampHigh = await postSim(page, { timeScale: 500 });
|
const clampHigh = await postSim(page, { timeScale: 2000 });
|
||||||
expect(clampHigh.status()).toBe(200);
|
expect(clampHigh.status()).toBe(200);
|
||||||
expect(((await clampHigh.json()) as SimState).timeScale).toBe(64); // top of the power-of-two ladder (v0.9.2)
|
expect(((await clampHigh.json()) as SimState).timeScale).toBe(1000); // top of the ladder (v0.14.0)
|
||||||
|
|
||||||
|
const inRange = await postSim(page, { timeScale: 500 });
|
||||||
|
expect(inRange.status()).toBe(200);
|
||||||
|
expect(((await inRange.json()) as SimState).timeScale).toBe(500); // ladder value passes through unclamped
|
||||||
|
|
||||||
const clampLow = await postSim(page, { timeScale: 0.1 });
|
const clampLow = await postSim(page, { timeScale: 0.1 });
|
||||||
expect(clampLow.status()).toBe(200);
|
expect(clampLow.status()).toBe(200);
|
||||||
|
|||||||
+4
-2
@@ -3,8 +3,10 @@ import path from 'node:path';
|
|||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
// Repo root — docker-compose.yml lives here; `docker compose restart` runs on
|
// Repo root — docker-compose.yml lives here; `docker compose restart` runs on
|
||||||
// this host (the test runner), browsers stay remote.
|
// this host (the test runner), browsers stay remote. CI points E2E_COMPOSE_ARGS at the
|
||||||
|
// isolated stack file + project (-f docker-compose.ci.yml -p flight-ci) instead of the default one.
|
||||||
const repoRoot = path.join(__dirname, '..');
|
const repoRoot = path.join(__dirname, '..');
|
||||||
|
const composeArgs = process.env.E2E_COMPOSE_ARGS ?? '';
|
||||||
|
|
||||||
interface StateBody {
|
interface StateBody {
|
||||||
account: { cash: number; reputation: number };
|
account: { cash: number; reputation: number };
|
||||||
@@ -46,7 +48,7 @@ test('state survives a container restart (sim clock + account persisted)', async
|
|||||||
expect(resBefore.status()).toBe(200);
|
expect(resBefore.status()).toBe(200);
|
||||||
const before = (await resBefore.json()) as StateBody;
|
const before = (await resBefore.json()) as StateBody;
|
||||||
|
|
||||||
execSync('docker compose restart flight', { cwd: repoRoot, stdio: 'pipe' });
|
execSync(`docker compose ${composeArgs} restart flight`, { cwd: repoRoot, stdio: 'pipe' });
|
||||||
|
|
||||||
// Wait for the app to come back, capturing the post-restart snapshot.
|
// Wait for the app to come back, capturing the post-restart snapshot.
|
||||||
let after: StateBody | undefined;
|
let after: StateBody | undefined;
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|||||||
import { openGameDb, type GameDb } from '@/lib/db/client';
|
import { openGameDb, type GameDb } from '@/lib/db/client';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||||
import { HUB_ICAO } from './seed';
|
import { HUB_ICAO } from './seed';
|
||||||
import {
|
import {
|
||||||
@@ -412,4 +414,110 @@ describe('refuelPlane', () => {
|
|||||||
const inst = await freshDb('refuel-unknown.db');
|
const inst = await freshDb('refuel-unknown.db');
|
||||||
await expectActionError(refuelPlane(inst, 'ghost'), 404);
|
await expectActionError(refuelPlane(inst, 'ghost'), 404);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- forFlight mode (v0.16.0) ---
|
||||||
|
|
||||||
|
it('forFlight adds exactly the liters needed for the package leg and deducts L × price', async () => {
|
||||||
|
const inst = await freshDb('refuel-forflight-ok.db');
|
||||||
|
await insertOpenPackage(inst, 'p-ff', { destIcao: 'LEMD' }); // EDDF → LEMD
|
||||||
|
await loadPackage(inst, 'p-ff', 'plane-starter');
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
// Partial tank below the requirement so L > 0.
|
||||||
|
const startFuel = Math.round(required / 2);
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: startFuel }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const { cost } = await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-ff' });
|
||||||
|
|
||||||
|
expect(cost).toBe(Math.round((required - startFuel) * FUEL_PRICE_PER_L * 100) / 100);
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.fuel).toBeCloseTo(required, 6); // topped up to exactly the leg requirement
|
||||||
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
|
expect(account.cash).toBeCloseTo(cashBefore - cost, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight leaves an exactly-feasible tank — flyPlane to the package dest succeeds right after', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-flyafter.db');
|
||||||
|
await insertOpenPackage(inst, 'p-fa', { destIcao: 'LEMD' }); // EDDF → LEMD
|
||||||
|
await loadPackage(inst, 'p-fa', 'plane-starter');
|
||||||
|
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === 'LEMD')!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
const required = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, km);
|
||||||
|
|
||||||
|
// Empty-ish tank: well below the leg requirement.
|
||||||
|
await inst.db.update(schema.planes).set({ fuel: Math.round(required / 4) }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-fa' });
|
||||||
|
|
||||||
|
// The leg must now be flyable — no epsilon-short 409 (regression guard for the float-exact target).
|
||||||
|
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.status).toBe('flying');
|
||||||
|
expect(plane.destIcao).toBe('LEMD');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight is a free no-op when the tank already covers the leg', async () => {
|
||||||
|
const inst = await freshDb('refuel-forflight-enough.db'); // seeded starter is full at EDDF
|
||||||
|
await insertOpenPackage(inst, 'p-ff2', { destIcao: 'LEMD' });
|
||||||
|
await loadPackage(inst, 'p-ff2', 'plane-starter');
|
||||||
|
const cashBefore = (await inst.db.select().from(schema.account))[0].cash;
|
||||||
|
|
||||||
|
const { cost } = await refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-ff2' });
|
||||||
|
|
||||||
|
expect(cost).toBe(0);
|
||||||
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
|
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel); // untouched
|
||||||
|
expect((await inst.db.select().from(schema.account))[0].cash).toBe(cashBefore);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a package that is not loaded on this plane with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-open.db'); // open — never loaded
|
||||||
|
await insertOpenPackage(inst, 'p-x');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-x' }), 409);
|
||||||
|
|
||||||
|
const inst2 = await freshDb('refuel-ff-other.db'); // loaded on ANOTHER plane
|
||||||
|
await insertOpenPackage(inst2, 'p-y', { status: 'loaded', planeId: 'plane-someone-else' });
|
||||||
|
await expectActionError(refuelPlane(inst2, 'plane-starter', { mode: 'forFlight', packageId: 'p-y' }), 409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects an expired package with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-expired.db');
|
||||||
|
await insertOpenPackage(inst, 'p-z', { status: 'expired', planeId: 'plane-starter' });
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-z' }), 409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects an unknown package id with 404', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-unknown.db');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'nope' }), 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a missing packageId with 400', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-nopkg.db');
|
||||||
|
await expectActionError(refuelPlane(inst, 'plane-starter', { mode: 'forFlight' }), 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forFlight rejects a leg that does not fit even a full tank with 409', async () => {
|
||||||
|
const inst = await freshDb('refuel-ff-nofit.db');
|
||||||
|
// UNNT (Narsarsuaq, Greenland) ↔ LPPD are ~7670 km apart — far beyond the ATR's range.
|
||||||
|
await insertOpenPackage(inst, 'p-far', { destIcao: 'LPPD' });
|
||||||
|
await loadPackage(inst, 'p-far', 'plane-starter');
|
||||||
|
await inst.db.update(schema.planes).set({ locationIcao: 'UNNT' }).where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
await expectActionError(
|
||||||
|
refuelPlane(inst, 'plane-starter', { mode: 'forFlight', packageId: 'p-far' }),
|
||||||
|
409,
|
||||||
|
/does not fit/i,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+53
-7
@@ -4,6 +4,7 @@ import * as schema from '@/lib/db/schema';
|
|||||||
import { persist, type GameDb } from '@/lib/db/client';
|
import { persist, type GameDb } from '@/lib/db/client';
|
||||||
import { loadAirportsGeoJson } from '@/lib/airports';
|
import { loadAirportsGeoJson } from '@/lib/airports';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { requiredFuelFor } from '@/lib/sim/movement';
|
||||||
import { runAction } from '@/lib/sim/engine';
|
import { runAction } from '@/lib/sim/engine';
|
||||||
import { getStateSnapshot } from './state';
|
import { getStateSnapshot } from './state';
|
||||||
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
import { FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION } from './catalog';
|
||||||
@@ -105,9 +106,10 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
|||||||
const type = PLANE_TYPES[plane.model];
|
const type = PLANE_TYPES[plane.model];
|
||||||
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||||
const distanceKm = haversineKm(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon);
|
const distanceKm = haversineKm(origin.lat, origin.lon, destFeature.properties.lat, destFeature.properties.lon);
|
||||||
const burnL = type.burnPerKm * distanceKm;
|
// Weighted burn model (v0.16.0): the leg needs enough fuel to cover it arriving empty.
|
||||||
if (burnL > plane.fuel) {
|
const requiredL = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
||||||
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(burnL)} L but the plane has ${Math.round(plane.fuel)} L`);
|
if (requiredL > plane.fuel) {
|
||||||
|
throw new GameActionError(409, `insufficient fuel: the leg needs ${Math.round(requiredL)} L but the plane has ${Math.round(plane.fuel)} L`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// runAction() ticked first, so this is current game time.
|
// runAction() ticked first, so this is current game time.
|
||||||
@@ -225,8 +227,19 @@ export async function sellPlane(inst: GameDb, planeId: string): Promise<{ payout
|
|||||||
|
|
||||||
// --- Refuel (POST /api/planes/:planeId/refuel) ---
|
// --- Refuel (POST /api/planes/:planeId/refuel) ---
|
||||||
|
|
||||||
// Fill a grounded plane to maxFuel at FUEL_PRICE_PER_L per missing liter.
|
// Refuel modes (v0.16.0): 'full' fills the tank to maxFuel; 'forFlight' adds just
|
||||||
export async function refuelPlane(inst: GameDb, planeId: string): Promise<{ cost: number }> {
|
// enough fuel for one loaded package's destination leg — required liters per the
|
||||||
|
// weighted burn model, independent of how much is already in the tank.
|
||||||
|
export interface RefuelOptions {
|
||||||
|
mode?: 'full' | 'forFlight';
|
||||||
|
packageId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill a grounded plane to maxFuel at FUEL_PRICE_PER_L per missing liter — or, with
|
||||||
|
// {mode:'forFlight', packageId}, top it up just enough to fly the loaded package's
|
||||||
|
// destination leg (409 if the package isn't loaded on this plane, is expired, or the
|
||||||
|
// leg doesn't fit a full tank).
|
||||||
|
export async function refuelPlane(inst: GameDb, planeId: string, opts: RefuelOptions = {}): Promise<{ cost: number }> {
|
||||||
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
const rows = await inst.db.select().from(schema.planes).where(eq(schema.planes.id, planeId));
|
||||||
const plane = rows[0];
|
const plane = rows[0];
|
||||||
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
if (!plane) throw new GameActionError(404, `plane ${planeId} not found`);
|
||||||
@@ -234,14 +247,47 @@ export async function refuelPlane(inst: GameDb, planeId: string): Promise<{ cost
|
|||||||
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be refueled`);
|
throw new GameActionError(409, `plane is ${plane.status}, only grounded planes can be refueled`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cost = Math.round((plane.maxFuel - plane.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
const mode = opts.mode ?? 'full';
|
||||||
|
let targetFuel: number; // tank level after the refuel
|
||||||
|
if (mode === 'forFlight') {
|
||||||
|
if (!opts.packageId) throw new GameActionError(400, 'packageId is required when mode is "forFlight"');
|
||||||
|
|
||||||
|
const pkgRows = await inst.db.select().from(schema.packages).where(eq(schema.packages.id, opts.packageId));
|
||||||
|
const pkg = pkgRows[0];
|
||||||
|
if (!pkg) throw new GameActionError(404, `package ${opts.packageId} not found`);
|
||||||
|
if (pkg.status !== 'loaded' || pkg.planeId !== plane.id) {
|
||||||
|
const where = pkg.planeId === plane.id ? '' : ', and it is bound to another plane';
|
||||||
|
throw new GameActionError(409, `only a package loaded on this plane can be refueled for (it is ${pkg.status}${where})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = PLANE_TYPES[plane.model];
|
||||||
|
if (!type) throw new Error(`unknown plane model ${plane.model}`); // → 500, cannot happen for seeded data
|
||||||
|
const origin = await airportByIcao(plane.locationIcao);
|
||||||
|
const dest = await airportByIcao(pkg.destIcao);
|
||||||
|
const distanceKm = haversineKm(origin.lat, origin.lon, dest.lat, dest.lon);
|
||||||
|
const requiredL = requiredFuelFor(type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm);
|
||||||
|
if (requiredL > plane.maxFuel) {
|
||||||
|
throw new GameActionError(409, `the leg to ${pkg.destIcao} needs ${Math.round(requiredL)} L even starting empty — it does not fit a full ${plane.maxFuel} L tank`);
|
||||||
|
}
|
||||||
|
// Land EXACTLY on the leg requirement when topping up: flyPlane re-computes this same value and
|
||||||
|
// compares with strict `>`, so fuel := requiredL guarantees the leg is feasible. The alternative
|
||||||
|
// (fuel + liters) can round a hair BELOW R in IEEE754 — f + fl(R − f) is not guaranteed ≥ R — and
|
||||||
|
// would 409 on an otherwise-feasible leg. Already enough → free no-op, tank untouched.
|
||||||
|
targetFuel = Math.max(plane.fuel, requiredL);
|
||||||
|
} else {
|
||||||
|
// Exactly maxFuel (as before v0.16.0) — clients/tests compare against it with strict equality.
|
||||||
|
targetFuel = plane.maxFuel;
|
||||||
|
}
|
||||||
|
|
||||||
|
const liters = Math.max(0, targetFuel - plane.fuel);
|
||||||
|
const cost = Math.round(liters * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
const account = (await inst.db.select().from(schema.account))[0];
|
const account = (await inst.db.select().from(schema.account))[0];
|
||||||
if (!account) throw new Error('account row missing');
|
if (!account) throw new Error('account row missing');
|
||||||
if (cost > 0 && account.cash < cost) {
|
if (cost > 0 && account.cash < cost) {
|
||||||
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
throw new GameActionError(409, `insufficient funds: refueling costs ${cost}, you have ${Math.round(account.cash)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await inst.db.update(schema.planes).set({ fuel: plane.maxFuel }).where(eq(schema.planes.id, planeId));
|
await inst.db.update(schema.planes).set({ fuel: targetFuel }).where(eq(schema.planes.id, planeId));
|
||||||
if (cost > 0) {
|
if (cost > 0) {
|
||||||
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-2
@@ -6,8 +6,11 @@ export interface PlaneType {
|
|||||||
name: string;
|
name: string;
|
||||||
// Fuel capacity, liters.
|
// Fuel capacity, liters.
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
// Fuel burn per km of flight, liters/km (cruise).
|
// Fuel burn per km of flight at a FULL tank, liters/km (cruise) — the weighted burn
|
||||||
|
// model (v0.16.0) calibrates its rate constant to this value at F = maxFuel.
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
// Operating empty weight in kg (v0.16.0) — feeds the weight-proportional burn model.
|
||||||
|
emptyWeightKg: number;
|
||||||
// Cruise speed, km/h — used by the sim tick to advance planes along routes.
|
// Cruise speed, km/h — used by the sim tick to advance planes along routes.
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
// Market price in € (v0.8.0): buying costs `price`, selling pays out
|
// Market price in € (v0.8.0): buying costs `price`, selling pays out
|
||||||
@@ -22,7 +25,8 @@ export const PLANE_TYPES: Record<string, PlaneType> = {
|
|||||||
id: 'atr72',
|
id: 'atr72',
|
||||||
name: 'ATR 72-600',
|
name: 'ATR 72-600',
|
||||||
maxFuel: 6300,
|
maxFuel: 6300,
|
||||||
burnPerKm: 1.75, // ~900 kg/h at 510 km/h cruise (Jet-A1 ≈ 0.8 kg/L)
|
burnPerKm: 1.75, // full-tank rate: ~893 L/h ≈ 714 kg/h at 510 km/h cruise (Jet-A1 ≈ 0.8 kg/L); the weighted model burns less as fuel drops off
|
||||||
|
emptyWeightKg: 9_300, // ATR 72-600 operating empty weight
|
||||||
speedKmh: 510,
|
speedKmh: 510,
|
||||||
// €200k — with the starting cash of €20k and typical hop rewards (~€1–3k),
|
// €200k — with the starting cash of €20k and typical hop rewards (~€1–3k),
|
||||||
// a second ATR takes sustained play to afford, as intended for the MVP sink.
|
// a second ATR takes sustained play to afford, as intended for the MVP sink.
|
||||||
@@ -49,6 +53,9 @@ export interface CatalogEntry {
|
|||||||
price: number;
|
price: number;
|
||||||
maxFuel: number;
|
maxFuel: number;
|
||||||
burnPerKm: number;
|
burnPerKm: number;
|
||||||
|
// Weighted burn model inputs (v0.16.0) — clients can mirror the closed forms in
|
||||||
|
// lib/sim/movement.ts with these + FUEL_DENSITY_KG_PER_L.
|
||||||
|
emptyWeightKg: number;
|
||||||
speedKmh: number;
|
speedKmh: number;
|
||||||
capacity: number;
|
capacity: number;
|
||||||
}
|
}
|
||||||
@@ -62,6 +69,7 @@ export function catalogEntries(): CatalogEntry[] {
|
|||||||
price: t.price,
|
price: t.price,
|
||||||
maxFuel: t.maxFuel,
|
maxFuel: t.maxFuel,
|
||||||
burnPerKm: t.burnPerKm,
|
burnPerKm: t.burnPerKm,
|
||||||
|
emptyWeightKg: t.emptyWeightKg,
|
||||||
speedKmh: t.speedKmh,
|
speedKmh: t.speedKmh,
|
||||||
capacity: t.capacity,
|
capacity: t.capacity,
|
||||||
}));
|
}));
|
||||||
|
|||||||
+2
-2
@@ -3,7 +3,7 @@ import { haversineKm } from '@/lib/geo';
|
|||||||
import { getGameDb } from '@/lib/db/client';
|
import { getGameDb } from '@/lib/db/client';
|
||||||
import * as schema from '@/lib/db/schema';
|
import * as schema from '@/lib/db/schema';
|
||||||
import { catalogEntries, FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION, type CatalogEntry } from './catalog';
|
import { catalogEntries, FUEL_PRICE_PER_L, PLANE_TYPES, SELL_FRACTION, type CatalogEntry } from './catalog';
|
||||||
import { fuelAt, progressAt, positionAt } from '@/lib/sim/movement';
|
import { fuelAtWeighted, progressAt, positionAt } from '@/lib/sim/movement';
|
||||||
|
|
||||||
// Read-only game-state snapshot for client polling (GET /api/state).
|
// Read-only game-state snapshot for client polling (GET /api/state).
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
|||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
||||||
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
||||||
return { ...pos, fuel: fuelAt(p.fuel, type.burnPerKm, distanceKm, progress) };
|
return { ...pos, fuel: fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, progress) };
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
+1
-1
@@ -17,7 +17,7 @@ function snapshot(overrides: Partial<StateSnapshot> = {}): StateSnapshot {
|
|||||||
planes: [],
|
planes: [],
|
||||||
packages: [],
|
packages: [],
|
||||||
catalog: [
|
catalog: [
|
||||||
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, speedKmh: 510, capacity: 6 },
|
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9_300, speedKmh: 510, capacity: 6 },
|
||||||
],
|
],
|
||||||
fuelPricePerL: 0.8,
|
fuelPricePerL: 0.8,
|
||||||
sellFraction: 0.5,
|
sellFraction: 0.5,
|
||||||
|
|||||||
+25
-7
@@ -90,8 +90,17 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(snap.sellFraction.type).toBe('number');
|
expect(snap.sellFraction.type).toBe('number');
|
||||||
|
|
||||||
const catalog = openApiSpec.components.schemas.CatalogEntry.properties;
|
const catalog = openApiSpec.components.schemas.CatalogEntry.properties;
|
||||||
expect(Object.keys(catalog).sort()).toEqual(['burnPerKm', 'capacity', 'label', 'maxFuel', 'model', 'price', 'speedKmh']);
|
expect(Object.keys(catalog).sort()).toEqual([
|
||||||
for (const key of ['burnPerKm', 'maxFuel', 'price', 'speedKmh'] as const) {
|
'burnPerKm',
|
||||||
|
'capacity',
|
||||||
|
'emptyWeightKg', // v0.16.0 weighted burn model input
|
||||||
|
'label',
|
||||||
|
'maxFuel',
|
||||||
|
'model',
|
||||||
|
'price',
|
||||||
|
'speedKmh',
|
||||||
|
]);
|
||||||
|
for (const key of ['burnPerKm', 'emptyWeightKg', 'maxFuel', 'price', 'speedKmh'] as const) {
|
||||||
expect(catalog[key].type, `CatalogEntry.${key}`).toBe('number');
|
expect(catalog[key].type, `CatalogEntry.${key}`).toBe('number');
|
||||||
}
|
}
|
||||||
expect(catalog.capacity.type).toBe('integer'); // v0.12.0 slot capacity
|
expect(catalog.capacity.type).toBe('integer'); // v0.12.0 slot capacity
|
||||||
@@ -153,7 +162,7 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(Object.keys(controls).sort()).toEqual(['paused', 'timeScale']);
|
expect(Object.keys(controls).sort()).toEqual(['paused', 'timeScale']);
|
||||||
expect(controls.timeScale.type).toBe('number');
|
expect(controls.timeScale.type).toBe('number');
|
||||||
expect(controls.timeScale.minimum).toBe(1);
|
expect(controls.timeScale.minimum).toBe(1);
|
||||||
expect(controls.timeScale.maximum).toBe(64);
|
expect(controls.timeScale.maximum).toBe(1000);
|
||||||
expect(controls.paused.type).toBe('boolean');
|
expect(controls.paused.type).toBe('boolean');
|
||||||
|
|
||||||
const error = openApiSpec.components.schemas.Error.properties;
|
const error = openApiSpec.components.schemas.Error.properties;
|
||||||
@@ -165,7 +174,7 @@ describe('OpenAPI spec', () => {
|
|||||||
const post = (p: string) =>
|
const post = (p: string) =>
|
||||||
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
((openApiSpec.paths as Record<string, { post?: unknown }>)[p]?.post ?? {}) as {
|
||||||
responses: Record<string, unknown>;
|
responses: Record<string, unknown>;
|
||||||
requestBody?: { content: Record<string, { schema: { $ref: string } }> };
|
requestBody?: { required?: boolean; content: Record<string, { schema: { $ref: string } }> };
|
||||||
parameters?: Array<{ name: string }>;
|
parameters?: Array<{ name: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -189,9 +198,10 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
expect(errorCodes('/api/planes/{planeId}/fly')).toEqual(['400', '404', '409']);
|
||||||
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
expect(errorCodes('/api/market/buy-plane')).toEqual(['400', '409']);
|
||||||
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
expect(errorCodes('/api/market/sell-plane')).toEqual(['400', '404', '409']);
|
||||||
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['404', '409']);
|
expect(errorCodes('/api/planes/{planeId}/refuel')).toEqual(['400', '404', '409']); // v0.16.0 optional body
|
||||||
|
|
||||||
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon/refuel take none.
|
// Request bodies: load/fly/buy/sell take their dedicated schemas; abandon takes none;
|
||||||
|
// refuel's is OPTIONAL (v0.16.0) — no body still means "fill to full".
|
||||||
expect(post('/api/packages/{id}/load').requestBody?.content['application/json'].schema.$ref).toBe(
|
expect(post('/api/packages/{id}/load').requestBody?.content['application/json'].schema.$ref).toBe(
|
||||||
'#/components/schemas/LoadPackageRequest',
|
'#/components/schemas/LoadPackageRequest',
|
||||||
);
|
);
|
||||||
@@ -205,7 +215,9 @@ describe('OpenAPI spec', () => {
|
|||||||
'#/components/schemas/SellPlaneRequest',
|
'#/components/schemas/SellPlaneRequest',
|
||||||
);
|
);
|
||||||
expect(post('/api/packages/{id}/abandon').requestBody).toBeUndefined();
|
expect(post('/api/packages/{id}/abandon').requestBody).toBeUndefined();
|
||||||
expect(post('/api/planes/{planeId}/refuel').requestBody).toBeUndefined();
|
const refuelBody = post('/api/planes/{planeId}/refuel').requestBody;
|
||||||
|
expect(refuelBody?.content['application/json'].schema.$ref).toBe('#/components/schemas/RefuelRequest');
|
||||||
|
expect(refuelBody?.required).toBe(false); // optional — no body still means "fill to full"
|
||||||
|
|
||||||
// Path parameters are declared on the parameterized routes.
|
// Path parameters are declared on the parameterized routes.
|
||||||
const paramNames = (p: string) => post(p).parameters?.map((x) => x.name);
|
const paramNames = (p: string) => post(p).parameters?.map((x) => x.name);
|
||||||
@@ -227,5 +239,11 @@ describe('OpenAPI spec', () => {
|
|||||||
const sell = openApiSpec.components.schemas.SellPlaneRequest;
|
const sell = openApiSpec.components.schemas.SellPlaneRequest;
|
||||||
expect(sell.required).toEqual(['planeId']);
|
expect(sell.required).toEqual(['planeId']);
|
||||||
expect(sell.properties.planeId.type).toBe('string');
|
expect(sell.properties.planeId.type).toBe('string');
|
||||||
|
|
||||||
|
// RefuelRequest (v0.16.0): both fields optional — no body / {} means "full".
|
||||||
|
const refuel = openApiSpec.components.schemas.RefuelRequest;
|
||||||
|
expect((refuel as { required?: string[] }).required ?? []).toEqual([]);
|
||||||
|
expect(((refuel.properties.mode) as { enum: string[] }).enum.sort()).toEqual(['forFlight', 'full']);
|
||||||
|
expect(refuel.properties.packageId.type).toBe('string');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+41
-10
@@ -197,7 +197,8 @@ export const openApiSpec = {
|
|||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Plane not grounded, or insufficient fuel for the leg (burnPerKm × great-circle km)',
|
description:
|
||||||
|
'Plane not grounded, or insufficient fuel for the leg (v0.16.0 weight-proportional burn — the fuel required to cover the great-circle distance arriving empty)',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -271,22 +272,35 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Refuel a grounded plane',
|
summary: 'Refuel a grounded plane',
|
||||||
description:
|
description:
|
||||||
'Fill a grounded plane to maxFuel (v0.8.0). Cost = (maxFuel − fuel) × fuel price per liter, deducted from cash; no body.',
|
'Refuel a grounded plane at the fuel price per added liter, deducted from cash (v0.8.0). The body is optional (v0.16.0): no body or mode "full" fills to maxFuel; mode "forFlight" with packageId adds just enough for that loaded package\'s destination leg — liters = required fuel for the great-circle distance (weight-proportional burn model) minus what is already in the tank.',
|
||||||
operationId: 'refuelPlane',
|
operationId: 'refuelPlane',
|
||||||
parameters: [
|
parameters: [
|
||||||
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
{ name: 'planeId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
],
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: false,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/RefuelRequest' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Refueled — full state snapshot (fuel at max, cash reduced by the cost)',
|
description: 'Refueled — full state snapshot (fuel raised by exactly the added liters, cash reduced by the cost)',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/StateSnapshot' } } },
|
||||||
},
|
},
|
||||||
|
400: {
|
||||||
|
description: 'Invalid body (not an object, unknown field, unknown mode, or forFlight without packageId)',
|
||||||
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown plane id',
|
description: 'Unknown plane id (or unknown package id in forFlight mode)',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Plane is flying, or cash is insufficient for the fill-up',
|
description:
|
||||||
|
'Plane is flying, the package is not loaded on this plane (or is expired), the leg does not fit a full tank, or cash is insufficient for the refuel',
|
||||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -376,11 +390,12 @@ export const openApiSpec = {
|
|||||||
label: { type: 'string', description: 'Display name (e.g. "ATR 72-600").' },
|
label: { type: 'string', description: 'Display name (e.g. "ATR 72-600").' },
|
||||||
price: { type: 'number', description: 'Market price in € (buy cost; sell pays out sellFraction × this).' },
|
price: { type: 'number', description: 'Market price in € (buy cost; sell pays out sellFraction × this).' },
|
||||||
maxFuel: { type: 'number', description: 'Fuel capacity, liters.' },
|
maxFuel: { type: 'number', description: 'Fuel capacity, liters.' },
|
||||||
burnPerKm: { type: 'number', description: 'Cruise fuel burn, liters/km.' },
|
burnPerKm: { type: 'number', description: 'Cruise fuel burn at a full tank, liters/km (v0.16.0 weighted model calibrates to this).' },
|
||||||
|
emptyWeightKg: { type: 'number', description: 'Operating empty weight, kg — with burnPerKm and maxFuel it drives the v0.16.0 weight-proportional burn model.' },
|
||||||
speedKmh: { type: 'number', description: 'Cruise speed, km/h.' },
|
speedKmh: { type: 'number', description: 'Cruise speed, km/h.' },
|
||||||
capacity: { type: 'integer', description: 'Cargo slot capacity — packages that can be loaded on one plane (v0.12.0).' },
|
capacity: { type: 'integer', description: 'Cargo slot capacity — packages that can be loaded on one plane (v0.12.0).' },
|
||||||
},
|
},
|
||||||
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'speedKmh', 'capacity'],
|
required: ['model', 'label', 'price', 'maxFuel', 'burnPerKm', 'emptyWeightKg', 'speedKmh', 'capacity'],
|
||||||
},
|
},
|
||||||
AccountState: {
|
AccountState: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
@@ -394,7 +409,7 @@ export const openApiSpec = {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
||||||
timeScale: { type: 'number', minimum: 1, maximum: 64 },
|
timeScale: { type: 'number', minimum: 1, maximum: 1000 },
|
||||||
paused: { type: 'boolean' },
|
paused: { type: 'boolean' },
|
||||||
},
|
},
|
||||||
required: ['clockMs', 'timeScale', 'paused'],
|
required: ['clockMs', 'timeScale', 'paused'],
|
||||||
@@ -406,8 +421,8 @@ export const openApiSpec = {
|
|||||||
timeScale: {
|
timeScale: {
|
||||||
type: 'number',
|
type: 'number',
|
||||||
minimum: 1,
|
minimum: 1,
|
||||||
maximum: 64,
|
maximum: 1000,
|
||||||
description: 'Game-time multiplier; values outside [1, 64] are clamped. The UI offers the power-of-two ladder 1/2/4/8/16/32/64.',
|
description: 'Game-time multiplier; values outside [1, 1000] are clamped. The UI offers the ladder 1/2/5/10/25/50/100/250/500/1000.',
|
||||||
},
|
},
|
||||||
paused: { type: 'boolean' },
|
paused: { type: 'boolean' },
|
||||||
},
|
},
|
||||||
@@ -440,6 +455,22 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
required: ['planeId'],
|
required: ['planeId'],
|
||||||
},
|
},
|
||||||
|
RefuelRequest: {
|
||||||
|
type: 'object',
|
||||||
|
description:
|
||||||
|
'Optional refuel body (v0.16.0) — omit it entirely or send {} to fill the tank; both fields are optional.',
|
||||||
|
properties: {
|
||||||
|
mode: {
|
||||||
|
enum: ['full', 'forFlight'],
|
||||||
|
description:
|
||||||
|
'"full" (default) fills the tank to maxFuel; "forFlight" adds just enough fuel for one loaded package\'s destination leg.',
|
||||||
|
},
|
||||||
|
packageId: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'Required with mode "forFlight": a package LOADED on this plane — its destIcao is the refuel target.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
Error: {
|
Error: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
|
|||||||
+32
-2
@@ -9,11 +9,14 @@ import { loadAirportsGeoJson } from '@/lib/airports';
|
|||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||||
import { arrivalTimeFor } from './movement';
|
import { arrivalTimeFor, fuelAtWeighted } from './movement';
|
||||||
import {
|
import {
|
||||||
|
clampTimeScale,
|
||||||
deliverPackages,
|
deliverPackages,
|
||||||
expirePackages,
|
expirePackages,
|
||||||
MAX_TICK_ELAPSED_MS,
|
MAX_TICK_ELAPSED_MS,
|
||||||
|
MAX_TIME_SCALE,
|
||||||
|
MIN_TIME_SCALE,
|
||||||
reputationGainFor,
|
reputationGainFor,
|
||||||
spawnCoveragePackages,
|
spawnCoveragePackages,
|
||||||
spawnOpenPackages,
|
spawnOpenPackages,
|
||||||
@@ -179,7 +182,8 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
expect(plane.locationIcao).toBe(TO);
|
expect(plane.locationIcao).toBe(TO);
|
||||||
expect(plane.lat).toBe(to.lat);
|
expect(plane.lat).toBe(to.lat);
|
||||||
expect(plane.lon).toBe(to.lon);
|
expect(plane.lon).toBe(to.lon);
|
||||||
expect(plane.fuel).toBeCloseTo(Math.max(0, type.maxFuel - type.burnPerKm * km), 6); // remaining fuel
|
// Remaining fuel per the v0.16.0 weight-proportional burn model (closed form).
|
||||||
|
expect(plane.fuel).toBeCloseTo(fuelAtWeighted(type.maxFuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, km, 1), 6);
|
||||||
expect(plane.departureSimTime).toBeNull();
|
expect(plane.departureSimTime).toBeNull();
|
||||||
expect(plane.destIcao).toBeNull(); // flight context cleared on landing
|
expect(plane.destIcao).toBeNull(); // flight context cleared on landing
|
||||||
|
|
||||||
@@ -374,6 +378,32 @@ describe('spawnCoveragePackages (v0.8.0 spawn coverage rule)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('clampTimeScale — v0.14.0 ladder bounds [1, 1000]', () => {
|
||||||
|
it('clamps below-minimum values to MIN_TIME_SCALE', () => {
|
||||||
|
expect(clampTimeScale(0)).toBe(MIN_TIME_SCALE);
|
||||||
|
expect(clampTimeScale(-5)).toBe(MIN_TIME_SCALE);
|
||||||
|
expect(clampTimeScale(0.1)).toBe(MIN_TIME_SCALE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps above-maximum values to MAX_TIME_SCALE', () => {
|
||||||
|
expect(clampTimeScale(1001)).toBe(MAX_TIME_SCALE);
|
||||||
|
expect(clampTimeScale(2000)).toBe(MAX_TIME_SCALE);
|
||||||
|
expect(clampTimeScale(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIME_SCALE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes in-range values through unclamped — ladder and off-ladder alike', () => {
|
||||||
|
for (const s of [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000]) {
|
||||||
|
expect(clampTimeScale(s)).toBe(s); // the full v0.14.0 slider ladder
|
||||||
|
}
|
||||||
|
expect(clampTimeScale(37)).toBe(37); // off-ladder but in range (e.g. a legacy value)
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the endpoints exact', () => {
|
||||||
|
expect(clampTimeScale(MIN_TIME_SCALE)).toBe(MIN_TIME_SCALE);
|
||||||
|
expect(clampTimeScale(MAX_TIME_SCALE)).toBe(MAX_TIME_SCALE);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Local helper mirroring lib/sim/movement.ts (kept private there on purpose — the
|
// Local helper mirroring lib/sim/movement.ts (kept private there on purpose — the
|
||||||
// engine composes arrivalTimeFor; tests just need the duration for fixtures).
|
// engine composes arrivalTimeFor; tests just need the duration for fixtures).
|
||||||
function travelMs(km: number, speedKmh: number): number {
|
function travelMs(km: number, speedKmh: number): number {
|
||||||
|
|||||||
+6
-6
@@ -12,7 +12,7 @@ import {
|
|||||||
type Rng,
|
type Rng,
|
||||||
type SeedAirport,
|
type SeedAirport,
|
||||||
} from '@/lib/game/seed';
|
} from '@/lib/game/seed';
|
||||||
import { arrivalTimeFor, fuelAt } from './movement';
|
import { arrivalTimeFor, fuelAtWeighted } from './movement';
|
||||||
|
|
||||||
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
|
// 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
|
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
|
||||||
@@ -22,12 +22,12 @@ import { arrivalTimeFor, fuelAt } from './movement';
|
|||||||
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms —
|
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms —
|
||||||
// comfortably above a normal client poll interval (~1 s), so active play advances
|
// comfortably above a normal client poll interval (~1 s), so active play advances
|
||||||
// ~real time × scale; small enough that one stale read after an absence moves game
|
// ~real time × scale; small enough that one stale read after an absence moves game
|
||||||
// time by at most 2 s × scale (≈ 2 min even at max scale 64). The sim therefore
|
// time by at most 2 s × scale (≈ 33 min even at max scale 1000). The sim therefore
|
||||||
// only meaningfully progresses while actively polled.
|
// only meaningfully progresses while actively polled.
|
||||||
export const MAX_TICK_ELAPSED_MS = 2_000;
|
export const MAX_TICK_ELAPSED_MS = 2_000;
|
||||||
|
|
||||||
export const MIN_TIME_SCALE = 1;
|
export const MIN_TIME_SCALE = 1;
|
||||||
export const MAX_TIME_SCALE = 64; // top of the power-of-two ladder (v0.9.2)
|
export const MAX_TIME_SCALE = 1000; // top of the slider ladder (v0.14.0)
|
||||||
|
|
||||||
// Reputation gain per delivered package: BASE + PER_KM × great-circle km, rounded
|
// Reputation gain per delivered package: BASE + PER_KM × great-circle km, rounded
|
||||||
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
|
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
|
||||||
@@ -131,14 +131,14 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
||||||
|
|
||||||
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg burn.
|
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn.
|
||||||
await inst.db.update(schema.planes)
|
await inst.db.update(schema.planes)
|
||||||
.set({
|
.set({
|
||||||
status: 'available',
|
status: 'available',
|
||||||
locationIcao: to.icao,
|
locationIcao: to.icao,
|
||||||
lat: to.lat,
|
lat: to.lat,
|
||||||
lon: to.lon,
|
lon: to.lon,
|
||||||
fuel: fuelAt(p.fuel, type.burnPerKm, distanceKm, 1),
|
fuel: fuelAtWeighted(p.fuel, type.burnPerKm, type.emptyWeightKg, type.maxFuel, distanceKm, 1),
|
||||||
departureSimTime: null,
|
departureSimTime: null,
|
||||||
destIcao: null,
|
destIcao: null,
|
||||||
})
|
})
|
||||||
@@ -264,7 +264,7 @@ export function runAction<T>(fn: (inst: GameDb) => Promise<T>): Promise<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tick first so the returned state reflects current time, then apply the new
|
// Tick first so the returned state reflects current time, then apply the new
|
||||||
// controls. timeScale is clamped to [1, 64]; validation of raw input happens in
|
// controls. timeScale is clamped to [1, 1000]; validation of raw input happens in
|
||||||
// the route handler (400 on non-number / non-boolean).
|
// the route handler (400 on non-number / non-boolean).
|
||||||
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
|
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
|
||||||
return withLock(async () => {
|
return withLock(async () => {
|
||||||
|
|||||||
+58
-14
@@ -1,12 +1,23 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { arrivalTimeFor, fuelAt, positionAt, progressAt, travelDurationMs } from './movement';
|
import {
|
||||||
|
arrivalTimeFor,
|
||||||
|
burnRateConstant,
|
||||||
|
FUEL_DENSITY_KG_PER_L,
|
||||||
|
fuelAtWeighted,
|
||||||
|
positionAt,
|
||||||
|
progressAt,
|
||||||
|
requiredFuelFor,
|
||||||
|
travelDurationMs,
|
||||||
|
} from './movement';
|
||||||
|
|
||||||
// Synthetic in-flight fixtures — no DB needed: everything is a pure function of
|
// Synthetic in-flight fixtures — no DB needed: everything is a pure function of
|
||||||
// the sim clock. ATR 72-600 numbers from lib/game/catalog.ts.
|
// the sim clock. ATR 72-600 numbers from lib/game/catalog.ts.
|
||||||
const DEP = 1_750_000_000_000; // departure sim time (ms)
|
const DEP = 1_750_000_000_000; // departure sim time (ms)
|
||||||
const SPEED = 510; // km/h
|
const SPEED = 510; // km/h
|
||||||
const BURN = 1.75; // L/km
|
const BURN = 1.75; // L/km at a full tank
|
||||||
|
const WE = 9_300; // kg, operating empty weight
|
||||||
|
const TANK = 6_300; // liters, full tank
|
||||||
|
|
||||||
// Frankfurt → Madrid, real coordinates from the CSV dataset.
|
// Frankfurt → Madrid, real coordinates from the CSV dataset.
|
||||||
const FROM = { lat: 50.0333, lon: 8.5706 };
|
const FROM = { lat: 50.0333, lon: 8.5706 };
|
||||||
@@ -96,17 +107,53 @@ describe('positionAt (great-circle slerp)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('fuelAt', () => {
|
describe('weighted burn model (v0.16.0)', () => {
|
||||||
it('burns fuel proportionally to distance flown', () => {
|
it('calibrates so a full tank burns exactly the old constant rate', () => {
|
||||||
const start = 6_300; // full ATR tank
|
const k = burnRateConstant(BURN, WE, TANK);
|
||||||
expect(fuelAt(start, BURN, KM, 0)).toBe(start);
|
expect(k * (WE + FUEL_DENSITY_KG_PER_L * TANK)).toBeCloseTo(BURN, 12);
|
||||||
expect(fuelAt(start, BURN, KM, 0.5)).toBeCloseTo(start - BURN * KM / 2, 9);
|
|
||||||
expect(fuelAt(start, BURN, KM, 1)).toBeCloseTo(start - BURN * KM, 9);
|
// Over a short hop from full, weighted ≈ constant — divergence only grows as fuel drops off.
|
||||||
|
const d = 100;
|
||||||
|
const consumed = TANK - fuelAtWeighted(TANK, BURN, WE, TANK, d, 1);
|
||||||
|
expect(Math.abs(consumed - BURN * d)).toBeLessThan(1); // < 1 L over 100 km from full
|
||||||
|
});
|
||||||
|
|
||||||
|
it('consumption matches numeric integration of r(F) = k·(We + ρF)', () => {
|
||||||
|
const k = burnRateConstant(BURN, WE, TANK);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
// Euler-integrate dF/dx = −k(We + ρF) from a full tank over the whole leg.
|
||||||
|
const steps = 200_000;
|
||||||
|
const h = KM / steps;
|
||||||
|
let f = TANK;
|
||||||
|
for (let i = 0; i < steps; i++) f -= k * (WE + rho * f) * h;
|
||||||
|
expect(Math.abs(fuelAtWeighted(TANK, BURN, WE, TANK, KM, 1) - f)).toBeLessThan(0.001); // Euler drift is sub-milliliter here
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requiredFuelFor is zero for a zero leg and strictly increasing in distance', () => {
|
||||||
|
expect(requiredFuelFor(BURN, WE, TANK, 0)).toBe(0);
|
||||||
|
let prev = requiredFuelFor(BURN, WE, TANK, 100);
|
||||||
|
for (const d of [500, 1_000, 2_000, 3_000, 4_000]) {
|
||||||
|
const cur = requiredFuelFor(BURN, WE, TANK, d);
|
||||||
|
expect(cur).toBeGreaterThan(prev);
|
||||||
|
prev = cur;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a lighter start burns less over the same distance', () => {
|
||||||
|
const burnFromFull = TANK - fuelAtWeighted(TANK, BURN, WE, TANK, KM, 1);
|
||||||
|
const burnFromHalf = TANK / 2 - fuelAtWeighted(TANK / 2, BURN, WE, TANK, KM, 1);
|
||||||
|
expect(burnFromFull).toBeGreaterThan(burnFromHalf);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('starting with exactly the required fuel arrives on empty', () => {
|
||||||
|
const req = requiredFuelFor(BURN, WE, TANK, KM);
|
||||||
|
expect(fuelAtWeighted(req, BURN, WE, TANK, KM, 1)).toBeCloseTo(0, 6);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('clamps at zero instead of going negative', () => {
|
it('clamps at zero instead of going negative', () => {
|
||||||
expect(fuelAt(100, BURN, 1_000, 1)).toBe(0); // needs 1750 L, has 100
|
expect(fuelAtWeighted(100, BURN, WE, TANK, KM, 1)).toBe(0); // needs ~2800 L from full, has 100
|
||||||
expect(fuelAt(100, BURN, 1_000, 0.01)).toBeCloseTo(100 - 17.5, 9);
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, 0)).toBe(TANK);
|
||||||
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, 0, 1)).toBe(TANK);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('composes with progressAt for a just-before-arrival snapshot', () => {
|
it('composes with progressAt for a just-before-arrival snapshot', () => {
|
||||||
@@ -114,9 +161,6 @@ describe('fuelAt', () => {
|
|||||||
const clock = DEP + duration - 1; // one ms before arrival
|
const clock = DEP + duration - 1; // one ms before arrival
|
||||||
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, clock));
|
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, clock));
|
||||||
expect(haversineKm(p.lat, p.lon, TO.lat, TO.lon)).toBeGreaterThan(0); // not yet at the gate
|
expect(haversineKm(p.lat, p.lon, TO.lat, TO.lon)).toBeGreaterThan(0); // not yet at the gate
|
||||||
expect(fuelAt(6_300, BURN, KM, progressAt(DEP, KM, SPEED, clock))).toBeCloseTo(
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, progressAt(DEP, KM, SPEED, clock))).toBeGreaterThan(0);
|
||||||
6_300 - BURN * KM * (1 - 1 / duration),
|
|
||||||
6,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+52
-4
@@ -65,8 +65,56 @@ export function positionAt(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fuel remaining after flying `progress` of a leg of distanceKm. Clamped at 0 —
|
// --- Weight-proportional fuel burn (v0.16.0) ---
|
||||||
// range exhaustion is not modeled yet (fuel management/refueling comes later).
|
//
|
||||||
export function fuelAt(startFuel: number, burnPerKm: number, distanceKm: number, progress: number): number {
|
// The instantaneous burn rate is proportional to total weight: r(F) = k·(We + ρF) L/km,
|
||||||
return Math.max(0, startFuel - burnPerKm * distanceKm * progress);
|
// where We is the empty weight in kg, ρ the fuel density and F the current load in
|
||||||
|
// liters — a heavier plane burns more per km. k is calibrated so that a FULL tank
|
||||||
|
// burns exactly the catalog's constant burnPerKm: k = burnPerKm / (We + ρ·maxFuel),
|
||||||
|
// so full-tank legs match the old model at departure and only diverge as fuel (and
|
||||||
|
// weight) drops off in flight. Closed forms of dF/dx = −k(We + ρF):
|
||||||
|
// fuel after distance D from F₀: (F₀ + We/ρ)·e^{−kρD} − We/ρ
|
||||||
|
// consumption over D: (F₀ + We/ρ)·(1 − e^{−kρD})
|
||||||
|
// fuel required to cover D arriving with 0, independent of F₀: (We/ρ)(e^{kρD} − 1)
|
||||||
|
|
||||||
|
// Jet-A1 density in kg/L — converts a liter load into its weight contribution.
|
||||||
|
export const FUEL_DENSITY_KG_PER_L = 0.8;
|
||||||
|
|
||||||
|
// Calibration constant k for one plane type (see the model note above).
|
||||||
|
export function burnRateConstant(burnPerKm: number, emptyWeightKg: number, maxFuel: number): number {
|
||||||
|
return burnPerKm / (emptyWeightKg + FUEL_DENSITY_KG_PER_L * maxFuel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fuel remaining after flying `progress` of a leg of distanceKm from startFuel under the
|
||||||
|
// weighted model. Clamped at 0 — range exhaustion is not modeled (a plane that runs dry
|
||||||
|
// limps to the gate on fumes, same as before).
|
||||||
|
export function fuelAtWeighted(
|
||||||
|
startFuel: number,
|
||||||
|
burnPerKm: number,
|
||||||
|
emptyWeightKg: number,
|
||||||
|
maxFuel: number,
|
||||||
|
distanceKm: number,
|
||||||
|
progress: number,
|
||||||
|
): number {
|
||||||
|
const d = distanceKm * progress;
|
||||||
|
if (d <= 0) return startFuel;
|
||||||
|
const k = burnRateConstant(burnPerKm, emptyWeightKg, maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
const f = (startFuel + emptyWeightKg / rho) * Math.exp(-k * rho * d) - emptyWeightKg / rho;
|
||||||
|
return Math.max(0, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Total fuel required to cover distanceKm arriving with an empty tank — independent of the
|
||||||
|
// starting load. A leg is flyable from a plane iff its current fuel covers this amount; it
|
||||||
|
// fits in the aircraft at all iff this does not exceed the tank capacity.
|
||||||
|
export function requiredFuelFor(
|
||||||
|
burnPerKm: number,
|
||||||
|
emptyWeightKg: number,
|
||||||
|
maxFuel: number,
|
||||||
|
distanceKm: number,
|
||||||
|
): number {
|
||||||
|
if (distanceKm <= 0) return 0;
|
||||||
|
const k = burnRateConstant(burnPerKm, emptyWeightKg, maxFuel);
|
||||||
|
const rho = FUEL_DENSITY_KG_PER_L;
|
||||||
|
return (emptyWeightKg / rho) * (Math.exp(k * rho * distanceKm) - 1);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-10
@@ -1,16 +1,16 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { MAX_SCALE, MIN_SCALE, TIME_SCALES, scaleToSlider, sliderToScale } from './timeScale';
|
import { MAX_SCALE, MIN_SCALE, TIME_SCALES, scaleToSlider, sliderToScale } from './timeScale';
|
||||||
|
|
||||||
const STEPS = TIME_SCALES.length - 1; // 6 intervals across the 7 ladder positions
|
const STEPS = TIME_SCALES.length - 1; // 9 intervals across the 10 ladder positions (v0.14.0)
|
||||||
|
|
||||||
describe('sliderToScale', () => {
|
describe('sliderToScale', () => {
|
||||||
it('is exact at the endpoints (0 → 1×, 1 → 64×)', () => {
|
it('is exact at the endpoints (0 → 1×, 1 → 1000×)', () => {
|
||||||
expect(sliderToScale(0)).toBe(MIN_SCALE);
|
expect(sliderToScale(0)).toBe(MIN_SCALE);
|
||||||
expect(sliderToScale(1)).toBe(MAX_SCALE);
|
expect(sliderToScale(1)).toBe(MAX_SCALE);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('maps each of the 7 positions to the power-of-two ladder', () => {
|
it('maps each of the 10 positions to the ladder', () => {
|
||||||
const expected = [1, 2, 4, 8, 16, 32, 64];
|
const expected = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000];
|
||||||
for (let i = 0; i < TIME_SCALES.length; i++) {
|
for (let i = 0; i < TIME_SCALES.length; i++) {
|
||||||
expect(sliderToScale(i / STEPS)).toBe(expected[i]);
|
expect(sliderToScale(i / STEPS)).toBe(expected[i]);
|
||||||
}
|
}
|
||||||
@@ -39,9 +39,9 @@ describe('sliderToScale', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('scaleToSlider', () => {
|
describe('scaleToSlider', () => {
|
||||||
it('is exact at the endpoints (1× → 0, 64× → 1)', () => {
|
it('is exact at the endpoints (1× → 0, 1000× → 1)', () => {
|
||||||
expect(scaleToSlider(1)).toBe(0);
|
expect(scaleToSlider(1)).toBe(0);
|
||||||
expect(scaleToSlider(64)).toBe(1);
|
expect(scaleToSlider(1000)).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('places each ladder value on its own position', () => {
|
it('places each ladder value on its own position', () => {
|
||||||
@@ -61,7 +61,7 @@ describe('scaleToSlider', () => {
|
|||||||
it('clamps out-of-range and non-finite input', () => {
|
it('clamps out-of-range and non-finite input', () => {
|
||||||
expect(scaleToSlider(0)).toBe(0);
|
expect(scaleToSlider(0)).toBe(0);
|
||||||
expect(scaleToSlider(-3)).toBe(0);
|
expect(scaleToSlider(-3)).toBe(0);
|
||||||
expect(scaleToSlider(65)).toBe(1);
|
expect(scaleToSlider(1001)).toBe(1); // above the ladder top → clamped to 1000× → t=1
|
||||||
expect(scaleToSlider(NaN)).toBe(0);
|
expect(scaleToSlider(NaN)).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -73,8 +73,9 @@ describe('round-trip', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('maps off-ladder scales to the nearest power of two', () => {
|
it('maps off-ladder scales to the nearest ladder step by log distance', () => {
|
||||||
expect(sliderToScale(scaleToSlider(3))).toBe(4); // log2(3) ≈ 1.58 → step 2 (4×)
|
expect(sliderToScale(scaleToSlider(3))).toBe(2); // ln 3 ≈ 1.10 → closer to 2 (ln ≈ 0.69) than 5 (ln ≈ 1.61)
|
||||||
expect(sliderToScale(scaleToSlider(60))).toBe(64); // legacy max from the v0.9.x era
|
expect(sliderToScale(scaleToSlider(60))).toBe(50); // legacy max from the v0.9.x era sits between 50 and 100, nearer 50
|
||||||
|
expect(sliderToScale(scaleToSlider(200))).toBe(250); // ln 200 ≈ 5.30 → closer to 250 (ln ≈ 5.52) than 100 (ln ≈ 4.61)
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+18
-9
@@ -1,24 +1,33 @@
|
|||||||
// Pure mapping helpers for the time-scale slider (v0.9.2) — no game logic, unit-testable
|
// Pure mapping helpers for the time-scale slider (v0.9.2, values reworked in v0.14.0) — no
|
||||||
// in node. The slider has 7 discrete positions on a power-of-two ladder:
|
// game logic, unit-testable in node. The slider has 10 discrete positions on a mixed
|
||||||
// 1× → 2× → 4× → 8× → 16× → 32× → 64×, so each step doubles the speed (matching
|
// ×2/×2.5 ladder: 1× → 2× → 5× → 10× → 25× → 50× → 100× → 250× → 500× → 1000×, so each
|
||||||
// POST /api/sim's clamp range [1, 64]).
|
// step roughly doubles the speed (matching POST /api/sim's clamp range [1, 1000]).
|
||||||
|
|
||||||
export const TIME_SCALES = [1, 2, 4, 8, 16, 32, 64] as const;
|
export const TIME_SCALES = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000] as const;
|
||||||
export const MIN_SCALE: number = TIME_SCALES[0];
|
export const MIN_SCALE: number = TIME_SCALES[0];
|
||||||
export const MAX_SCALE: number = TIME_SCALES[TIME_SCALES.length - 1];
|
export const MAX_SCALE: number = TIME_SCALES[TIME_SCALES.length - 1];
|
||||||
|
|
||||||
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||||
|
|
||||||
// t → scale: the position maps to the nearest ladder step. Exact at the endpoints:
|
// t → scale: the position maps to the nearest ladder step. Exact at the endpoints:
|
||||||
// sliderToScale(0) === 1, sliderToScale(1) === 64.
|
// sliderToScale(0) === 1, sliderToScale(1) === 1000.
|
||||||
export function sliderToScale(t: number): number {
|
export function sliderToScale(t: number): number {
|
||||||
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
|
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
|
||||||
return TIME_SCALES[clamp(Math.round(tt * (TIME_SCALES.length - 1)), 0, TIME_SCALES.length - 1)];
|
return TIME_SCALES[clamp(Math.round(tt * (TIME_SCALES.length - 1)), 0, TIME_SCALES.length - 1)];
|
||||||
}
|
}
|
||||||
|
|
||||||
// scale → t: the nearest ladder position by log2 distance. Exact at the endpoints:
|
// scale → t: the nearest ladder position by log distance. Exact at the endpoints:
|
||||||
// scaleToSlider(1) === 0, scaleToSlider(64) === 1; round-trips every value in TIME_SCALES.
|
// scaleToSlider(1) === 0, scaleToSlider(1000) === 1; round-trips every value in TIME_SCALES.
|
||||||
export function scaleToSlider(scale: number): number {
|
export function scaleToSlider(scale: number): number {
|
||||||
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
|
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
|
||||||
return Math.log2(s) / Math.log2(MAX_SCALE);
|
let best = 0;
|
||||||
|
let bestDist = Infinity;
|
||||||
|
for (let i = 0; i < TIME_SCALES.length; i++) {
|
||||||
|
const d = Math.abs(Math.log(s) - Math.log(TIME_SCALES[i]));
|
||||||
|
if (d < bestDist) {
|
||||||
|
bestDist = d;
|
||||||
|
best = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best / (TIME_SCALES.length - 1);
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-1
@@ -21,7 +21,18 @@ export interface GameStateResult {
|
|||||||
export async function fetchState(): Promise<StateSnapshot> {
|
export async function fetchState(): Promise<StateSnapshot> {
|
||||||
const res = await fetch('/api/state', { cache: 'no-store' });
|
const res = await fetch('/api/state', { cache: 'no-store' });
|
||||||
if (!res.ok) throw new Error(`GET /api/state → HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`GET /api/state → HTTP ${res.status}`);
|
||||||
return (await res.json()) as StateSnapshot;
|
const snapshot = (await res.json()) as StateSnapshot;
|
||||||
|
// Dev/e2e hook (v0.15.0): the last successfully polled snapshot, so tests can compare what
|
||||||
|
// the BROWSER received against a fresh node-side fetch. Client-only, harmless in prod.
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
(window as unknown as Record<string, unknown>).__flightLastSnapshot = {
|
||||||
|
planeIds: snapshot.planes.map((p) => p.id),
|
||||||
|
cash: snapshot.account.cash,
|
||||||
|
timeScale: snapshot.simState.timeScale,
|
||||||
|
at: Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return snapshot;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The shell's single polling source (v0.9.0): one GET /api/state loop for the whole page,
|
// The shell's single polling source (v0.9.0): one GET /api/state loop for the whole page,
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { advanceSimClock, type SimClockAnchor } from './useSimClock';
|
||||||
|
|
||||||
|
// ISS-007 (v0.16.1) — the pure extrapolation core of lib/useSimClock.ts. The hook itself is a
|
||||||
|
// thin setInterval + re-sync wrapper covered by e2e (panes.spec.ts "ticks smoothly between polls");
|
||||||
|
// this suite pins the math: game time advances real-time × timeScale, frozen while paused.
|
||||||
|
|
||||||
|
const anchor = (over: Partial<SimClockAnchor> = {}): SimClockAnchor => ({
|
||||||
|
clockMs: 1_750_000_000_000,
|
||||||
|
at: 1_000_000,
|
||||||
|
timeScale: 1,
|
||||||
|
paused: false,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('advanceSimClock', () => {
|
||||||
|
it('advances by exactly elapsed real-time × timeScale while running', () => {
|
||||||
|
expect(advanceSimClock(anchor(), 1_001_000)).toBe(1_750_000_000_000 + 1_000); // scale 1: 1 s real = 1 s game
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 25 }), 1_002_500)).toBe(1_750_000_000_000 + 62_500);
|
||||||
|
// The e2e scenario: scale 1000, 2.5 s real → 2 500 game seconds.
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_002_500)).toBe(1_750_000_000_000 + 2_500_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the anchor value exactly at zero elapsed', () => {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_000_000)).toBe(1_750_000_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is frozen while paused regardless of elapsed or scale', () => {
|
||||||
|
const a = anchor({ timeScale: 1000, paused: true });
|
||||||
|
expect(advanceSimClock(a, 1_000_000)).toBe(1_750_000_000_000);
|
||||||
|
expect(advanceSimClock(a, 2_000_000)).toBe(1_750_000_000_000); // a full second later — still frozen
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps to the anchor value when nowMs is before the anchor (clock skew), never backwards', () => {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: 1000 }), 999_999)).toBe(1_750_000_000_000);
|
||||||
|
expect(advanceSimClock(anchor({ paused: true }), 999_999)).toBe(1_750_000_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mirrors the server tick model (tickOnce): advance = elapsed × timeScale while actively polled', () => {
|
||||||
|
// lib/sim/engine.ts: clockMs += min(now − lastRealTickMs, MAX_TICK_ELAPSED_MS) × timeScale.
|
||||||
|
// For gaps under the 2 s clamp the client extrapolation is exactly the server's own formula.
|
||||||
|
const scale = 50;
|
||||||
|
for (const gap of [1, 250, 999, 1_999]) {
|
||||||
|
expect(advanceSimClock(anchor({ timeScale: scale }), 1_000_000 + gap)).toBe(
|
||||||
|
1_750_000_000_000 + gap * scale,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import type { StateSnapshot } from './game/state';
|
||||||
|
|
||||||
|
// ISS-007 (v0.16.1): the sim clock ticks smoothly on the CLIENT between polls instead of
|
||||||
|
// jumping once per snapshot. The server's authoritative rate is exactly real-time × timeScale
|
||||||
|
// (tickOnce in lib/sim/engine.ts: advance = min(elapsed, MAX_TICK_ELAPSED_MS) × timeScale), so
|
||||||
|
// client-side extrapolation mirrors the server's own model. Every new snapshot re-anchors to
|
||||||
|
// server truth, bounding any drift by network latency only.
|
||||||
|
|
||||||
|
export interface SimClockAnchor {
|
||||||
|
// Server truth at anchor time — the snapshot's simState.clockMs.
|
||||||
|
clockMs: number;
|
||||||
|
// Date.now() when that snapshot was received.
|
||||||
|
at: number;
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pure core of the extrapolation — mirrors tickOnce: while running, game time advances by
|
||||||
|
// real-time × timeScale; while paused it is frozen (advance 0). nowMs before `at` clamps to
|
||||||
|
// the anchor value instead of going backwards. Unit-testable in node.
|
||||||
|
export function advanceSimClock(anchor: SimClockAnchor, nowMs: number): number {
|
||||||
|
if (anchor.paused) return anchor.clockMs;
|
||||||
|
return anchor.clockMs + Math.max(0, nowMs - anchor.at) * anchor.timeScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ~10 fps display refresh — smooth for a seconds-precision wall clock without busy re-renders.
|
||||||
|
const DISPLAY_TICK_MS = 100;
|
||||||
|
|
||||||
|
export interface SimClockControls {
|
||||||
|
// EFFECTIVE controls (optimistic pending scale / current pause), not the snapshot's:
|
||||||
|
// UI changes take effect on click/drag without waiting for a confirming snapshot.
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the display clockMs to render, or null until the first snapshot arrives.
|
||||||
|
export function useSimClock(snapshot: StateSnapshot | null, controls: SimClockControls): number | null {
|
||||||
|
const anchorRef = useRef<SimClockAnchor | null>(null);
|
||||||
|
const [displayMs, setDisplayMs] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// Re-sync on every snapshot AND effective-control change: snap to server truth. The snapshot
|
||||||
|
// object is fresh per poll (useGameState), so this runs once per poll cycle as well.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!snapshot) return;
|
||||||
|
anchorRef.current = {
|
||||||
|
clockMs: snapshot.simState.clockMs,
|
||||||
|
at: Date.now(),
|
||||||
|
timeScale: controls.timeScale,
|
||||||
|
paused: controls.paused,
|
||||||
|
};
|
||||||
|
setDisplayMs(advanceSimClock(anchorRef.current, Date.now()));
|
||||||
|
}, [snapshot, controls.timeScale, controls.paused]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => {
|
||||||
|
const anchor = anchorRef.current;
|
||||||
|
if (anchor) setDisplayMs(advanceSimClock(anchor, Date.now()));
|
||||||
|
}, DISPLAY_TICK_MS);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// First paint after a snapshot arrives happens before the re-sync effect runs — show the
|
||||||
|
// snapshot value directly so the clock never blanks for a frame.
|
||||||
|
return displayMs ?? (snapshot ? snapshot.simState.clockMs : null);
|
||||||
|
}
|
||||||
+2
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flight-ops",
|
"name": "flight-ops",
|
||||||
"version": "0.12.2",
|
"version": "0.16.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"sql.js": "^1.14.2"
|
"sql.js": "^1.14.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "1.63.0",
|
||||||
"@types/node": "^22.20.3",
|
"@types/node": "^22.20.3",
|
||||||
"@types/react": "^19.3.0",
|
"@types/react": "^19.3.0",
|
||||||
"@types/react-dom": "^19.3.0",
|
"@types/react-dom": "^19.3.0",
|
||||||
|
|||||||
+16
-11
@@ -1,28 +1,33 @@
|
|||||||
import { defineConfig } from '@playwright/test';
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
const remoteRunner = true;
|
// Browsers run on the shared remote Playwright server by default (AGENTS.md).
|
||||||
|
// PW_REMOTE_BROWSER=0 → local browsers instead (CI, or boxes without LAN access to 192.168.1.4).
|
||||||
|
const remoteBrowser = process.env.PW_REMOTE_BROWSER !== '0';
|
||||||
|
|
||||||
if (!process.env.PW_TEST_CONNECT_WS_ENDPOINT) {
|
if (!process.env.PW_TEST_CONNECT_WS_ENDPOINT && remoteBrowser) {
|
||||||
process.env.PW_TEST_CONNECT_WS_ENDPOINT = 'ws://192.168.1.4:3000/';
|
process.env.PW_TEST_CONNECT_WS_ENDPOINT = 'ws://192.168.1.4:3000/';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// App under test. Default: the live compose instance behind Traefik, deployed manually
|
||||||
|
// before running the suite (AGENTS.md). When E2E_DEPLOY_CMD is set it runs as a webServer
|
||||||
|
// and the suite waits for baseURL to come up — CI uses this to target an isolated stack
|
||||||
|
// inside dind instead of production. All vars optional; unset = current local behavior.
|
||||||
|
const deployCmd = process.env.E2E_DEPLOY_CMD;
|
||||||
|
const baseUrl = process.env.E2E_BASE_URL ?? 'https://flight.dev.kkhost.pl';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: './e2e',
|
testDir: './e2e',
|
||||||
|
globalSetup: './e2e/ci-diagnostics.ts',
|
||||||
// Serial execution: e2e/state.spec.ts restarts the compose container mid-run,
|
// Serial execution: e2e/state.spec.ts restarts the compose container mid-run,
|
||||||
// which would break any map test running concurrently in another worker.
|
// which would break any map test running concurrently in another worker.
|
||||||
workers: 1,
|
workers: 1,
|
||||||
timeout: 300_000,
|
timeout: 300_000,
|
||||||
retries: 1,
|
retries: 1,
|
||||||
use: {
|
use: {
|
||||||
baseURL: process.env.E2E_BASE_URL ?? 'https://flight.dev.kkhost.pl',
|
baseURL: baseUrl,
|
||||||
trace: 'on-first-retry',
|
trace: 'on-first-retry',
|
||||||
},
|
},
|
||||||
webServer: remoteRunner
|
webServer: deployCmd
|
||||||
? undefined
|
? { command: deployCmd, url: baseUrl, reuseExistingServer: true, timeout: 600_000 }
|
||||||
: {
|
: undefined,
|
||||||
command: 'docker compose up -d --build',
|
|
||||||
url: 'https://flight.dev.kkhost.pl',
|
|
||||||
reuseExistingServer: true,
|
|
||||||
timeout: 600_000,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
Reference in New Issue
Block a user