Skip to content

fix: drive sliders from the song's actual stems - #10

Merged
topkoa merged 4 commits into
mainfrom
fix/dynamic-stem-sliders
Jul 19, 2026
Merged

topkoa merged 4 commits into
mainfrom
fix/dynamic-stem-sliders

Conversation

@topkoa

@topkoa topkoa commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The mixer rendered six hardcoded sliders (STEM_KEYS) for every song:

  • Songs with no stems still showed all six sliders; dragging them silently no-oped (all three volume-write routes miss, and the bootstrap poll gives up quietly after 12 s).
  • Songs with partial stems showed dead sliders for the missing ones.
  • Stems with ids outside the six known keys (strings, synth, …) got no slider at all and played at full volume with no control. Their levels were also stripped from state on every load (sanitizeState rebuilt levels from STEM_KEYS only).

Change

Track per-song stem availability and render slider rows from it:

  • Availability sources: the stems plugin's stems:state provider-ready event (authoritative, instant — stemIds, or stemCount: 0 for stem-less songs); the existing bootstrap poll as fallback for hosts without the stems plugin (derives ids from stems.getState() / bridge / audio-map, and flips unknown → known-empty on its 12 s give-up). Reset to unknown at the top of the playSong wrapper, before the await, so a provider-ready that lands mid-flight isn't erased.
  • Three-valued state: null = unknown → render the default six (exactly the old behavior, no "no stems" flash during load); [] → "No stems available for this song." notice; non-empty → exactly those sliders, in both the floating panel and the plugin screen. Rebuilds are guarded by a rendered-list stash, so unchanged sweeps do zero DOM work.
  • Unknown stem ids are first-class: sanitizeState now preserves dynamic level keys (canonicalized, clamped — so they persist and survive profiles), the audio-map gained exact-id detection from data-stem / /stems/<id>.<ext> paths, and the legacy gain-node wiring plus level pushes follow the dynamic list. Labels fall back to a titlecased id.
  • The plugin-screen rows now share makeSliderRow with the panel, which also fixes their percent tag never updating from applyStateToUi (it looked for _pctTag; the old plugin rows set _valueTag).

Testing

  • node tests/state.test.js — 16/16 pass (5 new: dynamic-key preservation, alias folding, dynamic round-trip through localStorage, normalizeAvailableStems shapes).
  • Manual verification in the desktop app is pending (stem-less song → notice; partial stems → filtered rows; non-standard id → working, persisting slider).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Per-song stem controls now dynamically match the available stems, including custom stem types.
    • Songs without available stems display a “No stems available” message instead of inactive controls.
    • Stem volume settings are preserved and applied across supported dynamic stem names.
  • Bug Fixes

    • Improved handling of stem aliases, duplicate entries, invalid values, and unavailable stems.
    • Enhanced protection against unsafe or malformed saved settings.
  • Documentation

    • Updated feature documentation to describe dynamic stem controls and the no-stems state.
  • Chores

    • Updated the plugin version to 1.3.0.

The mixer rendered six hardcoded sliders for every song: dead sliders on
songs without stems (drags silently no-oped), and no slider at all for
stems outside the six known ids, which played at full volume with no
control.

Track per-song availability (stems:state provider-ready when the stems
plugin is loaded, the bootstrap poll otherwise; null until either
reports) and render slider rows from it: only the song's stems get rows,
a stem-less song gets a "No stems available" notice, unknown
availability keeps the old six. Unknown stem ids are now first-class:
sanitizeState keeps their levels (so they persist and survive profiles),
the audio-map gains exact id detection from data-stem and
/stems/<id> paths, and the legacy gain-node wiring and level pushes
follow the dynamic list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: topkoa <topkoa@gmail.com>
@coderabbitai

coderabbitai Bot commented Jul 19, 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: 49 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: 90bd2faa-b3b2-4500-8842-531846e7683b

📥 Commits

Reviewing files that changed from the base of the PR and between dad4c91 and f4ec4a4.

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

Walkthrough

The stem mixer now discovers per-song stem IDs, preserves dynamic levels, applies them during bootstrap, and rebuilds slider rows accordingly. Songs without stems display an empty-state message, while plugin events and song changes reset and resynchronize stem availability.

Changes

Dynamic stem mixer

Layer / File(s) Summary
Dynamic stem state and normalization
screen.js, tests/state.test.js
State sanitization and available-stem normalization preserve dynamic IDs, canonicalize aliases, clamp values, reject reserved or unsafe keys, and persist dynamic levels.
Song stem discovery and synchronization
screen.js
Stem IDs are discovered from audio elements and plugin state, synchronized during bootstrap and song changes, applied to audio nodes, and cleaned up on destruction.
Dynamic mixer rendering and release support
screen.js, README.md, plugin.json
Mixer rows are rebuilt from the current stem list, custom labels are supported, empty songs show a notice, documentation reflects the behavior, and the plugin version is updated to 1.3.0.

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

