Skip to content

perf: write-behind slider saves — stop stuttering playback during drags - #12

Merged
topkoa merged 6 commits into
mainfrom
perf/write-behind-slider-saves
Jul 21, 2026
Merged

topkoa merged 6 commits into
mainfrom
perf/write-behind-slider-saves

Conversation

@topkoa

@topkoa topkoa commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On an installed build, dragging a stem slider while a song plays subtly stutters the timeline. Every input tick (pointer-move rate, 60–120+/sec) synchronously ran on the main thread:

  • the mixer''s own persist: localStorage getItem + JSON.parse + ~3× sanitizeState + JSON.stringify + setItem (setStemVolume)
  • window.stems.setVolume() → the stems plugin''s saveVolume() (another localStorage read+write) + an owner-status snapshot rebuild, plus setMuted() → saveMuted() (another write + snapshot)
  • an allocated stems.getState() array + a second full stemState scan

≈3 synchronous localStorage writes, 2 reads, and ~5 JSON passes per tick — starving the highway''s requestAnimationFrame loop. The audible gain write itself was always cheap.

Fix

Drags take a new lightweight path, previewStemVolume(): per tick it writes only the audible gain — via the live stems.stemState array (the API-documented caller-side fast path; falls back to getState()), the standalone <audio>/GainNode path, and the graph bridge — plus an in-memory staged state. Zero storage, zero JSON, zero cross-plugin persistence per tick. It deliberately does not write item.vol, so the flush''s stems.setVolume() still sees a change and persists.

Write-behind flush: one trailing ~250 ms flush after the last tick runs the full stems API (setVolume/setMuted → per-song persistence, button UI, owner status — once per drag) and our own saveState().

Coherency guards:

  • getCurrentState() overlays the staged state, so applyStoredState() firing from the mutation-observer sweep mid-drag can''t read stale storage and snap the volume back.
  • A direct saveState() supersedes the staging: every caller builds its state from getCurrentState() (staged values folded in), so the pending flush is completed-and-cancelled to keep it from overwriting a newer write.
  • pagehide and destroy() flush immediately so the final slider value can''t be lost.

EQ sliders get the same write-behind — which also fixes a latent bug: setEqBand''s if (skipSave) return; sat below the unconditional save, so skipSave never skipped anything.

Programmatic setStemVolume() callers keep the synchronous full-apply path; only their storage write is debounced.

Bumps plugin version to 1.4.1.

Testing

  • tests/state.test.js: 25/25 pass
  • Manually verified on an installed Windows build: continuous slider drags during playback no longer stutter the timeline; volume tracks live; levels persist across restart; stems-plugin button UI shows the final level after release
  • No stems-plugin changes required

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Slider adjustments are now saved shortly after dragging stops, improving responsiveness.
    • Final slider values are preserved when refreshing or closing the page.
  • Bug Fixes

    • Prevented in-progress stem and EQ adjustments from reverting to previously saved values.
    • Ensured pending changes are saved when the interface is closed or the component is removed.
  • Chores

    • Updated the plugin version from 1.4.0 to 1.4.1.

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 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@topkoa, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1eb50784-b98d-4c58-8070-d4bb6f7a9776

📥 Commits

Reviewing files that changed from the base of the PR and between 4dea531 and 69bad2d.

📒 Files selected for processing (2)
  • screen.js
  • tests/state.test.js
📝 Walkthrough

Walkthrough

Slider and EQ changes now use debounced write-behind persistence. Pending values remain current during interaction, flush on page unload or teardown, and stem updates are synchronized through the stems API.

Changes

Slider persistence

Layer / File(s) Summary
Staging and persistence control flow
screen.js
Adds pending state, debounced flushing, staged stem application, and current-state reads from pending values.
Stem and EQ update paths
screen.js
Routes stem slider input through preview staging and stages stem and EQ changes before persistence.
Unload and teardown flushing
screen.js
Flushes pending state on pagehide and during instance destruction, then removes the unload listener.

Manifest release metadata

Layer / File(s) Summary
Manifest version update
plugin.json
Updates the plugin version from 1.4.0 to 1.4.1.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant StemSlider
  participant screenjs
  participant StemsAPI
  participant localStorage
  StemSlider->>screenjs: stage slider value
  screenjs->>StemsAPI: apply audible stem level
  screenjs->>screenjs: debounce flush
  screenjs->>StemsAPI: apply pending stem levels
  screenjs->>localStorage: save sanitized state
Loading

Possibly related PRs

Suggested reviewers: byrongamatos, omikronapex

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: write-behind slider saves to reduce playback stutter during drags.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/write-behind-slider-saves

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Improves playback smoothness during stem/EQ slider drags by moving persistence work off the per-input tick and into a trailing write-behind flush, reducing synchronous localStorage/JSON work on the main thread.

