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
feat: SongBook drum charts — kit-grid notation, SVG sheet, tempo-adjustable play-along (#3115)
[._.]/ Adam Eivy7b98314c0d95
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0ef2d79bc8..99f0687855 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -96,3 +96,9 @@- **[issue-3110] A task that runs a bundled slashdo workflow no longer pastes the whole 250KB procedure into the agent's prompt.** Dispatching `/do:review` or `/do:better` handed the agent its fully-expanded command body — 258KB, roughly 65k tokens — on every single spawn, which on a smaller model could crowd out or overflow the context the actual work needed. Most of that bulk was never reachable: each of those commands carries all five of slashdo's reviewer loops (Copilot, arbitrary GitHub reviewer, local CLI agent, local model, and the multi-reviewer wrapper) though one run drives exactly one of them. When your reviewers are known — pinned on the task, or set in Code Review Defaults — the unreachable loops are now dropped, cutting 23% off `/do:review` (258KB down to 199KB) and 28% off `/do:depfree`; the run is given an explicit `--review-with` so it can't pick a reviewer whose procedure was left out. Whatever is still oversized is written to disk once and handed to the agent as a file path to read, instead of pasted. Nothing is pruned when the reviewer set isn't known — an over-trimmed prompt that drops the loop the agent needed would be worse than a fat one — and API providers, which have no file tools, still get the body inlined (now with a log line naming the command and its size, so the cost is visible rather than silent).- **Antigravity (agy) agents no longer die on the first-run folder-trust gate.** An agy agent launched in a fresh worktree could fail immediately with `Do you trust the contents of this project?` and a `paste-not-rendered` error, having done nothing. The spawner waits for a positive "input box is live" signal before pasting the task prompt, and for claude that signal — the terminal's bracketed-paste mode turning back on — arrives exactly when its composer appears. agy turns it on much earlier, when it enters full-screen mode, while it is still signing in and before its trust prompt has even drawn. So on any run where agy's sign-in outlasted the startup delay, the prompt was pasted into a screen that wasn't ready; the trust menu then appeared and swallowed it along with all three retries, and because the trust prompt hadn't been seen yet the auto-confirm never fired. agy now additionally waits for its composer footer, which only draws once the trust gate is resolved, so the trust prompt is confirmed first and the prompt lands in the input box. (`--dangerously-skip-permissions` does not bypass this gate, contrary to what the code previously assumed.)- Handshake markers are now matched against a rolling window of recent terminal output rather than a single read, so a prompt or footer that arrives split across two reads is still recognized.++## SongBook drums++- **[issue-3115] A drummer can finally keep a groove in the SongBook, read it as a real kit chart, and play along at a tempo they choose.** `drums` joins the instrument list and `drum` the content formats, so Drums appears in the index filter, the import form and the editor for free. A drum chart is authored as a grid that reads like the sheet it draws — `time:` / `tempo:` / `subdivision:` headers, blank-line-separated bars with an optional `x2` repeat on the label, one row per kit piece (crash, ride, hi-hat, two toms, snare, floor tom, kick, hi-hat foot) and one character per step (`-` rest, `x` normal, `X` accent, `o` open hat, `g` ghost, `f` flam; spacing optional). The parser is forgiving: a short row pads with rests, an over-long row truncates, an unknown piece or cell is reported and skipped, and the bars that did parse still render with the problems listed underneath rather than a blank page.+- The chart renders as a labelled, bar-gridded kit sheet in hand-rolled SVG — no engraving library, theme-aware ink in both light and dark, beat boundaries emphasized so a 16th-note row still reads in fours, and each bar scrolling as a unit on a phone. Play mode adds a transport bar: a practice-tempo input + slider (20–320) seeded from the chart's own `tempo:`, percent-of-written buttons (50/75/90/100/110%), a count-in of up to 2 bars, a loop toggle with a from/to bar range, and a metronome click layered over the kit on the same clock. A playhead column tracks the sounding step and the screen stays awake while it plays; space plays/stops, `+`/`-` nudge the tempo, `[`/`]` set the loop ends at the bar you're on.+- The kit is synthesized, so nothing is downloaded and no samples ship. The practice tempo is remembered per song on the machine you set it on — it is never written into the record, so it can't sync over a peer's own practice speed. Non-drum songs are untouched: transpose, chord diagrams and autoscroll behave exactly as before, and the transpose/voicing controls simply hide for a kit chart where they'd mean nothing. Pasting a drum chart into the importer auto-selects the format and previews it on the grid, and one example groove ("Example Rock Beat") ships as the format's worked reference — existing installs receive it on upgrade without ever overwriting a copy you've edited or deleted.diff --git a/client/src/components/songbook/DrumSheetView.jsx b/client/src/components/songbook/DrumSheetView.jsxnew file mode 100644index 0000000000..f2c72774e5--- /dev/null+++ b/client/src/components/songbook/DrumSheetView.jsx@@ -0,0 +1,282 @@+/**+ * DrumSheetView — renders PortOS drum-kit notation (drumNotation.js) as a+ * labelled, bar-gridded kit sheet in hand-rolled SVG, with no engraving library+ * (the same explicit choice `ScoreSheet.jsx` makes: no VexFlow / abcjs / OSMD).+ *+ * Geometry is driven off ONE constant — the grid cell size. Every row is a kit+ * piece, every column a grid step, so positioning a hit is a single multiply.+ * Beat boundaries get a heavier grid line so a 16th-note row still reads in+ * fours, and each hit's glyph follows its cell: a cross for cymbals/hats, a+ * filled notehead for drums, a ring for an open hi-hat, a small hollow head for+ * a ghost, a doubled head for a flam, all with the accent's own chevron.+ *+ * Ink comes from the PortOS theme CSS variables (`--port-text` / `--port-accent`+ * / `--port-text-muted`) applied through the `style` prop — SVG presentation+ * *attributes* don't evaluate `var()`, so `fill="var(--x)"` would silently paint+ * nothing. Same rule as ScoreSheet.+ *+ * Each bar is its own SVG so bars wrap responsively and a wide bar scrolls as a+ * UNIT on a narrow screen (mobile-responsive is non-negotiable) instead of+ * squeezing its columns into illegibility.+ *+ * Props:+ * text — the raw chart source (parsed here; the parser never throws)+ * fontSizeRem — scales the labels/legend text with the viewer's font control+ * activeStep — `{ bar, step }` | null — draws the playhead column+ * onStepClick — optional `(bar, step)` for a future tap-a-cell editor (#3115+ * out-of-scope); when absent the grid renders as a plain image+ */++import { memo, useMemo } from 'react';+import { parseDrumChart, kitPiece } from '../../lib/drumNotation.js';++// --- Geometry (internal SVG units; each bar's <svg> scales via viewBox) ------+const CELL = 22; // one grid step — every other measure derives from this+const ROW_H = CELL; // one kit-piece row+const LABEL_W = 74; // room for the row labels ("Hi-Hat", "Floor Tom")+const PAD = 6; // padding inside a bar's svg+const HEAD_R = CELL * 0.3; // notehead radius+const GHOST_R = CELL * 0.2;+const CROSS_R = CELL * 0.26;+const HEADER_H = 18; // bar-number / label strip above the grid++// Ink — theme CSS vars, applied via `style` (see the header note).+const INK = 'rgb(var(--port-text))';+const GRID = 'rgb(var(--port-text-muted) / 0.35)';+const GRID_BEAT = 'rgb(var(--port-text-muted) / 0.7)';+const LABEL = 'rgb(var(--port-text-muted))';+const ACTIVE = 'rgb(var(--port-accent))';+const ACTIVE_FILL = 'rgb(var(--port-accent) / 0.18)';+const UI_FONT = 'ui-sans-serif, system-ui, sans-serif';++const strokeStyle = (color) => ({ stroke: color });+const fillStyle = (color) => ({ fill: color });++// One hit's glyph. `cross` pieces (cymbals, hats) draw an ×; `head` pieces+// (drums) draw a notehead. The cell's own flags then modify it: a ring for an+// open hi-hat, a small hollow head for a ghost, a leading grace head for a flam,+// and a chevron above an accent.+const renderHit = (cell, piece, cx, cy, ink, key) => {+ const out = [];+ const cross = kitPiece(piece)?.glyph === 'cross';++ if (cell.flam) {+ // Grace note just ahead of the beat — small and offset left.+ const gx = cx - CELL * 0.3;+ out.push(cross+ ? <line key={`${key}-fl1`} x1={gx - GHOST_R} y1={cy - GHOST_R} x2={gx + GHOST_R} y2={cy + GHOST_R} style={strokeStyle(ink)} strokeWidth={1.1} />+ : <circle key={`${key}-fl1`} cx={gx} cy={cy} r={GHOST_R} style={{ fill: 'none', stroke: ink }} strokeWidth={1.1} />);+ if (cross) {+ out.push(<line key={`${key}-fl2`} x1={gx - GHOST_R} y1={cy + GHOST_R} x2={gx + GHOST_R} y2={cy - GHOST_R} style={strokeStyle(ink)} strokeWidth={1.1} />);+ }+ }++ if (cross) {+ const r = cell.ghost ? GHOST_R : CROSS_R;+ const w = cell.accent ? 2.2 : 1.6;+ out.push(+ <line key={`${key}-a`} x1={cx - r} y1={cy - r} x2={cx + r} y2={cy + r} style={strokeStyle(ink)} strokeWidth={w} strokeLinecap="round" />,+ <line key={`${key}-b`} x1={cx - r} y1={cy + r} x2={cx + r} y2={cy - r} style={strokeStyle(ink)} strokeWidth={w} strokeLinecap="round" />,+ );+ // Open hi-hat: the conventional circle around the ×.+ if (cell.open) {+ out.push(<circle key={`${key}-o`} cx={cx} cy={cy} r={r + 2.6} style={{ fill: 'none', stroke: ink }} strokeWidth={1.2} />);+ }+ } else if (cell.ghost) {+ // Ghost note — the parenthesized/hollow head convention.+ out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={GHOST_R} style={{ fill: 'none', stroke: ink }} strokeWidth={1.2} />);+ } else {+ out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={HEAD_R} style={fillStyle(ink)} />);+ }++ if (cell.accent) {+ // Accent chevron above the head (the > articulation mark, rotated to sit+ // horizontally over the note).+ const y = cy - CELL * 0.42;+ out.push(+ <path key={`${key}-ac`}+ d={`M ${cx - HEAD_R - 1} ${y - 2.4} L ${cx + HEAD_R + 1} ${y} L ${cx - HEAD_R - 1} ${y + 2.4}`}+ style={{ fill: 'none', stroke: ink }} strokeWidth={1.3} strokeLinecap="round" strokeLinejoin="round" />,+ );+ }+ return out;+};++// One bar → its own <svg>. Kept a component (not a helper returning elements) so+// React can key/diff bars independently as the playhead moves.+const Bar = ({ bar, pieces, subdivision, activeStep, onStepClick }) => {+ const steps = bar.rows[0]?.cells.length || 0;+ const gridW = steps * CELL;+ const width = LABEL_W + gridW + PAD * 2;+ const height = HEADER_H + pieces.length * ROW_H + PAD * 2;+ const gridLeft = PAD + LABEL_W;+ const gridTop = PAD + HEADER_H;+ const gridBottom = gridTop + pieces.length * ROW_H;+ // Only the bar the playhead is IN highlights a column.+ const active = activeStep && activeStep.bar === bar.index ? activeStep.step : null;++ const els = [];++ // Bar number + label strip.+ els.push(+ <text key="num" x={PAD} y={PAD + 12} fontSize={11} fontWeight="600" style={fillStyle(LABEL)} fontFamily={UI_FONT}>+ {bar.index}+ </text>,+ );+ if (bar.label) {+ els.push(+ <text key="label" x={gridLeft} y={PAD + 12} fontSize={11} style={fillStyle(LABEL)} fontFamily={UI_FONT}>+ {bar.label}+ {bar.repeat > 1 ? ` (${bar.repeatPass}/${bar.repeat})` : ''}+ </text>,+ );+ }++ // Playhead column — drawn first so glyphs and grid lines sit on top of it.+ if (active != null && active >= 0 && active < steps) {+ els.push(+ <rect key="ph" x={gridLeft + active * CELL} y={gridTop} width={CELL} height={gridBottom - gridTop}+ style={fillStyle(ACTIVE_FILL)} />,+ );+ }++ // Row labels + horizontal lane lines.+ pieces.forEach((id, ri) => {+ const y = gridTop + ri * ROW_H;+ els.push(+ <text key={`rl${id}`} x={PAD} y={y + ROW_H / 2 + 3.5} fontSize={10} style={fillStyle(LABEL)} fontFamily={UI_FONT}>+ {kitPiece(id)?.label || id}+ </text>,+ <line key={`rh${id}`} x1={gridLeft} y1={y} x2={gridLeft + gridW} y2={y} style={strokeStyle(GRID)} strokeWidth={1} />,+ );+ });+ els.push(+ <line key="rh-last" x1={gridLeft} y1={gridBottom} x2={gridLeft + gridW} y2={gridBottom} style={strokeStyle(GRID)} strokeWidth={1} />,+ );++ // Vertical step lines — every `subdivision`-th is a beat boundary (heavier),+ // and the bar's own edges are heavier still.+ for (let s = 0; s <= steps; s += 1) {+ const x = gridLeft + s * CELL;+ const isEdge = s === 0 || s === steps;+ const isBeat = s % subdivision === 0;+ els.push(+ <line key={`v${s}`} x1={x} y1={gridTop} x2={x} y2={gridBottom}+ style={strokeStyle(isBeat ? GRID_BEAT : GRID)} strokeWidth={isEdge ? 1.8 : (isBeat ? 1.2 : 0.6)} />,+ );+ }++ // Beat numbers under the grid.+ for (let s = 0; s < steps; s += subdivision) {+ els.push(+ <text key={`bn${s}`} x={gridLeft + s * CELL + CELL / 2} y={gridTop - 3} fontSize={9}+ style={fillStyle(LABEL)} fontFamily={UI_FONT} textAnchor="middle">+ {s / subdivision + 1}+ </text>,+ );+ }++ // Hits.+ const rowByPiece = new Map(bar.rows.map((r) => [r.piece, r]));+ pieces.forEach((id, ri) => {+ const row = rowByPiece.get(id);+ if (!row) return;+ const cy = gridTop + ri * ROW_H + ROW_H / 2;+ row.cells.forEach((cell, s) => {+ if (cell.rest) return;+ const cx = gridLeft + s * CELL + CELL / 2;+ els.push(...renderHit(cell, id, cx, cy, s === active ? ACTIVE : INK, `h${id}-${s}`));+ });+ });++ // Optional tap targets (a future click-to-toggle editor); absent by default so+ // the sheet is a plain image with no stray interactive nodes.+ if (onStepClick) {+ pieces.forEach((id, ri) => {+ for (let s = 0; s < steps; s += 1) {+ els.push(+ <rect key={`t${id}-${s}`} x={gridLeft + s * CELL} y={gridTop + ri * ROW_H} width={CELL} height={ROW_H}+ fill="transparent" style={{ cursor: 'pointer' }} onClick={() => onStepClick(bar.index, s, id)} />,+ );+ }+ });+ }++ return (+ // The bar scrolls as a unit on a narrow viewport: the svg keeps its intrinsic+ // width and the wrapper scrolls, rather than the viewBox squeezing columns.+ <div className="overflow-x-auto max-w-full">+ <svg+ viewBox={`0 0 ${width} ${height}`}+ width={width}+ height={height}+ role="img"+ aria-label={`Drum bar ${bar.index}${bar.label ? `: ${bar.label}` : ''}`}+ style={{ display: 'block', maxWidth: '100%', height: 'auto' }}+ >+ {els}+ </svg>+ </div>+ );+};++// Chart problems (unknown pieces, over-long rows, bad headers). Rendered+// ALONGSIDE the sheet, never instead of it — a chart with one bad row must still+// draw the bars that parsed.+const ErrorSummary = ({ errors }) => (+ <div className="mt-3 rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">+ <div className="font-semibold mb-1">+ {errors.length} chart note{errors.length === 1 ? '' : 's'}+ </div>+ <ul className="list-disc pl-4 space-y-0.5">+ {errors.map((err, i) => <li key={i}>{err}</li>)}+ </ul>+ </div>+);++function DrumSheetView({ text, fontSizeRem = 0.875, activeStep = null, onStepClick, className = '' }) {+ const chart = useMemo(() => parseDrumChart(text), [text]);++ if (!chart.bars.length) {+ return (+ <div className={`text-sm text-gray-500 ${className}`}>+ {chart.errors.length > 0+ ? 'No readable bars in this drum chart yet — check the notes below.'+ : 'No drum chart yet — add piece rows like "HH: x x x x".'}+ {chart.errors.length > 0 && <ErrorSummary errors={chart.errors} />}+ </div>+ );+ }++ return (+ <div className={className} style={{ fontSize: `${fontSizeRem}rem` }}>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mb-2 text-xs text-gray-500">+ <span>{chart.time.beats}/{chart.time.beatValue}</span>+ <span>♩ = {chart.tempo}</span>+ <span>+ {chart.subdivision} per beat+ </span>+ <span>{chart.bars.length} bar{chart.bars.length === 1 ? '' : 's'}</span>+ </div>++ <div className="flex flex-col gap-3">+ {chart.bars.map((bar) => (+ <Bar+ key={`${bar.index}`}+ bar={bar}+ pieces={chart.pieces}+ subdivision={chart.subdivision}+ activeStep={activeStep}+ onStepClick={onStepClick}+ />+ ))}+ </div>++ {chart.errors.length > 0 && <ErrorSummary errors={chart.errors} />}+ </div>+ );+}++// Props are primitives plus a shallow `activeStep` object, so memo keeps a host+// page's unrelated re-renders (stage flips, BPM edits) from redrawing the sheet.+export default memo(DrumSheetView);diff --git a/client/src/components/songbook/DrumSheetView.test.jsx b/client/src/components/songbook/DrumSheetView.test.jsxnew file mode 100644index 0000000000..bf990b6f65--- /dev/null+++ b/client/src/components/songbook/DrumSheetView.test.jsx@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest';+import { renderToStaticMarkup } from 'react-dom/server';+import DrumSheetView from './DrumSheetView.jsx';++// Invented grooves only (privacy convention).+const ROCK_BEAT = `time: 4/4+tempo: 96+subdivision: 4++# Bar 1 — basic rock beat+HH: x x x x x x x x+S: - - - - o - - -+K: o - - - - - o -`;++const count = (html, tag) => (html.match(new RegExp(`<${tag}[ />]`, 'g')) || []).length;++describe('DrumSheetView', () => {+ it('renders a bar-gridded kit sheet with no NaN geometry', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} />);+ expect(html).not.toMatch(/NaN/);+ expect(html).toContain('aria-label="Drum bar 1: Bar 1 — basic rock beat"');+ expect(html).toContain('Hi-Hat');+ expect(html).toContain('Snare');+ expect(html).toContain('Kick');+ });++ it('shows the chart header summary', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} />);+ expect(html).toContain('4/4');+ expect(html).toContain('96');+ expect(html).toContain('4 per beat');+ expect(html).toContain('1 bar');+ });++ it('takes ink from the theme CSS vars via style, never a var() attribute', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} />);+ // SVG presentation attributes don't evaluate var() — every themed color must+ // arrive through the style prop.+ expect(html).not.toMatch(/(?:fill|stroke)="(?:rgb\()?var\(/);+ expect(html).toContain('--port-text');+ });++ it('draws one glyph per struck cell only', () => {+ // subdivision 1 → 4 cells/bar; two hits on one row.+ const html = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nK: o-o-'} />);+ expect(count(html, 'circle')).toBe(2);+ });++ it('draws crosses for cymbal-family rows and heads for drums', () => {+ const hats = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nHH: xxxx'} />);+ const kick = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nK: oooo'} />);+ expect(count(hats, 'circle')).toBe(0); // × strokes, no noteheads+ expect(count(kick, 'circle')).toBe(4);+ });++ it('rings an open hi-hat and adds an accent chevron', () => {+ const open = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nHH: o---'} />);+ expect(count(open, 'circle')).toBe(1); // the open ring around the ×+ const accent = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nS: X---'} />);+ expect(count(accent, 'path')).toBe(1); // the accent chevron+ });++ it('draws a flam as a grace glyph plus the main hit', () => {+ const plain = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nS: x---'} />);+ const flam = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nS: f---'} />);+ expect(count(flam, 'circle')).toBe(count(plain, 'circle') + 1);+ });++ it('renders one bar block per bar, including repeat expansions', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={'# A x3\nHH: xxxx'} />);+ expect(count(html, 'svg')).toBe(3);+ expect(html).toContain('(1/3)');+ expect(html).toContain('(3/3)');+ });++ it('gives every bar its own scroll container so wide bars scroll as a unit', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={'# A\nHH: xxxxxxxxxxxxxxxx\n\n# B\nHH: xxxx'} />);+ expect((html.match(/overflow-x-auto/g) || []).length).toBe(2);+ });++ it('highlights the active step column in the active bar only', () => {+ const chart = '# A\nHH: xxxx\n\n# B\nHH: xxxx';+ const none = renderToStaticMarkup(<DrumSheetView text={chart} />);+ const lit = renderToStaticMarkup(<DrumSheetView text={chart} activeStep={{ bar: 2, step: 1 }} />);+ expect(count(none, 'rect')).toBe(0);+ expect(count(lit, 'rect')).toBe(1); // exactly one playhead column+ expect(lit).toContain('--port-accent');+ });++ it('ignores an out-of-range activeStep instead of drawing off-grid', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nHH: xxxx'} activeStep={{ bar: 1, step: 99 }} />);+ expect(count(html, 'rect')).toBe(0);+ expect(html).not.toMatch(/NaN/);+ });++ it('renders the sheet AND an errors summary for a partly-bad chart', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={'CB: xxxx\nHH: xxxx'} />);+ expect(html).toContain('aria-label="Drum bar 1"'); // the good row still drew+ expect(html).toContain('unknown kit piece');+ expect(html).toContain('1 chart note');+ });++ it('shows an empty-state hint (not a crash) for empty input', () => {+ for (const text of ['', null, undefined, 'time: 4/4']) {+ const html = renderToStaticMarkup(<DrumSheetView text={text} />);+ expect(html).toContain('No drum chart yet');+ }+ });++ it('reports errors even when nothing parsed into a bar', () => {+ const html = renderToStaticMarkup(<DrumSheetView text={'time: nope\n\nCB: xxxx'} />);+ expect(html).toContain('No readable bars');+ expect(html).toContain('bad time signature');+ });++ it('adds tap targets only when onStepClick is provided', () => {+ const chart = 'subdivision: 1\n\nHH: xxxx';+ expect(count(renderToStaticMarkup(<DrumSheetView text={chart} />), 'rect')).toBe(0);+ const interactive = renderToStaticMarkup(<DrumSheetView text={chart} onStepClick={() => {}} />);+ expect(count(interactive, 'rect')).toBe(4); // one per cell of the single row+ });+});diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsxnew file mode 100644index 0000000000..998b581a4c--- /dev/null+++ b/client/src/components/songbook/DrumTransportBar.jsx@@ -0,0 +1,167 @@+/**+ * DrumTransportBar — the play-along controls for a SongBook `drum` chart (#3115).+ *+ * Purely presentational over `useDrumPlayer`: play/stop, a practice-tempo number+ * input + slider (clamped by `clampBpm`, 20–320), percent-of-written quick+ * buttons that recompute BPM from the chart's `tempo:` marking, a count-in+ * select, a loop toggle with a from/to bar range, and a metronome-click toggle.+ * All state and audio live in the hook — this file only renders and calls back.+ *+ * Every control pairs `<label htmlFor>` with an `id`, and the buttons keep 44px+ * touch targets; the bar wraps so it stays usable on a phone.+ */++import { Play, Square, Repeat, Timer } from 'lucide-react';+import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';++// Practice speeds as a percentage of the chart's written tempo.+const PERCENTS = [50, 75, 90, 100, 110];+const COUNT_IN_OPTIONS = [0, 1, 2];++// 44px minimum touch targets, matching the viewer's own controls bar.+const ctrlBtnClass = 'flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50';+const smallSelectClass = 'bg-port-bg border border-port-border rounded px-2 py-2 min-h-[44px] text-xs text-white focus:border-port-accent focus:outline-none';++export default function DrumTransportBar({+ playing, onToggle, hasMusic = true,+ bpm, onBpmChange, onPercent, writtenTempo,+ countInBars, onCountInChange,+ loopEnabled, onLoopToggle, loopFrom, loopTo, onLoopRangeChange, barCount,+ clickEnabled, onClickToggle,+}) {+ const barOptions = Array.from({ length: Math.max(1, barCount) }, (_, i) => i + 1);+ // Which percent button (if any) the current BPM corresponds to — so the active+ // practice speed is visible rather than inferred.+ const activePercent = PERCENTS.find((p) => Math.round((writtenTempo * p) / 100) === bpm);++ return (+ <div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">+ {/* Transport */}+ <div className="flex items-center gap-1" 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 ? 'text-port-accent border-port-accent/50' : ''}`}+ 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>+ </div>++ {/* Practice tempo */}+ <div className="flex items-center gap-2">+ <label htmlFor="drum-bpm" className="text-xs text-gray-400">BPM</label>+ <input+ id="drum-bpm"+ type="number"+ min={METRONOME_BPM_MIN}+ max={METRONOME_BPM_MAX}+ value={bpm}+ onChange={(e) => onBpmChange(e.target.value)}+ className="w-16 bg-port-bg border border-port-border rounded px-2 py-2 min-h-[44px] text-sm text-white focus:border-port-accent focus:outline-none"+ />+ <label htmlFor="drum-bpm-slider" className="sr-only">Practice tempo</label>+ <input+ id="drum-bpm-slider"+ type="range"+ min={METRONOME_BPM_MIN}+ max={METRONOME_BPM_MAX}+ value={bpm}+ onChange={(e) => onBpmChange(e.target.value)}+ className="w-24 sm:w-32 accent-port-accent"+ title="Practice tempo (+/-)"+ />+ </div>++ {/* Percent of written tempo */}+ <div className="flex items-center gap-1" role="group" aria-label="Percent of written tempo">+ {PERCENTS.map((p) => (+ <button+ key={p}+ type="button"+ onClick={() => onPercent(p)}+ aria-pressed={activePercent === p}+ className={`px-2 min-h-[44px] rounded-lg border text-xs ${+ activePercent === p+ ? 'border-port-accent/50 text-port-accent'+ : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'+ }`}+ title={`${p}% of the written ${writtenTempo} BPM`}+ >+ {p}%+ </button>+ ))}+ </div>++ {/* Count-in */}+ <div className="flex items-center gap-2">+ <label htmlFor="drum-countin" className="text-xs text-gray-400">Count-in</label>+ <select+ id="drum-countin"+ value={countInBars}+ onChange={(e) => onCountInChange(e.target.value)}+ className={smallSelectClass}+ >+ {COUNT_IN_OPTIONS.map((n) => (+ <option key={n} value={n}>{n === 0 ? 'none' : `${n} bar${n === 1 ? '' : 's'}`}</option>+ ))}+ </select>+ </div>++ {/* Loop */}+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => onLoopToggle(!loopEnabled)}+ aria-pressed={loopEnabled}+ className={`${ctrlBtnClass} ${loopEnabled ? 'text-port-accent border-port-accent/50' : ''}`}+ aria-label={loopEnabled ? 'Disable loop' : 'Enable loop'}+ title="Loop a bar range ([ and ] set the ends)"+ >+ <Repeat size={16} />+ </button>+ {loopEnabled && (+ <>+ <label htmlFor="drum-loop-from" className="sr-only">Loop from bar</label>+ <select+ id="drum-loop-from"+ value={loopFrom}+ onChange={(e) => onLoopRangeChange(Number(e.target.value), loopTo)}+ className={smallSelectClass}+ >+ {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}+ </select>+ <span className="text-xs text-gray-500">–</span>+ <label htmlFor="drum-loop-to" className="sr-only">Loop to bar</label>+ <select+ id="drum-loop-to"+ value={loopTo}+ onChange={(e) => onLoopRangeChange(loopFrom, Number(e.target.value))}+ className={smallSelectClass}+ >+ {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}+ </select>+ </>+ )}+ </div>++ {/* Metronome click */}+ <button+ type="button"+ onClick={() => onClickToggle(!clickEnabled)}+ aria-pressed={clickEnabled}+ className={`${ctrlBtnClass} ${clickEnabled ? 'text-port-accent border-port-accent/50' : ''}`}+ aria-label={clickEnabled ? 'Turn the click off' : 'Turn the click on'}+ title="Metronome click over the kit"+ >+ <Timer size={16} />+ </button>+ </div>+ );+}diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsindex 6b7d7ad6a2..c27b125270 100644--- a/client/src/components/songbook/constants.js+++ b/client/src/components/songbook/constants.js@@ -22,13 +22,35 @@ export const INSTRUMENTS = [{ id: 'ukulele', label: 'Ukulele' },{ id: 'bass', label: 'Bass' },{ id: 'voice', label: 'Voice' },+ { id: 'drums', label: 'Drums' },{ id: 'other', label: 'Other' },];// Display label for a stored instrument id (unknown ids render as-is).export const instrumentLabel = (id) => INSTRUMENTS.find((i) => i.id === id)?.label || id;-export const SONG_FORMATS = ['chordpro', 'tab', 'plain'];+export const SONG_FORMATS = ['chordpro', 'tab', 'plain', 'drum'];++// The content format whose renderer is <DrumSheetView> (kit grid) rather than+// <TabSheetView>. Named so the viewer/import branches read intent, not a string.+export const DRUM_FORMAT = 'drum';+// The instrument that defaults a new song to the drum format.+export const DRUM_INSTRUMENT = 'drums';++// Options for a `<select>` over a known list plus whatever value is actually+// stored. A record synced from a NEWER peer (or hand-edited) can carry an+// instrument/format this client has never heard of — dropping it from the option+// list would make the select resolve to its first option and silently rewrite+// the record on the next save. So append the stored value as its own option and+// let the save round-trip it unchanged.+//+// `options` may be `[{ id, label }]` (INSTRUMENTS) or `['tab', …]` (SONG_FORMATS);+// both normalize to `{ id, label }`.+export const withStoredOption = (options, stored) => {+ const normalized = options.map((o) => (typeof o === 'string' ? { id: o, label: o } : o));+ if (!stored || normalized.some((o) => o.id === stored)) return normalized;+ return [...normalized, { id: stored, label: stored }];+};// Shared form/button recipes for the SongBook pages (index, import, viewer) —// kept here so the three pages don't drift on styling.diff --git a/client/src/components/songbook/constants.test.js b/client/src/components/songbook/constants.test.jsnew file mode 100644index 0000000000..c245fdbb23--- /dev/null+++ b/client/src/components/songbook/constants.test.js@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest';+import {+ INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT, DRUM_INSTRUMENT,+ instrumentLabel, withStoredOption,+} from './constants.js';++describe('SongBook constants', () => {+ it('mirrors the server songInstrumentEnum (server/lib/brainValidation.js)', () => {+ expect(INSTRUMENTS.map((i) => i.id)).toEqual([+ 'guitar', 'piano', 'ukulele', 'bass', 'voice', 'drums', 'other',+ ]);+ });++ it('mirrors the server songContentFormatEnum', () => {+ expect(SONG_FORMATS).toEqual(['chordpro', 'tab', 'plain', 'drum']);+ });++ it('names the drum format/instrument ids so callers don\'t hardcode strings', () => {+ expect(DRUM_FORMAT).toBe('drum');+ expect(DRUM_INSTRUMENT).toBe('drums');+ expect(SONG_FORMATS).toContain(DRUM_FORMAT);+ expect(INSTRUMENTS.map((i) => i.id)).toContain(DRUM_INSTRUMENT);+ });++ it('labels drums and falls through to the raw id for an unknown instrument', () => {+ expect(instrumentLabel('drums')).toBe('Drums');+ expect(instrumentLabel('hurdy-gurdy')).toBe('hurdy-gurdy');+ });+});++describe('withStoredOption', () => {+ it('returns the known list unchanged for a known value', () => {+ expect(withStoredOption(INSTRUMENTS, 'drums')).toEqual(INSTRUMENTS);+ expect(withStoredOption(SONG_FORMATS, 'drum').map((o) => o.id)).toEqual(SONG_FORMATS);+ });++ it('normalizes a string list into { id, label } pairs', () => {+ expect(withStoredOption(SONG_FORMATS, 'tab')).toEqual(+ SONG_FORMATS.map((f) => ({ id: f, label: f })),+ );+ });++ it('appends an UNKNOWN stored value so a save round-trips it (no silent coercion)', () => {+ // The failure this guards: a song synced from a newer peer carries a value+ // this client's enum doesn't list; dropping it from the <select> would make+ // the select resolve to its first option and rewrite the record on save.+ const instruments = withStoredOption(INSTRUMENTS, 'hurdy-gurdy');+ expect(instruments).toHaveLength(INSTRUMENTS.length + 1);+ expect(instruments.at(-1)).toEqual({ id: 'hurdy-gurdy', label: 'hurdy-gurdy' });++ const formats = withStoredOption(SONG_FORMATS, 'futureformat');+ expect(formats.at(-1)).toEqual({ id: 'futureformat', label: 'futureformat' });+ });++ it('appends nothing for an absent / empty stored value', () => {+ for (const stored of [undefined, null, '']) {+ expect(withStoredOption(INSTRUMENTS, stored)).toHaveLength(INSTRUMENTS.length);+ }+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 721802f1f0..89a35ea3d1 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -177,4 +177,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, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record); a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle applies live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer's drum transport bar. 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/index.js b/client/src/hooks/index.jsindex 0fb53878e4..bb56ba064c 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -119,6 +119,7 @@ export * from './useAutoRefetch.js';export * from './useCmdKSearch.js';export * from './useCooldownTick.js';export { default as useDrawerTab } from './useDrawerTab.js';+export { default as useDrumPlayer } from './useDrumPlayer.js';export * from './useHfTokenStatus.js';export * from './useKeyboardHelp.js';export * from './useLockToggle.js';diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.jsnew file mode 100644index 0000000000..b7e5127008--- /dev/null+++ b/client/src/hooks/useDrumPlayer.js@@ -0,0 +1,198 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { parseDrumChart, drumChartHasMusic } from '../lib/drumNotation.js';+import { createDrumPlayer, resolveLoopRange } from '../lib/drumPlayback.js';+import { clampBpm } from '../lib/metronome.js';+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';++/**+ * 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 sheet playhead, 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.+ *+ * 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 playhead from what you hear.+ * The user presses play again at the new setting. The click toggle is the+ * exception: it only gates FUTURE scheduling, so it applies 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+ * stale tempo (the per-song stored tempo lands after the player is created).+ *+ * The player, its interval and its scheduled audio are torn down on stop, on a+ * chart/song change, and on unmount — nothing survives the view.+ *+ * @param {string} text — the raw drum-chart source.+ * @param {{ songId?: string }} [options] — `songId` keys the persisted tempo.+ */+export default function useDrumPlayer(text, { songId } = {}) {+ const chart = useMemo(() => parseDrumChart(text), [text]);+ const barCount = chart.bars.length;+ // Bars can parse while every cell is a rest — there'd be nothing to hear, so+ // the transport gates Play on real hits rather than on the bar count.+ const hasMusic = useMemo(() => drumChartHasMusic(text), [text]);+ // The chart's own `tempo:` marking — the 100% reference for the percent buttons.+ const writtenTempo = clampBpm(chart.tempo) ?? 90;++ const storageKey = songId ? `songbook:drumBpm:${songId}` : null;+ const [bpm, setBpmState] = useState(writtenTempo);+ const [countInBars, setCountInBarsState] = useState(1);+ const [loopEnabled, setLoopEnabledState] = useState(false);+ const [loopFrom, setLoopFromState] = useState(1);+ const [loopTo, setLoopToState] = useState(1);+ const [clickEnabled, setClickEnabledState] = useState(false);+ const [playing, setPlaying] = useState(false);+ const [activeStep, setActiveStep] = useState(null);++ const playerRef = useRef(null);+ // Intent mirror of `playing`: during a first play the player's own flag only+ // flips after `await ctx.resume()`, so a rapid double-toggle read off the+ // player would start playback twice instead of netting out to a cancel (same+ // guard as useMidiPlayer).+ const playingRef = useRef(false);+ const setPlayingBoth = useCallback((v) => {+ playingRef.current = v;+ setPlaying(v);+ }, []);++ // Seed the practice tempo: the stored per-song value if there is one, else the+ // chart's written tempo. `null` from safeReadStorage is "never set" — distinct+ // from a stored value — so a fresh song follows its own marking.+ useEffect(() => {+ const stored = storageKey ? clampBpm(safeReadStorage(storageKey)) : null;+ setBpmState(stored ?? writtenTempo);+ }, [storageKey, writtenTempo]);++ // A chart change invalidates the loop range (the bar count differs).+ useEffect(() => {+ setLoopFromState(1);+ setLoopToState(Math.max(1, barCount));+ }, [barCount]);++ // One player per chart; torn down when the chart changes or the host unmounts,+ // so no interval or scheduled hit outlives the view. Initial settings come from+ // the sync effect below, which runs right after this one.+ useEffect(() => {+ if (!chart.bars.length) {+ playerRef.current = null;+ return undefined;+ }+ const player = createDrumPlayer(chart, {+ onStep: (info) => setActiveStep(info),+ onEnded: () => { setPlayingBoth(false); setActiveStep(null); },+ });+ playerRef.current = player;+ return () => {+ player.stop();+ playerRef.current = null;+ setPlayingBoth(false);+ setActiveStep(null);+ };+ }, [chart, setPlayingBoth]);++ // Push the current settings into whatever player is mounted. The player's own+ // setters rebuild its schedule only while idle, and every timing-critical+ // setter below stops playback first — so this never re-times live audio.+ useEffect(() => {+ const player = playerRef.current;+ if (!player) return;+ player.setBpm(bpm);+ player.setCountIn(countInBars);+ player.setLoop(loopEnabled ? { from: loopFrom, to: loopTo } : null);+ player.setClick(clickEnabled);+ }, [chart, bpm, countInBars, loopEnabled, loopFrom, loopTo, clickEnabled]);++ const stop = useCallback(() => {+ playerRef.current?.stop();+ setPlayingBoth(false);+ setActiveStep(null);+ }, [setPlayingBoth]);++ const toggle = useCallback(() => {+ const player = playerRef.current;+ if (!player) return;+ if (playingRef.current) { stop(); return; }+ setPlayingBoth(true);+ // play() resolves once playback has STARTED; an autoplay-policy failure lands+ // here — reset the button rather than lying "playing".+ Promise.resolve(player.play()).catch((err) => {+ console.error(`🥁 Drum play-along failed to start: ${err.message}`);+ setPlayingBoth(false);+ setActiveStep(null);+ });+ }, [setPlayingBoth, stop]);++ // Timing-critical edits stop playback first (see the header note); the sync+ // effect above then hands the new value to the now-idle player.+ const stopIfPlaying = useCallback(() => {+ if (playingRef.current) stop();+ }, [stop]);++ const setBpm = useCallback((next) => {+ const clamped = clampBpm(next);+ if (clamped == null) return;+ stopIfPlaying();+ setBpmState(clamped);+ if (storageKey) safeWriteStorage(storageKey, String(clamped));+ }, [stopIfPlaying, storageKey]);++ // Percent of the chart's WRITTEN tempo (the practice-slower control).+ const setBpmPercent = useCallback((percent) => {+ setBpm(Math.round((writtenTempo * percent) / 100));+ }, [setBpm, writtenTempo]);++ const setCountInBars = useCallback((next) => {+ stopIfPlaying();+ setCountInBarsState(Math.max(0, Math.min(4, Math.trunc(Number(next)) || 0)));+ }, [stopIfPlaying]);++ const setLoopEnabled = useCallback((enabled) => {+ stopIfPlaying();+ setLoopEnabledState(!!enabled);+ }, [stopIfPlaying]);++ // Clamped against the real bar count so the two selects can't describe a range+ // the chart doesn't have.+ const setLoopRange = useCallback((from, to) => {+ const range = resolveLoopRange(barCount, { from, to }) || { from: 1, to: Math.max(1, barCount) };+ stopIfPlaying();+ setLoopFromState(range.from);+ setLoopToState(range.to);+ }, [barCount, stopIfPlaying]);++ // Click only gates FUTURE scheduling — safe to flip mid-groove.+ const setClickEnabled = useCallback((enabled) => setClickEnabledState(!!enabled), []);++ // The bar the `[` / `]` loop-endpoint shortcuts act on: the playhead's bar+ // while playing, else the current loop start.+ const currentBar = activeStep?.bar || loopFrom;++ return {+ chart,+ barCount,+ hasMusic,+ writtenTempo,+ bpm,+ setBpm,+ setBpmPercent,+ countInBars,+ setCountInBars,+ loopEnabled,+ setLoopEnabled,+ loopFrom,+ loopTo,+ setLoopRange,+ clickEnabled,+ setClickEnabled,+ playing,+ activeStep,+ currentBar,+ toggle,+ stop,+ };+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 83b2d4fa6d..0a567f0590 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -125,6 +125,8 @@ grep -i "what you want to do" client/src/lib/README.md| `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). || `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. || `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. |+| `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`), and `drumChartHasMusic(text)`. 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, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — bandpassed noise burst for snare/hats/cymbals, pitch-dropping sine for kick/toms, 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. 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/drumNotation.js b/client/src/lib/drumNotation.jsnew file mode 100644index 0000000000..3738484a1d--- /dev/null+++ b/client/src/lib/drumNotation.js@@ -0,0 +1,324 @@+// PortOS drum-kit notation — a tiny, dependency-free grid DSL for a drum groove+// and the pure parser that turns it into the structured chart <DrumSheetView>+// draws and drumPlayback.js sounds. Companion to `scoreNotation.js` (pitched+// lead sheets) and `tabNotation.js` (chord/tab sheets): same contract — one pure+// forgiving parser, one hand-rolled SVG renderer, no engraving library.+//+// A drum chart IS a grid, so the format reads like the sheet it renders:+//+// time: 4/4+// tempo: 96+// subdivision: 4 ← grid steps per beat (4 = 16ths, 2 = 8ths, 3 = triplets)+//+// # Bar 1 — basic rock beat+// HH: x x x x x x x x+// S: - - - - o - - -+// K: o - - - - - o -+//+// HEADER lines are `key: value`, in any order, before the music: `time`,+// `tempo`, `subdivision`, and an optional `kit` (a comma/space list of piece+// ids that overrides the row ORDER — never which rows exist). Defaults are+// 4/4, 90 BPM, subdivision 4.+//+// BAR BLOCKS are separated by blank lines. A `#` line is a comment — and+// doubles as the block's label when it's the block's first line. A trailing+// `x2` / `x4` on the label repeats the whole block that many times.+//+// PIECE ROWS are `PIECE: cells`. PIECE is one of the nine kit ids below+// (case-insensitive, long aliases accepted: `crash`, `snare`, `kick`, …).+// CELLS are single characters; whitespace between them is optional and+// ignored, so `xxxxxxxx` and `x x x x x x x x` are the same row.+//+// The parser is forgiving and NEVER throws: an unknown piece token, a bad+// header, or an over-long row collects a message into `errors[]` and the rest+// of the chart still parses. Keep this module pure (no React, no imports) —+// it's unit-tested in a node env and barrelled.++// --- Kit -------------------------------------------------------------------+// One entry per kit piece, in TOP-TO-BOTTOM sheet order (cymbals above drums+// above feet, matching how a drum chart is conventionally engraved). `midi` is+// the General MIDI percussion note (documented reference for anyone wiring a+// MIDI export later — the synth in drumPlayback.js reads `sound`, not `midi`).+// `sound` picks the synth voice; `glyph` picks the notehead shape.+export const KIT_PIECES = [+ { id: 'CR', label: 'Crash', aliases: ['crash', 'cr', 'cc'], midi: 49, sound: 'crash', glyph: 'cross' },+ { id: 'RD', label: 'Ride', aliases: ['ride', 'rd'], midi: 51, sound: 'ride', glyph: 'cross' },+ { id: 'HH', label: 'Hi-Hat', aliases: ['hihat', 'hi-hat', 'hh', 'hat'], midi: 42, sound: 'hihat', glyph: 'cross' },+ { id: 'T1', label: 'Tom 1', aliases: ['tom1', 'tom', 't1', 'hitom'], midi: 48, sound: 'tom1', glyph: 'head' },+ { id: 'T2', label: 'Tom 2', aliases: ['tom2', 't2', 'midtom'], midi: 47, sound: 'tom2', glyph: 'head' },+ { id: 'S', label: 'Snare', aliases: ['snare', 's', 'sd'], midi: 38, sound: 'snare', glyph: 'head' },+ { id: 'FT', label: 'Floor Tom', aliases: ['floor', 'floortom', 'ft', 't3'], midi: 43, sound: 'floor', glyph: 'head' },+ { id: 'K', label: 'Kick', aliases: ['kick', 'k', 'bd', 'bass'], midi: 36, sound: 'kick', glyph: 'head' },+ { id: 'HF', label: 'Hi-Hat (foot)', aliases: ['hihatfoot', 'hhfoot', 'hf', 'foot'], midi: 44, sound: 'hihatFoot', glyph: 'cross' },+];++// Row order index for a piece id — the renderer and the `kit:` override both+// sort by this so a chart's rows always read in kit order regardless of the+// order the author typed them.+const PIECE_ORDER = new Map(KIT_PIECES.map((p, i) => [p.id, i]));++// Every accepted spelling → the canonical piece id. Built from `aliases` plus+// the id itself, all lowercased, so lookup is a single normalize + get.+const PIECE_BY_TOKEN = new Map();+for (const piece of KIT_PIECES) {+ PIECE_BY_TOKEN.set(piece.id.toLowerCase(), piece.id);+ for (const alias of piece.aliases) PIECE_BY_TOKEN.set(alias.toLowerCase(), piece.id);+}++// Piece descriptor by id (renderer/synth lookup).+export const kitPiece = (id) => KIT_PIECES.find((p) => p.id === id) || null;++// --- Cell glyphs -----------------------------------------------------------+// The six cell characters and what each means. `velocity` is the relative hit+// strength drumPlayback scales its voice gain by; `open` lengthens the hi-hat+// decay; `flam` sounds a grace note just before the beat.+export const CELL_GLYPHS = {+ '-': { id: 'rest', rest: true, velocity: 0, label: 'rest' },+ x: { id: 'normal', rest: false, velocity: 0.8, label: 'normal' },+ X: { id: 'accent', rest: false, velocity: 1, accent: true, label: 'accent' },+ o: { id: 'open', rest: false, velocity: 0.85, open: true, label: 'open' },+ g: { id: 'ghost', rest: false, velocity: 0.35, ghost: true, label: 'ghost' },+ f: { id: 'flam', rest: false, velocity: 0.9, flam: true, label: 'flam' },+};++// A cell char → its descriptor, or null when it isn't a known glyph. `.` and+// `_` are tolerated as rest synonyms because both read as "empty" in a grid and+// an author reaching for either means the same thing.+const REST_SYNONYMS = new Set(['.', '_']);+const cellFor = (ch) => {+ if (REST_SYNONYMS.has(ch)) return CELL_GLYPHS['-'];+ return CELL_GLYPHS[ch] || null;+};++// --- Header ----------------------------------------------------------------+const DEFAULT_HEADER = { beats: 4, beatValue: 4, tempo: 90, subdivision: 4, kit: null };++export const DEFAULT_DRUM_TEMPO = 90;+// Grid-resolution band. 1 = one cell per beat; 12 keeps a 4/4 bar under 50+// cells so the renderer stays legible and a typo like `subdivision: 400` can't+// build a 1600-cell bar.+export const SUBDIVISION_MIN = 1;+export const SUBDIVISION_MAX = 12;++const parseTimeSignature = (raw) => {+ const m = /^\s*(\d{1,2})\s*\/\s*(\d{1,2})\s*$/.exec(raw || '');+ if (!m) return null;+ const beats = Number(m[1]);+ const beatValue = Number(m[2]);+ if (!beats || !beatValue) return null;+ return { beats, beatValue };+};++// Header `kit:` value → an ordered piece-id list, or null when nothing in it+// resolves (so the caller keeps the default KIT_PIECES order rather than an+// empty override that would hide every row).+const parseKitOrder = (raw) => {+ const ids = String(raw || '')+ .split(/[\s,]+/)+ .map((token) => PIECE_BY_TOKEN.get(token.toLowerCase()))+ .filter(Boolean);+ return ids.length ? [...new Set(ids)] : null;+};++// A `# comment` label with an optional repeat suffix → { label, repeat }.+// `# Bar 1 — fill x2` repeats the block twice; the suffix is stripped from the+// label so the sheet shows "Bar 1 — fill" and the repeat shows as its own badge.+const REPEAT_SUFFIX = /\s*[x×]\s*(\d{1,2})\s*$/i;+const parseLabel = (raw) => {+ const text = raw.replace(/^#+\s*/, '').trim();+ const m = REPEAT_SUFFIX.exec(text);+ if (!m) return { label: text, repeat: 1 };+ const repeat = Number(m[1]);+ return {+ label: text.slice(0, m.index).trim(),+ // A `x0`/`x1` suffix is not a repeat — treat it as 1 rather than dropping+ // the bar entirely (an author typing x0 meant "once", not "delete this").+ repeat: Number.isFinite(repeat) && repeat > 1 ? Math.min(repeat, 32) : 1,+ };+};++// A header line is `word: value` and its key is one of ours. Anything else+// shaped like `word: value` is a piece row (`HH: x x …`) or garbage.+const HEADER_KEYS = new Set(['time', 'tempo', 'subdivision', 'kit']);+// Digits and dashes are part of the key, not the value — piece ids include `T1`+// and aliases include `hi-hat`, so a letters-only key would silently reject both.+const HEADER_RE = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/;++/**+ * Parse a drum chart into `{ time, tempo, subdivision, bars, pieces, errors }`.+ *+ * - `time` — `{ beats, beatValue }` (4/4 default).+ * - `tempo` — the written BPM (90 default). The viewer seeds its practice-tempo+ * control from this; playback takes an explicit bpm.+ * - `subdivision` — grid cells per beat.+ * - `bars` — `[{ index, label, repeat, rows: [{ piece, cells }] }]`. `index` is+ * the 1-based BAR number AFTER repeat expansion, so bar numbers on the sheet+ * match the loop-range control and the playback schedule. `cells` is always+ * exactly `beats × subdivision` long (short rows pad with rests).+ * - `pieces` — the ordered piece ids that appear anywhere in the chart (the+ * renderer's row list).+ * - `errors` — human-readable strings; never thrown.+ *+ * Always returns a usable object.+ */+export const parseDrumChart = (text) => {+ const header = { ...DEFAULT_HEADER };+ const errors = [];+ const lines = String(text || '').split(/\r?\n/);++ // Pass 1: pull header lines out, group the rest into blank-line-separated+ // blocks. A header is only honored BEFORE any music (per the format doc), so+ // a stray `tempo:` mid-chart is an error rather than a silent tempo change.+ const blocks = [];+ let current = null;+ let sawMusic = false;+ const flush = () => { if (current && current.rows.length) blocks.push(current); current = null; };++ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (!line) { flush(); continue; }++ if (line.startsWith('#')) {+ // A comment that opens a block is its label; later comments inside a+ // block are just comments.+ if (!current) current = { ...parseLabel(line), rows: [] };+ continue;+ }++ const headerMatch = HEADER_RE.exec(line);+ const key = headerMatch ? headerMatch[1].toLowerCase() : null;+ if (key && HEADER_KEYS.has(key)) {+ const value = headerMatch[2].trim();+ if (sawMusic) { errors.push(`header "${key}" appears after the music started — ignored`); continue; }+ if (key === 'time') {+ const ts = parseTimeSignature(value);+ if (ts) { header.beats = ts.beats; header.beatValue = ts.beatValue; }+ else errors.push(`bad time signature "${value}"`);+ } else if (key === 'tempo') {+ const t = Number(value);+ if (Number.isFinite(t) && t > 0) header.tempo = t;+ else errors.push(`bad tempo "${value}"`);+ } else if (key === 'subdivision') {+ const s = Number(value);+ if (Number.isInteger(s) && s >= SUBDIVISION_MIN && s <= SUBDIVISION_MAX) header.subdivision = s;+ else errors.push(`bad subdivision "${value}" (expected ${SUBDIVISION_MIN}–${SUBDIVISION_MAX})`);+ } else {+ const order = parseKitOrder(value);+ if (order) header.kit = order;+ else errors.push(`kit "${value}" names no known pieces — using the default row order`);+ }+ continue;+ }++ // Music line — `PIECE: cells`.+ sawMusic = true;+ if (!current) current = { label: '', repeat: 1, rows: [] };+ if (!headerMatch) { errors.push(`unrecognized line "${line}"`); continue; }+ const piece = PIECE_BY_TOKEN.get(key);+ if (!piece) { errors.push(`unknown kit piece "${headerMatch[1]}" — row skipped`); continue; }+ current.rows.push({ piece, raw: headerMatch[2] });+ }+ flush();++ const stepsPerBar = Math.max(1, header.beats * header.subdivision);++ // Pass 2: cells. Each raw row becomes an exactly-stepsPerBar-long cell array.+ const parsedBlocks = blocks.map((block, bi) => {+ const rows = [];+ for (const row of block.rows) {+ const cells = [];+ // One error per distinct bad character, not per occurrence — a row of the+ // wrong alphabet should read as one problem, not sixteen.+ const reported = new Set();+ for (const ch of row.raw) {+ if (/\s|\|/.test(ch)) continue; // spacing + optional bar-line decoration+ const cell = cellFor(ch);+ if (!cell && !reported.has(ch)) {+ reported.add(ch);+ errors.push(`bar ${bi + 1} ${row.piece}: unknown cell "${ch}" — treated as a rest`);+ }+ cells.push(cell || CELL_GLYPHS['-']);+ }+ if (cells.length > stepsPerBar) {+ errors.push(`bar ${bi + 1} ${row.piece}: ${cells.length} cells for a ${stepsPerBar}-step bar — extra cells truncated`);+ cells.length = stepsPerBar;+ }+ while (cells.length < stepsPerBar) cells.push(CELL_GLYPHS['-']);+ // A repeated piece within one block merges into the first row (an author+ // splitting `HH:` across two lines means one hi-hat part, not two rows) —+ // a struck cell always wins over a rest.+ const existing = rows.find((r) => r.piece === row.piece);+ if (existing) {+ existing.cells = existing.cells.map((c, i) => (cells[i].rest ? c : cells[i]));+ } else {+ rows.push({ piece: row.piece, cells });+ }+ }+ rows.sort((a, b) => (PIECE_ORDER.get(a.piece) ?? 0) - (PIECE_ORDER.get(b.piece) ?? 0));+ return { label: block.label, repeat: block.repeat, rows };+ }).filter((block) => block.rows.length > 0);++ // Pass 3: expand repeats into real bars so every downstream consumer (sheet,+ // schedule, loop range) counts bars the same way.+ const bars = [];+ for (const block of parsedBlocks) {+ for (let pass = 0; pass < block.repeat; pass += 1) {+ bars.push({+ index: bars.length + 1,+ label: block.label,+ repeat: block.repeat,+ repeatPass: pass + 1,+ rows: block.rows.map((r) => ({ piece: r.piece, cells: r.cells })),+ });+ }+ }++ // Rows the chart actually uses, in kit order (or the header's `kit:` order,+ // filtered to what's present — an override must not invent empty rows).+ const present = new Set(bars.flatMap((bar) => bar.rows.map((r) => r.piece)));+ const order = header.kit || KIT_PIECES.map((p) => p.id);+ const pieces = order.filter((id) => present.has(id));++ return {+ time: { beats: header.beats, beatValue: header.beatValue },+ tempo: header.tempo,+ subdivision: header.subdivision,+ stepsPerBar,+ bars,+ pieces,+ errors,+ };+};++// True when `text` looks like a drum chart — used by the import page to pick the+// `drum` format BEFORE falling through to tabNotation's `detectFormat` (which+// would classify a grid row as plain text). Deliberately strict: a chart needs+// at least one real piece row whose cells are all grid glyphs, so a chord sheet+// with a stray `S:` line doesn't get misread as a groove.+export const isDrumNotation = (text) => {+ const lines = String(text || '').split(/\r?\n/);+ let pieceRows = 0;+ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (!line || line.startsWith('#')) continue;+ const m = HEADER_RE.exec(line);+ if (!m) continue;+ const key = m[1].toLowerCase();+ if (HEADER_KEYS.has(key)) continue;+ if (!PIECE_BY_TOKEN.has(key)) continue;+ const cells = m[2].replace(/[\s|]/g, '');+ // A row of grid glyphs only, with at least one actual hit — `S: hello`+ // shares the `PIECE:` shape but is prose, and `S: ----` alone is ambiguous.+ if (!cells || !/^[-xXogf._]+$/.test(cells) || !/[xXogf]/.test(cells)) continue;+ pieceRows += 1;+ if (pieceRows >= 2) return true;+ }+ // A single strong row still counts when a drum-specific header is present+ // (`subdivision:` has no meaning in any other SongBook format).+ return pieceRows >= 1 && /^\s*subdivision\s*:/im.test(String(text || ''));+};++// True when the chart contains at least one struck cell — lets the UI show an+// empty-state hint instead of an all-rest grid.+export const drumChartHasMusic = (text) => parseDrumChart(text).bars+ .some((bar) => bar.rows.some((row) => row.cells.some((cell) => !cell.rest)));diff --git a/client/src/lib/drumNotation.test.js b/client/src/lib/drumNotation.test.jsnew file mode 100644index 0000000000..6ebef02e08--- /dev/null+++ b/client/src/lib/drumNotation.test.js@@ -0,0 +1,266 @@+import { describe, it, expect } from 'vitest';+import {+ parseDrumChart, isDrumNotation, drumChartHasMusic, kitPiece,+ KIT_PIECES, CELL_GLYPHS, DEFAULT_DRUM_TEMPO, SUBDIVISION_MAX,+} from './drumNotation.js';++// All fixtures are invented grooves (privacy convention) — no transcribed music.+const ROCK_BEAT = `time: 4/4+tempo: 96+subdivision: 4++# Bar 1 — basic rock beat+HH: x x x x x x x x+S: - - - - o - - -+K: o - - - - - o -`;++const cellIds = (cells) => cells.map((c) => c.id);++describe('parseDrumChart — headers', () => {+ it('reads time / tempo / subdivision', () => {+ const chart = parseDrumChart(ROCK_BEAT);+ expect(chart.time).toEqual({ beats: 4, beatValue: 4 });+ expect(chart.tempo).toBe(96);+ expect(chart.subdivision).toBe(4);+ expect(chart.stepsPerBar).toBe(16);+ expect(chart.errors).toEqual([]);+ });++ it('defaults a headerless chart to 4/4 @ 90 with subdivision 4', () => {+ const chart = parseDrumChart('K: o - - -\nS: - - o -');+ expect(chart.time).toEqual({ beats: 4, beatValue: 4 });+ expect(chart.tempo).toBe(DEFAULT_DRUM_TEMPO);+ expect(chart.subdivision).toBe(4);+ expect(chart.errors).toEqual([]);+ });++ it('accepts headers in any order and a non-4/4 signature', () => {+ const chart = parseDrumChart('subdivision: 2\ntempo: 140\ntime: 6/8\n\nHH: xxxxxx');+ expect(chart.time).toEqual({ beats: 6, beatValue: 8 });+ expect(chart.tempo).toBe(140);+ expect(chart.subdivision).toBe(2);+ expect(chart.stepsPerBar).toBe(12);+ });++ it('collects bad header values into errors and keeps the defaults', () => {+ const chart = parseDrumChart('time: banana\ntempo: soon\nsubdivision: 99\n\nK: o---');+ expect(chart.time).toEqual({ beats: 4, beatValue: 4 });+ expect(chart.tempo).toBe(DEFAULT_DRUM_TEMPO);+ expect(chart.subdivision).toBe(4);+ expect(chart.errors).toEqual([+ 'bad time signature "banana"',+ 'bad tempo "soon"',+ `bad subdivision "99" (expected 1–${SUBDIVISION_MAX})`,+ ]);+ });++ it('ignores (and reports) a header that appears after the music', () => {+ const chart = parseDrumChart('K: o---\n\ntempo: 200\n\nS: --o-');+ expect(chart.tempo).toBe(DEFAULT_DRUM_TEMPO);+ expect(chart.errors).toContain('header "tempo" appears after the music started — ignored');+ });++ it('honors a kit: row-order override, filtered to the pieces present', () => {+ const chart = parseDrumChart('kit: K, S, HH\n\nHH: xxxx\nS: --o-\nK: o---');+ expect(chart.pieces).toEqual(['K', 'S', 'HH']);+ });++ it('falls back to kit order when kit: names nothing known', () => {+ const chart = parseDrumChart('kit: cowbell, vuvuzela\n\nHH: xxxx\nK: o---');+ expect(chart.pieces).toEqual(['HH', 'K']);+ expect(chart.errors[0]).toMatch(/names no known pieces/);+ });+});++describe('parseDrumChart — bars and rows', () => {+ it('orders rows by kit position regardless of how they were typed', () => {+ const chart = parseDrumChart('K: o---\nHH: xxxx\nS: --o-');+ expect(chart.bars[0].rows.map((r) => r.piece)).toEqual(['HH', 'S', 'K']);+ expect(chart.pieces).toEqual(['HH', 'S', 'K']);+ });++ it('splits blocks on blank lines and labels them from the leading comment', () => {+ const chart = parseDrumChart(`# Groove+HH: xxxxxxxx+K: o-------++# Fill+S: xxxxxxxx`);+ expect(chart.bars).toHaveLength(2);+ expect(chart.bars.map((b) => b.label)).toEqual(['Groove', 'Fill']);+ expect(chart.bars.map((b) => b.index)).toEqual([1, 2]);+ });++ it('parses spaced and unspaced rows identically', () => {+ const spaced = parseDrumChart('HH: x x x x x x x x');+ const tight = parseDrumChart('HH: xxxxxxxx');+ expect(cellIds(tight.bars[0].rows[0].cells)).toEqual(cellIds(spaced.bars[0].rows[0].cells));+ });++ it('tolerates decorative bar-line pipes inside a row', () => {+ const chart = parseDrumChart('subdivision: 1\n\nHH: |x-x-|');+ expect(cellIds(chart.bars[0].rows[0].cells)).toEqual(['normal', 'rest', 'normal', 'rest']);+ });++ it('pads a short row with rests to the full bar', () => {+ const chart = parseDrumChart('time: 4/4\nsubdivision: 4\n\nK: o');+ const cells = chart.bars[0].rows[0].cells;+ expect(cells).toHaveLength(16);+ expect(cells[0].rest).toBe(false);+ expect(cells.slice(1).every((c) => c.rest)).toBe(true);+ expect(chart.errors).toEqual([]);+ });++ it('truncates an over-long row and reports it', () => {+ const chart = parseDrumChart('subdivision: 1\n\nK: oooooo');+ expect(chart.bars[0].rows[0].cells).toHaveLength(4);+ expect(chart.errors).toEqual(['bar 1 K: 6 cells for a 4-step bar — extra cells truncated']);+ });++ it('skips an unknown piece row, reports it, and still parses the rest', () => {+ const chart = parseDrumChart('CB: xxxx\nHH: xxxx');+ expect(chart.pieces).toEqual(['HH']);+ expect(chart.errors).toEqual(['unknown kit piece "CB" — row skipped']);+ expect(chart.bars).toHaveLength(1);+ });++ it('reports a line that is not a header, comment or piece row', () => {+ const chart = parseDrumChart('HH: xxxx\njust some prose');+ expect(chart.errors).toEqual(['unrecognized line "just some prose"']);+ expect(chart.bars[0].rows).toHaveLength(1);+ });++ it('merges a piece typed twice in one block, hits winning over rests', () => {+ const chart = parseDrumChart('subdivision: 1\n\nHH: x---\nHH: --x-');+ const rows = chart.bars[0].rows;+ expect(rows).toHaveLength(1);+ expect(cellIds(rows[0].cells)).toEqual(['normal', 'rest', 'normal', 'rest']);+ });++ it('treats an unknown cell char as a rest and reports it', () => {+ const chart = parseDrumChart('subdivision: 1\n\nK: o?o?');+ expect(cellIds(chart.bars[0].rows[0].cells)).toEqual(['open', 'rest', 'open', 'rest']);+ expect(chart.errors).toEqual(['bar 1 K: unknown cell "?" — treated as a rest']);+ });++ it('drops a block with no valid rows instead of emitting an empty bar', () => {+ const chart = parseDrumChart('HH: xxxx\n\n# orphan label only\n\nK: o---');+ expect(chart.bars).toHaveLength(2);+ expect(chart.bars.map((b) => b.rows[0].piece)).toEqual(['HH', 'K']);+ });++ it('returns a usable empty chart for empty / nullish input', () => {+ for (const input of ['', null, undefined, ' \n\n']) {+ const chart = parseDrumChart(input);+ expect(chart.bars).toEqual([]);+ expect(chart.pieces).toEqual([]);+ expect(chart.errors).toEqual([]);+ }+ });+});++describe('parseDrumChart — repeats', () => {+ it('expands an x2 block into two numbered bars', () => {+ const chart = parseDrumChart('# Groove x2\nHH: xxxx\nK: o---');+ expect(chart.bars).toHaveLength(2);+ expect(chart.bars.map((b) => b.index)).toEqual([1, 2]);+ expect(chart.bars.map((b) => b.repeatPass)).toEqual([1, 2]);+ expect(chart.bars[0].label).toBe('Groove');+ });++ it('expands x4 and keeps later blocks numbered after the expansion', () => {+ const chart = parseDrumChart('# A x4\nHH: xxxx\n\n# B\nS: xxxx');+ expect(chart.bars.map((b) => b.index)).toEqual([1, 2, 3, 4, 5]);+ expect(chart.bars[4].label).toBe('B');+ });++ it('accepts the × form and treats x1 / x0 as a single pass', () => {+ expect(parseDrumChart('# A ×3\nHH: xxxx').bars).toHaveLength(3);+ expect(parseDrumChart('# A x1\nHH: xxxx').bars).toHaveLength(1);+ expect(parseDrumChart('# A x0\nHH: xxxx').bars).toHaveLength(1);+ });+});++describe('parseDrumChart — kit pieces and glyphs', () => {+ it('parses all nine kit pieces by id', () => {+ const text = KIT_PIECES.map((p) => `${p.id}: x---`).join('\n');+ const chart = parseDrumChart(`subdivision: 1\n\n${text}`);+ expect(chart.pieces).toEqual(KIT_PIECES.map((p) => p.id));+ expect(chart.errors).toEqual([]);+ });++ it('accepts every long alias and lowercase spelling', () => {+ for (const piece of KIT_PIECES) {+ for (const token of [piece.id.toLowerCase(), ...piece.aliases]) {+ const chart = parseDrumChart(`subdivision: 1\n\n${token}: x---`);+ expect(chart.pieces, `alias "${token}"`).toEqual([piece.id]);+ }+ }+ });++ it('parses all six cell glyphs with their velocities', () => {+ const chart = parseDrumChart('subdivision: 3\n\nHH: -xXogf');+ const cells = chart.bars[0].rows[0].cells.slice(0, 6);+ expect(cellIds(cells)).toEqual(['rest', 'normal', 'accent', 'open', 'ghost', 'flam']);+ expect(cells.map((c) => c.velocity)).toEqual([+ CELL_GLYPHS['-'].velocity, CELL_GLYPHS.x.velocity, CELL_GLYPHS.X.velocity,+ CELL_GLYPHS.o.velocity, CELL_GLYPHS.g.velocity, CELL_GLYPHS.f.velocity,+ ]);+ expect(cells[2].accent).toBe(true);+ expect(cells[3].open).toBe(true);+ expect(cells[4].ghost).toBe(true);+ expect(cells[5].flam).toBe(true);+ });++ it('treats . and _ as rest synonyms', () => {+ const chart = parseDrumChart('subdivision: 1\n\nK: o._o');+ expect(cellIds(chart.bars[0].rows[0].cells)).toEqual(['open', 'rest', 'rest', 'open']);+ expect(chart.errors).toEqual([]);+ });++ it('exposes a descriptor per piece and null for an unknown id', () => {+ expect(kitPiece('HH')).toMatchObject({ label: 'Hi-Hat', sound: 'hihat' });+ expect(kitPiece('CB')).toBeNull();+ // Every piece carries the fields the renderer + synth read.+ for (const piece of KIT_PIECES) {+ expect(piece).toMatchObject({+ id: expect.any(String), label: expect.any(String),+ midi: expect.any(Number), sound: expect.any(String),+ });+ expect(['cross', 'head']).toContain(piece.glyph);+ }+ });+});++describe('isDrumNotation', () => {+ it('recognizes a drum chart', () => {+ expect(isDrumNotation(ROCK_BEAT)).toBe(true);+ expect(isDrumNotation('HH: xxxx\nK: o---')).toBe(true);+ });++ it('recognizes a single row when a drum-only header is present', () => {+ expect(isDrumNotation('subdivision: 4\n\nHH: xxxxxxxx')).toBe(true);+ expect(isDrumNotation('HH: xxxxxxxx')).toBe(false);+ });++ it('rejects a chord sheet, a tab staff, and prose', () => {+ expect(isDrumNotation('[Verse]\nC G Am F\nPlaceholder words here')).toBe(false);+ expect(isDrumNotation('e|--0--2--3--|\nB|--------3--|')).toBe(false);+ expect(isDrumNotation('S: something someone said')).toBe(false);+ expect(isDrumNotation('')).toBe(false);+ expect(isDrumNotation(null)).toBe(false);+ });++ it('rejects an all-rest grid (ambiguous, no hits)', () => {+ expect(isDrumNotation('HH: ----\nK: ----')).toBe(false);+ });+});++describe('drumChartHasMusic', () => {+ it('is true only when a cell is actually struck', () => {+ expect(drumChartHasMusic(ROCK_BEAT)).toBe(true);+ expect(drumChartHasMusic('HH: ----\nK: ----')).toBe(false);+ expect(drumChartHasMusic('time: 4/4')).toBe(false);+ expect(drumChartHasMusic('')).toBe(false);+ });+});diff --git a/client/src/lib/drumPlayback.js b/client/src/lib/drumPlayback.jsnew file mode 100644index 0000000000..e0cf378aa7--- /dev/null+++ b/client/src/lib/drumPlayback.js@@ -0,0 +1,454 @@+// Drum-kit playback for the SongBook `drum` format — turns a parsed drum chart+// (see drumNotation.js) into an audible groove you can practice along with at a+// tempo you control. The third consumer of the shared lookahead transport+// (`lookaheadTransport.js`), alongside `createScorePlayer` and `createMidiPlayer`:+// the clock, node lifecycle and teardown semantics are all the shared ones, so+// this module only owns the schedule math and the kit voices.+//+// The kit is SYNTHESIZED — noise burst + bandpass for snare/hats/cymbals, a+// pitch-dropping sine for kick/toms. No sampled kit ships with PortOS (repo size+// + sample licensing), and the synth reads well enough as a practice click-with-+// groove, which is what the play-along is for.+//+// `buildDrumSchedule` is PURE (no Web Audio) so the timing math — bpm, time+// signature, subdivision, count-in, loop expansion, per-glyph velocity — is+// unit-testable in a node env, mirroring `buildSchedule` in scorePlayback.js.++import { getAudioContext as ctx } from './audioContext.js';+import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';+import { makeSafeCall } from './scorePlayback.js';+import { kitPiece, DEFAULT_DRUM_TEMPO } from './drumNotation.js';++const { SCHEDULE_AHEAD } = SYNTH_TIMING;+const safeCall = makeSafeCall('drum playback');++// --- Schedule building (pure) ----------------------------------------------++// Clamp a loop range against the chart's real bar count. Returns null when the+// chart is empty or looping is off, so callers can branch on a single value+// instead of juggling three flags. `from`/`to` are 1-based inclusive bar numbers;+// a reversed pair is normalized rather than rejected (the UI's two selects can+// legitimately cross while the user is picking).+export const resolveLoopRange = (barCount, loop) => {+ if (!loop || !barCount) return null;+ const rawFrom = Number.isFinite(loop.from) ? Math.trunc(loop.from) : 1;+ const rawTo = Number.isFinite(loop.to) ? Math.trunc(loop.to) : barCount;+ const from = Math.min(Math.max(1, Math.min(rawFrom, rawTo)), barCount);+ const to = Math.min(Math.max(from, Math.max(rawFrom, rawTo)), barCount);+ return { from, to };+};++/**+ * Flatten a parsed drum chart into absolute-time hit events.+ *+ * Timing mirrors `scorePlayback.buildSchedule`: the tempo counts beats where one+ * beat is the time-signature denominator, so 4/4 reads as quarter=bpm and 6/8 as+ * eighth=bpm. One grid step is one beat / `subdivision`.+ *+ * @param {object} chart — output of `parseDrumChart`.+ * @param {object} [options]+ * @param {number} [options.bpm] — practice tempo (else the chart's `tempo`, else 90).+ * @param {{from:number,to:number}} [options.loop] — 1-based inclusive bar range;+ * the schedule covers ONLY those bars (the transport loops by replaying it).+ * @param {number} [options.countInBars] — silent-lead bars of click before bar 1.+ * @returns {{ events, bpm, stepSec, barSec, totalSec, countInSec, bars, loop }}+ */+export const buildDrumSchedule = (chart, options = {}) => {+ const beats = chart?.time?.beats || 4;+ const subdivision = chart?.subdivision || 4;+ const bpm = Number.isFinite(options.bpm) && options.bpm > 0+ ? options.bpm+ : (Number.isFinite(chart?.tempo) && chart.tempo > 0 ? chart.tempo : DEFAULT_DRUM_TEMPO);++ // The tempo counts NOTATED beats (the time-signature denominator), so one beat+ // is simply 60/bpm — 4/4 reads as quarter=bpm and 6/8 as eighth=bpm, the+ // conventional interpretation and the same one scorePlayback.buildSchedule+ // arrives at via its quarter-note durations. One grid step is a beat split+ // `subdivision` ways.+ const beatSec = 60 / bpm;+ const stepSec = beatSec / subdivision;+ const barSec = beatSec * beats;++ const allBars = Array.isArray(chart?.bars) ? chart.bars : [];+ const loop = resolveLoopRange(allBars.length, options.loop);+ const bars = loop ? allBars.slice(loop.from - 1, loop.to) : allBars;++ const countInBars = Math.max(0, Math.min(4, Math.trunc(options.countInBars) || 0));+ const countInSec = countInBars * barSec;++ const events = [];+ // Count-in: one click per notated beat, the downbeat accented. Scheduled as+ // real events (not a second clock) so the transport sounds them through the+ // same voice path, and `countIn: true` + a null bar/step lets the UI tell+ // "counting in" from "bar 1".+ for (let bar = 0; bar < countInBars; bar += 1) {+ for (let beat = 0; beat < beats; beat += 1) {+ events.push({+ bar: null,+ step: null,+ beat: beat + 1,+ piece: null,+ sound: 'click',+ velocity: beat === 0 ? 1 : 0.6,+ countIn: true,+ startSec: (bar * beats + beat) * beatSec,+ durSec: Math.min(0.08, stepSec),+ });+ }+ }++ bars.forEach((bar, barIdx) => {+ const barStart = countInSec + barIdx * barSec;+ for (const row of bar.rows || []) {+ const piece = kitPiece(row.piece);+ row.cells.forEach((cell, step) => {+ if (!cell || cell.rest) return;+ events.push({+ // The chart's own bar number (survives a loop-range slice, so the+ // playhead lights the right bar on the full sheet).+ bar: bar.index,+ step,+ piece: row.piece,+ sound: piece?.sound || 'snare',+ velocity: cell.velocity,+ open: !!cell.open,+ accent: !!cell.accent,+ ghost: !!cell.ghost,+ flam: !!cell.flam,+ countIn: false,+ startSec: barStart + step * stepSec,+ durSec: stepSec,+ });+ });+ }+ });++ events.sort((a, b) => a.startSec - b.startSec);+ return {+ events,+ bpm,+ stepSec,+ barSec,+ beatSec,+ countInSec,+ bars,+ loop,+ totalSec: countInSec + bars.length * barSec,+ };+};++// --- Kit voices -------------------------------------------------------------++const VOICE_PEAK = 0.5; // per-hit gain ceiling before the per-cell velocity scale++// Shared white-noise buffer (1s, re-generated only if the sample rate changes) —+// same idiom as chiptunePlayback.js's noise voice.+let noiseBuffer = null;+const getNoiseBuffer = (c) => {+ if (!noiseBuffer || noiseBuffer.sampleRate !== c.sampleRate) {+ noiseBuffer = c.createBuffer(1, c.sampleRate, c.sampleRate);+ const data = noiseBuffer.getChannelData(0);+ for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;+ }+ return noiseBuffer;+};++// One voice recipe per kit sound. `tone` sounds a pitch-dropping sine (membranes);+// `noise` sounds a bandpassed noise burst (metal + snare wires). `decay` is the+// exponential tail in seconds; `open` extends it for an open hi-hat.+const VOICES = {+ kick: { type: 'tone', from: 150, to: 45, decay: 0.22, gain: 1 },+ tom1: { type: 'tone', from: 260, to: 150, decay: 0.24, gain: 0.85 },+ tom2: { type: 'tone', from: 200, to: 115, decay: 0.28, gain: 0.85 },+ floor: { type: 'tone', from: 140, to: 80, decay: 0.34, gain: 0.85 },+ // A snare is a membrane plus wires: a short tone under a wide noise burst.+ snare: { type: 'noise', freq: 1900, q: 0.7, decay: 0.16, gain: 0.9, body: { from: 210, to: 170, decay: 0.09, gain: 0.5 } },+ hihat: { type: 'noise', freq: 8500, q: 1.6, decay: 0.045, openDecay: 0.28, gain: 0.5 },+ hihatFoot: { type: 'noise', freq: 7000, q: 1.4, decay: 0.035, gain: 0.35 },+ ride: { type: 'noise', freq: 6200, q: 0.9, decay: 0.5, gain: 0.4 },+ crash: { type: 'noise', freq: 4200, q: 0.4, decay: 1.1, gain: 0.5 },+ // Metronome click layered over the kit (and the count-in voice) — a short+ // pitched blip, brighter on the accent, so it cuts through the noise voices.+ click: { type: 'tone', from: 1600, to: 1550, decay: 0.05, gain: 0.7 },+};++// Flam grace-note lead: the ghost hit lands this far BEFORE the main hit.+const FLAM_LEAD_SEC = 0.032;++// Schedule one voice node pair; returns { osc, gain } for the transport's+// teardown tracking (an AudioBufferSourceNode satisfies the same+// start/stop/onended surface an OscillatorNode does).+const scheduleVoice = (c, voice, startAt, destination, { velocity, open }) => {+ const gain = c.createGain();+ const peak = Math.max(0.0002, VOICE_PEAK * (voice.gain ?? 1) * velocity);+ const decay = open && voice.openDecay ? voice.openDecay : voice.decay;+ let osc;++ if (voice.type === 'noise') {+ osc = c.createBufferSource();+ osc.buffer = getNoiseBuffer(c);+ osc.loop = true;+ const filter = c.createBiquadFilter();+ filter.type = 'bandpass';+ filter.frequency.setValueAtTime(voice.freq, startAt);+ filter.Q.value = voice.q;+ osc.connect(filter).connect(gain);+ } else {+ osc = c.createOscillator();+ osc.type = 'sine';+ osc.frequency.setValueAtTime(voice.from, startAt);+ osc.frequency.exponentialRampToValueAtTime(voice.to, startAt + decay);+ osc.connect(gain);+ }++ // Percussive envelope: instant attack, exponential decay to silence.+ gain.gain.setValueAtTime(peak, startAt);+ gain.gain.exponentialRampToValueAtTime(0.0001, startAt + decay);+ gain.connect(destination);+ osc.start(startAt);+ osc.stop(startAt + decay + 0.02);+ return { osc, gain };+};++// Sound one chart event — the main hit, plus a snare-body tone and/or a flam+// grace note when the voice/glyph calls for them. Every created node pair goes+// through `track` so the transport tears all of them down on stop.+const soundEvent = (c, ev, at, destination, track) => {+ const voice = VOICES[ev.sound] || VOICES.snare;+ if (ev.flam) {+ track(scheduleVoice(c, voice, Math.max(at - FLAM_LEAD_SEC, 0), destination, {+ velocity: ev.velocity * 0.45, open: ev.open,+ }));+ }+ track(scheduleVoice(c, voice, at, destination, { velocity: ev.velocity, open: ev.open }));+ if (voice.body) {+ track(scheduleVoice(c, voice.body, at, destination, { velocity: ev.velocity, open: false }));+ }+};++// --- Player -----------------------------------------------------------------++/**+ * Build a drum-kit player over a parsed chart.+ *+ * @param {object} chart — output of `parseDrumChart`.+ * @param {object} [options]+ * @param {number} [options.bpm] — practice tempo (else the chart's `tempo:`).+ * @param {number} [options.countInBars] — click-only lead-in bars.+ * @param {{from:number,to:number}|null} [options.loopBars] — 1-based inclusive+ * 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 {({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, 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 countInBars = options.countInBars || 0;++ const build = () => buildDrumSchedule(chart, { bpm, loop: loopBars, countInBars });+ let schedule = build();+ let master = 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+ // than baked into the schedule, so toggling the click mid-play needs no rebuild.+ const clickTimes = () => {+ const out = [];+ const beats = chart?.time?.beats || 4;+ for (let bar = 0; bar < schedule.bars.length; bar += 1) {+ for (let beat = 0; beat < beats; beat += 1) {+ out.push({+ startSec: schedule.countInSec + bar * schedule.barSec + beat * schedule.beatSec,+ accent: beat === 0,+ });+ }+ }+ return out;+ };+ let clicks = clickTimes();++ // Index of the first music (non-count-in) event. Events are sorted by onset and+ // every count-in event precedes the music, so this is where loop pass 2+ starts+ // — a looped range must not re-count-you-in every time around.+ const firstMusicIdx = () => {+ const i = schedule.events.findIndex((ev) => !ev.countIn);+ return i < 0 ? schedule.events.length : i;+ };+ // Length of one LOOP pass: the music only, since the count-in belongs to pass 0.+ const musicSec = () => schedule.totalSec - schedule.countInSec;+ // A pass with no music has nothing to advance past — a looping player must not+ // spin its rebase branch forever on one.+ const canLoop = () => !!schedule.loop && musicSec() > 0;++ // A cursor walks one list (events or clicks) forward through loop passes. Each+ // walker keeps its OWN `pass` because they advance at different rates: the+ // scheduler runs a lookahead window AHEAD of the audio clock while the playhead+ // trails BEHIND it, so a shared pass counter would drag the trailing walker+ // across a loop boundary early and collapse the loop to one pass.+ //+ // A pass-N onset sits at `pass * musicSec + ev.startSec` — pass 0 covers the+ // count-in plus the music, and pass ≥ 1 starts at `firstMusicIdx`, so the first+ // music event of pass 1 lands exactly at the end of pass 0.+ const makeCursor = () => ({ idx: 0, pass: 0 });+ const cursorTime = (cursor, startSec) => startSec + cursor.pass * musicSec();+ // Advance a cursor onto the next pass, or return false when it must stop.+ const advancePass = (cursor, from) => {+ if (!canLoop()) return false;+ cursor.pass += 1;+ cursor.idx = from;+ return true;+ };++ let hitCursor = makeCursor(); // schedules audio (runs ahead)+ let clickCursor = makeCursor(); // schedules the click layer (runs ahead)+ let headCursor = makeCursor(); // drives the playhead (trails)+ let lastHeadKey = null;+ const resetCursor = () => {+ hitCursor = makeCursor();+ clickCursor = makeCursor();+ headCursor = makeCursor();+ lastHeadKey = null;+ };++ const notify = (info) => safeCall(onStep, info);++ const scheduleWindow = (now, startTime, track) => {+ if (!master) return;+ const c = ctx();+ const horizon = now + SCHEDULE_AHEAD;++ // Hand every due hit to the audio clock; on exhausting the list a looping+ // player rebases onto the next pass and keeps going, while a one-shot player+ // stops scheduling and lets the transport's own end check finish it.+ for (;;) {+ if (hitCursor.idx >= schedule.events.length) {+ if (!advancePass(hitCursor, firstMusicIdx())) break;+ continue;+ }+ const ev = schedule.events[hitCursor.idx];+ const at = startTime + cursorTime(hitCursor, ev.startSec);+ if (at >= horizon) break;+ hitCursor.idx += 1;+ if (at < now - 0.05) continue; // already past (first tick after a stall)+ soundEvent(c, ev, Math.max(at, now), master, track);+ }++ // The click layer walks its own list on the same pass geometry. Its pass ≥ 1+ // restart index is 0: every click belongs to the music (the count-in's clicks+ // are real events on the hit list), so a loop pass replays all of them.+ if (clickEnabled) {+ for (;;) {+ if (clickCursor.idx >= clicks.length) {+ if (!advancePass(clickCursor, 0)) break;+ continue;+ }+ const click = clicks[clickCursor.idx];+ const at = startTime + cursorTime(clickCursor, click.startSec);+ if (at >= horizon) break;+ clickCursor.idx += 1;+ if (at < now - 0.05) continue;+ track(scheduleVoice(c, VOICES.click, Math.max(at, now), master, {+ velocity: click.accent ? 1 : 0.55, open: false,+ }));+ }+ }++ // Playhead: report the LATEST position whose onset has already passed. Keyed+ // by bar+step so a bar's simultaneous hits fire one callback, not one per+ // piece — and the key includes the pass, so a looped single bar re-lights.+ let latest = null;+ for (;;) {+ if (headCursor.idx >= schedule.events.length) {+ if (!advancePass(headCursor, firstMusicIdx())) break;+ continue;+ }+ const ev = schedule.events[headCursor.idx];+ if (startTime + cursorTime(headCursor, ev.startSec) > now) break;+ latest = ev;+ headCursor.idx += 1;+ }+ if (latest) {+ const key = `${headCursor.pass}:${latest.countIn ? 'c' : 'm'}:${latest.bar}:${latest.step}`;+ if (key !== lastHeadKey) {+ lastHeadKey = key;+ notify({ bar: latest.bar, step: latest.step, countIn: latest.countIn });+ }+ }+ };++ const transport = createLookaheadTransport({+ // A looping player never "ends" on its own — the transport's end check must+ // not finish it, so its length is unbounded until stop().+ getTotalSec: () => (schedule.loop ? Infinity : schedule.totalSec),+ scheduleWindow,+ prepare: () => {+ schedule = build();+ if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return false; }+ clicks = clickTimes();+ resetCursor();+ const c = ctx();+ master = c.createGain();+ master.gain.value = 1;+ master.connect(c.destination);+ return true;+ },+ seekCursors: (offsetSec) => {+ // The sheet has no scrub UI, so in practice this only ever runs with 0+ // (fresh play, and stop/finish resetting to the top). A resume offset+ // (transport.pause → play) positions every cursor past what already sounded.+ resetCursor();+ if (offsetSec <= 0) return;+ const skip = (cursor, list, key) => {+ while (cursor.idx < list.length && list[cursor.idx][key] < offsetSec) cursor.idx += 1;+ };+ skip(hitCursor, schedule.events, 'startSec');+ skip(headCursor, schedule.events, 'startSec');+ skip(clickCursor, clicks, 'startSec');+ },+ onStop: () => { notify(null); },+ onEnded: () => { safeCall(onEnded); },+ onTeardown: () => {+ if (master) {+ // Outside the request lifecycle — a disconnect on an already-torn-down+ // node must not throw into the transport's teardown path.+ try { master.disconnect(); } catch { /* already gone */ }+ master = null;+ }+ },+ });++ // A live setting change rebuilds the schedule while idle; while playing, the+ // caller restarts (a mid-groove tempo jump would desync the playhead against+ // already-scheduled audio).+ const rebuildIfIdle = () => {+ if (transport.isPlaying()) return;+ schedule = build();+ clicks = clickTimes();+ resetCursor();+ };++ return {+ play: transport.play,+ pause: transport.pause,+ stop: transport.stop,+ isPlaying: transport.isPlaying,+ setBpm: (next) => {+ bpm = Number.isFinite(next) && next > 0 ? next : null;+ rebuildIfIdle();+ },+ setLoop: (next) => { loopBars = next || null; rebuildIfIdle(); },+ setCountIn: (bars) => {+ countInBars = Math.max(0, Math.trunc(Number(bars)) || 0);+ rebuildIfIdle();+ },+ setClick: (enabled) => { clickEnabled = !!enabled; },+ schedule: () => schedule,+ };+};diff --git a/client/src/lib/drumPlayback.test.js b/client/src/lib/drumPlayback.test.jsnew file mode 100644index 0000000000..f99514a90d--- /dev/null+++ b/client/src/lib/drumPlayback.test.js@@ -0,0 +1,208 @@+import { describe, it, expect } from 'vitest';+import { parseDrumChart, CELL_GLYPHS } from './drumNotation.js';+import { buildDrumSchedule, resolveLoopRange } 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.++// 2 bars at subdivision 1 keeps the arithmetic readable: one cell per beat.+const TWO_BARS = `time: 4/4+tempo: 120+subdivision: 1++# A+HH: xxxx+K: o---++# B+S: x-x-`;++const near = (a, b) => expect(a).toBeCloseTo(b, 6);++describe('buildDrumSchedule — timing', () => {+ it('spaces steps by beat/subdivision at the given bpm', () => {+ const chart = parseDrumChart('time: 4/4\nsubdivision: 4\n\nHH: x-x-x-x-x-x-x-x-');+ const { events, stepSec, barSec, beatSec, totalSec } = buildDrumSchedule(chart, { bpm: 120 });+ near(beatSec, 0.5); // 120 bpm → 0.5s per notated beat+ near(stepSec, 0.125); // 16ths+ near(barSec, 2);+ near(totalSec, 2);+ expect(events).toHaveLength(8);+ events.forEach((ev, i) => near(ev.startSec, i * 0.25));+ });++ it('honors the chart tempo when no bpm override is given', () => {+ const chart = parseDrumChart('tempo: 60\nsubdivision: 1\n\nK: oooo');+ const schedule = buildDrumSchedule(chart);+ expect(schedule.bpm).toBe(60);+ near(schedule.beatSec, 1);+ near(schedule.totalSec, 4);+ });++ it('falls back to 90 bpm for a headerless chart', () => {+ expect(buildDrumSchedule(parseDrumChart('K: o---')).bpm).toBe(90);+ });++ it('counts the time-signature denominator as the beat (6/8 counts eighths)', () => {+ const chart = parseDrumChart('time: 6/8\ntempo: 120\nsubdivision: 1\n\nHH: xxxxxx');+ const { beatSec, barSec, events } = buildDrumSchedule(chart);+ near(beatSec, 0.5);+ near(barSec, 3); // six eighth-note beats+ near(events[5].startSec, 2.5);+ });++ it('lays consecutive bars end to end', () => {+ const { events, barSec } = buildDrumSchedule(parseDrumChart(TWO_BARS), { bpm: 120 });+ near(barSec, 2);+ const barB = events.filter((e) => e.bar === 2);+ expect(barB).toHaveLength(2);+ near(barB[0].startSec, 2); // bar 2 step 0+ near(barB[1].startSec, 3); // bar 2 step 2+ });++ it('expands a repeated block into real, separately-timed bars', () => {+ const chart = parseDrumChart('tempo: 120\nsubdivision: 1\n\n# A x3\nK: o---');+ const { events, totalSec } = buildDrumSchedule(chart);+ expect(events.map((e) => e.bar)).toEqual([1, 2, 3]);+ events.forEach((ev, i) => near(ev.startSec, i * 2));+ near(totalSec, 6);+ });++ it('returns an empty, usable schedule for an empty chart', () => {+ const schedule = buildDrumSchedule(parseDrumChart(''), { bpm: 100 });+ expect(schedule.events).toEqual([]);+ expect(schedule.totalSec).toBe(0);+ expect(schedule.loop).toBeNull();+ });+});++describe('buildDrumSchedule — velocity and glyph flags', () => {+ it('maps each glyph to its velocity', () => {+ const chart = parseDrumChart('subdivision: 3\n\nHH: xXogf-');+ const { events } = buildDrumSchedule(chart, { bpm: 120 });+ expect(events.map((e) => e.velocity)).toEqual([+ CELL_GLYPHS.x.velocity, CELL_GLYPHS.X.velocity, CELL_GLYPHS.o.velocity,+ CELL_GLYPHS.g.velocity, CELL_GLYPHS.f.velocity,+ ]);+ expect(events.map((e) => e.step)).toEqual([0, 1, 2, 3, 4]);+ // Accent > normal > ghost is the contract the synth relies on.+ expect(CELL_GLYPHS.X.velocity).toBeGreaterThan(CELL_GLYPHS.x.velocity);+ expect(CELL_GLYPHS.x.velocity).toBeGreaterThan(CELL_GLYPHS.g.velocity);+ });++ it('carries the open / accent / ghost / flam flags onto the event', () => {+ const { events } = buildDrumSchedule(parseDrumChart('subdivision: 2\n\nHH: oXgf'), { bpm: 120 });+ expect(events.map((e) => [e.open, e.accent, e.ghost, e.flam])).toEqual([+ [true, false, false, false],+ [false, true, false, false],+ [false, false, true, false],+ [false, false, false, true],+ ]);+ });++ it('emits no event for a rest', () => {+ const { events } = buildDrumSchedule(parseDrumChart('subdivision: 1\n\nK: -o--'), { bpm: 120 });+ expect(events).toHaveLength(1);+ expect(events[0].step).toBe(1);+ });++ it('resolves each piece to its synth voice', () => {+ const { events } = buildDrumSchedule(parseDrumChart('subdivision: 1\n\nK: o---\nS: -x--\nCR: --x-'), { bpm: 120 });+ expect(events.map((e) => [e.piece, e.sound])).toEqual([+ ['K', 'kick'], ['S', 'snare'], ['CR', 'crash'],+ ]);+ });++ it('sorts simultaneous hits together by onset', () => {+ const { events } = buildDrumSchedule(parseDrumChart('subdivision: 1\n\nHH: xxxx\nK: o-o-'), { bpm: 120 });+ expect(events.map((e) => e.startSec)).toEqual([...events.map((e) => e.startSec)].sort((a, b) => a - b));+ expect(events.filter((e) => e.startSec === 0).map((e) => e.piece).sort()).toEqual(['HH', 'K']);+ });+});++describe('buildDrumSchedule — count-in', () => {+ it('prepends one click per beat, downbeat accented, and offsets the music', () => {+ const chart = parseDrumChart('time: 4/4\ntempo: 120\nsubdivision: 1\n\nK: o---');+ const { events, countInSec, totalSec } = buildDrumSchedule(chart, { countInBars: 1 });+ near(countInSec, 2);+ near(totalSec, 4);+ const countIn = events.filter((e) => e.countIn);+ expect(countIn).toHaveLength(4);+ expect(countIn.every((e) => e.piece === null)).toBe(true);+ expect(countIn.map((e) => e.sound)).toEqual(Array(4).fill('click'));+ expect(countIn[0].velocity).toBeGreaterThan(countIn[1].velocity);+ countIn.forEach((ev, i) => near(ev.startSec, i * 0.5));+ // The music starts after the count-in.+ const music = events.filter((e) => !e.countIn);+ near(music[0].startSec, 2);+ expect(music[0].bar).toBe(1);+ });++ it('supports 2 bars of count-in and clamps a silly value', () => {+ const chart = parseDrumChart('tempo: 120\nsubdivision: 1\n\nK: o---');+ near(buildDrumSchedule(chart, { countInBars: 2 }).countInSec, 4);+ near(buildDrumSchedule(chart, { countInBars: 99 }).countInSec, 8); // clamped to 4 bars+ near(buildDrumSchedule(chart, { countInBars: -3 }).countInSec, 0);+ expect(buildDrumSchedule(chart, { countInBars: 0 }).events.every((e) => !e.countIn)).toBe(true);+ });+});++describe('buildDrumSchedule — loop range', () => {+ const chart = parseDrumChart(`tempo: 120+subdivision: 1++# A+K: o---++# B+S: x---++# C+HH: x---`);++ it('covers only the looped bars, rebased to zero', () => {+ const { events, bars, loop, totalSec } = buildDrumSchedule(chart, { loop: { from: 2, to: 3 } });+ expect(loop).toEqual({ from: 2, to: 3 });+ expect(bars.map((b) => b.index)).toEqual([2, 3]);+ // Bar numbers stay the CHART's (playhead correctness), but time starts at 0.+ expect(events.map((e) => e.bar)).toEqual([2, 3]);+ near(events[0].startSec, 0);+ near(events[1].startSec, 2);+ near(totalSec, 4);+ });++ it('offsets a looped range by the count-in', () => {+ const { events, countInSec } = buildDrumSchedule(chart, { loop: { from: 3, to: 3 }, countInBars: 1 });+ near(countInSec, 2);+ const music = events.filter((e) => !e.countIn);+ expect(music.map((e) => e.bar)).toEqual([3]);+ near(music[0].startSec, 2);+ });++ it('covers the whole chart when loop is absent', () => {+ const { bars, loop } = buildDrumSchedule(chart, {});+ expect(loop).toBeNull();+ expect(bars).toHaveLength(3);+ });+});++describe('resolveLoopRange', () => {+ it('returns null with no loop or no bars', () => {+ expect(resolveLoopRange(4, null)).toBeNull();+ expect(resolveLoopRange(0, { from: 1, to: 2 })).toBeNull();+ });++ it('clamps to the real bar count', () => {+ expect(resolveLoopRange(4, { from: 0, to: 99 })).toEqual({ from: 1, to: 4 });+ expect(resolveLoopRange(4, { from: 9, to: 9 })).toEqual({ from: 4, to: 4 });+ });++ it('normalizes a reversed range instead of rejecting it', () => {+ expect(resolveLoopRange(8, { from: 6, to: 2 })).toEqual({ from: 2, to: 6 });+ });++ it('defaults a missing endpoint to the full span', () => {+ expect(resolveLoopRange(5, {})).toEqual({ from: 1, to: 5 });+ expect(resolveLoopRange(5, { from: 3 })).toEqual({ from: 3, to: 5 });+ });+});diff --git a/client/src/lib/drumPlayer.test.js b/client/src/lib/drumPlayer.test.jsnew file mode 100644index 0000000000..ce753544ab--- /dev/null+++ b/client/src/lib/drumPlayer.test.js@@ -0,0 +1,196 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { parseDrumChart } from './drumNotation.js';+import { createDrumPlayer } from './drumPlayback.js';+import { createFakeAudio } from '../test/fakeAudioContext.js';++// The AUDIBLE half of drumPlayback.js — buildDrumSchedule's pure math is covered+// in drumPlayback.test.js with no Web Audio at all. This suite drives the real+// lookahead transport against the shared Web Audio fake, so the wiring (voices+// actually scheduled, playhead callbacks, loop rebase, teardown) is pinned.+//+// One fake pair for the whole file — lib/audioContext.js caches the context.+const { FakeAudioContext, audio } = createFakeAudio();++// Advance the audio clock relatively, ticking the lookahead interval alongside.+const drive = (deltaSec) => {+ const target = audio.now + deltaSec;+ for (let t = audio.now + 0.05; t <= target + 1e-9; t += 0.05) {+ audio.now = Number(t.toFixed(4));+ vi.advanceTimersByTime(50);+ }+};++// Invented groove (privacy convention): 2 bars, subdivision 1 (one cell/beat) at+// 240 bpm → 0.25s/beat, 1s/bar, so the whole chart is 2s.+const CHART = parseDrumChart(`time: 4/4+tempo: 240+subdivision: 1++# A+HH: xxxx+K: o-o-++# B+S: x-x-`);++describe('createDrumPlayer', () => {+ beforeEach(() => {+ audio.reset();+ vi.stubGlobal('AudioContext', FakeAudioContext);+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++ it('sounds a voice per hit and finishes with onEnded', async () => {+ const ended = vi.fn();+ const player = createDrumPlayer(CHART, { onEnded: ended });+ await player.play();+ drive(3);+ // 4 hats + 2 kicks + 2 snares = 8 hits. The snare voice layers a body tone,+ // so voices ≥ hits — what matters is that every hit sounded.+ expect(audio.oscillators.length).toBeGreaterThanOrEqual(8);+ expect(ended).toHaveBeenCalledTimes(1);+ expect(player.isPlaying()).toBe(false);+ });++ it('uses bandpassed noise for cymbals/snare and a pitched sweep for the kick', async () => {+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: x---\nK: -o--'), {});+ await player.play();+ drive(2);+ // The hat is a filtered noise burst; the kick is a sine sweep (no filter).+ expect(audio.filters.length).toBe(1);+ expect(audio.filters[0].type).toBe('bandpass');+ expect(audio.oscillators.some((o) => o.noise)).toBe(true);+ expect(audio.oscillators.some((o) => !o.noise)).toBe(true);+ });++ it('scales voice gain by the glyph velocity (accent louder than ghost)', async () => {+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: X-g-'), {});+ await player.play();+ drive(2);+ const peaks = audio.gains.map((g) => Math.max(...g.gain.values, 0));+ // [master, accent, ghost] in creation order — the accent must be louder.+ expect(peaks[1]).toBeGreaterThan(peaks[2]);+ player.stop();+ });++ it('reports the playhead per grid position, once per bar+step', async () => {+ const steps = [];+ const player = createDrumPlayer(CHART, { onStep: (info) => steps.push(info) });+ await player.play();+ drive(3);+ const positions = steps.filter(Boolean).map((s) => `${s.bar}:${s.step}`);+ // Simultaneous hats+kick at bar 1 step 0 collapse to ONE callback.+ expect(positions[0]).toBe('1:0');+ expect(new Set(positions).size).toBe(positions.length);+ expect(positions).toContain('2:0');+ // The final callback clears the playhead.+ expect(steps.at(-1)).toBeNull();+ });++ it('reports count-in beats as countIn with no bar/step', async () => {+ const steps = [];+ const player = createDrumPlayer(CHART, { countInBars: 1, onStep: (i) => steps.push(i) });+ await player.play();+ drive(0.6); // still inside the 1s count-in bar+ const counted = steps.filter((s) => s?.countIn);+ expect(counted.length).toBeGreaterThan(0);+ expect(counted[0]).toMatchObject({ bar: null, step: null, countIn: true });+ player.stop();+ });++ it('loops a bar range without ending and without re-counting-in', async () => {+ const ended = vi.fn();+ const steps = [];+ const player = createDrumPlayer(CHART, {+ loopBars: { from: 2, to: 2 }, countInBars: 1, onEnded: ended, onStep: (i) => steps.push(i),+ });+ await player.play();+ drive(6); // several passes over a 1-bar loop+ expect(ended).not.toHaveBeenCalled();+ expect(player.isPlaying()).toBe(true);+ // Only bar 2 ever sounds; the count-in happens exactly once.+ const music = steps.filter((s) => s && !s.countIn);+ expect(new Set(music.map((s) => s.bar))).toEqual(new Set([2]));+ expect(music.length).toBeGreaterThan(3); // looped, not a single pass+ player.stop();+ });++ it('layers a click when enabled and not when disabled', async () => {+ const quiet = createDrumPlayer(CHART, {});+ await quiet.play();+ drive(2.5);+ const withoutClick = audio.oscillators.length;+ quiet.stop();++ audio.reset();+ const clicked = createDrumPlayer(CHART, { clickEnabled: true });+ await clicked.play();+ drive(2.5);+ // 8 beats of click over the two bars.+ expect(audio.oscillators.length).toBeGreaterThan(withoutClick);+ clicked.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) });+ await player.play();+ drive(0.5);+ const scheduled = audio.oscillators.length;+ expect(scheduled).toBeGreaterThan(0);+ player.stop();+ expect(steps.at(-1)).toBeNull();+ // Every voice was stopped, and nothing further schedules.+ expect(audio.oscillators.every((o) => o.stopped !== null)).toBe(true);+ drive(3);+ expect(audio.oscillators).toHaveLength(scheduled);+ expect(player.isPlaying()).toBe(false);+ });++ it('setBpm while idle re-times the schedule; a faster tempo is shorter', async () => {+ const player = createDrumPlayer(CHART, {});+ expect(player.schedule().totalSec).toBeCloseTo(2, 5); // 240 bpm written+ player.setBpm(120);+ expect(player.schedule().totalSec).toBeCloseTo(4, 5);+ player.setBpm(240);+ expect(player.schedule().totalSec).toBeCloseTo(2, 5);+ });++ it('setLoop while idle narrows the schedule to the range', () => {+ const player = createDrumPlayer(CHART, {});+ expect(player.schedule().bars).toHaveLength(2);+ player.setLoop({ from: 2, to: 2 });+ expect(player.schedule().bars.map((b) => b.index)).toEqual([2]);+ player.setLoop(null);+ expect(player.schedule().bars).toHaveLength(2);+ });++ it('setCountIn while idle prepends the lead-in', () => {+ const player = createDrumPlayer(CHART, {});+ expect(player.schedule().countInSec).toBe(0);+ player.setCountIn(2);+ expect(player.schedule().countInSec).toBeCloseTo(2, 5); // two 1s bars+ });++ it('an empty chart reports ended immediately and schedules nothing', async () => {+ const ended = vi.fn();+ const player = createDrumPlayer(parseDrumChart(''), { onEnded: ended });+ await player.play();+ expect(ended).toHaveBeenCalledTimes(1);+ expect(audio.oscillators).toHaveLength(0);+ expect(player.isPlaying()).toBe(false);+ });++ it('a loop range over an all-rest chart does not spin forever', async () => {+ // canLoop guards the rebase: a pass with no music would otherwise loop the+ // scheduler's rebase branch endlessly.+ const player = createDrumPlayer(parseDrumChart('subdivision: 1\n\nHH: x---'), {+ loopBars: { from: 1, to: 1 }, countInBars: 0,+ });+ await player.play();+ drive(2);+ expect(player.isPlaying()).toBe(true);+ player.stop();+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2479275475..616c63f9cc 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -90,6 +90,8 @@ export * from './canvasRoll.js';export * from './chiptunePlayback.js';export * from './chordShapes.js';export * from './colorMatch.js';+export * from './drumNotation.js';+export * from './drumPlayback.js';export * from './editorialChecks.js';export * from './editorialHealth.js';export * from './lookaheadTransport.js';diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsxindex 28ff21498d..3f3cce596d 100644--- a/client/src/pages/SongBookImport.jsx+++ b/client/src/pages/SongBookImport.jsx@@ -22,13 +22,16 @@ import toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';import TabPills from '../components/ui/TabPills';import TabSheetView from '../components/songbook/TabSheetView';+import DrumSheetView from '../components/songbook/DrumSheetView';import {- SONG_STAGES, INSTRUMENTS, inputClass, labelClass, btnClass,+ SONG_STAGES, INSTRUMENTS, DRUM_FORMAT, DRUM_INSTRUMENT,+ inputClass, labelClass, btnClass,} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';import useDrawerTab from '../hooks/useDrawerTab';import { createSong, importSongFromUrl } from '../services/api';import { normalizePastedTab, detectFormat, parseTabSheet } from '../lib/tabNotation.js';+import { isDrumNotation } from '../lib/drumNotation.js';import { readClipboard } from '../lib/clipboard.js';import { isUrl, normalizeUrl } from '../utils/urlNormalize';@@ -139,12 +142,18 @@ export default function SongBookImport() {useEffect(() => {applyMetaDefaults(activeMetaRef.current);}, [tab, applyMetaDefaults]);- // Memoized on its real inputs so detectFormat (a full line-classifier pass)- // doesn't re-run on every unrelated keystroke (title/artist/tags).- const contentFormat = useMemo(- () => (tab === 'url' && fetchedFormat) || detectFormat(contentText),- [tab, fetchedFormat, contentText],- );+ // Memoized on its real inputs so the classifier passes don't re-run on every+ // unrelated keystroke (title/artist/tags). `isDrumNotation` runs BEFORE+ // detectFormat: a grid row would otherwise classify as plain text (#3115). A+ // chosen Drums instrument also implies the kit grid, so the format follows the+ // instrument even for a chart the sniff can't recognize yet (e.g. mid-typing).+ const contentFormat = useMemo(() => {+ if (tab === 'url' && fetchedFormat) return fetchedFormat;+ if (isDrumNotation(contentText)) return DRUM_FORMAT;+ if (instrument === DRUM_INSTRUMENT) return DRUM_FORMAT;+ return detectFormat(contentText);+ }, [tab, fetchedFormat, contentText, instrument]);+ const previewIsDrum = contentFormat === DRUM_FORMAT;const [save, saving] = useAsyncAction(async () => {const name = title.trim();@@ -264,11 +273,15 @@ export default function SongBookImport() {<div className="mb-4"><div className="text-xs text-gray-400 mb-1">Preview</div><div className="bg-port-card border border-port-border rounded-lg p-3 max-h-[50vh] overflow-y-auto overflow-x-auto">- <TabSheetView- text={contentText}- format={contentFormat}- instrumentView={toVoicingInstrument(instrument)}- />+ {previewIsDrum ? (+ <DrumSheetView text={contentText} />+ ) : (+ <TabSheetView+ text={contentText}+ format={contentFormat}+ instrumentView={toVoicingInstrument(instrument)}+ />+ )}</div></div>)}diff --git a/client/src/pages/SongBookImport.test.jsx b/client/src/pages/SongBookImport.test.jsxindex f86e15fa9a..eb0da6f1ae 100644--- a/client/src/pages/SongBookImport.test.jsx+++ b/client/src/pages/SongBookImport.test.jsx@@ -107,6 +107,50 @@ describe('SongBookImport', () => {await waitFor(() => expect(title.value).toBe('Paste Song'));});+ describe('drum charts (#3115)', () => {+ // Invented groove (privacy convention).+ const DRUM_CHART = 'time: 4/4\ntempo: 96\nsubdivision: 2\n\nHH: x x x x x x x x\nS: - - - - o - - -\nK: o - - - - - o -';++ it('auto-detects a pasted drum chart and previews it on the kit grid', async () => {+ renderPage();+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: DRUM_CHART } });+ // isDrumNotation runs BEFORE detectFormat — a grid row would otherwise+ // classify as plain text.+ expect(await screen.findByText('drum')).toBeTruthy();+ expect(screen.getByLabelText('Drum bar 1')).toBeTruthy();+ expect(screen.getAllByText('Hi-Hat').length).toBeGreaterThan(0);+ });++ it('saves the drum format with the chart text', async () => {+ renderPage();+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: DRUM_CHART } });+ fireEvent.change(screen.getByLabelText('Instrument'), { target: { value: 'drums' } });+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Example Groove' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save song' }));+ await waitFor(() => expect(api.createSong).toHaveBeenCalled());+ const [body] = api.createSong.mock.calls[0];+ expect(body.instrument).toBe('drums');+ expect(body.content.format).toBe('drum');+ expect(body.content.text).toContain('HH: x x x x x x x x');+ });++ it('choosing the Drums instrument defaults the format to drum', async () => {+ renderPage();+ // Content the drum sniff would NOT recognize — the instrument decides.+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: 'K: o\nnot yet a grid' } });+ fireEvent.change(screen.getByLabelText('Instrument'), { target: { value: 'drums' } });+ expect(await screen.findByText('drum')).toBeTruthy();+ });++ it('leaves a chord sheet on its detected format with the tab preview', async () => {+ renderPage();+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: '[Verse]\nC G Am F\nInvented lyric line' } });+ expect(await screen.findByText('tab')).toBeTruthy();+ expect(screen.queryByLabelText(/^Drum bar/)).toBeNull();+ expect(screen.getByText('Verse')).toBeTruthy();+ });+ });+it('sends an in-range pasted capo through unchanged', async () => {renderPage();fireEvent.change(screen.getByLabelText('Pasted tab content'), {diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex f030c182d7..8e2c6e69d5 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -6,7 +6,8 @@* overflow-y-auto body the page owns (the autoscroll container).** Two URL-param-driven modes (linkable-routes convention):- * - PLAY (default): the rendered sheet (TabSheetView) with an+ * - PLAY (default): the rendered sheet (TabSheetView — or DrumSheetView plus a+ * drum transport bar when the content format is `drum`, #3115) with an* Ultimate-Guitar-style controls bar — autoscroll play/pause + speed,* transpose ± (render-time transposeText, never mutates stored text; offset* persisted per song via safeStorage), font size ±, an instrument-view@@ -20,7 +21,10 @@* defaults, so `{ content: { text } }` alone would reset format to 'tab'.** Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top.- * A screen wake lock holds while autoscroll plays (useWakeLock).+ * For a drum chart the same keys drive the kit transport instead: space+ * play/stop, +/- BPM ±1, [ ] set the loop ends at the current bar.+ * A screen wake lock holds while autoscroll plays — or while the kit plays+ * (useWakeLock).*/import { useState, useEffect, useMemo, useRef, useCallback } from 'react';@@ -36,8 +40,11 @@ import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';import TabPills from '../components/ui/TabPills';import TabSheetView from '../components/songbook/TabSheetView';+import DrumSheetView from '../components/songbook/DrumSheetView';+import DrumTransportBar from '../components/songbook/DrumTransportBar';import {- SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS,+ SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT,+ DRUM_INSTRUMENT, withStoredOption,inputClass, labelClass, btnClass, instrumentLabel,} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';@@ -45,6 +52,7 @@ import { useConfirmDelete } from '../hooks/useConfirmDelete';import useDrawerTab from '../hooks/useDrawerTab';import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';import useAutoscroll from '../hooks/useAutoscroll';+import useDrumPlayer from '../hooks/useDrumPlayer';import useWakeLock from '../hooks/useWakeLock';import { transposeText } from '../lib/tabNotation.js';import { VOICING_INSTRUMENTS, toVoicingInstrument } from '../lib/chordShapes.js';@@ -86,6 +94,13 @@ const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);// Instrument-view toggle tabs (chord-diagram rendering — never mutates the record).const VIEW_TABS = VOICING_INSTRUMENTS.map((viewId) => ({ id: viewId, label: instrumentLabel(viewId) }));+// Worked example in the editor's placeholder — the grid DSL is easier to copy+// than to describe. Invented groove (privacy convention).+const DRUM_PLACEHOLDER = [+ 'time: 4/4', 'tempo: 96', 'subdivision: 4', '',+ '# Bar 1 — basic rock beat', 'HH: x x x x x x x x', 'S: - - - - o - - -', 'K: o - - - - - o -',+].join('\n');+// 44px minimum touch targets on the controls bar (mobile-friendly).const ctrlBtnClass = 'flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50';@@ -187,14 +202,65 @@ export default function SongBookViewer() {// presence unknown (rendered as plain links; only an explicit present:false// gets the "not on this machine" pill), never a false "No attachments".const shownAttachments = attachments === 'failed' ? (song?.attachments || []) : (attachments || []);- useWakeLock(playing);++ // Keyed on the content STRING (not the song object) so unrelated record+ // updates (stage flips, attachment meta) don't re-run the transpose pass.+ const contentText = song?.content?.text || '';+ // A drum chart renders on the kit grid and plays back through the drum+ // transport; transpose and chord voicings are meaningless for it.+ const isDrum = (song?.content?.format || 'tab') === DRUM_FORMAT;+ const renderedText = useMemo(+ () => (transpose && !isDrum ? transposeText(contentText, transpose) : contentText),+ [contentText, transpose, isDrum],+ );++ // Edit-form selects carry whatever the DRAFT holds, even when this client's+ // enum doesn't list it (a song synced from a newer peer) — so a save preserves+ // the stored value instead of coercing it to the first option.+ const draftIsDrum = draft?.format === DRUM_FORMAT;+ const instrumentOptions = useMemo(() => withStoredOption(INSTRUMENTS, draft?.instrument), [draft?.instrument]);+ const formatOptions = useMemo(() => withStoredOption(SONG_FORMATS, draft?.format), [draft?.format]);++ // Picking the Drums instrument defaults the format to the kit grid (only while+ // the sheet is still empty — never re-formatting text the user already wrote).+ const onInstrumentChange = useCallback((instrument) => {+ setDraft((prev) => {+ if (!prev) return prev;+ const next = { ...prev, instrument };+ if (instrument === DRUM_INSTRUMENT && !prev.text.trim()) next.format = DRUM_FORMAT;+ return next;+ });+ }, []);++ // --- Drum play-along (kit synth, practice tempo, loop, playhead).+ // The hook is called unconditionally (hooks rule); it parses to zero bars for+ // a non-drum song, so it stands up no player and touches no audio.+ const drum = useDrumPlayer(isDrum ? contentText : '', { songId: id });++ // The wake lock holds while EITHER hands-free surface is running.+ useWakeLock(playing || drum.playing);++ // Leaving play mode (Edit) or unmounting must not leave the kit sounding — the+ // hook tears the player down on unmount, but a mode flip keeps it mounted.+ useEffect(() => { if (editing) drum.stop(); }, [editing, drum.stop]);const scrollToTop = useCallback(() => {stop();if (scrollRef.current) scrollRef.current.scrollTop = 0;}, [stop]);- useKeyboardShortcuts(!editing && !!song, {+ // 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.+ const drumShortcuts = {+ ' ': drum.toggle,+ '+': () => drum.setBpm(drum.bpm + 1),+ '=': () => drum.setBpm(drum.bpm + 1),+ '-': () => drum.setBpm(drum.bpm - 1),+ '[': () => { drum.setLoopEnabled(true); drum.setLoopRange(drum.currentBar, drum.loopTo); },+ ']': () => { drum.setLoopEnabled(true); drum.setLoopRange(drum.loopFrom, drum.currentBar); },+ '0': scrollToTop,+ };+ const sheetShortcuts = {' ': toggle,'+': () => setPxPerSec((v) => Math.min(SPEED_MAX, v + 5)),'=': () => setPxPerSec((v) => Math.min(SPEED_MAX, v + 5)),@@ -202,15 +268,8 @@ export default function SongBookViewer() {'[': () => setTranspose(transpose - 1),']': () => setTranspose(transpose + 1),'0': scrollToTop,- });-- // Keyed on the content STRING (not the song object) so unrelated record- // updates (stage flips, attachment meta) don't re-run the transpose pass.- const contentText = song?.content?.text || '';- const renderedText = useMemo(- () => (transpose ? transposeText(contentText, transpose) : contentText),- [contentText, transpose],- );+ };+ useKeyboardShortcuts(!editing && !!song, isDrum ? drumShortcuts : sheetShortcuts);// --- Mutationsconst onStageChange = useCallback((stage) => {@@ -406,8 +465,11 @@ export default function SongBookViewer() {</div><div><label htmlFor="song-edit-instrument" className={labelClass}>Instrument</label>- <select id="song-edit-instrument" value={draft.instrument} onChange={(e) => setDraft({ ...draft, instrument: e.target.value })} className={inputClass}>- {INSTRUMENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}+ {/* withStoredOption keeps a value this client doesn't know (a song+ synced from a newer peer) in the list, so saving round-trips it+ instead of silently coercing to the first option. */}+ <select id="song-edit-instrument" value={draft.instrument} onChange={(e) => onInstrumentChange(e.target.value)} className={inputClass}>+ {instrumentOptions.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}</select></div><div>@@ -460,7 +522,7 @@ export default function SongBookViewer() {onChange={(e) => setDraft({ ...draft, format: e.target.value })}className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:border-port-accent focus:outline-none">- {SONG_FORMATS.map((f) => <option key={f} value={f}>{f}</option>)}+ {formatOptions.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}</select></div></div>@@ -468,7 +530,7 @@ export default function SongBookViewer() {id="song-edit-text"value={draft.text}onChange={(e) => setDraft({ ...draft, text: e.target.value })}- placeholder={'[Verse 1]\nC G\nExample lyrics here…'}+ placeholder={draftIsDrum ? DRUM_PLACEHOLDER : '[Verse 1]\nC G\nExample lyrics here…'}spellCheck={false}className={`${inputClass} font-mono min-h-[280px] whitespace-pre`}/>@@ -476,12 +538,16 @@ export default function SongBookViewer() {<div><div className="text-xs text-gray-400 mb-1">Preview</div><div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">- <TabSheetView- text={draft.text}- format={draft.format}- fontSizeRem={fontSize}- instrumentView={toVoicingInstrument(draft.instrument)}- />+ {draftIsDrum ? (+ <DrumSheetView text={draft.text} fontSizeRem={fontSize} />+ ) : (+ <TabSheetView+ text={draft.text}+ format={draft.format}+ fontSizeRem={fontSize}+ instrumentView={toVoicingInstrument(draft.instrument)}+ />+ )}</div></div></div>@@ -489,6 +555,31 @@ export default function SongBookViewer() {) : (/* ============================== PLAY MODE ============================== */<>+ {/* Drum play-along transport — its own bar above the shared controls,+ so the kit's tempo/loop/click sit together rather than interleaved+ with the sheet controls. */}+ {isDrum && (+ <DrumTransportBar+ playing={drum.playing}+ onToggle={drum.toggle}+ hasMusic={drum.hasMusic}+ bpm={drum.bpm}+ onBpmChange={drum.setBpm}+ onPercent={drum.setBpmPercent}+ writtenTempo={drum.writtenTempo}+ countInBars={drum.countInBars}+ onCountInChange={drum.setCountInBars}+ loopEnabled={drum.loopEnabled}+ onLoopToggle={drum.setLoopEnabled}+ loopFrom={drum.loopFrom}+ loopTo={drum.loopTo}+ onLoopRangeChange={drum.setLoopRange}+ barCount={drum.barCount}+ clickEnabled={drum.clickEnabled}+ onClickToggle={drum.setClickEnabled}+ />+ )}+<div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">{/* Autoscroll */}<div className="flex items-center gap-2">@@ -514,18 +605,20 @@ export default function SongBookViewer() {/></div>- {/* Transpose */}- <div className="flex items-center gap-1" role="group" aria-label="Transpose">- <button type="button" onClick={() => setTranspose(transpose - 1)} className={ctrlBtnClass} aria-label="Transpose down" title="Transpose down ([)">- <Minus size={16} />- </button>- <span className="min-w-[3.5rem] text-center text-sm text-gray-300 font-mono" title="Transpose (semitones)">- {transpose > 0 ? `+${transpose}` : transpose}- </span>- <button type="button" onClick={() => setTranspose(transpose + 1)} className={ctrlBtnClass} aria-label="Transpose up" title="Transpose up (])">- <Plus size={16} />- </button>- </div>+ {/* Transpose — meaningless on a kit grid, so hidden for drum charts */}+ {!isDrum && (+ <div className="flex items-center gap-1" role="group" aria-label="Transpose">+ <button type="button" onClick={() => setTranspose(transpose - 1)} className={ctrlBtnClass} aria-label="Transpose down" title="Transpose down ([)">+ <Minus size={16} />+ </button>+ <span className="min-w-[3.5rem] text-center text-sm text-gray-300 font-mono" title="Transpose (semitones)">+ {transpose > 0 ? `+${transpose}` : transpose}+ </span>+ <button type="button" onClick={() => setTranspose(transpose + 1)} className={ctrlBtnClass} aria-label="Transpose up" title="Transpose up (])">+ <Plus size={16} />+ </button>+ </div>+ )}{/* Font size */}<div className="flex items-center gap-1" role="group" aria-label="Font size">@@ -537,17 +630,20 @@ export default function SongBookViewer() {</button></div>- {/* Instrument view (chord diagrams) — render-only, URL-backed */}- <TabPills- variant="pills"- size="sm"- tabs={VIEW_TABS}- activeTab={instrumentView}- onChange={setInstrumentView}- ariaLabel="Instrument view"- mobileDropdown- mobileSelectId="song-instrument-view"- />+ {/* Instrument view (chord diagrams) — render-only, URL-backed. A drum+ chart has no chords to voice, so the picker hides. */}+ {!isDrum && (+ <TabPills+ variant="pills"+ size="sm"+ tabs={VIEW_TABS}+ activeTab={instrumentView}+ onChange={setInstrumentView}+ ariaLabel="Instrument view"+ mobileDropdown+ mobileSelectId="song-instrument-view"+ />+ )}{/* Stage */}<div>@@ -582,7 +678,14 @@ export default function SongBookViewer() {</div><div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">- {song.content?.text ? (+ {song.content?.text && isDrum ? (+ <DrumSheetView+ text={contentText}+ fontSizeRem={fontSize}+ activeStep={drum.activeStep}+ className="max-w-4xl"+ />+ ) : song.content?.text ? (<TabSheetViewtext={renderedText}format={song?.content?.format || 'tab'}diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 44b50a9fa4..2bc233d95c 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -186,6 +186,152 @@ E|--3-----|`;});});+ describe('drum charts (#3115)', () => {+ // Invented groove (privacy convention).+ const DRUM_CHART = `time: 4/4+tempo: 96+subdivision: 2++# Groove x2+HH: x x x x x x x x+S: - - - - o - - -+K: o - - - - - o -`;++ const drumSong = (extra = {}) => song({+ instrument: 'drums',+ content: { format: 'drum', text: DRUM_CHART },+ ...extra,+ });++ it('renders the kit sheet and the drum transport instead of the tab sheet', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ expect(await screen.findByText('Example Song')).toBeTruthy();+ // The kit sheet drew (labelled rows, per-bar svg).+ expect(screen.getByLabelText('Drum bar 1: Groove')).toBeTruthy();+ // One row label per bar that uses the piece (the block repeats x2).+ expect(screen.getAllByText('Hi-Hat').length).toBeGreaterThan(0);+ // Transport controls are present.+ expect(screen.getByLabelText('Play along')).toBeTruthy();+ expect(screen.getByLabelText('Practice tempo')).toBeTruthy();+ expect(screen.getByLabelText('Enable loop')).toBeTruthy();+ expect(screen.getByLabelText('Turn the click on')).toBeTruthy();+ });++ it('hides transpose and the chord instrument-view picker for a drum chart', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ expect(await screen.findByLabelText('Play along')).toBeTruthy();+ expect(screen.queryByLabelText('Transpose up')).toBeNull();+ expect(screen.queryByLabelText('Transpose down')).toBeNull();+ expect(screen.queryByRole('combobox', { name: 'Instrument view' })).toBeNull();+ // Autoscroll stays available.+ expect(screen.getByLabelText('Autoscroll speed')).toBeTruthy();+ });++ it('seeds BPM from the chart tempo and persists an edit per song (never the record)', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ await screen.findByLabelText('BPM');+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('96'));+ fireEvent.change(screen.getByLabelText('BPM'), { target: { value: '72' } });+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('72'));+ expect(globalThis.localStorage.getItem('songbook:drumBpm:abc')).toBe('72');+ // A practice tempo is a per-machine preference — never a record write.+ expect(api.updateSong).not.toHaveBeenCalled();+ });++ it('restores the stored BPM on reload instead of the written tempo', async () => {+ globalThis.localStorage.setItem('songbook:drumBpm:abc', '60');+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ await screen.findByLabelText('BPM');+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('60'));+ });++ it('recomputes BPM from a percent-of-written button', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ expect(await screen.findByLabelText('BPM')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: '50%' }));+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('48'));+ fireEvent.click(screen.getByRole('button', { name: '100%' }));+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('96'));+ });++ it('clamps a BPM outside the metronome band', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ const bpm = await screen.findByLabelText('BPM');+ fireEvent.change(bpm, { target: { value: '9999' } });+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('320'));+ fireEvent.change(screen.getByLabelText('BPM'), { target: { value: '1' } });+ await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('20'));+ });++ it('disables Play for an all-rest chart (bars parse, nothing sounds)', async () => {+ api.getSong.mockResolvedValue(drumSong({ content: { format: 'drum', text: 'HH: ----\nK: ----' } }));+ renderPage();+ const play = await screen.findByLabelText('Play along');+ expect(play.disabled).toBe(true);+ });++ it('reveals the loop bar range only when looping is on', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage();+ expect(await screen.findByLabelText('Enable loop')).toBeTruthy();+ expect(screen.queryByLabelText('Loop from bar')).toBeNull();+ fireEvent.click(screen.getByLabelText('Enable loop'));+ const from = await screen.findByLabelText('Loop from bar');+ // The repeated block expands to two real bars, so both are selectable.+ expect(from.querySelectorAll('option')).toHaveLength(2);+ expect(screen.getByLabelText('Loop to bar').value).toBe('2');+ });++ it('previews the kit sheet in edit mode and defaults Drums to the drum format', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage('/songbook/abc?mode=edit');+ expect(await screen.findByLabelText('Title')).toBeTruthy();+ expect(screen.getByLabelText('Format').value).toBe('drum');+ expect(screen.getByLabelText('Drum bar 1: Groove')).toBeTruthy();+ });++ it('keeps an unknown stored instrument/format selectable and preserves it on save', async () => {+ // A song synced from a NEWER peer carrying values this client doesn't list.+ api.getSong.mockResolvedValue(song({+ instrument: 'hurdy-gurdy',+ content: { format: 'futureformat', text: 'anything' },+ }));+ api.updateSong.mockImplementation((sid, patch) => Promise.resolve(song({ ...patch })));+ renderPage('/songbook/abc?mode=edit');+ const instrument = await screen.findByLabelText('Instrument');+ expect(instrument.value).toBe('hurdy-gurdy');+ expect(screen.getByLabelText('Format').value).toBe('futureformat');+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());+ const [, patch] = api.updateSong.mock.calls[0];+ expect(patch.instrument).toBe('hurdy-gurdy');+ expect(patch.content.format).toBe('futureformat');+ });++ it('switching a blank song to Drums defaults its format to drum', async () => {+ api.getSong.mockResolvedValue(song({ instrument: 'guitar', content: { format: 'tab', text: '' } }));+ renderPage('/songbook/abc?mode=edit');+ const instrument = await screen.findByLabelText('Instrument');+ fireEvent.change(instrument, { target: { value: 'drums' } });+ await waitFor(() => expect(screen.getByLabelText('Format').value).toBe('drum'));+ });++ it('does NOT re-format a song that already has sheet text', async () => {+ api.getSong.mockResolvedValue(song());+ renderPage('/songbook/abc?mode=edit');+ const instrument = await screen.findByLabelText('Instrument');+ fireEvent.change(instrument, { target: { value: 'drums' } });+ await waitFor(() => expect(screen.getByLabelText('Instrument').value).toBe('drums'));+ expect(screen.getByLabelText('Format').value).toBe('tab');+ });+ });+it('renders the edit form in ?mode=edit and saves the whole content object', async () => {api.updateSong.mockImplementation((id, patch) => Promise.resolve(song({ ...patch })));renderPage('/songbook/abc?mode=edit');diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 910806868b..94b4739008 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -21,11 +21,18 @@ export const createFakeAudio = ({ suspended = false } = {}) => {now: 0,oscillators: [],gains: [],- // Modules cache the shared AudioContext (lib/audioContext.js) across a- // test file, so create ONE pair per file and reset the recorders per- // test — a fresh pair mid-file would record into an object the cached- // context no longer points at.- reset() { this.now = 0; this.oscillators.length = 0; this.gains.length = 0; resolveResume = null; },+ // Bandpassed noise voices (createBufferSource + createBiquadFilter) — the+ // percussion synth in drumPlayback.js. `oscillators` records buffer sources+ // too (they satisfy the same start/stop/onended surface the transport tracks),+ // so a caller that only cares "how many voices sounded" reads that one list.+ filters: [],+ reset() {+ this.now = 0;+ this.oscillators.length = 0;+ this.gains.length = 0;+ this.filters.length = 0;+ resolveResume = null;+ },// Resolve a suspended context's pending resume() so play()'s await continues.flushResume() { const r = resolveResume; resolveResume = null; if (r) r(); },};@@ -54,10 +61,31 @@ export const createFakeAudio = ({ suspended = false } = {}) => {return osc;},createGain() {- const gain = { gain: fakeParam(), connect: (t) => t };+ const gain = { gain: fakeParam(), connect: (t) => t, disconnect() {} };audio.gains.push(gain);return gain;},+ // --- Noise-voice nodes (percussion synth) ------------------------------+ createBuffer(channels, length, sampleRate) {+ const data = new Float32Array(length);+ return { sampleRate, length, numberOfChannels: channels, getChannelData: () => data };+ },+ createBufferSource() {+ const src = {+ buffer: null, loop: false, playbackRate: { value: 1 },+ onended: null, started: null, stopped: null, noise: true,+ connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; },+ };+ // Recorded alongside oscillators: the transport tracks both the same way.+ audio.oscillators.push(src);+ return src;+ },+ createBiquadFilter() {+ const filter = { type: '', frequency: fakeParam(), Q: { value: 1 }, connect: (t) => t };+ audio.filters.push(filter);+ return filter;+ },+ sampleRate: 48000,};}return { FakeAudioContext, audio };diff --git a/data.reference/brain/songs.json b/data.reference/brain/songs.jsonindex a48ce70be8..3b1661d06c 100644--- a/data.reference/brain/songs.json+++ b/data.reference/brain/songs.json@@ -71,6 +71,30 @@"createdAt": "2026-07-15T00:00:00.000Z","updatedAt": "2026-07-15T00:00:00.000Z","originInstanceId": "seed"+ },+ "song-seed-example-rock-beat": {+ "title": "Example Rock Beat",+ "artist": "The Placeholders",+ "instrument": "drums",+ "stage": "new",+ "tags": [+ "drums",+ "groove",+ "example"+ ],+ "key": "",+ "capo": 0,+ "tuning": "",+ "sourceUrl": "",+ "content": {+ "format": "drum",+ "text": "time: 4/4\ntempo: 96\nsubdivision: 2\n\n# Basic rock beat x2\nHH: x x x x x x x x\nS: - - - - o - - -\nK: o - - - - - o -\n\n# Open hats and a ghost\nHH: x - o - x - o -\nS: - - - - o - - g\nK: o - - o - - o -\n\n# Fill down the toms\nS: x - x - X - - -\nT1: - - - - - x - -\nT2: - - - - - - x -\nFT: - - - - - - - x\nK: o - - - o - - -\n\n# Crash and out\nCR: X - - - - - - -\nK: o - - - - - - -"+ },+ "notes": "Worked example of the PortOS drum-grid format: two bars of a basic rock beat, a bar with open hi-hats and a ghost snare, a fill down the toms, and a crash. Practice it slower with the BPM control, then loop the fill bar.",+ "attachments": [],+ "createdAt": "2026-07-26T00:00:00.000Z",+ "updatedAt": "2026-07-26T00:00:00.000Z",+ "originInstanceId": "seed"}}}diff --git a/scripts/migrations/190-seed-songbook-songs.test.js b/scripts/migrations/190-seed-songbook-songs.test.jsindex 8fc5e8d83f..9789563b30 100644--- a/scripts/migrations/190-seed-songbook-songs.test.js+++ b/scripts/migrations/190-seed-songbook-songs.test.js@@ -110,11 +110,14 @@ describe('migration 190 — seed songbook songs', () => {});it('seeds the SHIPPED reference records against a real repo layout shape', async () => {- // Sanity-pin the shipped seed file: three instrument variants of the same- // public-domain song, stable ids, and a FIXED originInstanceId sentinel.+ // Sanity-pin the seeds THIS migration ships: three instrument variants of the+ // same public-domain song, stable ids, and a FIXED originInstanceId sentinel.+ // Later migrations add their own seed records to the same file (e.g. 209's+ // drum example), so this scopes to its own ids rather than the whole file —+ // and each new seed pins its own shape in its own migration's test.const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));- const ids = Object.keys(shipped.records);- expect(ids.sort()).toEqual(['song-seed-hotrs-guitar', 'song-seed-hotrs-piano', 'song-seed-hotrs-ukulele']);+ const ids = Object.keys(shipped.records).filter((id) => id.startsWith('song-seed-hotrs-')).sort();+ expect(ids).toEqual(['song-seed-hotrs-guitar', 'song-seed-hotrs-piano', 'song-seed-hotrs-ukulele']);for (const id of ids) {const rec = shipped.records[id];expect(rec.title).toBe('House of the Rising Sun');diff --git a/scripts/migrations/209-seed-drum-example-song.js b/scripts/migrations/209-seed-drum-example-song.jsnew file mode 100644index 0000000000..a3b2c8530a--- /dev/null+++ b/scripts/migrations/209-seed-drum-example-song.js@@ -0,0 +1,121 @@+/**+ * Migration 209 — seed the SongBook drum example groove into existing installs.+ *+ * The `drums` instrument / `drum` content format (#3115) ships one invented+ * example chart ("Example Rock Beat" by The Placeholders) in+ * data.reference/brain/songs.json — it doubles as the format's worked example,+ * so a drummer opening `/songbook` on an upgraded install has something to read,+ * play along with, and copy from. Fresh installs get it because+ * scripts/setup-data.js copies data.reference wholesale, but setup-data only+ * copies MISSING files, so every existing install would never receive it.+ *+ * Since migration 200, brain stores live per-record at+ * `data/brain/<type>/<id>/index.json` (collectionStore layout) rather than in a+ * monolithic `data/brain/<type>.json` — so unlike migration 190 (the pre-split+ * SongBook seed), this writes one record directory. The legacy monolithic file is+ * ALSO topped up when it's still present, so an install that hasn't run 200 yet+ * (migrations apply in filename order, but a repaired/pending 200 can lag) still+ * picks the seed up when its split finally runs.+ *+ * Idempotent and non-destructive: an id already present — a user-edited copy, a+ * peer-synced copy, or a tombstone from a deliberate delete — is NEVER+ * overwritten, so a deleted seed stays deleted. Nothing is written when the+ * existing record (or the legacy file) is unreadable: possibly-recoverable user+ * data beats a cosmetic starter chart. The seed carries a fixed+ * originInstanceId ('seed') so every install holds a byte-identical record and+ * the brain reconcile checksum still converges across peers.+ */++import { readFile, writeFile, mkdir, access } from 'fs/promises';+import { join, dirname } from 'path';++// Only THIS seed id — a later seed addition gets its own migration rather than+// silently riding along on a re-run of this one.+const SEED_IDS = ['song-seed-example-rock-beat'];++// Tagged read: 'missing' (ENOENT — nothing there, safe to create) is NOT the+// same as 'invalid' (exists but won't parse — user data a write would destroy).+// The migration runner executes before the service layer is wired, so no+// server/lib imports here.+async function readJsonTagged(path) {+ let raw;+ try {+ raw = await readFile(path, 'utf-8');+ } catch (err) {+ return err?.code === 'ENOENT' ? { state: 'missing' } : { state: 'invalid', error: err?.message };+ }+ try {+ return { state: 'ok', doc: JSON.parse(raw) };+ } catch (err) {+ return { state: 'invalid', error: err?.message };+ }+}++const exists = async (path) => access(path).then(() => true, () => false);++export async function up({ rootDir }) {+ const seedPath = join(rootDir, 'data.reference', 'brain', 'songs.json');+ const perRecordDir = join(rootDir, 'data', 'brain', 'songs');+ const legacyPath = join(rootDir, 'data', 'brain', 'songs.json');++ const seedRead = await readJsonTagged(seedPath);+ const seedRecords = seedRead.state === 'ok' && seedRead.doc?.records && typeof seedRead.doc.records === 'object'+ ? seedRead.doc.records+ : {};+ const present = SEED_IDS.filter((id) => seedRecords[id] !== undefined);+ if (present.length === 0) {+ console.log('🥁 drum-seed: no drum seed record in data.reference — no-op.');+ return { ok: true, reason: 'no-seeds' };+ }++ // --- Per-record store (the post-migration-200 layout) ---------------------+ let added = 0;+ let skipped = 0;+ for (const id of present) {+ const recordPath = join(perRecordDir, id, 'index.json');+ const read = await readJsonTagged(recordPath);+ if (read.state !== 'missing') {+ // Present (a user-edited copy / peer copy / tombstone) or unreadable —+ // either way, leave it alone.+ if (read.state === 'invalid') {+ console.error(`❌ drum-seed: ${id}/index.json is unreadable (${read.error}) — leaving it untouched.`);+ }+ skipped += 1;+ continue;+ }+ await mkdir(dirname(recordPath), { recursive: true });+ await writeFile(recordPath, JSON.stringify(seedRecords[id], null, 2) + '\n');+ added += 1;+ }++ // --- Legacy monolithic file (only when it still exists) -------------------+ // An install whose migration-200 split hasn't run yet still reads+ // data/brain/songs.json, so top that up too. We never CREATE the legacy file —+ // doing so on a split install would resurrect a shape nothing reads.+ let legacyAdded = 0;+ if (await exists(legacyPath)) {+ const legacyRead = await readJsonTagged(legacyPath);+ if (legacyRead.state === 'invalid') {+ console.error(`❌ drum-seed: data/brain/songs.json exists but is unreadable (${legacyRead.error}) — leaving it untouched.`);+ } else {+ const live = legacyRead.doc && typeof legacyRead.doc === 'object' ? legacyRead.doc : {};+ if (!live.records || typeof live.records !== 'object') live.records = {};+ for (const id of present) {+ if (live.records[id] !== undefined) continue;+ live.records[id] = seedRecords[id];+ legacyAdded += 1;+ }+ if (legacyAdded > 0) await writeFile(legacyPath, JSON.stringify(live, null, 2) + '\n');+ }+ }++ if (added === 0 && legacyAdded === 0) {+ console.log('🥁 drum-seed: drum example already present — no-op.');+ return { ok: true, reason: 'already-present', added: 0, legacyAdded: 0, skipped };+ }++ console.log(`🥁 drum-seed: added the drum example groove (${added} per-record, ${legacyAdded} legacy) to the SongBook.`);+ return { ok: true, reason: 'seeded', added, legacyAdded, skipped };+}++export default { up };diff --git a/scripts/migrations/209-seed-drum-example-song.test.js b/scripts/migrations/209-seed-drum-example-song.test.jsnew file mode 100644index 0000000000..7d6503eaa9--- /dev/null+++ b/scripts/migrations/209-seed-drum-example-song.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './209-seed-drum-example-song.js';+import { parseDrumChart } from '../../client/src/lib/drumNotation.js';++const SEED_ID = 'song-seed-example-rock-beat';++let rootDir;+let seedDir;+let perRecordDir;+let legacyPath;++beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-209-'));+ seedDir = join(rootDir, 'data.reference', 'brain');+ perRecordDir = join(rootDir, 'data', 'brain', 'songs');+ legacyPath = join(rootDir, 'data', 'brain', 'songs.json');+ mkdirSync(seedDir, { recursive: true });+});++afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+});++// Invented seed fixture (privacy convention) — mirrors the shipped shape.+const SEEDS = {+ records: {+ [SEED_ID]: {+ title: 'Example Rock Beat',+ artist: 'The Placeholders',+ instrument: 'drums',+ content: { format: 'drum', text: 'HH: xxxx\nK: o---' },+ attachments: [],+ createdAt: '2026-07-26T00:00:00.000Z',+ updatedAt: '2026-07-26T00:00:00.000Z',+ originInstanceId: 'seed',+ },+ // An unrelated seed the migration must NOT touch (it owns one id only).+ 'song-seed-other': { title: 'Other Seed', attachments: [] },+ },+};++const writeSeed = (obj = SEEDS) => writeFileSync(join(seedDir, 'songs.json'), JSON.stringify(obj, null, 2));+const recordPath = (id = SEED_ID) => join(perRecordDir, id, 'index.json');+const writeRecord = (obj, id = SEED_ID) => {+ mkdirSync(join(perRecordDir, id), { recursive: true });+ writeFileSync(recordPath(id), JSON.stringify(obj, null, 2));+};+const readRecord = (id = SEED_ID) => JSON.parse(readFileSync(recordPath(id), 'utf-8'));+const writeLegacy = (obj) => {+ mkdirSync(join(rootDir, 'data', 'brain'), { recursive: true });+ writeFileSync(legacyPath, JSON.stringify(obj, null, 2));+};+const readLegacy = () => JSON.parse(readFileSync(legacyPath, 'utf-8'));++describe('migration 209 — seed the drum example song', () => {+ it('writes the per-record file (with parent dirs) on a split install', async () => {+ writeSeed();+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ ok: true, reason: 'seeded', added: 1, legacyAdded: 0 });+ expect(readRecord().title).toBe('Example Rock Beat');+ expect(readRecord().instrument).toBe('drums');+ // It owns exactly one id — the other seed is another migration's business.+ expect(existsSync(recordPath('song-seed-other'))).toBe(false);+ });++ it('never overwrites an existing id — an edited copy survives', async () => {+ writeSeed();+ writeRecord({ title: 'My Customized Groove', updatedAt: '2026-08-01T00:00:00.000Z' });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ expect(readRecord().title).toBe('My Customized Groove');+ });++ it('never resurrects a tombstoned (deliberately deleted) seed', async () => {+ writeSeed();+ writeRecord({ _deleted: true, updatedAt: '2026-08-01T00:00:00.000Z', deletedAt: '2026-08-01T00:00:00.000Z', originInstanceId: 'x' });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ expect(readRecord()._deleted).toBe(true);+ });++ it('is idempotent — a second run adds nothing', async () => {+ writeSeed();+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second).toMatchObject({ reason: 'already-present', added: 0 });+ });++ it('tops up a still-present legacy monolithic file too', async () => {+ writeSeed();+ writeLegacy({ records: { 'user-song-1': { title: 'User Song' } } });+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ added: 1, legacyAdded: 1 });+ const live = readLegacy();+ expect(live.records[SEED_ID].title).toBe('Example Rock Beat');+ expect(live.records['user-song-1'].title).toBe('User Song');+ expect(live.records['song-seed-other']).toBeUndefined();+ });++ it('never CREATES a legacy file on a split install', async () => {+ writeSeed();+ await migration.up({ rootDir });+ expect(existsSync(legacyPath)).toBe(false);+ });++ it('leaves an existing legacy id alone', async () => {+ writeSeed();+ writeLegacy({ records: { [SEED_ID]: { title: 'Kept' } } });+ const result = await migration.up({ rootDir });+ expect(result.legacyAdded).toBe(0);+ expect(readLegacy().records[SEED_ID].title).toBe('Kept');+ });++ it('NEVER writes over an unreadable record or legacy file', async () => {+ writeSeed();+ mkdirSync(join(perRecordDir, SEED_ID), { recursive: true });+ writeFileSync(recordPath(), '{not json');+ writeLegacy({ records: {} });+ writeFileSync(legacyPath, '{also not json');+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ // Both corrupt files are byte-for-byte untouched (recoverable by the user).+ expect(readFileSync(recordPath(), 'utf-8')).toBe('{not json');+ expect(readFileSync(legacyPath, 'utf-8')).toBe('{also not json');+ });++ it('no-ops when the seed file is missing or lacks the drum record', async () => {+ const missing = await migration.up({ rootDir });+ expect(missing).toMatchObject({ ok: true, reason: 'no-seeds' });+ expect(existsSync(recordPath())).toBe(false);++ writeSeed({ records: { 'song-seed-other': { title: 'Other' } } });+ expect(await migration.up({ rootDir })).toMatchObject({ reason: 'no-seeds' });+ });++ it('ships a parseable drum chart in the real reference file', async () => {+ const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));+ const rec = shipped.records[SEED_ID];+ expect(rec).toBeDefined();+ expect(rec.title).toBe('Example Rock Beat');+ expect(rec.artist).toBe('The Placeholders');+ expect(rec.instrument).toBe('drums');+ expect(rec.content.format).toBe('drum');+ expect(rec.attachments).toEqual([]);+ // A fixed originInstanceId keeps the record byte-identical on every install,+ // so the brain reconcile checksum converges (see migration 190's note).+ expect(rec.originInstanceId).toBe('seed');+ // The worked example must actually parse clean — a seed with errors would+ // teach the format wrong.+ const chart = parseDrumChart(rec.content.text);+ expect(chart.errors).toEqual([]);+ expect(chart.bars.length).toBeGreaterThan(1);+ expect(chart.pieces).toContain('K');+ expect(chart.pieces).toContain('S');+ expect(chart.pieces).toContain('HH');+ expect(chart.tempo).toBeGreaterThan(0);+ // …and it must exercise the repeat + glyph range it's demonstrating.+ expect(chart.bars.some((b) => b.repeat > 1)).toBe(true);+ const glyphs = new Set(chart.bars.flatMap((b) => b.rows.flatMap((r) => r.cells.map((c) => c.id))));+ for (const id of ['normal', 'accent', 'open', 'ghost', 'rest']) expect(glyphs).toContain(id);+ });+});diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex ae6065efd5..9ac01f4cff 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -567,11 +567,15 @@ export const brainDigestRunSchema = z.object({// Learning stage for a repertoire songexport const songStageEnum = z.enum(['new', 'learning', 'learned', 'memorized']);-// Instrument the sheet is written for-export const songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other']);--// Content notation format (drives the client-side parser/renderer)-export const songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain']);+// Instrument the sheet is written for. ADDITIVE only — brain records sync raw+// (LWW, no Zod re-validation on receive), so an older peer already stores an+// unknown instrument fine; removing a value would 400 an edit of a synced song.+export const songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass', 'voice', 'drums', 'other']);++// Content notation format (drives the client-side parser/renderer). `drum` is+// the kit-grid DSL parsed by client/src/lib/drumNotation.js and drawn by+// <DrumSheetView> — everything else goes through tabNotation/<TabSheetView>.+export const songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain', 'drum']);// Nested content object — named so the update schema below can rebuild it// defaults-free (partialWithoutDefaults only strips TOP-LEVEL field defaults).diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex f021a5a875..dd9f972169 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -36,7 +36,10 @@ import {bucketReorderSchema,brainSyncQuerySchema,brainSyncPushSchema,- memoryInputSchema+ memoryInputSchema,+ songInputSchema,+ songInstrumentEnum,+ songContentFormatEnum} from './brainValidation.js';describe('brainValidation.js', () => {@@ -774,4 +777,41 @@ describe('brainValidation.js', () => {expect(result.success).toBe(false);});});++ describe('songbook enums', () => {+ // The client mirrors both lists in client/src/components/songbook/constants.js+ // (INSTRUMENTS / SONG_FORMATS) — keep them in lockstep.+ it('accepts every shipped instrument, including drums (#3115)', () => {+ for (const instrument of ['guitar', 'piano', 'ukulele', 'bass', 'voice', 'drums', 'other']) {+ expect(songInstrumentEnum.safeParse(instrument).success, instrument).toBe(true);+ }+ expect(songInstrumentEnum.safeParse('hurdy-gurdy').success).toBe(false);+ });++ it('accepts every shipped content format, including drum (#3115)', () => {+ for (const format of ['chordpro', 'tab', 'plain', 'drum']) {+ expect(songContentFormatEnum.safeParse(format).success, format).toBe(true);+ }+ expect(songContentFormatEnum.safeParse('futureformat').success).toBe(false);+ });++ it('round-trips a drum song through songInputSchema', () => {+ const result = songInputSchema.safeParse({+ title: 'Example Rock Beat',+ artist: 'The Placeholders',+ instrument: 'drums',+ content: { format: 'drum', text: 'HH: xxxx\nK: o---' },+ });+ expect(result.success).toBe(true);+ expect(result.data.instrument).toBe('drums');+ expect(result.data.content.format).toBe('drum');+ });++ it('still defaults to guitar/tab when neither is supplied', () => {+ const result = songInputSchema.safeParse({ title: 'Untitled' });+ expect(result.success).toBe(true);+ expect(result.data.instrument).toBe('guitar');+ expect(result.data.content).toEqual({ format: 'tab', text: '' });+ });+ });});