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
songs: add Web Audio metronome with count-in and beat indicator
[._.]/ Adam Eivy04fd0562e15d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex baf2ba30a1..142f0270c7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@- **Songs — an a cappella song workbench (Create → Songs)** — write, arrange, and learn songs like "500 Miles" by Peter, Paul and Mary. Each song tracks its key, tempo, and rhythm shape (slow 4/4 ballad, compound 6/8 dirge, free-time lament, and more), lyric sections, and the voice layers you're stacking — with per-layer learning notes. An "Add from ladder" picker seeds layers in the recommended foundation-first order (lead → bass → thirds → fifths → drone → counter-melody). A deep-linkable **Learning Guide** (Create → Songs → Learning Guide, or `/songs/guide`) covers dirge rhythm shapes with tempo bands, the layer-building ladder, a step-by-step practice sequence for learning a new song, and a plain-language musical-notation primer (staves, time signatures, note values, dynamics, reading a lead sheet). A worked "500 Miles" example is seeded on first visit. Reachable from `⌘K` and voice nav.- **Songs: AI generate, expand & evaluate** — like the manuscript and universe/series creators, the Songs workbench now drafts and critiques arrangements with AI. From the Songs list, **Generate** drafts a full arrangement (lyrics, voice layers, key/tempo/rhythm shape, notation, and learning notes) from the title/artist as a brief; inside the editor, **Generate draft** and **Expand current** rewrite or build on the open draft, and **Evaluate** scores the arrangement 0–100 for performance-readiness with concrete strengths, weaknesses, and suggestions. The model returns rhythm-shape and voice-layer ids the editor's pickers already understand. Generated drafts land in the editor for review and are never auto-saved.- **Songs: record & layer your own vocals** — record each part straight from the mic in the song editor (saved as a vocal take), assign takes to voice layers, then **Play layered** to start every unmuted take together — sample-aligned on one audio clock — so you can stack a lead, bass, and harmony and rehearse a cappella against yourself. Mute/solo individual takes, scrub each one with its own player, and the takes persist with the song.+- **Songs: a metronome with count-in and a visual beat pulse** — the song recorder now has a built-in metronome so you can keep time while you record. It defaults to the song's tempo (BPM) and derives its time signature from the sheet-music header (4/4 if none), accents beat 1 both audibly (a brighter click) and visually (a pulsing accent dot), and offers an optional one-bar count-in so you know exactly where beat 1 lands before you start singing. The clicks ride the same audio clock the layered playback uses, so the beat stays sample-accurate instead of drifting. This is also the shared timing grid the upcoming pitch-matching and sing-to-score features will build on.- **Daily budgets for the Chief of Staff's domains** — each domain (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) can now carry a daily cap on how many automatic actions it takes and how many minutes of work it does. When a domain reaches its cap it pauses that automatic work for the rest of the day and resumes after the counters reset at midnight; the Chief of Staff config panel shows each domain's usage so far today. Caps are off by default (blank means unlimited), so nothing changes until you set one. This rounds out the per-domain guardrails alongside the off / dry-run / execute controls.- **Scheduled "Claim Issue" task** — a new built-in CoS schedule (CoS → Schedule → Claim Issue) that runs the `/claim --issues` flow on a cadence: it picks the next open GitHub issue, creates its own `claim/issue-<num>` worktree, implements the fix, opens a PR that closes the issue, runs the configured reviewers, merges, and cleans up. Configurable per app via an **Issue Author Filter** — claim only issues filed by the repository owner (default) or any open issue regardless of author. Off by default; enable and pick a provider/model per app like the other improvement tasks.- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.diff --git a/client/src/components/songs/Metronome.jsx b/client/src/components/songs/Metronome.jsxnew file mode 100644index 0000000000..dcc942daa4--- /dev/null+++ b/client/src/components/songs/Metronome.jsx@@ -0,0 +1,159 @@+/**+ * Metronome — start/stop tempo reference with count-in and a visual beat pulse.+ *+ * Drives client/src/lib/metronome.js (sample-accurate Web Audio scheduler). The+ * BPM defaults from the song `tempo`; the time signature is derived from the+ * score header (default 4/4). Beat 1 is accented both audibly (brighter click)+ * and visually (filled accent dot). The optional one-bar count-in lets a singer+ * find beat 1 before recording / color-match begins.+ *+ * Reads tempo + score from props already on the song record — issues no fetch of+ * its own. Tears the metronome down on stop and on unmount so a navigation-away+ * can't leave a timer or scheduled audio running.+ */++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Play, Square, Timer } from 'lucide-react';+import toast from '../ui/Toast';+import {+ createMetronome,+ clampBpm,+ timeSignatureFromScore,+ METRONOME_BPM_MIN,+ METRONOME_BPM_MAX,+ DEFAULT_BPM,+} from '../../lib/metronome.js';++export default function Metronome({ tempo = null, score = '', countInBars = 1 }) {+ const [bpm, setBpm] = useState(() => clampBpm(tempo) ?? DEFAULT_BPM);+ const [countIn, setCountIn] = useState(true);+ const [running, setRunning] = useState(false);+ const [pulse, setPulse] = useState(null); // { beat, bar, accent, countIn }+ const metroRef = useRef(null);++ // Time signature from the score header — the dot row mirrors beats-per-bar.+ const timeSig = useMemo(() => timeSignatureFromScore(score), [score]);+ const beatsPerBar = timeSig.beats;++ const teardown = useCallback(() => {+ if (metroRef.current) {+ metroRef.current.stop();+ metroRef.current = null;+ }+ }, []);++ // Stop the metronome on unmount (deferred-work cleanup).+ useEffect(() => teardown, [teardown]);++ const stop = useCallback(() => {+ teardown();+ setRunning(false);+ setPulse(null);+ }, [teardown]);++ const start = useCallback(async () => {+ teardown();+ const metro = createMetronome({+ bpm,+ beatsPerBar,+ beatValue: timeSig.beatValue,+ countInBars: countIn ? countInBars : 0,+ onBeat: (info) => setPulse(info),+ });+ metroRef.current = metro;+ setRunning(true);+ await metro.start().catch((err) => {+ toast.error(err?.message || 'Could not start the metronome');+ stop();+ });+ }, [teardown, bpm, beatsPerBar, timeSig.beatValue, countIn, countInBars, stop]);++ const onBpmChange = useCallback((value) => {+ const next = clampBpm(value);+ if (next == null) return;+ setBpm(next);+ if (metroRef.current) metroRef.current.setBpm(next);+ }, []);++ const dots = useMemo(() => Array.from({ length: beatsPerBar }, (_, i) => i + 1), [beatsPerBar]);+ const activeBeat = running && pulse ? pulse.beat : 0;++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Timer size={15} className="text-port-accent" /> Metronome+ <span className="text-xs font-normal text-gray-500">{timeSig.beats}/{timeSig.beatValue}</span>+ </h3>+ <div className="flex items-center gap-2">+ {running ? (+ <button+ type="button"+ onClick={stop}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90"+ >+ <Square size={14} /> Stop+ </button>+ ) : (+ <button+ type="button"+ onClick={start}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"+ >+ <Play size={14} /> Start+ </button>+ )}+ </div>+ </div>++ {/* Visual beat pulse — one dot per beat; beat 1 is the accent. */}+ <div className="flex items-center gap-2 mt-3" aria-hidden="true">+ {dots.map((n) => {+ const isActive = n === activeBeat;+ const isAccent = n === 1;+ const tone = isActive+ ? (pulse?.countIn ? 'bg-port-warning' : 'bg-port-success')+ : 'bg-port-border';+ return (+ <span+ key={n}+ className={`rounded-full transition-transform duration-75 ${isAccent ? 'w-3.5 h-3.5' : 'w-2.5 h-2.5'} ${tone} ${isActive ? 'scale-125' : 'scale-100'}`}+ />+ );+ })}+ {running && (+ <span className="text-xs text-gray-500 ml-1">+ {pulse?.countIn ? 'Count-in…' : pulse?.bar ? `Bar ${pulse.bar}` : ''}+ </span>+ )}+ </div>++ <div className="flex items-end gap-4 mt-3 flex-wrap">+ <div>+ <label htmlFor="metronome-bpm" className="block text-xs text-gray-400 mb-1">Tempo (BPM)</label>+ <input+ id="metronome-bpm"+ type="number"+ inputMode="numeric"+ min={METRONOME_BPM_MIN}+ max={METRONOME_BPM_MAX}+ value={bpm}+ onChange={(e) => onBpmChange(e.target.value)}+ onBlur={() => onBpmChange(bpm)}+ className="w-24 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ <label htmlFor="metronome-countin" className="flex items-center gap-2 text-xs text-gray-400 pb-2 cursor-pointer">+ <input+ id="metronome-countin"+ type="checkbox"+ checked={countIn}+ onChange={(e) => setCountIn(e.target.checked)}+ className="accent-port-accent"+ />+ Count-in (one bar)+ </label>+ </div>+ </div>+ );+}diff --git a/client/src/components/songs/Metronome.test.jsx b/client/src/components/songs/Metronome.test.jsxnew file mode 100644index 0000000000..e0c74f84f6--- /dev/null+++ b/client/src/components/songs/Metronome.test.jsx@@ -0,0 +1,67 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { 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.+const engine = vi.hoisted(() => ({ instances: [], opts: [] }));+vi.mock('../../lib/metronome.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual, // keep the real clampBpm / timeSignatureFromScore pure helpers+ createMetronome: (opts) => {+ engine.opts.push(opts);+ const m = { start: vi.fn(() => Promise.resolve()), stop: vi.fn(), setBpm: vi.fn() };+ engine.instances.push(m);+ return m;+ },+ };+});+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++import Metronome from './Metronome.jsx';++describe('Metronome component', () => {+ beforeEach(() => {+ engine.instances = [];+ engine.opts = [];+ });++ it('defaults the BPM input from the song tempo', () => {+ render(<Metronome tempo={68} score="time: 4/4" />);+ expect(screen.getByLabelText('Tempo (BPM)')).toHaveValue(68);+ });++ it('shows the time signature derived from the score header', () => {+ render(<Metronome tempo={90} score={'time: 3/4\n| C4q D4q E4q |'} />);+ expect(screen.getByText('3/4')).toBeInTheDocument();+ });++ it('starts and stops the metronome, passing tempo + time-sig + count-in', async () => {+ render(<Metronome tempo={120} score="time: 4/4" />);+ fireEvent.click(screen.getByRole('button', { name: /start/i }));++ await waitFor(() => expect(engine.instances).toHaveLength(1));+ expect(engine.instances[0].start).toHaveBeenCalled();+ expect(engine.opts[0]).toMatchObject({ bpm: 120, beatsPerBar: 4, countInBars: 1 });++ // Once running, the control flips to Stop and tears the engine down on click.+ fireEvent.click(await screen.findByRole('button', { name: /stop/i }));+ expect(engine.instances[0].stop).toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /start/i })).toBeInTheDocument();+ });++ it('clamps the BPM input into the supported band', () => {+ render(<Metronome tempo={120} score="time: 4/4" />);+ const input = screen.getByLabelText('Tempo (BPM)');+ fireEvent.change(input, { target: { value: '5000' } });+ expect(input).toHaveValue(320);+ });++ 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));+ fireEvent.click(screen.getByRole('button', { name: /start/i }));+ await waitFor(() => expect(engine.opts).toHaveLength(1));+ expect(engine.opts[0].countInBars).toBe(0);+ });+});diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsxindex 100c4fcb5a..1ee65170a5 100644--- a/client/src/components/songs/SongRecordings.jsx+++ b/client/src/components/songs/SongRecordings.jsx@@ -20,6 +20,7 @@ import { startMemoRecording } from '../../lib/audioRecorder';import { createLayeredPlayer } from '../../lib/songPlayback';import { uploadFile, getUploadUrl } from '../../services/api';import { formatDurationMs } from '../../utils/formatters';+import Metronome from './Metronome';// Lower bound peak amplitude — below this the take is effectively silence// (dead mic / muted input), worth warning about before it joins the stack.@@ -32,7 +33,7 @@ const SILENCE_PEAK = 0.01;let tempSeq = 0;const tempRecordingId = () => `rec-new-${tempSeq++}`;-export default function SongRecordings({ recordings = [], layers = [], onChange }) {+export default function SongRecordings({ recordings = [], layers = [], onChange, tempo = null, score = '' }) {const [recording, setRecording] = useState(false);const [saving, setSaving] = useState(false);const [playing, setPlaying] = useState(false);@@ -175,6 +176,11 @@ export default function SongRecordings({ recordings = [], layers = [], onChange{recording && <span className="text-port-error"> ● Recording… sing now.</span>}</p>+ {/* Tempo reference + count-in — the shared timing grid for recording. */}+ <div className="mb-3">+ <Metronome tempo={tempo} score={score} />+ </div>+{/* Layer the next take targets (optional) */}{layers.length > 0 && !recording && (<div className="mb-3">diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d57d7f8cec..9c814277c1 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -89,6 +89,7 @@ grep -i "what you want to do" client/src/lib/README.md| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |+| `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`. || `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. || `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead. || `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex cce5cccae6..52403b01aa 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -55,6 +55,7 @@ export * from './voiceLabel.js';// === Page-scoped pure helpers ===export * from './cityPlaybackFrame.js';+export * from './metronome.js';export * from './pitchDetect.js';export * from './scoreNotation.js';export * from './scorePlayback.js';diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsnew file mode 100644index 0000000000..5590eed6dc--- /dev/null+++ b/client/src/lib/metronome.js@@ -0,0 +1,217 @@+// Sample-accurate metronome — the shared timing grid for the song system.+//+// Why Web Audio and not setInterval: a beat that rides setInterval drifts by+// tens of ms under load (same reason songPlayback.js stacks takes on one+// AudioContext clock rather than N <audio> elements). So we use the classic+// "two clocks" pattern — a coarse setInterval *lookahead* timer wakes every+// LOOKAHEAD_MS and schedules every click that falls inside the next+// SCHEDULE_AHEAD_S window directly on the AudioContext clock, which is+// sample-accurate. The UI/beat callbacks are fired with setTimeout aligned to+// each click's audio time so a visual pulse lands in sync with the click.+//+// This is the first real consumer of the song `tempo` (BPM) field. It exposes a+// beat-clock callback (`onBeat({ beat, bar, accent, countIn, whenAudioTime })`)+// so color-match (#1025) and sing-to-score (#1026) can later subscribe to the+// same grid. Pure-ish: no React; the <Metronome> component wraps it for UI.++import { parseScore } from './scoreNotation.js';++// BPM band — mirrors the server `tempo` validation (services/songs.js+// TEMPO_MIN / TEMPO_MAX, also enforced by the Zod schema in routes/songs.js).+export const METRONOME_BPM_MIN = 20;+export const METRONOME_BPM_MAX = 320;+export const DEFAULT_BPM = 120;++const DEFAULT_BEATS_PER_BAR = 4;+const LOOKAHEAD_MS = 25; // how often the lookahead timer wakes+const SCHEDULE_AHEAD_S = 0.12; // how far ahead of `currentTime` we schedule audio+const START_LEAD_S = 0.1; // small lead before the first beat absorbs jitter++// Lazily create + reuse one AudioContext for the metronome's clicks. Browsers+// cap the number of contexts; reusing one keeps every click on the same clock.+let sharedCtx = null;+function audioContext() {+ if (!sharedCtx) {+ const Ctor = window.AudioContext || window.webkitAudioContext;+ sharedCtx = new Ctor();+ }+ return sharedCtx;+}++// Clamp a BPM into the supported band. Returns null for non-numbers so a caller+// can distinguish "no/invalid value" from a legitimately-clamped number.+export const clampBpm = (bpm) => {+ // Absent (null / undefined / blank) is distinct from a clamped number — don't+ // let Number('') / Number(null) collapse to 0 and silently become the floor.+ if (bpm == null || bpm === '') return null;+ const n = Number(bpm);+ if (!Number.isFinite(n)) return null;+ return Math.max(METRONOME_BPM_MIN, Math.min(METRONOME_BPM_MAX, Math.round(n)));+};++// 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);++// Derive the time signature from a score. Accepts either the raw lead-sheet+// text or an already-parsed `{ beats, beatValue }` object. Defaults to 4/4 when+// absent (parseScore already falls back to 4/4 for a headerless score).+export const timeSignatureFromScore = (score) => {+ if (score && typeof score === 'object' && Number.isFinite(score.beats)) {+ return { beats: score.beats, beatValue: score.beatValue || 4 };+ }+ const parsed = parseScore(typeof score === 'string' ? score : '');+ return {+ beats: parsed.time?.beats || DEFAULT_BEATS_PER_BAR,+ beatValue: parsed.time?.beatValue || 4,+ };+};++// Pure beat-position math: map a global beat index (count-in beats first, then+// music beats) to its descriptor. `accent` marks the accented beat of the bar+// (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 countInBeats = Math.max(0, Math.floor(countInBars) || 0) * perBar;+ if (idx < countInBeats) {+ const beat = (idx % perBar) + 1;+ return { beat, bar: 0, accent: beat === accentBeat, countIn: true };+ }+ const m = idx - countInBeats;+ const beat = (m % perBar) + 1;+ return { beat, bar: Math.floor(m / perBar) + 1, accent: beat === accentBeat, countIn: false };+};++/**+ * Build a metronome over a tempo + time signature.+ *+ * @param {object} opts+ * @param {number} opts.bpm — beats per minute (clamped 20–320).+ * @param {number} opts.beatsPerBar — numerator of the time signature.+ * @param {number} opts.beatValue — denominator (carried for consumers; click cadence is BPM-based).+ * @param {number} opts.countInBars — lead-in bars before bar 1 (0 = none).+ * @param {number} opts.accentBeat — which beat of the bar is accented (default 1).+ * @param {(info) => void} opts.onBeat — fired on every beat with { beat, bar, accent, countIn, whenAudioTime }.+ * @param {(info) => void} opts.onCountInComplete — fired once at the first music downbeat.+ * @returns {{ start, stop, setBpm, isRunning, getBpm, getBeatsPerBar }}+ */+export function createMetronome({+ bpm = DEFAULT_BPM,+ beatsPerBar = DEFAULT_BEATS_PER_BAR,+ beatValue = 4,+ countInBars = 0,+ accentBeat = 1,+ onBeat = null,+ onCountInComplete = null,+} = {}) {+ let currentBpm = clampBpm(bpm) ?? DEFAULT_BPM;+ const perBar = Math.max(1, Math.floor(beatsPerBar) || DEFAULT_BEATS_PER_BAR);+ const countIn = Math.max(0, Math.floor(countInBars) || 0);+ const descriptorOpts = { beatsPerBar: perBar, countInBars: countIn, accentBeat };++ let running = false;+ let tickIndex = 0; // global beats scheduled so far (count-in + music)+ let nextNoteTime = 0; // audio time of the next beat to schedule+ let lookahead = null; // setInterval id for the lookahead scheduler+ const pendingTimeouts = new Set(); // beat-callback timers, cleared on stop()++ // Schedule one short click tone at audio time `when`. The accented beat is a+ // brighter, louder blip so beat 1 is audible without watching the screen.+ const scheduleClick = (when, accent) => {+ const c = audioContext();+ const osc = c.createOscillator();+ const gain = c.createGain();+ osc.frequency.value = accent ? 1500 : 1000;+ const peak = accent ? 0.5 : 0.3;+ // Fast attack, short exponential decay — a click, not a tone.+ gain.gain.setValueAtTime(0.0001, when);+ gain.gain.exponentialRampToValueAtTime(peak, when + 0.001);+ gain.gain.exponentialRampToValueAtTime(0.0001, when + 0.05);+ osc.connect(gain).connect(c.destination);+ osc.start(when);+ osc.stop(when + 0.06);+ osc.onended = () => {+ // Outside the request lifecycle — never let a disconnect throw escape.+ try { osc.disconnect(); gain.disconnect(); } catch { /* already torn down */ }+ };+ };++ // Fire the beat/count-in callbacks aligned to the click's audio time.+ const dispatchBeat = (idx, when) => {+ const info = { ...beatDescriptor(idx, descriptorOpts), whenAudioTime: when };+ const firstMusicBeat = !info.countIn && idx === countIn * perBar;+ const delayMs = Math.max(0, (when - audioContext().currentTime) * 1000);+ const id = setTimeout(() => {+ pendingTimeouts.delete(id);+ // setTimeout runs outside the request lifecycle — a throwing consumer+ // callback must not crash the process (CLAUDE.md deferred-work boundary).+ try {+ if (firstMusicBeat && onCountInComplete) onCountInComplete(info);+ if (onBeat) onBeat(info);+ } catch (err) {+ console.error(`❌ Metronome beat callback failed: ${err.message}`);+ }+ }, delayMs);+ pendingTimeouts.add(id);+ };++ // Lookahead scheduler — schedule every beat inside the next window.+ const scheduler = () => {+ const c = audioContext();+ while (nextNoteTime < c.currentTime + SCHEDULE_AHEAD_S) {+ const accent = beatDescriptor(tickIndex, descriptorOpts).accent;+ scheduleClick(nextNoteTime, accent);+ dispatchBeat(tickIndex, nextNoteTime);+ nextNoteTime += secondsPerBeat(currentBpm);+ tickIndex += 1;+ }+ };++ const start = async () => {+ if (running) return;+ const c = audioContext();+ // Autoplay policy starts the context suspended until a user gesture.+ if (c.state === 'suspended') await c.resume();+ running = true;+ tickIndex = 0;+ nextNoteTime = c.currentTime + START_LEAD_S;+ scheduler(); // schedule the first window synchronously+ lookahead = setInterval(() => {+ // Interval callback is outside the request lifecycle — guard it.+ try {+ scheduler();+ } catch (err) {+ console.error(`❌ Metronome scheduler failed: ${err.message}`);+ }+ }, LOOKAHEAD_MS);+ };++ // Cancel all scheduled work: the lookahead interval and every pending beat+ // callback. Already-scheduled audio nodes stop on their own `osc.stop(when)`.+ const stop = () => {+ running = false;+ if (lookahead != null) {+ clearInterval(lookahead);+ lookahead = null;+ }+ for (const id of pendingTimeouts) clearTimeout(id);+ pendingTimeouts.clear();+ tickIndex = 0;+ };++ // Change tempo live — takes effect on the next scheduled beat.+ const setBpm = (next) => {+ const clamped = clampBpm(next);+ if (clamped != null) currentBpm = clamped;+ };++ return {+ start,+ stop,+ setBpm,+ isRunning: () => running,+ getBpm: () => currentBpm,+ getBeatsPerBar: () => perBar,+ };+}diff --git a/client/src/lib/metronome.test.js b/client/src/lib/metronome.test.jsnew file mode 100644index 0000000000..ab111539a1--- /dev/null+++ b/client/src/lib/metronome.test.js@@ -0,0 +1,233 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ beatDescriptor,+ clampBpm,+ secondsPerBeat,+ timeSignatureFromScore,+ createMetronome,+ METRONOME_BPM_MIN,+ METRONOME_BPM_MAX,+} from './metronome.js';++// jsdom has no Web Audio. Minimal fake AudioContext that records every scheduled+// click's start time + frequency, with a manually-advanceable `currentTime` so a+// test can drive the lookahead scheduler deterministically.+function makeFakeAudioContext() {+ const ctx = {+ currentTime: 0,+ state: 'running',+ destination: {},+ started: [], // { t, freq }+ resume() { ctx.state = 'running'; return Promise.resolve(); },+ createGain() {+ return {+ gain: { value: 0, setValueAtTime() {}, exponentialRampToValueAtTime() {} },+ connect(node) { return node; },+ disconnect() {},+ };+ },+ createOscillator() {+ const osc = {+ frequency: { value: 0 },+ onended: null,+ connect(node) { return node; },+ disconnect() {},+ start(t) { ctx.started.push({ t, freq: osc.frequency.value }); },+ stop() {},+ };+ return osc;+ },+ };+ return ctx;+}++// The metronome module caches one shared AudioContext, so we reuse a single+// fake across tests (resetting its state each time) rather than swapping it.+// `window.AudioContext` must be a real constructor — an arrow fn isn't `new`able.+let fakeCtx = makeFakeAudioContext();++beforeEach(() => {+ fakeCtx.currentTime = 0;+ fakeCtx.state = 'running';+ fakeCtx.started.length = 0;+ function FakeAudioContext() { return fakeCtx; }+ window.AudioContext = FakeAudioContext;+});++afterEach(() => {+ vi.useRealTimers();+});++describe('clampBpm', () => {+ it('clamps into the 20–320 band and rounds', () => {+ expect(clampBpm(10)).toBe(METRONOME_BPM_MIN);+ expect(clampBpm(999)).toBe(METRONOME_BPM_MAX);+ expect(clampBpm(120.4)).toBe(120);+ expect(clampBpm('68')).toBe(68);+ });++ it('returns null for non-numbers (absent vs clamped)', () => {+ expect(clampBpm('abc')).toBeNull();+ expect(clampBpm(null)).toBeNull();+ expect(clampBpm(undefined)).toBeNull();+ });+});++describe('secondsPerBeat', () => {+ it('derives the interval from BPM', () => {+ expect(secondsPerBeat(120)).toBeCloseTo(0.5, 6);+ expect(secondsPerBeat(60)).toBeCloseTo(1, 6);+ expect(secondsPerBeat(68)).toBeCloseTo(60 / 68, 6);+ });++ it('falls back to the default tempo for invalid input', () => {+ expect(secondsPerBeat('nope')).toBeCloseTo(0.5, 6); // DEFAULT_BPM 120+ });+});++describe('timeSignatureFromScore', () => {+ it('derives the time signature from the score header', () => {+ expect(timeSignatureFromScore('time: 3/4\n| C4q D4q E4q |')).toEqual({ beats: 3, beatValue: 4 });+ expect(timeSignatureFromScore('time: 6/8\n| C4e |')).toEqual({ beats: 6, beatValue: 8 });+ });++ it('defaults to 4/4 when absent or empty', () => {+ expect(timeSignatureFromScore('')).toEqual({ beats: 4, beatValue: 4 });+ expect(timeSignatureFromScore(null)).toEqual({ beats: 4, beatValue: 4 });+ expect(timeSignatureFromScore('| C4q |')).toEqual({ beats: 4, beatValue: 4 });+ });++ it('accepts a pre-parsed { beats, beatValue } object', () => {+ expect(timeSignatureFromScore({ beats: 5, beatValue: 4 })).toEqual({ beats: 5, beatValue: 4 });+ });+});++describe('beatDescriptor', () => {+ it('accents beat 1 of every bar', () => {+ const opts = { beatsPerBar: 4, countInBars: 0 };+ expect(beatDescriptor(0, opts)).toMatchObject({ beat: 1, bar: 1, accent: true, countIn: false });+ expect(beatDescriptor(1, opts)).toMatchObject({ beat: 2, accent: false });+ expect(beatDescriptor(3, opts)).toMatchObject({ beat: 4, accent: false });+ expect(beatDescriptor(4, opts)).toMatchObject({ beat: 1, bar: 2, accent: true });+ });++ it('places the count-in bar as bar 0 then starts the music at bar 1', () => {+ const opts = { beatsPerBar: 4, countInBars: 1 };+ // 4 count-in beats (idx 0..3), then music starts at idx 4.+ for (let i = 0; i < 4; i += 1) {+ expect(beatDescriptor(i, opts)).toMatchObject({ bar: 0, countIn: true, beat: i + 1 });+ }+ expect(beatDescriptor(4, opts)).toMatchObject({ bar: 1, countIn: false, beat: 1, accent: true });+ expect(beatDescriptor(7, opts)).toMatchObject({ bar: 1, countIn: false, beat: 4 });+ expect(beatDescriptor(8, opts)).toMatchObject({ bar: 2, countIn: false, beat: 1, accent: true });+ });++ it('honours a custom beats-per-bar (3/4)', () => {+ const opts = { beatsPerBar: 3, countInBars: 1 };+ // count-in = 3 beats; music begins at idx 3.+ expect(beatDescriptor(2, opts)).toMatchObject({ bar: 0, countIn: true, beat: 3 });+ expect(beatDescriptor(3, opts)).toMatchObject({ bar: 1, countIn: false, beat: 1 });+ expect(beatDescriptor(6, opts)).toMatchObject({ bar: 2, beat: 1 });+ });++ it('respects a custom accentBeat', () => {+ expect(beatDescriptor(2, { beatsPerBar: 4, accentBeat: 3 })).toMatchObject({ beat: 3, accent: true });+ expect(beatDescriptor(0, { beatsPerBar: 4, accentBeat: 3 })).toMatchObject({ beat: 1, accent: false });+ });+});++// Drive both clocks in lockstep: advance the AudioContext clock and the fake+// timers together so the lookahead scheduler + beat-callback timeouts fire as in+// real time.+async function runFor(ms, step = 10) {+ for (let elapsed = 0; elapsed < ms; elapsed += step) {+ fakeCtx.currentTime += step / 1000;+ await vi.advanceTimersByTimeAsync(step);+ }+}++describe('createMetronome scheduling', () => {+ it('schedules clicks one beat apart at the given BPM', async () => {+ vi.useFakeTimers();+ const metro = createMetronome({ bpm: 120, beatsPerBar: 4, countInBars: 0 });+ await metro.start();+ await runFor(2000);+ metro.stop();++ expect(fakeCtx.started.length).toBeGreaterThanOrEqual(3);+ const times = fakeCtx.started.map((s) => s.t);+ for (let i = 1; i < times.length; i += 1) {+ expect(times[i] - times[i - 1]).toBeCloseTo(0.5, 3); // 60/120+ }+ });++ it('accents beat 1 of each bar with a brighter click', async () => {+ vi.useFakeTimers();+ const metro = createMetronome({ bpm: 240, beatsPerBar: 4, countInBars: 0 });+ await metro.start();+ await runFor(1200); // 240bpm → 0.25s/beat → ~4 beats in a bar+ metro.stop();++ // Every 4th click (beat 1) is the accent frequency.+ fakeCtx.started.forEach((click, i) => {+ const expected = i % 4 === 0 ? 1500 : 1000;+ expect(click.freq).toBe(expected);+ });+ });++ it('fires the count-in beats then onCountInComplete at the first music downbeat', async () => {+ vi.useFakeTimers();+ const beats = [];+ let countInCompleteAt = null;+ const metro = createMetronome({+ bpm: 120,+ beatsPerBar: 4,+ countInBars: 1,+ onBeat: (info) => beats.push(info),+ onCountInComplete: () => { countInCompleteAt = beats.length; },+ });+ await metro.start();+ await runFor(3200); // 1 count-in bar (2s) + ~2 music beats+ metro.stop();++ const countInBeats = beats.filter((b) => b.countIn);+ expect(countInBeats).toHaveLength(4); // one bar of count-in+ // onCountInComplete fires just before the first music beat was dispatched.+ expect(countInCompleteAt).toBe(4);+ const firstMusic = beats[4];+ expect(firstMusic).toMatchObject({ countIn: false, bar: 1, beat: 1, accent: true });+ // Beat callbacks carry the audio-clock timestamp for downstream consumers.+ expect(typeof firstMusic.whenAudioTime).toBe('number');+ });++ it('stop() cancels the lookahead interval and pending beat callbacks', async () => {+ vi.useFakeTimers();+ const beats = [];+ const metro = createMetronome({ bpm: 120, beatsPerBar: 4, onBeat: (info) => beats.push(info) });+ await metro.start();+ await runFor(600);+ metro.stop();++ expect(metro.isRunning()).toBe(false);+ const clicksAfterStop = fakeCtx.started.length;+ const beatsAfterStop = beats.length;++ // Advancing well past stop must schedule no further clicks or callbacks.+ await runFor(2000);+ expect(fakeCtx.started.length).toBe(clicksAfterStop);+ expect(beats.length).toBe(beatsAfterStop);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('setBpm changes the interval of subsequently-scheduled beats', async () => {+ vi.useFakeTimers();+ const metro = createMetronome({ bpm: 60, beatsPerBar: 4, countInBars: 0 });+ expect(metro.getBpm()).toBe(60);+ metro.setBpm(120);+ expect(metro.getBpm()).toBe(120);+ metro.setBpm(99999); // clamped+ expect(metro.getBpm()).toBe(METRONOME_BPM_MAX);+ metro.setBpm('garbage'); // ignored — keeps last valid+ expect(metro.getBpm()).toBe(METRONOME_BPM_MAX);+ });+});diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsxindex ccdb000493..7a95b7f6e6 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/SongEditor.jsx@@ -564,6 +564,8 @@ export default function SongEditor() {<SongRecordingsrecordings={song.recordings || []}layers={song.layers || []}+ tempo={song.tempo ?? null}+ score={song.score}onChange={(recordings) => setField('recordings', recordings)}/>@@ -812,6 +814,8 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs<SongRecordingsrecordings={song.recordings || []}layers={song.layers || []}+ tempo={song.tempo ?? null}+ score={song.score}onChange={(recordings) => setField('recordings', recordings)}/></div>