Changes:

  • Adds staged in-memory state and a ~250ms trailing flush to batch persistence after dragging ends.
  • Introduces a lightweight per-tick previewStemVolume() path to update audible gain without triggering heavy stems-plugin persistence/UI work each tick.
  • Updates plugin version to 1.4.1.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
screen.js Implements write-behind persistence, staged state coherency, per-tick preview path, and pagehide/destroy flushing.
plugin.json Bumps plugin version to 1.4.1.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread screen.js Resolved
Comment thread screen.js Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
screen.js (2)

214-229: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test coverage for the new debounce/flush machinery.

The provided test snippets cover sanitizeState/loadState/saveState round-trips, but nothing exercises pendingState staging, schedulePendingFlush's 250ms trailing debounce, or flushPending's interaction with applyPendingDragLevels. Given this logic is the crux of the PR (preventing stutter while guaranteeing no drag value is lost on flush), it's worth adding coverage using fake timers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@screen.js` around lines 214 - 229, Add fake-timer tests covering pendingState
staging, schedulePendingFlush’s 250 ms trailing debounce, and flushPending’s
interaction with applyPendingDragLevels and saveState. Verify repeated
scheduling postpones the flush, the final pending drag value is applied and
persisted after the timer fires, and pending state is cleared without losing the
last value.

797-820: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

setEqBand still pays the full sanitizeState() cost on every tick.

state = getCurrentState() (line 799, unchanged by this diff) runs unconditionally on every call, so every EQ input tick still does a full sanitizeState() clone (default-state clone + STEM_KEYS loop + arbitrary-stem loop + EQ_BANDS loop) before the new write-behind guard even gets a chance to skip anything. The comment at lines 814-816 claims parity with the stem-slider path ("same as the volume path"), but previewStemVolume only pays this cost once per drag session (only when pendingState is null), while setEqBand pays it on every tick regardless of pendingState. This only debounces the storage write, not the read/clone work that was part of the original stutter motivation for this PR.

Consider reading from pendingState.eq directly when it already exists, instead of re-deriving the full state via sanitizeState() each tick:

♻️ Suggested direction (avoid full sanitize when already staged)
 function setEqBand(index, value, skipSave) {
     const clamped = Math.max(-12, Math.min(12, Number(value) || 0));
-    const state = getCurrentState();
-    state.eq[index] = clamped;
+    const eqValues = (pendingState ? pendingState.eq : getCurrentState().eq).slice();
+    eqValues[index] = clamped;
     ensureAudioContext();
-    applyEqToGraph(state.eq);
+    applyEqToGraph(eqValues);
     ...
     if (skipSave) return;
-    if (!pendingState) pendingState = state;
+    if (!pendingState) pendingState = getCurrentState();
     pendingState.eq[index] = clamped;
     schedulePendingFlush();
 }

Using .slice() avoids mutating pendingState when skipSave is true, preserving the existing skip semantics.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@screen.js` around lines 797 - 820, Update setEqBand to reuse the
already-staged pendingState instead of calling getCurrentState and sanitizeState
on every input tick. When pendingState exists, use its EQ data directly; for
skipSave calls, operate on a copied EQ array so the staged state is not mutated.
Preserve the existing initialization, graph/UI updates, and scheduled flush
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@screen.js`:
- Around line 214-229: Add fake-timer tests covering pendingState staging,
schedulePendingFlush’s 250 ms trailing debounce, and flushPending’s interaction
with applyPendingDragLevels and saveState. Verify repeated scheduling postpones
the flush, the final pending drag value is applied and persisted after the timer
fires, and pending state is cleared without losing the last value.
- Around line 797-820: Update setEqBand to reuse the already-staged pendingState
instead of calling getCurrentState and sanitizeState on every input tick. When
pendingState exists, use its EQ data directly; for skipSave calls, operate on a
copied EQ array so the staged state is not mutated. Preserve the existing
initialization, graph/UI updates, and scheduled flush behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8a0fec13-17ed-40be-b574-7a00fabc5ce9

📥 Commits

Reviewing files that changed from the base of the PR and between 88e0234 and 4dea531.

📒 Files selected for processing (2)
  • plugin.json
  • screen.js

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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread screen.js Resolved
Comment thread screen.js Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

Comment thread screen.js Resolved
Comment thread tests/state.test.js Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Comment thread screen.js Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

screen.js:233

  • flushPending() can leave pendingDragLevels non-empty (when applyPendingDragLevels() re-stages a stem because the stems plugin threw mid-rebuild), but it never schedules another flush. If this happens on the trailing flush after a drag, the re-staged stems API application may never be retried, leaving per-song persistence / button UI stuck at the previous value even though audible gain changed during the drag.
    function flushPending() {
        if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; }
        applyPendingDragLevels();
        if (!pendingState) return;
        const state = pendingState;

Comment thread screen.js Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

@topkoa
topkoa merged commit 24c4fb7 into main Jul 21, 2026
4 checks passed
@topkoa
topkoa deleted the perf/write-behind-slider-saves branch July 21, 2026 23:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants