Compare commits

...
11 Commits
Author SHA1 Message Date
kamilkrzywda 6e1439391a Merge pull request 'v0.19.0 — ISS-011 auto-slow to 1× when all planes have landed' (#24) from feat/auto-slow-on-idle into master
CI / build + unit + e2e (push) Successful in 5m59s
2026-09-19 20:27:00 +02:00
kamilkrzywda 86379fc9c6 feat: v0.19.0 — ISS-011 auto-slow to 1x when all planes have landed
CI / build + unit + e2e (pull_request) Successful in 6m14s
2026-09-19 18:07:42 +00:00
kamilkrzywda f0602453ea Merge pull request 'v0.18.0 — ISS-010 relocate empty planes + bigger airport markers + popup options' (#20) from feat/plane-relocation into master
CI / build + unit + e2e (push) Successful in 6m4s
2026-09-19 18:44:56 +02:00
kamilkrzywda 337eda2743 test: target the plane option specifically in relocation popup e2e
CI / build + unit + e2e (pull_request) Successful in 7m32s
2026-09-19 16:35:19 +00:00
kamilkrzywda 8852ae11f2 test: fix POPUP_AIRPORT scoping in relocation popup e2e
CI / build + unit + e2e (pull_request) Failing after 6m49s
2026-09-19 16:23:03 +00:00
kamilkrzywda 008a77e456 feat: v0.18.0 part 3 — market row to relocate a grounded plane
CI / build + unit + e2e (pull_request) Failing after 6m17s
2026-09-19 16:03:03 +00:00
kamilkrzywda 3e62d63418 feat: v0.18.0 part 2 — airport popup relocate options 2026-09-19 15:57:33 +00:00
kamilkrzywda 09c1d8bcd8 feat: v0.18.0 part 1 — ISS-010 bigger airport markers 2026-09-19 15:57:23 +00:00
kamilkrzywda 0467b54c70 Merge pull request 'v0.17.0 — ISS-008 toasts for errors/events + browser notifications' (#19) from feat/toasts-and-notifications into master
CI / build + unit + e2e (push) Successful in 6m31s
2026-09-19 17:33:14 +02:00
kamilkrzywda 51d4f21d6b fix: v0.17.0 — sim-control POST retries + permission-aware notifications e2e
CI / build + unit + e2e (pull_request) Successful in 6m52s
2026-09-19 15:23:20 +00:00
kamilkrzywda d8dc785757 feat: v0.17.0 — ISS-008 toasts for errors/events + browser notifications
CI / build + unit + e2e (pull_request) Failing after 6m59s
2026-09-19 14:52:36 +00:00
21 changed files with 1326 additions and 41 deletions
+28
View File
@@ -1,5 +1,33 @@
# Changelog
## 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
- **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
- **Airport popup Relocate row** (`components/Map.tsx`): after the name/ICAO/local-time/weather lines, a `.popup-relocate` block with `[data-testid="airport-popup-plane"]` (grounded planes from the latest polled snapshot at click time) and `[data-testid="airport-popup-relocate"]` "Relocate here" — disabled until a plane is picked; on click it POSTs fly to the clicked airport, pushes the response snapshot through the shell's `applySnapshot` (new Map prop, same callback RightPane receives), and reports success/failure in `[data-testid="airport-popup-relocate-status"]`. With no grounded planes the row shows `[data-testid="airport-popup-no-planes"]` instead. Popups are plain HTML, not React — controls wired via `popup.getElement().querySelector(...)` after `.addTo(map)`
- **Bigger airport markers (ISS-010).** The r=3 dots were hard to click: `airports-circles` paint in `components/Map.tsx` goes from radius 3 / stroke 1 to radius 5 / stroke 1.5, and the hover highlight ring follows (r=8 → r=9). Paint-only — no data or interaction changes
- No server or OpenAPI changes — both surfaces reuse the existing fly endpoint (validations unchanged: 404 unknown plane / 409 flying or insufficient fuel / 400 unknown ICAO, strict unknown-field rejection kept)
- Tests: e2e — new `e2e/relocation.spec.ts` (serial mode, SCALE=1000, self-heal fly-home in afterEach like actions.spec.ts): market-row test ensures plane-starter grounded at the hub via API, picks it + the nearest non-hub airport (shortest leg) and asserts `/api/state` shows `flying` with that destIcao after clicking Relocate; popup test clicks the isolated LFRS marker (projected-center pattern from map.spec.ts), asserts the select lists "ATR 72-600 — EDDF" and the button is disabled until a plane is picked, then relocates via the popup. Marker-size regression gate = the existing map.spec.ts click tests keep passing
- Verified: `tsc --noEmit` clean; unit suite green locally (no lib/ changes — flyPlane's zero-package case already covered by actions.test.ts); e2e not run locally by design — CI verifies against an isolated stack
- **Fix (CI run #50): POPUP_AIRPORT scoping in the popup relocation e2e.** The LFRS marker click passed `POPUP_AIRPORT` into a `page.evaluate(() => …)` callback that runs in the BROWSER, where Node-scope constants don't exist — deterministic `ReferenceError: POPUP_AIRPORT is not defined` (relocation.spec.ts popup test, both attempts of run #50). The constant is now passed as an evaluate argument (`page.evaluate(({lon, lat}) => …, POPUP_AIRPORT)`); the other evaluate in the file only touches browser globals and needed no change. Test-only — no app code touched
- **Fix (CI run #51): strict-mode locator in the popup relocation e2e.** `expect(planeSel.locator('option')).toContainText(…)` resolved to BOTH options (placeholder + plane) → strict mode violation (relocation.spec.ts popup test, both attempts of run #51; the app rendered correctly). The assertion now targets `option[value="plane-starter"]` specifically with `toHaveText`. Test-only — no app code touched
## v0.17.0 — 2026-09-19 14:49
- **Bottom-right toasts for action errors (ISS-008).** Error messages like "insufficient funds: a ATR 72-600 costs 200000, you have 62721" now appear as toasts in the bottom-right corner — new `lib/useToasts.ts` hook (`useToasts() → {toasts, push(kind, msg), dismiss(id)}`, auto-dismiss after ~5 s, queue capped at 4 dropping the oldest; pure core `pushToast` unit-tested) and new `components/Toasts.tsx` `<ToastStack>` (fixed container `.toasts`, items `[data-testid="toast"]` with class `toast toast-error|toast-info` + a × dismiss button). Wired into BOTH error paths: `RightPane.runAction`'s catch now calls the shell's `onError` in addition to keeping the inline `[data-testid="right-error"]` pane error, and `LeftPane.applySimControls`'s catch (previously console.error-only) reports "Failed to update time controls (…)" through the same callback. The shell (`app/page.tsx`) owns the hook and renders the stack; CSS in `app/globals.css`
- **Event messages via snapshot diffing.** No server event feed exists, so new pure `lib/deriveEvents.ts` — `diffSnapshots(prev: StateSnapshot | null, next) → {kind:'info', message}[]` — derives human-readable events from the fields already in `/api/state`: plane landing (`flying→available`, "ATR 72-600 landed at Frankfurt"), package delivery (`loaded→delivered`, "Package delivered: +€X" with the reward), expiry (`open|loaded→expired`, "Package expired: A → B"), new packages (id only in next, "New package available: A → B") and planes bought/sold (plane id set changed, "Bought/Sold {model}"). The shell keeps a `prevRef` and diffs on every snapshot change, pushing each event as an info toast; the first snapshot after load emits nothing (no baseline — no page-load spam)
- **Browser notifications when the window is not focused.** Each derived event also fires `new Notification('Flight Ops', {body})` when `document.hidden && 'Notification' in window && Notification.permission === 'granted'`. The left-pane Time section gains an explicit opt-in button (`[data-testid="enable-notifications"]`) calling `Notification.requestPermission()`; its label reflects the result ("Enable notifications" → "Notifications enabled"/"Notifications blocked"), and it renders disabled with a tooltip title when the API is absent. SSR-safe: permission state starts null and is read in an effect after hydration
- No server or OpenAPI changes — diffing uses only existing snapshot fields (verified: planes by id/status/locationName, packages by id/status/reward/origin+dest names)
- Tests: unit — new `lib/deriveEvents.test.ts` suite pins every event format (landing, delivery with reward, expiry from open and loaded, new-package appearance, bought/sold, identical snapshots → [], first snapshot → [], non-events like takeoff/load ignored); `lib/useToasts.test.ts` covers the queue cap. e2e — new `e2e/toasts.spec.ts`: deterministic insufficient-funds path (select the most expensive model in `[data-testid="market-buy-model"]`, click Buy, expect a visible error toast matching /insufficient funds/ AND the inline `right-error` still showing; skips only if cash already covers the plane on a long-lived local instance) and the notifications opt-in (unsupported → disabled + title; otherwise fresh context shows "Enable notifications" and after clicking the label reflects the result — soft, since headless CI may deny permission)
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
- **Fix (CI runs #44/#47): sim-control POSTs are retried before surfacing the error.** A dropped `POST /api/sim` on the runner's flaky uplink left the UI optimistic while the server kept the old scale — panes.spec.ts:74 timed out with timeScale stuck at 1000 (run #47). `applySimControls` now retries each commit up to 3× total (~500 ms backoff) before surfacing the error toast; a newer intent arriving mid-retry supersedes the in-flight body instead of waiting out its retries (last-wins queueing kept), and the endpoint's set-semantics make re-sending an already-applied value idempotent. Pure retry core `retrySimPost` exported from LeftPane + unit-tested. Also run #47: toasts.spec.ts Part B is now permission-state-aware — headless Chromium reports `Notification.permission` as 'denied' (not 'default'), so the test branches on the actual state (denied → assert blocked label without clicking; granted → enabled label; default → prompt, click, accept either resulting label)
## 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)
+107
View File
@@ -68,6 +68,40 @@ body {
color: #cbd5e1;
}
/* ISS-010 (v0.18.0) — Relocate row inside the airport popup (plain HTML, not React). */
.popup-relocate {
margin-top: 8px;
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.popup-relocate select {
font-size: 12px;
padding: 3px 6px;
border-radius: 4px;
border: 1px solid rgba(148, 163, 184, 0.4);
}
.popup-relocate button {
font-size: 12px;
padding: 3px 10px;
border-radius: 4px;
border: 1px solid rgba(148, 163, 184, 0.4);
cursor: pointer;
}
.popup-relocate button:disabled {
opacity: 0.5;
cursor: default;
}
[data-testid='airport-popup-relocate-status'] {
font-size: 11px;
color: #334155;
}
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market */
.app-shell {
display: grid;
@@ -327,6 +361,12 @@ body {
padding: 4px 0;
}
/* 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. */
.market-row-relocate {
flex-wrap: wrap;
}
.market-preview {
font-size: 12px;
color: #f8fafc;
@@ -347,3 +387,70 @@ body {
padding: 6px 0 0;
border-top: 1px solid rgba(148, 163, 184, 0.2);
}
/* v0.17.0 — ISS-008: bottom-right toast stack (action errors + game events) */
.toasts {
position: fixed;
bottom: 12px;
right: 12px;
z-index: 50; /* above map popups/controls and the app header */
display: flex;
flex-direction: column;
gap: 8px;
max-width: 340px;
}
.toast {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 12px;
border-radius: 6px;
font-size: 13px;
background: rgba(15, 23, 42, 0.95);
color: #e2e8f0;
border: 1px solid rgba(148, 163, 184, 0.4);
}
.toast-error {
border-color: rgba(239, 68, 68, 0.7);
color: #fecaca;
}
.toast-info {
border-color: rgba(148, 163, 184, 0.5);
}
.toast-close {
flex-shrink: 0;
font-size: 14px;
line-height: 1;
padding: 2px 6px;
border-radius: 4px;
border: none;
background: transparent;
color: #94a3b8;
cursor: pointer;
}
.toast-close:hover {
color: #e2e8f0;
}
/* ISS-008 — the Time section's notifications opt-in button (same look as .time-controls buttons) */
.notif-toggle {
margin-top: 8px;
font-size: 12px;
padding: 4px 10px;
border-radius: 4px;
border: 1px solid rgba(148, 163, 184, 0.4);
background: rgba(30, 41, 59, 0.9);
color: #e2e8f0;
cursor: pointer;
}
.notif-toggle:disabled {
opacity: 0.5;
cursor: default;
}
+30 -5
View File
@@ -1,11 +1,14 @@
'use client';
import dynamic from 'next/dynamic';
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import LeftPane from '@/components/LeftPane';
import RightPane from '@/components/RightPane';
import ToastStack from '@/components/Toasts';
import type { HoverTarget } from '@/components/hoverTypes';
import { useGameState } from '@/lib/useGameState';
import { useToasts } from '@/lib/useToasts';
import { diffSnapshots } from '@/lib/deriveEvents';
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
@@ -19,12 +22,34 @@ export default function Home() {
// either pane highlights the matching plane/route/airports on the map.
const [hovered, setHovered] = useState<HoverTarget | null>(null);
// ISS-008 (v0.17.0): bottom-right toasts — action errors from both panes plus game events
// derived by diffing consecutive snapshots (no server event feed exists).
const { toasts, push, dismiss } = useToasts();
const onError = (message: string) => push('error', message);
// Diff each new snapshot against the previous one → info toasts. When the window is hidden
// and notifications are granted, mirror them as browser notifications too.
const prevSnapshotRef = useRef<typeof state>(null);
useEffect(() => {
if (state === null) return;
for (const event of diffSnapshots(prevSnapshotRef.current, state)) {
push('info', event.message);
if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
new Notification('Flight Ops', { body: event.message });
}
}
prevSnapshotRef.current = state;
}, [state, push]);
return (
<div className="app-shell">
<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 */}
<Map state={state} hovered={hovered} />
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} />
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} onError={onError} />
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
action response into the shared state, exactly like RightPane does */}
<Map state={state} hovered={hovered} applySnapshot={applySnapshot} />
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
<ToastStack toasts={toasts} onDismiss={dismiss} />
</div>
);
}
+105 -18
View File
@@ -16,6 +16,8 @@ interface LeftPaneProps {
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;
// ISS-008 (v0.17.0): report a failed sim-control POST to the shell as an error toast.
onError?: (message: string) => void;
}
// Discrete ladder slider (v0.9.2, values reworked in v0.14.0): position t ∈ [0,1] → nearest
@@ -46,16 +48,52 @@ export function pendingScaleConfirmed(pendingScale: number | null, serverTimeSca
return pendingScale !== null && serverTimeScale === pendingScale;
}
export default function LeftPane({ state, loading, error, onRefresh, onHover }: LeftPaneProps) {
// ISS-008 fix (v0.17.0, CI runs #44/#47): bounded retry for POST /api/sim — a commit dropped by
// the runner's flaky uplink used to leave the UI optimistic while the server kept the old scale.
// Up to maxAttempts tries with delayMs between them; stops early once superseded() flips (a newer
// intent arrived and the caller's loop sends it instead). post is idempotent set-semantics, so
// re-sending a body whose response was lost cannot double-apply. Pure core — unit-tested in node.
export const SIM_POST_MAX_ATTEMPTS = 3;
export const SIM_POST_RETRY_DELAY_MS = 500;
export type SimPostRetryResult =
| { ok: true }
| { ok: false; reason: 'exhausted'; error: unknown }
| { ok: false; reason: 'superseded' };
export async function retrySimPost(
post: () => Promise<void>,
superseded: () => boolean,
sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
maxAttempts: number = SIM_POST_MAX_ATTEMPTS,
delayMs: number = SIM_POST_RETRY_DELAY_MS,
): Promise<SimPostRetryResult> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
if (superseded()) return { ok: false, reason: 'superseded' }; // a newer intent takes over — don't even send this body
try {
await post();
return { ok: true };
} catch (err) {
lastError = err;
if (superseded()) return { ok: false, reason: 'superseded' }; // a newer intent arrived during the attempt — don't wait out the backoff
if (attempt < maxAttempts) await sleep(delayMs);
}
}
return { ok: false, reason: 'exhausted', error: lastError };
}
export default function LeftPane({ state, loading, error, onRefresh, onHover, onError }: LeftPaneProps) {
const [busy, setBusy] = useState(false);
// 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
// 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
// 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
// let a flush re-queue instead of send and silently drop a commit.
// POST /api/sim (retried up to SIM_POST_MAX_ATTEMPTS× on failure — CI runs #44/#47), then
// refetch the full snapshot immediately so the pane reflects the new controls without waiting
// for the next poll tick. After the final attempt fails keep the stale UI and surface an error
// toast (the running poll retries on its own). A commit that lands while another POST is in
// flight — including mid-retry — is held in a single slot (last intent wins) and supersedes
// the in-flight body, 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 let a flush re-queue instead of send and silently drop a commit.
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
const busyRef = useRef(false);
@@ -76,20 +114,32 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
try {
let current: { timeScale?: number; paused?: boolean } | null = body;
while (current !== null) {
const res = await fetch('/api/sim', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(current),
cache: 'no-store',
});
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
onRefresh();
if (current === body) sentOwn = true; // object identity — queued bodies are fresh literals
const target = current; // stable across this retry round
const result = await retrySimPost(
async () => {
const res = await fetch('/api/sim', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(target),
cache: 'no-store',
});
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
},
() => queuedRef.current !== null, // a newer intent supersedes the in-flight body mid-retry
);
if (result.ok) {
onRefresh();
if (target === body) sentOwn = true; // object identity — queued bodies are fresh literals
} else if (result.reason === 'exhausted') {
throw result.error; // only after the final attempt fails → error toast below
}
current = queuedRef.current; // pick up anything that arrived while we were in flight
queuedRef.current = null;
}
} catch (err) {
console.error('failed to apply sim controls', err);
// ISS-008: surface the failure as an error toast too — previously console-only.
onError?.(`Failed to update time controls (${err instanceof Error ? err.message : String(err)})`);
queuedRef.current = null; // don't replay a stale intent after a failed round-trip
} finally {
busyRef.current = false;
@@ -97,7 +147,7 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
}
return sentOwn ? 'sent' : 'failed';
},
[onRefresh],
[onRefresh, onError],
);
const paused = state?.simState.paused ?? false;
@@ -166,6 +216,25 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
[],
);
// ISS-008: browser-notification opt-in. Starts null (SSR-safe — the real permission is read
// in an effect after hydration, so server and client render identically) and follows the
// result of Notification.requestPermission(). 'unsupported' = no Notification API at all.
const [notifPermission, setNotifPermission] = useState<string | null>(null);
useEffect(() => {
if ('Notification' in window) setNotifPermission(Notification.permission);
else setNotifPermission('unsupported');
}, []);
// null (pre-effect) and 'default' both read as the opt-in prompt.
const notifLabel: string =
notifPermission === 'granted'
? 'Notifications enabled'
: notifPermission === 'denied'
? 'Notifications blocked'
: notifPermission === 'unsupported'
? 'Notifications unavailable'
: 'Enable notifications';
const displayedScale = pendingScale ?? timeScale;
// ISS-007: the clock ticks client-side between polls, re-syncing to server truth on every
@@ -253,6 +322,24 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
/>
<span data-testid="time-scale-value">{displayedScale}×</span>
</div>
{/* ISS-008: explicit opt-in for browser notifications (fired when the window is hidden). */}
<button
type="button"
data-testid="enable-notifications"
className="notif-toggle"
disabled={notifPermission === 'unsupported'}
title={notifPermission === 'unsupported' ? 'This browser does not support notifications' : undefined}
onClick={() => {
// A rejection (rare — e.g. some headless setups) reads as "blocked".
if ('Notification' in window) {
void Notification.requestPermission()
.then(setNotifPermission)
.catch(() => setNotifPermission('denied'));
}
}}
>
{notifLabel}
</button>
</section>
{error && (
+65 -5
View File
@@ -45,11 +45,14 @@ interface MapProps {
// 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;
// ISS-010 (v0.18.0): push an action endpoint's full response snapshot into the shared
// shell state — same callback RightPane receives, used by the airport popup's Relocate row.
applySnapshot: (snapshot: StateSnapshot) => void;
}
// 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.
export default function FlightMap({ state, hovered }: MapProps) {
export default function FlightMap({ state, hovered, applySnapshot }: MapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<maplibregl.Map | null>(null);
// /api/airports is fetched at most once per page life: every styledata event
@@ -58,6 +61,12 @@ export default function FlightMap({ state, hovered }: MapProps) {
// Latest snapshot + airport coordinate index, so the mount effect's styledata wiring
// and the state-change effect can both push data without prop-drilling into closures.
const stateRef = useRef<StateSnapshot | null>(null);
// ISS-010 (v0.18.0): the shell's applySnapshot is stable (useCallback with no deps), but the
// mount effect captures it once — keep a ref so the popup wiring always calls the latest one.
const applySnapshotRef = useRef(applySnapshot);
useEffect(() => {
applySnapshotRef.current = applySnapshot;
}, [applySnapshot]);
const airportsIndexRef = useRef<Map<string, AirportCoord> | null>(null);
const [airportCount, setAirportCount] = useState<number | null>(null);
const [styleId, setStyleId] = useState<string>(DEFAULT_STYLE_ID);
@@ -156,16 +165,67 @@ export default function FlightMap({ state, hovered }: MapProps) {
// deterministic generated weather — no gameplay effects per PLAN.md.
const w = weatherFor(p.icao);
const localTime = approxLocalTime(p.lon, Date.now());
new maplibregl.Popup({ offset: 10 })
// ISS-010 (v0.18.0): Relocate row — grounded planes from the latest snapshot can be
// repositioned to this airport via POST /api/planes/{id}/fly (pure repositioning).
const st = stateRef.current;
const groundedPlanes = st ? st.planes.filter((pl) => pl.status === 'available') : [];
const planeLabel = (model: string) => st?.catalog.find((c) => c.model === model)?.label ?? model;
const relocateHtml =
groundedPlanes.length > 0
? `<select data-testid="airport-popup-plane" aria-label="Plane to relocate here">` +
`<option value="">Select a plane\u2026</option>` +
groundedPlanes.map(
(pl) =>
`<option value="${escapeHtml(pl.id)}">${escapeHtml(planeLabel(pl.model))} \u2014 ${escapeHtml(pl.locationIcao)}</option>`,
).join('') +
`</select><button type="button" data-testid="airport-popup-relocate" disabled>Relocate here</button>`
: `<span data-testid="airport-popup-no-planes">No grounded planes to relocate.</span>`;
const popup = new maplibregl.Popup({ offset: 10 })
.setLngLat(f.geometry.coordinates as [number, number])
.setHTML(
`<div data-testid="airport-popup">` +
`<strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}<br/>` +
`<span data-testid="airport-local-time">${localTime} local (approx)</span><br/>` +
`<span data-testid="airport-weather">${w.condition}, wind ${w.windDirDeg}\u00B0 / ${w.windKt} kt, vis ${w.visibilityM} m</span>` +
`<div class="popup-relocate">` + relocateHtml + `<span data-testid="airport-popup-relocate-status"></span></div>` +
`</div>`,
)
.addTo(map);
// Popups are plain HTML, not React — the element only exists after addTo, so wire the
// controls via querySelector (the select enables the button once a plane is picked).
const el = popup.getElement();
const select = el?.querySelector<HTMLSelectElement>('[data-testid="airport-popup-plane"]');
const button = el?.querySelector<HTMLButtonElement>('[data-testid="airport-popup-relocate"]');
// The status span is always in the popup HTML (even with no grounded planes), so it
// exists whenever the select/button do.
const statusEl = el?.querySelector<HTMLElement>('[data-testid="airport-popup-relocate-status"]');
if (select && button && statusEl) {
select.addEventListener('change', () => {
button.disabled = select.value === '';
});
button.addEventListener('click', async () => {
const planeId = select.value;
if (!planeId || button.disabled) return;
button.disabled = true;
statusEl.textContent = 'Relocating\u2026';
try {
const res = await fetch(`/api/planes/${planeId}/fly`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ destIcao: p.icao }),
cache: 'no-store',
});
const data = (await res.json()) as StateSnapshot & { error?: string };
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
applySnapshotRef.current(data); // shared shell state updates immediately, like the panes' runAction
statusEl.textContent = 'Relocation started.';
} catch (err) {
statusEl.textContent = err instanceof Error ? err.message : String(err);
button.disabled = false; // allow retry / picking another plane
}
});
}
};
const onPlaneClick = (e: maplibregl.MapLayerMouseEvent) => {
@@ -224,9 +284,9 @@ export default function FlightMap({ state, hovered }: MapProps) {
type: 'circle',
source: AIRPORTS_SOURCE_ID,
paint: {
'circle-radius': 3,
'circle-radius': 5, // ISS-010 (v0.18.0): bigger — the r=3 dots were hard to click
'circle-color': '#e11d48',
'circle-stroke-width': 1,
'circle-stroke-width': 1.5,
'circle-stroke-color': '#ffffff',
},
});
@@ -317,7 +377,7 @@ export default function FlightMap({ state, hovered }: MapProps) {
source: AIRPORTS_SOURCE_ID,
filter: ['any', ['==', ['get', 'icao'], ''], ['==', ['get', 'icao'], '']],
paint: {
'circle-radius': 8, // ring around the base airport circles (r=3)
'circle-radius': 9, // ring around the base airport circles (r=5)
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
'circle-stroke-width': 2.5,
'circle-stroke-color': '#facc15',
+83 -4
View File
@@ -1,6 +1,7 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import type { GeoJsonFeatureCollection } from '@/lib/airports';
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { abandonPenalty } from '@/lib/game/penalty';
@@ -16,6 +17,9 @@ interface RightPaneProps {
// 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;
// ISS-008 (v0.17.0): report a failed action to the shell as an error toast — in ADDITION
// to the inline pane error, which stays (both surfaces by design).
onError?: (message: string) => void;
}
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
@@ -104,7 +108,7 @@ function LoadControls({
);
}
export default function RightPane({ state, loading, applySnapshot, onHover }: RightPaneProps) {
export default function RightPane({ state, loading, applySnapshot, onHover, onError }: RightPaneProps) {
const [busy, setBusy] = useState(false);
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
// snapshot prop changes every tick) or the next successful action.
@@ -119,6 +123,32 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
const [sellPlaneId, setSellPlaneId] = useState<string | null>(null);
const [refuelPlaneId, setRefuelPlaneId] = useState<string | null>(null);
// ISS-010 (v0.18.0): Relocate row selections — same "effective selection" pattern as the rows above:
// the user's pick while it stays valid, else a sensible default (first grounded plane / first airport).
const [relocatePlaneId, setRelocatePlaneId] = useState<string | null>(null);
const [relocateDestIcao, setRelocateDestIcao] = useState<string | null>(null);
// ISS-010 (v0.18.0): one-time /api/airports fetch per page life — destination options for the
// Relocate row, sorted by name so e2e selection is stable. Same promise-ref pattern as Map.tsx;
// on failure airportOptions stays null and the Relocate button simply remains disabled.
const [airportOptions, setAirportOptions] = useState<Array<{ name: string; icao: string }> | null>(null);
const airportsPromiseRef = useRef<Promise<Array<{ name: string; icao: string }>> | null>(null);
useEffect(() => {
if (!airportsPromiseRef.current) {
airportsPromiseRef.current = fetch('/api/airports', { cache: 'no-store' })
.then((res) => {
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
return res.json() as Promise<GeoJsonFeatureCollection>;
})
.then((fc) =>
fc.features
.map((f) => ({ name: f.properties.name, icao: f.properties.icao }))
.sort((a, b) => a.name.localeCompare(b.name, 'en')),
);
}
void airportsPromiseRef.current.then(setAirportOptions).catch(() => {});
}, []);
// POST an action endpoint. Every success returns the FULL post-action snapshot (v0.8.0
// convention) — pushed into the shared state immediately; a 4xx {error} body becomes the
// inline pane error and the stale UI stays until the next poll. Buttons are disabled while
@@ -139,12 +169,14 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
setActionError(null);
applySnapshot(data);
} catch (err) {
setActionError(err instanceof Error ? err.message : String(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],
[applySnapshot, busy, onError],
);
if (loading && !state) {
@@ -177,6 +209,11 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
state.planes.find((p) => p.id === refuelPlaneId && p.status === 'available' && p.fuel < p.maxFuel) ??
refuelable[0] ??
null;
// ISS-010 (v0.18.0): Relocate — any GROUNDED plane can be repositioned to any airport via the
// existing fly endpoint (pure repositioning, no package needed since v0.12.0).
const relocatePlane = grounded.find((p) => p.id === relocatePlaneId) ?? grounded[0] ?? null;
const relocateDest =
airportOptions === null ? null : airportOptions.find((a) => a.icao === relocateDestIcao) ?? airportOptions[0] ?? null;
// Previews computed client-side from the snapshot's catalog + economy constants (v0.10.0).
const sellEntry = sellPlane ? catalog.find((e) => e.model === sellPlane.model) : undefined;
@@ -417,6 +454,48 @@ export default function RightPane({ state, loading, applySnapshot, onHover }: Ri
Refuel to full
</button>
</div>
{/* ISS-010 (v0.18.0): relocate a grounded plane — the fly endpoint already allows pure
repositioning, this row just exposes it for planes with nothing on board. */}
<div className="market-row market-row-relocate">
<select
data-testid="relocate-plane"
aria-label="Plane to relocate"
value={relocatePlane?.id ?? ''}
onChange={(e) => setRelocatePlaneId(e.target.value || null)}
>
{grounded.map((p) => (
<option key={p.id} value={p.id}>
{planeName(p)} — {p.locationIcao}
</option>
))}
</select>
<select
data-testid="relocate-dest"
aria-label="Relocation destination airport"
value={relocateDest?.icao ?? ''}
onChange={(e) => setRelocateDestIcao(e.target.value || null)}
>
{airportOptions?.map((a) => (
<option key={a.icao} value={a.icao}>
{a.name}
</option>
))}
</select>
<button
type="button"
data-testid="relocate-go"
className="pane-btn"
disabled={busy || relocatePlane === null || relocateDest === null}
onClick={() => {
if (relocatePlane && relocateDest) {
void runAction(`/api/planes/${relocatePlane.id}/fly`, { destIcao: relocateDest.icao });
}
}}
>
Relocate
</button>
</div>
</section>
{actionError && <p data-testid="right-error" className="pane-error">{actionError}</p>}
+24
View File
@@ -0,0 +1,24 @@
'use client';
import type { Toast } from '@/lib/useToasts';
// ISS-008 (v0.17.0): the bottom-right toast stack — action errors and game events derived
// from snapshot diffs. Fixed-position overlay above the map; each item auto-dismisses via
// the hook's TTL or its × button.
export default function ToastStack({ toasts, onDismiss }: { toasts: Toast[]; onDismiss?: (id: number) => void }) {
if (toasts.length === 0) return null;
return (
<div className="toasts" role="status">
{toasts.map((t) => (
<div key={t.id} data-testid="toast" className={`toast toast-${t.kind}`}>
<span>{t.message}</span>
{onDismiss && (
<button type="button" data-testid={`toast-dismiss-${t.id}`} className="toast-close" onClick={() => onDismiss(t.id)}>
×
</button>
)}
</div>
))}
</div>
);
}
+69 -2
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { pendingScaleConfirmed } from './LeftPane';
import { describe, expect, it, vi } from 'vitest';
import { pendingScaleConfirmed, retrySimPost, SIM_POST_MAX_ATTEMPTS, SIM_POST_RETRY_DELAY_MS } from './LeftPane';
// ISS-001 — the optimistic slider value is cleared exactly when a rendered snapshot confirms
// it (server scale === pending), never earlier. Clearing at commit time would snap the pointer
@@ -22,3 +22,70 @@ describe('pendingScaleConfirmed', () => {
expect(pendingScaleConfirmed(1, 1)).toBe(true); // committing the current value confirms immediately
});
});
// ISS-008 fix (CI runs #44/#47): a dropped POST /api/sim must be retried before surfacing the
// error — up to SIM_POST_MAX_ATTEMPTS tries with SIM_POST_RETRY_DELAY_MS between them, and a newer
// intent supersedes the in-flight body instead of waiting out its retries.
describe('retrySimPost', () => {
it('pins the retry budget: 3 attempts total, ~500 ms backoff', () => {
expect(SIM_POST_MAX_ATTEMPTS).toBe(3);
expect(SIM_POST_RETRY_DELAY_MS).toBe(500);
});
it('succeeds on the first attempt without sleeping or retrying', async () => {
const post = vi.fn(async () => {});
const sleep = vi.fn(async () => {});
await expect(retrySimPost(post, () => false, sleep)).resolves.toEqual({ ok: true });
expect(post).toHaveBeenCalledTimes(1);
expect(sleep).not.toHaveBeenCalled();
});
it('retries with the backoff delay and succeeds on a later attempt', async () => {
let calls = 0;
const post = vi.fn(async () => {
if (++calls < 3) throw new Error('dropped');
});
const sleep = vi.fn(async () => {});
await expect(retrySimPost(post, () => false, sleep)).resolves.toEqual({ ok: true });
expect(post).toHaveBeenCalledTimes(3);
expect(sleep).toHaveBeenCalledTimes(2); // one backoff between each pair of attempts
expect(sleep).toHaveBeenCalledWith(SIM_POST_RETRY_DELAY_MS);
});
it('gives up after the final attempt with the last error (no trailing sleep)', async () => {
const err = new Error('down');
const post = vi.fn(async () => {
throw err;
});
const sleep = vi.fn(async () => {});
const result = await retrySimPost(post, () => false, sleep);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.reason).toBe('exhausted');
if (result.reason === 'exhausted') expect(result.error).toBe(err); // the LAST attempt's error
}
expect(post).toHaveBeenCalledTimes(SIM_POST_MAX_ATTEMPTS);
expect(sleep).toHaveBeenCalledTimes(SIM_POST_MAX_ATTEMPTS - 1);
});
it('stops retrying once a newer intent supersedes the in-flight body (no further attempts or sleeps)', async () => {
let calls = 0;
const post = vi.fn(async () => {
calls++; // flip "superseded" right after the first failure, like a queued commitNow would
throw new Error('dropped');
});
const sleep = vi.fn(async () => {});
await expect(retrySimPost(post, () => calls >= 1, sleep)).resolves.toEqual({ ok: false, reason: 'superseded' });
expect(post).toHaveBeenCalledTimes(1); // the caller's loop sends the newer body instead
expect(sleep).not.toHaveBeenCalled(); // supersede is checked before the backoff sleep
});
it('never even sends a body that is already superseded', async () => {
const post = vi.fn(async () => {});
const sleep = vi.fn(async () => {});
await expect(retrySimPost(post, () => true, sleep)).resolves.toEqual({ ok: false, reason: 'superseded' });
expect(post).not.toHaveBeenCalled();
expect(sleep).not.toHaveBeenCalled();
});
});
+14 -3
View File
@@ -117,6 +117,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
plane = s.planes.find((p) => p.id === 'plane-starter')!;
}
if (plane.locationIcao !== HUB) {
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
// 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);
@@ -221,7 +224,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;
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 } });
expect(homeRes.ok()).toBeTruthy();
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.locationIcao), { timeout: 120_000 }).toBe(HUB);
@@ -308,8 +313,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.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 setScale(page, SCALE);
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);
@@ -347,7 +354,9 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
res = await page.request.post(`/api/packages/${pkg.id}/abandon`);
expect(res.status()).toBe(409);
// Fly home from the hop so the fuel section starts at the hub.
// 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 } });
expect(res.ok()).toBeTruthy();
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 120_000 }).toBe(HUB);
@@ -370,6 +379,8 @@ test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
const atFar = sFar.planes.find((p) => p.id === 'plane-starter')!;
expect(atFar.locationIcao).toBe(FAR);
// The return leg fits: the weighted burn over it is less than what's left in the tank.
// ISS-011: the FAR arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
await setScale(page, SCALE);
const backRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
expect(backRes.ok()).toBeTruthy();
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
+130
View File
@@ -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);
});
+5
View File
@@ -89,6 +89,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
.toBe(true);
}
if (starter.locationIcao !== HUB) {
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
// 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 } });
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
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}` })
.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 } });
expect(home.status()).toBe(200);
await expect
+189
View File
@@ -0,0 +1,189 @@
import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
// v0.18.0 — ISS-010: relocating a GROUNDED (empty) plane to any airport against the live origin.
// Two UI surfaces drive the EXISTING POST /api/planes/{id}/fly endpoint (pure repositioning has
// been allowed since v0.12.0 — no API change): the right-pane market row
// (relocate-plane / relocate-dest / relocate-go) and the Relocate row inside the airport popup on
// the map (airport-popup-plane / airport-popup-relocate). Marker-size regression is covered by
// the existing e2e/map.spec.ts click tests, not here.
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps cleanup flights to seconds of real time
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
// LFRS Nantes Atlantique — same isolated marker as e2e/map.spec.ts: its nearest neighbour is ~78 px
// away at the initial zoom, so a click on its projected center cannot hit another circle.
const POPUP_AIRPORT = { icao: 'LFRS', lon: -1.61073, lat: 47.153198 };
interface StateBody {
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.ok()).toBeTruthy();
}
// 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 { timeScale: number };
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
}
// Closest airport to the hub from /api/airports → shortest possible leg (fuel trivial).
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/actions.spec.ts): let any in-flight leg finish and
// reposition plane-starter home via the API — repositioning needs no package (v0.12.0 manual
// flight) — 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') {
// 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 tests deliberately leave plane-starter mid-flight, 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('market row relocates a grounded plane via the right pane', async ({ page }) => {
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
await flyHomeViaApi(page);
// Full tank before departure — a partially drained plane left by an earlier spec could not
// afford the cleanup round trip.
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
expect(refuel.ok()).toBeTruthy();
const nearest = await nearestToHub(page);
await page.goto('/');
const planeSel = page.getByTestId('relocate-plane');
await expect(planeSel).toBeVisible({ timeout: 15_000 }); // pane renders once the first snapshot lands
await planeSel.selectOption('plane-starter');
// Destination options come from the one-time /api/airports fetch (sorted by name) — selectOption
// waits until the matching option exists, so this doubles as the load wait.
const destSel = page.getByTestId('relocate-dest');
await destSel.selectOption(nearest.icao);
const goBtn = page.getByTestId('relocate-go');
await expect(goBtn).toBeEnabled();
await goBtn.click();
// The click fires the fly POST asynchronously (runAction is fire-and-forget from the test's view),
// so poll until it took effect on the server.
await expect.poll(async () => {
const b = await getState(page);
const p = b.planes.find((x) => x.id === 'plane-starter')!;
return p.status === 'flying' && p.destIcao === nearest.icao;
}, { timeout: 15_000, message: 'waiting for the relocate click to take effect (status "flying" + dest set)' }).toBe(true);
});
test('airport popup offers Relocate options for grounded planes', async ({ page }) => {
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one leg to LFRS
await flyHomeViaApi(page);
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
expect(refuel.ok()).toBeTruthy();
await page.goto('/');
// Wait until the airport count renders (airports loaded) and the map has a snapshot containing
// the plane — the popup's Relocate row is built from that same latest snapshot.
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;
}, { timeout: 15_000 }).toBeGreaterThan(0);
await expect.poll(async () =>
page.evaluate(() => {
const m = (window as any).__flightMap;
if (!m || !m.getSource('planes')) return false;
try {
return m.querySourceFeatures('planes').some((f: { properties?: Record<string, unknown> }) => f.properties?.id === 'plane-starter');
} catch {
return false; // source not ready yet — keep polling
}
}),
{ timeout: 15_000 },
).toBe(true);
// Click the LFRS marker (projected center — same pattern as e2e/map.spec.ts). The constant is
// passed AS AN ARGUMENT: the evaluate callback runs in the browser, where Node-scope values don't exist.
const pt = await page.evaluate(({ lon, lat }) => {
const map = (window as any).__flightMap;
const p = map.project([lon, lat]);
const rect = map.getContainer().getBoundingClientRect();
return { x: rect.left + p.x, y: rect.top + p.y };
}, POPUP_AIRPORT);
await page.mouse.click(pt.x, pt.y);
const popup = page.getByTestId('airport-popup');
await expect(popup).toBeVisible();
await expect(popup).toContainText(POPUP_AIRPORT.icao);
// The Relocate row: a select of grounded planes + the button (disabled until one is picked).
const planeSel = page.getByTestId('airport-popup-plane');
await expect(planeSel).toBeVisible();
// Target THE PLANE OPTION specifically — locator('option') also matches the placeholder and
// trips strict mode (CI run #51).
await expect(planeSel.locator('option[value="plane-starter"]')).toHaveText(/ATR 72-600 — EDDF/);
const goBtn = page.getByTestId('airport-popup-relocate');
await expect(goBtn).toBeDisabled(); // placeholder selected
await planeSel.selectOption('plane-starter');
await expect(goBtn).toBeEnabled();
await goBtn.click();
await expect.poll(async () => {
const b = await getState(page);
const p = b.planes.find((x) => x.id === 'plane-starter')!;
return p.status === 'flying' && p.destIcao === POPUP_AIRPORT.icao;
}, { timeout: 15_000, message: 'waiting for the popup relocate click to take effect (status "flying" + dest set)' }).toBe(true);
});
+8 -1
View File
@@ -174,6 +174,9 @@ async function flyHomeViaApi(page: Page): Promise<void> {
.toBe(true);
}
if (starter.locationIcao !== HUB) {
// ISS-011: the landing above auto-slown the sim to 1× — re-set SCALE so the return leg
// 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 } });
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
await expect
@@ -284,6 +287,8 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
await expect(onboardRow).not.toBeVisible({ timeout: 15_000 });
// Restore: fly home so the live instance stays in its onboarding state for the next run.
// ISS-011: the arrival above auto-slown the sim to 1×, so re-set SCALE for this leg.
await setScale(page, SCALE);
const homeRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
expect(homeRes.status()).toBe(200);
await expect
@@ -401,7 +406,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');
// 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);
await expect
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
+76
View File
@@ -0,0 +1,76 @@
import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
// v0.17.0 — ISS-008: action errors surface as bottom-right toasts (in addition to the inline
// pane error) and game events appear as info toasts via snapshot diffing; the left-pane Time
// section offers an explicit "Enable notifications" opt-in for browser notifications.
interface CatalogEntry {
model: string;
label: string;
price: number;
}
interface StateBody {
account: { cash: number };
catalog: CatalogEntry[];
}
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;
}
test('failed actions toast bottom-right (inline error stays) and the Time section offers a notifications opt-in', async ({ page }) => {
await page.goto('/');
const buyModel = page.getByTestId('market-buy-model');
await expect(buyModel, 'the market section renders once the first snapshot lands').toBeVisible({ timeout: 15_000 });
// Part A — deterministic error path: the most expensive catalog model (ATR 72-600, €200k) is
// unaffordable with starting cash (€20k). On a long-lived local instance cash may have grown
// past it — then this part is skipped in place; CI's isolated stack always starts fresh.
const body = await getState(page);
const priciest = [...body.catalog].sort((a, b) => b.price - a.price)[0];
if (body.account.cash < priciest.price) {
await buyModel.selectOption(priciest.model);
await page.getByTestId('market-buy').click();
// The toast appears with the server's error message and the error variant class…
const toast = page.locator('[data-testid="toast"]').filter({ hasText: /insufficient funds/i });
await expect(toast, 'the error toast appears bottom-right').toBeVisible({ timeout: 10_000 });
await expect(toast).toHaveClass(/toast-error/);
// …and the inline pane error still shows (both surfaces by design). It auto-clears on the
// next poll (~1 s), so assert right after the toast — both are set in the same commit.
await expect(page.getByTestId('right-error')).toContainText(/insufficient funds/);
}
// Part B — notifications opt-in in the Time section.
const btn = page.getByTestId('enable-notifications');
await expect(btn, 'the notifications button renders in the Time section').toBeVisible({ timeout: 15_000 });
// Browsers without the Notification API: disabled with a tooltip-ish title.
const supported = await page.evaluate(() => 'Notification' in window);
if (!supported) {
await expect(btn).toBeDisabled();
await expect(btn).toHaveAttribute('title', /does not support/i);
return;
}
// Branch on the ACTUAL permission state — headless CI reports 'denied' (not 'default'), so a
// fresh context is not guaranteed to show the opt-in prompt (CI run #47).
const permission = await page.evaluate(() => Notification.permission);
if (permission === 'denied') {
// LeftPane renders the blocked-state label without any click.
await expect(btn, 'denied context shows the blocked-state label').toHaveText('Notifications blocked', { timeout: 10_000 });
} else if (permission === 'granted') {
await expect(btn, 'pre-granted context shows the enabled label').toHaveText('Notifications enabled', { timeout: 10_000 });
} else {
// 'default' — the opt-in prompt. Clicking requests it; headless may deny, so accept either
// outcome, but the label must CHANGE from the prompt to reflect the result.
await expect(btn, 'non-denied context shows the opt-in prompt').toHaveText('Enable notifications', { timeout: 10_000 });
await btn.click();
await expect(btn).not.toHaveText('Enable notifications', { timeout: 10_000 });
}
});
+162
View File
@@ -0,0 +1,162 @@
import { describe, expect, it } from 'vitest';
import type { PackageState, PlaneState, StateSnapshot } from './game/state';
import { diffSnapshots } from './deriveEvents';
// ISS-008 (v0.17.0): snapshot-diffing event derivation — pure core of the toast/notification
// feature, unit-tested in node like advanceSimClock/fetchState.
const CATALOG = [
{ model: 'atr72', label: 'ATR 72-600', price: 200_000, maxFuel: 6300, burnPerKm: 1.75, emptyWeightKg: 9300, speedKmh: 510, capacity: 6 },
];
const basePlane = (id: string): PlaneState => ({
id,
model: 'atr72',
status: 'available',
fuel: 6300,
maxFuel: 6300,
locationIcao: 'EDDF',
locationName: 'Frankfurt',
destIcao: null,
destName: null,
departureSimTime: null,
lat: 50.03,
lon: 8.56,
});
const basePackage = (id: string): PackageState => ({
id,
originIcao: 'EDDF',
originName: 'Frankfurt',
destIcao: 'LEMD',
destName: 'Madrid–Barajas',
reward: 1234.5,
cargoType: 'mail',
cargoCount: 2,
deadlineSimTime: 0,
status: 'open',
planeId: null,
createdSimTime: 0,
});
const snapshot = (over: Partial<StateSnapshot> = {}): StateSnapshot => ({
account: { cash: 20_000, reputation: 10 },
simState: { clockMs: 0, timeScale: 1, paused: false },
planes: [basePlane('plane-starter')],
packages: [],
catalog: CATALOG,
fuelPricePerL: 0.8,
sellFraction: 0.5,
...over,
});
describe('diffSnapshots', () => {
it('returns [] for identical snapshots (only clock/cash drift)', () => {
const prev = snapshot();
const next = snapshot({ account: { cash: 21_000, reputation: 11 }, simState: { clockMs: 60_000, timeScale: 1, paused: false } });
expect(diffSnapshots(prev, next)).toEqual([]);
});
it('returns [] for the first snapshot (no baseline — no "new package" spam on page load)', () => {
const next = snapshot({ packages: [basePackage('pkg-1'), basePackage('pkg-2')] });
expect(diffSnapshots(null, next)).toEqual([]);
});
it('emits a landing event when a plane goes flying → available (new locationName is the arrival)', () => {
const prev = snapshot({
planes: [
{
...basePlane('plane-starter'),
status: 'flying',
destIcao: 'LEMD',
destName: 'Madrid–Barajas',
departureSimTime: 0,
},
],
});
const next = snapshot({
planes: [
{ ...basePlane('plane-starter'), locationIcao: 'LEMD', locationName: 'Madrid–Barajas' },
],
});
expect(diffSnapshots(prev, next)).toEqual([
{ kind: 'info', message: 'ATR 72-600 landed at Madrid–Barajas' },
]);
});
it('emits a delivery event with the reward when a loaded package is delivered on arrival', () => {
const prev = snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }] });
const next = snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'delivered', planeId: 'plane-starter' }] });
expect(diffSnapshots(prev, next)).toEqual([
{ kind: 'info', message: 'Package delivered: +€1,234.50' },
]);
});
it('emits an expiry event for open → expired and loaded → expired', () => {
const fromOpen = diffSnapshots(
snapshot({ packages: [basePackage('pkg-1')] }),
snapshot({ packages: [{ ...basePackage('pkg-1'), status: 'expired' }] }),
);
expect(fromOpen).toEqual([{ kind: 'info', message: 'Package expired: Frankfurt → Madrid–Barajas' }]);
const fromLoaded = diffSnapshots(
snapshot({ packages: [{ ...basePackage('pkg-2'), status: 'loaded', planeId: 'plane-starter' }] }),
snapshot({ packages: [{ ...basePackage('pkg-2'), status: 'expired', planeId: 'plane-starter' }] }),
);
expect(fromLoaded).toEqual([{ kind: 'info', message: 'Package expired: Frankfurt → Madrid–Barajas' }]);
});
it('emits a new-package event for ids only in the next snapshot', () => {
const prev = snapshot({ packages: [basePackage('pkg-1')] });
const next = snapshot({ packages: [basePackage('pkg-1'), basePackage('pkg-2')] });
expect(diffSnapshots(prev, next)).toEqual([
{ kind: 'info', message: 'New package available: Frankfurt → Madrid–Barajas' },
]);
});
it('emits bought/sold events when the plane id set changes (with the model name)', () => {
const bought = diffSnapshots(
snapshot(),
snapshot({ planes: [basePlane('plane-starter'), basePlane('plane-2')] }),
);
expect(bought).toEqual([{ kind: 'info', message: 'Bought ATR 72-600' }]);
const sold = diffSnapshots(
snapshot({ planes: [basePlane('plane-starter'), basePlane('plane-2')] }),
snapshot(),
);
expect(sold).toEqual([{ kind: 'info', message: 'Sold ATR 72-600' }]);
});
it('reports every transition in one diff (planes first, then packages)', () => {
const prev = snapshot({
planes: [
{ ...basePlane('plane-starter'), status: 'flying', destIcao: 'LEMD', destName: 'Madrid–Barajas' },
basePlane('plane-2'),
],
packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }],
});
const next = snapshot({
planes: [
{ ...basePlane('plane-starter'), locationIcao: 'LEMD', locationName: 'Madrid–Barajas' },
basePlane('plane-3'),
],
packages: [{ ...basePackage('pkg-1'), status: 'delivered', planeId: 'plane-starter' }],
});
expect(diffSnapshots(prev, next)).toEqual([
{ kind: 'info', message: 'ATR 72-600 landed at Madrid–Barajas' },
{ kind: 'info', message: 'Bought ATR 72-600' },
{ kind: 'info', message: 'Sold ATR 72-600' },
{ kind: 'info', message: 'Package delivered: +€1,234.50' },
]);
});
it('ignores transitions that are not events (open → loaded, available → flying)', () => {
const prev = snapshot({ packages: [basePackage('pkg-1')] });
const next = snapshot({
planes: [{ ...basePlane('plane-starter'), status: 'flying', destIcao: 'LEMD', destName: 'Madrid–Barajas' }],
packages: [{ ...basePackage('pkg-1'), status: 'loaded', planeId: 'plane-starter' }],
});
expect(diffSnapshots(prev, next)).toEqual([]);
});
});
+61
View File
@@ -0,0 +1,61 @@
import type { StateSnapshot } from './game/state';
import { PLANE_TYPES } from './game/catalog';
import { formatCash } from './format';
// ISS-008 (v0.17.0): derive human-readable game events by diffing two consecutive /api/state
// snapshots — there is no server event feed, so the client watches for transitions in the
// fields it already receives. Pure and unit-tested; the shell calls it once per new snapshot
// and turns each result into an info toast (plus a browser notification when hidden).
export interface GameEvent {
kind: 'info';
message: string;
}
const planeName = (model: string): string => PLANE_TYPES[model]?.name ?? model;
export function diffSnapshots(prev: StateSnapshot | null, next: StateSnapshot): GameEvent[] {
// No baseline yet (first snapshot after load) — nothing to compare against. Emitting a
// "new package" event for every existing row would spam the stack on page load.
if (prev === null) return [];
const events: GameEvent[] = [];
// Planes: landed (flying → available, new locationName is the arrival airport), bought or
// sold (id set changed — ids are stable for a plane's whole life).
const prevPlanes = new Map(prev.planes.map((p) => [p.id, p]));
for (const plane of next.planes) {
const before = prevPlanes.get(plane.id);
if (!before) {
events.push({ kind: 'info', message: `Bought ${planeName(plane.model)}` });
continue;
}
if (before.status === 'flying' && plane.status === 'available') {
events.push({ kind: 'info', message: `${planeName(plane.model)} landed at ${plane.locationName}` });
}
}
for (const [id, before] of prevPlanes) {
if (!next.planes.some((p) => p.id === id)) {
events.push({ kind: 'info', message: `Sold ${planeName(before.model)}` });
}
}
// Packages: delivered (loaded → delivered, reward paid out in the same tick), expired
// (open|loaded → expired), newly appeared (id only in next — terminal packages are never
// deleted, so an id appearing is always a genuinely new one).
const prevPackages = new Map(prev.packages.map((p) => [p.id, p]));
for (const pkg of next.packages) {
const before = prevPackages.get(pkg.id);
if (!before) {
events.push({ kind: 'info', message: `New package available: ${pkg.originName} → ${pkg.destName}` });
continue;
}
if (before.status === 'loaded' && pkg.status === 'delivered') {
events.push({ kind: 'info', message: `Package delivered: +${formatCash(pkg.reward)}` });
} else if ((before.status === 'open' || before.status === 'loaded') && pkg.status === 'expired') {
events.push({ kind: 'info', message: `Package expired: ${pkg.originName} → ${pkg.destName}` });
}
}
return events;
}
+74
View File
@@ -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', () => {
it('tops the market up to MARKET_TARGET_OPEN_PACKAGES using the shared seed builder', async () => {
const inst = await freshDb('spawn.db');
+18 -2
View File
@@ -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 clockMs = Math.round(sim.clockMs + advanceMs);
let landedThisTick = 0;
if (advanceMs > 0) {
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);
// AFTER delivery on purpose: a plane that just landed gets work spawned
// at its new location within the same tick.
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.
await inst.db.update(schema.simState).set({ clockMs, lastRealTickMs: nowMs });
await inst.db.update(schema.simState).set(sets);
await persist(inst);
const updated = (await inst.db.select().from(schema.simState))[0];
if (!updated) throw new Error('sim_state row missing after tick');
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { MAX_TOASTS, pushToast, type Toast } from './useToasts';
// ISS-008 (v0.17.0): the toast queue's pure core — append + cap at MAX_TOASTS dropping the
// oldest. The hook itself is a thin useState wrapper around this (auto-dismiss timers are
// plain setTimeout, covered by e2e via the visible toasts).
const toast = (id: number, message: string): Toast => ({ id, kind: 'info', message });
describe('pushToast', () => {
it('appends to an empty queue and preserves order', () => {
expect(pushToast([], toast(1, 'a'))).toEqual([toast(1, 'a')]);
expect(pushToast([toast(1, 'a')], toast(2, 'b'))).toEqual([toast(1, 'a'), toast(2, 'b')]);
});
it('keeps the newest MAX_TOASTS entries, dropping the oldest beyond the cap', () => {
let queue: Toast[] = [];
for (let id = 1; id <= MAX_TOASTS + 2; id++) queue = pushToast(queue, toast(id, `m${id}`));
expect(queue).toEqual([toast(MAX_TOASTS - 1, 'm3'), toast(MAX_TOASTS, 'm4'), toast(MAX_TOASTS + 1, 'm5'), toast(MAX_TOASTS + 2, 'm6')]);
});
it('does not mutate the input queue', () => {
const before = [toast(1, 'a')];
pushToast(before, toast(2, 'b'));
expect(before).toEqual([toast(1, 'a')]);
});
});
+50
View File
@@ -0,0 +1,50 @@
'use client';
import { useCallback, useRef, useState } from 'react';
// ISS-008 (v0.17.0): transient toast notifications — a bottom-right stack for action errors
// and game events derived from snapshot diffs. Each toast auto-dismisses after TOAST_TTL_MS;
// the queue is capped at MAX_TOASTS (oldest dropped) so an event burst can't fill the corner.
export type ToastKind = 'error' | 'info';
export interface Toast {
id: number;
kind: ToastKind;
message: string;
}
export const TOAST_TTL_MS = 5_000;
export const MAX_TOASTS = 4;
// Pure core (unit-tested): append a toast, dropping the oldest beyond the cap.
export function pushToast(toasts: Toast[], toast: Toast): Toast[] {
return [...toasts, toast].slice(-MAX_TOASTS);
}
export interface UseToastsResult {
toasts: Toast[];
push: (kind: ToastKind, message: string) => void;
dismiss: (id: number) => void;
}
export function useToasts(): UseToastsResult {
const [toasts, setToasts] = useState<Toast[]>([]);
const nextIdRef = useRef(1);
// Functional update — a late timer for an already-dismissed/dropped id is a no-op.
const dismiss = useCallback((id: number) => {
setToasts((current) => current.filter((t) => t.id !== id));
}, []);
const push = useCallback(
(kind: ToastKind, message: string) => {
const toast: Toast = { id: nextIdRef.current++, kind, message };
setToasts((current) => pushToast(current, toast));
setTimeout(() => dismiss(toast.id), TOAST_TTL_MS);
},
[dismiss],
);
return { toasts, push, dismiss };
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "flight-ops",
"version": "0.16.1",
"version": "0.19.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",