Skip to content

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

address review (claude): follow-pan conflict, double-toggle race, exact gutter signature, tail LEAD alignment, rAF-loop tests

[._.]/ Adam Eivy3bd7dbd30a60
diff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsx
index 63e2b8baad..ace8dfccd7 100644
--- a/client/src/components/songs/MidiPianoRoll.jsx
+++ b/client/src/components/songs/MidiPianoRoll.jsx
@@ -102,6 +102,11 @@ export default function MidiPianoRoll({
// Set of midis sounding this frame (null when idle) — written by the rAF
// playback loop, painted onto the pitch gutter by draw().
const soundingRef = useRef(null);
+ // Whether the view should follow the moving playhead. An explicit user pan
+ // (drag / wheel / shift+arrows) turns following off so the loop's page-snap
+ // doesn't fight the pan frame-by-frame; it turns back on when the playhead
+ // re-enters the view, on a seek, and on play.
+ const followRef = useRef(true);
const duration = Math.max(data?.durationSec || 0, 0.001);
// Longest note in the file — the lookback window for lowerBound() scans.
@@ -323,28 +328,35 @@ export default function MidiPianoRoll({
}
wasPlayingRef.current = true;
lastFrameRef.current = '';
+ followRef.current = true; // pressing play re-follows the playhead
let raf = 0;
const loop = () => {
const pos = getPositionRef.current?.() ?? 0;
playheadSecRef.current = pos;
- // Page-turn follow: when the playhead exits the visible window (or a
- // seek lands outside it), snap the view so it re-enters near the left.
+ // Page-turn follow: when the playhead exits the visible window, snap the
+ // view so it re-enters near the left — but only while following (an
+ // explicit user pan turns following off until the playhead re-enters).
const { gridW, pps, maxScroll } = geometry();
const view = gridW / pps;
let paged = false;
- if (pos < scrollSecRef.current || pos > scrollSecRef.current + view) {
+ const visible = pos >= scrollSecRef.current && pos <= scrollSecRef.current + view;
+ if (visible) {
+ followRef.current = true;
+ } else if (followRef.current) {
scrollSecRef.current = Math.min(Math.max(0, pos - view * 0.1), maxScroll);
paged = true;
}
// Sounding set — scan only the slice that can overlap the playhead.
const sounding = new Set();
- let sum = 0;
for (let i = lowerBound(notes, pos - maxDurSec); i < notes.length; i += 1) {
const n = notes[i];
if (n.startSec > pos) break;
- if (pos < n.startSec + n.durationSec) { sounding.add(n.midi); sum += n.midi; }
+ if (pos < n.startSec + n.durationSec) sounding.add(n.midi);
}
- const frame = `${Math.round((pos - scrollSecRef.current) * pps)}:${sounding.size}:${sum}`;
+ // Signature = playhead pixel + exact sounding pitches (the set is
+ // polyphony-sized, so the sort/join is cheap) — a size+sum digest would
+ // miss contrary semitone motion at a sub-pixel playhead step.
+ const frame = `${Math.round((pos - scrollSecRef.current) * pps)}:${[...sounding].sort((a, b) => a - b).join(',')}`;
if (paged || frame !== lastFrameRef.current) {
lastFrameRef.current = frame;
soundingRef.current = sounding;
@@ -439,6 +451,7 @@ export default function MidiPianoRoll({
const { pps } = geometry();
const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
scrollSecRef.current += delta / pps;
+ followRef.current = false; // explicit pan — stop chasing the playhead
scheduleDraw();
}, [applyZoomAnchored, geometry, scheduleDraw]);
@@ -480,6 +493,7 @@ export default function MidiPianoRoll({
const dx = pos.x - tracked.x;
if (Math.abs(dx) > 2 || tracked.moved) {
scrollSecRef.current -= dx / pps;
+ followRef.current = false; // explicit pan — stop chasing the playhead
pointersRef.current.set(e.pointerId, { ...pos, moved: true });
setHoverIdentity(null);
scheduleDraw();
@@ -508,6 +522,7 @@ export default function MidiPianoRoll({
const { pps, gridTop } = geometry();
if (pos.x >= GUTTER_W && pos.y >= gridTop) {
playheadSecRef.current = scrollSecRef.current + (pos.x - GUTTER_W) / pps;
+ followRef.current = true; // a seek re-follows
onSeek?.(playheadSecRef.current);
setHoverIdentity(null);
draw();
@@ -521,8 +536,10 @@ export default function MidiPianoRoll({
const dir = e.key === 'ArrowLeft' ? -1 : 1;
if (e.shiftKey) {
scrollSecRef.current += dir * (gridW / pps) * 0.5;
+ followRef.current = false; // explicit pan — stop chasing the playhead
} else {
playheadSecRef.current = Math.min(duration, Math.max(0, playheadSecRef.current + dir * (10 / pps)));
+ followRef.current = true; // a seek re-follows
onSeek?.(playheadSecRef.current);
}
draw();
diff --git a/client/src/components/songs/MidiPianoRoll.test.jsx b/client/src/components/songs/MidiPianoRoll.test.jsx
new file mode 100644
index 0000000000..8fcb801449
--- /dev/null
+++ b/client/src/components/songs/MidiPianoRoll.test.jsx
@@ -0,0 +1,130 @@
+import { render, cleanup, fireEvent } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import MidiPianoRoll from './MidiPianoRoll.jsx';
+
+// Drives the playback rAF loop deterministically (#2490): requestAnimationFrame
+// is stubbed to a manual queue so each pump() runs exactly one frame. The loop
+// sets no React state — it mutates refs and paints the canvas — so assertions
+// read the mocked 2d-context call counts/args.
+
+const makeCtx = () => ({
+ clearRect: vi.fn(), fillRect: vi.fn(), strokeRect: vi.fn(), fillText: vi.fn(),
+ save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), closePath: vi.fn(),
+ rect: vi.fn(), clip: vi.fn(), roundRect: vi.fn(), fill: vi.fn(), stroke: vi.fn(),
+ moveTo: vi.fn(), arcTo: vi.fn(), setTransform: vi.fn(),
+ fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,
+});
+
+// Long file + two-voice pitch handoff at t=5000 where the pair {60,64} → {61,63}
+// keeps BOTH the set size and the midi sum constant — the case a size+sum
+// repaint signature would miss.
+const DATA = {
+ durationSec: 10000,
+ minMidi: 60,
+ maxMidi: 64,
+ tracks: [{ index: 0 }],
+ tempos: [],
+ notes: [
+ { id: 'a', midi: 60, startSec: 0, durationSec: 5000, velocity: 0.8, track: 0, name: 'C4' },
+ { id: 'b', midi: 64, startSec: 0, durationSec: 5000, velocity: 0.8, track: 0, name: 'E4' },
+ { id: 'c', midi: 61, startSec: 5000, durationSec: 5000, velocity: 0.8, track: 0, name: 'C#4' },
+ { id: 'd', midi: 63, startSec: 5000, durationSec: 5000, velocity: 0.8, track: 0, name: 'D#4' },
+ ],
+};
+
+describe('<MidiPianoRoll> playback rAF loop', () => {
+ let ctx;
+ let rafQueue;
+ const pump = () => {
+ const q = rafQueue;
+ rafQueue = [];
+ q.forEach((cb) => cb());
+ };
+
+ beforeEach(() => {
+ ctx = makeCtx();
+ rafQueue = [];
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ vi.stubGlobal('requestAnimationFrame', (cb) => { rafQueue.push(cb); return rafQueue.length; });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });
+ });
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete HTMLElement.prototype.clientWidth;
+ });
+
+ const renderRoll = (getPosition, { zoom = 1 } = {}) => render(
+ <MidiPianoRoll
+ data={DATA}
+ chords={[]}
+ showChords={false}
+ zoom={zoom}
+ onZoomChange={() => {}}
+ height={200}
+ playing
+ getPosition={getPosition}
+ onSeek={() => {}}
+ onTogglePlay={() => {}}
+ />,
+ );
+
+ it('skips the full repaint on visually identical frames', () => {
+ renderRoll(() => 100);
+ pump(); // first loop frame paints
+ const after1 = ctx.clearRect.mock.calls.length;
+ pump();
+ pump();
+ pump();
+ // Position, sounding set, and page state are all unchanged — every
+ // subsequent frame skips the canvas repaint.
+ expect(ctx.clearRect.mock.calls.length).toBe(after1);
+ });
+
+ it('repaints when the sounding pitches change even at constant set size, sum, and playhead pixel', () => {
+ // At fit zoom, pps = (800-44)/10000 ≈ 0.0756 px/s — a 1.5 s step moves the
+ // playhead well under a pixel, so only the pitch handoff distinguishes the
+ // frames.
+ let pos = 4999;
+ renderRoll(() => pos);
+ pump(); // paints with {60, 64} sounding
+ const before = ctx.clearRect.mock.calls.length;
+ pos = 5000.5; // same rounded playhead px; sounding set is now {61, 63}
+ pump();
+ expect(ctx.clearRect.mock.calls.length).toBe(before + 1);
+ });
+
+ it('pages the view to follow a playhead that exits the visible window', () => {
+ // zoom 8 → view ≈ 1250 s. Jumping to t=2000 must snap the window so the
+ // playhead re-enters near the left (scroll ≈ 1875 s) — verified by the
+ // ruler now labeling a tick inside the new window (t=1920 → "32:00").
+ let pos = 0;
+ renderRoll(() => pos, { zoom: 8 });
+ pump();
+ pos = 2000;
+ pump();
+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);
+ expect(labels).toContain('32:00');
+ });
+
+ it('stops chasing the playhead after an explicit wheel pan, until it re-enters the view', () => {
+ let pos = 0;
+ const { container } = renderRoll(() => pos, { zoom: 8 });
+ const canvas = container.querySelector('canvas');
+ pump();
+ // User wheels the view far ahead of the playhead (deltaY pans horizontally).
+ fireEvent.wheel(canvas, { deltaY: 3000 });
+ pump(); // scheduleDraw repaint at the panned scroll
+ pos = 2000; // playhead still far behind the panned window (scroll ≈ 4960)
+ pump();
+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);
+ // No snap back: the pre-snap window at t≈2000 would label "34:00"; a
+ // followed snap would put scroll at 1875 (labels near 32:00). After the
+ // pan the window sits ≈4960 s in, so the ruler labels ≈"84:00"+.
+ expect(labels).toContain('84:00');
+ expect(labels).not.toContain('32:00');
+ });
+});
diff --git a/client/src/hooks/useMidiPlayer.js b/client/src/hooks/useMidiPlayer.js
index 5b8e805de9..5e458af8aa 100644
--- a/client/src/hooks/useMidiPlayer.js
+++ b/client/src/hooks/useMidiPlayer.js
@@ -16,34 +16,44 @@ import { createMidiPlayer } from '../lib/midiPlayback.js';
export default function useMidiPlayer(data) {
const [playing, setPlaying] = useState(false);
const playerRef = useRef(null);
+ // Intent mirror of the `playing` state. Toggle branches on THIS, not
+ // player.isPlaying(): during a first play the player's flag only flips after
+ // its `await ctx.resume()`, so a rapid double-toggle would read false twice
+ // and start playback instead of netting out to a cancel.
+ const playingRef = useRef(false);
+ const setPlayingBoth = useCallback((v) => {
+ playingRef.current = v;
+ setPlaying(v);
+ }, []);
useEffect(() => {
if (!data) return undefined;
- const player = createMidiPlayer(data, { onEnded: () => setPlaying(false) });
+ const player = createMidiPlayer(data, { onEnded: () => setPlayingBoth(false) });
playerRef.current = player;
return () => {
player.stop();
playerRef.current = null;
- setPlaying(false);
+ setPlayingBoth(false);
};
- }, [data]);
+ }, [data, setPlayingBoth]);
const toggle = useCallback(() => {
const player = playerRef.current;
if (!player) return;
- if (player.isPlaying()) {
+ if (playingRef.current) {
+ // pause() also aborts a play() still awaiting ctx.resume() (playToken).
player.pause();
- setPlaying(false);
+ setPlayingBoth(false);
} else {
- setPlaying(true);
+ setPlayingBoth(true);
// play() resolves once playback has STARTED; a resume failure (autoplay
// policy edge) lands here — reset the button instead of lying "playing".
player.play().catch((err) => {
console.error(`🎹 MIDI preview failed to start: ${err.message}`);
- setPlaying(false);
+ setPlayingBoth(false);
});
}
- }, []);
+ }, [setPlayingBoth]);
const seek = useCallback((sec) => { playerRef.current?.seek(sec); }, []);
const getPosition = useCallback(() => playerRef.current?.position() ?? 0, []);
diff --git a/client/src/lib/midiPlayback.js b/client/src/lib/midiPlayback.js
index ef6f3ec4c4..618a7bdd6d 100644
--- a/client/src/lib/midiPlayback.js
+++ b/client/src/lib/midiPlayback.js
@@ -67,18 +67,22 @@ export const createMidiPlayer = (data, options = {}) => {
// Position the scheduler cursor at the first note starting at/after `offset`,
// and (with soundTails) immediately sound the tails of notes already
// sustaining across it — seeking into a held chord should be audible, not
- // silent until the next onset. Notes are start-sorted, so the tail scan
- // can't early-break; it's a one-time O(n) pass per seek/play, not per tick.
+ // silent until the next onset. Tails anchor to the transport clock
+ // (startTime + offset — callers set startTime first), NOT bare currentTime:
+ // the play() path re-anchors with a LEAD of pre-roll, and a tail started at
+ // "now" would run LEAD early relative to every newly scheduled onset. Notes
+ // are start-sorted, so the tail scan can't early-break; it's a one-time
+ // O(n) pass per seek/play, not per tick.
const seekCursors = (offset, soundTails = false) => {
let idx = notes.findIndex((n) => n.startSec >= offset - 1e-6);
if (idx < 0) idx = notes.length;
nextIdx = idx;
if (!soundTails) return;
- const now = ctx().currentTime;
+ const at = Math.max(startTime + offset, ctx().currentTime);
for (let i = 0; i < idx; i += 1) {
const n = notes[i];
const remaining = n.startSec + n.durationSec - offset;
- if (remaining > 1e-3) playTone(n.midi, now, remaining, n.velocity);
+ if (remaining > 1e-3) playTone(n.midi, at, remaining, n.velocity);
}
};