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
refactor: share normalizeBeatsPerBar between the scheduler and BeatPulse (#4130)
Adam Eivy095d3398d1dd
diff --git a/client/src/components/songs/Metronome.test.jsx b/client/src/components/songs/Metronome.test.jsxindex e0c74f84f6..5db1881e49 100644--- a/client/src/components/songs/Metronome.test.jsx+++ b/client/src/components/songs/Metronome.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';// Mock the metronome engine — jsdom has no Web Audio. Track instances so the// test can assert start/stop and setBpm wiring without driving the audio clock.@@ -57,6 +57,22 @@ describe('Metronome component', () => {expect(input).toHaveValue(320);});+ // The engine reports `countIn` while the shared <BeatPulse> takes `countingIn`+ // — a field-name slip would silently draw count-in beats as ordinary ones.+ it('maps the engine beat onto the shared pulse, count-in included', async () => {+ render(<Metronome tempo={120} score="time: 4/4" />);+ fireEvent.click(screen.getByRole('button', { name: /start/i }));+ await waitFor(() => expect(engine.opts).toHaveLength(1));++ act(() => engine.opts[0].onBeat({ beat: 2, bar: 0, accent: false, countIn: true }));+ expect(screen.getByRole('status')).toHaveAttribute('aria-label', 'Counting in, beat 2');+ expect(screen.getByText('Count-in…')).toBeInTheDocument();++ act(() => engine.opts[0].onBeat({ beat: 3, bar: 4, accent: false, countIn: false }));+ expect(screen.getByRole('status')).toHaveAttribute('aria-label', 'Beat 3');+ expect(screen.getByText('Bar 4')).toBeInTheDocument();+ });+it('omits the count-in when the toggle is unchecked', async () => {render(<Metronome tempo={100} score="time: 4/4" />);fireEvent.click(screen.getByLabelText(/count-in/i));diff --git a/client/src/components/ui/BeatPulse.jsx b/client/src/components/ui/BeatPulse.jsxindex f35aa027d4..c6d32e8221 100644--- a/client/src/components/ui/BeatPulse.jsx+++ b/client/src/components/ui/BeatPulse.jsx@@ -9,10 +9,11 @@* them with a different readout ("Bar 3", "2/8 bars", "5/12 chords"), so the* text stays with the host.*- * Conventions the copies agreed on and this keeps:- * - beat 1 is the downbeat and reads a size larger, matching the accented click;- * - a count-in beat lights amber (`port-warning`) so "not yet" is unmistakable;- * - unlit dots are `port-border`, i.e. the same weight as any inert chrome.+ * What the copies already agreed on and this keeps: a count-in beat lights amber+ * (`port-warning`) so "not yet" is unmistakable, and unlit dots are+ * `port-border`, the same weight as any inert chrome. Newly canonical for every+ * surface: beat 1 is drawn a size larger, matching the accented click — the+ * Metronome had that downbeat accent and the transports didn't.** `beat` is 1-based and nullish/`0` when stopped — the audible click is easy to* lose under a backing track, so "nothing lit" has to read as stopped. Hosts@@ -20,15 +21,18 @@* lives here once rather than being re-typed at every call site.*/+import { normalizeBeatsPerBar } from '../../lib/metronome.js';+// Lit dots are `port-success`, not `port-accent`: in the transport bars the// accent color already means "this control is engaged" (`activeCtrlClass`), and// a beat dot borrowing it competed with the play button. Green reads as// "sounding now" and stays clearly distinct from the amber count-in.const litTone = (countingIn) => (countingIn ? 'bg-port-warning' : 'bg-port-success');-export default function BeatPulse({ beatsPerBar = 4, beat = null, countingIn = false }) {- // A malformed time signature must not blank the row out.- const beats = Number.isFinite(beatsPerBar) ? Math.max(1, Math.floor(beatsPerBar)) : 4;+export default function BeatPulse({ beatsPerBar, beat = null, countingIn = false }) {+ // Same normalization the scheduler applies, so a garbled `time:` header can't+ // leave the dots disagreeing with the clicks.+ const beats = normalizeBeatsPerBar(beatsPerBar);const label = countingIn? `Counting in, beat ${beat || 1}`: (beat ? `Beat ${beat}` : 'Stopped');diff --git a/client/src/components/ui/BeatPulse.test.jsx b/client/src/components/ui/BeatPulse.test.jsxindex 70ca249d96..dc62eccf88 100644--- a/client/src/components/ui/BeatPulse.test.jsx+++ b/client/src/components/ui/BeatPulse.test.jsx@@ -64,13 +64,13 @@ describe('BeatPulse', () => {expect(screen.getByRole('status')).toHaveAttribute('aria-label', 'Stopped');});- it('falls back to 4 beats when the time signature is unusable', () => {- const { container } = render(<BeatPulse beatsPerBar={NaN} beat={null} />);- expect(dotsOf(container)).toHaveLength(4);- });-- it('never renders an empty row for a zero or negative beat count', () => {- const { container } = render(<BeatPulse beatsPerBar={0} beat={null} />);- expect(dotsOf(container)).toHaveLength(1);- });+ // The scheduler reads a garbled numerator as 4/4 (`normalizeBeatsPerBar`), so+ // the dots have to land on the same count or they stop matching the clicks.+ it.each([['absent', undefined], ['NaN', NaN], ['zero', 0]])(+ 'falls back to 4 beats for a %s time signature, like the scheduler does',+ (_label, beatsPerBar) => {+ const { container } = render(<BeatPulse beatsPerBar={beatsPerBar} beat={null} />);+ expect(dotsOf(container)).toHaveLength(4);+ },+ );});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9c4f24d2fb..fa4c918e15 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -146,7 +146,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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 `resumeAudioContext()` call with the teardown-race guard, the optional `audioSession` claim held for exactly as long as the transport sounds, `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`. |+| `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`, and `normalizeBeatsPerBar` — the ONE reading of a time-signature numerator (garbled/zero/negative → 4), shared by the scheduler and the visual `<BeatPulse>` so the dots can't disagree with the clicks. || `midiChords.js` | Chord detection for the MIDI visualization UI (#2477). `detectChordWindows(notes, { minWindowSec })` sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → `[{ startSec, endSec, label, midis }]` (adjacent same-label windows merged); `nameChord(pcs, bassPc)` maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (`C E G#`) rather than guessing wrong; `chordNoteNames(midis)` for tooltips. Pure — no canvas/React. || `midiNotes.js` | Minimal Standard MIDI File parser + normalizer for the MIDI visualization UI (#2477) — in-tree, zero deps. `parseMidiFile(arrayBuffer)` parses SMF format 0/1 (running status, note-on vel-0-as-off, tempo map incl. mid-file changes, SMPTE division, track names) into the piano-roll view-model `{ durationSec, minMidi, maxMidi, notes:[{id,midi,startSec,durationSec,velocity,track,name}], tracks, tempos }`. Throws on non-MIDI bytes. Consumed by `useMidiNotes` → `<MidiPianoRoll>`. NOT the lead-sheet parser (`scoreNotation.js`). || `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point) and `position()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. |diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsindex ec968354d4..43e086bedf 100644--- a/client/src/lib/metronome.js+++ b/client/src/lib/metronome.js@@ -43,6 +43,12 @@ export const clampBpm = (bpm) => {return Math.max(METRONOME_BPM_MIN, Math.min(METRONOME_BPM_MAX, Math.round(n)));};+// One canonical reading of a time-signature numerator: a garbled, zero or+// negative `beatsPerBar` falls back to 4/4 rather than producing a bar with no+// beats in it. The scheduler and the visual pulse must agree on this or the+// dots stop matching the clicks.+export const normalizeBeatsPerBar = (beatsPerBar) => Math.max(1, Math.floor(beatsPerBar) || DEFAULT_BEATS_PER_BAR);+// Seconds between beats at a given BPM (the beat unit is the time-signature// denominator, i.e. one click per notated beat).export const secondsPerBeat = (bpm) => 60 / (clampBpm(bpm) ?? DEFAULT_BPM);@@ -66,7 +72,7 @@ export const timeSignatureFromScore = (score) => {// (default beat 1); `countIn` flags the lead-in bars (bar 0). Exported so the UI// and tests can reason about positions without driving the audio clock.export const beatDescriptor = (idx, { beatsPerBar = DEFAULT_BEATS_PER_BAR, countInBars = 0, accentBeat = 1 } = {}) => {- const perBar = Math.max(1, Math.floor(beatsPerBar) || DEFAULT_BEATS_PER_BAR);+ const perBar = normalizeBeatsPerBar(beatsPerBar);const countInBeats = Math.max(0, Math.floor(countInBars) || 0) * perBar;if (idx < countInBeats) {const beat = (idx % perBar) + 1;@@ -100,7 +106,7 @@ export function createMetronome({onCountInComplete = null,} = {}) {let currentBpm = clampBpm(bpm) ?? DEFAULT_BPM;- const perBar = Math.max(1, Math.floor(beatsPerBar) || DEFAULT_BEATS_PER_BAR);+ const perBar = normalizeBeatsPerBar(beatsPerBar);const countIn = Math.max(0, Math.floor(countInBars) || 0);const descriptorOpts = { beatsPerBar: perBar, countInBars: countIn, accentBeat };