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
fix: harden drum preview playback lifecycle (#3222)
[._.]/ Adam Eivy0c4083f7c286
diff --git a/client/src/components/songbook/DrumPreview.jsx b/client/src/components/songbook/DrumPreview.jsxindex fa69c103ae..551b95ad10 100644--- a/client/src/components/songbook/DrumPreview.jsx+++ b/client/src/components/songbook/DrumPreview.jsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useMemo, useState } from 'react';import useDrumPlayer from '../../hooks/useDrumPlayer.js';+import useWakeLock from '../../hooks/useWakeLock.js';import { chartHasMusic, parseDrumChart } from '../../lib/drumNotation.js';import DrumSheetView from './DrumSheetView.jsx';import DrumTransportBar from './DrumTransportBar.jsx';@@ -17,12 +18,39 @@ export default function DrumPreview({songId,fontSizeRem,sheetClassName = '',+ settingsMirror,}) {const [snapshot, setSnapshot] = useState(text);const [playAfterReload, setPlayAfterReload] = useState(false);const player = useDrumPlayer(snapshot, { songId });const chartChanged = text !== snapshot;const liveHasMusic = useMemo(() => chartHasMusic(parseDrumChart(text)), [text]);+ useWakeLock(player.playing);++ const setBpm = useCallback((next) => {+ player.setBpm(next);+ settingsMirror?.setBpm(next);+ }, [player.setBpm, settingsMirror]);+ const setBpmPercent = useCallback((percent) => {+ player.setBpmPercent(percent);+ settingsMirror?.setBpm(Math.round((player.writtenTempo * percent) / 100));+ }, [player.setBpmPercent, player.writtenTempo, settingsMirror]);+ const setCountInBars = useCallback((next) => {+ player.setCountInBars(next);+ settingsMirror?.setCountInBars(next);+ }, [player.setCountInBars, settingsMirror]);+ const setLoopEnabled = useCallback((enabled) => {+ player.setLoopEnabled(enabled);+ settingsMirror?.setLoopEnabled(enabled);+ }, [player.setLoopEnabled, settingsMirror]);+ const setLoopRange = useCallback((from, to) => {+ player.setLoopRange(from, to);+ settingsMirror?.setLoopRange(from, to);+ }, [player.setLoopRange, settingsMirror]);+ const setClickEnabled = useCallback((enabled) => {+ player.setClickEnabled(enabled);+ settingsMirror?.setClickEnabled(enabled);+ }, [player.setClickEnabled, settingsMirror]);const toggle = useCallback(() => {if (player.playing) {@@ -38,35 +66,36 @@ export default function DrumPreview({}, [player.playing, player.toggle, snapshot, text]);// A snapshot update rebuilds the idle player. Start only after that render so- // toggle() cannot accidentally launch the stale chart from the click render.+ // toggle() cannot launch the stale chart or run before its tempo seed lands.useEffect(() => {- if (!playAfterReload || snapshot !== text) return;+ if (!playAfterReload || snapshot !== text || !player.chartSettingsReady) return;setPlayAfterReload(false);player.toggle();- }, [playAfterReload, player.toggle, snapshot, text]);+ }, [playAfterReload, player.chartSettingsReady, player.toggle, snapshot, text]);const displayedText = player.playing ? snapshot : text;return (<div className="min-w-0">+ {/* A sounding snapshot must keep Stop enabled even if the live draft is silent. */}<DrumTransportBarplaying={player.playing}onToggle={toggle}- hasMusic={chartChanged ? liveHasMusic : player.hasMusic}+ hasMusic={player.playing || (chartChanged ? liveHasMusic : player.hasMusic)}bpm={player.bpm}- onBpmChange={player.setBpm}- onPercent={player.setBpmPercent}+ onBpmChange={setBpm}+ onPercent={setBpmPercent}writtenTempo={player.writtenTempo}countInBars={player.countInBars}- onCountInChange={player.setCountInBars}+ onCountInChange={setCountInBars}loopEnabled={player.loopEnabled}- onLoopToggle={player.setLoopEnabled}+ onLoopToggle={setLoopEnabled}loopFrom={player.loopFrom}loopTo={player.loopTo}- onLoopRangeChange={player.setLoopRange}+ onLoopRangeChange={setLoopRange}barCount={player.barCount}clickEnabled={player.clickEnabled}- onClickToggle={player.setClickEnabled}+ onClickToggle={setClickEnabled}beatsPerBar={player.beatsPerBar}pulse={player.pulse}currentBar={player.currentBar}diff --git a/client/src/components/songbook/DrumPreview.test.jsx b/client/src/components/songbook/DrumPreview.test.jsxindex 7a682f83c6..6e3efc420b 100644--- a/client/src/components/songbook/DrumPreview.test.jsx+++ b/client/src/components/songbook/DrumPreview.test.jsx@@ -6,6 +6,7 @@ const mockPlayer = vi.hoisted(() => ({toggle: vi.fn(),stop: vi.fn(),hasMusic: true,+ chartSettingsReady: true,bpm: 96,setBpm: vi.fn(),setBpmPercent: vi.fn(),@@ -27,7 +28,9 @@ const mockPlayer = vi.hoisted(() => ({}));const useDrumPlayer = vi.hoisted(() => vi.fn(() => mockPlayer));+const useWakeLock = vi.hoisted(() => vi.fn());vi.mock('../../hooks/useDrumPlayer.js', () => ({ default: useDrumPlayer }));+vi.mock('../../hooks/useWakeLock.js', () => ({ default: useWakeLock }));vi.mock('./DrumTransportBar.jsx', () => ({default: ({ onToggle, playing, hasMusic }) => (<button type="button" onClick={onToggle} disabled={!hasMusic}>@@ -47,9 +50,11 @@ const CHART_B = 'tempo: 96\nHH: xxxx\nK: o-o-';describe('DrumPreview', () => {beforeEach(() => {mockPlayer.playing = false;+ mockPlayer.chartSettingsReady = true;mockPlayer.toggle.mockReset();mockPlayer.stop.mockReset();useDrumPlayer.mockClear();+ useWakeLock.mockClear();});it('freezes the sounding chart and sheet while live text changes', () => {@@ -62,12 +67,25 @@ describe('DrumPreview', () => {expect(screen.getByText('Chart changed — press Play to reload.')).toBeTruthy();});- it('rebuilds from the latest snapshot before starting after a change', async () => {+ it('keeps Stop enabled when the live draft becomes silent', () => {const { rerender } = render(<DrumPreview text={CHART_A} />);+ mockPlayer.playing = true;+ rerender(<DrumPreview text="HH: ----" />);++ expect(screen.getByRole('button', { name: 'Stop preview' }).disabled).toBe(false);+ expect(useWakeLock).toHaveBeenLastCalledWith(true);+ });++ it('waits for the latest snapshot settings before starting after a change', async () => {+ const { rerender } = render(<DrumPreview text={CHART_A} />);+ mockPlayer.chartSettingsReady = false;rerender(<DrumPreview text={CHART_B} />);fireEvent.click(screen.getByRole('button', { name: 'Play preview' }));await waitFor(() => expect(useDrumPlayer.mock.calls.at(-1)[0]).toBe(CHART_B));+ expect(mockPlayer.toggle).not.toHaveBeenCalled();+ mockPlayer.chartSettingsReady = true;+ rerender(<DrumPreview text={CHART_B} />);expect(mockPlayer.toggle).toHaveBeenCalledTimes(1);expect(screen.queryByText('Chart changed — press Play to reload.')).toBeNull();});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8021ee9442..9aa15190fd 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -180,5 +180,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. || `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |-| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, 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. |+| `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 the chart/transport controls plus `chartSettingsReady`, which becomes true after a replacement chart's persisted/written tempo seed lands. 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 and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. || `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.jsindex acd62ff0c3..7d885fd258 100644--- a/client/src/hooks/useDrumPlayer.js+++ b/client/src/hooks/useDrumPlayer.js@@ -55,6 +55,10 @@ export default function useDrumPlayer(text, { songId } = {}) {const storageKey = songId ? `songbook:drumBpm:${songId}` : null;const [bpm, setBpmState] = useState(writtenTempo);+ // A chart change seeds tempo in an effect. Consumers that need to start the+ // replacement player automatically must wait for this marker, otherwise they+ // can launch it with the previous chart's BPM before the seed render lands.+ const [settingsChart, setSettingsChart] = useState(chart);const [countInBars, setCountInBarsState] = useState(1);const [loopEnabled, setLoopEnabledState] = useState(false);const [loopFrom, setLoopFromState] = useState(1);@@ -83,7 +87,8 @@ export default function useDrumPlayer(text, { songId } = {}) {useEffect(() => {const stored = storageKey ? clampBpm(safeReadStorage(storageKey)) : null;setBpmState(stored ?? writtenTempo);- }, [storageKey, writtenTempo]);+ setSettingsChart(chart);+ }, [chart, storageKey, writtenTempo]);// A chart change invalidates the loop range (the bar count differs).useEffect(() => {@@ -217,6 +222,7 @@ export default function useDrumPlayer(text, { songId } = {}) {return {chart,+ chartSettingsReady: settingsChart === chart,barCount,hasMusic,writtenTempo,diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 45ede44592..8c7d959012 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -548,6 +548,7 @@ export default function SongBookViewer() {songId={id}fontSizeRem={fontSize}sheetClassName="p-3"+ settingsMirror={drum}/>) : (<TabSheetViewdiff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex f6ff4f67f4..f8b947b2cd 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -328,6 +328,16 @@ K: o - - - - - o -`;expect(screen.getByLabelText('Play along')).toBeTruthy();});+ it('keeps edit-preview practice settings when returning to play mode', async () => {+ api.getSong.mockResolvedValue(drumSong());+ renderPage('/songbook/abc?mode=edit');+ const bpm = await screen.findByLabelText('Practice tempo (BPM)');+ fireEvent.change(bpm, { target: { value: '72' } });+ fireEvent.click(screen.getByRole('button', { name: 'View' }));++ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('72'));+ });+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({