Skip to content

feat: client-side Spotify-style shuffle for native streaming - #380

Merged
LargeModGames merged 4 commits into
mainfrom
feature/native-shuffle
Jul 17, 2026
Merged

LargeModGames merged 4 commits into
mainfrom
feature/native-shuffle

Conversation

@LargeModGames

@LargeModGames LargeModGames commented Jul 17, 2026 •

Copy link
Copy Markdown
Owner

What

Client-side ("Spotify-style") shuffle for native streaming. When shuffle is on and you start a playlist, album, or Liked Songs with spotatui as the playback device, the app now owns the shuffled play order itself (a flat, pre-shuffled URI list loaded via LoadRequest::from_tracks with Spirc-side shuffle off) instead of delegating shuffle to Spirc/Spotify.

Why

Spirc/Spotify regenerate the shuffle order on every context reload. Because the native queue suspends and resumes the context on each queued track, a queue interruption could reshuffle the remaining order and replay tracks you had already heard. Owning the order in-app means a suspend/resume reloads the same order at the right index, so every track plays exactly once per pass.

Behavior

  • Shuffles the tracklist once with the selected song pinned first; everything else follows exactly once per pass.
  • The full playlist / Liked Songs context loads in the background (capped at 3000 tracks, with a status message when truncated) so playback starts instantly from the tracks already on hand, then swaps in the complete order with a single position-preserving reload.
  • Turning shuffle off restores the context's natural order and keeps your place; each repeat-all lap reshuffles for a fresh order, like the Spotify client.
  • Manual Next/Previous, repeat-one replays, and duplicate track ids are resolved to the correct occurrence. Albums load fully up front; contexts the session can't cover (artist/show, raw search/recommendation lists) fall back to the previous Spirc shuffle.
  • Slim (--no-default-features --features telemetry) CI build is unaffected: the pure order/merge helpers are unconditional and unit-tested, the streaming orchestration is #[cfg(feature = "streaming")].

Commits

  • feat: the client-side shuffle session, background context fetch, queue suspend/resume integration, and lap reshuffle.
  • refactor: post-review cleanup (dropped a write-only session field, extracted the duplicated re-anchor logic and the playlist/saved-track pagination loops).
  • docs: CHANGELOG entry.

Testing

  • cargo fmt --all
  • cargo clippy -- -D warnings (streaming) and cargo clippy --no-default-features --features telemetry -- -D warnings (slim)
  • cargo test --no-default-features --features telemetry (462 passed, including the new shuffle helper tests)
  • Manual smoke test of native shuffle + queue interaction still pending.

Summary by CodeRabbit

  • New Features
    • Added Spotify-style shuffle for native streaming playback with stable, app-owned play order.
    • Shuffle supports playlists, albums, and Liked Songs, including background loading for large collections.
  • Bug Fixes
    • Shuffle now resumes correctly after queue suspension, repeat-all reshuffle, and repeat-one behavior (including duplicate tracks).
    • Shuffle playback previews are preserved appropriately during resume, and shuffled state is cleared when switching devices or starting a new target.

Own the shuffled play order in-app (LoadRequest::from_tracks with spirc
shuffle off) so every track plays once per pass and queue suspend/resume
reloads the same order instead of reshuffling the context. Lazy-loads the
full playlist/Liked Songs context in the background (3000-track cap),
restores original order on shuffle-off, and reshuffles each repeat-all lap.
- drop the write-only context_uri field from NativeSpotifyShuffleSession
- extract reanchor_by_rank for the duplicated re-anchor blocks in
  finish_full_context_fetch
- extract a shared paginate_uris helper for the playlist/saved-track
  fetch loops
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 311fb4c7-6dd4-4685-9c34-bc837df1998c

📥 Commits

Reviewing files that changed from the base of the PR and between 77b05c1 and 0489994.

📒 Files selected for processing (6)
  • src/core/app.rs
  • src/core/queue.rs
  • src/infra/network/mod.rs
  • src/infra/network/native_shuffle.rs
  • src/infra/queue/dispatch.rs
  • src/tui/ui/popups.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/tui/ui/popups.rs
  • src/infra/network/native_shuffle.rs

📝 Walkthrough

Walkthrough

Native streaming playback now owns stable Spotify-style shuffle sessions for supported contexts. Sessions load and merge context tracks, track duplicate-aware playback indexes, survive queue suspension and resume, reshuffle repeat-all laps, and clear when playback targets or devices change.

Changes

Native Spotify shuffle

