Repository navigation
Conversation
…le playback continues in the background (LargeModGames#395)
📝 WalkthroughWalkthroughPlayback polling now centralizes transient error handling for authentication, rate-limit, network, and selected server failures. Recognized errors update status and retry timing, while authentication errors dispatch ChangesPlayback transient error recovery
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant PlaybackPoll
participant ErrorHandler
participant App
participant IoEvent
PlaybackPoll->>ErrorHandler: pass formatted polling error
ErrorHandler->>App: set status and retry timestamp
ErrorHandler->>IoEvent: dispatch RefreshAuthentication for auth errors
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify code
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/infra/network/playback.rs`:
- Around line 1081-1092: Add regression tests for the authentication-error
branch handling in the playback error flow, covering both “401” and
“Unauthorized” variants alongside the existing access-token-missing case. Assert
that each authorization failure dispatches RefreshAuthentication, updates
instant_since_last_current_playback_poll, sets the session-expired status
message, and returns before generic error handling; preserve existing rate-limit
coverage.
- Around line 1086-1090: Update the expired-session branch in
get_current_playback to use the async self.show_status_message helper with the
existing message and TTL instead of app.set_status_message, releasing the app
lock before awaiting it and reacquiring the lock only for subsequent state
updates such as instant_since_last_current_playback_poll.
🪄 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: 997a5eb1-1c5a-4778-9fe9-0c6136086572
📒 Files selected for processing (1)
src/infra/network/playback.rs
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/infra/network/playback.rs`:
- Around line 393-459: Refactor handle_transient_playback_poll_error and its
call site so all four transient playback messages use the async network layer’s
self.show_status_message helper, preserving TTL scaling and avoiding direct
status_message assignments or app.set_status_message. Since the helper requires
self, either make the handler an async &mut self method or return the
message/TTL and let the caller show it after releasing the App lock; preserve
authentication refresh dispatch and poll-timestamp updates.
🪄 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: 2f03c3fc-0869-4576-b5c1-3932417a88ab
📒 Files selected for processing (1)
src/infra/network/playback.rs
| /// Handle transient failures from the playback poll (`me/player`) that must not | ||
| /// replace the still-playing UI with the full-screen Error route. Returns `true` | ||
| /// when the error was consumed: a status message was shown, the next poll was | ||
| /// scheduled, and the caller must skip generic error handling. | ||
| fn handle_transient_playback_poll_error(app: &mut App, err_text: &str) -> bool { | ||
| let lowered = err_text.to_lowercase(); | ||
|
|
||
| // Playback polling is observational: a stale/missing Web API token must | ||
| // not replace the still-playing UI with a blocking error screen. Queue a | ||
| // forced refresh and let the next poll reconcile the player state. | ||
| if err_text.contains("401") | ||
| || err_text.contains("Unauthorized") | ||
| || lowered.contains("access token missing") | ||
| { | ||
| app.dispatch(IoEvent::RefreshAuthentication); | ||
| app.set_status_message( | ||
| "Spotify session expired. Refreshing authentication automatically.", | ||
| 5, | ||
| ); | ||
| app.instant_since_last_current_playback_poll = Instant::now(); | ||
| return true; | ||
| } | ||
|
|
||
| if err_text.contains("429") | ||
| || err_text.contains("Too Many Requests") | ||
| || err_text.contains("Too many requests") | ||
| { | ||
| app.status_message = Some( | ||
| "Spotify rate limit hit. Retrying automatically; please wait a few seconds.".to_string(), | ||
| ); | ||
| app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(6)); | ||
| app.instant_since_last_current_playback_poll = Instant::now(); | ||
| return true; | ||
| } | ||
|
|
||
| if lowered.contains("error sending request for url") | ||
| || err_text.contains("connection reset") | ||
| || err_text.contains("connection refused") | ||
| || err_text.contains("timed out") | ||
| || err_text.contains("temporary failure") | ||
| || err_text.contains("dns") | ||
| { | ||
| app.status_message = Some( | ||
| "Temporary Spotify network error while polling playback; retrying automatically.".to_string(), | ||
| ); | ||
| app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(5)); | ||
| app.instant_since_last_current_playback_poll = Instant::now(); | ||
| return true; | ||
| } | ||
|
|
||
| if err_text.contains("504") | ||
| || err_text.contains("503") | ||
| || err_text.contains("502") | ||
| || err_text.contains("Gateway Timeout") | ||
| || err_text.contains("Service Unavailable") | ||
| || err_text.contains("Bad Gateway") | ||
| { | ||
| app.status_message = | ||
| Some("Spotify server temporarily unavailable (5xx); retrying automatically.".to_string()); | ||
| app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(10)); | ||
| app.instant_since_last_current_playback_poll = Instant::now(); | ||
| return true; | ||
| } | ||
|
|
||
| false | ||
| } | ||
|
|
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
All four branches bypass the async-network-layer status-message helper.
The auth branch (408-411) calls app.set_status_message(...) instead of self.show_status_message(...), already flagged in a prior review as a path-instruction violation for this async network layer. The other three branches (420-423, 435-438, 450-451) go further and assign app.status_message / app.status_message_expires_at directly, which the guideline explicitly forbids regardless of layer.
Practical effect: none of these transient messages get TTL-scaled by status_message_ttl_percent, unlike every other status message shown from the async network layer via show_status_message.
Since handle_transient_playback_poll_error takes app: &mut App rather than &mut self, it can't call self.show_status_message as-is. Converting it to an async &mut self method (or having it return the message/ttl for the caller to show after dropping the app lock) would satisfy the rule for all four branches at once.
As per path instructions, "User feedback goes through the status-message helpers, never by assigning app.status_message directly... or self.show_status_message(msg, ttl_secs) in the async network layer."
♻️ Sketch of one way to satisfy the rule
-fn handle_transient_playback_poll_error(app: &mut App, err_text: &str) -> bool {
+enum PollErrorOutcome {
+ RefreshAuth(&'static str),
+ Status(&'static str, u64),
+}
+
+fn classify_transient_playback_poll_error(err_text: &str) -> Option<PollErrorOutcome> {
let lowered = err_text.to_lowercase();
if err_text.contains("401") || err_text.contains("Unauthorized") || lowered.contains("access token missing") {
- app.dispatch(IoEvent::RefreshAuthentication);
- app.set_status_message("Spotify session expired. Refreshing authentication automatically.", 5);
- app.instant_since_last_current_playback_poll = Instant::now();
- return true;
+ return Some(PollErrorOutcome::RefreshAuth("Spotify session expired. Refreshing authentication automatically."));
}
// ... same pattern for the other branches, returning PollErrorOutcome::Status(msg, ttl)
}Then at the call site (around line 1145), drop the app lock, await self.show_status_message(msg, ttl), dispatch RefreshAuthentication if applicable, and reacquire the lock only to set instant_since_last_current_playback_poll.
🤖 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/network/playback.rs` around lines 393 - 459, Refactor
handle_transient_playback_poll_error and its call site so all four transient
playback messages use the async network layer’s self.show_status_message helper,
preserving TTL scaling and avoiding direct status_message assignments or
app.set_status_message. Since the helper requires self, either make the handler
an async &mut self method or return the message/TTL and let the caller show it
after releasing the App lock; preserve authentication refresh dispatch and
poll-timestamp updates.
Source: Path instructions
|
Thanks for looking at this. I have a wider fix in #399 so I'll close this one. Worth flagging for future reference: dispatching |
…#395) (#399) # 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 #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 #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. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## 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. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Fixes #395.
Summary
401 "Access token missing" shown after every song transition while playback continues in the background
Validation
🤖 AI-authored PR, operated by @yhay81.
Summary by CodeRabbit