Sequence Diagram(s)

sequenceDiagram
  participant Song
  participant StemsPlugin
  participant StemMixer
  participant AudioGraph
  Song->>StemsPlugin: playSong
  StemsPlugin->>StemMixer: stems:state provider-ready
  StemMixer->>AudioGraph: discover and configure current stem IDs
  AudioGraph-->>StemMixer: stem audio map
  StemMixer->>StemMixer: render rows and apply stored levels
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers: omikronapex, byrongamatos

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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: slider rows now follow each song's actual stems instead of fixed defaults.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 fix/dynamic-stem-sliders

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

Updates the Stem Mixer UI and persisted state handling to reflect the actual stems present in the current song, including arbitrary stem IDs beyond the legacy six, and introduces an explicit “unknown / none / list” availability model to avoid dead sliders.

Changes:

  • Track per-song stem availability (event-driven with bootstrap polling fallback) and render slider rows dynamically (including “No stems available” message).
  • Preserve and apply dynamic (non-STEM_KEYS) stem level keys through state sanitization, audio-map detection, and UI updates.
  • Add tests for dynamic-key preservation/normalization, and bump plugin version.

Reviewed changes

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

File Description
tests/state.test.js Adds coverage for dynamic level preservation, alias folding expectations, localStorage round-trips, and availability normalization.
screen.js Implements three-valued availableStems, dynamic slider row rendering, dynamic stem detection, and state sanitization updates.
README.md Updates feature description to reflect per-song/dynamic stem sliders and the no-stems notice.
plugin.json Bumps plugin version to 1.3.0.

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

Comment thread screen.js Resolved
Comment thread screen.js Resolved
…ng change

Review follow-ups: own-key lookups everywhere a dynamic stem id indexes a plain object (STEM_ALIASES, STEM_LABELS, levels dedup), drop __proto__ outright, and kill the previous song's bootstrap timers at the top of the playSong wrapper so a leftover tick can't report the old song's stems or flip the new song to 'no stems' mid-load.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: topkoa <topkoa@gmail.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 4 out of 4 changed files in this pull request and generated 2 comments.

Comment thread screen.js Resolved
Comment thread screen.js Resolved
Review follow-ups: an array smuggled into persisted levels no longer leaks its numeric indices in as stem ids, and getStemAudioMap's exact-id detection drops __proto__ like every other dynamic-id path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: topkoa <topkoa@gmail.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 4 out of 4 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (4)

screen.js:589

  • state.levels[stem] !== undefined can mis-detect a missing dynamic stem level when stem collides with Object.prototype (e.g., "constructor"). In that case state.levels[stem] resolves to an inherited function, which then gets passed into setStemVolume and can produce NaN/invalid gain. Use an own-property check when deciding whether to fall back to the default level.
                    const level = state.levels[stem] !== undefined ? state.levels[stem] : 1;

screen.js:722

  • For dynamic stem ids that collide with Object.prototype (e.g., "constructor"), state.levels[stem] !== undefined may return an inherited function even when no saved level exists. That makes Math.round(level * 100) yield NaN and can set the range input to an invalid value. Prefer an own-property check for the default fallback.
                const level = state.levels[stem] !== undefined ? state.levels[stem] : 1;

screen.js:752

  • When stem is a dynamic id that collides with Object.prototype (e.g., "constructor"), state.levels[stem] !== undefined can be true even if there is no own key, causing level to become an inherited function and breaking the appliedLevels idempotence check / volume push. Use hasOwnProperty to determine whether a saved level exists.
            const level = state.levels[stem] !== undefined ? state.levels[stem] : 1;

screen.js:945

  • state.levels[stem] !== undefined is unsafe for dynamic stem ids that may match Object.prototype properties (e.g., "constructor"). If there is no saved level, the lookup returns an inherited function and Number(...) becomes NaN, creating a broken slider value. Use an own-property check and default to 1 when absent.
            const current = state.levels[stem] !== undefined ? Number(state.levels[stem]) : 1;

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
screen.js (1)

121-157: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Alias-only dynamic levels are silently dropped for the six known stems.

next.levels already owns all six STEM_KEYS (defaulted to 1) the moment it's cloned from DEFAULT_STATE — before the STEM_KEYS.forEach pass even runs. So the dynamic loop's guard Object.prototype.hasOwnProperty.call(next.levels, canonical) is always true for any alias resolving to one of the six known ids, even when the raw payload never contained the canonical key itself. A payload like { levels: { voice: 0.9 } } (alias only, no vocals key) will have its voice value dropped and vocals silently reset to the default 1, instead of being folded in as the "aliased dynamic keys are folded into the canonical known key" comment/behavior implies.