Layer / File(s) Summary
Shuffle session model and ordering
src/core/app.rs, src/infra/network/native_shuffle.rs
Adds streaming shuffle session state, duplicate-aware index resolution, shuffled ordering, context folding, re-anchoring, and unit tests.
Shuffle startup and context loading
src/infra/network/native_shuffle.rs, src/infra/network/playback.rs, src/infra/network/metadata.rs, src/infra/network/mod.rs, CHANGELOG.md
Intercepts eligible native playback, loads shuffled tracks, fetches playlist or liked-song pages up to the configured cap, merges results, and documents the behavior.
Shuffle controls and playback synchronization
src/core/app.rs, src/infra/network/native_shuffle.rs, src/infra/network/mod.rs, src/infra/player/events.rs, src/infra/network/playback.rs
Routes shuffle toggles and lap reshuffles, synchronizes indexes from player events, handles manual navigation, and clears sessions during explicit playback changes, disconnects, or device transfer.
Queue suspension and resume
src/core/queue.rs, src/core/app.rs, src/infra/queue/dispatch.rs, src/tui/ui/popups.rs
Stores generation-bound shuffled resume indexes, resumes native shuffle after queue playback, and uses the Spotify mirror for suspended-context previews.

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

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant App
  participant Network
  participant SpotifyAPI
  participant StreamingPlayer
  User->>App: Enable shuffle and start context
  App->>Network: ToggleNativeShuffleSession
  Network->>SpotifyAPI: Fetch context tracks
  SpotifyAPI-->>Network: Track URIs
  Network->>StreamingPlayer: Load shuffled URI order
  StreamingPlayer-->>App: TrackChanged
  App->>Network: ReshuffleNativeShuffleLap or ResumeNativeShuffleSession
  Network->>StreamingPlayer: Reload session order
Loading
🚥 Pre-merge checks | ✅ 4
✅ 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 uses the required conventional-commit prefix and clearly describes the main change: client-side Spotify-style shuffle for native streaming.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/native-shuffle
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch feature/native-shuffle

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/infra/queue/dispatch.rs (1)

688-700: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add regression coverage for both resume outcomes.

Test that Some(index) preserves the existing shuffle order and that None clears or finishes the session. Because this branch is behind feature = "streaming", slim telemetry tests alone will not exercise it. As per coding guidelines, add or adjust tests when behavior changes.

🤖 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 `@src/infra/queue/dispatch.rs` around lines 688 - 700, Add regression tests for
the SpotifyShuffled resume handling around ResumeNativeShuffleSession: cover
Some(index) preserving the existing shuffle order and None clearing or finishing
the session. Ensure the tests enable the streaming feature and exercise the
dispatch branch rather than only slim telemetry paths.

Source: Coding guidelines

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

Inline comments:
In `@src/core/app.rs`:
- Around line 3937-3950: The manual Next flow must pass SuspendCause::ManualSkip
when suspending the native Spotify shuffle context. Update the caller path in
next_track and the suspend_native_spotify_context_for_queue invocation so manual
skips reach resume_index_after_queue with ManualSkip, while preserving
AutoAdvance for automatic queue advancement.

In `@src/core/queue.rs`:
- Around line 75-80: Update the SpotifyShuffled suspend state and the native
shuffle session lifecycle so suspended resumes cannot outlive the session they
belong to. Prefer storing the session generation alongside resume_index and have
resume_native_shuffle_session() validate it against the active
native_spotify_shuffle before applying the index; alternatively, ensure
clear_native_shuffle_session() also clears queue_suspended.

In `@src/tui/ui/popups.rs`:
- Around line 188-191: Update the SuspendedContext::SpotifyShuffled match arm to
inspect resume_index: return spotify_mirror(max) only for Some(_), and return an
empty Vec for None so exhausted shuffle sessions produce no preview tracks.

---

Nitpick comments:
In `@src/infra/queue/dispatch.rs`:
- Around line 688-700: Add regression tests for the SpotifyShuffled resume
handling around ResumeNativeShuffleSession: cover Some(index) preserving the
existing shuffle order and None clearing or finishing the session. Ensure the
tests enable the streaming feature and exercise the dispatch branch rather than
only slim telemetry paths.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e6a196fc-0f15-493a-b141-50b5ff6b2982

📥 Commits

Reviewing files that changed from the base of the PR and between 4edef39 and 77b05c1.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • src/core/app.rs
  • src/core/queue.rs
  • src/infra/network/metadata.rs
  • src/infra/network/mod.rs
  • src/infra/network/native_shuffle.rs
  • src/infra/network/playback.rs
  • src/infra/player/events.rs
  • src/infra/queue/dispatch.rs
  • src/tui/ui/popups.rs

Comment thread src/core/app.rs Resolved
Comment thread src/core/queue.rs Resolved
Comment thread src/tui/ui/popups.rs Resolved
- Bind a suspended shuffle resume to its session generation so a session
  replaced while the queue drains cannot inherit a stale index. The resume
  handler applies the index only while the live session's generation matches,
  and clears only the session it actually suspended.
- Pass the suspend cause through suspend_native_spotify_context_for_queue:
  a manual Next uses ManualSkip (advances under repeat-one) while an auto
  track-end uses AutoAdvance (replays under repeat-one).
