Skip to content

fix: 401 "Access token missing" error screen at every song transition (#395) - #399

Merged
LargeModGames merged 1 commit into
mainfrom
fix/395-token-401-amplification
Jul 22, 2026
Merged

LargeModGames merged 1 commit into
mainfrom
fix/395-token-401-amplification

Conversation

@LargeModGames

@LargeModGames LargeModGames commented Jul 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes #395.

With playback on an external Connect device, spotatui showed the full-screen error route at every track transition with a 401 Access token missing from me/player, even though the music never stopped and the very next poll succeeded with the same token.

The 401 itself comes from Spotify's player-service gateway (only me/player* ever produces that message, and no client-side mistake reproduces it), but the app amplified a transient blip into a visible failure in three ways, all fixed here:

  1. Every 401 forced a full token refresh. Under PKCE that also rotates the refresh token, so at the 1 second external-device poll cadence a spurious 401 minted a whole new token family every few seconds. That is the POST /api/token every few seconds visible in the reporter logs, and a lost rotated refresh token logs the user out. Forced refreshes are now rate limited to one per 30 seconds by a shared ForcedRefreshGate; a 401 inside the cooldown retries with the token already in hand.
  2. The retry was immediate, so it landed inside the same window that produced the 401 and failed identically. It now backs off 1 second first. Recovery stays strictly one-shot on both paths.
  3. The playback poll treated the surfaced 401 as fatal. It now tolerates a short run: silent on the first (the self-healing case), a status message from the second, the error route only on the fourth. The counter resets on every poll the API answers, including idle and 404, so a genuinely dead session still surfaces in about four seconds.

Two supporting changes:

  • Diagnostics. Every non-2xx Spotify response now logs the endpoint path, status, response body and the age of the token that was attached. Never the token value, never the query string. One reporter run with this will separate "server-side transition flake" from "fresh-token propagation lag" from "shared client ID degradation".
  • Which Spotify app you are actually on. The setup wizard writes the shared ncspot client ID as the primary client_id for both of its options and keeps your own app as fallback_client_id, so "I set up my own app" has never meant "I am using my own app". Startup now says so. This cost real diagnostic time on 401 "Access token missing" shown after every song transition while playback continues in the background #395: the reporter believed they were on their own client ID and were not.

The shared request helper's parameters were grouped into a SpotifyApiRequest struct, since the extra gate argument tripped clippy::too_many_arguments.

Testing

  • cargo fmt --all
  • cargo clippy --no-default-features --features telemetry -- -D warnings, clean
  • cargo test --no-default-features --features telemetry, 483 passed
  • cargo test, 731 passed
  • cargo test --features all-sources, 804 passed

New tests:

  • second_unauthorized_within_cooldown_retries_without_forcing_refresh: two calls, each answered 401 then 200, asserting exactly one forced refresh across both and that the second call's retry reuses the already-refreshed token.
  • unauthorized_forces_refresh_again_once_cooldown_expires: an elapsed cooldown still recovers a token that really did go bad.
  • repeated_unauthorized_in_one_call_gives_up_after_one_recovery: termination, plus the status stays in the error text that playback.rs matches on.
  • retries_once_with_refreshed_token_after_401 extended to assert the retry is backed off.
  • Four tests over client_id_notice_for covering wizard option 1, wizard option 2, a hand-edited personal-primary config, and a genuine fallback.

Not covered by tests: the poll escalation threshold against a real external Connect device. That needs a manual pass, which has not been done yet.

Additional notes

  • Overlaps with fix: 401 "Access token missing" shown after every song transition while playb... #398, which addresses the error-route symptom only. That PR dispatches IoEvent::RefreshAuthentication on every poll 401, which runs a forced refresh_token_and_cache, so at the 1 second cadence it adds a PKCE refresh-token rotation per second on top of the one the request path already performs. It also has no escalation path, so a genuinely dead session shows "session expired, refreshing automatically" forever. The two changes conflict textually in the same Err arm.
  • The 401 itself is server-side and this PR does not claim to fix it. Fixes 1 to 3 target the app's own amplification loop, which is wrong on its own terms regardless of the trigger; the diagnostics are the honest way to pin the trigger down.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of intermittent Spotify authorization failures during playback transitions.
    • Added retry backoff and refresh cooldowns to prevent repeated token refresh attempts.
    • Increased tolerance for brief authorization errors while polling playback status.
    • Enhanced diagnostics for unsuccessful Spotify responses.
  • User Experience

    • Startup now indicates which Spotify app session was used, including fallback authentication scenarios.

…#395)

Spotify's player service intermittently rejects a valid token on
me/player, typically right at a track transition. The app turned that
blip into a visible failure three ways, all fixed here:

- Every 401 forced a full token refresh, which under PKCE also rotates
  the refresh token. At the 1s external-device poll cadence that minted
  a new token family every few seconds. Forced refreshes are now rate
  limited to one per 30s by a shared ForcedRefreshGate, and a 401 inside
  the cooldown retries with the token already in hand.
- The single retry fired immediately, landing back inside the window
  that produced the 401. It now backs off 1s first. Recovery stays
  one-shot on both paths.
- The playback poll treated the surfaced 401 as fatal. It now tolerates
  a short run (silent on the first, status message from the second,
  error route on the fourth) and resets on every poll the API answers.

Also adds diagnostics on every non-2xx response (endpoint, status, body,
and the age of the attached token, never the token itself), and reports
which Spotify app the session signed in as: the setup wizard writes the
shared ncspot client ID as the primary for both of its options and keeps
your own app as the fallback, so "I set up my own app" never meant "I am
using my own app".

The shared request helper's parameters were grouped into a
SpotifyApiRequest struct, since the extra gate argument tripped
clippy::too_many_arguments.
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds Spotify client ID authentication notices, throttles forced token refreshes after repeated 401 responses, tolerates transient playback polling failures, improves response diagnostics, and resets refresh state after login.

Changes

Spotify authentication and playback handling

Layer / File(s) Summary
Authentication client selection notices
src/core/auth.rs, src/runtime.rs
Authentication reports shared or fallback client ID usage, while startup logs and conditionally displays the corresponding notice.
401 refresh cooldown and request diagnostics
src/infra/network/requests.rs
Requests use structured parameters, cooldown-gated token refreshes, bounded 401 retries, response logging, and expanded retry tests.
Playback polling failure tolerance
src/infra/network/playback.rs, src/infra/network/mod.rs, CHANGELOG.md
Playback polling tolerates consecutive 401 responses, resets failure state for successful or idle results, resets refresh cooldown after login, and documents the fix.

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

Possibly related PRs

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #395 by rate-limiting refreshes, retrying 401s, and preventing brief playback polling failures from showing the error screen.
Out of Scope Changes check ✅ Passed The added logging, client ID notice, and request refactor all support the reported Spotify 401 handling and do not appear unrelated.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title uses the required fix: prefix and clearly describes the main change, the recurring 401 error during song transitions.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/395-token-401-amplification
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/395-token-401-amplification

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

@LargeModGames
LargeModGames marked this pull request as ready for review July 22, 2026 22:54
@LargeModGames
LargeModGames merged commit a12172e into main Jul 22, 2026
15 checks passed
@LargeModGames
LargeModGames deleted the fix/395-token-401-amplification branch July 22, 2026 22:54
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.

401 "Access token missing" shown after every song transition while playback continues in the background

1 participant