From 57a27abf84b2985aa410a63d530997dfbf4da0f3 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 31 Aug 2026 14:12:16 -0600 Subject: [PATCH 1/3] fix(qconnect): recover state-only renderer takebacks cx --- crates/qconnect-app/src/renderer.rs | 154 +++++++++++++++++++++++++++- 1 file changed, 150 insertions(+), 4 deletions(-) diff --git a/crates/qconnect-app/src/renderer.rs b/crates/qconnect-app/src/renderer.rs index e50312aa2..02255472a 100644 --- a/crates/qconnect-app/src/renderer.rs +++ b/crates/qconnect-app/src/renderer.rs @@ -39,6 +39,47 @@ const LOAD_ATTEMPT_DEDUP_WINDOW: Duration = Duration::from_secs(5); /// queue. Matches the Tauri adapter's prior `QCONNECT_REMOTE_QUEUE_SOURCE`. pub const QCONNECT_REMOTE_QUEUE_SOURCE: &str = "qobuz_connect_remote"; +/// Whether a queue row can be named by Qobuz Connect without looking the id up. +/// +/// Source provenance is the authority: local-library and media-server ids can +/// overlap the numeric Qobuz id space, while offline Qobuz downloads retain the +/// real catalog id and remain resolvable. A missing source is accepted only by +/// the [`QueueTrack`] wrapper below, where the legacy `is_local` discriminator +/// is still available. +pub fn qconnect_source_is_resolvable(track_id: u64, source: Option<&str>) -> bool { + if track_id == 0 { + return false; + } + match source.map(str::trim).filter(|source| !source.is_empty()) { + Some(source) => matches!( + source.to_ascii_lowercase().as_str(), + "qobuz" + | "qobuz_download" + | "qobuz_purchase" + | "offline" + | QCONNECT_REMOTE_QUEUE_SOURCE + ), + // Callers with only the wire-shaped `(id, source)` pair have no local + // bit. Every current local producer stamps an explicit source, so the + // source-less shape is the legacy catalog case. + None => true, + } +} + +/// Queue-row form of [`qconnect_source_is_resolvable`]. This is the canonical +/// admission predicate for desktop queue filtering and daemon publication. +pub fn qconnect_queue_track_is_resolvable(track: &QueueTrack) -> bool { + match track + .source + .as_deref() + .map(str::trim) + .filter(|source| !source.is_empty()) + { + Some(source) => qconnect_source_is_resolvable(track.id, Some(source)), + None => track.id > 0 && !track.is_local, + } +} + pub fn qconnect_repeat_mode_from_loop_mode(loop_mode: i32) -> Option { // QConnect protocol loop mode values: 1 = off, 2 = repeat one, 3 = repeat all. match loop_mode { @@ -322,6 +363,41 @@ pub async fn force_remote_track_stream( Ok(true) } +/// Resolve the track for a state-only PLAYING command on a cold engine. +/// Official clients can omit `current_track`; the synchronized queue cursor is +/// then the next authority. The id that `stop()` deliberately preserved is +/// accepted only when it still names a resolvable row in that queue; a bare +/// local-library id is never guessed to be Qobuz. +async fn takeback_track_id( + engine: &impl QconnectRendererEngine, + renderer_state: &QConnectRendererState, +) -> Option { + if let Some(track_id) = renderer_state + .current_track + .as_ref() + .map(|track| track.track_id) + .filter(|track_id| *track_id > 0) + { + return Some(track_id); + } + + let (tracks, current_index) = engine.get_all_queue_tracks().await; + if let Some(track_id) = current_index + .and_then(|index| tracks.get(index)) + .filter(|track| qconnect_queue_track_is_resolvable(track)) + .map(|track| track.id) + .filter(|track_id| *track_id > 0) + { + return Some(track_id); + } + + let track_id = engine.get_playback_state().track_id; + tracks + .iter() + .find(|track| track.id == track_id && qconnect_queue_track_is_resolvable(track)) + .map(|track| track.id) +} + pub async fn apply_remote_loop_mode( engine: &impl QconnectRendererEngine, loop_mode: i32, @@ -454,14 +530,20 @@ pub async fn apply_renderer_command( // SetActive takeback path; the has_loaded_audio gate // keeps echoes and live playback on the plain resume. let cold_engine = !engine.has_loaded_audio(); - let cold_track = projection_renderer_state.current_track.as_ref(); - if cold_engine && cold_track.is_some() { - let track_id = cold_track.map(|t| t.track_id).unwrap_or(0); + if cold_engine { + let Some(track_id) = + takeback_track_id(engine, &projection_renderer_state).await + else { + return Err( + "cold-start resume has no projected, queued, or preserved track" + .to_string(), + ); + }; let start_position_secs = renderer_state .current_position_ms .or(*current_position_ms) .map(|ms| ms / 1000) - .unwrap_or(0); + .unwrap_or_else(|| engine.get_playback_state().position); match force_remote_track_stream( engine, sync_state, @@ -1308,6 +1390,70 @@ mod tests { assert_eq!(calls.resumes, 0, "no bare resume on a cold engine"); } + /// The field shape from the owner's 2026-08-31 regression: both the + /// command and renderer projection omit current_track, but the synchronized + /// queue still has the authoritative cursor. This must cold-load that row, + /// never fall through to `resume()` on an empty engine. + #[tokio::test] + async fn cold_resume_falls_back_to_queue_cursor_when_projection_omits_track() { + let mut engine = MockEngine::new(); + engine.playback = PlaybackState { + track_id: 7, + position: 38, + ..Default::default() + }; + engine.queue_tracks = vec![mock_queue_track(6), mock_queue_track(7)]; + engine.queue_index = Some(1); + engine.loaded_audio = false; + let sync = sync(); + let cmd = RendererCommand::SetState { + playing_state: Some(PLAYING_STATE_PLAYING), + current_position_ms: None, + current_track: None, + next_track: None, + }; + + apply_renderer_command(&engine, &sync, &cmd, &QConnectRendererState::default()) + .await + .unwrap(); + + let calls = engine.calls(); + assert_eq!(calls.start_track_streams, vec![7]); + assert_eq!(calls.start_positions, vec![38]); + assert_eq!(calls.resumes, 0); + } + + #[tokio::test] + async fn cold_resume_never_guesses_a_local_queue_id_is_qobuz() { + let mut engine = MockEngine::new(); + engine.playback = PlaybackState { + track_id: 7, + ..Default::default() + }; + let mut local = mock_queue_track(7); + local.source = Some("local".to_string()); + local.is_local = true; + engine.queue_tracks = vec![local]; + engine.queue_index = Some(0); + engine.loaded_audio = false; + let cmd = RendererCommand::SetState { + playing_state: Some(PLAYING_STATE_PLAYING), + current_position_ms: None, + current_track: None, + next_track: None, + }; + + let error = + apply_renderer_command(&engine, &sync(), &cmd, &QConnectRendererState::default()) + .await + .expect_err("local ids must not be sent to Qobuz"); + + assert!(error.contains("no projected, queued, or preserved track")); + let calls = engine.calls(); + assert!(calls.start_track_streams.is_empty()); + assert_eq!(calls.resumes, 0); + } + /// The cold-start load never fires while audio is loaded: a resume during /// live playback (or a cloud echo) stays a plain resume, no re-stream. #[tokio::test] From a5f62662f5a4dd6555021fa031cb854f3cce7c4d Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 31 Aug 2026 14:12:42 -0600 Subject: [PATCH 2/3] fix(qconnect): filter unresolvable queue tracks cx --- .../translations/de/LC_MESSAGES/qbz-ui.po | 5 + .../translations/en/LC_MESSAGES/qbz-ui.po | 5 + .../translations/es/LC_MESSAGES/qbz-ui.po | 5 + .../translations/fr/LC_MESSAGES/qbz-ui.po | 5 + .../translations/ja/LC_MESSAGES/qbz-ui.po | 4 + .../translations/nl/LC_MESSAGES/qbz-ui.po | 5 + .../translations/pt/LC_MESSAGES/qbz-ui.po | 5 + .../translations/ru/LC_MESSAGES/qbz-ui.po | 6 + crates/qbz-qt/src/album_qt.rs | 3 + crates/qbz-qt/src/bulk_tracks_qt.rs | 3 + crates/qbz-qt/src/local_album_actions.rs | 7 +- crates/qbz-qt/src/local_bulk.rs | 10 +- crates/qbz-qt/src/local_playback.rs | 11 +- crates/qbz-qt/src/local_playlist_qt.rs | 3 + crates/qbz-qt/src/myqbz_play_qt.rs | 57 ++-- crates/qbz-qt/src/playback_qt.rs | 141 ++++++--- crates/qbz-qt/src/playlist_qt.rs | 3 + crates/qbz-qt/src/qconnect_qt.rs | 290 +++++++++++------- crates/qbz-qt/src/queue_qt.rs | 12 +- crates/qbzd/src/qconnect/publish.rs | 13 +- crates/qconnect-app/src/lib.rs | 1 + crates/qconnect-app/src/renderer.rs | 37 +++ 22 files changed, 424 insertions(+), 207 deletions(-) diff --git a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po index 6c701ff56..f05f4da8a 100644 --- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po @@ -6299,3 +6299,8 @@ msgstr "Sponsoren" msgid "And all those anonymous sponsors..." msgstr "Und all die anonymen Sponsoren..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect kann lokale Tracks nicht auflösen. {} Track wurde übersprungen und nicht zur Warteschlange hinzugefügt. Schalte Qobuz Connect aus, um ihn abzuspielen." +msgstr[1] "Qobuz Connect kann lokale Tracks nicht auflösen. {} Tracks wurden übersprungen und nicht zur Warteschlange hinzugefügt. Schalte Qobuz Connect aus, um sie abzuspielen." diff --git a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po index 94ef60183..0f820f937 100644 --- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po @@ -1889,3 +1889,8 @@ msgstr "{} of {}" msgid "Last playlist" msgstr "Last playlist" + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgstr[1] "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." diff --git a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po index 60d217132..88e7caad3 100644 --- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po @@ -6305,3 +6305,8 @@ msgstr "Patrocinadores" msgid "And all those anonymous sponsors..." msgstr "Y todos esos patrocinadores anónimos..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect no puede resolver tracks locales. Se ignoró {} track y no se incluyó en la lista. Si deseas reproducirlo, apaga Qobuz Connect." +msgstr[1] "Qobuz Connect no puede resolver tracks locales. Se ignoraron {} tracks y no se incluyeron en la lista. Si deseas reproducirlos, apaga Qobuz Connect." diff --git a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po index 906aeaced..c559c8066 100644 --- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po @@ -6297,3 +6297,8 @@ msgstr "Sponsors" msgid "And all those anonymous sponsors..." msgstr "Et tous ces sponsors anonymes..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect ne peut pas résoudre les morceaux locaux. {} morceau a été ignoré et n’a pas été ajouté à la file d’attente. Désactivez Qobuz Connect pour le lire." +msgstr[1] "Qobuz Connect ne peut pas résoudre les morceaux locaux. {} morceaux ont été ignorés et n’ont pas été ajoutés à la file d’attente. Désactivez Qobuz Connect pour les lire." diff --git a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po index 4079d8134..e996d7f12 100644 --- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po @@ -6281,3 +6281,7 @@ msgstr "スポンサー" msgid "And all those anonymous sponsors..." msgstr "そして、すべての匿名スポンサーの皆さん…" + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect はローカルトラックを解決できません。{} 曲をスキップし、キューに追加しませんでした。再生するには Qobuz Connect をオフにしてください。" diff --git a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po index f0ba44118..430d43d5d 100644 --- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po @@ -6287,3 +6287,8 @@ msgstr "Sponsors" msgid "And all those anonymous sponsors..." msgstr "En al die anonieme sponsors..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect kan lokale tracks niet vinden. {} track is overgeslagen en niet aan de wachtrij toegevoegd. Schakel Qobuz Connect uit om deze af te spelen." +msgstr[1] "Qobuz Connect kan lokale tracks niet vinden. {} tracks zijn overgeslagen en niet aan de wachtrij toegevoegd. Schakel Qobuz Connect uit om ze af te spelen." diff --git a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po index 7437983b0..a95fed09d 100644 --- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po @@ -6297,3 +6297,8 @@ msgstr "Patrocinadores" msgid "And all those anonymous sponsors..." msgstr "E todos esses patrocinadores anônimos..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "O Qobuz Connect não consegue resolver faixas locais. {} faixa foi ignorada e não foi adicionada à fila. Desative o Qobuz Connect para reproduzi-la." +msgstr[1] "O Qobuz Connect não consegue resolver faixas locais. {} faixas foram ignoradas e não foram adicionadas à fila. Desative o Qobuz Connect para reproduzi-las." diff --git a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po index 5780ad0ca..764980699 100644 --- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po @@ -6317,3 +6317,9 @@ msgstr "Спонсоры" msgid "And all those anonymous sponsors..." msgstr "И все те анонимные спонсоры..." + +msgid "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it." +msgid_plural "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them." +msgstr[0] "Qobuz Connect не может распознать локальные треки. Пропущен {} локальный трек; он не добавлен в очередь. Отключите Qobuz Connect, чтобы воспроизвести его." +msgstr[1] "Qobuz Connect не может распознать локальные треки. Пропущено {} локальных трека; они не добавлены в очередь. Отключите Qobuz Connect, чтобы воспроизвести их." +msgstr[2] "Qobuz Connect не может распознать локальные треки. Пропущено {} локальных треков; они не добавлены в очередь. Отключите Qobuz Connect, чтобы воспроизвести их." diff --git a/crates/qbz-qt/src/album_qt.rs b/crates/qbz-qt/src/album_qt.rs index bd0de1f70..4f2b74646 100644 --- a/crates/qbz-qt/src/album_qt.rs +++ b/crates/qbz-qt/src/album_qt.rs @@ -773,6 +773,9 @@ pub fn bulk_action(album_id: String, ids_json: String, action: String) { picked, crate::playback_qt::PlayContext::album(&album_id), ); + if picked.is_empty() { + return; + } if let Err(e) = crate::playback_qt::enqueue_track_list_mode(&runtime, picked, mode).await { diff --git a/crates/qbz-qt/src/bulk_tracks_qt.rs b/crates/qbz-qt/src/bulk_tracks_qt.rs index 6c085a0ab..849f2f311 100644 --- a/crates/qbz-qt/src/bulk_tracks_qt.rs +++ b/crates/qbz-qt/src/bulk_tracks_qt.rs @@ -123,6 +123,9 @@ pub fn run(ids_json: String, action: String, context_kind: String, context_id: S queue, crate::playback_qt::PlayContext::new(&context_kind, &context_id), ); + if queue.is_empty() { + return; + } let runtime = crate::app(); if let Err(e) = crate::playback_qt::enqueue_track_list_mode(&runtime, queue, mode).await diff --git a/crates/qbz-qt/src/local_album_actions.rs b/crates/qbz-qt/src/local_album_actions.rs index 9ff8d69db..2a2140764 100644 --- a/crates/qbz-qt/src/local_album_actions.rs +++ b/crates/qbz-qt/src/local_album_actions.rs @@ -964,9 +964,9 @@ fn publish_doc(doc: Option) { /// "Play next" / "Play later" / "Add to queue" over a track SUBSET — the same /// core helpers `local_playback::enqueue` uses, just without the id round-trip. /// -/// QConnect EXEMPT (contract §6.3): no routed arm / sync-on-add tail — a -/// local-only batch is never Qobuz-castable, so the predicate is always false -/// (Slint local_album_actions.rs:486-494 is likewise unhooked). +/// The shared enqueue seam runs before any core mutation. While QConnect is +/// enabled it drops this local-only batch, raises the single counted notice, +/// and leaves the existing queue untouched. async fn enqueue_rows(runtime: &Runtime, tracks: Vec, mode: &str) { let tracks = tokio::task::spawn_blocking(move || { let mut tracks = tracks; @@ -976,6 +976,7 @@ async fn enqueue_rows(runtime: &Runtime, tracks: Vec, mode: &str) { .await .unwrap_or_default(); let queue: Vec = tracks.iter().map(local_queue_track).collect(); + let queue = crate::playback_qt::stamped(queue, None); if queue.is_empty() { return; } diff --git a/crates/qbz-qt/src/local_bulk.rs b/crates/qbz-qt/src/local_bulk.rs index 6dc13e133..b76f09c32 100644 --- a/crates/qbz-qt/src/local_bulk.rs +++ b/crates/qbz-qt/src/local_bulk.rs @@ -296,9 +296,9 @@ pub(crate) async fn apply(rows: Vec, action: &str) -> bool { /// a multi-row insert keeps its order, "play-later" appends to the manual /// block's tail, anything else appends. /// -/// QConnect EXEMPT (contract §6.3): no routed arm / sync-on-add tail — a -/// local-only batch is never Qobuz-castable, so the predicate is always false -/// (Slint local_bulk.rs:261-269 is likewise unhooked). +/// The shared enqueue seam runs before any core mutation. While QConnect is +/// enabled it drops this local-only batch, raises the single counted notice, +/// and leaves the existing queue untouched. async fn enqueue_rows(rows: Vec, mode: &str) { let runtime = crate::app(); // Same folder-cover backfill the single-row path runs @@ -313,6 +313,10 @@ async fn enqueue_rows(rows: Vec, mode: &str) { .await .unwrap_or_default(); let queue: Vec = rows.iter().map(local_queue_track).collect(); + let queue = crate::playback_qt::stamped(queue, None); + if queue.is_empty() { + return; + } log::info!("[qbz-qt] local bulk {mode}: {} track(s)", queue.len()); let Some(_owner_action) = crate::playback_qt::begin_owner_action() else { return; diff --git a/crates/qbz-qt/src/local_playback.rs b/crates/qbz-qt/src/local_playback.rs index 2a496a06c..9d698d3e8 100644 --- a/crates/qbz-qt/src/local_playback.rs +++ b/crates/qbz-qt/src/local_playback.rs @@ -816,6 +816,9 @@ pub(crate) async fn enqueue_rows(runtime: &Runtime, tracks: Vec, mod // Same stamping seam the Qobuz enqueue paths use, so an appended local // block carries its own origin instead of inheriting whatever is playing. let queue = crate::playback_qt::stamped(tracks.iter().map(local_queue_track).collect(), None); + if queue.is_empty() { + return; + } let Some(_owner_action) = crate::playback_qt::begin_owner_action() else { return; }; @@ -823,11 +826,9 @@ pub(crate) async fn enqueue_rows(runtime: &Runtime, tracks: Vec, mod // (reversed so a multi-track insert keeps its order), "later" appends to // the block tail, anything else appends. // - // QConnect EXEMPT (contract §6.3): no routed arm and no sync-on-add tail - // here — this is a LOCAL-only path, so `batch_all_qconnect_castable` is - // always false and the push would never fire; hooking the arm would only - // risk the refusal toast on every click (Slint local_playback.rs:437-450 - // is likewise unhooked). + // This remains a local-only execution path. While QConnect is enabled the + // shared seam above returns an empty batch after raising the counted + // notice, so no local row can enter the connected queue here. match mode.as_str() { "next" => { for t in queue.into_iter().rev() { diff --git a/crates/qbz-qt/src/local_playlist_qt.rs b/crates/qbz-qt/src/local_playlist_qt.rs index dfcae72ee..42741a3aa 100644 --- a/crates/qbz-qt/src/local_playlist_qt.rs +++ b/crates/qbz-qt/src/local_playlist_qt.rs @@ -1437,6 +1437,9 @@ pub async fn enqueue_all(runtime: &Runtime, mode: &str) -> Result<(), String> { queue, crate::playback_qt::PlayContext::playlist(&playlist_id), ); + if queue.is_empty() { + return Ok(()); + } crate::playback_qt::enqueue_track_list_mode(runtime, queue, mode).await } diff --git a/crates/qbz-qt/src/myqbz_play_qt.rs b/crates/qbz-qt/src/myqbz_play_qt.rs index f5c0f7319..cbac4a6c4 100644 --- a/crates/qbz-qt/src/myqbz_play_qt.rs +++ b/crates/qbz-qt/src/myqbz_play_qt.rs @@ -779,41 +779,40 @@ pub(crate) fn play_inline_track(item_source_item_id: String, track_id: String, a crate::queue_qt::publish(&runtime).await; } InlineTrackMode::PlayNext => { - let mut stamped = crate::playback_qt::stamped(vec![track], None); - if let Some(track) = stamped.pop() { - // QConnect CONTROLLER mode (§7): route the insert to the - // peer's queue — early-returns when handled (stamped - // first: a blacklisted track must not reach the peer when - // the local path would drop it). - if crate::playback_qt::route_track_to_peer(&track, "next").await { - return; - } - let added_castable = crate::playback_qt::batch_all_qconnect_castable( - std::slice::from_ref(&track), - ); - runtime.core().add_track_next(track).await; - crate::playback_qt::sync_qconnect_after_add(added_castable).await; + let Some(track) = crate::playback_qt::stamped(vec![track], None).pop() else { + return; + }; + // QConnect CONTROLLER mode (§7): route the insert to the + // peer's queue — early-returns when handled (stamped first: a + // blocked track must not reach the peer when the local path + // would drop it). + if crate::playback_qt::route_track_to_peer(&track, "next").await { + return; } + let added_castable = crate::playback_qt::batch_all_qconnect_castable( + std::slice::from_ref(&track), + ); + runtime.core().add_track_next(track).await; + crate::playback_qt::sync_qconnect_after_add(added_castable).await; crate::queue_qt::publish(&runtime).await; crate::toast_qt::success(qbz_i18n::t("Playing next")); } InlineTrackMode::PlayLater => { - let mut stamped = crate::playback_qt::stamped(vec![track], None); - if let Some(track) = stamped.pop() { - // QConnect CONTROLLER mode (§7): route the add to the - // peer's queue. Mode "queue", NOT "later": the local op - // here appends via `add_tracks` (the documented inline/row - // divergence above), so the route matches what the LOCAL - // path does. - if crate::playback_qt::route_track_to_peer(&track, "queue").await { - return; - } - let added_castable = crate::playback_qt::batch_all_qconnect_castable( - std::slice::from_ref(&track), - ); - runtime.core().add_tracks(vec![track]).await; - crate::playback_qt::sync_qconnect_after_add(added_castable).await; + let Some(track) = crate::playback_qt::stamped(vec![track], None).pop() else { + return; + }; + // QConnect CONTROLLER mode (§7): route the add to the peer's + // queue. Mode "queue", NOT "later": the local op here appends + // via `add_tracks` (the documented inline/row divergence + // above), so the route matches what the LOCAL path does. + if crate::playback_qt::route_track_to_peer(&track, "queue").await { + return; } + let added_castable = crate::playback_qt::batch_all_qconnect_castable( + std::slice::from_ref(&track), + ); + runtime.core().add_tracks(vec![track]).await; + crate::playback_qt::sync_qconnect_after_add(added_castable).await; crate::queue_qt::publish(&runtime).await; crate::toast_qt::success(qbz_i18n::t("Added to queue")); } diff --git a/crates/qbz-qt/src/playback_qt.rs b/crates/qbz-qt/src/playback_qt.rs index 69ce69b15..64ef4bf12 100644 --- a/crates/qbz-qt/src/playback_qt.rs +++ b/crates/qbz-qt/src/playback_qt.rs @@ -779,7 +779,7 @@ pub(crate) fn queue_track_unavailable(track: &QueueTrack) -> bool { dead && !crate::offline_qt::is_cached_id(track.id) } -/// Why rows were dropped, counted per reason. The two are NOT interchangeable +/// Why rows were dropped, counted per reason. The reasons are NOT interchangeable /// and must not collapse into one number: a blacklist drop is what the user /// asked for and stays SILENT, while an unavailability drop is news they never /// asked for and owes them a toast (D4 — "el usuario siempre debe saber"). One @@ -790,6 +790,9 @@ pub(crate) struct QueueDrops { pub blacklisted: usize, /// Dropped because Qobuz pulled the track AND we hold no offline copy. pub unavailable: usize, + /// Dropped while QConnect is enabled because its source is not resolvable + /// by Qobuz. These rows never enter the local queue in that mode. + pub qconnect_unresolvable: usize, } /// The ONE toast a queue build owes when it silently shortened itself @@ -829,17 +832,19 @@ fn toast_unavailable_dropped(count: usize) { /// itself dropped, the walk lands on the next survivor, which is what the user /// asking for "play from here" means once "here" is gone. /// -/// Renamed from `filter_blacklisted_queue`: it now drops for two reasons and +/// Renamed from `filter_blacklisted_queue`: it now drops for three reasons and /// the old name named only one of them. fn filter_unplayable_queue( tracks: Vec, start: Option, ) -> (Vec, Option, QueueDrops) { + let qconnect_enabled = crate::qconnect_qt::queue_admission_enabled(); let (kept, start, dropped) = filter_queue_with( tracks, start, queue_track_blacklisted, queue_track_unavailable, + |track| qconnect_enabled && !crate::qconnect_qt::is_qconnect_queue_track(track), ); if dropped.blacklisted > 0 { log::info!( @@ -853,26 +858,33 @@ fn filter_unplayable_queue( dropped.unavailable ); } + if dropped.qconnect_unresolvable > 0 { + log::info!( + "[qbz-qt] qconnect admission: dropped {} unresolvable track(s) from the queue", + dropped.qconnect_unresolvable + ); + } (kept, start, dropped) } /// The pure half, split out so the index remap is unit-testable without a bound -/// session (the blacklist store needs one). The two predicates decide; +/// session (the blacklist store needs one). The three predicates decide; /// everything else is arithmetic, and that arithmetic is unchanged. /// -/// TWO predicates, not one OR'd closure, because the caller has to know WHICH +/// Separate predicates, not one OR'd closure, because the caller has to know WHICH /// one claimed each row (see [`QueueDrops`]). `blacklisted` is tested FIRST and /// wins ties: a pulled track by an artist the user blocked is a row they /// already chose not to see, and toasting "1 track skipped" for it would /// announce exactly the content the blacklist exists to hide. /// /// The log line that used to live here moved to `filter_unplayable_queue`: it -/// said "blacklist", which a second reason turns into a lie. +/// said "blacklist", which any additional reason turns into a lie. fn filter_queue_with( tracks: Vec, start: Option, blacklisted: impl Fn(&T) -> bool, unavailable: impl Fn(&T) -> bool, + qconnect_unresolvable: impl Fn(&T) -> bool, ) -> (Vec, Option, QueueDrops) { let clicked = start.unwrap_or(0); let mut kept = Vec::with_capacity(tracks.len()); @@ -888,6 +900,10 @@ fn filter_queue_with( dropped.unavailable += 1; continue; } + if qconnect_unresolvable(&track) { + dropped.qconnect_unresolvable += 1; + continue; + } if new_start.is_none() && i >= clicked { new_start = Some(kept.len()); } @@ -938,6 +954,7 @@ pub(crate) struct PreparedQueue { start: Option, anchor: Option, unavailable_dropped: usize, + qconnect_unresolvable_dropped: usize, } impl PreparedQueue { @@ -959,12 +976,14 @@ pub(crate) fn prepare_queue_stamped( let (mut tracks, start, dropped) = filter_unplayable_queue(tracks, start); if tracks.is_empty() && asked > 0 { log::info!( - "[qbz-qt] set_queue: all {asked} track(s) filtered ({} blacklisted, {} unavailable) \ + "[qbz-qt] set_queue: all {asked} track(s) filtered ({} blacklisted, {} unavailable, {} qconnect-unresolvable) \ — keeping the previous queue", dropped.blacklisted, - dropped.unavailable + dropped.unavailable, + dropped.qconnect_unresolvable ); toast_unavailable_dropped(dropped.unavailable); + crate::qconnect_qt::toast_unresolvable_tracks(dropped.qconnect_unresolvable); return None; } stamp_context(&mut tracks, context); @@ -980,6 +999,7 @@ pub(crate) fn prepare_queue_stamped( start, anchor, unavailable_dropped: dropped.unavailable, + qconnect_unresolvable_dropped: dropped.qconnect_unresolvable, }) } @@ -1006,12 +1026,14 @@ async fn commit_prepared_queue_with_offline_only( start, anchor, unavailable_dropped, + qconnect_unresolvable_dropped, } = prepared; runtime .core() .set_queue_with_offline_only(tracks, start, offline_only) .await; toast_unavailable_dropped(unavailable_dropped); + crate::qconnect_qt::toast_unresolvable_tracks(qconnect_unresolvable_dropped); if let Some(svc) = crate::qconnect_qt::service() { svc.sync_local_queue_if_changed().await; } @@ -1067,6 +1089,7 @@ pub(crate) fn stamped(tracks: Vec, context: Option) -> // in the list must not be reachable by dragging it into the queue either. // No start index to remap here — these APPEND. let mut dropped = QueueDrops::default(); + let qconnect_enabled = crate::qconnect_qt::queue_admission_enabled(); let mut tracks: Vec = tracks .into_iter() .filter(|t| { @@ -1078,6 +1101,10 @@ pub(crate) fn stamped(tracks: Vec, context: Option) -> dropped.unavailable += 1; return false; } + if qconnect_enabled && !crate::qconnect_qt::is_qconnect_queue_track(t) { + dropped.qconnect_unresolvable += 1; + return false; + } true }) .collect(); @@ -1093,11 +1120,18 @@ pub(crate) fn stamped(tracks: Vec, context: Option) -> dropped.unavailable ); } + if dropped.qconnect_unresolvable > 0 { + log::info!( + "[qbz-qt] qconnect admission: dropped {} unresolvable track(s) from an enqueue", + dropped.qconnect_unresolvable + ); + } // Idempotent with the seam below it: `myqbz_play_qt` stamps and THEN calls // `set_queue_stamped`, whose second pass finds nothing left to drop and so // raises no second toast. That module's existing "both passes are // idempotent" comment stays true. toast_unavailable_dropped(dropped.unavailable); + crate::qconnect_qt::toast_unresolvable_tracks(dropped.qconnect_unresolvable); stamp_context(&mut tracks, context); warn_dead_context(&tracks, "enqueue"); tracks @@ -1109,22 +1143,13 @@ pub(crate) fn stamped(tracks: Vec, context: Option) -> // --------------------------------------------------------------------------- /// QConnect sync-on-add predicate (#442, playback.rs:4082-4096): true when -/// EVERY track of an added batch is Qobuz-castable (mirrors -/// `sync_local_queue_if_changed`'s all-or-nothing admission — `local` / -/// `plex` refused, offline `qobuz_download` eligible). A non-castable batch -/// skips the post-add push so a local/plex add never trips the refusal toast -/// on every click; the next track tick already surfaces that state. +/// every surviving row uses a Qobuz-resolvable provenance. The shared enqueue +/// seam normally guarantees this while QConnect is enabled; this remains a +/// defensive gate for callers running while it is disabled or starting up. pub(crate) fn batch_all_qconnect_castable(tracks: &[QueueTrack]) -> bool { - tracks.iter().all(|qt| { - qt.id > 0 - && !matches!( - qt.source - .as_deref() - .map(|s| s.to_ascii_lowercase()) - .as_deref(), - Some("local") | Some("plex") - ) - }) + tracks + .iter() + .all(crate::qconnect_qt::is_qconnect_queue_track) } /// QConnect sync-on-add (#442, playback.rs:4098-4111): after a local queue @@ -1979,8 +2004,8 @@ pub async fn enqueue_album( _ => runtime.core().add_tracks(tracks).await, } // QConnect sync-on-add (#442): push the updated queue to the session so a - // connected controller sees the new items; skipped silently for a - // non-castable batch (self-gating when a peer owns playback). + // connected controller sees the surviving items (self-gating when a peer + // owns playback). sync_qconnect_after_add(added_castable).await; publish_queue(runtime).await; Ok(()) @@ -2369,8 +2394,8 @@ pub async fn enqueue_track_list_mode( } _ => runtime.core().add_tracks(tracks).await, } - // QConnect sync-on-add (#442): push the updated queue to the session; - // skipped silently for a non-castable batch. + // QConnect sync-on-add (#442): push the updated surviving queue to the + // session. sync_qconnect_after_add(added_castable).await; publish_queue(runtime).await; Ok(()) @@ -5170,8 +5195,13 @@ mod tests { /// the one the user clicked — silently, and only when something was blocked. #[test] fn start_index_follows_the_clicked_track() { - let (kept, start, _) = - filter_queue_with(vec![0, 1, 2, 3, 4], Some(2), |n| n % 2 == 1, |_| false); + let (kept, start, _) = filter_queue_with( + vec![0, 1, 2, 3, 4], + Some(2), + |n| n % 2 == 1, + |_| false, + |_| false, + ); assert_eq!(kept, vec![0, 2, 4]); assert_eq!(start, Some(1)); // the 2 moved from index 2 to index 1 } @@ -5179,8 +5209,13 @@ mod tests { /// Clicking a row that is itself blocked lands on the next survivor. #[test] fn a_blocked_clicked_row_falls_forward() { - let (kept, start, _) = - filter_queue_with(vec![0, 1, 2, 3], Some(1), |n| n % 2 == 1, |_| false); + let (kept, start, _) = filter_queue_with( + vec![0, 1, 2, 3], + Some(1), + |n| n % 2 == 1, + |_| false, + |_| false, + ); assert_eq!(kept, vec![0, 2]); assert_eq!(start, Some(1)); // the 1 was dropped, so start on the 2 } @@ -5189,8 +5224,13 @@ mod tests { /// (an out-of-range index is what makes the core start nothing at all). #[test] fn a_fully_blocked_tail_clamps_to_the_last_survivor() { - let (kept, start, _) = - filter_queue_with(vec![0, 1, 3, 5], Some(2), |n| n % 2 == 1, |_| false); + let (kept, start, _) = filter_queue_with( + vec![0, 1, 3, 5], + Some(2), + |n| n % 2 == 1, + |_| false, + |_| false, + ); assert_eq!(kept, vec![0]); assert_eq!(start, Some(0)); } @@ -5198,7 +5238,8 @@ mod tests { /// Everything blocked: an empty queue carries NO start index. #[test] fn everything_blocked_yields_no_start() { - let (kept, start, _) = filter_queue_with(vec![1, 3, 5], Some(1), |n| n % 2 == 1, |_| false); + let (kept, start, _) = + filter_queue_with(vec![1, 3, 5], Some(1), |n| n % 2 == 1, |_| false, |_| false); assert!(kept.is_empty()); assert_eq!(start, None); } @@ -5207,7 +5248,8 @@ mod tests { /// user without a blacklist takes. #[test] fn nothing_blocked_is_identity() { - let (kept, start, _) = filter_queue_with(vec![0, 2, 4], Some(2), |_| false, |_| false); + let (kept, start, _) = + filter_queue_with(vec![0, 2, 4], Some(2), |_| false, |_| false, |_| false); assert_eq!(kept, vec![0, 2, 4]); assert_eq!(start, Some(2)); } @@ -5215,7 +5257,7 @@ mod tests { /// Acceptance §8-5: a build containing dead tracks drops them AND re-maps /// the start index to the track the user actually clicked. Same arithmetic /// as the blacklist, different predicate — which is why the helper took a - /// second closure instead of a rewrite. + /// dedicated closure instead of a rewrite. #[test] fn unavailable_rows_drop_and_remap_the_start_index() { // Rows 1 and 3 are "pulled"; the user clicked row 4. @@ -5224,6 +5266,7 @@ mod tests { Some(4), |_| false, |n| *n == 1 || *n == 3, + |_| false, ); assert_eq!(kept, vec![0, 2, 4]); assert_eq!(start, Some(2)); // the 4 moved from index 4 to index 2 @@ -5236,8 +5279,13 @@ mod tests { /// news. A single counter would force one policy on both. #[test] fn the_two_drop_reasons_are_counted_separately() { - let (kept, _, dropped) = - filter_queue_with(vec![0, 1, 2, 3], Some(0), |n| *n == 1, |n| *n == 2); + let (kept, _, dropped) = filter_queue_with( + vec![0, 1, 2, 3], + Some(0), + |n| *n == 1, + |n| *n == 2, + |_| false, + ); assert_eq!(kept, vec![0, 3]); assert_eq!(dropped.blacklisted, 1); assert_eq!(dropped.unavailable, 1); @@ -5248,12 +5296,29 @@ mod tests { /// content the blacklist exists to keep off their screen. #[test] fn blacklist_wins_the_tie_and_stays_silent() { - let (kept, _, dropped) = filter_queue_with(vec![0, 1], Some(0), |n| *n == 1, |n| *n == 1); + let (kept, _, dropped) = + filter_queue_with(vec![0, 1], Some(0), |n| *n == 1, |n| *n == 1, |_| false); assert_eq!(kept, vec![0]); assert_eq!(dropped.blacklisted, 1); assert_eq!(dropped.unavailable, 0); } + #[test] + fn qconnect_unresolvable_rows_drop_and_remap_the_start_index() { + let (kept, start, dropped) = filter_queue_with( + vec![0, 1, 2, 3, 4], + Some(3), + |_| false, + |_| false, + |n| *n == 1 || *n == 3, + ); + assert_eq!(kept, vec![0, 2, 4]); + assert_eq!(start, Some(2)); + assert_eq!(dropped.qconnect_unresolvable, 2); + assert_eq!(dropped.blacklisted, 0); + assert_eq!(dropped.unavailable, 0); + } + #[test] fn song_card_near_fit_keeps_the_final_glyphs_instead_of_an_ellipsis() { // TextMetrics.width is a painted bounding box, while the line layout diff --git a/crates/qbz-qt/src/playlist_qt.rs b/crates/qbz-qt/src/playlist_qt.rs index ae67aa68a..5ad76f3dd 100644 --- a/crates/qbz-qt/src/playlist_qt.rs +++ b/crates/qbz-qt/src/playlist_qt.rs @@ -2225,6 +2225,9 @@ pub async fn enqueue_all( mode: &str, ) -> Result<(), String> { let tracks = crate::playback_qt::stamped(current_queue(), open_context()); + if tracks.is_empty() { + return Ok(()); + } crate::playback_qt::enqueue_track_list_mode(runtime, tracks, mode).await } diff --git a/crates/qbz-qt/src/qconnect_qt.rs b/crates/qbz-qt/src/qconnect_qt.rs index 485142c8a..5f2be9b81 100644 --- a/crates/qbz-qt/src/qconnect_qt.rs +++ b/crates/qbz-qt/src/qconnect_qt.rs @@ -103,23 +103,69 @@ type Runtime = Arc>; /// download is still the same catalog id and is eligible; every server/file /// source is not, even when its numeric id happens to look like a Qobuz id. pub(crate) fn is_qconnect_queue_track(track: &qbz_models::QueueTrack) -> bool { - if track.id == 0 { - return false; + qconnect_app::qconnect_queue_track_is_resolvable(track) +} + +/// Queue admission follows the user's enabled intent, not the transient +/// transport badge. Otherwise a reconnect window can admit local rows that +/// poison the next cloud sync even though QConnect was never turned off. +pub(crate) fn queue_admission_enabled() -> bool { + service().is_some_and(|service| service.has_enabled_intent()) +} + +/// One user-facing notice per queue action, pluralized across all locales. +/// The caller owns batching; this helper never emits once per row. +pub(crate) fn toast_unresolvable_tracks(count: usize) { + if count == 0 { + return; } - match track - .source - .as_deref() - .map(str::trim) - .filter(|source| !source.is_empty()) - { - Some(source) => matches!( - source.to_ascii_lowercase().as_str(), - "qobuz" | "qobuz_download" | "qobuz_purchase" | "offline" - ), - // Legacy catalog rows predate the source stamp. Their explicit - // non-local bit is the compatibility discriminator. - None => !track.is_local, + crate::toast_qt::info(qbz_i18n::tf( + "Qobuz Connect can't resolve local tracks. {} track was skipped and wasn't added to the queue. Turn off Qobuz Connect to play it.", + "Qobuz Connect can't resolve local tracks. {} tracks were skipped and weren't added to the queue. Turn off Qobuz Connect to play them.", + count as i64, + &[&count.to_string()], + )); +} + +fn resolvable_track_ids(tracks: &[(u64, Option)]) -> (Vec, usize) { + let mut kept = Vec::with_capacity(tracks.len()); + let mut dropped = 0; + for (track_id, source) in tracks { + if qconnect_app::qconnect_source_is_resolvable(*track_id, source.as_deref()) { + kept.push(*track_id); + } else { + dropped += 1; + } } + (kept, dropped) +} + +/// Defensive projection for queues that predate the admission seam (session +/// restore, an older build, or an internal caller). Keeps catalog order and +/// maps the old cursor onto the first surviving row at/after it, falling back +/// to the last survivor when the remainder of the queue was local-only. +fn resolvable_queue_projection( + tracks: &[qbz_models::QueueTrack], + start: Option, +) -> (Vec, Option, usize) { + let clicked = start.unwrap_or(0); + let mut kept = Vec::with_capacity(tracks.len()); + let mut new_start = None; + let mut dropped = 0; + for (index, track) in tracks.iter().enumerate() { + if !is_qconnect_queue_track(track) { + dropped += 1; + continue; + } + if new_start.is_none() && index >= clicked { + new_start = Some(kept.len()); + } + kept.push(track.id); + } + if new_start.is_none() && !kept.is_empty() { + new_start = Some(kept.len() - 1); + } + (kept, new_start, dropped) } // --------------------------------------------------------------------------- @@ -138,17 +184,6 @@ pub(crate) fn is_qconnect_queue_track(track: &qbz_models::QueueTrack) -> bool { // --------------------------------------------------------------------------- pub(crate) mod publish { use cxx_qt_lib::QString; - use std::sync::atomic::{AtomicBool, Ordering}; - - /// Rust-side mirror of the bridge bit. Queue projections are assembled off - /// the Qt thread, so they cannot read `QbzQConnect.qconnectConnected` - /// directly. Keeping the mirror at the one publish funnel makes the QML - /// greyout and the Rust action guards agree on the same session edge. - static CONNECTED: AtomicBool = AtomicBool::new(false); - - pub(crate) fn is_connected() -> bool { - CONNECTED.load(Ordering::SeqCst) - } /// One device-picker row (the Slint `QconnectDevice` struct), serialized /// onto `QbzQConnect.devices_json` by [`devices`] (same JSON precedent as @@ -167,7 +202,6 @@ pub(crate) mod publish { /// `NowPlayingState.qconnect-connected` -> `QbzQConnect.qconnect_connected` /// (the golden ConnectButton badge). pub(crate) fn connected(connected: bool) { - CONNECTED.store(connected, Ordering::SeqCst); crate::qconnect_bridge::ui(move |mut b| { b.as_mut().set_qconnect_connected(connected); }); @@ -2058,10 +2092,10 @@ impl QtQconnectService { /// /// Echo-safe by construction: the inbound materialize path never calls this, /// and we skip when the local queue already equals the cloud's last-applied - /// queue OR the last queue we pushed. Admission mirrors the webplayer's - /// `assessQconnectQueueSync` — all-or-nothing: a queue containing any local / - /// Plex track is refused whole (a renderer can only play Qobuz catalog ids; - /// offline qobuz_download IS eligible — its id is the real Qobuz id). + /// queue OR the last queue we pushed. Admission normally happened before + /// the core queue mutation. A defensive + /// projection here also repairs restored/legacy mixed queues instead of + /// refusing the whole cloud update. pub async fn sync_local_queue_if_changed(&self) { let Ok(Some(_runtime_action)) = self.begin_runtime_action_if_running() else { return; @@ -2094,7 +2128,7 @@ impl QtQconnectService { if tracks.is_empty() { return; } - let ordered_ids: Vec = tracks.iter().map(|track| track.id).collect(); + let source_ordered_ids: Vec = tracks.iter().map(|track| track.id).collect(); // Echo-suppress: skip when this is the cloud's current queue (materialized // inbound) so our own adoption / a remote queue change never bounces back. @@ -2106,7 +2140,7 @@ impl QtQconnectService { .iter() .map(|item| item.track_id) .collect(); - if applied_ids == ordered_ids { + if applied_ids == source_ordered_ids { return; } } @@ -2114,25 +2148,30 @@ impl QtQconnectService { // ...and skip when we already pushed this exact queue (cloud echo pending). { let guard = lock_inner(&self.inner); - if guard.last_pushed_queue_ids.as_deref() == Some(ordered_ids.as_slice()) { + if guard.last_pushed_queue_ids.as_deref() == Some(source_ordered_ids.as_slice()) { return; } } - // Admission: refuse the whole push if any track isn't Qobuz-castable. - let all_eligible = tracks.iter().all(is_qconnect_queue_track); - if !all_eligible { - log::info!("[QConnect] Local queue has non-Qobuz tracks; not casting to Connect"); - crate::toast_qt::error(qbz_i18n::t("Mixed queue — not cast to Qobuz Connect")); - dev_push_event("-> queue push REFUSED (mixed/non-Qobuz)".to_string()); - // Remember it so we don't re-toast on every track tick within this queue. - lock_inner(&self.inner).last_pushed_queue_ids = Some(ordered_ids); + let (ordered_ids, projected_start, dropped) = + resolvable_queue_projection(&tracks, current_index); + if dropped > 0 { + log::info!( + "[QConnect] Queue projection skipped {dropped} non-Qobuz track(s) before cloud sync" + ); + toast_unresolvable_tracks(dropped); + dev_push_event(format!( + "-> queue projection skipped {dropped} non-Qobuz track(s)" + )); + } + if ordered_ids.is_empty() { + lock_inner(&self.inner).last_pushed_queue_ids = Some(source_ordered_ids); return; } let count = ordered_ids.len(); let track_ids: Vec = ordered_ids.iter().map(|id| *id as i64).collect(); - let start_index = current_index.unwrap_or(0); + let start_index = projected_start.unwrap_or(0); let payload = json!({ "track_ids": track_ids, "queue_position": start_index, @@ -2153,7 +2192,7 @@ impl QtQconnectService { dev_push_event(format!( "-> QueueLoadTracks {count} tracks start={start_index}" )); - lock_inner(&self.inner).last_pushed_queue_ids = Some(ordered_ids); + lock_inner(&self.inner).last_pushed_queue_ids = Some(source_ordered_ids); } Err(err) => log::warn!("[QConnect] Failed to push local queue: {err}"), } @@ -2168,13 +2207,9 @@ impl QtQconnectService { /// Unlike `sync_local_queue_if_changed`, the queue push here is /// UNCONDITIONAL (no echo-gate, no is_local_renderer_active gate) — the user /// just issued a fresh play, so the current core queue IS what should run on - /// the peer. Admission is the SAME all-or-nothing rule: a queue containing - /// any local / Plex track is refused whole (a renderer can only play Qobuz - /// catalog ids; offline qobuz_download IS eligible). On refusal it toasts and - /// returns `true` (handled — do NOT fall back to playing a mixed queue - /// locally that we just declined to cast). On any send error it logs and - /// still returns `true` (a peer owns playback; falling back to local audio - /// would double-play). + /// the peer. Any legacy non-Qobuz rows are projected out while preserving + /// order and cursor. On any send error it logs and still returns `true` (a + /// peer owns playback; falling back to local audio would double-play). pub async fn play_on_peer_if_active(&self, track_id: u64) -> bool { let (app, sync_state) = { let guard = lock_inner(&self.inner); @@ -2192,9 +2227,8 @@ impl QtQconnectService { } // D8 guard: an offline-only-playlist queue is never pushed to the - // cloud. Returning false lets the play proceed LOCALLY (unlike the - // mixed-queue refusal below, local playback of these tracks is fine — - // the prohibition is only on the cloud push). + // cloud. Returning false lets the play proceed LOCALLY; playback of + // these tracks is fine, the prohibition is only on the cloud push. if self.runtime.core().queue_is_offline_only() { log::info!( "[QConnect] queue is from an offline-only playlist; not routing to peer renderer" @@ -2207,23 +2241,24 @@ impl QtQconnectService { if tracks.is_empty() { return false; } - let ordered_ids: Vec = tracks.iter().map(|track| track.id).collect(); - - // Admission: refuse the whole push if any track isn't Qobuz-castable. - let all_eligible = tracks.iter().all(is_qconnect_queue_track); - if !all_eligible { - log::info!("[QConnect] Local queue has non-Qobuz tracks; not casting to Connect"); - crate::toast_qt::error(qbz_i18n::t("Mixed queue — not cast to Qobuz Connect")); - dev_push_event("-> queue push REFUSED (mixed/non-Qobuz)".to_string()); - // Remember it so the poll loop's sync doesn't re-toast this queue. - lock_inner(&self.inner).last_pushed_queue_ids = Some(ordered_ids); - // Handled: do NOT play a refused queue locally. + let source_ordered_ids: Vec = tracks.iter().map(|track| track.id).collect(); + let (ordered_ids, projected_start, dropped) = + resolvable_queue_projection(&tracks, current_index); + if dropped > 0 { + log::info!("[QConnect] play_on_peer projected out {dropped} non-Qobuz track(s)"); + toast_unresolvable_tracks(dropped); + dev_push_event(format!( + "-> play_on_peer skipped {dropped} non-Qobuz track(s)" + )); + } + if ordered_ids.is_empty() || !ordered_ids.contains(&track_id) { + lock_inner(&self.inner).last_pushed_queue_ids = Some(source_ordered_ids); return true; } let count = ordered_ids.len(); let track_ids: Vec = ordered_ids.iter().map(|id| *id as i64).collect(); - let start_index = current_index.unwrap_or(0); + let start_index = projected_start.unwrap_or(0); let payload = json!({ "track_ids": track_ids, "queue_position": start_index, @@ -2244,7 +2279,7 @@ impl QtQconnectService { dev_push_event(format!( "-> play_on_peer QueueLoadTracks {count} start={start_index}" )); - lock_inner(&self.inner).last_pushed_queue_ids = Some(ordered_ids); + lock_inner(&self.inner).last_pushed_queue_ids = Some(source_ordered_ids); } Err(err) => { log::warn!("[QConnect] play_on_peer: queue push failed: {err}"); @@ -2290,7 +2325,7 @@ impl QtQconnectService { log::info!( "[QConnect] play_next_on_peer: track {track_id} not Qobuz-castable; refusing" ); - crate::toast_qt::error(qbz_i18n::t("Track not castable to Qobuz Connect")); + toast_unresolvable_tracks(1); dev_push_event(format!("-> play_next REFUSED (non-Qobuz track {track_id})")); // Handled: do NOT add a non-castable track to the local queue while a // peer owns playback. @@ -2363,7 +2398,7 @@ impl QtQconnectService { log::info!( "[QConnect] add_to_queue_on_peer: track {track_id} not Qobuz-castable; refusing" ); - crate::toast_qt::error(qbz_i18n::t("Track not castable to Qobuz Connect")); + toast_unresolvable_tracks(1); dev_push_event(format!( "-> add_to_queue REFUSED (non-Qobuz track {track_id})" )); @@ -2394,10 +2429,8 @@ impl QtQconnectService { /// Controller add-to-queue routing for a MULTI-track batch (album / playlist / /// favorites bulk). Same contract as the single-track - /// `add_to_queue_on_peer_if_active`, but admission is ALL-OR-NOTHING: if ANY - /// track in the batch is non-castable (`local` / `plex`), the WHOLE batch is - /// refused (toast + `return true`, nothing routed and nothing added locally) — - /// mirroring the queue-sync's all-or-nothing rule. A single + /// `add_to_queue_on_peer_if_active`. Admission is partial: non-Qobuz rows + /// are counted once and omitted while every resolvable row keeps its order. A single /// `CtrlSrvrQueueAddTracks` carries every id (the protocol `track_ids` is a /// full `Vec`), and the cloud echoes a `QueueUpdated` that /// `materialize_remote_queue` applies locally, so we never mutate the local @@ -2414,22 +2447,22 @@ impl QtQconnectService { return false; } - if let Some((bad_id, _)) = tracks - .iter() - .find(|(id, source)| !self.is_track_castable(*id, source.as_deref())) - { + let (ids_u64, dropped) = resolvable_track_ids(tracks); + if dropped > 0 { log::info!( - "[QConnect] add_to_queue_batch_on_peer: track {bad_id} not Qobuz-castable; refusing whole batch" + "[QConnect] add_to_queue_batch_on_peer: skipped {dropped} non-Qobuz track(s)" ); - crate::toast_qt::error(qbz_i18n::t("Some tracks can't be cast to Qobuz Connect")); + toast_unresolvable_tracks(dropped); dev_push_event(format!( - "-> add_to_queue REFUSED (non-Qobuz track {bad_id} in batch of {})", - tracks.len() + "-> add_to_queue skipped {dropped} non-Qobuz track(s) from batch of {}", + tracks.len(), )); + } + if ids_u64.is_empty() { return true; } - let ids: Vec = tracks.iter().map(|(id, _)| *id as i64).collect(); + let ids: Vec = ids_u64.iter().map(|id| *id as i64).collect(); let count = ids.len(); let payload = json!({ "track_ids": ids, @@ -2453,7 +2486,7 @@ impl QtQconnectService { true } - /// Controller play-next routing for a MULTI-track batch. Same all-or-nothing + /// Controller play-next routing for a MULTI-track batch. Same partial /// admission as `add_to_queue_batch_on_peer_if_active`. The server /// `CtrlSrvrQueueInsertTracks` inserts the whole `track_ids` block right after /// `insert_after` and PRESERVES the list order, so the ids are passed in @@ -2470,18 +2503,16 @@ impl QtQconnectService { return false; } - if let Some((bad_id, _)) = tracks - .iter() - .find(|(id, source)| !self.is_track_castable(*id, source.as_deref())) - { - log::info!( - "[QConnect] play_next_batch_on_peer: track {bad_id} not Qobuz-castable; refusing whole batch" - ); - crate::toast_qt::error(qbz_i18n::t("Some tracks can't be cast to Qobuz Connect")); + let (ids_u64, dropped) = resolvable_track_ids(tracks); + if dropped > 0 { + log::info!("[QConnect] play_next_batch_on_peer: skipped {dropped} non-Qobuz track(s)"); + toast_unresolvable_tracks(dropped); dev_push_event(format!( - "-> play_next REFUSED (non-Qobuz track {bad_id} in batch of {})", - tracks.len() + "-> play_next skipped {dropped} non-Qobuz track(s) from batch of {}", + tracks.len(), )); + } + if ids_u64.is_empty() { return true; } @@ -2498,7 +2529,6 @@ impl QtQconnectService { .and_then(|item| i64::try_from(item.queue_item_id).ok()) }); - let ids_u64: Vec = tracks.iter().map(|(id, _)| *id).collect(); let ids: Vec = ids_u64.iter().map(|id| *id as i64).collect(); let count = ids.len(); let mut payload = json!({ @@ -2576,7 +2606,7 @@ impl QtQconnectService { log::info!( "[QConnect] play_later_on_peer: track {track_id} not Qobuz-castable; refusing" ); - crate::toast_qt::error(qbz_i18n::t("Track not castable to Qobuz Connect")); + toast_unresolvable_tracks(1); dev_push_event(format!( "-> play_later REFUSED (non-Qobuz track {track_id})" )); @@ -2661,7 +2691,7 @@ impl QtQconnectService { } if !self.is_track_castable(track_id, source) { log::info!("[QConnect] insert_at_slot: track {track_id} not Qobuz-castable; refusing"); - crate::toast_qt::error(qbz_i18n::t("Track not castable to Qobuz Connect")); + toast_unresolvable_tracks(1); dev_push_event(format!( "-> insert_at_slot REFUSED (non-Qobuz track {track_id})" )); @@ -2719,8 +2749,8 @@ impl QtQconnectService { } /// Controller play-LATER routing for a MULTI-track batch (#442). Same - /// all-or-nothing admission as `play_next_batch_on_peer_if_active`; the - /// whole block lands after the manual-block tail in NATURAL order (the + /// partial admission as `play_next_batch_on_peer_if_active`; the surviving + /// block lands after the manual-block tail in NATURAL order (the /// server preserves list order), mirroring the local /// `enqueue_queue_tracks_later` semantics. pub async fn play_later_batch_on_peer_if_active( @@ -2734,24 +2764,21 @@ impl QtQconnectService { return false; } - if let Some((bad_id, _)) = tracks - .iter() - .find(|(id, source)| !self.is_track_castable(*id, source.as_deref())) - { - log::info!( - "[QConnect] play_later_batch_on_peer: track {bad_id} not Qobuz-castable; refusing whole batch" - ); - crate::toast_qt::error(qbz_i18n::t("Some tracks can't be cast to Qobuz Connect")); + let (ids_u64, dropped) = resolvable_track_ids(tracks); + if dropped > 0 { + log::info!("[QConnect] play_later_batch_on_peer: skipped {dropped} non-Qobuz track(s)"); + toast_unresolvable_tracks(dropped); dev_push_event(format!( - "-> play_later REFUSED (non-Qobuz track {bad_id} in batch of {})", - tracks.len() + "-> play_later skipped {dropped} non-Qobuz track(s) from batch of {}", + tracks.len(), )); + } + if ids_u64.is_empty() { return true; } let insert_after = self.controller_later_anchor().await; - let ids_u64: Vec = tracks.iter().map(|(id, _)| *id).collect(); let ids: Vec = ids_u64.iter().map(|id| *id as i64).collect(); let count = ids.len(); let mut payload = json!({ @@ -2799,13 +2826,9 @@ impl QtQconnectService { is_peer_renderer_active(&state.session) } - /// Single-track castability check, mirroring `sync_local_queue_if_changed`'s - /// all-or-nothing rule: castable = a positive id whose `source` is not - /// `local` / `plex` (offline `qobuz_download` IS eligible; the default/None - /// is treated as `qobuz`). + /// Single-track form of the shared source-aware admission contract. fn is_track_castable(&self, track_id: u64, source: Option<&str>) -> bool { - let source = source.unwrap_or("qobuz").to_ascii_lowercase(); - track_id > 0 && source != "local" && source != "plex" + qconnect_app::qconnect_source_is_resolvable(track_id, source) } // ----------------------------------------------------------------------- @@ -4435,7 +4458,7 @@ async fn deferred_renderer_join( #[cfg(test)] mod tests { - use super::is_qconnect_queue_track; + use super::{is_qconnect_queue_track, resolvable_queue_projection, resolvable_track_ids}; use qbz_models::QueueTrack; fn track(source: Option<&str>, is_local: bool) -> QueueTrack { @@ -4467,7 +4490,13 @@ mod tests { #[test] fn qconnect_admits_catalog_and_offline_catalog_rows() { - for source in ["qobuz", "qobuz_download", "qobuz_purchase", "offline"] { + for source in [ + "qobuz", + "qobuz_download", + "qobuz_purchase", + "offline", + "qobuz_connect_remote", + ] { assert!( is_qconnect_queue_track(&track(Some(source), true)), "{source}" @@ -4494,6 +4523,33 @@ mod tests { assert!(!is_qconnect_queue_track(&row)); } + #[test] + fn controller_batches_keep_resolvable_rows_in_original_order() { + let tracks = vec![ + (11, Some("qobuz".to_string())), + (12, Some("local".to_string())), + (13, Some("qobuz_connect_remote".to_string())), + (14, Some("jellyfin".to_string())), + (15, Some("qobuz_download".to_string())), + ]; + let (kept, dropped) = resolvable_track_ids(&tracks); + assert_eq!(kept, vec![11, 13, 15]); + assert_eq!(dropped, 2); + } + + #[test] + fn defensive_queue_projection_remaps_a_dropped_cursor_forward() { + let tracks = vec![ + track(Some("qobuz"), false), + track(Some("local"), true), + track(Some("qobuz_connect_remote"), false), + ]; + let (kept, start, dropped) = resolvable_queue_projection(&tracks, Some(1)); + assert_eq!(kept, vec![42, 42]); + assert_eq!(start, Some(1)); + assert_eq!(dropped, 1); + } + #[test] fn cast_teardown_replaces_only_the_exact_enabled_intent() { let source = include_str!("qconnect_qt.rs"); diff --git a/crates/qbz-qt/src/queue_qt.rs b/crates/qbz-qt/src/queue_qt.rs index 53e4af363..3e8ebb48b 100644 --- a/crates/qbz-qt/src/queue_qt.rs +++ b/crates/qbz-qt/src/queue_qt.rs @@ -830,13 +830,14 @@ async fn play_extended_upcoming( log::warn!("[qbz-qt] queue: upcoming changed during extended activation"); return; } - if crate::qconnect_qt::publish::is_connected() + if crate::qconnect_qt::queue_admission_enabled() && !crate::qconnect_qt::is_qconnect_queue_track(&track) { log::info!( "[qbz-qt] queue: skipped QConnect-incompatible upcoming row {}", track.id ); + crate::qconnect_qt::toast_unresolvable_tracks(1); return; } if let Some(service) = crate::qconnect_qt::service() { @@ -892,13 +893,14 @@ pub async fn play_extended( log::warn!("[qbz-qt] queue: history changed during activation"); return; } - if crate::qconnect_qt::publish::is_connected() + if crate::qconnect_qt::queue_admission_enabled() && !crate::qconnect_qt::is_qconnect_queue_track(&track) { log::info!( "[qbz-qt] queue: skipped QConnect-incompatible history row {}", track.id ); + crate::qconnect_qt::toast_unresolvable_tracks(1); return; } if let Some(service) = crate::qconnect_qt::service() { @@ -1224,13 +1226,17 @@ pub async fn drop_extended( log::warn!("[qbz-qt] queue: history changed during extended drag"); return; } - if crate::qconnect_qt::publish::is_connected() + // Admission follows enabled intent, including reconnect windows; + // otherwise a local history row can enter the queue while the + // transport is down and poison the next cloud sync. + if crate::qconnect_qt::queue_admission_enabled() && !crate::qconnect_qt::is_qconnect_queue_track(&track) { log::info!( "[qbz-qt] queue: skipped QConnect-incompatible history drag {}", track.id ); + crate::qconnect_qt::toast_unresolvable_tracks(1); return; } if let Some(service) = crate::qconnect_qt::service() { diff --git a/crates/qbzd/src/qconnect/publish.rs b/crates/qbzd/src/qconnect/publish.rs index 8dd474b71..af6ece0ae 100644 --- a/crates/qbzd/src/qconnect/publish.rs +++ b/crates/qbzd/src/qconnect/publish.rs @@ -27,7 +27,9 @@ use std::sync::{Arc, Mutex as StdMutex}; use qbz_app::shell::AppRuntime; use qbz_models::CoreEvent; -use qconnect_app::{is_local_renderer_active, QueueCommandType}; +use qconnect_app::{ + is_local_renderer_active, qconnect_queue_track_is_resolvable, QueueCommandType, +}; use serde_json::json; use tokio::sync::broadcast; use tokio::task::JoinHandle; @@ -128,14 +130,7 @@ pub async fn publish_local_queue_if_changed( } // Admission: refuse the whole push if any track isn't Qobuz-castable. - let all_eligible = tracks.iter().all(|track| { - let source = track - .source - .as_deref() - .unwrap_or("qobuz") - .to_ascii_lowercase(); - source != "local" && source != "plex" && track.id > 0 - }); + let all_eligible = tracks.iter().all(qconnect_queue_track_is_resolvable); if !all_eligible { if !authority.is_current(stamp) { return; diff --git a/crates/qconnect-app/src/lib.rs b/crates/qconnect-app/src/lib.rs index 0ec9646b9..51eedf3e5 100644 --- a/crates/qconnect-app/src/lib.rs +++ b/crates/qconnect-app/src/lib.rs @@ -59,6 +59,7 @@ pub use qconnect_core::{ pub use qconnect_protocol::{ QueueCommandType, RendererBufferState, RendererReport, RendererReportType, }; +pub use renderer::{qconnect_queue_track_is_resolvable, qconnect_source_is_resolvable}; pub use renderer_engine::QconnectRendererEngine; pub use reporting::{ build_renderer_playback_report, qconnect_report_track_id, renderer_buffer_state, diff --git a/crates/qconnect-app/src/renderer.rs b/crates/qconnect-app/src/renderer.rs index 02255472a..306a90a66 100644 --- a/crates/qconnect-app/src/renderer.rs +++ b/crates/qconnect-app/src/renderer.rs @@ -1175,6 +1175,43 @@ mod tests { model_track_to_core_queue_track(&mock_track(id)) } + #[test] + fn qconnect_admission_uses_provenance_and_accepts_materialized_rows() { + for source in [ + "qobuz", + "qobuz_download", + "qobuz_purchase", + "offline", + QCONNECT_REMOTE_QUEUE_SOURCE, + ] { + let mut track = mock_queue_track(7); + track.source = Some(source.to_string()); + track.is_local = source == "qobuz_download"; + assert!(qconnect_queue_track_is_resolvable(&track), "{source}"); + } + + for source in ["local", "plex", "jellyfin", "subsonic", "navidrome"] { + let mut track = mock_queue_track(7); + track.source = Some(source.to_string()); + track.is_local = true; + assert!(!qconnect_queue_track_is_resolvable(&track), "{source}"); + } + } + + #[test] + fn qconnect_admission_legacy_rows_require_non_local_positive_ids() { + let mut track = mock_queue_track(7); + track.source = None; + track.is_local = false; + assert!(qconnect_queue_track_is_resolvable(&track)); + + track.is_local = true; + assert!(!qconnect_queue_track_is_resolvable(&track)); + track.id = 0; + track.is_local = false; + assert!(!qconnect_queue_track_is_resolvable(&track)); + } + fn queue_state( version: QueueVersion, items: Vec, From bb8b627cae45a904d6f27cfaa82f9ec2991b57dc Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 31 Aug 2026 14:12:55 -0600 Subject: [PATCH 3/3] fix(connectivity): use the defined Microsoft NCSI probe cx --- .../qbz-app/src/offline_mode/connectivity.rs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/qbz-app/src/offline_mode/connectivity.rs b/crates/qbz-app/src/offline_mode/connectivity.rs index 659cdd10d..d260c4442 100644 --- a/crates/qbz-app/src/offline_mode/connectivity.rs +++ b/crates/qbz-app/src/offline_mode/connectivity.rs @@ -86,7 +86,11 @@ const PROBES: &[ProbeEndpoint] = &[ expect: ProbeExpect::Status204, }, ProbeEndpoint { - url: "https://www.msftconnecttest.com/connecttest.txt", + // Microsoft NCSI defines this probe as plain HTTP. HTTPS is not a + // supported equivalent: the CDN can answer with an Akamai certificate + // that is not valid for www.msftconnecttest.com, producing a rustls + // error before the strict body check can run. + url: "http://www.msftconnecttest.com/connecttest.txt", expect: ProbeExpect::BodyContains("Microsoft Connect Test"), }, ]; @@ -595,4 +599,21 @@ mod tests { assert!(!ipv6_has_default_route(non_default)); assert!(!ipv6_has_default_route(lo_default)); } + + #[test] + fn microsoft_ncsi_probe_uses_its_defined_http_transport() { + let endpoint = PROBES + .iter() + .find(|endpoint| { + matches!( + endpoint.expect, + ProbeExpect::BodyContains("Microsoft Connect Test") + ) + }) + .expect("Microsoft NCSI probe"); + assert_eq!( + endpoint.url, + "http://www.msftconnecttest.com/connecttest.txt" + ); + } }