- Show no queue-preview rows for an exhausted shuffle session (None resume).
- Add regression tests for generation forwarding and repeat-one cause behavior.
@LargeModGames

Copy link
Copy Markdown
Owner Author

@coderabbitai All four findings are addressed in 0489994.

1. Bind the suspended shuffle resume to the shuffle session (Major).
SuspendedContext::SpotifyShuffled now carries the session generation alongside resume_index. Both suspend sites stamp session.generation, it is threaded through IoEvent::ResumeNativeShuffleSession(Option<usize>, u64), and resume_native_shuffle_session applies the index only while the live session's generation still matches. A session replaced mid-drain is left running untouched; the None (exhausted) path clears only the session it actually suspended. The full-context-fetch remap already guards on generation before touching the suspend state.

2. Pass ManualSkip from the manual Next path.
suspend_native_spotify_context_for_queue now takes a SuspendCause. next_track passes ManualSkip (advances past the current track under repeat-one) and handle_native_spotify_track_end passes AutoAdvance (replays under repeat-one).

3. Respect an exhausted resume index in the preview.
The SpotifyShuffled arm in queue_preview_tracks now returns spotify_mirror(max) for Some(_) and Vec::new() for None.

4. Regression coverage.
Added streaming-gated tests: generation binding plus the repeat-one cause distinction (core::app), and both resume outcomes forwarding index and generation (infra::queue::dispatch).

Verified with cargo fmt, cargo clippy --features streaming -D warnings, and the full cargo test --features streaming suite (683 passing), plus the slim telemetry gate.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

git show --no-ext-diff --stat --oneline 0489994
printf '\n=== Changed paths ===\n'
git diff-tree --no-commit-id --name-only -r 0489994

printf '\n=== Relevant symbols and tests ===\n'
rg -n -C 4 \
  'SpotifyShuffled|ResumeNativeShuffleSession|SuspendCause|suspend_native_spotify_context_for_queue|queue_preview_tracks|resume_native_shuffle_session|generation.*resume|repeat.one|repeat_one' \
  src/core/app.rs src/core/queue.rs src/infra/network/mod.rs src/infra/network/native_shuffle.rs src/infra/queue/dispatch.rs src/tui/ui/popups.rs \
  || true

printf '\n=== Commit patch ===\n'
git show --no-ext-diff --format=fuller --find-renames 0489994 -- \
  src/core/app.rs src/core/queue.rs src/infra/network/mod.rs src/infra/network/native_shuffle.rs src/infra/queue/dispatch.rs src/tui/ui/popups.rs

Length of output: 46532


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '=== Resume handler ==='
sed -n '595,655p' src/infra/network/native_shuffle.rs

printf '%s\n' '=== Full-context fetch generation validation and suspended remap ==='
sed -n '770,945p' src/infra/network/native_shuffle.rs

printf '%s\n' '=== All SpotifyShuffled construction sites ==='
rg -n -C 5 'SpotifyShuffled\s*\{' src --glob '*.rs'

printf '%s\n' '=== Suspend-cause definitions and call sites ==='
rg -n -C 4 'enum SuspendCause|SuspendCause::(ManualSkip|AutoAdvance)|suspend_native_spotify_context_for_queue\s*\(' \
  src --glob '*.rs'

Length of output: 30032


@LargeModGames: Verified in 0489994. All four findings are addressed.

  1. SpotifyShuffled now snapshots the session generation, dispatch forwards it, and resume reloads or clears state only when the active session generation matches. finish_full_context_fetch also returns before remapping a suspension when its generation is stale.

  2. Native automatic track-end suspension uses AutoAdvance, while manual Next uses ManualSkip. The repeat-one regression test confirms the former retains the current index and the latter advances.

  3. The queue preview returns Vec::new() for an exhausted shuffled suspension with resume_index: None.

  4. The added streaming-gated tests cover generation binding, repeat-one cause behavior, and forwarding both Some(index) and None resume outcomes.

I did not independently execute the reported formatting, clippy, or test commands, but the implementation and test coverage match the stated fixes.


✏️ Learnings added
Learnt from: LargeModGames
URL: https://github.com/LargeModGames/spotatui/pull/380

Timestamp: 2026-07-17T21:23:16.968Z
Learning: For native streaming shuffle in `src/core/app.rs` and `src/infra/network/native_shuffle.rs`, a `SuspendedContext::SpotifyShuffled` resume must be bound to the `NativeSpotifyShuffleSession.generation`. Resume and full-context-fetch code must not reload, clear, or remap a replacement session when the suspended or fetch generation is stale. Manual Next queue handoff uses `SuspendCause::ManualSkip`, while an automatic native track-end handoff uses `SuspendCause::AutoAdvance`, which differs under repeat-one.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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.

1 participant