Skip to content

fix(autoplay): constrain spotify recs by current track audio features - #605

Merged
LucasSantana-Dev merged 6 commits into
mainfrom
fix/autoplay-genre-drift
Apr 14, 2026
Merged

LucasSantana-Dev merged 6 commits into
mainfrom
fix/autoplay-genre-drift

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 14, 2026 •

Copy link
Copy Markdown
Owner

Problem

Autoplay kept recommending "weird electro music" regardless of what was playing. Root cause: the Spotify /v1/recommendations API was called with only seed_tracks and no audio feature constraints. Spotify's algorithm picks recommendations purely from track audio features, so a reggaeton/forró track with high energy can drift to electro (same energy profile, different genre).

Fix

Pass min_energy/max_energy, min_valence/max_valence, and min_danceability/max_danceability constraints to the Spotify recommendations call, derived from the current track's audio features (±0.25 tolerance window). These are fetched earlier in the pipeline via getTrackAudioFeatures and now forwarded through collectRecommendationCandidates → collectSpotifyRecommendationCandidates → getSpotifyRecommendations.

When currentFeatures is null (no Spotify link, or features unavailable), the call falls back to unconstrained — no behavior change for those cases.

Changes

  • spotifyApi.ts: getSpotifyRecommendations accepts optional SpotifyAudioFeatureConstraints (energy, valence, danceability) and appends min/max bounds to the API request
  • queueManipulation.ts: thread currentFeatures from the replenish call site down to the Spotify recommendations function
  • 3 new tests in spotifyApi.spec.ts: constraints passed correctly, unconstrained when undefined, bounds clamped to [0,1]
  • 2 updated tests in queueManipulation.spec.ts: flexible assertions for the new 4th arg

Checklist

  • 97 queueManipulation tests pass
  • 33 spotifyApi tests pass (3 new)
  • TypeScript type-check clean
  • Lint clean

Bump: v2.6.119

Summary by CodeRabbit

  • New Features

    • Recommendations now intelligently consider audio characteristics (energy, valence, danceability) of your currently playing track to discover more sonically similar songs.
  • Tests

    • Added comprehensive tests for audio constraint parameter handling and bounds validation.
    • Updated existing tests to improve recommendation parameter verification.

@vercel

vercel Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 14, 2026 4:11am

@coderabbitai

coderabbitai Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 33 minutes and 10 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 33 minutes and 10 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a5faa475-819e-4a3c-a285-ab4a2beba9d2

📥 Commits

Reviewing files that changed from the base of the PR and between 93f1383 and bafb28b.

📒 Files selected for processing (2)
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/utils/music/queueManipulation.ts
📝 Walkthrough

Walkthrough

A new SpotifyAudioFeatureConstraints type is introduced to capture optional audio feature constraints (energy, valence, danceability). The getSpotifyRecommendations function is extended to accept these constraints and translate them into Spotify API query parameters with computed min/max bounds. Queue management logic is updated to compute current track audio features and pass them as constraints when generating recommendations.

Changes

Cohort / File(s) Summary
Spotify API Enhancement
packages/bot/src/spotify/spotifyApi.ts
Added SpotifyAudioFeatureConstraints type definition and extended getSpotifyRecommendations to accept optional audioConstraints parameter. When provided, derives and appends Spotify query parameters (min_*/max_*) for energy, valence, and danceability using a 0.25 tolerance, clamping to [0, 1] range, and formatting to two decimal places.
Spotify API Tests
packages/bot/src/spotify/spotifyApi.spec.ts
Added three new Jest test cases validating: (1) when audioConstraints is provided, corresponding min_*/max_* parameters are included with computed bounds; (2) when audioConstraints is undefined, no constraint parameters are present; (3) constraint values are clamped to [0, 1] range.
Queue Manipulation Implementation
packages/bot/src/utils/music/queueManipulation.ts
Updated _replenishQueue to compute currentFeatures for the currently playing track. Extended collectSpotifyRecommendationCandidates and collectRecommendationCandidates signatures to accept currentFeatures parameter and derive audioConstraints to pass into getSpotifyRecommendations.
Queue Manipulation Tests
packages/bot/src/utils/music/queueManipulation.spec.ts
Updated two test assertions to inspect mock.calls instead of using toHaveBeenCalledWith, verifying call count, token argument, seed ID array, and numeric limit argument (15) for getSpotifyRecommendations.

