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): guard resume-window teardown race + align AI prompt vocabulary

[._.]/ Adam Eivyf5a9fc503df9
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index b528ae24c7..bdb3eda891 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -156,6 +156,10 @@ export const createScorePlayer = (score, options = {}) => {
let nextNotifyIdx = 0; // next event to fire onNote for
let lastNotified = -1;
let nodes = []; // live { osc, gain } for teardown
+ // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
+ // and bails if a teardown landed during that await, so a stop/score-change/unmount
+ // mid–first-play can't re-arm an orphaned interval after the await resolves.
+ let playToken = 0;
const stopNodes = () => {
for (const n of nodes) {
@@ -231,7 +235,9 @@ export const createScorePlayer = (score, options = {}) => {
const play = async () => {
if (playing) return;
const c = ctx();
+ const token = ++playToken;
if (c.state === 'suspended' && c.resume) await c.resume();
+ if (token !== playToken) return; // a stop/pause landed during the resume await
if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return; }
schedule = buildSchedule(score, bpm); // pick up a tempo change made while idle
@@ -245,6 +251,7 @@ export const createScorePlayer = (score, options = {}) => {
// Pause — stop sounding, remember position, keep the cursor for resume.
const pause = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
if (!playing) return;
offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), schedule.totalSec);
clearTick();
@@ -254,6 +261,7 @@ export const createScorePlayer = (score, options = {}) => {
// Stop — full teardown back to the top, clears the playhead.
const stop = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
clearTick();
stopNodes();
playing = false;
@@ -330,6 +338,11 @@ export const createMultiScorePlayer = (parts, options = {}) => {
let offsetSec = 0; // resume position (seconds into the score)
let master = null; // shared bus GainNode (created per play)
let nodes = []; // live { osc, gain } across all voices, for teardown
+ // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`
+ // and bails if a teardown landed during that await — otherwise a checkbox toggle
+ // (which tears the player down) mid–first-play re-arms an orphaned, un-stoppable
+ // interval after the await resolves.
+ let playToken = 0;
const stopNodes = () => {
for (const n of nodes) {
@@ -400,7 +413,9 @@ export const createMultiScorePlayer = (parts, options = {}) => {
const play = async () => {
if (playing) return;
const c = ctx();
+ const token = ++playToken;
if (c.state === 'suspended' && c.resume) await c.resume();
+ if (token !== playToken) return; // a stop/pause landed during the resume await
rebuild(); // pick up a tempo change made while idle
if (!totalSec) { safeCall(onEnded); return; }
@@ -416,6 +431,7 @@ export const createMultiScorePlayer = (parts, options = {}) => {
};
const pause = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
if (!playing) return;
offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), totalSec);
clearTick();
@@ -424,6 +440,7 @@ export const createMultiScorePlayer = (parts, options = {}) => {
};
const stop = () => {
+ playToken++; // abort an in-flight play() still awaiting ctx.resume()
clearTick();
stopNodes();
playing = false;
diff --git a/client/src/lib/scorePlayback.race.test.js b/client/src/lib/scorePlayback.race.test.js
new file mode 100644
index 0000000000..e36ffc89bd
--- /dev/null
+++ b/client/src/lib/scorePlayback.race.test.js
@@ -0,0 +1,66 @@
+// Resume-window race guard for the score players. Lives in its own file because
+// the module memoizes one shared AudioContext on first use — a fresh module
+// registry (per Vitest file) lets the first play() create a *suspended* context
+// whose resume() we can leave pending, reproducing the teardown-during-await race
+// that the playToken guard fixes. See createScorePlayer / createMultiScorePlayer.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { parseScore } from './scoreNotation.js';
+import { createScorePlayer, createMultiScorePlayer } from './scorePlayback.js';
+
+const audio = { now: 0, oscillators: [] };
+const fakeParam = () => ({ setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} });
+
+// A context that starts suspended and only resumes when we resolve the deferred
+// returned by resume() — so a test can interleave a stop()/pause() between play()'s
+// `await ctx.resume()` and its continuation.
+let resolveResume;
+function SuspendedAudioContext() {
+ return {
+ state: 'suspended',
+ resume() { return new Promise((r) => { resolveResume = r; }); },
+ get currentTime() { return audio.now; },
+ destination: { id: 'destination' },
+ createOscillator() {
+ const osc = { type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,
+ connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; } };
+ audio.oscillators.push(osc);
+ return osc;
+ },
+ createGain() { return { gain: fakeParam(), connect: (t) => t }; },
+ };
+}
+
+describe('resume-window teardown race', () => {
+ beforeEach(() => {
+ audio.now = 0;
+ audio.oscillators = [];
+ resolveResume = undefined;
+ vi.stubGlobal('AudioContext', SuspendedAudioContext);
+ vi.useFakeTimers();
+ });
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+ const SCORE = parseScore('time: 4/4\ntempo: 120\n| C4q D4q E4q F4q |');
+
+ it('createScorePlayer: stop() during the resume await aborts play() (no scheduler armed)', async () => {
+ const player = createScorePlayer(SCORE, { bpm: 120 });
+ const playing = player.play(); // suspends on ctx.resume()
+ player.stop(); // teardown lands mid-await — bumps the token
+ resolveResume(); // resume resolves; play() must see the stale token and bail
+ await playing;
+ audio.now = 5; vi.advanceTimersByTime(5000); // no interval should be running
+ expect(player.isPlaying()).toBe(false);
+ expect(audio.oscillators).toHaveLength(0); // nothing scheduled by the aborted play
+ });
+
+ it('createMultiScorePlayer: stop() during the resume await aborts play() (no orphaned interval)', async () => {
+ const player = createMultiScorePlayer([{ id: 'melody', score: SCORE }], { bpm: 120 });
+ const playing = player.play();
+ player.stop();
+ resolveResume();
+ await playing;
+ audio.now = 5; vi.advanceTimersByTime(5000);
+ expect(player.isPlaying()).toBe(false);
+ expect(audio.oscillators).toHaveLength(0);
+ });
+});
diff --git a/server/services/songsAI.js b/server/services/songsAI.js
index 892290eb68..f3c08f9aca 100644
--- a/server/services/songsAI.js
+++ b/server/services/songsAI.js
@@ -88,7 +88,7 @@ ${want || 'Write a short, mournful a cappella ballad.'}${existingBlock}
${rhythmVocab()}
Dirge/lament shapes: ${DIRGE_RHYTHM_SHAPES.map((s) => s.id).join(', ')}.
-# Voice layers — return these foundation-first (lead, then bass, then thirds/fifths, then drone/counter). Use the id when it matches.
+# Voice layers — return these foundation-first (melody, then bass, then the mid harmonies, then the high harmonies). Use the id when it matches.
${layerVocab()}
# Output contract
@@ -174,9 +174,9 @@ ${songBlock}
# What to assess
- Singability: are the parts in comfortable ranges, do entrances/breaths work unaccompanied?
-- Harmony: do the layers build foundation-first (lead, bass, thirds, fifths) and stay in tune as a stack?
+- Harmony: do the layers build foundation-first (melody, bass, mid harmonies, high harmonies) and stay in tune as a stack?
- Structure & lyrics: does the form serve the mood; do lyrics scan and breathe across the bar?
-- Layer balance: is anything missing (a drone, a counter-melody) or overcrowded?
+- Layer balance: is anything missing (the bass floor, a sustained high pad) or overcrowded?
# Output contract
Return ONLY a JSON object (no prose, no markdown fence):