feat: v0.9.2 — power-of-two time scale: slider steps through the 1/2/4/8/16/32/64 ladder, POST /api/sim clamp widened to [1,64]

This commit is contained in:
2026-09-17 19:15:15 +00:00
parent 62f9929b51
commit 03653fc50e
12 changed files with 80 additions and 51 deletions
+7
View File
@@ -1,5 +1,12 @@
# Changelog
## v0.9.2 — 2026-09-17 18:10
- **Power-of-two time scale** (left-pane UI refinement + API range bump): the slider now steps through the discrete ladder **1× → 2× → 4× → 8× → 16× → 32× → 64×** — each of the 7 positions doubles the speed instead of the v0.9.1 continuous log mapping `round(60^t)`. `lib/timeScale.ts` rewritten: `TIME_SCALES = [1,2,4,8,16,32,64]`, `sliderToScale(t)` maps to the nearest ladder step (exact at endpoints 0→1×, 1→64×), `scaleToSlider(s)` places a scale on its nearest position by log₂ distance; off-ladder values (e.g. a legacy 60) snap to the nearest power of two
- **Server clamp raised [1,60] → [1,64]** so the top of the ladder actually works end-to-end: `MAX_TIME_SCALE = 64` in `lib/sim/engine.ts`, error message + comments in `app/api/sim/route.ts`, OpenAPI `SimState.timeScale`/`SimControlsRequest.timeScale` maximums updated (spec lives in code per AGENTS.md)
- Slider step is now `1/6` (7 positions, one doubling per keyboard-arrow step); debounce/release-flush/in-flight-queue commit behavior from v0.9.1 unchanged; "N×" label and pause toggle unchanged
- Tests: unit — `lib/timeScale.test.ts` rewritten for the ladder (endpoint exactness 0→1/1→64, all 7 positions map to [1,2,4,8,16,32,64], monotonic non-decreasing over a 2000-step grid, only-ladder-values output, clamping of out-of-range/non-finite input, round-trip for every ladder value, off-ladder snapping 3→4 and legacy 60→64); `app/api/sim/route.test.ts` clamp matrix updated (500 → 64, new 64 pass-through case, both-fields call at 64); `lib/openapi.test.ts` maximum assertion 60 → 64; e2e — `panes.spec.ts` slider test now drives End → "64×" + `/api/state` timeScale=64 and Home → "1×"+timeScale=1, `sim.spec.ts` clamp-high expectation 60 → 64 (scale-60 tick-math test unchanged — 60 still passes through unclamped); live instance restored to scale 1 + unpaused in-test and in `afterEach` as before
- Verified: unit suite green; `tsc --noEmit` clean; e2e re-run against the rebuilt compose instance
## v0.9.1 — 2026-09-17 16:03
- **Log-scale time slider** (left-pane UI refinement): the 1x–60x `<select>` in `components/LeftPane.tsx` is replaced by a single `<input type="range" data-testid="time-scale-slider">` — position t ∈ [0,1] maps to `scale = round(60^t)` (t=0→1×, mid≈8×, t=1→60×) so equal slider distances are equal multiplicative steps; 60 discrete positions (`step = 1/59`) keep keyboard arrows usable (~7% per step). The current value is shown beside the slider as "N×" (`data-testid="time-scale-value"`); pause/resume toggle unchanged
- **Debounced commit**: dragging updates the displayed value optimistically; `POST /api/sim {timeScale}` fires after a 250 ms debounce and flushes immediately on release (native `change` event); a commit landing while another POST is in flight is held in a single slot and flushed right after, so rapid slider moves never drop the last intent — server's [1,60] clamp kept as backstop, no new dependencies
+9 -4
View File
@@ -31,15 +31,20 @@ describe('POST /api/sim', () => {
expect(body.paused).toBe(false);
});
it('sets and clamps timeScale into [1, 60]', async () => {
it('sets and clamps timeScale into [1, 64]', async () => {
const hi = await post({ timeScale: 500 });
expect(hi.status).toBe(200);
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(60);
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(64);
const lo = await post({ timeScale: 0.1 });
expect(lo.status).toBe(200);
expect(((await lo.json()) as { timeScale: number }).timeScale).toBe(1);
// The top of the power-of-two ladder passes through unclamped (v0.9.2).
const max = await post({ timeScale: 64 });
expect(max.status).toBe(200);
expect(((await max.json()) as { timeScale: number }).timeScale).toBe(64);
const mid = await post({ timeScale: 37 });
expect(mid.status).toBe(200);
expect(((await mid.json()) as { timeScale: number }).timeScale).toBe(37);
@@ -66,10 +71,10 @@ describe('POST /api/sim', () => {
});
it('applies both fields in one call', async () => {
const res = await post({ timeScale: 60, paused: true });
const res = await post({ timeScale: 64, paused: true });
expect(res.status).toBe(200);
const body = (await res.json()) as { timeScale: number; paused: boolean };
expect(body.timeScale).toBe(60);
expect(body.timeScale).toBe(64);
expect(body.paused).toBe(true);
await post({ timeScale: 1, paused: false }); // restore
});
+2 -2
View File
@@ -1,6 +1,6 @@
import { applyTimeControls } from '@/lib/sim/engine';
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–60, paused?: boolean }.
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–64, paused?: boolean }.
// Ticks the clock first (so the response reflects current game time), then applies
// and persists the new controls. Returns the updated simState.
@@ -23,7 +23,7 @@ export async function POST(req: Request) {
}
}
if (input.timeScale !== undefined && (typeof input.timeScale !== 'number' || !Number.isFinite(input.timeScale))) {
return Response.json({ error: 'timeScale must be a finite number (1–60)' }, { status: 400 });
return Response.json({ error: 'timeScale must be a finite number (1–64)' }, { status: 400 });
}
if (input.paused !== undefined && typeof input.paused !== 'boolean') {
return Response.json({ error: 'paused must be a boolean' }, { status: 400 });
+6 -6
View File
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'reac
import type { ContractState, PlaneState, StateSnapshot } from '@/lib/game/state';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
import { scaleToSlider, sliderToScale } from '@/lib/timeScale';
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
interface LeftPaneProps {
state: StateSnapshot | null;
@@ -14,9 +14,9 @@ interface LeftPaneProps {
onRefresh: () => void;
}
// Log-scale slider (v0.9.1): position t ∈ [0,1] → scale = round(60^t), so equal distances
// are equal multiplicative steps. 60 discrete positions keep keyboard arrows usable (~7% per step).
const SCALE_SLIDER_STEP = 1 / 59;
// Power-of-two slider (v0.9.2): position t ∈ [0,1] → nearest step of the ladder
// 1×/2×/4×/8×/16×/32×/64× — each of the 7 positions doubles the speed.
const SCALE_SLIDER_STEP = 1 / (TIME_SCALES.length - 1); // one doubling per keyboard-arrow step
const SCALE_COMMIT_DEBOUNCE_MS = 250;
function planeLocation(p: PlaneState, contracts: ContractState[]): string {
@@ -34,7 +34,7 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
// 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 and flushed right after, so the last
// user intent always reaches the server (the server's [1,60] clamp stays as backstop).
// user intent always reaches the server (the server's [1,64] clamp stays as backstop).
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
const applySimControls = useCallback(
@@ -73,7 +73,7 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
// Slider commit (v0.9.1): the displayed value follows the drag optimistically via
// pendingScale; POST /api/sim fires after a 250 ms debounce, or immediately when the
// user releases the slider (browsers fire a native 'change' on release). The server's
// [1,60] clamp stays as the backstop.
// [1,64] clamp stays as the backstop.
const [pendingScale, setPendingScaleState] = useState<number | null>(null);
const pendingRef = useRef<number | null>(null);
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+4 -4
View File
@@ -54,7 +54,7 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
});
test('time controls: pause freezes the sim and the log-scale slider sets timeScale', async ({ page }) => {
test('time controls: pause freezes the sim and the power-of-two slider sets timeScale', async ({ page }) => {
await page.goto('/');
const pauseBtn = page.getByTestId('pause-toggle');
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
@@ -65,13 +65,13 @@ test('time controls: pause freezes the sim and the log-scale slider sets timeSca
// …and in the pane itself (the refetch after POST flips the button to Resume).
await expect(pauseBtn).toHaveText('Resume');
// Scale via the log-scale slider. End jumps to max (t=1 → 60×): the label updates
// Scale via the power-of-two slider. End jumps to max (t=1 → 64×): the label updates
// optimistically on input, and release flushes the debounced POST immediately.
const slider = page.getByTestId('time-scale-slider');
await slider.focus();
await page.keyboard.press('End');
await expect(page.getByTestId('time-scale-value')).toHaveText('60×', { timeout: 10_000 });
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(60);
await expect(page.getByTestId('time-scale-value')).toHaveText('64×', { timeout: 10_000 });
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(64);
// Home jumps to min (t=0 → 1×).
await page.keyboard.press('Home');
+1 -1
View File
@@ -134,7 +134,7 @@ test('the hook can also create a fresh short-deadline contract, which then expir
test('POST /api/sim validates and clamps its input', async ({ page }) => {
const clampHigh = await postSim(page, { timeScale: 500 });
expect(clampHigh.status()).toBe(200);
expect(((await clampHigh.json()) as SimState).timeScale).toBe(60);
expect(((await clampHigh.json()) as SimState).timeScale).toBe(64); // top of the power-of-two ladder (v0.9.2)
const clampLow = await postSim(page, { timeScale: 0.1 });
expect(clampLow.status()).toBe(200);
+1 -1
View File
@@ -122,7 +122,7 @@ describe('OpenAPI spec', () => {
expect(Object.keys(controls).sort()).toEqual(['paused', 'timeScale']);
expect(controls.timeScale.type).toBe('number');
expect(controls.timeScale.minimum).toBe(1);
expect(controls.timeScale.maximum).toBe(60);
expect(controls.timeScale.maximum).toBe(64);
expect(controls.paused.type).toBe('boolean');
const error = openApiSpec.components.schemas.Error.properties;
+3 -3
View File
@@ -336,7 +336,7 @@ export const openApiSpec = {
type: 'object',
properties: {
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
timeScale: { type: 'number', minimum: 1, maximum: 60 },
timeScale: { type: 'number', minimum: 1, maximum: 64 },
paused: { type: 'boolean' },
},
required: ['clockMs', 'timeScale', 'paused'],
@@ -348,8 +348,8 @@ export const openApiSpec = {
timeScale: {
type: 'number',
minimum: 1,
maximum: 60,
description: 'Game-time multiplier; values outside [1, 60] are clamped.',
maximum: 64,
description: 'Game-time multiplier; values outside [1, 64] are clamped. The UI offers the power-of-two ladder 1/2/4/8/16/32/64.',
},
paused: { type: 'boolean' },
},
+3 -3
View File
@@ -22,12 +22,12 @@ import { arrivalTimeFor, fuelAt } from './movement';
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms —
// comfortably above a normal client poll interval (~1 s), so active play advances
// ~real time × scale; small enough that one stale read after an absence moves game
// time by at most 2 s × scale (≤ 2 min even at max scale 60). The sim therefore
// time by at most 2 s × scale (≈ 2 min even at max scale 64). The sim therefore
// only meaningfully progresses while actively polled.
export const MAX_TICK_ELAPSED_MS = 2_000;
export const MIN_TIME_SCALE = 1;
export const MAX_TIME_SCALE = 60;
export const MAX_TIME_SCALE = 64; // top of the power-of-two ladder (v0.9.2)
// Reputation gain per completed contract: BASE + PER_KM × great-circle km, rounded
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
@@ -252,7 +252,7 @@ export function runAction<T>(fn: (inst: GameDb) => Promise<T>): Promise<T> {
}
// Tick first so the returned state reflects current time, then apply the new
// controls. timeScale is clamped to [1, 60]; validation of raw input happens in
// controls. timeScale is clamped to [1, 64]; validation of raw input happens in
// the route handler (400 on non-number / non-boolean).
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
return withLock(async () => {
+30 -15
View File
@@ -1,30 +1,34 @@
import { describe, expect, it } from 'vitest';
import { MAX_SCALE, MIN_SCALE, scaleToSlider, sliderToScale } from './timeScale';
import { MAX_SCALE, MIN_SCALE, TIME_SCALES, scaleToSlider, sliderToScale } from './timeScale';
const STEPS = TIME_SCALES.length - 1; // 6 intervals across the 7 ladder positions
describe('sliderToScale', () => {
it('is exact at the endpoints (0 → 1×, 1 → 60×)', () => {
it('is exact at the endpoints (0 → 1×, 1 → 64×)', () => {
expect(sliderToScale(0)).toBe(MIN_SCALE);
expect(sliderToScale(1)).toBe(MAX_SCALE);
});
it('maps mid-slider to ~8× (√60 rounds to 8)', () => {
expect(sliderToScale(0.5)).toBe(8);
it('maps each of the 7 positions to the power-of-two ladder', () => {
const expected = [1, 2, 4, 8, 16, 32, 64];
for (let i = 0; i < TIME_SCALES.length; i++) {
expect(sliderToScale(i / STEPS)).toBe(expected[i]);
}
});
it('is monotonic non-decreasing across the whole range', () => {
let prev = sliderToScale(0);
for (let i = 1; i <= 2000; i++) {
const t = i / 2000;
const s = sliderToScale(t);
const s = sliderToScale(i / 2000);
expect(s).toBeGreaterThanOrEqual(prev);
prev = s;
}
});
it('covers every integer scale 1..60 somewhere on the slider', () => {
const seen = new Set<number>();
for (let i = 0; i <= 2000; i++) seen.add(sliderToScale(i / 2000));
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) expect(seen.has(s)).toBe(true);
it('only ever returns a ladder value', () => {
for (let i = 0; i <= 2000; i++) {
expect(TIME_SCALES).toContain(sliderToScale(i / 2000));
}
});
it('clamps out-of-range and non-finite input', () => {
@@ -35,9 +39,15 @@ describe('sliderToScale', () => {
});
describe('scaleToSlider', () => {
it('is exact at the endpoints (1× → 0, 60× → 1)', () => {
it('is exact at the endpoints (1× → 0, 64× → 1)', () => {
expect(scaleToSlider(1)).toBe(0);
expect(scaleToSlider(60)).toBe(1);
expect(scaleToSlider(64)).toBe(1);
});
it('places each ladder value on its own position', () => {
for (let i = 0; i < TIME_SCALES.length; i++) {
expect(scaleToSlider(TIME_SCALES[i])).toBeCloseTo(i / STEPS, 12);
}
});
it('stays within [0, 1] for in-range scales', () => {
@@ -51,15 +61,20 @@ describe('scaleToSlider', () => {
it('clamps out-of-range and non-finite input', () => {
expect(scaleToSlider(0)).toBe(0);
expect(scaleToSlider(-3)).toBe(0);
expect(scaleToSlider(61)).toBe(1);
expect(scaleToSlider(65)).toBe(1);
expect(scaleToSlider(NaN)).toBe(0);
});
});
describe('round-trip', () => {
it('sliderToScale(scaleToSlider(s)) === s for every integer scale 1..60', () => {
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) {
it('sliderToScale(scaleToSlider(s)) === s for every ladder value', () => {
for (const s of TIME_SCALES) {
expect(sliderToScale(scaleToSlider(s))).toBe(s);
}
});
it('maps off-ladder scales to the nearest power of two', () => {
expect(sliderToScale(scaleToSlider(3))).toBe(4); // log2(3) ≈ 1.58 → step 2 (4×)
expect(sliderToScale(scaleToSlider(60))).toBe(64); // legacy max from the v0.9.x era
});
});
+13 -11
View File
@@ -1,22 +1,24 @@
// Pure log-scale mapping helpers for the time-scale slider (v0.9.1) — no game logic,
// unit-testable in node. Slider position t ∈ [0,1] ↔ scale = round(60^t), so equal
// distances on the slider correspond to equal multiplicative steps: 1× at t=0, ~8×
// mid-slider, 60× at t=1 (matching POST /api/sim's clamp range).
// Pure mapping helpers for the time-scale slider (v0.9.2) — no game logic, unit-testable
// in node. The slider has 7 discrete positions on a power-of-two ladder:
// 1× → 2× → 4× → 8× → 16× → 32× → 64×, so each step doubles the speed (matching
// POST /api/sim's clamp range [1, 64]).
export const MIN_SCALE = 1;
export const MAX_SCALE = 60;
export const TIME_SCALES = [1, 2, 4, 8, 16, 32, 64] as const;
export const MIN_SCALE: number = TIME_SCALES[0];
export const MAX_SCALE: number = TIME_SCALES[TIME_SCALES.length - 1];
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
// t → scale. Exact at the endpoints: sliderToScale(0) === 1, sliderToScale(1) === 60.
// t → scale: the position maps to the nearest ladder step. Exact at the endpoints:
// sliderToScale(0) === 1, sliderToScale(1) === 64.
export function sliderToScale(t: number): number {
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
return Math.round(clamp(Math.pow(MAX_SCALE, tt), MIN_SCALE, MAX_SCALE));
return TIME_SCALES[clamp(Math.round(tt * (TIME_SCALES.length - 1)), 0, TIME_SCALES.length - 1)];
}
// scale → t (inverse of the pre-rounding mapping). Exact at the endpoints:
// scaleToSlider(1) === 0, scaleToSlider(60) === 1. Round-trips every integer 1..60.
// scale → t: the nearest ladder position by log2 distance. Exact at the endpoints:
// scaleToSlider(1) === 0, scaleToSlider(64) === 1; round-trips every value in TIME_SCALES.
export function scaleToSlider(scale: number): number {
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
return Math.log(s) / Math.log(MAX_SCALE);
return Math.log2(s) / Math.log2(MAX_SCALE);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "flight-ops",
"version": "0.9.1",
"version": "0.9.2",
"private": true,
"scripts": {
"dev": "next dev -p 3000",