Sequence Diagram

sequenceDiagram
    participant QueueMgr as Queue Manager
    participant TrackFeatures as Track Audio Features API
    participant SpotifyAPI as Spotify Recommendations API
    
    QueueMgr->>TrackFeatures: getTrackAudioFeatures(currentTrackId)
    activate TrackFeatures
    TrackFeatures-->>QueueMgr: SpotifyAudioFeatures {energy, valence, danceability}
    deactivate TrackFeatures
    
    QueueMgr->>QueueMgr: Derive audioConstraints from currentFeatures
    
    QueueMgr->>SpotifyAPI: getSpotifyRecommendations(token, seedIds, limit, audioConstraints)
    activate SpotifyAPI
    SpotifyAPI->>SpotifyAPI: Compute min_*/max_* bounds (±0.25 tolerance)
    SpotifyAPI->>SpotifyAPI: Clamp values to [0, 1] range
    SpotifyAPI->>SpotifyAPI: Format to 2 decimal places
    SpotifyAPI-->>QueueMgr: Filtered recommendations matching audio constraints
    deactivate SpotifyAPI
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

bot, size/m

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: constraining Spotify recommendations by current track audio features to fix autoplay genre drift.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/autoplay-genre-drift

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 and usage tips.

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/utils/music/queueManipulation.spec.ts`:
- Around line 2970-2975: The mock-call assertions for
spotifyApiMock.getSpotifyRecommendations only check token, seed IDs, and limit;
update the assertions to also extract and assert the 4th argument
(audioConstraints) from the first call (e.g., const [callToken, callIds,
callLimit, callAudioConstraints] =
spotifyApiMock.getSpotifyRecommendations.mock.calls[0]!) and assert that
callAudioConstraints matches the expected constraints used in the test; apply
the same additional assertion in the other block around lines 3039-3044 that
validates the second call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 75cfacee-cfa9-4a3e-88da-bb7887d44832

📥 Commits

Reviewing files that changed from the base of the PR and between 40bbc37 and 93f1383.

📒 Files selected for processing (4)
  • packages/bot/src/spotify/spotifyApi.spec.ts
  • packages/bot/src/spotify/spotifyApi.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/utils/music/queueManipulation.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🔇 Additional comments (3)
packages/bot/src/spotify/spotifyApi.spec.ts (1)

522-576: Strong coverage for constraint query behavior.

Constrained params, unconstrained fallback, and clamping are all explicitly validated here. Nice addition for regression safety.

packages/bot/src/utils/music/queueManipulation.ts (1)

375-400: Feature threading and fallback behavior look correct.

currentFeatures is propagated end-to-end and only translated into Spotify constraints when available, while safely preserving unconstrained behavior otherwise.

Also applies to: 773-815, 883-905

packages/bot/src/spotify/spotifyApi.ts (1)

8-12: Constraint mapping implementation is solid.

The min/max bounds are conditionally added, clamped to [0, 1], and keep existing behavior unchanged when constraints are absent.

Also applies to: 27-89

Comment thread packages/bot/src/utils/music/queueManipulation.spec.ts
@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 6be2cbf into main Apr 14, 2026
12 checks passed
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…#605)

* fix(autoplay): constrain spotify recs by current track audio features

* test(autoplay): verify audioconstraints arg type in recommendation tests

* ci: trigger workflow run for pr #605

* ci: retrigger workflow
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/autoplay-genre-drift branch May 23, 2026 02:21

This branch was successfully deployed

1 active deployment
Preview — bafb28b3 Deployed Apr 14, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant