From 4dea5311f878a70ef6de4e63bb5f3cc763818216 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 18:32:14 -0400 Subject: [PATCH 1/6] =?UTF-8?q?perf:=20write-behind=20slider=20saves=20?= =?UTF-8?q?=E2=80=94=20stop=20stuttering=20playback=20during=20drags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dragging a stem slider fired a synchronous persistence chain on every `input` tick (pointer-move rate): our own localStorage read + JSON.parse + triple sanitize + JSON.stringify + write, plus stems.setVolume()/ setMuted() (each persisting per-song state in the stems plugin and rebuilding owner-status snapshots) and an allocated getState() pass. All of it on the main thread, where it starved the highway's requestAnimationFrame loop and visibly stuttered the timeline. Drags now go through previewStemVolume(): only the audible gain (via the live stemState array, the documented caller-side fast path) and an in-memory staged state per tick. One flush ~250 ms after the last tick runs the full stems API + our save. getCurrentState() overlays the staged state so mid-drag UI sweeps can't snap the volume back; a direct saveState() supersedes and cancels the staging; pagehide and destroy() flush immediately. EQ sliders get the same write-behind, which also fixes setEqBand's skipSave flag sitting below an unconditional save (it never skipped). Co-Authored-By: Claude Fable 5 --- plugin.json | 2 +- screen.js | 125 +++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 121 insertions(+), 6 deletions(-) diff --git a/plugin.json b/plugin.json index cd1478c..3e84166 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "stem_mixer", "name": "Stem Mixer", - "version": "1.4.0", + "version": "1.4.1", "private": false, "nav": { "label": "Stem Mixer", diff --git a/screen.js b/screen.js index 6e07f9e..1eba4c9 100644 --- a/screen.js +++ b/screen.js @@ -106,6 +106,15 @@ // only — levels, aliases and persistence all stay keyed by id. let stemMeta = Object.create(null); let onStemsStateEvent = null; + // Write-behind persistence for slider drags. localStorage is synchronous + // main-thread work, and the old per-`input`-tick save chain (our state + // write + the stems plugin's saveVolume/saveMuted + owner-status + // snapshots) starved the highway's requestAnimationFrame loop and + // stuttered playback. Drags stage their state here and flush once, + // shortly after the last tick. + let pendingState = null; + let pendingDragLevels = Object.create(null); + let pendingFlushTimer = null; function invalidateAudioCaches() { stemAudioMapCache = null; @@ -176,6 +185,14 @@ } function saveState(state) { + // A direct save supersedes the drag write-behind: every caller builds + // `state` from getCurrentState(), which already folds staged values + // in. Finish the staged stems-API application and drop the staging — + // otherwise a later flush would overwrite this newer write with + // older data. + if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } + pendingState = null; + applyPendingDragLevels(); try { localStorage.setItem(STATE_KEY, JSON.stringify(sanitizeState(state))); } catch (_) { @@ -183,6 +200,34 @@ } } + // Apply staged drag levels through the FULL stems API — the per-song + // persistence, button-UI updates and owner-status snapshot that + // previewStemVolume() deliberately skips on every `input` tick. + function applyPendingDragLevels() { + const staged = pendingDragLevels; + pendingDragLevels = Object.create(null); + Object.keys(staged).forEach((stem) => { + setStemVolumeViaStemsApi(stem, staged[stem]); + }); + } + + function flushPending() { + if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } + applyPendingDragLevels(); + if (!pendingState) return; + const state = pendingState; + pendingState = null; + saveState(state); + } + + function schedulePendingFlush() { + // Trailing debounce: one flush shortly after the last slider tick. + // 250 ms is long enough that a continuous drag never flushes mid-drag + // and short enough that the final value lands effectively instantly. + if (pendingFlushTimer) clearTimeout(pendingFlushTimer); + pendingFlushTimer = setTimeout(flushPending, 250); + } + function loadProfiles() { try { const raw = localStorage.getItem(PROFILES_KEY); @@ -209,6 +254,11 @@ } function getCurrentState() { + // While a drag's write-behind save is pending, the staged state — not + // localStorage — is the truth. Every reader (applyStoredState's + // re-push, profile capture, autolevel) must see it, or a mid-drag UI + // sweep would read the stale stored level and snap the volume back. + if (pendingState) return sanitizeState(pendingState); return sanitizeState(loadState()); } @@ -559,10 +609,63 @@ appliedLevels[canonical] = clamped; if (!skipSave) { - const state = getCurrentState(); - state.levels[canonical] = clamped; - saveState(state); + if (!pendingState) pendingState = getCurrentState(); + pendingState.levels[canonical] = clamped; + schedulePendingFlush(); + } + } + + // Per-tick path for slider drags. `input` fires at pointer-move rate, so + // this does only the work that must track the pointer: the audible gain + // and the staged state. Everything heavy — our localStorage write, the + // stems plugin's saveVolume/saveMuted/button updates/owner-status + // snapshots — waits for flushPending(). Deliberately does NOT write + // item.vol: the flush's stems.setVolume() only persists when it sees the + // value change from the one it last saved. + function previewStemVolume(stem, level) { + const clamped = Math.max(0, Math.min(1, Number(level) || 0)); + const canonical = canonicalStemId(stem); + if (!window.stems) { + const map = getStemAudioMap(); + if (map[canonical]) { + map[canonical].volume = clamped; + map[canonical].muted = false; + } + ensureStemNodes(); + if (stemNodes[canonical]) { + stemNodes[canonical].gain.value = clamped; + } + } else { + // stemState is the live internal array (no allocation, unlike + // getState()); the API docs bless writing gain.gain.value + // directly as the caller-side fast path. + const list = Array.isArray(window.stems.stemState) + ? window.stems.stemState + : (typeof window.stems.getState === 'function' ? window.stems.getState() : null); + if (Array.isArray(list)) { + list.forEach((item) => { + if (canonicalStemId(item && item.id) !== canonical) return; + if (item.gain && item.gain.gain) item.gain.gain.value = clamped; + if ('on' in item) item.on = true; + if (item.audio) item.audio.muted = false; + }); + } } + + const bridged = stemsBridgeByStem[canonical]; + if (bridged) { + if (bridged.gain && bridged.gain.gain) bridged.gain.gain.value = clamped; + if (bridged.audio) { + bridged.audio.muted = false; + bridged.audio.volume = 1; + } + } + + appliedLevels[canonical] = clamped; + if (!pendingState) pendingState = getCurrentState(); + pendingState.levels[canonical] = clamped; + pendingDragLevels[canonical] = clamped; + schedulePendingFlush(); } function clearStemBootstrapTimers() { @@ -695,7 +798,6 @@ const clamped = Math.max(-12, Math.min(12, Number(value) || 0)); const state = getCurrentState(); state.eq[index] = clamped; - saveState(state); ensureAudioContext(); applyEqToGraph(state.eq); @@ -709,6 +811,12 @@ } if (skipSave) return; + // Write-behind, same as the volume path — EQ `input` fires just as + // fast as the stem sliders. (The save used to run unconditionally + // above this guard, so skipSave never actually skipped it.) + if (!pendingState) pendingState = state; + pendingState.eq[index] = clamped; + schedulePendingFlush(); } function updateAutolevelButtonState(enabled) { @@ -1000,7 +1108,7 @@ input.addEventListener('input', () => { const level = parseInt(input.value, 10) / 100; pct.textContent = `${input.value}%`; - setStemVolume(stem, level); + previewStemVolume(stem, level); }); input._pctTag = pct; (registry || stemInputs)[stem] = input; @@ -1697,6 +1805,9 @@ else if (Number(d.stemCount) === 0) setAvailableStems([]); }; window.addEventListener('stems:state', onStemsStateEvent); + // A drag's write-behind save is only ~250 ms behind, but a close/refresh + // inside that window must not lose the final slider value. + window.addEventListener('pagehide', flushPending); const originalPlaySong = window.playSong; if (typeof originalPlaySong === 'function') { @@ -1767,6 +1878,10 @@ onStemsStateEvent = null; } try { clearStemBootstrapTimers(); } catch (e) { /* ignore */ } + // Land any staged drag state before this instance dies — the + // replacement instance reads localStorage on boot. + try { flushPending(); } catch (e) { /* ignore */ } + try { window.removeEventListener('pagehide', flushPending); } catch (e) { /* ignore */ } clearTimeout(uiUpdateTimer); if (autolevelTimer) { clearInterval(autolevelTimer); autolevelTimer = null; } From 2e17c8e2e38cd0d43930f5d0b37a10aacbae39d4 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 18:41:51 -0400 Subject: [PATCH 2/6] Handle object-form getState() in preview; survive failed saves (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit previewStemVolume() only handled array-shaped getState(), but stemsReachable() documents the older keyed-object shape as a valid surface — a host with only that surface would have heard nothing until the flush. Apply through either shape, keyed items falling back to their key as the stem id. saveState() cleared pendingState before the localStorage write, so a quota/private-mode throw dropped the in-memory truth and re-exposed stale storage to getCurrentState() readers. On failure, keep the state as pendingState; the next save retries naturally since every caller builds from getCurrentState(). Co-Authored-By: Claude Fable 5 --- screen.js | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/screen.js b/screen.js index 1eba4c9..ce9fec8 100644 --- a/screen.js +++ b/screen.js @@ -196,7 +196,12 @@ try { localStorage.setItem(STATE_KEY, JSON.stringify(sanitizeState(state))); } catch (_) { - // Ignore storage errors (private mode, quota, etc). + // Storage failed (private mode, quota, etc). Keep this state as + // the in-memory truth: getCurrentState() readers must not fall + // back to the stale stored copy, or a UI sweep would snap live + // values back for the rest of the session. The next save retries + // naturally — callers build from getCurrentState(). + pendingState = sanitizeState(state); } } @@ -639,16 +644,24 @@ // stemState is the live internal array (no allocation, unlike // getState()); the API docs bless writing gain.gain.value // directly as the caller-side fast path. - const list = Array.isArray(window.stems.stemState) + const raw = Array.isArray(window.stems.stemState) ? window.stems.stemState : (typeof window.stems.getState === 'function' ? window.stems.getState() : null); - if (Array.isArray(list)) { - list.forEach((item) => { - if (canonicalStemId(item && item.id) !== canonical) return; - if (item.gain && item.gain.gain) item.gain.gain.value = clamped; - if ('on' in item) item.on = true; - if (item.audio) item.audio.muted = false; - }); + const applyItem = (item, fallbackId) => { + if (!item || typeof item !== 'object') return; + if (canonicalStemId(item.id != null ? item.id : fallbackId) !== canonical) return; + if (item.gain && item.gain.gain) item.gain.gain.value = clamped; + if ('on' in item) item.on = true; + if (item.audio) item.audio.muted = false; + }; + // Array (newer) or keyed object (older) — the same two getState() + // shapes stemsReachable() accepts. Without the object arm, a host + // whose only surface is object-form getState() would hear nothing + // until the flush. + if (Array.isArray(raw)) { + raw.forEach((item) => applyItem(item, null)); + } else if (raw && typeof raw === 'object') { + Object.keys(raw).forEach((key) => applyItem(raw[key], key)); } } From 2b04585e3a062adf4d5d724222ea1801c040ff01 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 18:49:35 -0400 Subject: [PATCH 3/6] Isolate per-stem flush errors; test the failed-save fallback (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit applyPendingDragLevels() cleared the staging map and then called the stems API bare — a mid-rebuild throw (which stemsReachable() already anticipates) would abort the caller's saveState()/flushPending() and drop every remaining staged level. Each stem now applies inside its own try/catch and a failed one is re-staged (unless a newer level arrived) for the next flush/save to retry; the audible gain already landed via previewStemVolume(). Export getCurrentState and add a regression test: a throwing localStorage.setItem must leave reads on the in-memory truth, not regress to stale storage, and the next successful save must land it. Co-Authored-By: Claude Fable 5 --- screen.js | 13 +++++++++++-- tests/state.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/screen.js b/screen.js index ce9fec8..86cbab1 100644 --- a/screen.js +++ b/screen.js @@ -212,7 +212,16 @@ const staged = pendingDragLevels; pendingDragLevels = Object.create(null); Object.keys(staged).forEach((stem) => { - setStemVolumeViaStemsApi(stem, staged[stem]); + try { + setStemVolumeViaStemsApi(stem, staged[stem]); + } catch (e) { + // The stems plugin can throw mid-rebuild (stemsReachable() + // expects the same). Don't let one stem abort the caller's + // save or drop the rest — re-stage it (unless a newer level + // arrived meanwhile) so the next flush/save retries. The + // audible gain already landed via previewStemVolume(). + if (!(stem in pendingDragLevels)) pendingDragLevels[stem] = staged[stem]; + } }); } @@ -1796,7 +1805,7 @@ module.exports = { STEM_KEYS, EQ_BANDS, DEFAULT_STATE, STEM_ALIASES, sanitizeState, cloneState, canonicalStemId, safeDecodeUrl, stemIdFromUrl, - loadState, saveState, loadProfiles, saveProfiles, + loadState, saveState, getCurrentState, loadProfiles, saveProfiles, normalizeAvailableStems, levelFor, extractStemMeta, stemDisplayName, sameStemSet, STEM_LABELS, }; diff --git a/tests/state.test.js b/tests/state.test.js index feb0456..57bb224 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -265,3 +265,28 @@ test('loadProfiles tolerates corrupt storage and non-object payloads', () => { global.localStorage.setItem('stem_mixer:profiles', '"a string"'); assert.deepEqual(loadProfiles(), {}); }); + +test('saveState keeps in-memory truth when the storage write fails', () => { + const { saveState, getCurrentState } = freshPlugin(); + // Seed a persisted baseline. + saveState({ levels: { vocals: 0.2 } }); + assert.equal(getCurrentState().levels.vocals, 0.2); + + // Break the store the way quota/private mode does. + const originalSetItem = global.localStorage.setItem; + global.localStorage.setItem = () => { throw new Error('quota'); }; + saveState({ levels: { vocals: 0.9 } }); + // Reads must see the failed write, not regress to the stale stored 0.2 — + // otherwise a UI sweep would snap the live value back mid-session. + assert.equal(getCurrentState().levels.vocals, 0.9); + + // Once storage recovers, the next save (built from getCurrentState, as + // every caller does) lands the in-memory truth on disk. + global.localStorage.setItem = originalSetItem; + const next = getCurrentState(); + next.levels.bass = 0.5; + saveState(next); + assert.equal(getCurrentState().levels.vocals, 0.9); + assert.equal(getCurrentState().levels.bass, 0.5); + assert.equal(JSON.parse(global.localStorage.getItem('stem_mixer:state')).levels.vocals, 0.9); +}); From ed0d8023caec7324eb276bba6f906fdbf7e380ba Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 18:56:49 -0400 Subject: [PATCH 4/6] Sanitize once in saveState; finally-restore the test stub (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit saveState() sanitized the same payload twice when the write threw — once for the stringify, again for the pendingState fallback. Compute it once and reuse it for both. The storage-failure test now restores the stubbed setItem in a finally. (freshPlugin() rebuilds localStorage per test, so a leak could not actually cascade — but airtight teardown is cheaper than reasoning about it.) Co-Authored-By: Claude Fable 5 --- screen.js | 5 +++-- tests/state.test.js | 20 +++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/screen.js b/screen.js index 86cbab1..78a2de1 100644 --- a/screen.js +++ b/screen.js @@ -193,15 +193,16 @@ if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } pendingState = null; applyPendingDragLevels(); + const sanitized = sanitizeState(state); try { - localStorage.setItem(STATE_KEY, JSON.stringify(sanitizeState(state))); + localStorage.setItem(STATE_KEY, JSON.stringify(sanitized)); } catch (_) { // Storage failed (private mode, quota, etc). Keep this state as // the in-memory truth: getCurrentState() readers must not fall // back to the stale stored copy, or a UI sweep would snap live // values back for the rest of the session. The next save retries // naturally — callers build from getCurrentState(). - pendingState = sanitizeState(state); + pendingState = sanitized; } } diff --git a/tests/state.test.js b/tests/state.test.js index 57bb224..35203ee 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -272,17 +272,23 @@ test('saveState keeps in-memory truth when the storage write fails', () => { saveState({ levels: { vocals: 0.2 } }); assert.equal(getCurrentState().levels.vocals, 0.2); - // Break the store the way quota/private mode does. + // Break the store the way quota/private mode does. finally-restore so a + // failing assertion can't leave the broken setItem behind (freshPlugin() + // would rebuild localStorage anyway, but keep the teardown airtight). const originalSetItem = global.localStorage.setItem; - global.localStorage.setItem = () => { throw new Error('quota'); }; - saveState({ levels: { vocals: 0.9 } }); - // Reads must see the failed write, not regress to the stale stored 0.2 — - // otherwise a UI sweep would snap the live value back mid-session. - assert.equal(getCurrentState().levels.vocals, 0.9); + try { + global.localStorage.setItem = () => { throw new Error('quota'); }; + saveState({ levels: { vocals: 0.9 } }); + // Reads must see the failed write, not regress to the stale stored + // 0.2 — otherwise a UI sweep would snap the live value back + // mid-session. + assert.equal(getCurrentState().levels.vocals, 0.9); + } finally { + global.localStorage.setItem = originalSetItem; + } // Once storage recovers, the next save (built from getCurrentState, as // every caller does) lands the in-memory truth on disk. - global.localStorage.setItem = originalSetItem; const next = getCurrentState(); next.levels.bass = 0.5; saveState(next); From 527965574da7145ff5a70d22ad6e53111072e090 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 19:01:52 -0400 Subject: [PATCH 5/6] Drop the redundant sanitize on non-pending reads (review) loadState() already returns a fresh sanitized object, so getCurrentState() re-sanitizing it was pure overhead (pre-existing, but this path rides every UI sweep). The pending branch keeps its sanitize deliberately: it doubles as the clone that stops callers mutating the returned state from aliasing into pendingState. Co-Authored-By: Claude Fable 5 --- screen.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/screen.js b/screen.js index 78a2de1..d17ceec 100644 --- a/screen.js +++ b/screen.js @@ -273,8 +273,11 @@ // localStorage — is the truth. Every reader (applyStoredState's // re-push, profile capture, autolevel) must see it, or a mid-drag UI // sweep would read the stale stored level and snap the volume back. + // The sanitize here doubles as a CLONE: callers mutate the returned + // state, and none of that may alias into pendingState. loadState() + // already returns a fresh sanitized object, so no second pass there. if (pendingState) return sanitizeState(pendingState); - return sanitizeState(loadState()); + return loadState(); } function isStemsPluginActive() { From 69bad2d6dc51a9dc18a2bceb63affe3dbf1618e3 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 21 Jul 2026 19:10:52 -0400 Subject: [PATCH 6/6] Fix the saveState contract comment (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The comment claimed every caller builds from getCurrentState(); applyProfile() passes a wholesale replacement. The behavior was already right for both — a direct save is the newer truth either way — but the comment misstated the contract. Say what is actually true. Co-Authored-By: Claude Fable 5 --- screen.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/screen.js b/screen.js index d17ceec..8d829ca 100644 --- a/screen.js +++ b/screen.js @@ -185,11 +185,13 @@ } function saveState(state) { - // A direct save supersedes the drag write-behind: every caller builds - // `state` from getCurrentState(), which already folds staged values - // in. Finish the staged stems-API application and drop the staging — - // otherwise a later flush would overwrite this newer write with - // older data. + // A direct save supersedes the drag write-behind. Callers either + // build `state` from getCurrentState() (staged values folded in) or + // pass a deliberate wholesale replacement (applyProfile) — in both + // cases this write is the newer truth, so drop the staging: a later + // flush must not overwrite it with older data. The staged stems-API + // application still runs — those levels were audible, and the stems + // plugin's own per-song persistence isn't covered by our store. if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } pendingState = null; applyPendingDragLevels(); @@ -200,8 +202,9 @@ // Storage failed (private mode, quota, etc). Keep this state as // the in-memory truth: getCurrentState() readers must not fall // back to the stale stored copy, or a UI sweep would snap live - // values back for the rest of the session. The next save retries - // naturally — callers build from getCurrentState(). + // values back for the rest of the session. Any later save either + // carries this forward (getCurrentState-based callers) or + // replaces it on purpose — both retry the write. pendingState = sanitized; } }