From 25f2e609ab43f463bf60defd953622923a4d170e Mon Sep 17 00:00:00 2001 From: Divij <148875733+divijg19@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:35:52 +0530 Subject: [PATCH] v2.9.1: Verify WASM at release and trim TS comments and helpers - Release verify job now installs wasm-pack, builds the WASM package with the CI path remap before Vitest, and runs wasm-pack test --node. Tag pushes do not trigger the CI push gate, so without this the release's parity tests silently skipped on the missing pkg directory. - Corrected the CI comment that still claimed opt-level="s" ships for wasm. - Removed wasm.integration.test.ts: its assertions were tautologies and vi.resetModules() did not reset the already-imported loader state. - autoRepeat.test.ts now uses the shared startedOrFail helper; its stale 100ms-gap timing comment was corrected. - Trimmed verbose TS comments to their invariant statements across the runtime, components and tests (~270 LoC removed), keeping the contracts that prevent regressions. - solid-js stays on the latest 1.x (1.9.20); the 2.x migration is still blocked by the lack of a stable Solid 2 testing library. - Version bumped to 2.9.1 across all manifests. Verification: 163 Vitest, 211 Rust, 106 WASM + count guard, 17 parity, clippy host + wasm32, fmt, lint, typecheck, build, YAML parse. --- .github/workflows/ci.yml | 3 +- .github/workflows/release.yml | 18 +++ package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/App.tsx | 13 +-- src/__tests__/App.accessibility.test.tsx | 17 +-- src/__tests__/answerValidation.test.ts | 13 +-- src/__tests__/audioPlayback.test.ts | 16 +-- src/__tests__/autoRepeat.test.ts | 35 +----- src/__tests__/flashExposure.test.tsx | 22 +--- src/__tests__/splashSkip.test.tsx | 19 +--- src/__tests__/wasm.integration.test.ts | 116 ------------------- src/components/AdvancedSettings.tsx | 32 +----- src/components/AnswerNumbers.tsx | 23 +--- src/components/SessionEndDetails.tsx | 25 +---- src/runtime/browser.ts | 136 +++++------------------ src/runtime/index.ts | 15 +-- src/runtime/localPlanner.ts | 59 ++-------- src/runtime/types.ts | 14 +-- 21 files changed, 106 insertions(+), 478 deletions(-) delete mode 100644 src/__tests__/wasm.integration.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1af1c8d..c5f4ef3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -299,7 +299,8 @@ jobs: echo "no plain #[test] in any wasm-compiled test module" # `build:wasm`, not `build:web`. The release profile — lto, - # codegen-units=1, opt-level="s", strip — is what actually ships, and + # codegen-units=1, strip — plus the wasm-only opt-level=3 override in + # `build:wasm` is what actually ships (desktop stays at "s"), and # `wasm-pack test` above only ever compiles a dev profile, so this is the # one step that proves the shipped artefact builds at all. The Vite half # of `build:web` is deliberately not repeated here: the frontend job diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 38cc6d1..9579706 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,9 +40,27 @@ jobs: - name: Install frontend dependencies run: bun install --frozen-lockfile + # The bridge is only built in the `build-web` job, but a tag push does + # not trigger CI's `push` gate (main only), so this verify job is the + # release's own WASM check. Build the package first or the parity spec + # silently skips on the missing pkg directory. + - name: Install wasm-pack + uses: taiki-e/install-action@v2 + with: + tool: wasm-pack + + - name: Build release WASM package + env: + RUSTFLAGS: "--remap-path-prefix=/home/runner=/U" + run: bun run build:wasm + - name: Run Vitest run: bun run test + - name: Run WASM tests + working-directory: src-tauri + run: wasm-pack test --node + - name: Lint frontend run: bun x biome check . diff --git a/package.json b/package.json index 115f398..d94d606 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "flashspan", "private": true, - "version": "2.9.0", + "version": "2.9.1", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 143d9cb..440cced 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "Flashspan" -version = "2.9.0" +version = "2.9.1" dependencies = [ "getrandom 0.4.3", "image", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 345c8f0..0b31611 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "Flashspan" -version = "2.9.0" +version = "2.9.1" description = "Mental Maths training simulator" authors = ["you"] repository = "" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index eb184bf..e5463ae 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Ascent Flash", - "version": "2.9.0", + "version": "2.9.1", "identifier": "com.divijg19.ascentflash", "build": { "frontendDist": "../dist", diff --git a/src/App.tsx b/src/App.tsx index 94275ca..afd5c7f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -28,16 +28,9 @@ function isEscapeKey(event: KeyboardEvent): boolean { } /** - * Enter or leave fullscreen, best-effort. - * - * Never throws and never blocks a caller on a refusal: the Fullscreen API is - * simply absent on some targets (iOS Safari has no element `requestFullscreen`, - * as do cross-origin iframes and some WebViews) and can be refused by policy. - * Treating a refusal as fatal left the Start button permanently dead there, so - * a failure is swallowed and the session runs windowed; the countdown tick - * retries the request, which is the mechanism that actually matters. An absent - * `requestFullscreen` is not special-cased — calling it throws `TypeError`, - * which the same handler catches. + * Enter or leave fullscreen, best-effort. The API is absent on some targets and + * can be refused by policy; a failure is swallowed so the session still runs + * windowed. The countdown tick retries the request. */ async function setFullscreen(enabled: boolean): Promise { if (typeof document === "undefined") { diff --git a/src/__tests__/App.accessibility.test.tsx b/src/__tests__/App.accessibility.test.tsx index ea2e2f4..572ef3e 100644 --- a/src/__tests__/App.accessibility.test.tsx +++ b/src/__tests__/App.accessibility.test.tsx @@ -170,20 +170,9 @@ describe("App accessibility tests", () => { }); /** - * Opening the advanced settings moves focus into the panel and traps Tab - * inside it. - * - * The trap is driven by a ref on the overlay element that lives in - * `AdvancedSettings` but is read by a `createEffect` in `App.tsx`. Those two - * are in different components now, and `App` holds the element in a plain - * (non-reactive) variable rather than a signal — so the effect depends only - * on `showAdvanced()`, and nothing re-runs it if the ref is assigned late or - * not at all. That failure is silent: the panel still renders and every other - * assertion here passes, while keyboard users tab straight out of the dialog - * into the page behind it. - * - * So assert the focus actually moved, which is the observable consequence of - * the ref having been wired up. + * Opening advanced settings must move focus into the panel. Assert the + * observable consequence: the overlay ref being wired up silently is easy + * to miss otherwise. */ /** * An interruption while the tab is hidden must return the app to idle and diff --git a/src/__tests__/answerValidation.test.ts b/src/__tests__/answerValidation.test.ts index a51de92..ee53bd1 100644 --- a/src/__tests__/answerValidation.test.ts +++ b/src/__tests__/answerValidation.test.ts @@ -194,16 +194,9 @@ describe("validateAnswer", () => { }); /** - * `deterministicFallback` must agree with `next_distinct_value` in - * `core/engine.rs`: rotate the magnitude one step inside the digit-width domain, - * and carry the previous value's sign while the running sum can still fund it. - * - * This block previously pinned the opposite rule. It asserted that a negative - * predecessor comes back positive ("strips minus") and that an affordable - * positive duplicate becomes negative — the two halves of the divergence - * `src/__tests__/generatorFallback.test.ts` now pins against. Its comments also - * referred to a `maxExclusive` the implementation no longer had, so the values - * they claimed to explain were stale. + * `deterministicFallback` must mirror `next_distinct_value` in `core/engine.rs`: + * rotate the magnitude within the digit width, carry the previous sign while + * the sum funds it. Parity is pinned by `generatorFallback.test.ts`. */ describe("deterministicFallback", () => { it("keeps a negative payload negative while the sum funds it", () => { diff --git a/src/__tests__/audioPlayback.test.ts b/src/__tests__/audioPlayback.test.ts index 50e1e16..190861a 100644 --- a/src/__tests__/audioPlayback.test.ts +++ b/src/__tests__/audioPlayback.test.ts @@ -148,18 +148,10 @@ describe("browser audio playback", () => { }); /** - * Warmup's whole job is to have the bytes decoded before the countdown - * ends, and it used to also mark the device ready from a muted play-through - * that was rewound straight away — so one early "success" silenced every - * later failure, including a device that died mid-session. - * - * It also runs on the only cold cache a page ever gets, which is where the - * two claims meet: the ticks that arrive while the first decode is still in - * flight are waiting on the same promise, so when it lands they would both - * sound. Only the newest may — a beep that fires a tick late is a beep - * attached to the wrong number. That is why this is the first test in the - * file to touch the buffers: a load that *succeeds* is cached for the life - * of the page, and no later test can be slow again. + * Warmup decodes bytes without claiming device readiness. This is the only + * cold cache a page gets, so it is also where the slow-load race is tested: + * ticks waiting on the same promise must not both sound. It runs first + * because a successful load is cached for the page's lifetime. */ it("decodes on warmup without claiming anything, and lets only the newest tick sound", async () => { const started = mark(); diff --git a/src/__tests__/autoRepeat.test.ts b/src/__tests__/autoRepeat.test.ts index bdcbd02..d80451b 100644 --- a/src/__tests__/autoRepeat.test.ts +++ b/src/__tests__/autoRepeat.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { browserRuntime } from "../runtime/browser"; import { normalizeAutoRepeat } from "../runtime/localPlanner"; -import type { StartSessionResponse } from "../runtime/types"; +import { startedOrFail } from "./helpers"; /** * Auto-repeat must terminate after the requested number of repeats. @@ -22,24 +22,11 @@ const BASE_CONFIG = { allow_negative_numbers: false, } as const; -// A 2-number session is 3.1s of countdown plus 2 x (500ms + 100ms) = 4.3s. +// A 2-number session is 3.1s of countdown plus 2 x 500ms exposure = 5.1s; +// 6000ms leaves slack for timer delivery. const SESSION_MS = 6000; describe("auto-repeat", () => { - /** - * None of these cases exercise the superseded-stop path, so a null response - * here would mean the runtime broke its own contract rather than declined. - */ - function startedOrFail( - response: Awaited>, - ): StartSessionResponse { - expect(response).not.toBeNull(); - if (!response) { - throw new Error("startSession unexpectedly returned null"); - } - return response; - } - beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(0); @@ -157,20 +144,8 @@ describe("auto-repeat", () => { }); /** - * Leaving the end screen must destroy the pending restart. - * - * This is the property that makes a manual Start safe. The end screen shows - * the auto-repeat countdown bar, and its only way back to the home screen is - * the "Home" button, which calls `stop()`. `stopSession` cancels - * `pendingAutoRepeat` and bumps `sessionEpoch`, so by the time the user can - * press Start again there is no repeat left to race them. - * - * If that ever stops holding — a new route off the end screen that skips - * `stop`, or a `stopSession` that stops clearing the timer — the manual Start - * and the pending restart both reach `startSession`, the loser throws - * "A session is already starting", and `App.tsx`'s catch sets the phase to - * idle while a session is live and flashing numbers. So pin the cancellation - * rather than the UI layout: the layout is easy to read, the invariant is not. + * Leaving the end screen must cancel the pending restart, so a manual Start + * cannot race it. Pin the cancellation rather than the UI route. */ it("cancels the pending restart when the user leaves the end screen", async () => { await browserRuntime.setSoundEnabled(false); diff --git a/src/__tests__/flashExposure.test.tsx b/src/__tests__/flashExposure.test.tsx index 12b8b56..0be8e4f 100644 --- a/src/__tests__/flashExposure.test.tsx +++ b/src/__tests__/flashExposure.test.tsx @@ -17,24 +17,10 @@ import { import { startedOrFail } from "./helpers"; /** - * Every flashed number must stay on screen for at least its full exposure. - * - * This is the "first flash number is short lived" bug. The driver used to - * schedule each event against an absolute grid anchored at session start, so - * whatever lateness the *previous* event was delivered with was subtracted from - * this one's window. The first show is the only one delivered alongside the - * countdown's paint tail and the countdown->flashing view transition, so its - * lateness truncated the first number's exposure while later numbers flashed - * for the full duration. - * - * The driver now chains fixed intervals, which makes exposure exact by - * construction: a late delivery can only delay when an event lands, never - * shorten how long the previous one stayed up. - * - * Lateness is injected where a browser creates it — the timer fires later than - * asked — by padding the delay the runtime requests. Exposure is then measured - * from the payloads' own `emitted_at_ms` rather than from the test's tick - * positions, so the assertion is about what a user would actually see. + * Every flashed number must stay on screen for at least its full exposure. The + * driver chains fixed intervals so lateness delays an event without shortening + * the previous exposure; tests inject lateness into timer delays and measure + * exposure from payload timestamps. */ const CONFIG = { diff --git a/src/__tests__/splashSkip.test.tsx b/src/__tests__/splashSkip.test.tsx index 05dd84f..5d186d3 100644 --- a/src/__tests__/splashSkip.test.tsx +++ b/src/__tests__/splashSkip.test.tsx @@ -105,22 +105,9 @@ describe("skipping the splash", () => { }); /** - * The splash must not move after it appears, and its fade-out must never be cut - * short. - * - * Two independent defects produced the stutter: - * - * 1. The banner declared no intrinsic size, so its box had zero height until the - * 278KB PNG decoded and the flex column re-centred mid-fade. The - * width/height attributes below are what fix that; if they are ever dropped, - * the layout jump comes straight back. - * 2. The fade lived in CSS while the schedule lived in JS as separate literals, - * so the unmount could land before the transition finished (cutting the last - * frames) or long after it (an invisible, click-through overlay). Unmount now - * hangs off the opacity transition ending, with a timer as the backstop. - * - * Honest caveat: jsdom does not run CSS transitions, so the lifecycle test - * exercises the JS schedule and the backstop, not real fade timing. + * The splash must not shift when its PNG decodes (hence the width/height + * attributes) and its JS unmount schedule must outlast the CSS fade. jsdom does + * not run transitions, so these tests cover the schedule and backstop only. */ describe("splash presentation", () => { afterEach(async () => { diff --git a/src/__tests__/wasm.integration.test.ts b/src/__tests__/wasm.integration.test.ts deleted file mode 100644 index 46d6df0..0000000 --- a/src/__tests__/wasm.integration.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { getWasmVersion, loadWasmCoreBridge } from "../wasm/loader"; - -describe("WASM integration tests - startup fallback", () => { - beforeEach(() => { - // Reset module state before each test - vi.resetModules(); - }); - - afterEach(() => { - vi.clearAllMocks(); - }); - - it("loadWasmCoreBridge returns false gracefully on first failure", async () => { - // This test imports the actual loader which has internal state - // The result depends on whether WASM is available in test environment - // Just verify the function returns a boolean - const result = await loadWasmCoreBridge(); - expect(typeof result).toBe("boolean"); - }); - - it("getWasmVersion returns null safely if WASM not loaded", () => { - // Test the safety of getWasmVersion when WASM is not available - const version = getWasmVersion(); - // Should return string if available or null if not - expect(typeof version === "string" || version === null).toBe(true); - }); - - it("WASM module import handles missing exports gracefully", async () => { - // The loader checks for required exports (normalize, build, version) - // If any are missing, it logs info and returns false - // This test verifies the logic handles incomplete modules - const result = await loadWasmCoreBridge(); - expect(typeof result).toBe("boolean"); - }); - - it("handles WASM initialization timeout or network error", async () => { - // The try/catch in loadWasmCoreBridge catches all errors - // Network timeouts, module not found, wasm init errors all return false - const result = await loadWasmCoreBridge(); - // Should not throw, should return boolean - expect(typeof result).toBe("boolean"); - }); - - it("subsequent loadWasmCoreBridge calls return cached result", async () => { - // First call (may succeed or fail) - const result1 = await loadWasmCoreBridge(); - - // Second call should return same result without re-attempting - // (internal wasmBridgeLoadAttempted flag prevents re-attempts) - const result2 = await loadWasmCoreBridge(); - - expect(result1).toBe(result2); - }); - - it("app can bootstrap without WASM and use JS fallback", async () => { - // This is more of an integration test of the whole flow - // Verify that if WASM fails, the browser runtime is still initialized - // and the app can function with JS-based session planning - - const isBrowserEnv = typeof window !== "undefined"; - expect(isBrowserEnv).toBe(true); - - // In browser, WASM may or may not load, but app should work either way - const wasmLoaded = await loadWasmCoreBridge(); - expect(typeof wasmLoaded).toBe("boolean"); - }); - - it("error handling preserves stack traces for debugging", () => { - // getWasmVersion catches errors and logs them - // This ensures errors don't crash the app but are still logged - getWasmVersion(); - - // Should not throw even if something goes wrong internally - expect(() => getWasmVersion()).not.toThrow(); - }); - - it("WASM version detection is resilient to module variations", () => { - // The loader uses asFunction to safely check for wasm_version export - // This handles variations in how the module might export functions - const version = getWasmVersion(); - - // Version should be string or null (not undefined or error) - expect(version === null || typeof version === "string").toBe(true); - }); - - it("multiple concurrent WASM load attempts are serialized", async () => { - // The loader uses wasmBridgeLoadAttempted flag to ensure only one load attempt - // This test verifies concurrent calls don't trigger multiple loads - - const promises = [ - loadWasmCoreBridge(), - loadWasmCoreBridge(), - loadWasmCoreBridge(), - ]; - - const results = await Promise.all(promises); - - // All should have same result (the first successful or failed attempt) - expect(results[0]).toBe(results[1]); - expect(results[1]).toBe(results[2]); - }); - - it("health check logs version when available", () => { - // The performWasmHealthCheck function in index.tsx calls getWasmVersion - // and logs it if available - - const version = getWasmVersion(); - - // If version is available, it should be a valid string - if (version !== null) { - expect(typeof version).toBe("string"); - expect(version.length).toBeGreaterThan(0); - } - }); -}); diff --git a/src/components/AdvancedSettings.tsx b/src/components/AdvancedSettings.tsx index e241f1f..56870b0 100644 --- a/src/components/AdvancedSettings.tsx +++ b/src/components/AdvancedSettings.tsx @@ -4,20 +4,9 @@ import { COLOR_SCHEMES } from "../runtime/types"; import { numericValue } from "./NumberField"; /** - * The advanced settings overlay: auto-repeat, answer mode, colour and theme. - * - * This was a ~320-line block inline in `App.tsx`, which pushed the app's own - * session handling far enough down the file that it was hard to find. It is - * pure presentation plus signal plumbing, so it extracts cleanly. - * - * Reactive values arrive as accessors rather than plain values, which is the - * Solid convention: passing `props.autoRepeat.enabled` would read the signal - * once at render time and never update, whereas `props.autoRepeat.enabled()` - * stays subscribed inside the child's effects and event handlers. - * - * Props are grouped by the section they belong to rather than flattened. There - * are seventeen of them, and a flat list of unrelated signals on one surface - * makes it hard to see which controls a given setter actually drives. + * Advanced settings overlay: auto-repeat, answer mode, colour and theme. Props + * are accessors per Solid convention — a plain value is read once at render and + * never updates — and grouped by section. */ /** How the answer to a finished session is collected. */ @@ -95,18 +84,9 @@ const LIGHT_NAMES: Record = { export function AdvancedSettings(props: AdvancedSettingsProps): JSX.Element { /** - * Keeps Tab inside the panel while the overlay is open. - * - * This lived in `App.tsx` for as long as the panel did, reaching through an - * `overlayRef` callback into DOM the component itself rendered. That made the - * parent own the focus behaviour of markup it does not control, and it needed - * a `createEffect` plus `onCleanup` to compensate for not knowing when the - * panel mounts. The component already knows, so `onMount` is the honest - * shape and the parent is free of both the ref and the effect. - * - * `document.activeElement` is read rather than an index into `focusable`, - * because the browser moves focus with the keyboard and a mouse independently - * of the order the elements were listed in. + * Keep Tab inside the panel while open. Read `document.activeElement` + * rather than an index into `focusable`, since focus moves independently of + * element order. */ let overlayRef: HTMLDivElement | undefined; onMount(() => { diff --git a/src/components/AnswerNumbers.tsx b/src/components/AnswerNumbers.tsx index 3b7d940..16639eb 100644 --- a/src/components/AnswerNumbers.tsx +++ b/src/components/AnswerNumbers.tsx @@ -1,25 +1,10 @@ import { For, type JSX, Show } from "solid-js"; /** - * The revealed number series, listed in order. - * - * Written out in full in both answer modes on the end screen. The modes differ - * in how the answer is collected, but once the answer exists the list is - * identical — same markup, same gate, same place in the layout — so a change to - * it (a row class, a separator, a count) had to be made twice with no test - * between the copies. - * - * It deliberately lives *inside* the answer body rather than beside it: that - * body is the flex column that centres the card, so hoisting this out of it - * would move it in the layout. - * - * `visible` is an accessor, not a boolean, and the gate is a `` rather - * than a bare ternary over the prop. A plain boolean is read once when the - * component's body runs, and the body is not itself reactive, so the gate would - * be frozen at whatever it was when the end screen mounted — here, always - * `false`. The list then never appeared, however many times "Show numbers" was - * pressed: only the button's label changed. `numbers` is an accessor for the - * same reason, which is why `` already worked. + * The revealed number series, listed in order. Lives inside the answer body so + * the flex layout centres it. `visible` and `numbers` are accessors and the + * gate is ``: a plain value would be read once at mount and the list + * would never appear. */ export function AnswerNumbers(props: { visible: () => boolean; diff --git a/src/components/SessionEndDetails.tsx b/src/components/SessionEndDetails.tsx index 905178d..8fc4367 100644 --- a/src/components/SessionEndDetails.tsx +++ b/src/components/SessionEndDetails.tsx @@ -2,29 +2,8 @@ import type { JSX } from "solid-js"; import { AutoRepeatBar } from "./AutoRepeatBar"; /** - * The shared tail of the end screen: the auto-repeat countdown and the footer. - * - * The two answer modes differ only in how the answer is *collected* — a reveal - * button versus a typed input — but this part was duplicated verbatim between - * them. That mattered because the copies could drift: the type mode's footer - * gained a Validate button and a stricter condition on the numbers toggle - * while the reveal mode's stayed as it was, and nothing failed when they - * disagreed. - * - * The revealed number list is deliberately *not* here. It sits inside the - * answer body, after the collected answer, and is centred by that body's flex - * layout — so it is mode-specific markup with its own condition rather than - * shared content that merely looks shared. - * - * `footerLead` is the one part of the footer that genuinely differs per mode, - * so it is passed in rather than branching on the mode inside this component. - * - * Props are accessors for the same reason as `AdvancedSettings`: a plain value - * would be read once at render and never update. `footerLead` is a thunk for - * that same reason — passing an already-evaluated `JSX.Element` left its - * reactivity to how the compiler happened to wrap the expression, which differed - * between the two modes' call sites (a fragment versus a ternary) and is exactly - * the trap `AnswerNumbers` fell into. + * Shared tail of the end screen: auto-repeat countdown and footer. Props are + * accessors (and `footerLead` a thunk) so they stay reactive after mount. */ export interface SessionEndDetailsProps { autoRepeatEnabled: () => boolean; diff --git a/src/runtime/browser.ts b/src/runtime/browser.ts index cb2b5ba..2dfd40b 100644 --- a/src/runtime/browser.ts +++ b/src/runtime/browser.ts @@ -105,14 +105,9 @@ let soundEnabled = loadSoundEnabled(); let hasLoggedWasmPlannerReady = false; let hasLoggedWasmPlannerFallback = false; /** - * What audio has actually done so far: nothing yet, a sound played, or a - * playback attempt failed. `getAudioStatus` reports this instead of a static - * capability guess, so it can never claim "ready" for a dead device. - * - * A later success clears a failure, so a device that comes back — a headset - * that reconnects, an audio server that finishes starting — stops being - * reported as broken without a reload. That is the same self-healing the - * native worker does, and it is why there is no one-way latch here. + * What audio has actually done so far. `getAudioStatus` reports this instead + * of a static capability guess; a later success clears a failure so a device + * that comes back is reported as working again, matching the native worker. */ let audioState: "not-started" | "ready" | "failed" = "not-started"; @@ -167,16 +162,9 @@ function ensureAudioContext(): AudioContext | null { } /** - * Unlock the graph from inside a user gesture. - * - * The autoplay policy only accepts a *direct* user gesture, and the Start - * click has already been spent by the time anything asynchronous reaches - * audio: the UI awaits a fullscreen transition first, so a resume attempted - * from the session start is outside the gesture it came from. This listener is - * the fix, because `pointerdown` and `keydown` fire synchronously with the - * gesture — the one thing the policy asks for. It stays registered for the life - * of the page, since an engine may suspend the context again at any time (a - * backgrounded tab, or any audio interruption on iOS). + * Unlock the graph from inside a direct user gesture. The Start click's async + * work happens after a fullscreen await, so a `pointerdown`/`keydown` listener + * is required. It stays registered because engines may re-suspend the context. */ function unlockAudio(): void { const ctx = ensureAudioContext(); @@ -353,22 +341,9 @@ function addListener( } /** - * Abandon any pending auto-repeat restart. - * - * Four call sites need this exact teardown — starting a new session, the - * hidden-tab abort, stopping, and the explicit cancel control — and each had - * its own copy of the block. They have to stay in step, which is the same - * "one algorithm, several copies, no test between them" shape as the planner - * sign divergence this file used to have. - * - * Clearing the handle *is* the cancellation. The block used to set a separate - * `cancelled` flag first, but it was written in the same breath as the nulling, - * so every reader's `pendingAutoRepeat?.cancelled` was already false by the - * time it could be observed — dead state that read as if a timer callback had - * some other way of surviving. Nulling makes every existing guard see the - * teardown, so the flag bought nothing. - * - * A no-op when nothing is pending, so callers do not need to guard. + * Abandon any pending auto-repeat restart. Clearing the handle *is* the + * cancellation: every existing guard reads `pendingAutoRepeat`, so nulling it + * makes them all see the teardown. No-op when nothing is pending. */ function cancelPendingAutoRepeat(): void { if (!pendingAutoRepeat) { @@ -489,15 +464,9 @@ function errorName(error: unknown): string { } /** - * Record a playback failure. - * - * Deliberately has neither of the two exemptions the media-element version - * needed. There is no "already proven working" guard, because one early - * success used to silence every later failure — including a device that died - * mid-session. And there is no `AbortError` exemption, because that rejection - * was an artefact of cutting by seeking a media element, which is the whole - * reason this is Web Audio now. What survives is the autoplay policy, which is - * a state rather than a fault, and clears on the next gesture. + * Record a playback failure. No "already proven working" guard and no + * `AbortError` exemption: a genuine failure is always reported. Only + * `NotAllowedError` — the autoplay policy, a state not a fault — is ignored. */ function recordAudioFailure(error: unknown): void { if (errorName(error) === "NotAllowedError") { @@ -515,15 +484,10 @@ function silenceAudio(): void { } /** - * Prime the graph ahead of the first flash: bring the context up if a gesture - * is still live, and start fetching and decoding the clips so the beep lands - * on time instead of stalling on first use. - * - * It says nothing about availability on purpose. The version this replaces - * marked the device ready from a muted play-through that was rewound straight - * away, so one early "success" proved a device that was never heard at all. - * Decoding shows what it actually shows — that the bytes are there — and - * `audioState` moves on the first real play. + * Prime the graph ahead of the first flash: resume the context within a live + * gesture and start decoding clips. Says nothing about availability — decoding + * proves only that the bytes are there; `audioState` moves on the first real + * play. */ function warmupAudio(): void { if (!soundEnabled) { @@ -682,15 +646,9 @@ function asFiniteNumber(value: unknown): number | null { } /** - * Append an event, refusing a timestamp that would collide with the previous - * one. - * - * The driver chains fixed intervals, so two events sharing an `at` would fire in - * the same turn of the event loop and a flashed number would never be seen. - * Rust's schedule guarantees a minimum spacing (invariant I2 in `core/timing.rs`), - * but nothing in TypeScript enforced it, and a zero-delay step from a foreign or - * corrupt module would otherwise slip through. Rejecting the plan here falls - * back to the local planner, which cannot produce a collision. + * Append an event, refusing a timestamp colliding with the previous one: two + * events at the same `at` would fire in one turn and a flash would be unseen. + * Rejecting such a plan falls back to the local planner. */ function pushEvent( events: PlannedDriverEvent[], @@ -1068,18 +1026,10 @@ async function startSessionImpl( events = local; } - // Chained single-timer driver: at most one pending timeout, so timer - // bookkeeping stays O(1) and stopping clears a single handle. - // - // Each event is scheduled the fixed interval after the previous one, - // *not* against an absolute grid. Anchoring to absolute times makes the - // previous event's delivery lateness eat into this one's window: the - // countdown's paint tail and the countdown->flashing view transition - // delay the first show, which then shortened the first number's exposure - // by the same amount, so it visibly flashed for less than the rest. - // Fixed intervals make exposure exact by construction: a late callback - // can only delay when an event lands, never shorten how long the - // previous one stays on screen. + // Chained single-timer driver: at most one pending timeout. Schedule each + // event at a fixed interval after the previous one, not on an absolute + // grid — a late delivery can delay an event but never shorten the + // previous number's exposure. const previousAtMs = (pos: number): number => pos === 0 ? 0 : events[pos - 1].at; const fireEvent = (pos: number): void => { @@ -1174,17 +1124,9 @@ export function validateAnswer( } /** - * A session abandoned while the tab is hidden must not run on forever. - * - * The driver chains fixed intervals, so a late delivery stretches the session - * rather than dropping stimulus. Chrome throttles a deeply-nested chained timer - * to one wake per minute once a page has been hidden past five minutes, which - * would leave a 10,000-number session crawling for hours with nothing to show - * for it. Interrupting the session at the boundary keeps that case finite and - * tells the user what happened, instead of a screen that appears stuck. - * - * The threshold is a product decision, not a correctness one: the schedule - * itself never needed it. + * A session abandoned while the tab is hidden must not run on forever. Browsers + * throttle deeply-nested timers in hidden pages to one wake per minute, which + * would stretch a long session over hours; abort at the boundary instead. */ const MAX_HIDDEN_SESSION_MS = 30_000; let hiddenAtMs: number | null = null; @@ -1376,29 +1318,9 @@ export const browserRuntime: Runtime = { }, }; -// --------------------------------------------------------------------------- -// Test seams -// -// Internals exported purely so tests can drive them without a full session. -// They are not part of the app's API: nothing in `src/` outside this module and -// the test suite reads them. -// -// `planStepsToEvents` — the WASM-plan-to-driver-event converter, a pure -// function with no ambient state, declared `export` where it is defined. -// -// `validateAnswer` — the answer-grading entry point, exercised directly -// because it is where the answer key comes from. -// -// `__test_clearSessionTimers` / `__test_setCompletedSession` — thin wrappers -// around module-private state. Named with the `__test_` prefix so it is -// obvious at the call site that this is a seam, not API. -// -// The pure planner that mirrors the Rust core — `normalizeSessionConfig`, -// `normalizeAutoRepeat`, `maxTotalForDigits`, `generateNumber`, -// `deterministicFallback`, `generateLocalPlan`, `parseProvidedAnswerText` and -// `parseWithNumberFallback` — now lives in `./localPlanner`, which is where the -// wasm-parity suites reach it. -// --------------------------------------------------------------------------- +// Test seams: exported only so tests can drive internals without a full +// session. `planStepsToEvents` and `validateAnswer` are pure entry points; +// `__test_*` names mark wrappers around module-private state. /** Simulate a driver timer firing, so `clearSessionTimers` can be unit-tested. */ export function __test_clearSessionTimers(session: { diff --git a/src/runtime/index.ts b/src/runtime/index.ts index 62bc675..9eadc69 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -1,16 +1,7 @@ /** - * Runtime abstraction layer for Flashspan. - * - * This module defines the platform-agnostic runtime interface that both - * desktop (Tauri) and browser (WASM) runtimes implement. The UI depends - * only on this interface, not on platform-specific APIs. - * - * Responsibilities: - * - Manage session lifecycle (start, stop, answer submission) - * - Emit session events (countdown, show, clear, complete) - * - Handle app settings (color scheme, theme, sound) - * - Coordinate with audio playback and fullscreen - * - Bridge deterministic core logic with platform-specific effects + * Platform-agnostic runtime interface implemented by both the Tauri and + * browser backends; the UI depends only on this module. Covers session + * lifecycle, events, settings, audio/fullscreen coordination and grading. */ // Re-export every runtime type, so `./runtime` is the one import the UI needs. diff --git a/src/runtime/localPlanner.ts b/src/runtime/localPlanner.ts index 89f507a..e55d025 100644 --- a/src/runtime/localPlanner.ts +++ b/src/runtime/localPlanner.ts @@ -1,16 +1,7 @@ /** - * The browser's local planner: the TypeScript mirror of the Rust core. - * - * Every value this module produces must agree with `src-tauri/src/core` value - * for value, because it is the *only* planner when the WASM bridge is - * unavailable. The wasm-parity suites assert that agreement against the real - * Rust core (see `wasmParity.test.ts`), so the functions here are exported where - * they are defined rather than wrapped in a seam. - * - * It is deliberately pure: no timers, DOM, storage or Web Audio. The mixed - * browser runtime that drives a session lives in `browser.ts` and imports what - * it needs from here; keeping the two apart makes the "mirror of Rust" boundary - * explicit and lets this half be tested without the driver machinery. + * The browser's local planner: a pure TypeScript mirror of `src-tauri/src/core`. + * It is the only planner when WASM is unavailable, so parity with Rust is + * enforced by `wasmParity.test.ts`. No timers, DOM, storage or Web Audio here. */ import type { @@ -188,31 +179,10 @@ export function generateNumber( } /** - * Deterministic replacement for a generated value that equals the previous one: - * rotate the magnitude one step inside its own digit-width domain. - * - * This mirrors `next_distinct_value` in `core/engine.rs` and is not free to - * differ from it. The JS planner runs whenever the WASM bridge is unavailable, - * so a disagreement means the browser and the desktop produce different number - * sequences for the same config — and a different sign on a flash — under a - * session the user configured identically. - * - * Two rules from the Rust original, both of which this previously got wrong: - * - * 1. The sign follows the **previous** value. A negative predecessor stays - * negative and a positive one stays positive. The old form returned - * `Math.abs(lastVal)` for any negative predecessor, which both dropped the - * sign *and* skipped the rotation, so it disagreed with Rust on magnitude as - * well as sign. - * 2. A negative result survives only while the running sum can still fund it. - * The old form returned `-next` for *any* positive predecessor whenever - * negatives were enabled, so a positive duplicate became a negative. - * - * Together those meant that whenever a session allowed negatives — the only - * configuration where the sign can differ — this function disagreed with the - * planner that actually ships in the WASM bundle on every reachable input. - * With negatives disabled the result is always positive on both sides, which - * is why the parity corpus never caught it. + * Deterministic replacement for a repeat: rotate the magnitude one step inside + * its digit-width domain, mirroring `next_distinct_value` in `core/engine.rs`. + * The sign follows the **previous** value, and a negative result survives only + * while the running sum can fund it — both are parity requirements with Rust. */ export function deterministicFallback( lastPayload: string | null, @@ -254,18 +224,9 @@ export function deterministicFallback( } /** - * The fallback session plan, generated once up front when no Rust plan is - * available (the WASM bridge failed to load, or its steps did not validate). - * - * The values are generated eagerly rather than lazily at fire time: the driver's - * fixed-interval chaining means nothing is ever dropped, so the full sequence is - * always shown, and grading plus the answer reveal must both be able to see it. - * Generating lazily could only ever know a partial sum. - * - * Callers build this plan exactly once and reuse it for both the flashed events - * and the stored `plannedNumbers`/`plannedSum`. Building it twice produced two - * independent random sequences, so the browser flashed one set of numbers and - * then graded against another. + * Fallback plan when no Rust plan is available. Generated eagerly so grading + * and the reveal see the full sequence, and built exactly once — a second call + * would produce a different sequence from the one flashed. */ export function generateLocalPlan(config: SessionConfigEffective): { numbers: number[]; diff --git a/src/runtime/types.ts b/src/runtime/types.ts index 03a7183..c127139 100644 --- a/src/runtime/types.ts +++ b/src/runtime/types.ts @@ -14,17 +14,9 @@ export type ColorScheme = | "sage"; /** - * The colour schemes the picker offers, in display order. - * - * Declared once, next to the `ColorScheme` union it enumerates. The union used - * to be repeated twice more — as a `const` array in the settings panel and as a - * six-way inline comparison in the settings loader — so adding a scheme to the - * type without updating both left the picker without the new option and the - * loader silently resetting a saved preference to the default. - * - * Both drift directions are compile errors now, by different mechanisms: - * `satisfies` rejects a scheme the union does not know about, and - * `_AllSchemesListed` below rejects a union member the list has forgotten. + * Colour schemes the picker offers, in display order. `satisfies` and + * `_AllSchemesListed` make both drift directions against `ColorScheme` a + * compile error. */ export const COLOR_SCHEMES = [ "ocean",