Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add a metronome volume + mute to the SongBook drum transport
[._.]/ Adam Eivy83892eb0fa94
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2cdcff3d57..e301855ec1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -45,6 +45,8 @@## SongBook+- **The drum play-along metronome now has a volume control, and its mute reads as one.** The transport's only slider was the practice tempo, sitting right beside the metronome button — so it looked like the metronome's volume, and there was no way to actually balance the click against the kit: it was full-level or nothing. The metronome now carries its own speaker button and short volume slider as a pair, the tempo control is labelled BPM, and the click level is remembered per machine (it starts at full, so nothing changes until you move it). Dragging the level up while muted unmutes, rather than leaving you with a slider that does nothing; `m` mutes and unmutes from the keyboard. Muting still leaves the count-in audible — "click off, count me in" is the point of that pairing — and the level applies live, mid-groove, without stopping playback. The count-in itself is now the metronome click it always described itself as: it had been sounding as four snare hits, because "click" isn't a kit piece and fell through to the kit's snare.+- **Drum charts now play through a real drum-machine kit, with a punchy kick.** The play-along kit was synthesized from a single generic recipe, and the kick came out weak: its pitch slid from the attack all the way down across its whole (very short) tail, so it never settled on a fundamental and never developed any body — on a phone or laptop speaker it barely registered under the hats. The kit has been rebuilt as three you can choose between from the practice settings: **TR-909** (the new default — attack-forward kick, bright snare crack, tight hats), **TR-808** (deep sub kick with a long tail, thin snare, metallic square-cluster hats), and **Acoustic** (rounder, closer to a studio kit). Every drum now snaps to its pitch in the first few hundredths of a second and then rings out, the way a real drum machine does, and the low drums are saturated so the harmonics carry the kick on small speakers that can't reproduce a 48 Hz fundamental at all — measured, that puts about 9 dB more of the kick through a small-speaker response than the old recipe. The whole kit runs into a soft limiter, so a downbeat stacking kick, crash and metronome no longer clips. Swapping kits applies immediately without stopping playback, and your choice is remembered on that machine.- **[issue-3222] Drum-chart previews are now audible while you write or import.** The editor and import preview both include the full practice transport, animate the sounding chart's playhead, and keep playing the snapshot captured at Play even as you continue typing; a clear reload notice appears when the draft changes.diff --git a/client/src/components/songbook/DrumPreview.jsx b/client/src/components/songbook/DrumPreview.jsxindex 771e8fe65c..129e0dc983 100644--- a/client/src/components/songbook/DrumPreview.jsx+++ b/client/src/components/songbook/DrumPreview.jsx@@ -57,6 +57,10 @@ export default function DrumPreview({player.setClickEnabled(enabled);settingsMirror?.setClickEnabled(enabled);}, [player.setClickEnabled, settingsMirror]);+ const setClickVolume = useCallback((level) => {+ player.setClickVolume(level);+ settingsMirror?.setClickVolume(level);+ }, [player.setClickVolume, settingsMirror]);// The kit persists globally, but the viewer's transport already read it at// mount — mirror the change so the two don't disagree until a reload.const setKitId = useCallback((next) => {@@ -91,6 +95,8 @@ export default function DrumPreview({barCount={player.barCount}clickEnabled={player.clickEnabled}onClickToggle={setClickEnabled}+ clickVolume={player.clickVolume}+ onClickVolumeChange={setClickVolume}kitId={player.kitId}onKitChange={setKitId}beatsPerBar={player.beatsPerBar}diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsxindex f79771ee27..d207d20a59 100644--- a/client/src/components/songbook/DrumTransportBar.jsx+++ b/client/src/components/songbook/DrumTransportBar.jsx@@ -5,8 +5,8 @@* stepper + number input (slider on wider screens, clamped by `clampBpm`,* 20–320), percent-of-written quick buttons that recompute BPM from the chart's* `tempo:` marking, a kit picker (TR-909 / TR-808 / Acoustic), a count-in select,- * a loop toggle with a from/to bar range, a metronome-click toggle, and a live- * beat/bar readout. All state and audio live in the hook — this file only+ * a loop toggle with a from/to bar range, a metronome mute + volume pair, and a+ * live beat/bar readout. All state and audio live in the hook — this file only* renders and calls back.** PHONE-FIRST LAYOUT. A phone is the primary SongBook surface, and the previous@@ -23,9 +23,12 @@*/import { useMemo, useState } from 'react';-import { Play, Square, Repeat, Timer, Minus, Plus, SlidersHorizontal } from 'lucide-react';+import {+ Play, Square, Repeat, Minus, Plus, SlidersHorizontal, Volume2, VolumeX,+} from 'lucide-react';import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';import { DRUM_KIT_LIST, resolveDrumKit } from '../../lib/drumKits.js';+import { clampClickVolume, DEFAULT_CLICK_VOLUME } from '../../lib/drumPlayback.js';import { ctrlBtnClass, activeCtrlClass } from './constants.js';// Practice speeds as a percentage of the chart's written tempo.@@ -68,12 +71,17 @@ export default function DrumTransportBar({countInBars, onCountInChange,loopEnabled, onLoopToggle, loopFrom, loopTo, onLoopRangeChange, barCount,clickEnabled, onClickToggle,+ clickVolume = DEFAULT_CLICK_VOLUME, onClickVolumeChange,kitId, onKitChange,beatsPerBar = 4, pulse = null, currentBar = null,}) {// Setup controls: collapsed by default on a phone, always shown from `sm` up.const [showSetup, setShowSetup] = useState(false);+ // The click level rides a 0–100 slider but is stored 0–1, so the two ends+ // convert here rather than leaking percent into the player.+ const clickPercent = Math.round((clampClickVolume(clickVolume) ?? DEFAULT_CLICK_VOLUME) * 100);+// `pulse` turns over on every beat, so the bar-range options must not be// rebuilt with it — a 32-bar song is 64 <option>s per beat otherwise.const barOptions = useMemo(@@ -88,38 +96,62 @@ export default function DrumTransportBar({<div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 space-y-2">{/* --- Primary: the controls you touch while playing -------------------- */}<div className="flex flex-wrap items-center gap-x-3 gap-y-2">- <div className="flex items-center gap-1.5" role="group" aria-label="Drum play-along">- <button- type="button"- onClick={onToggle}- // An all-rest chart parses into bars but has nothing to sound — a Play- // button that silently does nothing reads as broken.- disabled={!hasMusic}- className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeCtrlClass : ''}`}- aria-label={playing ? 'Stop play-along' : 'Play along'}- title={hasMusic- ? (playing ? 'Stop (space)' : 'Play along (space)')- : 'Nothing to play — this chart has no hits yet'}- >- {playing ? <Square size={16} /> : <Play size={18} />}- </button>+ <button+ type="button"+ onClick={onToggle}+ // An all-rest chart parses into bars but has nothing to sound — a Play+ // button that silently does nothing reads as broken.+ disabled={!hasMusic}+ className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeCtrlClass : ''}`}+ aria-label={playing ? 'Stop play-along' : 'Play along'}+ title={hasMusic+ ? (playing ? 'Stop (space)' : 'Play along (space)')+ : 'Nothing to play — this chart has no hits yet'}+ >+ {playing ? <Square size={16} /> : <Play size={18} />}+ </button>++ {/* Metronome — a primary control: it's the thing you toggle between+ "play me the groove" and "just count me in", and the level you+ balance against your own playing.- {/* Metronome click — a primary control: it's the thing you toggle- between "play me the groove" and "just count me in". */}+ It reads as a VOLUME (speaker icon + its own short slider) so the+ tempo control beside it can't be mistaken for one — with the BPM+ slider as the bar's only slider, that was exactly the confusion. */}+ <div className="flex items-center gap-1" role="group" aria-label="Metronome"><buttontype="button"onClick={() => onClickToggle(!clickEnabled)}aria-pressed={clickEnabled}className={`${ctrlBtnClass} ${clickEnabled ? activeCtrlClass : ''}`}aria-label={clickEnabled ? 'Turn the metronome off' : 'Turn the metronome on'}- title="Metronome click over the kit"+ title={clickEnabled+ ? 'Mute the metronome click (m) — the count-in still sounds'+ : 'Unmute the metronome click (m)'}>- <Timer size={16} />+ {clickEnabled ? <Volume2 size={16} /> : <VolumeX size={16} />}</button>+ <label htmlFor="drum-click-volume" className="sr-only">Metronome volume</label>+ <input+ id="drum-click-volume"+ type="range"+ min={0}+ max={100}+ step={5}+ value={clickPercent}+ onChange={(e) => onClickVolumeChange(Number(e.target.value) / 100)}+ aria-valuetext={`${clickPercent}%`}+ // Tall box, thin native track: the thumb centers in it, so a phone+ // gets a 44px drag target without the slider looking chunky.+ className="w-14 sm:w-20 min-h-[44px] accent-port-accent"+ title={`Metronome volume (${clickPercent}%)`}+ /></div>- {/* Practice tempo — steppers everywhere, slider only where there's room */}- <div className="flex items-center gap-1">+ {/* Practice tempo — steppers everywhere, slider only where there's room.+ The visible "BPM" carries the unit: an unlabelled number between a+ minus and a plus, trailed by a slider, reads as a level. */}+ <div className="flex items-center gap-1" role="group" aria-label="Practice tempo"><buttontype="button"onClick={() => onBpmChange(bpm - BPM_STEP)}@@ -150,6 +182,7 @@ export default function DrumTransportBar({><Plus size={16} /></button>+ <span aria-hidden="true" className="text-xs text-gray-500 ml-0.5">BPM</span><label htmlFor="drum-bpm-slider" className="sr-only">Practice tempo slider</label><inputid="drum-bpm-slider"diff --git a/client/src/components/songbook/DrumTransportBar.test.jsx b/client/src/components/songbook/DrumTransportBar.test.jsxindex d68c56d493..66b508d64b 100644--- a/client/src/components/songbook/DrumTransportBar.test.jsx+++ b/client/src/components/songbook/DrumTransportBar.test.jsx@@ -24,6 +24,8 @@ const props = (extra = {}) => ({barCount: 4,clickEnabled: true,onClickToggle: vi.fn(),+ clickVolume: 1,+ onClickVolumeChange: vi.fn(),kitId: '909',onKitChange: vi.fn(),beatsPerBar: 4,@@ -43,6 +45,34 @@ describe('DrumTransportBar', () => {expect(screen.getByLabelText('Turn the metronome off')).toBeTruthy();});+ it('keeps the metronome volume beside its mute, in the primary row', () => {+ // The confusion this fixes: with the BPM slider as the bar's only slider,+ // the tempo control read as a volume. So the metronome carries its OWN+ // slider next to a speaker button, and the tempo is labelled in BPM.+ const p = props();+ render(<DrumTransportBar {...p} />);+ const volume = screen.getByLabelText('Metronome volume');+ expect(volume.type).toBe('range');+ expect(volume.value).toBe('100');+ fireEvent.change(volume, { target: { value: '40' } });+ // The slider is 0–100; the player's level is 0–1.+ expect(p.onClickVolumeChange).toHaveBeenCalledWith(0.4);+ expect(screen.getByText('BPM')).toBeTruthy();+ });++ it('shows the stored level and flips the icon-button between mute and unmute', () => {+ const p = props({ clickVolume: 0.35 });+ const { rerender } = render(<DrumTransportBar {...p} />);+ expect(screen.getByLabelText('Metronome volume').value).toBe('35');+ fireEvent.click(screen.getByLabelText('Turn the metronome off'));+ expect(p.onClickToggle).toHaveBeenCalledWith(false);++ rerender(<DrumTransportBar {...props({ clickEnabled: false, clickVolume: 0.35 })} />);+ // Muted still shows the level — it's what you get back when you unmute.+ expect(screen.getByLabelText('Turn the metronome on')).toBeTruthy();+ expect(screen.getByLabelText('Metronome volume').value).toBe('35');+ });+it('collapses the setup controls under sm and expands them on the disclosure', () => {render(<DrumTransportBar {...props()} />);const toggle = screen.getByLabelText('Show practice settings');diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8601593fea..420a9e772e 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -180,5 +180,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. || `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |-| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record) and the selected kit (`songbook:drumKit`) persists per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle and the kit swap apply live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. |+| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, clickVolume, setClickVolume, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record) while the selected kit (`songbook:drumKit`), the click toggle (`songbook:drumClick`) and the click level (`songbook:drumClickVolume`) persist per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle, the click level and the kit swap apply live (raising the level off silence also unmutes, so the slider is never a dead control); the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. || `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.jsindex 4243d42835..6807e7cd7f 100644--- a/client/src/hooks/useDrumPlayer.js+++ b/client/src/hooks/useDrumPlayer.js@@ -1,32 +1,38 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { parseDrumChart, chartHasMusic } from '../lib/drumNotation.js';-import { createDrumPlayer, resolveLoopRange, resolvePlayhead } from '../lib/drumPlayback.js';+import {+ createDrumPlayer, resolveLoopRange, resolvePlayhead,+ clampClickVolume, DEFAULT_CLICK_VOLUME,+} from '../lib/drumPlayback.js';import { resolveDrumKit } from '../lib/drumKits.js';import { clampBpm } from '../lib/metronome.js';-import { useLocalStorageBool } from './useLocalStorageBool.js';+import { useLocalStorageBool, useLocalStoragePersisted } from './useLocalStorageBool.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';// The selected kit is global to the machine (see the `kitId` state below).const KIT_STORAGE_KEY = 'songbook:drumKit';+// So is the metronome level (see the header note).+const CLICK_VOLUME_STORAGE_KEY = 'songbook:drumClickVolume';/*** Drum play-along transport for a SongBook `drum` chart (#3115) — React wrapper* over `lib/drumPlayback.js`. Owns the player lifecycle, the practice settings- * (tempo / count-in / loop range / click) and the playback position, so- * `SongBookViewer` only renders controls.+ * (tempo / count-in / loop range / click on-off and level) and the playback+ * position, so `SongBookViewer` only renders controls.** Practice tempo is a PER-MACHINE preference, not synced content: it persists to* `safeStorage` under the song id (exactly like the viewer's transpose offset)- * and is never written into the record. The metronome is the same kind of- * preference but global to the machine, so it uses the shared- * `useLocalStorageBool`.+ * and is never written into the record. The metronome — both its on/off and its+ * level — is the same kind of preference but global to the MACHINE: the click is+ * a reference pulse you balance against your own playing, not a property of any+ * one song.** A timing-critical edit (tempo, count-in, loop range) while playing STOPS* playback rather than re-timing a running schedule — already-scheduled audio* can't be moved, so a live rebase would desync the position from what you hear.- * The user presses play again at the new setting. The click toggle and the kit- * selection are the exceptions: they only gate FUTURE scheduling, so they apply- * live.+ * The user presses play again at the new setting. The click toggle, the click+ * level and the kit selection are the exceptions: they gate or scale FUTURE+ * scheduling only, so they apply live.** Settings live in state AND are pushed into the player by a sync effect, so the* order the seeding effects happen to run in can't leave the player holding a@@ -79,6 +85,14 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {// against no pulse is the unusual case, and "never chosen" must not read as// "chosen off" (the hook's own default handles that distinction).const [clickEnabled, setClickEnabled] = useLocalStorageBool('songbook:drumClick', true);+ // How loud that click sits over the kit. `parse` only runs on a value that was+ // really stored, and `clampClickVolume` returns null for a garbled one — which+ // together keep "never chosen" (→ full) distinct from a stored 0 (→ silent).+ const [clickVolume, setClickVolumeState] = useLocalStoragePersisted(+ CLICK_VOLUME_STORAGE_KEY,+ DEFAULT_CLICK_VOLUME,+ { parse: (raw) => clampClickVolume(raw) ?? DEFAULT_CLICK_VOLUME },+ );// Which synth kit sounds the chart (909 / 808 / acoustic). Like the metronome// it's a taste setting global to the MACHINE, not per song — and it changes no// timing, so unlike the tempo/loop settings it applies without stopping@@ -145,14 +159,19 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {player.setBpm(bpm);player.setCountIn(countInBars);player.setLoop(loopEnabled ? { from: loopFrom, to: loopTo } : null);- player.setClick(clickEnabled);- }, [chart, bpm, countInBars, loopEnabled, loopFrom, loopTo, clickEnabled]);+ }, [chart, bpm, countInBars, loopEnabled, loopFrom, loopTo]);- // The kit gets its OWN effect rather than joining the one above: each timing- // setter there rebuilds the schedule while idle, so folding the kit in would- // re-flatten and re-sort every event three times over to deliver what is- // really a one-line assignment.- useEffect(() => { playerRef.current?.setKit(kitId); }, [chart, kitId]);+ // The settings that touch no timing get their OWN effect rather than joining+ // the one above: each timing setter there rebuilds the schedule while idle, so+ // folding these in would re-flatten and re-sort every event three times over+ // to deliver what are really one-line assignments.+ useEffect(() => {+ const player = playerRef.current;+ if (!player) return;+ player.setClick(clickEnabled);+ player.setClickVolume(clickVolume);+ player.setKit(kitId);+ }, [chart, clickEnabled, clickVolume, kitId]);// Live playhead read — the source both consumers below share. Stable identity// so a caller's animation-frame loop can depend on it without restarting.@@ -227,6 +246,22 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {safeWriteStorage(KIT_STORAGE_KEY, id);}, []);+ // Metronome level. Like the kit it changes no timing, so playback keeps+ // running and the live-settings effect above hands it to the sounding player.+ //+ // Raising it off silence UNMUTES: reaching for the level is an intent to hear+ // the click, and a slider that moves while the mute button holds it silent is+ // the "I adjusted it and nothing happened" bug. The reverse is deliberately+ // NOT wired — dragging to zero leaves the toggle alone, so unmuting later+ // can't come back silent.+ const setClickVolume = useCallback((next) => {+ const level = clampClickVolume(next);+ if (level == null) return;+ setClickVolumeState(level); // persists as a side effect+ // Guarded so a drag doesn't re-write the toggle's storage on every frame.+ if (level > 0 && !clickEnabled) setClickEnabled(true);+ }, [clickEnabled, setClickEnabled]);+// Percent of the chart's WRITTEN tempo (the practice-slower control).const setBpmPercent = useCallback((percent) => {setBpm(Math.round((writtenTempo * percent) / 100));@@ -273,6 +308,8 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {setLoopRange,clickEnabled,setClickEnabled,+ clickVolume,+ setClickVolume,kitId,setKitId,playing,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 30e837334d..079a47ee9a 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -128,7 +128,7 @@ grep -i "what you want to do" client/src/lib/README.md| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. || `drumKits.js` | The three selectable synth kits for the SongBook drum play-along — `DRUM_KIT_LIST` (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived `DRUM_KITS` / `DRUM_KIT_IDS` / `DEFAULT_DRUM_KIT` (`909` punchy, `808` deep-sub, `acoustic`), `resolveDrumKit(id)` (unknown/stale id → the default, never silence), `kitVoiceLayers(kit, sound)` (unmapped piece → the snare, never silence) and the kit-independent `CLICK_VOICE`. Pure DATA: each voice is a list of LAYERS — `tone` (`wave, from, to, pitchDecay, drive`), `noise` (`filter`), or `metal` (N square `partials` summed into one filter+envelope) — that `drumPlayback.js` realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: `pitchDecay` is INDEPENDENT of the amplitude `decay` (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), `drive` tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a `metal` layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers. || `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `drumGlyphLegend(pieceIds)` (all six cell characters, with the `o` row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each `KIT_PIECES` row's `technique` (how that piece is struck). Only the hi-hat voice sustains an `o` in playback, so the `open` wording follows the piece's `sound`, not its glyph shape. NOT the lead-sheet parser (`scoreNotation.js`). |-| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, kit, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — recipes in `drumKits.js`, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. `setKit(id)` applies LIVE (it touches no timing, unlike `setBpm`/`setLoop`/`setCountIn`, which only rebuild while idle). Pure (no React) — `SongBookViewer` owns the transport UI. |+| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, clickVolume, kit, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — recipes in `drumKits.js`, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. The metronome — the through-music click AND the count-in, which both sound `CLICK_VOICE`, never a kit piece — rides its OWN gain bus into the master, so `setClickVolume(0–1)` moves clicks already queued in the lookahead window instead of only the next ones (a level of 0 additionally schedules no click voice at all — the level persists, so a silenced click must not keep building a voice per beat forever) (`clampClickVolume` returns null for an unset/garbled level so a caller can tell "never chosen" from a stored `DEFAULT_CLICK_VOLUME`-vs-silence). `setKit(id)`, `setClick(enabled)` and `setClickVolume(level)` apply LIVE (they touch no timing, unlike `setBpm`/`setLoop`/`setCountIn`, which only rebuild while idle). Pure (no React) — `SongBookViewer` owns the transport UI. || `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the suspended-context resume with the teardown-race guard, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. || `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |diff --git a/client/src/lib/drumPlayback.js b/client/src/lib/drumPlayback.jsindex 4fe54e9399..fe5afcb18e 100644--- a/client/src/lib/drumPlayback.js+++ b/client/src/lib/drumPlayback.js@@ -23,6 +23,30 @@ import { CLICK_VOICE, kitVoiceLayers, resolveDrumKit } from './drumKits.js';const { SCHEDULE_AHEAD } = SYNTH_TIMING;const safeCall = makeSafeCall('drum playback');+// The `sound` name a count-in event carries. It is NOT a kit piece — it sounds+// through `CLICK_VOICE` on the click bus, so a count-in is the same blip as the+// through-music click and follows the same volume. ONE predicate decides both+// the voice and the bus: two (say, `sound` for the voice and `countIn` for the+// bus) would let a future click event get the right blip on the wrong bus, and+// silently stop following the volume control.+const CLICK_SOUND = 'click';+const isClickEvent = (ev) => ev.sound === CLICK_SOUND;++// Metronome-click level, 0 (silent) – 1 (full). Full is the historical level, so+// an install that never touches the new control hears exactly what it did.+export const DEFAULT_CLICK_VOLUME = 1;++// Clamp a click level into 0–1. Returns null for a missing/unparseable value so+// a caller can tell "never set" from a legitimately-clamped 0 (the same+// sentinel contract as `clampBpm`) — `Number('')` is 0, i.e. silence, and must+// not be able to masquerade as a chosen level.+export const clampClickVolume = (value) => {+ if (value == null || value === '') return null;+ const n = Number(value);+ if (!Number.isFinite(n)) return null;+ return Math.min(1, Math.max(0, n));+};+// --- Schedule building (pure) ----------------------------------------------// Clamp a loop range against the chart's real bar count. Returns null when the@@ -89,7 +113,7 @@ export const buildDrumSchedule = (chart, options = {}) => {step: null,beat: beat + 1,piece: null,- sound: 'click',+ sound: CLICK_SOUND,velocity: beat === 0 ? 1 : 0.6,countIn: true,startSec: (bar * beats + beat) * beatSec,@@ -333,8 +357,13 @@ const soundLayers = (c, layers, at, destination, track, { velocity, open }) => {// Sound one chart event — the hit, plus a flam grace note when the glyph calls// for one. Every created node pair goes through `track` so the transport tears// all of them down on stop.+//+// A count-in event is the metronome, not a kit piece: it sounds through+// `CLICK_VOICE`. Left to `kitVoiceLayers` it would fall through to the kit's+// SNARE (the "unmapped piece stays audible" fallback), which is why a count-in+// used to be four snare hits instead of four clicks.const soundEvent = (c, kit, ev, at, destination, track) => {- const layers = kitVoiceLayers(kit, ev.sound);+ const layers = isClickEvent(ev) ? CLICK_VOICE : kitVoiceLayers(kit, ev.sound);if (ev.flam) {soundLayers(c, layers, Math.max(at - FLAM_LEAD_SEC, 0), destination, track, {velocity: ev.velocity * 0.45, open: ev.open,@@ -356,19 +385,21 @@ const soundEvent = (c, kit, ev, at, destination, track) => {* bar range; when set, playback repeats that range until stopped.* @param {boolean} [options.clickEnabled] — layer a metronome click on every* notated beat, on the same clock as the kit.+ * @param {number} [options.clickVolume] — click/count-in level, 0–1 (default 1).* @param {string} [options.kit] — kit id from `drumKits.js` (`909` / `808` /* `acoustic`); an unknown id falls back to the default rather than to silence.* @param {({bar:number|null, step:number|null, countIn:boolean})=>void} [options.onStep]* — the now-sounding grid position (null when playback ends/stops), for the* sheet playhead.* @param {()=>void} [options.onEnded] — fired once when a non-looping chart ends.- * @returns {{ play, pause, stop, isPlaying, setBpm, setLoop, setClick, setKit, schedule }}+ * @returns {{ play, pause, stop, isPlaying, setBpm, setLoop, setClick, setClickVolume, setKit, schedule }}*/export const createDrumPlayer = (chart, options = {}) => {const { onStep, onEnded } = options;let bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : null;let loopBars = options.loopBars || null;let clickEnabled = !!options.clickEnabled;+ let clickVolume = clampClickVolume(options.clickVolume) ?? DEFAULT_CLICK_VOLUME;let countInBars = options.countInBars || 0;// The kit only affects which voices SOUND, never the schedule — so unlike the// timing settings it can change mid-play (the next scheduled hit picks it up).@@ -378,6 +409,11 @@ export const createDrumPlayer = (chart, options = {}) => {let schedule = build();let master = null;let masterOut = null;+ // The metronome gets its OWN sub-bus into the drum master. A per-hit velocity+ // scale would only reach clicks scheduled AFTER the change, so a slider drag+ // wouldn't be heard until the lookahead window had drained; a bus moves+ // everything already queued too, which is what makes the control feel live.+ let clickBus = null;// Click track for the CURRENT schedule: one marker per notated beat of the// music (the count-in carries its own clicks as real events). Derived rather@@ -465,7 +501,10 @@ export const createDrumPlayer = (chart, options = {}) => {if (at >= horizon) break;hitCursor.idx += 1;if (at < now - 0.05) continue; // already past (first tick after a stall)- soundEvent(c, kit, ev, Math.max(at, now), master, track);+ // Count-in beats are metronome, not kit — they ride the click bus so the+ // volume control governs them too. They are deliberately NOT gated on+ // `clickEnabled`: "click off, count-in on" is the "just count me in" mode.+ soundEvent(c, kit, ev, Math.max(at, now), isClickEvent(ev) ? clickBus : master, track);}// The click layer walks its own list on the same pass geometry. Its pass ≥ 1@@ -482,7 +521,15 @@ export const createDrumPlayer = (chart, options = {}) => {if (at >= horizon) break;clickCursor.idx += 1;if (at < now - 0.05) continue;- soundLayers(c, CLICK_VOICE, Math.max(at, now), master, track, {+ // A level of 0 is silence, and it PERSISTS — dragging the slider down is+ // the obvious way to shut the click up, so without this a practice loop+ // would build a voice per beat forever to sound nothing. The gate sits+ // after the cursor advance (skipping the loop wholesale would leave the+ // cursor behind and dump a backlog on the tick after you turn it back+ // up); the cost is that raising the level mid-window loses at most one+ // lookahead of clicks.+ if (clickVolume <= 0) continue;+ soundLayers(c, CLICK_VOICE, Math.max(at, now), clickBus, track, {velocity: click.accent ? 1 : 0.55, open: false,});}@@ -540,6 +587,9 @@ export const createDrumPlayer = (chart, options = {}) => {masterOut.oversample = '2x';master.connect(masterOut);masterOut.connect(c.destination);+ clickBus = c.createGain();+ clickBus.gain.value = clickVolume;+ clickBus.connect(master);return true;},seekCursors: (offsetSec) => {@@ -560,10 +610,11 @@ export const createDrumPlayer = (chart, options = {}) => {onTeardown: () => {// Outside the request lifecycle — a disconnect on an already-torn-down// node must not throw into the transport's teardown path.- for (const node of [master, masterOut]) {+ for (const node of [clickBus, master, masterOut]) {if (!node) continue;try { node.disconnect(); } catch { /* already gone */ }}+ clickBus = null;master = null;masterOut = null;},@@ -599,6 +650,15 @@ export const createDrumPlayer = (chart, options = {}) => {rebuildIfIdle();},setClick: (enabled) => { clickEnabled = !!enabled; },+ // Level of the click layer AND the count-in, live (see the `clickBus`+ // declaration for why it's a bus). `setTargetAtTime` rather than a step+ // assignment so a drag across a ringing blip doesn't pop.+ setClickVolume: (level) => {+ const next = clampClickVolume(level);+ if (next == null) return;+ clickVolume = next;+ if (clickBus) clickBus.gain.setTargetAtTime(next, ctx().currentTime, 0.01);+ },// Kit changes touch no timing, so — like the click toggle — they apply live:// whatever is already in the lookahead window finishes on the old kit and// everything scheduled after this lands on the new one.diff --git a/client/src/lib/drumPlayback.test.js b/client/src/lib/drumPlayback.test.jsindex afb5be59ad..767e2c7562 100644--- a/client/src/lib/drumPlayback.test.js+++ b/client/src/lib/drumPlayback.test.js@@ -1,6 +1,9 @@import { describe, it, expect } from 'vitest';import { parseDrumChart, CELL_GLYPHS } from './drumNotation.js';-import { buildDrumSchedule, resolveLoopRange, resolvePlayhead } from './drumPlayback.js';+import {+ buildDrumSchedule, resolveLoopRange, resolvePlayhead,+ clampClickVolume, DEFAULT_CLICK_VOLUME,+} from './drumPlayback.js';// Invented grooves only (privacy convention). Every assertion here is pure math// over the parsed chart — no AudioContext is created anywhere in this suite.@@ -257,3 +260,24 @@ describe('resolvePlayhead', () => {expect(resolvePlayhead(buildDrumSchedule(parseDrumChart(''), {}), 1)).toBeNull();});});++describe('clampClickVolume', () => {+ it('clamps a level into 0–1', () => {+ expect(clampClickVolume(0.4)).toBe(0.4);+ expect(clampClickVolume(0)).toBe(0);+ expect(clampClickVolume(1)).toBe(1);+ expect(clampClickVolume(2.5)).toBe(1);+ expect(clampClickVolume(-3)).toBe(0);+ expect(clampClickVolume('0.75')).toBe(0.75);+ });++ it('returns null — not silence — for a value that was never set', () => {+ // The sentinel contract: a caller falls back to DEFAULT_CLICK_VOLUME on null.+ // `Number('')` and `Number(null)` are both 0, so collapsing them into the+ // band would turn "no stored preference" into a muted metronome.+ for (const absent of [null, undefined, '', 'loud', NaN, {}]) {+ expect(clampClickVolume(absent)).toBeNull();+ }+ expect(DEFAULT_CLICK_VOLUME).toBe(1); // the fallback is FULL, never silence+ });+});diff --git a/client/src/lib/drumPlayer.test.js b/client/src/lib/drumPlayer.test.jsindex e9263d5f55..0ae70a6f38 100644--- a/client/src/lib/drumPlayer.test.js+++ b/client/src/lib/drumPlayer.test.js@@ -11,6 +11,19 @@ import { createFakeAudio } from '../test/fakeAudioContext.js';// One fake pair for the whole file — lib/audioContext.js caches the context.const { FakeAudioContext, audio } = createFakeAudio();+// GainNodes the player builds before any voice: the drum master and the+// metronome's own click bus. Every later gain in `audio.gains` is a voice+// envelope, so tests that reason about voices skip these two.+const BUS_GAINS = 2;++// Metronome blips that actually sounded: CLICK_VOICE is a lone square starting+// at 1600 Hz, a frequency no kit voice uses (noise sources carry no `frequency`).+const clickBlips = () => audio.oscillators.filter((o) => o.frequency?.values[0] === 1600);++// A bus's current level: set outright when the bus is built, then glided with+// setTargetAtTime on a live change (which the fake records into `values`).+const busLevel = (bus) => (bus.gain.values.length ? bus.gain.values.at(-1) : bus.gain.value);+// Advance the audio clock relatively, ticking the lookahead interval alongside.const drive = (deltaSec) => {const target = audio.now + deltaSec;@@ -112,10 +125,11 @@ describe('createDrumPlayer', () => {const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: X-g-'), {});await player.play();drive(2);- // Creation order is [master, ...accent layers, ...ghost layers] — a voice can- // be several layers (the 808 hat is a six-oscillator cluster), so compare the- // two halves rather than two fixed indices.- const peaks = audio.gains.slice(1).map((g) => Math.max(...g.gain.values, 0));+ // Creation order is [master, click bus, ...accent layers, ...ghost layers] —+ // the two buses are built up front in prepare(), and a voice can be several+ // layers (the 808 hat is a six-oscillator cluster), so compare the two halves+ // rather than two fixed indices.+ const peaks = audio.gains.slice(BUS_GAINS).map((g) => Math.max(...g.gain.values, 0));const half = peaks.length / 2;expect(Number.isInteger(half)).toBe(true);expect(Math.max(...peaks.slice(0, half))).toBeGreaterThan(Math.max(...peaks.slice(half)));@@ -148,7 +162,7 @@ describe('createDrumPlayer', () => {drive(0.2);expect(audio.oscillators.length).toBeGreaterThan(1);expect(audio.filters).toHaveLength(1);- expect(audio.gains).toHaveLength(2); // the master bus + one voice envelope+ expect(audio.gains).toHaveLength(BUS_GAINS + 1); // the buses + one voice envelopefor (const osc of audio.oscillators) expect(osc.connections).toEqual([audio.filters[0]]);player.stop();// Every partial was stopped — one tracked entry per oscillator, so an open@@ -223,6 +237,93 @@ describe('createDrumPlayer', () => {clicked.stop();});+ it('sounds the click on its own bus, at the level it was built with', async () => {+ const player = createDrumPlayer(CHART, { clickEnabled: true, clickVolume: 0.4 });+ await player.play();+ drive(1);+ const [master, clickBus] = audio.gains;+ // The bus hangs off the drum master (so it still goes through the master+ // soft-clipper) and carries the level.+ expect(clickBus.connections).toEqual([master]);+ expect(busLevel(clickBus)).toBe(0.4);+ // Every click envelope feeds the bus, and no KIT voice does.+ const clickVoices = audio.gains.filter((g) => g.connections.includes(clickBus));+ expect(clickVoices.length).toBeGreaterThan(0);+ // Nothing on the master is also on the click bus — a kit voice riding the+ // click bus would duck with the metronome slider.+ const masterVoices = audio.gains.filter((g) => g.connections.includes(master));+ expect(masterVoices.some((g) => clickVoices.includes(g))).toBe(false);+ player.stop();+ });++ it('setClickVolume moves the bus live, without stopping playback', async () => {+ const player = createDrumPlayer(CHART, { clickEnabled: true });+ await player.play();+ drive(0.5);+ const clickBus = audio.gains[1];+ expect(busLevel(clickBus)).toBe(1); // default: unchanged from before+ // A bus move reaches clicks ALREADY scheduled in the lookahead window — that+ // is the whole reason the level isn't folded into each click's velocity.+ player.setClickVolume(0.25);+ expect(busLevel(clickBus)).toBe(0.25);+ expect(player.isPlaying()).toBe(true);+ // A garbled level is ignored rather than silencing the click.+ player.setClickVolume('nope');+ expect(busLevel(clickBus)).toBe(0.25);+ player.stop();+ });++ it('schedules no click voice at all once the level is zero', async () => {+ // Dragging the slider to 0 deliberately does NOT flip the mute toggle, and+ // the level persists — so a silent click that still built a voice per beat+ // would do that forever, on every chart, for nothing.+ const muted = createDrumPlayer(CHART, { clickEnabled: false });+ await muted.play();+ drive(2.5);+ const kitOnly = audio.oscillators.length;+ muted.stop();++ audio.reset();+ const zeroed = createDrumPlayer(CHART, { clickEnabled: true, clickVolume: 0 });+ await zeroed.play();+ drive(2.5);+ // Level 0 costs exactly what muting costs: not one extra node, and not one+ // click blip.+ expect(audio.oscillators).toHaveLength(kitOnly);+ expect(clickBlips()).toHaveLength(0);+ zeroed.stop();++ // Turning it back up mid-run resumes the click without a restart.+ audio.reset();+ const raised = createDrumPlayer(CHART, { clickEnabled: true, clickVolume: 0 });+ await raised.play();+ drive(0.5);+ expect(clickBlips()).toHaveLength(0);+ raised.setClickVolume(1);+ drive(1);+ expect(clickBlips().length).toBeGreaterThan(0);+ raised.stop();+ });++ it('counts in with the metronome click, not with the kit snare', async () => {+ // `sound: 'click'` is not a kit piece — left to kitVoiceLayers it falls+ // through to the SNARE, which made a count-in four snare hits.+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nK: o---'), {+ countInBars: 1, clickEnabled: false, clickVolume: 0.5,+ });+ await player.play();+ drive(1.2); // the 1s count-in bar, then the kick on bar 1+ const clickBus = audio.gains[1];+ // Four click blips, one per count-in beat, each routed through the bus.+ const blips = clickBlips();+ expect(blips).toHaveLength(4);+ expect(audio.gains.filter((g) => g.connections.includes(clickBus))).toHaveLength(4);+ // The count-in sounds even with the through-music click muted ("just count+ // me in"), and the kick still lands on the kit master.+ expect(audio.oscillators.length).toBeGreaterThan(blips.length);+ player.stop();+ });+it('stop() clears the interval, silences live voices and clears the playhead', async () => {const steps = [];const player = createDrumPlayer(CHART, { onStep: (i) => steps.push(i) });diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex d3f7e2b492..98bd3bdf88 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -254,9 +254,11 @@ export default function SongBookViewer() {}, [stop]);// Play-mode shortcuts. A drum chart rebinds them onto the kit transport (space- // play/stop, +/- BPM, [ ] loop ends) since transpose/scroll-speed don't apply.+ // play/stop, +/- BPM, [ ] loop ends, m mutes the click) since transpose/+ // scroll-speed don't apply.const drumShortcuts = {' ': drum.toggle,+ m: () => drum.setClickEnabled(!drum.clickEnabled),'+': () => drum.setBpm(drum.bpm + 1),'=': () => drum.setBpm(drum.bpm + 1),'-': () => drum.setBpm(drum.bpm - 1),@@ -587,6 +589,8 @@ export default function SongBookViewer() {barCount={drum.barCount}clickEnabled={drum.clickEnabled}onClickToggle={drum.setClickEnabled}+ clickVolume={drum.clickVolume}+ onClickVolumeChange={drum.setClickVolume}kitId={drum.kitId}onKitChange={drum.setKitId}beatsPerBar={drum.beatsPerBar}diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 16844d7732..dda7922762 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -297,6 +297,51 @@ K: o - - - - - o -`;expect(await screen.findByLabelText('Turn the metronome on')).toBeTruthy();});+ it('mutes the metronome from the m shortcut as well as the button', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ await screen.findByLabelText('Turn the metronome off');+ fireEvent.keyDown(window, { key: 'm' });+ expect(await screen.findByLabelText('Turn the metronome on')).toBeTruthy();+ fireEvent.keyDown(window, { key: 'm' });+ expect(await screen.findByLabelText('Turn the metronome off')).toBeTruthy();+ });++ it('defaults the metronome to full and persists a level per machine', async () => {+ api.getSong.mockResolvedValue(drumSong());+ const { unmount } = renderPage();+ const volume = await screen.findByLabelText('Metronome volume');+ // No stored level is "never chosen" → full, NOT silent.+ expect(volume.value).toBe('100');+ fireEvent.change(volume, { target: { value: '30' } });+ await waitFor(() => expect(screen.getByLabelText('Metronome volume').value).toBe('30'));+ expect(globalThis.localStorage.getItem('songbook:drumClickVolume')).toBe('0.3');+ // The click is a reference pulse, not song content — no record write, and+ // the level is global rather than keyed by song.+ expect(api.updateSong).not.toHaveBeenCalled();+ unmount();++ renderPage();+ await waitFor(() => expect(screen.getByLabelText('Metronome volume').value).toBe('30'));+ });++ it('raising the level off silence unmutes, so the slider is never a dead control', async () => {+ globalThis.localStorage.setItem('songbook:drumClick', '0');+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ const volume = await screen.findByLabelText('Metronome volume');+ expect(screen.getByLabelText('Turn the metronome on')).toBeTruthy(); // muted+ fireEvent.change(volume, { target: { value: '60' } });+ // Reaching for the level is an intent to HEAR it.+ expect(await screen.findByLabelText('Turn the metronome off')).toBeTruthy();++ // The reverse is deliberately not wired: dragging to zero leaves the+ // toggle alone, so unmuting later can't come back silent.+ fireEvent.change(screen.getByLabelText('Metronome volume'), { target: { value: '0' } });+ await waitFor(() => expect(screen.getByLabelText('Metronome volume').value).toBe('0'));+ expect(screen.getByLabelText('Turn the metronome off')).toBeTruthy();+ });+it('reveals the loop bar range only when looping is on', async () => {api.getSong.mockResolvedValue(drumSong());renderPage();diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 4f0603ff30..8b4c56dddc 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -55,6 +55,9 @@ export const createFakeAudio = ({ suspended = false } = {}) => {values,setValueAtTime: (v) => values.push(v),exponentialRampToValueAtTime: (v) => values.push(v),+ // Glide to a target (drumPlayback's click-volume bus) — recorded like any+ // other scheduled value so a test reads the level off `values`.+ setTargetAtTime: (v) => values.push(v),};};function FakeAudioContext() {