Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0467b54c70 | ||
|
|
51d4f21d6b | ||
|
|
d8dc785757 | ||
|
|
eb69359a38 | ||
|
|
3acf471295 | ||
|
|
7d2f8f07c8 |
@@ -1,5 +1,21 @@
|
||||
# Changelog
|
||||
|
||||
## 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)
|
||||
- No server or OpenAPI changes — display-only client work
|
||||
- Tests: unit — new suite in `lib/useSimClock.test.ts` pins the extrapolation math (exact elapsed × scale advance, frozen while paused at any scale, zero-elapsed identity, clock-skew clamp never goes backwards, mirrors the tickOnce formula under the 2 s clamp). e2e (`panes.spec.ts`) — new test: at scale 1000 sample `sim-clock` three times ~1.3 s apart real time and assert the displayed clock strictly advances between CONSECUTIVE samples (with poll-only rendering a pair could straddle zero snapshots and not change), plus format check and a total-advance sanity bound
|
||||
- Verified: `tsc --noEmit` clean; unit suite green locally; e2e not run locally by design — CI verifies against an isolated stack
|
||||
|
||||
## v0.16.0 — 2026-09-19 12:18
|
||||
- **Weight-proportional fuel burn (ISS-005, part A).** Fuel no longer burns at a constant L/km — the instantaneous rate is proportional to total weight, `r(F) = k·(We + ρF)` L/km with We the empty weight and ρ = 0.8 kg/L (Jet-A1), so a heavier plane burns more per km and a tank gets lighter as it empties. The constant `k` is calibrated so a FULL tank burns exactly the catalog's old `burnPerKm`, keeping full-tank departure behavior identical to before; divergence only grows in flight as fuel drops off. Closed forms of `dF/dx = −k(We + ρF)` live in `lib/sim/movement.ts` (single source of truth):
|
||||
- `fuelAtWeighted(startFuel, burnPerKm, emptyWeightKg, maxFuel, distanceKm, progress)` — fuel remaining after flying `progress` of the leg (replaces the old constant-rate `fuelAt`, which is removed)
|
||||
|
||||
@@ -347,3 +347,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;
|
||||
}
|
||||
|
||||
+26
-3
@@ -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,32 @@ 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} />
|
||||
<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 */}
|
||||
<Map state={state} hovered={hovered} />
|
||||
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} />
|
||||
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||
<ToastStack toasts={toasts} onDismiss={dismiss} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+113
-19
@@ -5,6 +5,7 @@ import type { PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
||||
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||
import { useSimClock } from '@/lib/useSimClock';
|
||||
import type { HoverTarget } from './hoverTypes';
|
||||
|
||||
interface LeftPaneProps {
|
||||
@@ -15,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
|
||||
@@ -45,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);
|
||||
|
||||
@@ -75,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;
|
||||
@@ -96,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;
|
||||
@@ -165,8 +216,33 @@ 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
|
||||
// snapshot. Fed with EFFECTIVE controls so a scale drag / pause click takes effect immediately,
|
||||
// not when the confirming snapshot lands. Only the sim-clock paragraph uses this — deadline and
|
||||
// penalty previews stay snapshot-based (deterministic against the server clock).
|
||||
const simClockMs = useSimClock(state, { timeScale: displayedScale, paused });
|
||||
|
||||
return (
|
||||
<aside data-testid="left-pane" className="pane left-pane">
|
||||
<h2 className="pane-title">Assets</h2>
|
||||
@@ -221,7 +297,7 @@ export default function LeftPane({ state, loading, error, onRefresh, onHover }:
|
||||
<section className="pane-section">
|
||||
<h3 className="pane-heading">Time</h3>
|
||||
<p data-testid="sim-clock" className="sim-clock">
|
||||
{formatSimClock(state.simState.clockMs)}
|
||||
{simClockMs !== null && formatSimClock(simClockMs)}
|
||||
{paused ? ' (paused)' : ''}
|
||||
</p>
|
||||
<div className="time-controls">
|
||||
@@ -246,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 && (
|
||||
|
||||
@@ -16,6 +16,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 +107,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.
|
||||
@@ -139,12 +142,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) {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ import { test, expect, type Page } from '@playwright/test';
|
||||
// The panes render from the shell's single /api/state poll (lib/useGameState.ts); time
|
||||
// controls POST to /api/sim and refetch immediately, so UI assertions settle within a tick.
|
||||
|
||||
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder (same convention as e2e/sim.spec.ts)
|
||||
|
||||
interface SimState {
|
||||
clockMs: number;
|
||||
timeScale: number;
|
||||
@@ -104,6 +106,40 @@ test('time controls: pause freezes the sim and the ladder slider sets timeScale'
|
||||
expect(after.simState.paused).toBe(false);
|
||||
});
|
||||
|
||||
test('sim clock ticks smoothly between polls — seconds advance without waiting for a snapshot (ISS-007)', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
const clock = page.getByTestId('sim-clock');
|
||||
await expect(clock).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Fastest scale so game seconds move visibly inside the sampling window.
|
||||
const post = await page.request.post('/api/sim', { data: { timeScale: SCALE, paused: false } });
|
||||
expect(post.status()).toBe(200);
|
||||
|
||||
// "YYYY-MM-DD HH:MM:SS UTC" → epoch ms (UTC). While running there is no "(paused)" suffix.
|
||||
const sample = async () => {
|
||||
const text = ((await clock.textContent()) ?? '').trim();
|
||||
expect(text, `clock format: ${text}`).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/);
|
||||
return Date.parse(text.replace(' ', 'T').replace(' UTC', 'Z'));
|
||||
};
|
||||
|
||||
// Three samples ~1.3 s apart real time: at scale 1000 each gap is ≈1300 game seconds, so the
|
||||
// displayed clock must strictly advance between CONSECUTIVE samples — with the old poll-only
|
||||
// rendering a sample pair could straddle zero snapshot updates and show no change at all.
|
||||
const t0 = await sample();
|
||||
await new Promise((r) => setTimeout(r, 1_300));
|
||||
const t1 = await sample();
|
||||
await new Promise((r) => setTimeout(r, 1_300));
|
||||
const t2 = await sample();
|
||||
|
||||
expect(t1).toBeGreaterThan(t0);
|
||||
expect(t2).toBeGreaterThan(t1);
|
||||
// Sanity: ~2.6 s real × 1000 ≈ 2.6 M game ms — generous bounds keep slow CI boxes safe while
|
||||
// still catching a frozen or wildly mis-scaled clock.
|
||||
const total = t2 - t0;
|
||||
expect(total).toBeGreaterThanOrEqual(1_000_000);
|
||||
expect(total).toBeLessThanOrEqual(6_000_000);
|
||||
});
|
||||
|
||||
test('slider commit keeps the chosen scale on screen until confirmed — no snap-back (ISS-001)', async ({ page }) => {
|
||||
test.setTimeout(60_000);
|
||||
await page.goto('/');
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { advanceSimClock, type SimClockAnchor } from './useSimClock';
|
||||
|
||||
// ISS-007 (v0.16.1) — the pure extrapolation core of lib/useSimClock.ts. The hook itself is a
|
||||
// thin setInterval + re-sync wrapper covered by e2e (panes.spec.ts "ticks smoothly between polls");
|
||||
// this suite pins the math: game time advances real-time × timeScale, frozen while paused.
|
||||
|
||||
const anchor = (over: Partial<SimClockAnchor> = {}): SimClockAnchor => ({
|
||||
clockMs: 1_750_000_000_000,
|
||||
at: 1_000_000,
|
||||
timeScale: 1,
|
||||
paused: false,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('advanceSimClock', () => {
|
||||
it('advances by exactly elapsed real-time × timeScale while running', () => {
|
||||
expect(advanceSimClock(anchor(), 1_001_000)).toBe(1_750_000_000_000 + 1_000); // scale 1: 1 s real = 1 s game
|
||||
expect(advanceSimClock(anchor({ timeScale: 25 }), 1_002_500)).toBe(1_750_000_000_000 + 62_500);
|
||||
// The e2e scenario: scale 1000, 2.5 s real → 2 500 game seconds.
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_002_500)).toBe(1_750_000_000_000 + 2_500_000);
|
||||
});
|
||||
|
||||
it('returns the anchor value exactly at zero elapsed', () => {
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_000_000)).toBe(1_750_000_000_000);
|
||||
});
|
||||
|
||||
it('is frozen while paused regardless of elapsed or scale', () => {
|
||||
const a = anchor({ timeScale: 1000, paused: true });
|
||||
expect(advanceSimClock(a, 1_000_000)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(a, 2_000_000)).toBe(1_750_000_000_000); // a full second later — still frozen
|
||||
});
|
||||
|
||||
it('clamps to the anchor value when nowMs is before the anchor (clock skew), never backwards', () => {
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 999_999)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(anchor({ paused: true }), 999_999)).toBe(1_750_000_000_000);
|
||||
});
|
||||
|
||||
it('mirrors the server tick model (tickOnce): advance = elapsed × timeScale while actively polled', () => {
|
||||
// lib/sim/engine.ts: clockMs += min(now − lastRealTickMs, MAX_TICK_ELAPSED_MS) × timeScale.
|
||||
// For gaps under the 2 s clamp the client extrapolation is exactly the server's own formula.
|
||||
const scale = 50;
|
||||
for (const gap of [1, 250, 999, 1_999]) {
|
||||
expect(advanceSimClock(anchor({ timeScale: scale }), 1_000_000 + gap)).toBe(
|
||||
1_750_000_000_000 + gap * scale,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StateSnapshot } from './game/state';
|
||||
|
||||
// ISS-007 (v0.16.1): the sim clock ticks smoothly on the CLIENT between polls instead of
|
||||
// jumping once per snapshot. The server's authoritative rate is exactly real-time × timeScale
|
||||
// (tickOnce in lib/sim/engine.ts: advance = min(elapsed, MAX_TICK_ELAPSED_MS) × timeScale), so
|
||||
// client-side extrapolation mirrors the server's own model. Every new snapshot re-anchors to
|
||||
// server truth, bounding any drift by network latency only.
|
||||
|
||||
export interface SimClockAnchor {
|
||||
// Server truth at anchor time — the snapshot's simState.clockMs.
|
||||
clockMs: number;
|
||||
// Date.now() when that snapshot was received.
|
||||
at: number;
|
||||
timeScale: number;
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
// Pure core of the extrapolation — mirrors tickOnce: while running, game time advances by
|
||||
// real-time × timeScale; while paused it is frozen (advance 0). nowMs before `at` clamps to
|
||||
// the anchor value instead of going backwards. Unit-testable in node.
|
||||
export function advanceSimClock(anchor: SimClockAnchor, nowMs: number): number {
|
||||
if (anchor.paused) return anchor.clockMs;
|
||||
return anchor.clockMs + Math.max(0, nowMs - anchor.at) * anchor.timeScale;
|
||||
}
|
||||
|
||||
// ~10 fps display refresh — smooth for a seconds-precision wall clock without busy re-renders.
|
||||
const DISPLAY_TICK_MS = 100;
|
||||
|
||||
export interface SimClockControls {
|
||||
// EFFECTIVE controls (optimistic pending scale / current pause), not the snapshot's:
|
||||
// UI changes take effect on click/drag without waiting for a confirming snapshot.
|
||||
timeScale: number;
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
// Returns the display clockMs to render, or null until the first snapshot arrives.
|
||||
export function useSimClock(snapshot: StateSnapshot | null, controls: SimClockControls): number | null {
|
||||
const anchorRef = useRef<SimClockAnchor | null>(null);
|
||||
const [displayMs, setDisplayMs] = useState<number | null>(null);
|
||||
|
||||
// Re-sync on every snapshot AND effective-control change: snap to server truth. The snapshot
|
||||
// object is fresh per poll (useGameState), so this runs once per poll cycle as well.
|
||||
useEffect(() => {
|
||||
if (!snapshot) return;
|
||||
anchorRef.current = {
|
||||
clockMs: snapshot.simState.clockMs,
|
||||
at: Date.now(),
|
||||
timeScale: controls.timeScale,
|
||||
paused: controls.paused,
|
||||
};
|
||||
setDisplayMs(advanceSimClock(anchorRef.current, Date.now()));
|
||||
}, [snapshot, controls.timeScale, controls.paused]);
|
||||
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
const anchor = anchorRef.current;
|
||||
if (anchor) setDisplayMs(advanceSimClock(anchor, Date.now()));
|
||||
}, DISPLAY_TICK_MS);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
// First paint after a snapshot arrives happens before the re-sync effect runs — show the
|
||||
// snapshot value directly so the clock never blanks for a frame.
|
||||
return displayMs ?? (snapshot ? snapshot.simState.clockMs : null);
|
||||
}
|
||||
@@ -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')]);
|
||||
});
|
||||
});
|
||||
@@ -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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "flight-ops",
|
||||
"version": "0.16.0",
|
||||
"version": "0.17.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3000",
|
||||
|
||||
Reference in New Issue
Block a user