From 4287b68bcf3d9fa0e7352b077b7d10c28d79d565 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 10:39:39 -0400 Subject: [PATCH 01/11] Let CI collect the Python tests, and cover the timebase it gates on Two red checks, neither caused by recent work, both red on main since at least #45. bench-python was not a failing test. conftest decides what to ignore by importing each test module and seeing whether it complains about a missing dependency, and it caught ImportError and Exception. pytest.importorskip raises Skipped, which derives from BaseException, so it went straight past both handlers and out of conftest -- taking the whole collection with it. CI has been running NONE of the 1057 ingest tests since, behind a single red job that read like one broken benchmark. Every test written for the import and alignment work has only ever run locally. The regression test for it needed care of its own. Written the obvious way it does not fail when the bug returns, it SKIPS -- the escaping Skipped marks the test itself skipped, so a green run would mean nothing. It catches BaseException and converts an escape into an assertion failure. Verified in both directions: fails with the fix removed, passes with it. lint_test is a 100% coverage gate on nativeAudioTimebase.ts, which had drifted to 95.7%. The uncovered code was real and unexercised: the game's getLoadedStemRoles, and on the desktop side warmUp (the whole reason a first playback is not a cold start), loadPackAudio, and the pack branch of a device switch. Now covered by tests that assert the behaviour rather than merely executing the lines -- including that a warmUp failure is survivable, since the first real load is supposed to init the engine anyway. One local-only failure is left and deliberately untouched: test_model_upgrade_gate_snapshot_reports_missing_external_gates reads the repo's real benchmark evidence, so it fails on a machine where MUSDB has been run and passes on a clean checkout. Not a CI failure, but it will fail for anyone who runs that benchmark, and isolating it to a temp evidence root would be the fix. Co-Authored-By: Claude Opus 5 --- .../desktop/tests/nativeAudioTimebase.test.ts | 151 ++++++++++++++++++ apps/game/tests/nativeAudioTimebase.test.ts | 35 ++++ python/ingest/tests/conftest.py | 9 ++ .../ingest/tests/test_conftest_collection.py | 75 +++++++++ 4 files changed, 270 insertions(+) create mode 100644 python/ingest/tests/test_conftest_collection.py diff --git a/apps/desktop/tests/nativeAudioTimebase.test.ts b/apps/desktop/tests/nativeAudioTimebase.test.ts index af50b85b..10a302c6 100644 --- a/apps/desktop/tests/nativeAudioTimebase.test.ts +++ b/apps/desktop/tests/nativeAudioTimebase.test.ts @@ -1366,4 +1366,155 @@ describe("NativeAudioTimebase", () => { (tb as unknown as { _lastOutputBufferFrames: number | null })._lastOutputBufferFrames = 256; expect(tb.getOutputLatencySec()).toBeUndefined(); }); + // warmUp exists so the FIRST playback isn't a cold start -- without it the + // engine only really engaged on a second load, which is where the "select an + // instrument first" workaround came from. + it("warmUp starts the output stream ahead of the first real load", async () => { + const invoke = vi.fn(async () => null); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + await tb.warmUp(); + + expect(invoke).toHaveBeenCalledWith("native_audio_warm_up"); + }); + + it("warmUp failing is not an error -- the first load still inits the engine", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_warm_up") throw new Error("no output device yet"); + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + await expect(tb.warmUp()).resolves.toBeUndefined(); + }); + + it("loadPackAudio reports duration and roles, and applies runtime settings", async () => { + const invoke = vi.fn(async (cmd: string, payload?: Record) => { + if (cmd === "native_audio_load_pack_audio") { + expect(payload?.containerPath).toBe("C:/songs/demo.feedpak"); + expect(payload?.role).toBe("keys"); + return { mime: "audio/ogg", duration_sec: 31.5, roles: ["keys", "bass"] }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + tb.setPlaybackRate(0.75); + + const out = await tb.loadPackAudio("C:/songs/demo.feedpak", "keys"); + expect(out).toEqual({ durationSec: 31.5, roles: ["keys", "bass"] }); + expect(invoke).toHaveBeenCalledWith("native_audio_set_playback_rate", { rate: 0.75 }); + }); + + it("loadPackAudio falls back to the sentinel when duration is unusable", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_pack_audio") { + return { mime: "audio/ogg", duration_sec: 0, roles: [] }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + const out = await tb.loadPackAudio("C:/songs/odd.feedpak", null); + expect(out.durationSec).toBeGreaterThan(0); + expect(out.roles).toEqual([]); + }); + + it("loadPackAudio treats missing roles as none rather than undefined", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_pack_audio") { + return { mime: "audio/ogg", duration_sec: 5 }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + const out = await tb.loadPackAudio("C:/songs/legacy.feedpak", null); + expect(out.roles).toEqual([]); + }); + + // Switching device has to re-load whatever was last loaded, and a pack is + // one of the three things that can be. + it("setOutputDevice reloads the last pack when that is what was playing", async () => { + const calls: string[] = []; + const invoke = vi.fn(async (cmd: string) => { + calls.push(cmd); + if (cmd === "native_audio_load_pack_audio") { + return { mime: "audio/ogg", duration_sec: 8, roles: ["keys"] }; + } + if (cmd === "native_audio_get_state") return null; + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + await tb.loadPackAudio("C:/songs/demo.feedpak", "keys"); + + calls.length = 0; + await tb.setOutputDevice({ name: "Headphones", channels: 2, sample_rate_hz: 48_000 }); + expect(calls).toContain("native_audio_load_pack_audio"); + }); + + it("setOutputDevice before any load just persists the choice", async () => { + const calls: string[] = []; + const invoke = vi.fn(async (cmd: string) => { + calls.push(cmd); + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + await tb.setOutputDevice({ name: "Headphones", channels: 2, sample_rate_hz: 48_000 }); + + expect(calls).not.toContain("native_audio_load_pack_audio"); + expect(calls).not.toContain("native_audio_load_auralsong_audio"); + }); + it("loadPackAudio uses the sentinel when the decoder omits duration entirely", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_pack_audio") { + // No duration_sec field at all, as opposed to a zero or a NaN. + return { mime: "audio/ogg", roles: ["keys"] }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + const out = await tb.loadPackAudio("C:/songs/nodur.feedpak", "keys"); + expect(out.durationSec).toBe(24 * 60 * 60); + }); + + it("loadPackAudio falls back to the sentinel when the duration cache is cleared during apply", async () => { + let tbRef: { loadedDurationSec: number | null } | null = null; + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_pack_audio") { + return { mime: "audio/ogg", duration_sec: 19, roles: ["keys"] }; + } + if (cmd === "native_audio_set_playback_rate" && tbRef) { + tbRef.loadedDurationSec = null; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + tbRef = tb as unknown as { loadedDurationSec: number | null }; + + const out = await tb.loadPackAudio("C:/songs/cleared.feedpak", "keys"); + expect(out.durationSec).toBe(24 * 60 * 60); + }); }); diff --git a/apps/game/tests/nativeAudioTimebase.test.ts b/apps/game/tests/nativeAudioTimebase.test.ts index 4d7bc100..e65c1b58 100644 --- a/apps/game/tests/nativeAudioTimebase.test.ts +++ b/apps/game/tests/nativeAudioTimebase.test.ts @@ -1365,4 +1365,39 @@ describe("NativeAudioTimebase", () => { (tb as unknown as { _lastOutputBufferFrames: number | null })._lastOutputBufferFrames = 256; expect(tb.getOutputLatencySec()).toBeUndefined(); }); + // The per-track mixer reads these to build its channel strips, so an engine + // that reports no roles has to come back as an empty list rather than + // something the UI will try to iterate. + it("exposes the stem roles the engine loaded", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_auralsong_audio") { + return { mime: "audio/ogg", duration_sec: 12, roles: ["keys", "bass", "drums"] }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + expect(tb.getLoadedStemRoles()).toEqual([]); + + await tb.loadFromAuralSong("C:/songs/demo.auralsong"); + expect(tb.getLoadedStemRoles()).toEqual(["keys", "bass", "drums"]); + }); + + it("reports no stem roles for a single-stem load that omits them", async () => { + const invoke = vi.fn(async (cmd: string) => { + if (cmd === "native_audio_load_auralsong_audio") { + // A legacy/single-stem pack: the field is simply absent. + return { mime: "audio/ogg", duration_sec: 12 }; + } + return null; + }); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + + const { NativeAudioTimebase } = await import("../src/nativeAudioTimebase"); + const tb = new NativeAudioTimebase(); + await tb.loadFromAuralSong("C:/songs/legacy.auralsong"); + expect(tb.getLoadedStemRoles()).toEqual([]); + }); }); diff --git a/python/ingest/tests/conftest.py b/python/ingest/tests/conftest.py index 7a2cd6cf..eb009d4e 100644 --- a/python/ingest/tests/conftest.py +++ b/python/ingest/tests/conftest.py @@ -54,6 +54,15 @@ def _module_imports(path: Path) -> bool: return True except (ImportError, ModuleNotFoundError): return False + except pytest.skip.Exception: + # A module-scope pytest.importorskip("...") for a dependency that is + # not installed. It means exactly what an ImportError here means, but + # it derives from BaseException rather than Exception, so it used to + # sail past both of these handlers and out of conftest entirely -- + # taking the whole collection with it. CI has been skipping every + # ingest test since, while reporting a single red job that looked like + # one broken benchmark. + return False except Exception: # noqa: BLE001 -- a non-import collection error should surface return True diff --git a/python/ingest/tests/test_conftest_collection.py b/python/ingest/tests/test_conftest_collection.py new file mode 100644 index 00000000..9dcc0995 --- /dev/null +++ b/python/ingest/tests/test_conftest_collection.py @@ -0,0 +1,75 @@ +"""The collection probe must survive the modules it probes. + +``conftest`` decides which test files to ignore by importing each one and +seeing whether it blows up on a missing dependency. That probe has to catch +every way a module can say "not here", and one of them is not an exception in +the ordinary sense: ``pytest.importorskip`` raises ``Skipped``, which derives +from ``BaseException``. + +It escaped the probe's handlers, propagated out of conftest, and took the +entire collection with it -- so CI ran none of the ingest tests at all while +showing one red job that read like a single broken benchmark. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +_CONFTEST = Path(__file__).with_name("conftest.py") + + +def _load_conftest(): + spec = importlib.util.spec_from_file_location("_conftest_under_test", _CONFTEST) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _probe(path: Path) -> bool: + """Call the probe, turning anything it lets escape into a failure. + + This has to catch BaseException, not Exception, and the reason is the whole + point of the test: the bug was a BaseException subclass escaping. Letting + it propagate here would mark THIS test skipped rather than failed -- a + regression test that quietly goes green is worth less than no test, and is + how the original bug survived in the first place. + """ + try: + return _load_conftest()._module_imports(path) + except BaseException as exc: # noqa: BLE001 + raise AssertionError( + f"_module_imports let {type(exc).__name__} escape; conftest would " + "have died and taken the whole collection with it" + ) from exc + + +def test_module_scope_importorskip_is_ignored_not_fatal(tmp_path): + """The exact shape that broke it: importorskip at module scope.""" + mod = tmp_path / "test_needs_absent_dep.py" + mod.write_text( + "import pytest\n" + "pytest.importorskip('a_module_that_is_not_installed_anywhere')\n", + encoding="utf-8", + ) + assert _probe(mod) is False + + +def test_a_missing_import_is_ignored(tmp_path): + mod = tmp_path / "test_plain_missing.py" + mod.write_text("import a_module_that_is_not_installed_anywhere\n", encoding="utf-8") + assert _probe(mod) is False + + +def test_a_real_error_still_surfaces(tmp_path): + """Ignoring a broken test file would hide it, so only import problems count.""" + mod = tmp_path / "test_broken.py" + mod.write_text("raise ValueError('this module is genuinely broken')\n", encoding="utf-8") + assert _probe(mod) is True + + +def test_a_healthy_module_is_collected(tmp_path): + mod = tmp_path / "test_fine.py" + mod.write_text("def test_ok():\n assert True\n", encoding="utf-8") + assert _probe(mod) is True From 96e39d617f4cc02061ac17b8db8af1ef4893c332 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 10:47:38 -0400 Subject: [PATCH 02/11] Fix the import casing Linux sees, and unpin a rename that was not a regression Two more reds, both older than this branch. The casing one is the same bug that was fixed in main.ts and missed one file over: the test imported "../src/auralsongAudioLoader" while git tracks auralSongAudioLoader.ts. Windows resolves it either way, so it can only fail on the CI runner -- which is exactly why it survived. Fixed everywhere the lowercase spelling appeared rather than just at the one line CI named. The other is a source-level pin that broke on a rename. It required the overlay's result to be bound to `melodicTracks`, and a fingering stage was later inserted between the overlay and the final tracks, so that binding became `refinedMelodicTracks`. The behaviour the pin guards was not just intact but extended; only the name moved. It now matches the binding by suffix and, more to the point, checks the bound value actually reaches the final melodicTracks. The old pin asserted the call happened and would have passed just as happily if the result were thrown away -- which is the regression it existed to catch. Full TS suite: 1214 passed, 3 skipped. Co-Authored-By: Claude Opus 5 --- apps/game/tests/auralSongAudioLoader.test.ts | 4 ++-- apps/game/tests/refinementOverlay.test.ts | 21 +++++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/apps/game/tests/auralSongAudioLoader.test.ts b/apps/game/tests/auralSongAudioLoader.test.ts index 347db720..cb0783fc 100644 --- a/apps/game/tests/auralSongAudioLoader.test.ts +++ b/apps/game/tests/auralSongAudioLoader.test.ts @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { loadAuralSongAudioIntoTransport, type AuralSongAudioLoadTransport } from "../src/auralsongAudioLoader"; +import { loadAuralSongAudioIntoTransport, type AuralSongAudioLoadTransport } from "../src/auralSongAudioLoader"; import type { TransportTimebase } from "../src/audioBackend"; function makeTimebase(withDirectLoad: boolean): TransportTimebase { @@ -44,7 +44,7 @@ function makeTransport(): AuralSongAudioLoadTransport & { }; } -describe("auralsongAudioLoader", () => { +describe("auralSongAudioLoader", () => { it("uses direct load when timebase supports loadFromAuralSong", async () => { const transport = makeTransport(); const readAuralSongAudio = vi.fn(async () => ({ mime: "audio/wav", bytes: [1, 2, 3] })); diff --git a/apps/game/tests/refinementOverlay.test.ts b/apps/game/tests/refinementOverlay.test.ts index 3be1d92b..668b719e 100644 --- a/apps/game/tests/refinementOverlay.test.ts +++ b/apps/game/tests/refinementOverlay.test.ts @@ -144,9 +144,24 @@ describe("main.ts wiring (source-level pin)", () => { it("songChartLoader calls loadRefinementsForRoles + applies overlay into melodicTracks", () => { // Compose-and-return shape (Phase 2.T) — caller assigns the result. - expect(chartSrc).toMatch( - /(?:const|let)\s+melodicTracks\s*=\s*applyRefinementsToMelodicTracks\s*\(\s*baseMelodicTracks\s*,\s*refinements\s*\)/ - ); + // + // The binding is matched by suffix rather than by exact name. It was + // pinned to `melodicTracks` and a fingering stage was later inserted + // between the overlay and the final tracks, so the overlay's result became + // `refinedMelodicTracks` -- a rename that broke the pin while the + // behaviour it guards was not just intact but extended. + const overlayBinding = + /(?:const|let)\s+(\w*[Mm]elodicTracks)\s*=\s*applyRefinementsToMelodicTracks\s*\(\s*baseMelodicTracks\s*,\s*refinements\s*\)/; + expect(chartSrc).toMatch(overlayBinding); + + // And the result has to actually go somewhere. The old pin checked only + // that the call happened and would have passed just as happily if its + // value were thrown away, which is the failure it existed to catch. + const bound = chartSrc.match(overlayBinding)?.[1] ?? ""; + expect(bound).toBeTruthy(); + const finalAssignment = chartSrc.indexOf("const melodicTracks ="); + expect(finalAssignment).toBeGreaterThan(-1); + expect(chartSrc.slice(finalAssignment, finalAssignment + 400)).toContain(bound); // The loader call must pass a warn callback so invalid files don't get // silently swallowed (they shouldn't be fatal, but they must surface). expect(chartSrc).toMatch( From 118b07af066d51934f3031a13f4ac0f6d29e4bd8 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 10:54:32 -0400 Subject: [PATCH 03/11] Clear the ruff errors the Python job could not reach before The lint step reports nine errors, and none of them could fail the build while collection was crashing ahead of it -- the job died before lint mattered. Fixing collection is what surfaced them. Two are mine: an ambiguous `l` as the loop variable in the correlation, now `lag`, which is what it actually is; and a pytest import left behind in the new conftest test. The rename is pure -- Schumann still measures 5.108s at 58.9x, unchanged to the digit. One is worth more than a lint waiver: in cli.py a loop variable named `field` shadowed the `dataclasses.field` imported at module scope. Harmless where it sits, since that function never needs the import, but it is the kind of thing that is only harmless until someone adds a line. The loop variable is `key` now. The rest are unused imports removed by ruff --fix. 81 tests pass across the touched modules; ruff is clean. Co-Authored-By: Claude Opus 5 --- python/ingest/scripts/refresh_drums_inplace.py | 1 - .../ingest/src/aural_ingest/algorithms/piano_playability.py | 4 ++-- python/ingest/src/aural_ingest/cli.py | 6 +++--- python/ingest/src/aural_ingest/render_align.py | 4 ++-- python/ingest/tests/test_conftest_collection.py | 1 - python/ingest/tests/test_import_dir_extension_rewrite.py | 1 - python/ingest/tests/test_piano_playability.py | 1 - python/ingest/tests/test_protected_stems.py | 1 - 8 files changed, 7 insertions(+), 12 deletions(-) diff --git a/python/ingest/scripts/refresh_drums_inplace.py b/python/ingest/scripts/refresh_drums_inplace.py index 17f441cf..6017c6a2 100644 --- a/python/ingest/scripts/refresh_drums_inplace.py +++ b/python/ingest/scripts/refresh_drums_inplace.py @@ -9,7 +9,6 @@ from __future__ import annotations import json -import sys import time from pathlib import Path diff --git a/python/ingest/src/aural_ingest/algorithms/piano_playability.py b/python/ingest/src/aural_ingest/algorithms/piano_playability.py index cb94717c..9de5b886 100644 --- a/python/ingest/src/aural_ingest/algorithms/piano_playability.py +++ b/python/ingest/src/aural_ingest/algorithms/piano_playability.py @@ -67,9 +67,9 @@ from __future__ import annotations from bisect import bisect_left -from dataclasses import dataclass, field, replace +from dataclasses import dataclass, replace from types import MappingProxyType -from typing import Any, Iterable, Mapping, Sequence +from typing import Any, Mapping, Sequence from aural_ingest.transcription import MelodicNote diff --git a/python/ingest/src/aural_ingest/cli.py b/python/ingest/src/aural_ingest/cli.py index d85254b8..3b9cc813 100644 --- a/python/ingest/src/aural_ingest/cli.py +++ b/python/ingest/src/aural_ingest/cli.py @@ -4954,9 +4954,9 @@ def _runtime_note_payload_rejection(item: Any, index: int) -> str | None: instrument = item.get("instrument") if not isinstance(instrument, str) or not instrument.strip(): return f"{label}.instrument must be a non-empty string" - for field, upper in (("string", 8), ("fret", 36)): - if field in item and _json_int(item.get(field), lo=0, hi=upper) is None: - return f"{label}.{field} must be an integer in [0, {upper}] when present" + for key, upper in (("string", 8), ("fret", 36)): + if key in item and _json_int(item.get(key), lo=0, hi=upper) is None: + return f"{label}.{key} must be an integer in [0, {upper}] when present" return None diff --git a/python/ingest/src/aural_ingest/render_align.py b/python/ingest/src/aural_ingest/render_align.py index 6df10114..7991c5a9 100644 --- a/python/ingest/src/aural_ingest/render_align.py +++ b/python/ingest/src/aural_ingest/render_align.py @@ -107,8 +107,8 @@ def measure_lead_in( return Alignment(0.0, 0.0, False, "not enough onsets to correlate") max_lag = min(int(MAX_LEAD_SEC * _SR / _HOP), len(env) - 1) - corr = np.array([float(np.dot(env[l:], train[: len(train) - l])) - for l in range(max_lag)]) + corr = np.array([float(np.dot(env[lag:], train[: len(train) - lag])) + for lag in range(max_lag)]) # Strongest peak wins, with no preference for earlier candidates. # # Preferring the earliest near-tied peak looks like the right way to break diff --git a/python/ingest/tests/test_conftest_collection.py b/python/ingest/tests/test_conftest_collection.py index 9dcc0995..2183d7a4 100644 --- a/python/ingest/tests/test_conftest_collection.py +++ b/python/ingest/tests/test_conftest_collection.py @@ -15,7 +15,6 @@ import importlib.util from pathlib import Path -import pytest _CONFTEST = Path(__file__).with_name("conftest.py") diff --git a/python/ingest/tests/test_import_dir_extension_rewrite.py b/python/ingest/tests/test_import_dir_extension_rewrite.py index a28b7bdd..59e3e574 100644 --- a/python/ingest/tests/test_import_dir_extension_rewrite.py +++ b/python/ingest/tests/test_import_dir_extension_rewrite.py @@ -15,7 +15,6 @@ from __future__ import annotations -import shutil from pathlib import Path import pytest diff --git a/python/ingest/tests/test_piano_playability.py b/python/ingest/tests/test_piano_playability.py index 5a07b039..d88d25ec 100644 --- a/python/ingest/tests/test_piano_playability.py +++ b/python/ingest/tests/test_piano_playability.py @@ -1,5 +1,4 @@ from aural_ingest.algorithms.piano_playability import ( - DEFAULT_PLAYABILITY_CONFIG, BeatGrid, HarmonyContext, MotifConfig, diff --git a/python/ingest/tests/test_protected_stems.py b/python/ingest/tests/test_protected_stems.py index 036a2c89..2bd287b3 100644 --- a/python/ingest/tests/test_protected_stems.py +++ b/python/ingest/tests/test_protected_stems.py @@ -20,7 +20,6 @@ from pathlib import Path -import pytest from aural_ingest import cli as cli_mod From fabfa3166a5c463fbb853a99a952f5742e4ab86a Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 11:00:11 -0400 Subject: [PATCH 04/11] Build the provenance default the way 3.11 will accept Two test modules failed to import on the runner: ValueError: mutable default for field provenance is not allowed: use default_factory Python 3.12 accepts a mappingproxy as a dataclass default and 3.11 rejects it, so the bare `= MappingProxyType({})` imports fine on a 3.13 dev machine and raises at collection on the 3.11 runner. It has been that way since it was written on 2026-08-27 and nobody saw it, because CI was not collecting these tests at all -- the conftest crash meant the job died long before it got here. default_factory works on every version. Checked for the same pattern elsewhere; there is none. Co-Authored-By: Claude Opus 5 --- .../src/aural_ingest/algorithms/piano_playability.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/python/ingest/src/aural_ingest/algorithms/piano_playability.py b/python/ingest/src/aural_ingest/algorithms/piano_playability.py index 9de5b886..46b007f4 100644 --- a/python/ingest/src/aural_ingest/algorithms/piano_playability.py +++ b/python/ingest/src/aural_ingest/algorithms/piano_playability.py @@ -67,7 +67,7 @@ from __future__ import annotations from bisect import bisect_left -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from types import MappingProxyType from typing import Any, Mapping, Sequence @@ -974,7 +974,14 @@ class SalienceContext: beats: BeatGrid = BeatGrid() melody: frozenset[tuple[float, int]] = frozenset() motif: frozenset[tuple[float, int]] = frozenset() - provenance: Mapping[tuple[float, int], Sequence[str]] = MappingProxyType({}) + # default_factory, not a bare MappingProxyType({}). Python 3.12 accepts a + # mappingproxy as a dataclass default and 3.11 rejects it outright, so the + # bare form imports fine on a 3.13 dev machine and raises at collection on + # the 3.11 runner. Nobody saw it because CI was not collecting these tests + # at all. + provenance: Mapping[tuple[float, int], Sequence[str]] = field( + default_factory=lambda: MappingProxyType({}) + ) primary_source: str = "primary" From 702bf5239973662775ded68f8d62c257fbdc4e7f Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 11:22:59 -0400 Subject: [PATCH 05/11] Ramp the transport instead of switching it, and stop splicing the audio Two more sources of the stutter, both below the timing fix rather than in it. Pause set is_playing = false and the very next block was silence. Full amplitude to zero between one sample and the next is a step, and a step is a click -- one on stop and another on start, so two per note in Wait mode. The song now ramps over 5ms. The ramp is applied between the song and the piano so it moves only the recording: a live note is the player's finger on a key and has nothing to do with whether the transport is running. And the gate was seeking after it paused, forward to a fixed point just before the note. That splices two pieces of audio that were never adjacent -- about 45ms of the previous note's ring, elided. Silence would have made that free; a ringing chord does not, and these pieces are mostly ringing chords. The transport now stops where it stops and resumes from exactly there. The cost is the gap between key press and note going from ~20ms to ~65ms, because it is now the pause overrun rather than a park point we chose. That is the honest price of not cutting the audio, and it is well inside what felt wrong at 200ms. The engine's own test module has not compiled since the piano merge -- its runtime constructor was missing the piano field -- so cargo test was broken there and nothing noticed. Fixed, and the fade has five tests of its own, including that a settled transport is left alone rather than ramped toward a value it already holds. One existing test earned its keep immediately by catching a wrong resting gain: render_output_paused_is_silence. Co-Authored-By: Claude Opus 5 --- apps/game/src-tauri/src/native_audio.rs | 162 +++++++++++++++++++++++- apps/game/src/main.ts | 23 ++-- 2 files changed, 175 insertions(+), 10 deletions(-) diff --git a/apps/game/src-tauri/src/native_audio.rs b/apps/game/src-tauri/src/native_audio.rs index 06459835..befaeefd 100644 --- a/apps/game/src-tauri/src/native_audio.rs +++ b/apps/game/src-tauri/src/native_audio.rs @@ -114,6 +114,16 @@ struct EngineRuntimeState { /// Sampled piano, mixed over the song from the chart's own notes. piano: crate::piano::PianoEngine, + + /// Song gain, ramped rather than switched, so starting and stopping the + /// transport does not cut the waveform mid-cycle. + /// + /// Pause used to set `is_playing = false` and the very next block was + /// silence. From full amplitude to zero between one sample and the next is + /// a step, and a step is a click -- one on stop and another on start. In + /// Wait mode that happens at every single note, which is what the + /// remaining "stutter" turned out to be once the timing was right. + transport_gain: f32, } #[derive(Default)] @@ -500,6 +510,7 @@ impl NativeAudioHandle { playback_rate: 1.0, loop_region: None, time_stretcher: None, + transport_gain: 0.0, }; let snapshot = Arc::new(EngineSnapshot::default()); @@ -1041,6 +1052,61 @@ fn apply_engine_command( } } +/// Milliseconds of ramp on transport start and stop. +/// +/// Long enough to remove the step that makes the click, short enough that the +/// music still starts when the player's key does -- at five milliseconds the +/// ramp is under the ear's resolution for onset timing while being far longer +/// than the single-sample edge that caused the problem. +const TRANSPORT_FADE_MS: f32 = 5.0; + +/// Move `transport_gain` toward its target across this block, in place. +fn apply_transport_fade( + runtime: &mut EngineRuntimeState, + out: &mut [f32], + channels: usize, + sample_rate_hz: u32, +) { + let target: f32 = if runtime.is_playing { 1.0 } else { 0.0 }; + let frames = out.len() / channels.max(1); + if frames == 0 { + return; + } + + // Already settled: no per-sample work, and no rounding drift from ramping + // toward a value we are already at. + if (runtime.transport_gain - target).abs() <= f32::EPSILON { + if target < 1.0 { + out.fill(0.0); + } + return; + } + + let fade_frames = ((TRANSPORT_FADE_MS / 1000.0) * sample_rate_hz as f32).max(1.0); + let step = 1.0 / fade_frames; + + let mut gain = runtime.transport_gain; + for frame in 0..frames { + gain = if gain < target { + (gain + step).min(target) + } else { + (gain - step).max(target) + }; + // Settle rather than creep. 240 additions of 1/240 do not land exactly + // on the target in f32 -- the residue here measured 7.9e-7, which is + // inaudible but would keep this function doing per-sample work forever + // on a transport that has finished moving. + if (gain - target).abs() < 1e-5 { + gain = target; + } + let base = frame * channels; + for ch in 0..channels { + out[base + ch] *= gain; + } + } + runtime.transport_gain = gain; +} + fn drain_engine_commands( runtime: &mut EngineRuntimeState, commands: &mut Consumer, @@ -1254,7 +1320,10 @@ fn render_output_block(runtime: &mut EngineRuntimeState, out: &mut [f32], channe return 0; } - if !runtime.is_playing { + // Silence only once the fade has actually reached zero. Cutting here the + // moment `is_playing` clears is what made the click: the last block still + // held full-amplitude samples. + if !runtime.is_playing && runtime.transport_gain <= 0.0 { out.fill(0.0); return 0; } @@ -1396,6 +1465,12 @@ fn process_audio_callback_f32( render_output_block(runtime, out, engine_channels); + // Ramp the song in and out rather than switching it. Applied here, between + // the song and the piano, so it moves only the recording: a live note is + // the player's finger on a key and has nothing to do with whether the + // transport is running. + apply_transport_fade(runtime, out, engine_channels, sample_rate_hz); + // Over the song, not instead of it: the piano is a cue laid on top. Only // while the transport runs, or a paused song would keep playing its part. // Always, not only while the transport runs: a live note is the player @@ -1842,9 +1917,94 @@ mod tests { playback_rate: 1.0, loop_region: None, time_stretcher: None, + piano: crate::piano::PianoEngine::default(), + // Resting at zero, like a freshly built engine. The fade is applied + // by the block mixer above render_output_block, so this value never + // scales what these tests measure -- it only decides whether a + // paused render is already silent or still has a tail to emit. + transport_gain: 0.0, } } + // ---- transport fade ------------------------------------------------- + // + // The click these guard against is a step from full amplitude to zero + // between one sample and the next, on every pause and every resume. In + // Wait mode that is two per note. + + #[test] + fn pausing_ramps_the_song_down_instead_of_cutting_it() { + let mut rt = mk_runtime(48_000); + rt.transport_gain = 1.0; + rt.is_playing = false; + let mut out = vec![1.0f32; 64 * 2]; + + apply_transport_fade(&mut rt, &mut out, 2, 48_000); + + // Descending, and crucially the FIRST sample is not already zero -- + // that is the step that clicked. + assert!(out[0] > 0.0, "first sample cut to silence: {}", out[0]); + assert!(out[0] < 1.0, "no attenuation applied at all"); + assert!(out[out.len() - 2] < out[0], "gain did not descend"); + assert!(rt.transport_gain < 1.0); + } + + #[test] + fn resuming_ramps_the_song_up_from_silence() { + let mut rt = mk_runtime(48_000); + rt.transport_gain = 0.0; + rt.is_playing = true; + let mut out = vec![1.0f32; 64 * 2]; + + apply_transport_fade(&mut rt, &mut out, 2, 48_000); + + assert!(out[0] < out[out.len() - 2], "gain did not ascend"); + assert!(rt.transport_gain > 0.0); + } + + #[test] + fn a_settled_transport_leaves_the_block_alone() { + // Steady-state playback must not be touched sample by sample, and must + // not drift below unity through repeated ramping toward a value it is + // already at. + let mut rt = mk_runtime(48_000); + rt.transport_gain = 1.0; + rt.is_playing = true; + let mut out = vec![0.5f32; 32 * 2]; + + apply_transport_fade(&mut rt, &mut out, 2, 48_000); + + assert!(out.iter().all(|v| (*v - 0.5).abs() < f32::EPSILON)); + assert_eq!(rt.transport_gain, 1.0); + } + + #[test] + fn a_settled_pause_stays_silent() { + let mut rt = mk_runtime(48_000); + rt.transport_gain = 0.0; + rt.is_playing = false; + let mut out = vec![0.7f32; 32 * 2]; + + apply_transport_fade(&mut rt, &mut out, 2, 48_000); + + assert!(out.iter().all(|v| *v == 0.0), "paused output leaked audio"); + } + + #[test] + fn the_fade_completes_within_its_stated_duration() { + // 5ms at 48kHz is 240 frames; one block of that length must finish the + // ramp, or a pause would trail audibly instead of stopping. + let mut rt = mk_runtime(48_000); + rt.transport_gain = 1.0; + rt.is_playing = false; + let frames = ((TRANSPORT_FADE_MS / 1000.0) * 48_000.0) as usize; + let mut out = vec![1.0f32; frames * 2]; + + apply_transport_fade(&mut rt, &mut out, 2, 48_000); + + assert_eq!(rt.transport_gain, 0.0, "fade did not reach silence"); + } + #[test] fn golden_click_track_renders_without_time_drift() { // Impulses at known source frames; at rate 1 they must appear at the diff --git a/apps/game/src/main.ts b/apps/game/src/main.ts index 58245f1e..96e9803f 100644 --- a/apps/game/src/main.ts +++ b/apps/game/src/main.ts @@ -1461,15 +1461,16 @@ const GRACE_WINDOW_SEC = 0.05; // time. This has to clear the whole chain with room to spare. const GATE_LEAD_SEC = 0.12; -// Where the transport parks once it has stopped. +// The transport no longer parks anywhere -- it stops where it stops. // -// Deliberately much closer to the note than the gate, and reached by seeking -// FORWARD from wherever the overrun actually left the playhead. Parking back -// at the gate point would replay whatever was heard during the overrun -- -// the doubled attack this mode started out with. Parking here costs a small -// skip of pre-note audio instead, and keeps the gap between key press and -// note short enough to feel like playing rather than like latency. -const PARK_LEAD_SEC = 0.02; +// It used to seek to a fixed point just before the note, which bought a +// shorter key-press-to-note gap at the cost of eliding whatever lay between +// there and where the sound actually stopped. Silence would have made that +// free; a ringing chord does not, and these pieces are mostly ringing chords. +// +// The cost of dropping it is that the gap now equals the pause overrun, +// roughly 65ms rather than 20ms. That is the honest price of not cutting the +// audio, and it is well inside what felt wrong before. // How long after a note's onset a hit still counts as that note's, when Grace // is on and the transport is free-running. @@ -1726,7 +1727,11 @@ function learnGateTick(): void { learnHit.clear(); } else { transportController.pause(); - transportController.seek(g.t - PARK_LEAD_SEC); + // No seek. Pausing already leaves the playhead short of the note, and + // moving it afterwards splices two pieces of audio that were never + // adjacent -- roughly 45ms of the previous note's ring, elided. Under a + // sustain that reads as a stutter, which is the whole complaint. Resume + // continues from exactly where the sound stopped. learnWaiting = true; setAudioStatus(`Wait mode — play: ${g.pitches.map(learnNoteName).join(" + ")}`); } From 3544fbaf06c955ff41abbb0ba93cfa7c78d2f243 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 11:36:37 -0400 Subject: [PATCH 06/11] Stop the key press and the recording both playing the same note The remaining stutter is a flam, not a stutter. Wait mode holds the transport just short of a note and the player's key releases it, so the recording sounds that note a moment later -- while the sampler has already sounded it under their finger. Two attacks of one pitch, tens of milliseconds apart. The chart's own part is silenced in Wait mode for exactly this reason; the live half was not, so it kept doubling. A press that answers the gate no longer sounds through the sampler: the recording is about to play it, and that is the note the player asked to hear. Any other note still sounds -- nothing else is going to play it, and a wrong note the player cannot hear is a wrong note they cannot correct. That also explains why removing the park seek made it worse rather than better. The park was not the problem; the gap it left was. Widening it from 20ms to 65ms pulled the two attacks apart until they read as separate events instead of one thick one. The park is back, and the elision that worried me is covered now: the join happens while the transport is stopped and faded out, with a ramp either side, so what is skipped is the smooth middle of a decay. TS suite: 1214 passed, 3 skipped. Co-Authored-By: Claude Opus 5 --- apps/game/src/main.ts | 55 ++++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/apps/game/src/main.ts b/apps/game/src/main.ts index 96e9803f..2cf2d780 100644 --- a/apps/game/src/main.ts +++ b/apps/game/src/main.ts @@ -1461,16 +1461,15 @@ const GRACE_WINDOW_SEC = 0.05; // time. This has to clear the whole chain with room to spare. const GATE_LEAD_SEC = 0.12; -// The transport no longer parks anywhere -- it stops where it stops. +// Where the transport parks once it has stopped. // -// It used to seek to a fixed point just before the note, which bought a -// shorter key-press-to-note gap at the cost of eliding whatever lay between -// there and where the sound actually stopped. Silence would have made that -// free; a ringing chord does not, and these pieces are mostly ringing chords. -// -// The cost of dropping it is that the gap now equals the pause overrun, -// roughly 65ms rather than 20ms. That is the honest price of not cutting the -// audio, and it is well inside what felt wrong before. +// Close to the note, because this distance is how long the player waits to +// hear the note they just played, and that gap is the whole feel of the mode. +// The elision it causes -- from wherever the pause overrun left the playhead +// up to here -- is covered by the engine's fade: the join happens in silence +// with a ramp either side, so what is skipped is the smooth middle of a decay +// rather than an audible cut. +const PARK_LEAD_SEC = 0.02; // How long after a note's onset a hit still counts as that note's, when Grace // is on and the transport is free-running. @@ -1654,6 +1653,18 @@ function learnRegisterPlayed(pitch: number): void { } } +/** + * Is `pitch` one the gate is currently holding the transport for? + * + * Only the group under the cursor: a note further along the chart is not one + * the recording is about to play, so the player pressing it early should still + * hear something. + */ +function learnExpectsPitch(pitch: number): boolean { + if (learnIdx >= learnGroups.length) return false; + return learnGroups[learnIdx].pitches.includes(pitch); +} + function learnGateTick(): void { if (!learnGroups.length) return; @@ -1727,11 +1738,14 @@ function learnGateTick(): void { learnHit.clear(); } else { transportController.pause(); - // No seek. Pausing already leaves the playhead short of the note, and - // moving it afterwards splices two pieces of audio that were never - // adjacent -- roughly 45ms of the previous note's ring, elided. Under a - // sustain that reads as a stutter, which is the whole complaint. Resume - // continues from exactly where the sound stopped. + // Park close to the note so the recording answers the key press quickly. + // + // This elides the few tens of milliseconds between where the sound + // actually stopped and here. That used to matter; it does not now, + // because the join happens while the transport is faded out and stopped, + // and the engine ramps back in rather than switching. What is skipped is + // the smooth middle of a decay, and 5ms of ramp covers the seam. + transportController.seek(g.t - PARK_LEAD_SEC); learnWaiting = true; setAudioStatus(`Wait mode — play: ${g.pitches.map(learnNoteName).join(" + ")}`); } @@ -2029,6 +2043,19 @@ window.addEventListener("auralprimer:midi-input", (ev) => { } if (msg.message_type === "note_on" && (msg.data2 ?? 0) > 0) { + // Not this one: the recording is about to play it. + // + // Wait mode holds the transport just short of a note and the player's key + // releases it, so the recording sounds that note a moment later. Sounding + // it here as well puts two attacks of the same pitch a few tens of + // milliseconds apart, which is a flam -- and a flam is exactly what a + // stutter sounds like. The chart's own part is already silenced in Wait + // mode for the same reason; this is the live half of it. + // + // A note that is NOT what the gate is waiting for still sounds, because + // nothing else is going to play it and a wrong note the player cannot hear + // is a wrong note they cannot correct. + if (learnMode && learnWaiting && learnExpectsPitch(pitch)) return; void invoke("piano_note_on", { pitch, velocity: msg.data2 ?? 80 }).catch((e) => { // Surfaced, not swallowed: a piano that cannot sound looked exactly like // one that was working, which is how a silent bug survived a build. From 23c402ab97ae41f771735c1caa1ad67bebbeeefa Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 11:45:20 -0400 Subject: [PATCH 07/11] Let the key press be the note, and resume past the recording's own attack I had this backwards. Suppressing the player's note and letting the recording strike it fixed the doubling by removing the wrong half: the player presses a key and the app answers with the note, which is the app playing it, not them. In Wait mode the press IS the note. So the press sounds again, and the transport resumes PAST the recording's attack of the note just played -- about 45ms, which is the striking part of a piano note. The recording carries on from where that note is already ringing, under the one the player is holding. One attack, theirs. Floored against the next group, because on a fast run the gap between notes can be shorter than an attack, and skipping blindly would drop a note from the recording while still demanding it from the player. This is the third pass at the same symptom and the first two were not wasted: the engine really had no fade on pause, and that clicked on every stop and start regardless of who plays what. What changed is the diagnosis of the part underneath it, which was never a stutter -- it was a flam, and the question was which of the two attacks should not have been there. TS suite: 1214 passed, 3 skipped. Co-Authored-By: Claude Opus 5 --- apps/game/src/main.ts | 49 +++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/apps/game/src/main.ts b/apps/game/src/main.ts index 2cf2d780..2b040e36 100644 --- a/apps/game/src/main.ts +++ b/apps/game/src/main.ts @@ -1471,6 +1471,16 @@ const GATE_LEAD_SEC = 0.12; // rather than an audible cut. const PARK_LEAD_SEC = 0.02; +// How far past a note's onset the recording resumes, once the player has +// played that note themselves. +// +// A piano attack is the first few tens of milliseconds; past that the note is +// ringing rather than striking, and resuming there is heard as the player's +// own note continuing instead of a second one starting. Short enough that +// almost nothing musical is skipped, and floored against the next note so a +// fast run never loses one. +const ATTACK_SKIP_SEC = 0.045; + // How long after a note's onset a hit still counts as that note's, when Grace // is on and the transport is free-running. // @@ -1649,20 +1659,32 @@ function learnRegisterPlayed(pitch: number): void { // would fight a transport that is already running. if (learnWaiting) { learnWaiting = false; + // Resume PAST the recording's attack of the note just played. + // + // The player has played it. Letting the recording strike it again is the + // doubling -- their note under their finger, then the same pitch again a + // moment later, which is the flam that reads as a stutter. Their key is + // the attack; the recording carries on from where that note is already + // ringing. + const played = learnGroups[learnIdx - 1]; + if (played) transportController.seek(resumeAfterAttack(played)); void transportController.play(); } } /** - * Is `pitch` one the gate is currently holding the transport for? + * Where to resume so the recording does not re-strike a note already played. * - * Only the group under the cursor: a note further along the chart is not one - * the recording is about to play, so the player pressing it early should still - * hear something. + * Far enough past the onset to clear the attack transient, and never past the + * next note the player is going to be asked for -- on a fast run the gap + * between groups can be shorter than an attack, and skipping into the next + * note would drop it from the recording while still demanding it from the + * player. */ -function learnExpectsPitch(pitch: number): boolean { - if (learnIdx >= learnGroups.length) return false; - return learnGroups[learnIdx].pitches.includes(pitch); +function resumeAfterAttack(played: LearnGroup): number { + const next = learnGroups[learnIdx]; + const ceiling = next ? next.t - GATE_LEAD_SEC : Number.POSITIVE_INFINITY; + return Math.min(played.t + ATTACK_SKIP_SEC, Math.max(played.t, ceiling)); } function learnGateTick(): void { @@ -2043,19 +2065,6 @@ window.addEventListener("auralprimer:midi-input", (ev) => { } if (msg.message_type === "note_on" && (msg.data2 ?? 0) > 0) { - // Not this one: the recording is about to play it. - // - // Wait mode holds the transport just short of a note and the player's key - // releases it, so the recording sounds that note a moment later. Sounding - // it here as well puts two attacks of the same pitch a few tens of - // milliseconds apart, which is a flam -- and a flam is exactly what a - // stutter sounds like. The chart's own part is already silenced in Wait - // mode for the same reason; this is the live half of it. - // - // A note that is NOT what the gate is waiting for still sounds, because - // nothing else is going to play it and a wrong note the player cannot hear - // is a wrong note they cannot correct. - if (learnMode && learnWaiting && learnExpectsPitch(pitch)) return; void invoke("piano_note_on", { pitch, velocity: msg.data2 ?? 80 }).catch((e) => { // Surfaced, not swallowed: a piano that cannot sound looked exactly like // one that was working, which is how a silent bug survived a build. From 7ec8d3f6dbbcec93f56a4e7e7685503f212f43f7 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Tue, 1 Sep 2026 20:22:24 -0400 Subject: [PATCH 08/11] Show how far through the song we are, and let it be dragged A scrub bar under the transport: position, elapsed and total, and a handle to move the playhead. It reads its duration from the timebase rather than the transport state -- the state carries the playhead, and the web timebase has no duration at all, so the bar hides itself instead of scaling against a zero. Two rules make a scrubber feel right and both are about who owns the value. While a drag is in progress the render tick must not write to the thumb, or it fights the finger; and the seek lands on release rather than on every intermediate frame, or dragging across a seven-minute song issues hundreds of seeks and the engine spends the gesture catching up. The elapsed readout still follows the thumb live, so the drag has feedback without the transport moving. The drag is claimed on pointerdown rather than on the first input event, because by the time a value arrives the tick has already overwritten it once. The other two asks were already there and are left alone: per-track volume is the stem mixer, which appears when the engine reports more than one stem, and Left/Right seek by 5s already, or 1s with Shift held. Co-Authored-By: Claude Opus 5 --- apps/game/src/appShellHtml.ts | 9 ++++ apps/game/src/main.ts | 86 ++++++++++++++++++++++++++++++++++- apps/game/src/style.css | 19 ++++++++ 3 files changed, 113 insertions(+), 1 deletion(-) diff --git a/apps/game/src/appShellHtml.ts b/apps/game/src/appShellHtml.ts index e97c67c7..820a9bb8 100644 --- a/apps/game/src/appShellHtml.ts +++ b/apps/game/src/appShellHtml.ts @@ -173,6 +173,15 @@ export function appShellHtml(): string { +
(no audio)
diff --git a/apps/game/src/main.ts b/apps/game/src/main.ts index 2b040e36..3073aca1 100644 --- a/apps/game/src/main.ts +++ b/apps/game/src/main.ts @@ -1942,6 +1942,86 @@ function formatPlayhead(sec: number): string { * it believes is audible, and drift between those is exactly what a * sync complaint is about. Showing only the answer hides the disagreement. */ +// --- Song scrub bar --------------------------------------------------------- +// +// Driven from the same tick as the playhead readout, so the thumb and the +// clock can never disagree. Two rules make a scrubber feel right and both are +// about who owns the value: while the user is dragging, the tick must not +// write over their thumb; and the seek must land on release rather than on +// every intermediate frame, or a drag across a long song issues hundreds of +// seeks and the engine spends the whole gesture catching up. +const songScrubEl = document.getElementById("songScrub") as HTMLElement | null; +const songScrubRangeEl = document.getElementById("songScrubRange") as HTMLInputElement | null; +const songScrubNowEl = document.getElementById("songScrubNow"); +const songScrubTotalEl = document.getElementById("songScrubTotal"); +const SCRUB_STEPS = 1000; + +let scrubbing = false; + +function scrubDurationSec(): number { + // From the timebase, not the transport state: the state carries the playhead + // and the web timebase has no duration at all, so the bar hides itself + // rather than scaling against a zero it would have to special-case anyway. + const d = nativeTimebase?.getDurationSec?.() ?? 0; + return Number.isFinite(d) && d > 0 ? d : 0; +} + +function formatClock(sec: number): string { + if (!Number.isFinite(sec) || sec < 0) sec = 0; + const m = Math.floor(sec / 60); + const s = Math.floor(sec % 60); + return `${m}:${String(s).padStart(2, "0")}`; +} + +function seekFromScrub(): void { + if (!songScrubRangeEl) return; + const dur = scrubDurationSec(); + if (dur <= 0) return; + const t = (Number(songScrubRangeEl.value) / SCRUB_STEPS) * dur; + transportController.seek(t); + transportHostDeps.onTransportChanged?.(); + transportHostDeps.onSeeked?.(transportController.getState().t); +} + +if (songScrubRangeEl) { + // pointerdown rather than input: the drag has to be claimed before the first + // value change arrives, or that first frame is still overwritten by the tick. + songScrubRangeEl.addEventListener("pointerdown", () => { scrubbing = true; }); + songScrubRangeEl.addEventListener("keydown", () => { scrubbing = true; }); + songScrubRangeEl.addEventListener("input", () => { + // Live feedback while dragging, without seeking yet. + if (songScrubNowEl) { + const dur = scrubDurationSec(); + songScrubNowEl.textContent = formatClock((Number(songScrubRangeEl.value) / SCRUB_STEPS) * dur); + } + }); + const commit = () => { + if (!scrubbing) return; + scrubbing = false; + seekFromScrub(); + }; + songScrubRangeEl.addEventListener("change", commit); + songScrubRangeEl.addEventListener("pointerup", commit); + songScrubRangeEl.addEventListener("pointercancel", commit); + songScrubRangeEl.addEventListener("blur", commit); +} + +function renderSongScrub(): void { + if (!songScrubEl || !songScrubRangeEl) return; + const dur = scrubDurationSec(); + songScrubEl.hidden = dur <= 0; + if (dur <= 0) return; + + if (songScrubTotalEl) songScrubTotalEl.textContent = formatClock(dur); + // The user owns the thumb mid-drag; writing to it here would fight them. + if (scrubbing) return; + + const t = transportController.getState().t; + const v = String(Math.round(Math.min(1, Math.max(0, t / dur)) * SCRUB_STEPS)); + if (songScrubRangeEl.value !== v) songScrubRangeEl.value = v; + if (songScrubNowEl) songScrubNowEl.textContent = formatClock(t); +} + function renderPlayheadHud(): void { if (!playheadHudEl || !playheadClockEl) return; @@ -2113,7 +2193,11 @@ pianoGainEl?.addEventListener("input", () => { }); renderPlayheadHud(); -window.setInterval(renderPlayheadHud, LIVE_INPUT_HUD_INTERVAL_MS); +renderSongScrub(); +window.setInterval(() => { + renderPlayheadHud(); + renderSongScrub(); +}, LIVE_INPUT_HUD_INTERVAL_MS); // --- Play-mode transport hotkeys --------------------------------------- // Space start/pause/resume + Left/Right jog. Logic lives in diff --git a/apps/game/src/style.css b/apps/game/src/style.css index b56fad03..a09d000f 100644 --- a/apps/game/src/style.css +++ b/apps/game/src/style.css @@ -1602,3 +1602,22 @@ li { color: var(--accent3); min-width: 4em; } + +/* Song scrub bar — position in the song, and a handle to change it. */ +.songScrub { + margin: 0.5rem 0 0.35rem; +} +.songScrubRange { + width: 100%; + margin: 0; + cursor: pointer; + accent-color: #38bdf8; +} +.songScrubTimes { + display: flex; + justify-content: space-between; + font-size: 0.72rem; + opacity: 0.7; + font-variant-numeric: tabular-nums; + margin-top: 0.1rem; +} From 659b4be16b2e6cb7a00439f7fc8c975dc3f7810c Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Thu, 3 Sep 2026 07:35:35 -0400 Subject: [PATCH 09/11] Find the model packs from a worktree, and send the tab lane sideways again Two things, and the first caused a failure far larger than itself. Every search root the demucs modelpack resolver builds comes from __file__, cwd or sys.executable, and in a linked worktree all of those stay inside the worktree. The packs live in the main checkout, so a pack that plainly exists is reported "not found in default search locations" and stem separation silently degrades to provider=none. Downstream, the guitar-split stage then falls back to the raw mix and writes files named lead_guitar.wav and rhythm_guitar.wav; instrument conditioning reads those NAMES as evidence of what is in the song and masks the transcriber to guitar. Four solo-piano recordings imported that way came back with zero keys notes and the whole part relabelled rhythm guitar. A worktree's .git is a file reading "gitdir:
/.git/worktrees/", so the main checkout is derivable; it is added as a root. An ordinary clone has .git as a directory and gains nothing. Re-importing psalm 130 with the fix gives provider=demucs, all nine stems, conditioning that includes every piano group, and 887 keys notes against 882 authored -- from zero. The tab lane goes back to right-to-left. The perspective highway answered the wrong question: what made the sideways version unreadable was never the direction, it was that the window was a fixed number of SECONDS spread over whatever width the canvas happened to be, so a wide window made the notes fly. It now fixes the opposite quantity -- 140 px per second, the same constant the Nashville chord lane uses, with the visible span falling out of the width. Two lanes over the same music now scroll at one rate, which is what makes reading one of them teach you the other. The scroll-speed contract test pinned the old expression rather than the property. It now checks the pixel rate scales with the multiplier, the way the nashville and beats cases beside it already did. Co-Authored-By: Claude Opus 5 --- apps/game/tests/scrollSpeedMultiplier.test.ts | 8 +- python/ingest/src/aural_ingest/cli.py | 39 +++++ .../tests/test_worktree_modelpack_lookup.py | 75 +++++++++ visualizers/viz-tab/src/index.ts | 157 ++++++++---------- 4 files changed, 187 insertions(+), 92 deletions(-) create mode 100644 python/ingest/tests/test_worktree_modelpack_lookup.py diff --git a/apps/game/tests/scrollSpeedMultiplier.test.ts b/apps/game/tests/scrollSpeedMultiplier.test.ts index ea006a53..82eb2357 100644 --- a/apps/game/tests/scrollSpeedMultiplier.test.ts +++ b/apps/game/tests/scrollSpeedMultiplier.test.ts @@ -64,8 +64,12 @@ describe("scroll-speed multiplier contract (TransportState.scrollSpeedMultiplier const src = read("visualizers/viz-tab/src/index.ts"); // Reads the clamped multiplier in BOTH render paths. expect(src).toMatch(/clampScrollSpeedMultiplier\(opts\.scrollSpeedMultiplier\)/); - // Tab path shrinks the visible window so higher multiplier = more spacing. - expect(src).toMatch(/const\s+windowSec\s*=\s*this\.windowSec\s*\/\s*scrollMul/); + // Tab path scales its PIXEL RATE, the way viz-nashville and viz-beats do: + // the visible span then falls out of the canvas width instead of being a + // fixed number of seconds. That is what keeps the apparent speed the same + // on any window, and what makes this lane and the chord lane above it + // scroll together rather than at two different rates. + expect(src).toMatch(/pxPerSec\s*=\s*[^;]*\*\s*scrollMul/); // Piano-roll path shrinks look-ahead/behind the same way. expect(src).toMatch(/const\s+lookAheadSec\s*=\s*this\.pianoLookAheadSec\s*\/\s*scrollMul/); expect(src).toMatch(/const\s+lookBehindSec\s*=\s*this\.pianoLookBehindSec\s*\/\s*scrollMul/); diff --git a/python/ingest/src/aural_ingest/cli.py b/python/ingest/src/aural_ingest/cli.py index 3b9cc813..c2a269f9 100644 --- a/python/ingest/src/aural_ingest/cli.py +++ b/python/ingest/src/aural_ingest/cli.py @@ -1342,6 +1342,42 @@ def _config_with_cli_demucs_modelpack_options(args: argparse.Namespace, config: return out +def _git_main_worktree_root(start: Path) -> Path | None: + """The main checkout, when ``start`` is inside a linked git worktree. + + A worktree's assets are not its own. Model packs, build output and the + portable all live in the main checkout, and every search root derived from + __file__, cwd or sys.executable stays inside the worktree -- so a modelpack + that plainly exists is reported "not found in default search locations" and + stem separation silently degrades to none. That failure is quiet and its + consequences are not: without separation the guitar-split fallback writes + mix-derived stems named after guitar, and instrument conditioning then reads + those names as evidence and masks the transcriber to guitar. + + In a linked worktree ``.git`` is a FILE reading ``gitdir:
/.git/ + worktrees/``; the main checkout is the parent of that ``.git``. In a + normal clone ``.git`` is a directory and there is nothing to add. + """ + try: + for parent in [start, *start.parents]: + dot_git = parent / ".git" + if dot_git.is_dir(): + return None # ordinary clone: already rooted + if dot_git.is_file(): + text = dot_git.read_text(encoding="utf-8", errors="replace").strip() + if not text.startswith("gitdir:"): + return None + git_dir = Path(text.split(":", 1)[1].strip()) + #
/.git/worktrees/ ->
+ for anc in git_dir.parents: + if anc.name == ".git": + return anc.parent + return None + except Exception: + return None + return None + + def _default_demucs_modelpack_candidates(modelpack_ids: Iterable[str] | None = None) -> list[Path]: selected_ids = tuple(modelpack_ids) if modelpack_ids is not None else SUPPORTED_DEMUCS_MODELPACK_IDS roots: list[Path] = [] @@ -1380,6 +1416,9 @@ def add_root(root: Path | None) -> None: add_root(this_file.parent) add_root(this_file.parents[2]) add_root(this_file.parents[4]) + # Running from a linked git worktree: the packs live in the main + # checkout, which none of the roots above can reach. + add_root(_git_main_worktree_root(this_file.parent)) except Exception: pass diff --git a/python/ingest/tests/test_worktree_modelpack_lookup.py b/python/ingest/tests/test_worktree_modelpack_lookup.py new file mode 100644 index 00000000..0845693c --- /dev/null +++ b/python/ingest/tests/test_worktree_modelpack_lookup.py @@ -0,0 +1,75 @@ +"""A linked git worktree must still find the model packs. + +A worktree's assets are not its own: model packs, build output and the portable +all live in the main checkout, while every search root the resolver derives -- +from __file__, cwd, sys.executable -- stays inside the worktree. The pack is +then reported "not found in default search locations" and stem separation +degrades to `none`. + +That failure is quiet and its consequences are not. Without separation the +guitar-split stage falls back to the raw mix and writes files named +lead_guitar.wav / rhythm_guitar.wav; instrument conditioning reads those names +as evidence of what is in the song and masks the transcriber to guitar. Four +solo-piano recordings imported that way came out with zero keys notes and the +whole part relabelled rhythm guitar. +""" +from __future__ import annotations + +from pathlib import Path + +from aural_ingest.cli import _default_demucs_modelpack_candidates, _git_main_worktree_root + + +def _make_worktree(tmp_path: Path) -> tuple[Path, Path]: + """A main checkout with a linked worktree pointing back at it.""" + main = tmp_path / "MainCheckout" + (main / ".git" / "worktrees" / "wt").mkdir(parents=True) + (main / "dist" / "modelpacks").mkdir(parents=True) + (main / "dist" / "modelpacks" / "demucs_6.zip").write_bytes(b"stub") + + wt = tmp_path / "worktrees" / "wt" + (wt / "python" / "ingest" / "src" / "aural_ingest").mkdir(parents=True) + (wt / ".git").write_text( + f"gitdir: {(main / '.git' / 'worktrees' / 'wt').as_posix()}\n", encoding="utf-8" + ) + return main, wt + + +def test_the_main_checkout_is_found_from_a_worktree(tmp_path): + main, wt = _make_worktree(tmp_path) + found = _git_main_worktree_root(wt / "python" / "ingest" / "src" / "aural_ingest") + assert found == main + + +def test_an_ordinary_clone_adds_nothing(tmp_path): + """`.git` as a directory means we are already at the root; nothing to add.""" + repo = tmp_path / "clone" + (repo / ".git").mkdir(parents=True) + (repo / "src").mkdir() + assert _git_main_worktree_root(repo / "src") is None + + +def test_a_malformed_git_file_is_not_fatal(tmp_path): + """Resolution is best-effort: a bad pointer must not break the import.""" + repo = tmp_path / "odd" + (repo / "src").mkdir(parents=True) + (repo / ".git").write_text("this is not a gitdir pointer\n", encoding="utf-8") + assert _git_main_worktree_root(repo / "src") is None + + +def test_the_real_worktree_can_see_a_modelpack_path(): + """Against this checkout, whatever kind it is. + + In a worktree the candidate list must contain a path under the main + checkout; in a plain clone this is trivially satisfied by the local roots. + """ + candidates = _default_demucs_modelpack_candidates(["demucs_6"]) + assert candidates, "no candidate paths at all" + assert any(c.name == "demucs_6.zip" for c in candidates) + + here = Path(__file__).resolve() + main = _git_main_worktree_root(here.parent) + if main is not None: + assert any(main in c.parents for c in candidates), ( + "running from a worktree but no candidate points at the main checkout" + ) diff --git a/visualizers/viz-tab/src/index.ts b/visualizers/viz-tab/src/index.ts index 481cf3a9..26730291 100644 --- a/visualizers/viz-tab/src/index.ts +++ b/visualizers/viz-tab/src/index.ts @@ -125,6 +125,13 @@ const FLAT_NOTE_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", " const BLACK_PITCH_CLASSES = new Set([1, 3, 6, 8, 10]); const BG_COLOR = "#111721"; const PANEL_COLOR = "#141d2b"; +//: Pixels of travel per second of song, before the user's speed multiplier. +//: +//: Matched to the Nashville chord lane deliberately. Two lanes scrolling the +//: same material at different rates is the thing that made this view hard to +//: read next to it -- the eye calibrates on one and is wrong about the other. +const TAB_BASE_PX_PER_SEC = 140; + const STRING_COLOR = "rgba(255,255,255,0.18)"; const HIT_LINE_COLOR = "rgba(255,255,255,0.76)"; const TEXT_COLOR = "#ecf2ff"; @@ -548,8 +555,6 @@ export class TabRenderer { private role: InstrumentRole = "melodic"; private keySignature: KeySignatureAnalysis | null = null; - /** Seconds of lookahead visible to the right of the hit line. */ - private windowSec = 4.0; /** Fraction of canvas width where the hit line sits (from left). */ private hitLineFrac = 0.15; private pianoLookAheadSec = 7.0; @@ -622,69 +627,58 @@ export class TabRenderer { const w = canvas.width; const h = canvas.height; const scrollMul = clampScrollSpeedMultiplier(opts.scrollSpeedMultiplier); - const windowSec = this.windowSec / scrollMul; const numStrings = tuning.strings.length; - // A receding highway rather than a sideways belt. - // - // Scrolling moved every note the same number of pixels per frame however - // far off it was, so the whole field smeared at once and the fret numbers - // -- which are the entire point of this view -- went with it. Under - // perspective a note an octave of time away crawls, and only the notes - // about to be played move quickly. The eye reads the far ones because they - // are nearly still, and the near ones because they are large. + // Right to left, at a fixed pixel rate — the Nashville model. // - // Depth is 1/(1 + k*u): u is time-to-hit normalised over the window, so - // u=0 is the hit line and u=1 the horizon. Everything -- lane spread, note - // size, glyph size -- is that one number, which is what makes it read as - // distance rather than as things being drawn smaller. - const DEPTH = 5.2; - const farScale = 1 / (1 + DEPTH); - const horizonY = h * 0.06; - const hitY = h * (1 - this.hitLineFrac); - const cx = w * 0.5; - // Near-plane half-width. The lanes reach most of the canvas at the hit - // line, which is where the player is actually looking. - const halfSpread = w * 0.44; - - const depthScale = (u: number): number => 1 / (1 + DEPTH * clamp(u, 0, 1)); - // Normalised so u=1 lands exactly on the horizon whatever DEPTH is. - const depthY = (u: number): number => - hitY - ((1 - depthScale(u)) / (1 - farScale)) * (hitY - horizonY); - const laneOffset = (s: number): number => - numStrings <= 1 ? 0 : ((s / (numStrings - 1)) * 2 - 1) * halfSpread; - const laneX = (s: number, u: number): number => cx + laneOffset(s) * depthScale(u); - - // Lanes, drawn as the rails they are: wide and bright at the hit line, - // converging and faint at the horizon, so depth is legible with no notes - // on screen at all. + // The perspective highway was an answer to the wrong question. What made + // the sideways version unreadable was never the direction, it was that the + // window was a fixed number of SECONDS: four seconds spread across + // whatever width the canvas happened to be, so a wide window made the + // notes fly and a narrow one crawled. The chord lane above it has always + // felt right because it fixes the opposite quantity — 140 px per second, + // with the visible span falling out of the width — so the speed is the + // same on any monitor and reading one lane teaches you the other. + const pxPerSec = TAB_BASE_PX_PER_SEC * scrollMul; + const hitX = Math.round(w * this.hitLineFrac); + const windowSec = Math.max(0.5, (w - hitX) / pxPerSec); + + const topPad = 18; + const botPad = 14; + const laneGap = numStrings > 1 ? (h - topPad - botPad) / (numStrings - 1) : 0; + // String 0 is the highest-pitched: it belongs at the top, the way tab is + // written and the way the fretboard looks to the player holding it. + const laneY = (s: number): number => Math.round(topPad + s * laneGap); + + // Lanes: the strings, full width, dimmer behind the hit line where the + // notes have already been played. for (let s = 0; s < numStrings; s += 1) { - const steps = 24; - for (let i = 0; i < steps; i += 1) { - const u0 = i / steps; - const u1 = (i + 1) / steps; - const near = 1 - u0; - ctx.strokeStyle = STRING_COLOR; - ctx.globalAlpha = 0.25 + near * 0.75; - ctx.lineWidth = 0.5 + depthScale(u0) * 1.6; - ctx.beginPath(); - ctx.moveTo(laneX(s, u0), depthY(u0)); - ctx.lineTo(laneX(s, u1), depthY(u1)); - ctx.stroke(); - } + const y = laneY(s) + 0.5; + ctx.strokeStyle = STRING_COLOR; + ctx.globalAlpha = 0.28; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(0, y); + ctx.lineTo(hitX, y); + ctx.stroke(); + ctx.globalAlpha = 0.7; + ctx.beginPath(); + ctx.moveTo(hitX, y); + ctx.lineTo(w, y); + ctx.stroke(); } ctx.globalAlpha = 1; - // The hit line spans the near plane, across the lanes rather than through - // them, because it is a moment in time and they are pitches. + // The hit line runs across the strings, because it is a moment in time and + // they are pitches. ctx.strokeStyle = HIT_LINE_COLOR; ctx.lineWidth = 2; ctx.beginPath(); - ctx.moveTo(cx - halfSpread, hitY); - ctx.lineTo(cx + halfSpread, hitY); + ctx.moveTo(hitX + 0.5, topPad - 10); + ctx.lineTo(hitX + 0.5, h - botPad + 10); ctx.stroke(); - const tStart = t - 0.5; + const tStart = t - hitX / pxPerSec; const tEnd = t + windowSec; const color = ROLE_COLORS[this.role]; const glow = ROLE_GLOW_COLORS[this.role]; @@ -692,60 +686,43 @@ export class TabRenderer { ctx.textAlign = "center"; ctx.textBaseline = "middle"; - // Far to near, so a nearer note occludes the one behind it the way the - // distance already implies. - const visible: { note: MelodicNote; fret: FretPosition; u: number }[] = []; + const pillH = Math.round(Math.min(22, Math.max(11, laneGap * 0.72))); + const fontPx = Math.max(9, Math.min(15, Math.round(pillH * 0.68))); + for (const note of track.notes) { if (note.t_on > tEnd || note.t_off < tStart) continue; const fretInfo = noteToFretPosition(note, tuning); if (!fretInfo) continue; - visible.push({ note, fret: fretInfo, u: (note.t_on - t) / windowSec }); - } - visible.sort((a, b) => b.u - a.u); - - for (const { fret: fretInfo, u } of visible) { - const uc = clamp(u, 0, 1); - const scale = depthScale(uc); - // Whole pixels, still: a glyph landing on a different sub-pixel offset - // each frame is anti-aliased differently each frame, which reads as - // shimmer. Perspective slows the far ones down but does not put them on - // the grid. - const x = Math.round(laneX(fretInfo.string, uc)); - const y = Math.round(depthY(uc)); - - // Held past the line rather than clipped: u goes negative for a note - // being played, and the pill staying put is the confirmation. - // Floor lands at 0.62 on the horizon, which is where the old fixed - // window had to be pinned to stay readable -- perspective earns it back - // instead of asserting it. - const alpha = u < 0 ? 1 : 0.55 + 0.45 * scale; + + // Whole pixels: a glyph landing on a different sub-pixel offset each + // frame is anti-aliased differently each frame, which reads as shimmer. + const x = Math.round(hitX + (note.t_on - t) * pxPerSec); + const y = laneY(fretInfo.string); + // Sustain drawn as the note's real length, so a held note is visibly + // held rather than being a dot that lingers. + const held = Math.round(Math.max(0, (note.t_off - note.t_on)) * pxPerSec); + const pillW = Math.max(pillH, Math.min(held, w)); + + const playing = note.t_on <= t && note.t_off >= t; + ctx.globalAlpha = playing ? 1 : x < hitX ? 0.45 : 0.92; ctx.save(); - ctx.globalAlpha = alpha * 0.5; + ctx.globalAlpha *= 0.5; ctx.fillStyle = glow; - ctx.beginPath(); - ctx.arc(x, y, Math.max(4, 17 * scale), 0, Math.PI * 2); + roundRectPath(ctx, x - pillH * 0.5 - 2, y - pillH * 0.5 - 2, pillW + 4, pillH + 4, 6); ctx.fill(); ctx.restore(); - const pillW = Math.round(Math.max(9, 28 * scale)); - const pillH = Math.round(Math.max(8, 23 * scale)); - ctx.save(); - ctx.globalAlpha = alpha; ctx.fillStyle = color; - roundRectPath(ctx, x - pillW * 0.5, y - pillH * 0.5, pillW, pillH, Math.max(2, 5 * scale)); + roundRectPath(ctx, x - pillH * 0.5, y - pillH * 0.5, pillW, pillH, 5); ctx.fill(); - // Below about 9px the digits stop being digits, so the pill carries the - // note on its own out there. It still says WHEN and WHICH STRING, which - // is what a note that far away is for; the fret arrives with the size. - const fontPx = Math.round(16 * scale); if (fontPx >= 9) { ctx.fillStyle = "#051018"; ctx.font = `800 ${fontPx}px ui-monospace, SFMono-Regular, Consolas, monospace`; - ctx.fillText(String(fretInfo.fret), x, y); + ctx.fillText(String(fretInfo.fret), x, y + 1); } - ctx.restore(); + ctx.globalAlpha = 1; } ctx.save(); From 7d3e43072933f70857b4807d480104d2bc85f4ce Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Thu, 3 Sep 2026 08:49:37 -0400 Subject: [PATCH 10/11] Let the play route use the whole window The stage was capped at a reading width. 1180px is right for menus and copy and wrong for a control rail beside a scrolling instrument lane, which just got a smaller stage and two dead margins. The widescreen escape only fired past 1500px and only widened to 1720px, so a wide monitor was still letterboxed at both ends. The play route now takes the window it is given; every other route keeps the cap, because prose spanning two thousand pixels is worse, not better. Toggled as a class from routeController rather than through :has(), so the layout does not depend on the selector engine and the state is visible in the DOM -- which is also where the rest of the route state already lives. Co-Authored-By: Claude Opus 5 --- apps/game/src/routeController.ts | 7 +++++++ apps/game/src/style.css | 16 +++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/apps/game/src/routeController.ts b/apps/game/src/routeController.ts index 6fc3a8f7..753e644a 100644 --- a/apps/game/src/routeController.ts +++ b/apps/game/src/routeController.ts @@ -76,6 +76,13 @@ export function initRouteController(deps: RouteControllerDeps): RouteControllerH el.classList.toggle("isActive", r === route); } + // The play route uses the whole window; every other route keeps the + // reading-width cap. Toggled here because this is the one place that + // already knows which route is showing. + document + .querySelector(".appMain") + ?.classList.toggle("isPlayRoute", route === "play"); + const navMap: Record = { home: "navHome", play: "navPlay", diff --git a/apps/game/src/style.css b/apps/game/src/style.css index a09d000f..e9092ca3 100644 --- a/apps/game/src/style.css +++ b/apps/game/src/style.css @@ -223,13 +223,15 @@ main { max-width: min(96vw, 1720px); } -/* Widen appMain on widescreen when the play route is showing — gives the - bandSetupBody (rail + stage) room to breathe. Falls back to the standard - 1180px cap on narrower viewports. */ -@media (min-width: 1500px) { - .appMain:has(.route[data-route="play"].isActive) { - max-width: min(96vw, 1720px); - } +/* The play route is a stage, not prose, so it takes the window it is given. + The 1180px cap is a reading width -- right for menus and copy, wrong for a + rail plus a scrolling instrument lane, which just get a smaller stage and a + pair of dead margins. It used to widen only past 1500px and only to 1720px, + so a wide monitor still showed letterboxing at both ends. + Set by routeController rather than :has(), so it does not depend on the + selector engine and can be reasoned about from the DOM. */ +.appMain.isPlayRoute { + max-width: none; } .route { From 052a173e098ba9270461d4edc069e1af587be465 Mon Sep 17 00:00:00 2001 From: Nathanael Anderson Date: Fri, 4 Sep 2026 22:13:14 -0400 Subject: [PATCH 11/11] Put the seek bar where the player is looking The scrub bar shipped in the setup rail, under the loop controls and above a status pre. That is the right place to configure a song and the wrong place to scrub one: during play the eye is on the stage, and the rail is off to the side -- so a control that existed may as well not have. It now sits on the stage bar beside the time readout, which is already where the playhead, the MIDI input and the spacing slider live. Same behaviour, same two rules about who owns the value while a drag is in progress; only the markup and layout moved. Co-Authored-By: Claude Opus 5 --- apps/game/src/appShellHtml.ts | 18 +++++++++--------- apps/game/src/style.css | 23 ++++++++++++++--------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/apps/game/src/appShellHtml.ts b/apps/game/src/appShellHtml.ts index 820a9bb8..85630a95 100644 --- a/apps/game/src/appShellHtml.ts +++ b/apps/game/src/appShellHtml.ts @@ -173,15 +173,6 @@ export function appShellHtml(): string { -
(no audio)
@@ -217,6 +208,15 @@ export function appShellHtml(): string { +