Repository navigation
perf: write-behind slider saves — stop stuttering playback during drags - #12
Conversation
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>
|
Warning Review limit reached
Next review available in: 21 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughSlider 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. ChangesSlider persistence
Manifest release metadata
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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
screen.js (2)
214-229: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo test coverage for the new debounce/flush machinery.
The provided test snippets cover
sanitizeState/loadState/saveStateround-trips, but nothing exercisespendingStatestaging,schedulePendingFlush's 250ms trailing debounce, orflushPending's interaction withapplyPendingDragLevels. 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
setEqBandstill pays the fullsanitizeState()cost on every tick.
state = getCurrentState()(line 799, unchanged by this diff) runs unconditionally on every call, so every EQinputtick still does a fullsanitizeState()clone (default-state clone +STEM_KEYSloop + arbitrary-stem loop +EQ_BANDSloop) 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"), butpreviewStemVolumeonly pays this cost once per drag session (only whenpendingStateis null), whilesetEqBandpays it on every tick regardless ofpendingState. 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.eqdirectly when it already exists, instead of re-deriving the full state viasanitizeState()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 mutatingpendingStatewhenskipSaveis 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
📒 Files selected for processing (2)
plugin.jsonscreen.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>
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>
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>
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>
There was a problem hiding this comment.
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 leavependingDragLevelsnon-empty (whenapplyPendingDragLevels()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;
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>
Problem
On an installed build, dragging a stem slider while a song plays subtly stutters the timeline. Every
inputtick (pointer-move rate, 60–120+/sec) synchronously ran on the main thread:getItem+JSON.parse+ ~3×sanitizeState+JSON.stringify+setItem(setStemVolume)window.stems.setVolume()→ the stems plugin''ssaveVolume()(another localStorage read+write) + an owner-status snapshot rebuild, plussetMuted()→saveMuted()(another write + snapshot)stems.getState()array + a second fullstemStatescan≈3 synchronous localStorage writes, 2 reads, and ~5 JSON passes per tick — starving the highway''s
requestAnimationFrameloop. 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 livestems.stemStatearray (the API-documented caller-side fast path; falls back togetState()), 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 writeitem.vol, so the flush''sstems.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 ownsaveState().Coherency guards:
getCurrentState()overlays the staged state, soapplyStoredState()firing from the mutation-observer sweep mid-drag can''t read stale storage and snap the volume back.saveState()supersedes the staging: every caller builds its state fromgetCurrentState()(staged values folded in), so the pending flush is completed-and-cancelled to keep it from overwriting a newer write.pagehideanddestroy()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''sif (skipSave) return;sat below the unconditional save, soskipSavenever 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🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Chores