In current normal operation this is low-probability, since setStemVolume always canonicalizes before saveState, so this plugin never itself persists alias-only keys — but it's a real gap for legacy-format or externally-written state. Guard against the raw payload instead of the already-defaulted next.levels:

🐛 Proposed fix
         Object.keys(rawLevels).forEach((key) => {
             const canonical = canonicalStemId(key);
-            // Own-key check, not `in`: next.levels is a plain object, so `in`
-            // would see inherited names ('constructor', …) and wrongly skip a
-            // stem that happens to use one. '__proto__' is the one key plain
-            // assignment can't shadow — drop it outright.
+            // Check the RAW payload for an existing canonical entry, not
+            // next.levels — next.levels already owns all six STEM_KEYS
+            // (defaulted to 1) before this loop runs, so checking it would
+            // always block an alias-only value (e.g. only "voice", no
+            // "vocals") from ever reaching its canonical stem.
+            // '__proto__' is the one key plain assignment can't shadow —
+            // drop it outright.
             if (!canonical || canonical === 'full' || canonical === '__proto__' ||
-                Object.prototype.hasOwnProperty.call(next.levels, canonical)) return;
+                (canonical !== key && Object.prototype.hasOwnProperty.call(rawLevels, canonical))) return;
             const n = Number(rawLevels[key]);
             if (Number.isFinite(n)) next.levels[canonical] = Math.max(0, Math.min(1, n));
         });

Worth adding a test for the alias-only case (only voice, no vocals) alongside the existing "both present" test in tests/state.test.js.

🤖 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 121 - 157, Update sanitizeState’s dynamic levels loop
to check whether the canonical key exists in rawLevels, rather than next.levels,
so alias-only entries such as voice are folded into the known canonical stem.
Preserve the existing handling for explicit canonical keys, unknown stems, and
reserved keys, and add coverage in the state tests for an alias-only payload.
🤖 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.

Outside diff comments:
In `@screen.js`:
- Around line 121-157: Update sanitizeState’s dynamic levels loop to check
whether the canonical key exists in rawLevels, rather than next.levels, so
alias-only entries such as voice are folded into the known canonical stem.
Preserve the existing handling for explicit canonical keys, unknown stems, and
reserved keys, and add coverage in the state tests for an alias-only payload.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d84277fd-5c29-4540-b917-eff886bf3407

📥 Commits

Reviewing files that changed from the base of the PR and between 8dcd289 and dad4c91.

📒 Files selected for processing (4)
  • README.md
  • plugin.json
  • screen.js
  • tests/state.test.js

CodeRabbit: the dynamic-levels dedup checked next.levels, which already owns all six defaulted STEM_KEYS, so an alias-only payload (voice with no vocals) could never reach its canonical stem - dedup against the raw payload instead, with exact canonical keys still winning over aliases. Copilot: reading state.levels[stem] with a bare !== undefined resolved inherited names (constructor) to prototype values for dynamic ids - new levelFor() helper does an own-key, finite, clamped lookup with default 1, used at all four read sites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: topkoa <topkoa@gmail.com>
@topkoa

topkoa commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both review-body findings in f4ec4a4:

@coderabbitai's outside-diff comment (alias-only dynamic levels dropped, screen.js 121–157): confirmed — next.levels owns all six defaulted STEM_KEYS before the dynamic loop runs, so the own-key dedup unconditionally blocked alias-only payloads like { voice: 0.9 } from reaching vocals. Took the proposed fix: dedup against rawLevels instead, with canonical !== key so an explicit canonical key still wins over its aliases. Test added: sanitizeState folds an alias-only payload into the canonical known key.

Copilot's four suppressed low-confidence comments (state.levels[stem] !== undefined at the bootstrap push, applyStateToUi, applyStoredState, renderStemRowsInto): all confirmed as one class — for a dynamic id like constructor with no saved level, the bare lookup resolves an inherited prototype value and poisons the gain math. Replaced all four sites with a new levelFor(levels, stem) helper: own-key lookup, finite check, clamp to [0,1], default 1. Exported and covered by levelFor uses own keys only and defaults inherited/missing/invalid to 1.

20/20 tests pass.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@topkoa Thanks for the thorough breakdown. The raw-payload deduplication correctly preserves alias-only levels while retaining canonical-key precedence, and centralizing guarded access in levelFor() addresses the inherited-property issue consistently across all four call sites. The focused regression coverage is appreciated.

🐇 ✅


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@topkoa
topkoa merged commit b491da7 into main Jul 19, 2026
3 checks passed
@topkoa
topkoa deleted the fix/dynamic-stem-sliders branch July 19, 2026 05:03
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