Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4f7947666 | ||
|
|
570ad52d47 | ||
|
|
59974d1b79 | ||
|
|
af5176354a | ||
|
|
f5468bb640 | ||
|
|
0970ee4710 | ||
|
|
6e1439391a | ||
|
|
86379fc9c6 |
@@ -1,18 +1,16 @@
|
|||||||
# Flight Simulator — Workflow Rules
|
# Flight Simulator — Workflow Rules
|
||||||
|
|
||||||
## 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. Connected issues/tasks that reference the same part of code MAY be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel).
|
||||||
2. **Feature branch + PR** — every change lands on a feature branch off `master` (no direct pushes to master). The branch carries the commits below; open a pull request to `master`.
|
2. **Feature branch + PR** — every change lands on a feature branch off `master` (no direct pushes to master). The branch carries the commits below; open a pull request to `master`.
|
||||||
3. **Changelog entry** — every such change is listed in `CHANGELOG.md` with date, time and version (format: `## v<version> — YYYY-MM-DD HH:MM`, then bullet points of what changed).
|
3. **Changelog entry** — every such change is listed in `CHANGELOG.md` with date, time and version (format: `## v<version> — YYYY-MM-DD HH:MM`, then bullet points of what changed).
|
||||||
4. **Version bump** — the version is updated in `package.json`.
|
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.
|
5. **CI must pass** — enforced by branch protection on `master` (required status check `CI / build + unit + e2e (pull request)`): the PR cannot be merged until CI is green. Merge via auto-merge (`POST /repos/{owner}/{repo}/pulls/{n}/merge` with body `{"do":"merge","merge_style":"merge","merge_when_checks_succeed":true}`) so it merges automatically once CI passes. 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.
|
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 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**.
|
1. **CI-only** — e2e runs ONLY in CI, against an isolated docker stack inside dind built from `docker-compose.ci.yml` (project name `flight-ci`, app container on a static IP; see `.gitea/workflows/ci.yml`). There are NO local e2e runs at all: locally you verify with `tsc --noEmit` + `npx vitest run` + `npx playwright test --list` (typecheck, unit suite, specs compile and list), and the full e2e suite is verified by CI on every PR. **CI never deploys to or modifies production.**
|
||||||
2. **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.
|
2. **CI env vars** (`playwright.config.ts`, all optional) — `E2E_BASE_URL` (app under test; CI sets it to the in-network app host, so the config's default of the live Traefik instance at `https://flight.dev.kkhost.pl` is never used), `E2E_DEPLOY_CMD` (runs as Playwright webServer: deploys the stack and waits for readiness before tests start; CI uses build + `up -d` + `logs -f`), `PW_REMOTE_BROWSER=0` (CI runs local chromium because the shared remote browser server at 192.168.1.4 cannot reach a stack inside dind — when unset, the config defaults to that remote server and to the live instance as baseURL), and `E2E_COMPOSE_ARGS`, read by `e2e/state.spec.ts` for its mid-run `docker compose restart flight` (CI points it at `-f docker-compose.ci.yml -p flight-ci`).
|
||||||
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,28 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.20.0 — 2026-09-19 19:21
|
||||||
|
- **On board moved to the left pane (ISS-021).** The "On board" section (per-plane blocks with loaded/expired cargo rows, Refuel-for-leg / Fly-to / Abandon + penalty preview) now renders in `components/LeftPane.tsx` between Fleet and Time — wallet stays on top. The JSX moved verbatim (same testids: `onboard-{planeId}`, `onboard-package-{pkg.id}`, `refuel-for-*`, `fly-to-*`, `abandon-*` + penalty preview), along with the `onboard` computation (`planes.filter(flying || slotsUsedFor > 0)`) and per-plane cargo filter. All onboard e2e locators are global testids, so existing specs work unchanged
|
||||||
|
- **Left pane widened: grid swapped to 360/1fr/280.** `.app-shell` in `app/globals.css` goes from `280px minmax(0, 1fr) 360px` to `360px minmax(0, 1fr) 280px` — total fixed width stays 640 px, so the map column is pixel-identical (map.spec.ts clicks via dynamic `map.project()`). Stale comments updated (on-board blocks now in the left pane; Relocate row comment reflects the 280 px right pane)
|
||||||
|
- **Shared action runner hook.** RightPane's local `runAction` (busy gate, inline pane error + shell toast on failure, full post-action snapshot pushed via `applySnapshot`) extracted to new `lib/useGameAction.ts`: `useGameAction(state, applySnapshot, onError) → { runAction, busy, actionError }`, exact semantics kept incl. the non-2xx throw/catch and inline-error auto-clear on the next snapshot. Used in BOTH panes; LeftPane receives `applySnapshot` from the shell (`app/page.tsx`). RightPane keeps `[data-testid="right-error"]`; LeftPane gains a matching `[data-testid="left-action-error"]`. Pure helpers `slotsUsedFor` / `loadEligiblePlanes` stay exported from RightPane (unit tests import them there; LeftPane imports `slotsUsedFor` from it); the Market Relocate row + `/api/airports` fetch stay in RightPane
|
||||||
|
- Tests: e2e — `panes.spec.ts` first test now also asserts the "On board" heading is visible inside `[data-testid="left-pane"]` and absent from the right pane; stale header comments updated in `actions.spec.ts` / `right-pane.spec.ts`. No unit-test changes (baseline 283)
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
- **On-board cargo rows are two lines (ISS-028).** Each `onboard-package-*` row now stacks a full-width "Fly to <airport>" button on its own line above Refuel + Abandon side by side: `components/LeftPane.tsx` moves the fly-to button out of `.contract-main` into the row root and wraps refuel-for + abandon in a new `.onboard-actions` div — all testids, label text, penalty preview and disabled states unchanged. Long destination names in the fly-to label truncate with an ellipsis instead of overflowing: the label's inner span gets `min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap`, full name preserved via a `title` attribute (CSS in `app/globals.css`: `.onboard-block .contract-row` becomes flex-column, new `.onboard-fly-btn` / `.onboard-fly-label` / `.onboard-actions`). No e2e changes — specs locate everything by testid and assert no layout or button order; no version bump (part 2 of v0.20.0)
|
||||||
|
|
||||||
|
## v0.19.2 — 2026-09-19 20:06
|
||||||
|
- **AGENTS.md "Change process" item 1** — connected issues/tasks that reference the same part of code may now be done together on one branch/PR with a single version bump (e.g. two UI tweaks to the same panel)
|
||||||
|
- **AGENTS.md "E2E tests" section rewritten to match current reality** — e2e runs ONLY in CI, against an isolated docker stack inside dind (`docker-compose.ci.yml`); there are NO local e2e runs at all (local verification = `tsc --noEmit` + `npx vitest run` + `npx playwright test --list`; the full suite is verified by CI on every PR). Dropped the stale local-run instructions (deploying to the Traefik-routed instance before testing, driving browsers through the remote Playwright server at 192.168.1.4:3000); kept and reworded the CI env vars that actually exist in `playwright.config.ts` (`E2E_BASE_URL`, `E2E_DEPLOY_CMD`, `PW_REMOTE_BROWSER=0`, `E2E_COMPOSE_ARGS`)
|
||||||
|
|
||||||
|
## v0.19.1 — 2026-09-19 18:48
|
||||||
|
- AGENTS.md: document that CI-green is enforced on master by branch protection (required status check) and that merges use auto-merge (`merge_when_checks_succeed`) so PRs merge automatically once CI passes
|
||||||
|
|
||||||
|
## v0.19.0 — 2026-09-19 18:05
|
||||||
|
- **Auto-slow to 1× when all planes have landed (ISS-011).** When the last plane in flight lands, the sim slows down on its own so an idle fleet doesn't sit at 1000×. Server-side and authoritative: `tickOnce` (`lib/sim/engine.ts`) now remembers how many planes `deliverPackages` finalized during a tick, and when ≥1 plane landed this tick AND no plane remains with status `'flying'` AND the sim is not paused, it persists `timeScale = 1` on the same `sim_state` write as the clock — so the UI slider reflects it on the very next snapshot (no API or OpenAPI change: timeScale is still set via the existing `POST /api/sim`, and `clampTimeScale` semantics are untouched since 1 is a valid ladder value)
|
||||||
|
- **Arrival-triggered, not idle-enforced.** The trigger fires only on the tick that processes a landing — a grounded fleet at high scale with no flight ever happening is left alone (this keeps the existing slider e2e in `panes.spec.ts` green: it sets 1000× and expects the server to confirm it while nothing is flying). Paused state is untouched: while paused no landings are processed, so a paused sim never auto-slows
|
||||||
|
- **No auto-restore by design.** The previous scale is not remembered — once the game slows to 1× after the last landing, the player speeds up manually again (slider or `POST /api/sim`). Deliberately minimal scope: no "resume my old speed" behavior
|
||||||
|
- Tests: unit — new `describe('auto-slow …')` block in `lib/sim/engine.test.ts`: last plane lands → stored timeScale becomes 1; a landing while another plane is still flying → no change; already at 1× → stays 1; paused sim with all planes landed → no change. e2e — new `e2e/auto-slow.spec.ts` (serial mode, SCALE=1000, self-heal fly-home in afterEach like relocation.spec.ts): sets 1000× via the API, dispatches plane-starter on the shortest leg from its hub (EDDF → nearest airport), waits for the landing and asserts the server's `timeScale` is exactly 1 in that snapshot, then proves manual override still works (`POST /api/sim {timeScale: 1000}` confirmed by response + fresh snapshot)
|
||||||
|
- **e2e suite adapted to the new behavior.** Every existing spec that flies out-and-back relied on 1000× persisting across a landing — with ISS-011 it no longer does, so each return leg now re-sets SCALE explicitly: `flyHomeViaApi` in actions/relocation/right-pane/hover (re-set before the repositioning flight after waiting for an in-flight leg to land) and the restore legs inside the test bodies of actions.spec.ts (core loop, expired packages, validation paths ×2), right-pane.spec.ts (fly-to-destination, refuel-for-leg) and hover.spec.ts (flying-plane route highlight). map-interactions.spec.ts needed no change — its `loadAndFly` helper already re-sets SCALE before every landing wait
|
||||||
|
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||||
|
|
||||||
## v0.18.0 — 2026-09-19 16:02
|
## v0.18.0 — 2026-09-19 16:02
|
||||||
- **Relocate a grounded (empty) plane to any airport (ISS-010).** `flyPlane` has allowed pure repositioning since v0.12.0, but the UI only exposed flying for planes that carried cargo — an empty grounded plane had no fly control anywhere. Two new surfaces now drive the EXISTING `POST /api/planes/{id}/fly {destIcao}` endpoint (no API or OpenAPI change):
|
- **Relocate a grounded (empty) plane to any airport (ISS-010).** `flyPlane` has allowed pure repositioning since v0.12.0, but the UI only exposed flying for planes that carried cargo — an empty grounded plane had no fly control anywhere. Two new surfaces now drive the EXISTING `POST /api/planes/{id}/fly {destIcao}` endpoint (no API or OpenAPI change):
|
||||||
- **Right-pane market row** (`components/RightPane.tsx`): a fourth `.market-row` with `[data-testid="relocate-plane"]` (grounded planes, "ATR 72-600 — EDDF" labels), `[data-testid="relocate-dest"]` (all airports from a one-time `GET /api/airports` fetch per page life — same promise-ref pattern as Map.tsx — sorted by name for stable e2e selection) and the `[data-testid="relocate-go"]` "Relocate" button, disabled while busy or until both selects have a value. Same effective-selection + `runAction` pattern as the buy/sell/refuel rows (first grounded plane / first airport preselected); the row wraps (`market-row-relocate`) since two selects don't fit one 360 px line
|
- **Right-pane market row** (`components/RightPane.tsx`): a fourth `.market-row` with `[data-testid="relocate-plane"]` (grounded planes, "ATR 72-600 — EDDF" labels), `[data-testid="relocate-dest"]` (all airports from a one-time `GET /api/airports` fetch per page life — same promise-ref pattern as Map.tsx — sorted by name for stable e2e selection) and the `[data-testid="relocate-go"]` "Relocate" button, disabled while busy or until both selects have a value. Same effective-selection + `runAction` pattern as the buy/sell/refuel rows (first grounded plane / first airport preselected); the row wraps (`market-row-relocate`) since two selects don't fit one 360 px line
|
||||||
|
|||||||
+32
-4
@@ -102,10 +102,12 @@ body {
|
|||||||
color: #334155;
|
color: #334155;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market */
|
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market.
|
||||||
|
ISS-021 (v0.20.0): left widened to 360px (it now carries the On board section), right
|
||||||
|
narrowed to 280px — total fixed width stays 640px, so the map column is unchanged. */
|
||||||
.app-shell {
|
.app-shell {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 280px minmax(0, 1fr) 360px;
|
grid-template-columns: 360px minmax(0, 1fr) 280px;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,7 +364,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ISS-010 (v0.18.0) — the Relocate row carries TWO selects, so let it wrap instead of
|
/* ISS-010 (v0.18.0) — the Relocate row carries TWO selects, so let it wrap instead of
|
||||||
squeezing both below their readable width in the 360 px pane. */
|
squeezing both below their readable width in the 280 px right pane (ISS-021 v0.20.0). */
|
||||||
.market-row-relocate {
|
.market-row-relocate {
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
@@ -374,7 +376,7 @@ body {
|
|||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* v0.12.0 — on-board blocks (per plane) in the right pane */
|
/* v0.12.0 — on-board blocks (per plane); moved to the left pane in ISS-021 (v0.20.0) */
|
||||||
.onboard-block {
|
.onboard-block {
|
||||||
background: rgba(30, 41, 59, 0.6);
|
background: rgba(30, 41, 59, 0.6);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
@@ -382,10 +384,36 @@ body {
|
|||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ISS-028 (v0.20.0 part 2) — on-board cargo rows are two lines: a full-width fly-to button,
|
||||||
|
then refuel + abandon side by side below it; long destination names truncate with an ellipsis. */
|
||||||
.onboard-block .contract-row {
|
.onboard-block .contract-row {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
padding: 6px 0 0;
|
padding: 6px 0 0;
|
||||||
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
border-top: 1px solid rgba(148, 163, 184, 0.2);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-block .contract-row .contract-sub {
|
||||||
|
margin-top: 0; /* row spacing comes from the container's gap */
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-fly-btn {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-fly-label {
|
||||||
|
display: block;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.onboard-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* v0.17.0 — ISS-008: bottom-right toast stack (action errors + game events) */
|
/* v0.17.0 — ISS-008: bottom-right toast stack (action errors + game events) */
|
||||||
|
|||||||
+3
-1
@@ -43,7 +43,9 @@ export default function Home() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} onError={onError} />
|
{/* ISS-021 (v0.20.0) — applySnapshot also reaches the left pane: its On board section's
|
||||||
|
refuel/fly/abandon actions push their response snapshot into the shared state */}
|
||||||
|
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
||||||
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
||||||
action response into the shared state, exactly like RightPane does */}
|
action response into the shared state, exactly like RightPane does */}
|
||||||
|
|||||||
+109
-2
@@ -3,9 +3,12 @@
|
|||||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||||
import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
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 { abandonPenalty } from '@/lib/game/penalty';
|
||||||
|
import { formatCash, formatDeadlineRelative, formatFuel, formatSimClock } from '@/lib/format';
|
||||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||||
|
import { useGameAction } from '@/lib/useGameAction';
|
||||||
import { useSimClock } from '@/lib/useSimClock';
|
import { useSimClock } from '@/lib/useSimClock';
|
||||||
|
import { slotsUsedFor } from './RightPane';
|
||||||
import type { HoverTarget } from './hoverTypes';
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface LeftPaneProps {
|
interface LeftPaneProps {
|
||||||
@@ -14,6 +17,9 @@ 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-021 (v0.20.0): push the full snapshot returned by an action endpoint into the shared shell
|
||||||
|
// state — needed now that the On board section's refuel/fly/abandon actions live in this pane.
|
||||||
|
applySnapshot: (snapshot: StateSnapshot) => void;
|
||||||
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
|
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
|
||||||
onHover: (target: HoverTarget | null) => void;
|
onHover: (target: HoverTarget | null) => void;
|
||||||
// ISS-008 (v0.17.0): report a failed sim-control POST to the shell as an error toast.
|
// ISS-008 (v0.17.0): report a failed sim-control POST to the shell as an error toast.
|
||||||
@@ -83,9 +89,12 @@ export async function retrySimPost(
|
|||||||
return { ok: false, reason: 'exhausted', error: lastError };
|
return { ok: false, reason: 'exhausted', error: lastError };
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LeftPane({ state, loading, error, onRefresh, onHover, onError }: LeftPaneProps) {
|
export default function LeftPane({ state, loading, error, onRefresh, applySnapshot, onHover, onError }: LeftPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
// ISS-021 (v0.20.0): shared action runner for the On board section (moved here from RightPane).
|
||||||
|
const { runAction, busy: actionsBusy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||||
|
|
||||||
// POST /api/sim (retried up to SIM_POST_MAX_ATTEMPTS× on failure — CI runs #44/#47), then
|
// POST /api/sim (retried up to SIM_POST_MAX_ATTEMPTS× on failure — CI runs #44/#47), then
|
||||||
// refetch the full snapshot immediately so the pane reflects the new controls without waiting
|
// refetch the full snapshot immediately so the pane reflects the new controls without waiting
|
||||||
// for the next poll tick. After the final attempt fails keep the stale UI and surface an error
|
// for the next poll tick. After the final attempt fails keep the stale UI and surface an error
|
||||||
@@ -153,6 +162,12 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
|||||||
const paused = state?.simState.paused ?? false;
|
const paused = state?.simState.paused ?? false;
|
||||||
const timeScale = state?.simState.timeScale ?? 1;
|
const timeScale = state?.simState.timeScale ?? 1;
|
||||||
|
|
||||||
|
// On board (v0.12.0, moved from the right pane in ISS-021 v0.20.0): every plane that carries
|
||||||
|
// cargo or is mid-flight gets a block — its loaded/expired packages with fly-to-destination +
|
||||||
|
// abandon controls, and flying planes show their current leg.
|
||||||
|
const clockMs = state?.simState.clockMs ?? 0;
|
||||||
|
const onboard = state ? state.planes.filter((p) => p.status === 'flying' || slotsUsedFor(state, p.id) > 0) : [];
|
||||||
|
|
||||||
// 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
|
||||||
@@ -294,6 +309,96 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{/* ISS-021 (v0.20.0): moved here from the right pane — between Fleet and Time. */}
|
||||||
|
<section className="pane-section">
|
||||||
|
<h3 className="pane-heading">On board</h3>
|
||||||
|
{onboard.length === 0 ? (
|
||||||
|
<p className="pane-muted">Nothing on board.</p>
|
||||||
|
) : (
|
||||||
|
onboard.map((plane) => {
|
||||||
|
const cargo = state.packages.filter(
|
||||||
|
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
||||||
|
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
||||||
|
// child, so this covers the whole block without flicker between sub-elements.
|
||||||
|
<div
|
||||||
|
key={plane.id}
|
||||||
|
data-testid={`onboard-${plane.id}`}
|
||||||
|
className="onboard-block"
|
||||||
|
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
>
|
||||||
|
<div className="contract-main">
|
||||||
|
<span className="plane-model">{PLANE_TYPES[plane.model]?.name ?? plane.model}</span>
|
||||||
|
{plane.status === 'flying' ? (
|
||||||
|
<>
|
||||||
|
<span className="plane-status status-flying">in flight</span>
|
||||||
|
{plane.destName && (
|
||||||
|
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
||||||
|
{plane.locationName} → {plane.destName}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="plane-status status-available">{plane.locationIcao}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{cargo.map((pkg) => {
|
||||||
|
const penalty = abandonPenalty(pkg, clockMs);
|
||||||
|
return (
|
||||||
|
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`fly-to-${pkg.id}`}
|
||||||
|
className="pane-btn onboard-fly-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
||||||
|
>
|
||||||
|
<span className="onboard-fly-label" title={`Fly to ${pkg.destName}`}>
|
||||||
|
Fly to {pkg.destName}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<div className="onboard-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`refuel-for-${pkg.id}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/planes/${plane.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
||||||
|
>
|
||||||
|
Refuel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`abandon-${pkg.id}`}
|
||||||
|
className="pane-btn"
|
||||||
|
disabled={actionsBusy || plane.status !== 'available'}
|
||||||
|
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
||||||
|
>
|
||||||
|
Abandon{' '}
|
||||||
|
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="contract-sub">
|
||||||
|
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
||||||
|
<span>{formatCash(pkg.reward)}</span>
|
||||||
|
{pkg.status === 'expired' ? (
|
||||||
|
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
||||||
|
) : (
|
||||||
|
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
<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">
|
||||||
@@ -347,6 +452,8 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover, on
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{/* ISS-021 (v0.20.0): inline error from a failed On board action — mirrors right-error. */}
|
||||||
|
{actionError && <p data-testid="left-action-error" className="pane-error">{actionError}</p>}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
+6
-132
@@ -1,11 +1,11 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import type { GeoJsonFeatureCollection } from '@/lib/airports';
|
import type { GeoJsonFeatureCollection } from '@/lib/airports';
|
||||||
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
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 { formatCash, formatDeadlineRelative } from '@/lib/format';
|
import { formatCash, formatDeadlineRelative } from '@/lib/format';
|
||||||
|
import { useGameAction } from '@/lib/useGameAction';
|
||||||
import type { HoverTarget } from './hoverTypes';
|
import type { HoverTarget } from './hoverTypes';
|
||||||
|
|
||||||
interface RightPaneProps {
|
interface RightPaneProps {
|
||||||
@@ -109,13 +109,9 @@ function LoadControls({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function RightPane({ state, loading, applySnapshot, onHover, onError }: RightPaneProps) {
|
export default function RightPane({ state, loading, applySnapshot, onHover, onError }: RightPaneProps) {
|
||||||
const [busy, setBusy] = useState(false);
|
// ISS-021 (v0.20.0): shared action runner — busy gate, inline pane error + shell toast on
|
||||||
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
// failure, full post-action snapshot pushed into the shared state on success.
|
||||||
// snapshot prop changes every tick) or the next successful action.
|
const { runAction, busy, actionError } = useGameAction(state, applySnapshot, onError);
|
||||||
const [actionError, setActionError] = useState<string | null>(null);
|
|
||||||
useEffect(() => {
|
|
||||||
if (state !== null) setActionError(null);
|
|
||||||
}, [state]);
|
|
||||||
|
|
||||||
// Market picker selections — same "effective selection" pattern as LoadControls: the
|
// Market picker selections — same "effective selection" pattern as LoadControls: the
|
||||||
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
|
// user's pick while it stays valid, else a sensible default (first catalog entry / first plane).
|
||||||
@@ -149,36 +145,6 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
|||||||
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
|
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// POST an action endpoint. Every success returns the FULL post-action snapshot (v0.8.0
|
|
||||||
// convention) — pushed into the shared state immediately; a 4xx {error} body becomes the
|
|
||||||
// inline pane error and the stale UI stays until the next poll. Buttons are disabled while
|
|
||||||
// a request is in flight, so at most one action runs at a time.
|
|
||||||
const runAction = useCallback(
|
|
||||||
async (path: string, body?: unknown) => {
|
|
||||||
if (busy) return;
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
const res = await fetch(path, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
|
||||||
cache: 'no-store',
|
|
||||||
});
|
|
||||||
const data = (await res.json()) as StateSnapshot & { error?: string };
|
|
||||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
||||||
setActionError(null);
|
|
||||||
applySnapshot(data);
|
|
||||||
} catch (err) {
|
|
||||||
const message = err instanceof Error ? err.message : String(err);
|
|
||||||
setActionError(message); // inline pane error stays…
|
|
||||||
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[applySnapshot, busy, onError],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (loading && !state) {
|
if (loading && !state) {
|
||||||
return (
|
return (
|
||||||
<aside data-testid="right-pane" className="pane right-pane">
|
<aside data-testid="right-pane" className="pane right-pane">
|
||||||
@@ -192,13 +158,6 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
|||||||
const clockMs = state.simState.clockMs;
|
const clockMs = state.simState.clockMs;
|
||||||
const open = state.packages.filter((p) => p.status === 'open');
|
const open = state.packages.filter((p) => p.status === 'open');
|
||||||
|
|
||||||
// On board (v0.12.0): every plane that carries cargo or is mid-flight gets a block —
|
|
||||||
// its loaded/expired packages with fly-to-destination + abandon controls, and flying
|
|
||||||
// planes show their current leg.
|
|
||||||
const onboard = state.planes.filter(
|
|
||||||
(p) => p.status === 'flying' || slotsUsedFor(state, p.id) > 0,
|
|
||||||
);
|
|
||||||
|
|
||||||
const catalog = state.catalog;
|
const catalog = state.catalog;
|
||||||
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
||||||
|
|
||||||
@@ -270,92 +229,7 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="pane-section">
|
{/* ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time). */}
|
||||||
<h3 className="pane-heading">On board</h3>
|
|
||||||
{onboard.length === 0 ? (
|
|
||||||
<p className="pane-muted">Nothing on board.</p>
|
|
||||||
) : (
|
|
||||||
onboard.map((plane) => {
|
|
||||||
const cargo = state.packages.filter(
|
|
||||||
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
|
|
||||||
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
|
|
||||||
// child, so this covers the whole block without flicker between sub-elements.
|
|
||||||
<div
|
|
||||||
key={plane.id}
|
|
||||||
data-testid={`onboard-${plane.id}`}
|
|
||||||
className="onboard-block"
|
|
||||||
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
|
|
||||||
onMouseLeave={() => onHover(null)}
|
|
||||||
>
|
|
||||||
<div className="contract-main">
|
|
||||||
<span className="plane-model">{planeName(plane)}</span>
|
|
||||||
{plane.status === 'flying' ? (
|
|
||||||
<>
|
|
||||||
<span className="plane-status status-flying">in flight</span>
|
|
||||||
{plane.destName && (
|
|
||||||
<span data-testid={`plane-leg-${plane.id}`} className="contract-route">
|
|
||||||
{plane.locationName} → {plane.destName}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<span className="plane-status status-available">{plane.locationIcao}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{cargo.map((pkg) => {
|
|
||||||
const penalty = abandonPenalty(pkg, clockMs);
|
|
||||||
return (
|
|
||||||
<div key={pkg.id} data-testid={`onboard-package-${pkg.id}`} className="contract-row">
|
|
||||||
<div className="contract-main">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`refuel-for-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || plane.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/planes/${plane.id}/refuel`, { mode: 'forFlight', packageId: pkg.id })}
|
|
||||||
>
|
|
||||||
Refuel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`fly-to-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || plane.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/planes/${plane.id}/fly`, { destIcao: pkg.destIcao })}
|
|
||||||
>
|
|
||||||
Fly to {pkg.destName}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-testid={`abandon-${pkg.id}`}
|
|
||||||
className="pane-btn"
|
|
||||||
disabled={busy || plane.status !== 'available'}
|
|
||||||
onClick={() => void runAction(`/api/packages/${pkg.id}/abandon`)}
|
|
||||||
>
|
|
||||||
Abandon{' '}
|
|
||||||
<span data-testid={`abandon-penalty-${pkg.id}`}>−{formatCash(penalty)}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="contract-sub">
|
|
||||||
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
|
|
||||||
<span>{formatCash(pkg.reward)}</span>
|
|
||||||
{pkg.status === 'expired' ? (
|
|
||||||
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
|
|
||||||
) : (
|
|
||||||
<span>{formatDeadlineRelative(pkg.deadlineSimTime, clockMs)}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="pane-section">
|
<section className="pane-section">
|
||||||
<h3 className="pane-heading">Market</h3>
|
<h3 className="pane-heading">Market</h3>
|
||||||
|
|||||||
+16
-4
@@ -3,7 +3,8 @@ 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 1000× →
|
// via the right pane → click its destination in the on-board list (left pane since
|
||||||
|
// v0.20.0, ISS-021) → fly at 1000× →
|
||||||
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
|
// 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.
|
||||||
@@ -117,6 +118,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
}
|
}
|
||||||
if (plane.locationIcao !== HUB) {
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
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);
|
||||||
@@ -221,7 +225,9 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
|
|||||||
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
const refuelCost = Math.round((afterRefuel.maxFuel - landed.fuel) * FUEL_PRICE_PER_L * 100) / 100;
|
||||||
expect(s.account.cash).toBeCloseTo(before.account.cash + pkg.reward - refuelCost, 6);
|
expect(s.account.cash).toBeCloseTo(before.account.cash + pkg.reward - refuelCost, 6);
|
||||||
|
|
||||||
// Restore: fly home (repositioning — no package needed in the v0.12.0 model).
|
// Restore: fly home (repositioning — no package needed in the v0.12.0 model). ISS-011: the
|
||||||
|
// arrival above auto-slown the sim to 1×, so re-set SCALE for the return leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
const homeRes = await page.request.post(`/api/planes/${planeId}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
expect(homeRes.ok()).toBeTruthy();
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.locationIcao), { timeout: 120_000 }).toBe(HUB);
|
||||||
@@ -308,8 +314,10 @@ test('expired packages deliver and abandon with no reward and no penalty', async
|
|||||||
expect(s.packages.find((p) => p.id === pkgB.id)!.status).toBe('abandoned');
|
expect(s.packages.find((p) => p.id === pkgB.id)!.status).toBe('abandoned');
|
||||||
expect(s.account.cash).toBe(cashBeforeAbandon); // free — expired abandons cost nothing
|
expect(s.account.cash).toBe(cashBeforeAbandon); // free — expired abandons cost nothing
|
||||||
|
|
||||||
// Restore: refuel + fly home (scale is still SCALE from the expiry wait above).
|
// Restore: refuel + fly home. ISS-011: the LEMD arrival above auto-slown the sim to 1×, so
|
||||||
|
// re-set SCALE for the return leg (the expiry wait's scale no longer persists past a landing).
|
||||||
await page.request.post('/api/planes/plane-starter/refuel');
|
await page.request.post('/api/planes/plane-starter/refuel');
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(homeRes.ok()).toBeTruthy();
|
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);
|
||||||
@@ -347,7 +355,9 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
|
|||||||
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
|
||||||
expect(res.status()).toBe(409);
|
expect(res.status()).toBe(409);
|
||||||
|
|
||||||
// Fly home from the hop so the fuel section starts at the hub.
|
// Fly home from the hop so the fuel section starts at the hub. ISS-011: the hop arrival above
|
||||||
|
// auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
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);
|
||||||
@@ -370,6 +380,8 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ 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 fits: the weighted burn over it is less than what's left in the tank.
|
// The return leg fits: the weighted burn over it is less than what's left in the tank.
|
||||||
|
// ISS-011: the FAR arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
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.ok()).toBeTruthy();
|
expect(backRes.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);
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
// v0.19.0 — ISS-011: when the LAST plane lands (no plane remains in flight) the sim auto-slows
|
||||||
|
// to 1×, server-side and persisted on the sim_state row so the UI slider reflects it on the next
|
||||||
|
// snapshot. Arrival-triggered by design: a grounded fleet at high scale is left alone, there is no
|
||||||
|
// auto-restore — the player speeds up manually again (asserted below).
|
||||||
|
|
||||||
|
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||||
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
|
|
||||||
|
interface SimState {
|
||||||
|
clockMs: number;
|
||||||
|
timeScale: number;
|
||||||
|
paused: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
simState: SimState;
|
||||||
|
planes: Array<{ id: string; status: string; locationIcao: string; destIcao: string | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
return (await res.json()) as StateBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postSim(page: Page, body: Record<string, unknown>): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/sim', { data: body });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the time scale and VERIFY from the response that it stuck — if something external ever
|
||||||
|
// resets the live instance's controls mid-test, fail loudly here instead of timing out later.
|
||||||
|
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 SimState;
|
||||||
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closest airport to the hub from /api/airports → shortest possible leg (fastest e2e flight).
|
||||||
|
async function nearestToHub(page: Page): Promise<{ icao: string }> {
|
||||||
|
const res = await page.request.get('/api/airports');
|
||||||
|
expect(res.ok()).toBeTruthy();
|
||||||
|
const fc = (await res.json()) as { features: Array<{ properties: { icao: string; lat: number; lon: number } }> };
|
||||||
|
const hub = fc.features.find((f) => f.properties.icao === HUB)!.properties;
|
||||||
|
let nearest = fc.features.filter((f) => f.properties.icao !== HUB)[0].properties;
|
||||||
|
for (const f of fc.features) {
|
||||||
|
if (f.properties.icao === HUB) continue;
|
||||||
|
const d = Math.hypot(f.properties.lat - hub.lat, f.properties.lon - hub.lon);
|
||||||
|
const dn = Math.hypot(nearest.lat - hub.lat, nearest.lon - hub.lon);
|
||||||
|
if (d < dn) nearest = f.properties;
|
||||||
|
}
|
||||||
|
return { icao: nearest.icao };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal helper (same pattern as e2e/relocation.spec.ts): let any in-flight leg finish and
|
||||||
|
// reposition plane-starter home via the API so every test starts from the canonical state even
|
||||||
|
// after an interrupted previous run.
|
||||||
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
|
let s = await getState(page);
|
||||||
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
|
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
}
|
||||||
|
if (plane.status === 'flying') {
|
||||||
|
// Let the in-flight leg finish before repositioning. While flying, locationIcao stays at the
|
||||||
|
// DEPARTURE airport — re-read state after landing before deciding whether a repositioning
|
||||||
|
// flight is needed.
|
||||||
|
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) {
|
||||||
|
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal in CLEANUP (afterEach): the test deliberately leaves plane-starter at the far end, so
|
||||||
|
// fast-forward + reposition home here; then restore scale=1 / unpaused for later specs.
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
await flyHomeViaApi(page);
|
||||||
|
await postSim(page, { timeScale: 1, paused: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
|
test('auto-slow to 1× when the last plane lands; manual speed-up still works (ISS-011)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
||||||
|
await flyHomeViaApi(page); // deterministic: the starter sits grounded at EDDF
|
||||||
|
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
|
||||||
|
// Set 1000× via the API and verify it stuck.
|
||||||
|
await setScale(page, SCALE);
|
||||||
|
|
||||||
|
// Dispatch plane-starter on the shortest leg from its hub (repositioning — no package needed).
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: nearest.icao } });
|
||||||
|
expect(flyRes.status()).toBe(200);
|
||||||
|
|
||||||
|
// Wait for the landing…
|
||||||
|
let landedBody: StateBody | undefined;
|
||||||
|
await expect
|
||||||
|
.poll(async () => {
|
||||||
|
const b = await getState(page);
|
||||||
|
const p = b.planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
if (p.status === 'available' && p.locationIcao === nearest.icao) landedBody = b;
|
||||||
|
return !!landedBody;
|
||||||
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${nearest.icao}` })
|
||||||
|
.toBe(true);
|
||||||
|
|
||||||
|
// …and the server has auto-slown to 1× — persisted on sim_state, so this very snapshot shows it.
|
||||||
|
expect(landedBody!.simState.timeScale).toBe(1);
|
||||||
|
|
||||||
|
// Manual override still works: POST /api/sim {timeScale: 1000} → confirmed by the response…
|
||||||
|
const post = await page.request.post('/api/sim', { data: { timeScale: SCALE } });
|
||||||
|
expect(post.status()).toBe(200);
|
||||||
|
expect(((await post.json()) as SimState).timeScale).toBe(SCALE);
|
||||||
|
// …and by a fresh snapshot (no auto-restore of the previous scale — and no re-slow either,
|
||||||
|
// since nothing is in flight: the trigger is arrival-based, not idle-enforcement).
|
||||||
|
expect((await getState(page)).simState.timeScale).toBe(SCALE);
|
||||||
|
});
|
||||||
@@ -89,6 +89,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
}
|
}
|
||||||
if (starter.locationIcao !== HUB) {
|
if (starter.locationIcao !== HUB) {
|
||||||
|
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
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)
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect
|
await expect
|
||||||
@@ -291,6 +294,8 @@ test('hovering an on-board block of a flying plane highlights its route', async
|
|||||||
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
|
|
||||||
|
// ISS-011: the arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(home.status()).toBe(200);
|
expect(home.status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
|
|||||||
@@ -69,6 +69,12 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
|
|||||||
|
|
||||||
// Sim clock renders (UTC wall-clock of the game time).
|
// Sim clock renders (UTC wall-clock of the game time).
|
||||||
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
|
||||||
|
|
||||||
|
// ISS-021 (v0.20.0): the On board section moved to the left pane (between Fleet and Time) —
|
||||||
|
// its heading renders here…
|
||||||
|
await expect(page.getByTestId('left-pane').getByRole('heading', { name: 'On board', exact: true })).toBeVisible();
|
||||||
|
// …and no longer in the right pane.
|
||||||
|
await expect(page.getByTestId('right-pane').getByRole('heading', { name: 'On board', exact: true })).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
|
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
|
||||||
|
|||||||
@@ -72,6 +72,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
}
|
}
|
||||||
if (plane.locationIcao !== HUB) {
|
if (plane.locationIcao !== HUB) {
|
||||||
|
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
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);
|
||||||
|
|||||||
+11
-3
@@ -2,8 +2,9 @@ import type { Page } from '@playwright/test';
|
|||||||
import { expect, test } from '@playwright/test';
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
// v0.12.0 — right Jobs & Market pane against the live origin: open packages render with
|
// v0.12.0 — right Jobs & Market pane against the live origin: open packages render with
|
||||||
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list shows
|
// names/reward/deadline and Load (UI click) binds one to the starter; the on-board list
|
||||||
// loaded packages with fly-to-destination + abandon buttons (penalty preview from the same
|
// (moved to the left pane in v0.20.0, ISS-021) shows loaded packages with fly-to-destination +
|
||||||
|
// abandon buttons (penalty preview from the same
|
||||||
// formula as the server); flying planes show their current leg; market buy/sell/refuel previews
|
// formula as the server); flying planes show their current leg; market buy/sell/refuel previews
|
||||||
// match the catalog + economy constants exposed in /api/state. Packages are created via
|
// 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.
|
||||||
@@ -174,6 +175,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
.toBe(true);
|
.toBe(true);
|
||||||
}
|
}
|
||||||
if (starter.locationIcao !== HUB) {
|
if (starter.locationIcao !== HUB) {
|
||||||
|
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
|
||||||
|
// fast-forwards instead of taking real-time hours.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
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)
|
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect
|
await expect
|
||||||
@@ -284,6 +288,8 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
|
|||||||
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
|
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
// Restore: fly home so the live instance stays in its onboarding state for the next run.
|
// Restore: fly home so the live instance stays in its onboarding state for the next run.
|
||||||
|
// ISS-011: the arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(homeRes.status()).toBe(200);
|
expect(homeRes.status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
@@ -401,7 +407,9 @@ test('on-board row Refuel tops up just enough for the package leg; market button
|
|||||||
await expect(page.getByTestId('market-refuel')).toHaveText('Refuel to full');
|
await expect(page.getByTestId('market-refuel')).toHaveText('Refuel to full');
|
||||||
|
|
||||||
// Restore: fly home — pkg2's destination IS the hub, so it delivers on arrival. The tank holds
|
// Restore: fly home — pkg2's destination IS the hub, so it delivers on arrival. The tank holds
|
||||||
// exactly the leg requirement, so this also proves "just enough" is enough.
|
// exactly the leg requirement, so this also proves "just enough" is enough. ISS-011: the far-end
|
||||||
|
// arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
|
||||||
|
await setScale(page, SCALE);
|
||||||
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
expect((await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } })).status()).toBe(200);
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
||||||
|
|||||||
@@ -237,6 +237,80 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('auto-slow to 1× when the last plane lands (ISS-011)', () => {
|
||||||
|
const FROM = 'EDDF';
|
||||||
|
const TO = 'LEMD';
|
||||||
|
|
||||||
|
// Starter flying EDDF→LEMD with departureSimTime set so its arrival is EXACTLY T0 —
|
||||||
|
// any advancing tick past T0 finalizes it. timeScale is the value under test.
|
||||||
|
async function setupLanding(name: string, timeScale: number) {
|
||||||
|
const inst = await freshDb(name);
|
||||||
|
const fc = await loadAirportsGeoJson();
|
||||||
|
const from = fc.features.find((f) => f.properties.icao === FROM)!.properties;
|
||||||
|
const to = fc.features.find((f) => f.properties.icao === TO)!.properties;
|
||||||
|
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
|
const type = PLANE_TYPES.atr72;
|
||||||
|
|
||||||
|
await inst.db.update(schema.simState).set({ timeScale });
|
||||||
|
await inst.db.update(schema.planes)
|
||||||
|
.set({ status: 'flying', destIcao: TO, departureSimTime: T0 - travelMs(km, type.speedKmh), fuel: type.maxFuel })
|
||||||
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
|
return { inst, from, km, type };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('last plane lands → stored timeScale becomes 1', async () => {
|
||||||
|
const { inst } = await setupLanding('autoslow-last.db', 1000);
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||||
|
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.timeScale).toBe(1); // persisted on the sim_state row…
|
||||||
|
expect((await inst.db.select().from(schema.simState))[0].timeScale).toBe(1); // …and visible to the next snapshot
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available'); // landing itself unchanged
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a landing while another plane is still flying → no change', async () => {
|
||||||
|
const { inst, from, type } = await setupLanding('autoslow-other.db', 1000);
|
||||||
|
// A second plane on the same route departing at T0 — arrives far after this tick's clock.
|
||||||
|
await inst.db.insert(schema.planes).values({
|
||||||
|
id: 'p-b', model: 'atr72', status: 'flying', fuel: type.maxFuel, maxFuel: type.maxFuel,
|
||||||
|
locationIcao: FROM, destIcao: TO, lat: from.lat, lon: from.lon, departureSimTime: T0,
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 2_000);
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.timeScale).toBe(1000); // p-b still in flight — no auto-slow
|
||||||
|
const byId = new Map((await inst.db.select().from(schema.planes)).map((p) => [p.id, p.status]));
|
||||||
|
expect(byId.get('plane-starter')).toBe('available'); // the starter did land…
|
||||||
|
expect(byId.get('p-b')).toBe('flying'); // …but the fleet is not idle
|
||||||
|
});
|
||||||
|
|
||||||
|
it('already at 1× → stays 1', async () => {
|
||||||
|
const { inst } = await setupLanding('autoslow-one.db', 1);
|
||||||
|
vi.setSystemTime(T0 + 2_000); // one tick at scale 1 advances 2e3 game ms — past the T0 arrival
|
||||||
|
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.timeScale).toBe(1);
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('paused sim with all planes landed → no change', async () => {
|
||||||
|
const inst = await freshDb('autoslow-paused.db');
|
||||||
|
// The fleet is fully grounded (the seeded starter) — a paused tick must not touch the
|
||||||
|
// scale even though "no plane in flight" holds: the trigger requires a landing this tick.
|
||||||
|
await inst.db.update(schema.simState).set({ timeScale: 1000, paused: true });
|
||||||
|
|
||||||
|
vi.setSystemTime(T0 + 5_000);
|
||||||
|
const sim = await tickOnce(inst);
|
||||||
|
|
||||||
|
expect(sim.timeScale).toBe(1000); // no landing processed while paused → trigger never fires
|
||||||
|
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('spawnOpenPackages', () => {
|
describe('spawnOpenPackages', () => {
|
||||||
it('tops the market up to MARKET_TARGET_OPEN_PACKAGES using the shared seed builder', async () => {
|
it('tops the market up to MARKET_TARGET_OPEN_PACKAGES using the shared seed builder', async () => {
|
||||||
const inst = await freshDb('spawn.db');
|
const inst = await freshDb('spawn.db');
|
||||||
|
|||||||
+18
-2
@@ -71,17 +71,33 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
|||||||
const advanceMs = sim.paused ? 0 : Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale;
|
const advanceMs = sim.paused ? 0 : Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale;
|
||||||
const clockMs = Math.round(sim.clockMs + advanceMs);
|
const clockMs = Math.round(sim.clockMs + advanceMs);
|
||||||
|
|
||||||
|
let landedThisTick = 0;
|
||||||
if (advanceMs > 0) {
|
if (advanceMs > 0) {
|
||||||
await expirePackages(inst, clockMs);
|
await expirePackages(inst, clockMs);
|
||||||
await deliverPackages(inst, clockMs);
|
// ISS-011: remember the landings so the tick can auto-slow to 1× when this was
|
||||||
|
// the last plane in flight.
|
||||||
|
landedThisTick = await deliverPackages(inst, clockMs);
|
||||||
await spawnOpenPackages(inst, clockMs);
|
await spawnOpenPackages(inst, clockMs);
|
||||||
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
// AFTER delivery on purpose: a plane that just landed gets work spawned
|
||||||
// at its new location within the same tick.
|
// at its new location within the same tick.
|
||||||
await spawnCoveragePackages(inst, clockMs);
|
await spawnCoveragePackages(inst, clockMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sets: Partial<Pick<schema.SimStateRow, 'clockMs' | 'lastRealTickMs' | 'timeScale'>> = {
|
||||||
|
clockMs,
|
||||||
|
lastRealTickMs: nowMs,
|
||||||
|
};
|
||||||
|
// Auto-slow (ISS-011): when ≥1 plane landed this tick and NO plane remains in flight,
|
||||||
|
// drop the stored timeScale to 1× — persisted here so the UI slider reflects it on the
|
||||||
|
// next snapshot. Arrival-triggered by design: a grounded fleet at high scale is left
|
||||||
|
// alone (the player speeds up manually again; there is no auto-restore).
|
||||||
|
if (landedThisTick > 0 && !sim.paused) {
|
||||||
|
const flying = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'flying'));
|
||||||
|
if (flying.length === 0) sets.timeScale = MIN_TIME_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
||||||
await inst.db.update(schema.simState).set({ clockMs, lastRealTickMs: nowMs });
|
await inst.db.update(schema.simState).set(sets);
|
||||||
await persist(inst);
|
await persist(inst);
|
||||||
const updated = (await inst.db.select().from(schema.simState))[0];
|
const updated = (await inst.db.select().from(schema.simState))[0];
|
||||||
if (!updated) throw new Error('sim_state row missing after tick');
|
if (!updated) throw new Error('sim_state row missing after tick');
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import type { StateSnapshot } from '@/lib/game/state';
|
||||||
|
|
||||||
|
// ISS-021 (v0.20.0) — shared action runner for the side panes (extracted verbatim from
|
||||||
|
// RightPane.runAction when the On board section moved to LeftPane). POSTs an action endpoint;
|
||||||
|
// every success returns the FULL post-action snapshot (v0.8.0 convention), pushed into the
|
||||||
|
// shared shell state immediately via applySnapshot so the UI updates without waiting for the
|
||||||
|
// next poll tick. A non-2xx {error} body becomes the pane's inline error AND is mirrored to
|
||||||
|
// the shell as a bottom-right toast via onError (ISS-008 — both surfaces by design). Buttons
|
||||||
|
// are disabled while a request is in flight, so at most one action runs per pane at a time.
|
||||||
|
export function useGameAction(
|
||||||
|
state: StateSnapshot | null,
|
||||||
|
applySnapshot: (snapshot: StateSnapshot) => void,
|
||||||
|
onError?: (message: string) => void,
|
||||||
|
): { runAction: (path: string, body?: unknown) => Promise<void>; busy: boolean; actionError: string | null } {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
||||||
|
// snapshot prop changes every tick) or the next successful action.
|
||||||
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (state !== null) setActionError(null);
|
||||||
|
}, [state]);
|
||||||
|
|
||||||
|
const runAction = useCallback(
|
||||||
|
async (path: string, body?: unknown) => {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
const data = (await res.json()) as StateSnapshot & { error?: string };
|
||||||
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||||
|
setActionError(null);
|
||||||
|
applySnapshot(data);
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
setActionError(message); // inline pane error stays…
|
||||||
|
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[applySnapshot, busy, onError],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { runAction, busy, actionError };
|
||||||
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flight-ops",
|
"name": "flight-ops",
|
||||||
"version": "0.18.0",
|
"version": "0.20.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Reference in New Issue
Block a user