From e1138756e64505362a890ccb959de66fee481bf9 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 16:37:25 -0600 Subject: [PATCH 01/10] feat(library): playlist membership index substrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split the snapshot's single timestamp into honest freshness columns (header_updated_at vs membership_synced_at, plus membership_count and remote revision evidence), add authoritative-list generations with a two-generation retirement grace, persist ownership explicitly, and add incremental add/remove/create producers so successful mutations move the snapshot synchronously. New playlist_membership module answers the inverse question — which writable playlists already hold these tracks — over the snapshot, both sidecar tables and local playlists, through a typed PlaylistTrackRef instead of the plex:/id string mangling. All membership tables gain reverse-direction indexes; migrations are probe-then-ALTER with a legacy backfill test. cc --- crates/qbz-library/src/database.rs | 8 + crates/qbz-library/src/lib.rs | 1 + crates/qbz-library/src/local_playlists.rs | 13 + crates/qbz-library/src/playlist_membership.rs | 479 +++++++++++ .../src/qobuz_playlist_snapshot.rs | 807 ++++++++++++++++-- 5 files changed, 1214 insertions(+), 94 deletions(-) create mode 100644 crates/qbz-library/src/playlist_membership.rs diff --git a/crates/qbz-library/src/database.rs b/crates/qbz-library/src/database.rs index 5c04cac02..7328a508b 100644 --- a/crates/qbz-library/src/database.rs +++ b/crates/qbz-library/src/database.rs @@ -264,6 +264,11 @@ impl LibraryDatabase { CREATE INDEX IF NOT EXISTS idx_playlist_local_tracks_playlist ON playlist_local_tracks(qobuz_playlist_id); + -- The Add-to-Playlist picker asks the inverse question — "which + -- playlists hold this track" (playlist_membership.rs). + CREATE INDEX IF NOT EXISTS idx_playlist_local_tracks_track + ON playlist_local_tracks(local_track_id, qobuz_playlist_id); + -- Plex tracks added to playlists. Kept in its own table because -- Plex tracks live on a remote server and have a TEXT rating key, -- not the i64 filesystem id used by local_tracks. No foreign key @@ -282,6 +287,9 @@ impl LibraryDatabase { CREATE INDEX IF NOT EXISTS idx_playlist_plex_tracks_playlist ON playlist_plex_tracks(qobuz_playlist_id); + CREATE INDEX IF NOT EXISTS idx_playlist_plex_tracks_key + ON playlist_plex_tracks(plex_rating_key, qobuz_playlist_id); + -- Custom track order per playlist (user-defined arrangement) CREATE TABLE IF NOT EXISTS playlist_track_custom_order ( id INTEGER PRIMARY KEY, diff --git a/crates/qbz-library/src/lib.rs b/crates/qbz-library/src/lib.rs index 5923b6931..f899e9cd0 100644 --- a/crates/qbz-library/src/lib.rs +++ b/crates/qbz-library/src/lib.rs @@ -37,6 +37,7 @@ pub mod local_playlists; mod metadata; mod models; mod mount_info; +pub mod playlist_membership; pub mod qobuz_playlist_snapshot; pub mod reachability; mod remote_tag_sidecar; diff --git a/crates/qbz-library/src/local_playlists.rs b/crates/qbz-library/src/local_playlists.rs index ff6d1e025..f3ab169a0 100644 --- a/crates/qbz-library/src/local_playlists.rs +++ b/crates/qbz-library/src/local_playlists.rs @@ -154,6 +154,19 @@ pub fn init_schema(conn: &Connection) -> Result<()> { CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_playlist ON local_playlist_tracks(playlist_id, position); + + -- Inverse direction for the Add-to-Playlist picker's containment + -- question (playlist_membership.rs). Partial: each row fills exactly + -- one of the three identity columns. + CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_qobuz + ON local_playlist_tracks(qobuz_track_id, playlist_id) + WHERE qobuz_track_id IS NOT NULL; + CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_path + ON local_playlist_tracks(local_path, playlist_id) + WHERE local_path IS NOT NULL; + CREATE INDEX IF NOT EXISTS idx_local_playlist_tracks_plex + ON local_playlist_tracks(plex_key, playlist_id) + WHERE plex_key IS NOT NULL; "#, )?; // Additive migration (B3): DBs created before the favorite/hidden diff --git a/crates/qbz-library/src/playlist_membership.rs b/crates/qbz-library/src/playlist_membership.rs new file mode 100644 index 000000000..831821f27 --- /dev/null +++ b/crates/qbz-library/src/playlist_membership.rs @@ -0,0 +1,479 @@ +//! The inverse membership question: WHICH playlists already hold this track? +//! +//! The playlist tables were all indexed forward (`playlist_id` leading); +//! the Add-to-Playlist picker asks the opposite direction. This module owns +//! the typed track reference at that boundary — replacing the loosely encoded +//! `"plex:"` / `""` strings — and the containment query across all +//! four membership stores: +//! +//! - `qobuz_playlist_snapshot_tracks` — Qobuz tracks in Qobuz playlists +//! (hydrated by the membership worker; honesty via `index_state`); +//! - `playlist_local_tracks` / `playlist_plex_tracks` — library/Plex sidecars +//! attached to Qobuz playlists (authoritative locally, complete by +//! construction: QBZ is their only writer); +//! - `local_playlist_tracks` — everything inside `local:` playlists (same: +//! locally authoritative). +//! +//! Identity notes. Jellyfin and Subsonic rows reach playlists through their +//! `local_tracks` projection, so their playlist identity IS the library row +//! (`track_id` + the stored path/key) — structurally collision-free across +//! servers because each server's items are distinct projected rows. Plex +//! sidecars store the bare rating key (the Plex merge keeps it in +//! `file_path`); rating keys are scoped to the single configured server, the +//! same assumption the sidecar tables have always made. + +use std::collections::{HashMap, HashSet}; + +use rusqlite::{params, Connection, Result}; + +/// One selected track at the picker/index boundary. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PlaylistTrackRef { + /// A Qobuz catalog track. + Qobuz(u64), + /// A library-projected row: a local file, or a Jellyfin/Subsonic track + /// (their playlist storage identity is the projection). `path` is the + /// `local_tracks.file_path` value local playlists key on. + Library { + track_id: i64, + path: Option, + }, + /// A Plex track by rating key. + Plex { rating_key: String }, +} + +impl PlaylistTrackRef { + /// Build the ref for a library row the way the playlist writers key it: + /// Plex rows carry the rating key in `file_path`; every other source is + /// the projected library row itself. + pub fn from_library_row(source: &str, track_id: i64, file_path: &str) -> Self { + if source == "plex" { + Self::Plex { + rating_key: file_path.to_string(), + } + } else { + Self::Library { + track_id, + path: Some(file_path.to_string()), + } + } + } +} + +/// A playlist that contains at least one of the selected refs. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ContainmentTarget { + Qobuz(u64), + Local(String), +} + +#[derive(Debug, Clone)] +pub struct PlaylistContainment { + pub target: ContainmentTarget, + /// How many DISTINCT selected refs this playlist holds (the picker's + /// "N of M"). Duplicate rows inside a playlist count once. + pub contained: u32, +} + +/// SQLite's default variable cap is 999; stay far under it. +const IN_CHUNK: usize = 400; + +fn placeholders(n: usize) -> String { + let mut s = String::with_capacity(n * 2); + for i in 0..n { + if i > 0 { + s.push(','); + } + s.push('?'); + } + s +} + +/// Every writable playlist containing at least one of `refs`, with the +/// distinct-ref count. Qobuz targets come from the membership snapshot +/// restricted to OWNED, ACTIVE playlists (the strip offers add targets, and a +/// retired header must not resurrect there) plus the sidecar tables; `local:` +/// targets from `local_playlist_tracks`. Whether the Qobuz half may be +/// presented as definitive is `qobuz_playlist_snapshot::index_state`'s call, +/// not this function's. +pub fn playlists_containing( + conn: &Connection, + refs: &[PlaylistTrackRef], +) -> Result> { + // ordinal = position in `refs`; contained counts distinct ordinals. + let mut qobuz_ids: Vec<(i64, usize)> = Vec::new(); + let mut lib_ids: Vec<(i64, usize)> = Vec::new(); + let mut lib_paths: Vec<(&str, usize)> = Vec::new(); + let mut plex_keys: Vec<(&str, usize)> = Vec::new(); + for (ordinal, r) in refs.iter().enumerate() { + match r { + PlaylistTrackRef::Qobuz(id) => qobuz_ids.push((*id as i64, ordinal)), + PlaylistTrackRef::Library { track_id, path } => { + lib_ids.push((*track_id, ordinal)); + if let Some(p) = path { + lib_paths.push((p.as_str(), ordinal)); + } + } + PlaylistTrackRef::Plex { rating_key } => plex_keys.push((rating_key.as_str(), ordinal)), + } + } + + let mut hits: HashMap> = HashMap::new(); + let mut collect_qobuz = |rows: Vec<(i64, usize)>| { + for (pid, ordinal) in rows { + hits.entry(ContainmentTarget::Qobuz(pid as u64)) + .or_default() + .insert(ordinal); + } + }; + + // Qobuz refs → snapshot membership of owned active playlists. + for chunk in qobuz_ids.chunks(IN_CHUNK) { + let sql = format!( + "SELECT t.qobuz_playlist_id, t.track_id + FROM qobuz_playlist_snapshot_tracks t + JOIN qobuz_playlist_snapshot h + ON h.qobuz_playlist_id = t.qobuz_playlist_id + WHERE h.is_owned = 1 AND h.inactive = 0 + AND t.track_id IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)), + |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, tid) = row?; + for (id, ordinal) in chunk { + if *id == tid { + found.push((pid, *ordinal)); + } + } + } + collect_qobuz(found); + } + + // Library refs → local-track sidecars on Qobuz playlists. + for chunk in lib_ids.chunks(IN_CHUNK) { + let sql = format!( + "SELECT qobuz_playlist_id, local_track_id FROM playlist_local_tracks + WHERE local_track_id IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)), + |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, tid) = row?; + for (id, ordinal) in chunk { + if *id == tid { + found.push((pid, *ordinal)); + } + } + } + collect_qobuz(found); + } + + // Plex refs → Plex sidecars on Qobuz playlists. + for chunk in plex_keys.chunks(IN_CHUNK) { + let sql = format!( + "SELECT qobuz_playlist_id, plex_rating_key FROM playlist_plex_tracks + WHERE plex_rating_key IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(key, _)| *key)), + |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, key) = row?; + for (k, ordinal) in chunk { + if *k == key { + found.push((pid, *ordinal)); + } + } + } + collect_qobuz(found); + } + + // All three identity columns of local playlists. + let mut collect_local = |rows: Vec<(String, usize)>| { + for (pid, ordinal) in rows { + hits.entry(ContainmentTarget::Local(pid)) + .or_default() + .insert(ordinal); + } + }; + for chunk in qobuz_ids.chunks(IN_CHUNK) { + let sql = format!( + "SELECT playlist_id, qobuz_track_id FROM local_playlist_tracks + WHERE qobuz_track_id IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(id, _)| *id)), + |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, tid) = row?; + for (id, ordinal) in chunk { + if *id == tid { + found.push((pid.clone(), *ordinal)); + } + } + } + collect_local(found); + } + for chunk in lib_paths.chunks(IN_CHUNK) { + let sql = format!( + "SELECT playlist_id, local_path FROM local_playlist_tracks + WHERE local_path IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(p, _)| *p)), + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, path) = row?; + for (p, ordinal) in chunk { + if *p == path { + found.push((pid.clone(), *ordinal)); + } + } + } + collect_local(found); + } + for chunk in plex_keys.chunks(IN_CHUNK) { + let sql = format!( + "SELECT playlist_id, plex_key FROM local_playlist_tracks + WHERE plex_key IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(k, _)| *k)), + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, key) = row?; + for (k, ordinal) in chunk { + if *k == key { + found.push((pid.clone(), *ordinal)); + } + } + } + collect_local(found); + } + + let mut out: Vec = hits + .into_iter() + .map(|(target, ordinals)| PlaylistContainment { + target, + contained: ordinals.len() as u32, + }) + .collect(); + // Deterministic order: fullest first, then stable by identity. + out.sort_by(|a, b| { + b.contained.cmp(&a.contained).then_with(|| { + let key = |t: &ContainmentTarget| match t { + ContainmentTarget::Qobuz(id) => (0u8, id.to_string()), + ContainmentTarget::Local(id) => (1u8, id.clone()), + }; + key(&a.target).cmp(&key(&b.target)) + }) + }); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::qobuz_playlist_snapshot as snapshot; + + fn conn() -> Connection { + let c = Connection::open_in_memory().unwrap(); + snapshot::init_schema(&c).unwrap(); + crate::local_playlists::init_schema(&c).unwrap(); + // Self-contained copies of the sidecar tables (the database.rs idiom: + // unit tests build only the schema slice they exercise). + c.execute_batch( + "CREATE TABLE playlist_local_tracks ( + id INTEGER PRIMARY KEY, + qobuz_playlist_id INTEGER NOT NULL, + local_track_id INTEGER NOT NULL, + position INTEGER NOT NULL, + added_at INTEGER NOT NULL, + UNIQUE(qobuz_playlist_id, local_track_id)); + CREATE TABLE playlist_plex_tracks ( + id INTEGER PRIMARY KEY, + qobuz_playlist_id INTEGER NOT NULL, + plex_rating_key TEXT NOT NULL, + position INTEGER NOT NULL, + added_at INTEGER NOT NULL, + UNIQUE(qobuz_playlist_id, plex_rating_key));", + ) + .unwrap(); + c + } + + /// ONE authoritative list naming every playlist (separate lists would + /// advance the generation and retire the earlier ones — the grace rule + /// working as intended), then a membership snapshot for each. + fn owned_playlists(c: &Connection, playlists: &[(u64, &str, &[u64])]) { + let entries: Vec = playlists + .iter() + .map(|(id, name, ids)| snapshot::AuthoritativeEntry { + qobuz_playlist_id: *id, + name: name.to_string(), + owner: None, + track_count: Some(ids.len() as u32), + remote_updated_at: None, + is_owned: true, + }) + .collect(); + snapshot::record_authoritative_list(c, &entries).unwrap(); + for (id, name, ids) in playlists { + snapshot::replace_tracks(c, *id, name, None, ids, None).unwrap(); + } + } + + fn contained(rows: &[PlaylistContainment], target: ContainmentTarget) -> Option { + rows.iter() + .find(|r| r.target == target) + .map(|r| r.contained) + } + + #[test] + fn ref_construction_routes_plex_by_stored_key() { + assert_eq!( + PlaylistTrackRef::from_library_row("plex", 99, "12345"), + PlaylistTrackRef::Plex { + rating_key: "12345".into() + } + ); + assert_eq!( + PlaylistTrackRef::from_library_row("jellyfin", 7, "/j/item"), + PlaylistTrackRef::Library { + track_id: 7, + path: Some("/j/item".into()) + } + ); + } + + #[test] + fn qobuz_containment_counts_distinct_refs() { + let c = conn(); + owned_playlists( + &c, + &[ + (1, "Both", &[10, 20, 30]), + (2, "One", &[20]), + (3, "Neither", &[99]), + ], + ); + + let rows = playlists_containing( + &c, + &[PlaylistTrackRef::Qobuz(10), PlaylistTrackRef::Qobuz(20)], + ) + .unwrap(); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(2)); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(2)), Some(1)); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(3)), None); + // Fullest playlist first. + assert_eq!(rows[0].target, ContainmentTarget::Qobuz(1)); + } + + #[test] + fn duplicate_membership_rows_count_once() { + let c = conn(); + owned_playlists(&c, &[(1, "Dupes", &[10, 10, 10])]); + let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap(); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(1)); + } + + #[test] + fn unowned_and_inactive_playlists_are_not_targets() { + let c = conn(); + snapshot::record_authoritative_list( + &c, + &[snapshot::AuthoritativeEntry { + qobuz_playlist_id: 5, + name: "Followed".into(), + owner: None, + track_count: Some(1), + remote_updated_at: None, + is_owned: false, + }], + ) + .unwrap(); + snapshot::replace_tracks(&c, 5, "Followed", None, &[10], None).unwrap(); + let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap(); + assert!(rows.is_empty()); + + owned_playlists(&c, &[(6, "Mine", &[10])]); + // Retire 6 by two authoritative lists without it. + for _ in 0..2 { + snapshot::record_authoritative_list(&c, &[]).unwrap(); + } + let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap(); + assert!(rows.is_empty()); + } + + #[test] + fn sidecars_and_local_playlists_answer_by_typed_identity() { + let c = conn(); + c.execute_batch( + "INSERT INTO playlist_local_tracks VALUES (NULL, 7, 42, 0, 1); + INSERT INTO playlist_plex_tracks VALUES (NULL, 7, 'rk-9', 1, 1);", + ) + .unwrap(); + let lp = crate::local_playlists::create(&c, "Local mix", None, false).unwrap(); + crate::local_playlists::add_tracks( + &c, + &lp, + &[ + crate::local_playlists::LocalPlaylistTrackInput::Qobuz(1000), + crate::local_playlists::LocalPlaylistTrackInput::Local("/music/a.flac".into()), + crate::local_playlists::LocalPlaylistTrackInput::Plex("rk-9".into()), + ], + ) + .unwrap(); + + let refs = [ + PlaylistTrackRef::Qobuz(1000), + PlaylistTrackRef::Library { + track_id: 42, + path: Some("/music/a.flac".into()), + }, + PlaylistTrackRef::Plex { + rating_key: "rk-9".into(), + }, + ]; + let rows = playlists_containing(&c, &refs).unwrap(); + // The Qobuz playlist holds the library row and the Plex key (2 of 3); + // the local playlist holds all three. + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(7)), Some(2)); + assert_eq!(contained(&rows, ContainmentTarget::Local(lp.clone())), Some(3)); + assert_eq!(rows[0].target, ContainmentTarget::Local(lp)); + } + + #[test] + fn empty_refs_answer_nothing() { + let c = conn(); + assert!(playlists_containing(&c, &[]).unwrap().is_empty()); + } +} diff --git a/crates/qbz-library/src/qobuz_playlist_snapshot.rs b/crates/qbz-library/src/qobuz_playlist_snapshot.rs index 3934f2285..b46d00bfd 100644 --- a/crates/qbz-library/src/qobuz_playlist_snapshot.rs +++ b/crates/qbz-library/src/qobuz_playlist_snapshot.rs @@ -1,25 +1,35 @@ -//! Local snapshot of the user's QOBUZ playlists (offline-mode port, B7/B8). +//! Local snapshot of the user's QOBUZ playlists (offline-mode port, B7/B8; +//! membership index substrate, 2.1.1 Add-to-Playlist redesign). //! //! Spec D11 left an HONEST LIMIT: playlist names and membership live only in //! the Qobuz API, so offline a mixed playlist falls back to a synthesized //! "Playlist (N local)" name and shows zero Qobuz rows. This module stores a -//! point-in-time snapshot captured opportunistically from data the app -//! ALREADY fetches while online (no new API traffic): +//! point-in-time snapshot captured from data the app fetches while online: //! -//! - NAMES: every user-playlist list load (sidebar / playlist manager) -//! upserts id + name (+ owner, track_count) for ALL listed playlists — -//! cheap names-only rows, no track membership. +//! - HEADERS: every authoritative user-playlist list load (sidebar / playlist +//! manager) upserts id + name (+ owner, track_count, ownership) for ALL +//! listed playlists and advances the AUTHORITY GENERATION. A header absent +//! from two consecutive authoritative lists is marked `inactive` — never +//! deleted on a single miss, tolerating Qobuz post-write lag. //! - MEMBERSHIP: opening a playlist DETAIL online full-replaces its snapshot -//! track ids (the detail fetch already returns the full track list). -//! Membership is recorded ONLY for playlists already captured by the -//! names producer (the user's own list) — a merely-viewed public playlist -//! never lands in the snapshot, so the offline surfaces stay the user's. +//! track ids, and the background hydrator does the same from the +//! ids-only `playlist/get?extra=track_ids` fetch. Membership is recorded +//! ONLY for playlists already captured by a header producer (the user's own +//! list) — a merely-viewed public playlist never lands in the snapshot. +//! - MUTATIONS: successful add/remove/create through QBZ update the snapshot +//! incrementally and synchronously, so the picker's containment answer +//! moves without waiting for a re-sync. //! -//! Rows are point-in-time: offline consumers show them as-is (no staleness -//! UI in v1); `snapped_at` is stamped for the future. +//! Freshness is deliberately NOT one timestamp (that overload is exactly what +//! made an empty membership answer unreadable): `header_updated_at` says when +//! the list last named this playlist, `membership_synced_at` says when the +//! track ids were last authoritative, `membership_count` + +//! `membership_remote_updated_at` are the evidence a later list compares +//! against to decide staleness. `snapped_at` remains for the older offline +//! consumers and is stamped wherever it always was. //! -//! All functions take `&Connection` (the local_playlists idiom): no Tauri -//! state, no async runtime — testable with in-memory SQLite. +//! All functions take `&Connection` (the local_playlists idiom): no async +//! runtime — testable with in-memory SQLite. use std::collections::HashMap; @@ -31,20 +41,69 @@ pub struct SnapshotHeader { pub qobuz_playlist_id: u64, pub name: String, pub owner: Option, - /// The playlist's TOTAL Qobuz track count at snapshot time (not the + /// The playlist's TOTAL Qobuz track count at header time (not the /// offline-playable subset). pub track_count: Option, - /// Unix ms when this header was last written. + /// Unix ms when this header was last written (legacy stamp; kept for the + /// offline consumers that predate the split freshness columns). pub snapped_at: i64, + /// Unix ms when an authoritative list last named this playlist. + pub header_updated_at: Option, + /// Unix ms when the membership rows were last authoritative. NULL means + /// membership was never captured — which is NOT "empty playlist". + pub membership_synced_at: Option, + /// Number of membership rows written at the last sync. + pub membership_count: Option, + /// The playlist's API `updated_at` as reported by the authoritative list. + pub remote_updated_at: Option, + /// The API `updated_at` in force when membership was last synced. + pub membership_remote_updated_at: Option, + /// Last authority generation that listed this playlist. + pub seen_generation: i64, + /// The session user owns (can write to) this playlist. Persisted + /// explicitly instead of being re-inferred from whichever response + /// happened to be loaded. + pub is_owned: bool, + /// Absent from two consecutive authoritative lists. Kept, not deleted, so + /// a Qobuz-side hiccup cannot erase local knowledge. + pub inactive: bool, } -/// Names-producer input (one listed playlist). +/// Authoritative-list producer input (one listed playlist). #[derive(Debug, Clone)] -pub struct SnapshotNameEntry { +pub struct AuthoritativeEntry { pub qobuz_playlist_id: u64, pub name: String, pub owner: Option, pub track_count: Option, + pub remote_updated_at: Option, + pub is_owned: bool, +} + +/// Why the hydrator wants to refresh a playlist's membership. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StaleReason { + NeverSynced, + CountMismatch, + RemoteRevision, +} + +#[derive(Debug, Clone)] +pub struct HydrationCandidate { + pub qobuz_playlist_id: u64, + pub reason: StaleReason, +} + +/// The picker's honest tri-state for the containment section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MembershipIndexState { + /// Every owned active playlist has authoritative membership. + Complete, + /// Some owned playlists still await a membership sync. + Updating { pending: u32 }, + /// No authoritative list was ever recorded (fresh profile, or the app has + /// never been online) — an empty containment answer means nothing. + Unavailable, } fn now_ms() -> i64 { @@ -55,8 +114,9 @@ fn now_ms() -> i64 { .as_millis() as i64 } -/// Create the snapshot tables. Idempotent (`IF NOT EXISTS`), run by -/// `LibraryDatabase::open` next to the rest of the schema. +/// Create the snapshot tables. Idempotent (`IF NOT EXISTS` + pragma-guarded +/// additive ALTERs, the database.rs idiom), run by `LibraryDatabase::open` +/// next to the rest of the schema. pub fn init_schema(conn: &Connection) -> Result<()> { conn.execute_batch( r#" @@ -76,80 +136,435 @@ pub fn init_schema(conn: &Connection) -> Result<()> { CREATE INDEX IF NOT EXISTS idx_qobuz_playlist_snapshot_tracks ON qobuz_playlist_snapshot_tracks(qobuz_playlist_id, position); - "#, - ) -} -/// NAMES producer: upsert a header row for every listed playlist. Never -/// touches the membership table. Stamps `snapped_at` = now on each row. -pub fn upsert_names(conn: &Connection, entries: &[SnapshotNameEntry]) -> Result<()> { - if entries.is_empty() { - return Ok(()); - } - let ts = now_ms(); - let mut stmt = conn.prepare( - "INSERT INTO qobuz_playlist_snapshot - (qobuz_playlist_id, name, owner, track_count, snapped_at) - VALUES (?1, ?2, ?3, ?4, ?5) - ON CONFLICT(qobuz_playlist_id) DO UPDATE SET - name = excluded.name, - owner = excluded.owner, - track_count = excluded.track_count, - snapped_at = excluded.snapped_at", + -- The picker's containment question runs in the opposite direction: + -- "which playlists hold THIS track". + CREATE INDEX IF NOT EXISTS idx_qobuz_playlist_snapshot_tracks_track + ON qobuz_playlist_snapshot_tracks(track_id, qobuz_playlist_id); + + CREATE TABLE IF NOT EXISTS qobuz_playlist_index_meta ( + key TEXT PRIMARY KEY, + value INTEGER NOT NULL + ); + "#, )?; - for e in entries { - stmt.execute(params![ - e.qobuz_playlist_id as i64, - e.name, - e.owner, - e.track_count, - ts - ])?; + // Additive migration (2.1.1 membership index): the split freshness + // columns. One probe guards the whole batch — they ship together. + let has_freshness: bool = conn + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('qobuz_playlist_snapshot') + WHERE name = 'membership_synced_at'", + [], + |r| r.get::<_, i32>(0), + ) + .map(|count| count > 0) + .unwrap_or(false); + if !has_freshness { + conn.execute_batch( + "ALTER TABLE qobuz_playlist_snapshot ADD COLUMN header_updated_at INTEGER; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_synced_at INTEGER; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_count INTEGER; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN remote_updated_at INTEGER; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN membership_remote_updated_at INTEGER; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN seen_generation INTEGER NOT NULL DEFAULT 0; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN is_owned INTEGER NOT NULL DEFAULT 0; + ALTER TABLE qobuz_playlist_snapshot ADD COLUMN inactive INTEGER NOT NULL DEFAULT 0; + -- Backfill: the old single stamp was both header and membership + -- evidence; keep it as the header stamp everywhere, and as the + -- membership stamp only where membership rows actually exist. + UPDATE qobuz_playlist_snapshot + SET header_updated_at = snapped_at + WHERE header_updated_at IS NULL; + UPDATE qobuz_playlist_snapshot + SET membership_synced_at = snapped_at, + membership_count = ( + SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id + = qobuz_playlist_snapshot.qobuz_playlist_id) + WHERE membership_synced_at IS NULL + AND EXISTS ( + SELECT 1 FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id + = qobuz_playlist_snapshot.qobuz_playlist_id);", + )?; } Ok(()) } +// ───────────────────────── Authority generations ───────────────────────── + +const GENERATION_KEY: &str = "authority_generation"; + +/// Last recorded authority generation; 0 when no authoritative list was ever +/// recorded. +pub fn current_generation(conn: &Connection) -> Result { + conn.query_row( + "SELECT value FROM qobuz_playlist_index_meta WHERE key = ?1", + params![GENERATION_KEY], + |r| r.get(0), + ) + .optional() + .map(|v| v.unwrap_or(0)) +} + +/// HEADERS producer: record one successful authoritative user-playlist list. +/// Upserts every entry, advances the authority generation, and marks headers +/// unseen for TWO consecutive generations `inactive` (the grace that +/// tolerates Qobuz post-write lag). Returns the new generation. +/// +/// An EMPTY list is still recorded (a user can genuinely delete every +/// playlist), but the caller must only invoke this for a fetch that +/// succeeded — a network failure must never masquerade as an empty library. +pub fn record_authoritative_list( + conn: &Connection, + entries: &[AuthoritativeEntry], +) -> Result { + let ts = now_ms(); + conn.execute_batch("BEGIN IMMEDIATE")?; + let result = (|| -> Result { + let generation = current_generation(conn)? + 1; + { + let mut stmt = conn.prepare( + "INSERT INTO qobuz_playlist_snapshot + (qobuz_playlist_id, name, owner, track_count, snapped_at, + header_updated_at, remote_updated_at, seen_generation, + is_owned, inactive) + VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6, ?7, ?8, 0) + ON CONFLICT(qobuz_playlist_id) DO UPDATE SET + name = excluded.name, + owner = excluded.owner, + track_count = excluded.track_count, + snapped_at = excluded.snapped_at, + header_updated_at = excluded.header_updated_at, + remote_updated_at = excluded.remote_updated_at, + seen_generation = excluded.seen_generation, + is_owned = excluded.is_owned, + inactive = 0", + )?; + for e in entries { + stmt.execute(params![ + e.qobuz_playlist_id as i64, + e.name, + e.owner, + e.track_count, + ts, + e.remote_updated_at, + generation, + e.is_owned, + ])?; + } + } + conn.execute( + "UPDATE qobuz_playlist_snapshot + SET inactive = 1 + WHERE inactive = 0 AND seen_generation <= ?1 - 2", + params![generation], + )?; + conn.execute( + "INSERT INTO qobuz_playlist_index_meta (key, value) VALUES (?1, ?2) + ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![GENERATION_KEY, generation], + )?; + Ok(generation) + })(); + match result { + Ok(generation) => { + conn.execute_batch("COMMIT")?; + Ok(generation) + } + Err(e) => { + let _ = conn.execute_batch("ROLLBACK"); + Err(e) + } + } +} + +// ───────────────────────── Membership producers ───────────────────────── + /// MEMBERSHIP producer: full-replace the snapshot track ids of ONE playlist -/// (detail load) and refresh its header (name / owner / track_count / -/// snapped_at). Returns `false` (writing NOTHING) when the playlist has no -/// header row — i.e. it was never captured by the names producer, so it is -/// not one of the user's listed playlists. +/// (detail load or hydrator fetch) and refresh its header. Stamps +/// `membership_synced_at` / `membership_count`, and records the API +/// `updated_at` in force (`remote_updated_at_evidence`) when the caller has +/// one. Returns `false` (writing NOTHING) when the playlist has no header +/// row — i.e. it was never captured by the headers producer, so it is not +/// one of the user's listed playlists. pub fn replace_tracks( conn: &Connection, qobuz_playlist_id: u64, name: &str, owner: Option<&str>, track_ids: &[u64], + remote_updated_at_evidence: Option, ) -> Result { - let updated = conn.execute( - "UPDATE qobuz_playlist_snapshot - SET name = ?2, owner = ?3, track_count = ?4, snapped_at = ?5 - WHERE qobuz_playlist_id = ?1", - params![ - qobuz_playlist_id as i64, - name, - owner, - track_ids.len() as u32, - now_ms() - ], - )?; - if updated == 0 { + let ts = now_ms(); + conn.execute_batch("BEGIN IMMEDIATE")?; + let result = (|| -> Result { + let updated = conn.execute( + "UPDATE qobuz_playlist_snapshot + SET name = ?2, owner = ?3, track_count = ?4, snapped_at = ?5, + membership_synced_at = ?5, membership_count = ?4, + membership_remote_updated_at = + COALESCE(?6, remote_updated_at) + WHERE qobuz_playlist_id = ?1", + params![ + qobuz_playlist_id as i64, + name, + owner, + track_ids.len() as u32, + ts, + remote_updated_at_evidence, + ], + )?; + if updated == 0 { + return Ok(false); + } + conn.execute( + "DELETE FROM qobuz_playlist_snapshot_tracks WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + )?; + let mut stmt = conn.prepare( + "INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id) + VALUES (?1, ?2, ?3)", + )?; + for (pos, tid) in track_ids.iter().enumerate() { + stmt.execute(params![qobuz_playlist_id as i64, pos as i64, *tid as i64])?; + } + Ok(true) + })(); + match result { + Ok(wrote) => { + conn.execute_batch("COMMIT")?; + Ok(wrote) + } + Err(e) => { + let _ = conn.execute_batch("ROLLBACK"); + Err(e) + } + } +} + +/// Incremental MUTATION producer: a successful `playlist/addTracks` appends +/// its ids to the snapshot so the containment answer moves immediately. +/// Applies only when membership was already captured (`membership_synced_at` +/// set) — an uncaptured playlist stays queued for the hydrator instead of +/// pretending an append equals a snapshot. Returns whether it applied. +pub fn apply_added_tracks( + conn: &Connection, + qobuz_playlist_id: u64, + track_ids: &[u64], +) -> Result { + if track_ids.is_empty() { return Ok(false); } - conn.execute( - "DELETE FROM qobuz_playlist_snapshot_tracks WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - )?; - let mut stmt = conn.prepare( - "INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id) - VALUES (?1, ?2, ?3)", - )?; - for (pos, tid) in track_ids.iter().enumerate() { - stmt.execute(params![qobuz_playlist_id as i64, pos as i64, *tid as i64])?; + let ts = now_ms(); + conn.execute_batch("BEGIN IMMEDIATE")?; + let result = (|| -> Result { + let captured: Option = conn + .query_row( + "SELECT membership_synced_at FROM qobuz_playlist_snapshot + WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |r| r.get(0), + ) + .optional()? + .flatten(); + if captured.is_none() { + return Ok(false); + } + let next: i64 = conn.query_row( + "SELECT COALESCE(MAX(position) + 1, 0) + FROM qobuz_playlist_snapshot_tracks + WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |r| r.get(0), + )?; + let mut stmt = conn.prepare( + "INSERT INTO qobuz_playlist_snapshot_tracks (qobuz_playlist_id, position, track_id) + VALUES (?1, ?2, ?3)", + )?; + for (offset, tid) in track_ids.iter().enumerate() { + stmt.execute(params![ + qobuz_playlist_id as i64, + next + offset as i64, + *tid as i64 + ])?; + } + conn.execute( + "UPDATE qobuz_playlist_snapshot + SET membership_count = ( + SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id = ?1), + track_count = ( + SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id = ?1), + membership_synced_at = ?2, snapped_at = ?2 + WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64, ts], + )?; + Ok(true) + })(); + match result { + Ok(applied) => { + conn.execute_batch("COMMIT")?; + Ok(applied) + } + Err(e) => { + let _ = conn.execute_batch("ROLLBACK"); + Err(e) + } } - Ok(true) } +/// Incremental MUTATION producer: a successful track removal drops every +/// membership row bearing the removed TRACK ids. Same capture precondition +/// as `apply_added_tracks`. +pub fn apply_removed_tracks( + conn: &Connection, + qobuz_playlist_id: u64, + track_ids: &[u64], +) -> Result { + if track_ids.is_empty() { + return Ok(false); + } + let ts = now_ms(); + conn.execute_batch("BEGIN IMMEDIATE")?; + let result = (|| -> Result { + let captured: Option = conn + .query_row( + "SELECT membership_synced_at FROM qobuz_playlist_snapshot + WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |r| r.get(0), + ) + .optional()? + .flatten(); + if captured.is_none() { + return Ok(false); + } + { + let mut stmt = conn.prepare( + "DELETE FROM qobuz_playlist_snapshot_tracks + WHERE qobuz_playlist_id = ?1 AND track_id = ?2", + )?; + for tid in track_ids { + stmt.execute(params![qobuz_playlist_id as i64, *tid as i64])?; + } + } + conn.execute( + "UPDATE qobuz_playlist_snapshot + SET membership_count = ( + SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id = ?1), + track_count = ( + SELECT COUNT(*) FROM qobuz_playlist_snapshot_tracks t + WHERE t.qobuz_playlist_id = ?1), + membership_synced_at = ?2, snapped_at = ?2 + WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64, ts], + )?; + Ok(true) + })(); + match result { + Ok(applied) => { + conn.execute_batch("COMMIT")?; + Ok(applied) + } + Err(e) => { + let _ = conn.execute_batch("ROLLBACK"); + Err(e) + } + } +} + +/// MUTATION producer: a playlist just created through QBZ. Inserts its header +/// at the CURRENT generation (it cannot have been in the last list yet — the +/// grace rule, not a fresh fetch, is what keeps it alive) with an empty, +/// captured membership, so an immediate follow-up add applies incrementally. +pub fn record_created_playlist( + conn: &Connection, + qobuz_playlist_id: u64, + name: &str, + owner: Option<&str>, +) -> Result<()> { + let ts = now_ms(); + let generation = current_generation(conn)?; + conn.execute( + "INSERT INTO qobuz_playlist_snapshot + (qobuz_playlist_id, name, owner, track_count, snapped_at, + header_updated_at, membership_synced_at, membership_count, + seen_generation, is_owned, inactive) + VALUES (?1, ?2, ?3, 0, ?4, ?4, ?4, 0, ?5, 1, 0) + ON CONFLICT(qobuz_playlist_id) DO UPDATE SET + name = excluded.name, + owner = excluded.owner, + seen_generation = excluded.seen_generation, + is_owned = 1, + inactive = 0", + params![qobuz_playlist_id as i64, name, owner, ts, generation], + )?; + Ok(()) +} + +// ───────────────────────── Hydration planning ───────────────────────── + +/// The membership refreshes the hydrator still owes, oldest debt first: +/// never-synced playlists, then count mismatches, then remote-revision +/// mismatches. Only owned, active playlists — followed/read-only playlists +/// are informational and must not spend the rate budget. +pub fn hydration_queue(conn: &Connection) -> Result> { + let mut stmt = conn.prepare( + "SELECT qobuz_playlist_id, + membership_synced_at IS NULL AS never_synced, + membership_count IS NOT track_count AS count_mismatch, + (remote_updated_at IS NOT NULL + AND membership_remote_updated_at IS NOT remote_updated_at) + AS revision_mismatch + FROM qobuz_playlist_snapshot + WHERE is_owned = 1 AND inactive = 0 + AND (membership_synced_at IS NULL + OR membership_count IS NOT track_count + OR (remote_updated_at IS NOT NULL + AND membership_remote_updated_at IS NOT remote_updated_at)) + ORDER BY never_synced DESC, count_mismatch DESC, qobuz_playlist_id", + )?; + let mut out = Vec::new(); + for r in stmt.query_map([], |r| { + Ok(( + r.get::<_, i64>(0)? as u64, + r.get::<_, bool>(1)?, + r.get::<_, bool>(2)?, + )) + })? { + let (pid, never, count) = r?; + out.push(HydrationCandidate { + qobuz_playlist_id: pid, + reason: if never { + StaleReason::NeverSynced + } else if count { + StaleReason::CountMismatch + } else { + StaleReason::RemoteRevision + }, + }); + } + Ok(out) +} + +/// The containment section's honest tri-state. +pub fn index_state(conn: &Connection) -> Result { + if current_generation(conn)? == 0 { + return Ok(MembershipIndexState::Unavailable); + } + let pending = hydration_queue(conn)?.len() as u32; + Ok(if pending == 0 { + MembershipIndexState::Complete + } else { + MembershipIndexState::Updating { pending } + }) +} + +// ───────────────────────────── Readers ───────────────────────────── + fn row_to_header(r: &rusqlite::Row) -> Result { Ok(SnapshotHeader { qobuz_playlist_id: r.get::<_, i64>("qobuz_playlist_id")? as u64, @@ -157,26 +572,40 @@ fn row_to_header(r: &rusqlite::Row) -> Result { owner: r.get("owner")?, track_count: r.get("track_count")?, snapped_at: r.get("snapped_at")?, + header_updated_at: r.get("header_updated_at")?, + membership_synced_at: r.get("membership_synced_at")?, + membership_count: r.get("membership_count")?, + remote_updated_at: r.get("remote_updated_at")?, + membership_remote_updated_at: r.get("membership_remote_updated_at")?, + seen_generation: r.get("seen_generation")?, + is_owned: r.get("is_owned")?, + inactive: r.get("inactive")?, }) } +const HEADER_COLUMNS: &str = "qobuz_playlist_id, name, owner, track_count, snapped_at, \ + header_updated_at, membership_synced_at, membership_count, \ + remote_updated_at, membership_remote_updated_at, seen_generation, \ + is_owned, inactive"; + /// One snapshot header, or None. pub fn get_header(conn: &Connection, qobuz_playlist_id: u64) -> Result> { conn.query_row( - "SELECT qobuz_playlist_id, name, owner, track_count, snapped_at - FROM qobuz_playlist_snapshot WHERE qobuz_playlist_id = ?1", + &format!( + "SELECT {HEADER_COLUMNS} FROM qobuz_playlist_snapshot + WHERE qobuz_playlist_id = ?1" + ), params![qobuz_playlist_id as i64], row_to_header, ) .optional() } -/// All snapshot headers. +/// All snapshot headers, inactive ones included (offline consumers decide). pub fn all_headers(conn: &Connection) -> Result> { - let mut stmt = conn.prepare( - "SELECT qobuz_playlist_id, name, owner, track_count, snapped_at - FROM qobuz_playlist_snapshot", - )?; + let mut stmt = conn.prepare(&format!( + "SELECT {HEADER_COLUMNS} FROM qobuz_playlist_snapshot" + ))?; let mut out = Vec::new(); for r in stmt.query_map([], row_to_header)? { out.push(r?); @@ -226,20 +655,26 @@ mod tests { c } - fn name_entry(id: u64, name: &str, count: u32) -> SnapshotNameEntry { - SnapshotNameEntry { + fn entry(id: u64, name: &str, count: u32) -> AuthoritativeEntry { + AuthoritativeEntry { qobuz_playlist_id: id, name: name.to_string(), owner: Some("me".to_string()), track_count: Some(count), + remote_updated_at: None, + is_owned: true, } } + fn record(c: &Connection, entries: &[AuthoritativeEntry]) -> i64 { + record_authoritative_list(c, entries).unwrap() + } + #[test] fn roundtrip_header_and_tracks() { let c = conn(); - upsert_names(&c, &[name_entry(42, "Road Trip", 3)]).unwrap(); - let wrote = replace_tracks(&c, 42, "Road Trip", Some("me"), &[30, 10, 20]).unwrap(); + record(&c, &[entry(42, "Road Trip", 3)]); + let wrote = replace_tracks(&c, 42, "Road Trip", Some("me"), &[30, 10, 20], None).unwrap(); assert!(wrote); let h = get_header(&c, 42).unwrap().unwrap(); @@ -247,6 +682,10 @@ mod tests { assert_eq!(h.owner.as_deref(), Some("me")); assert_eq!(h.track_count, Some(3)); assert!(h.snapped_at > 0); + assert!(h.is_owned); + assert!(!h.inactive); + assert_eq!(h.membership_count, Some(3)); + assert!(h.membership_synced_at.is_some()); // Snapshot order preserved, not sorted by id. assert_eq!(track_ids(&c, 42).unwrap(), vec![30, 10, 20]); @@ -257,9 +696,9 @@ mod tests { #[test] fn replace_is_full_replace() { let c = conn(); - upsert_names(&c, &[name_entry(7, "Mix", 3)]).unwrap(); - replace_tracks(&c, 7, "Mix", None, &[1, 2, 3]).unwrap(); - replace_tracks(&c, 7, "Mix renamed", None, &[9]).unwrap(); + record(&c, &[entry(7, "Mix", 3)]); + replace_tracks(&c, 7, "Mix", None, &[1, 2, 3], None).unwrap(); + replace_tracks(&c, 7, "Mix renamed", None, &[9], None).unwrap(); assert_eq!(track_ids(&c, 7).unwrap(), vec![9]); let h = get_header(&c, 7).unwrap().unwrap(); @@ -279,28 +718,208 @@ mod tests { #[test] fn names_only_rows_without_tracks() { let c = conn(); - upsert_names(&c, &[name_entry(1, "A", 10), name_entry(2, "B", 0)]).unwrap(); + record(&c, &[entry(1, "A", 10), entry(2, "B", 0)]); assert_eq!(all_headers(&c).unwrap().len(), 2); assert!(track_ids(&c, 1).unwrap().is_empty()); assert!(all_track_ids(&c).unwrap().is_empty()); - // Re-upserting updates the name in place without creating track rows. - upsert_names(&c, &[name_entry(1, "A renamed", 11)]).unwrap(); + // Re-recording updates the name in place without creating track rows, + // and never touches the membership stamp. + record(&c, &[entry(1, "A renamed", 11), entry(2, "B", 0)]); let h = get_header(&c, 1).unwrap().unwrap(); assert_eq!(h.name, "A renamed"); assert_eq!(h.track_count, Some(11)); + assert!(h.membership_synced_at.is_none()); assert!(track_ids(&c, 1).unwrap().is_empty()); } #[test] fn replace_refuses_unknown_playlist() { let c = conn(); - // No names row -> the detail producer writes NOTHING (a merely + // No header row -> the detail producer writes NOTHING (a merely // viewed public playlist must not land in the snapshot). - let wrote = replace_tracks(&c, 99, "Someone's list", None, &[1, 2]).unwrap(); + let wrote = replace_tracks(&c, 99, "Someone's list", None, &[1, 2], None).unwrap(); assert!(!wrote); assert!(get_header(&c, 99).unwrap().is_none()); assert!(track_ids(&c, 99).unwrap().is_empty()); } + + #[test] + fn header_upsert_is_not_membership_evidence() { + // The 2.1.0 research finding: header refreshes used to renew the one + // timestamp that also vouched for membership. Now they must not. + let c = conn(); + record(&c, &[entry(5, "Mix", 2)]); + replace_tracks(&c, 5, "Mix", None, &[1, 2], None).unwrap(); + let synced = get_header(&c, 5).unwrap().unwrap().membership_synced_at; + + record(&c, &[entry(5, "Mix", 2)]); + let h = get_header(&c, 5).unwrap().unwrap(); + assert_eq!(h.membership_synced_at, synced); + assert_eq!(h.membership_count, Some(2)); + } + + #[test] + fn generations_and_two_generation_grace() { + let c = conn(); + assert_eq!(current_generation(&c).unwrap(), 0); + let g1 = record(&c, &[entry(1, "A", 0), entry(2, "B", 0)]); + assert_eq!(g1, 1); + + // B missing once: still active (post-write lag tolerance). + record(&c, &[entry(1, "A", 0)]); + assert!(!get_header(&c, 2).unwrap().unwrap().inactive); + + // B missing twice: inactive, but never deleted. + record(&c, &[entry(1, "A", 0)]); + let h = get_header(&c, 2).unwrap().unwrap(); + assert!(h.inactive); + + // B reappears: active again. + record(&c, &[entry(1, "A", 0), entry(2, "B", 0)]); + assert!(!get_header(&c, 2).unwrap().unwrap().inactive); + } + + #[test] + fn hydration_queue_reasons_and_order() { + let c = conn(); + let mut never = entry(1, "Never", 4); + never.remote_updated_at = Some(100); + let mut mismatch = entry(2, "Mismatch", 5); + mismatch.remote_updated_at = Some(100); + let mut revised = entry(3, "Revised", 1); + revised.remote_updated_at = Some(100); + let mut fresh = entry(4, "Fresh", 1); + fresh.remote_updated_at = Some(100); + let followed = AuthoritativeEntry { + is_owned: false, + ..entry(5, "Followed", 9) + }; + record( + &c, + &[ + never.clone(), + mismatch.clone(), + revised.clone(), + fresh.clone(), + followed, + ], + ); + // Membership for 2 (3 of 5 -> count mismatch), 3 (agrees, but synced + // under an older remote revision), 4 (agrees, current revision). + replace_tracks(&c, 2, "Mismatch", None, &[1, 2, 3], Some(100)).unwrap(); + replace_tracks(&c, 3, "Revised", None, &[7], Some(90)).unwrap(); + replace_tracks(&c, 4, "Fresh", None, &[8], Some(100)).unwrap(); + // The list reasserts the authoritative counts/revisions the entries + // declared (replace_tracks overwrote track_count with the membership + // size, which is exactly the drift the queue must notice). + record(&c, &[never, mismatch, revised, fresh]); + + let queue = hydration_queue(&c).unwrap(); + let ids: Vec = queue.iter().map(|q| q.qobuz_playlist_id).collect(); + assert_eq!(ids, vec![1, 2, 3]); + assert_eq!(queue[0].reason, StaleReason::NeverSynced); + assert_eq!(queue[1].reason, StaleReason::CountMismatch); + assert_eq!(queue[2].reason, StaleReason::RemoteRevision); + + match index_state(&c).unwrap() { + MembershipIndexState::Updating { pending } => assert_eq!(pending, 3), + other => panic!("expected Updating, got {other:?}"), + } + } + + #[test] + fn index_state_lifecycle() { + let c = conn(); + assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Unavailable); + record(&c, &[entry(1, "A", 1)]); + assert!(matches!( + index_state(&c).unwrap(), + MembershipIndexState::Updating { pending: 1 } + )); + replace_tracks(&c, 1, "A", None, &[10], None).unwrap(); + assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Complete); + } + + #[test] + fn incremental_add_and_remove() { + let c = conn(); + record(&c, &[entry(1, "A", 2), entry(2, "Uncaptured", 3)]); + replace_tracks(&c, 1, "A", None, &[10, 20], None).unwrap(); + + assert!(apply_added_tracks(&c, 1, &[30, 40]).unwrap()); + assert_eq!(track_ids(&c, 1).unwrap(), vec![10, 20, 30, 40]); + let h = get_header(&c, 1).unwrap().unwrap(); + assert_eq!(h.membership_count, Some(4)); + assert_eq!(h.track_count, Some(4)); + + assert!(apply_removed_tracks(&c, 1, &[20, 30]).unwrap()); + assert_eq!(track_ids(&c, 1).unwrap(), vec![10, 40]); + assert_eq!( + get_header(&c, 1).unwrap().unwrap().membership_count, + Some(2) + ); + + // A playlist whose membership was never captured refuses the + // increment — the hydrator owns it (its queue entry stays). + assert!(!apply_added_tracks(&c, 2, &[1]).unwrap()); + assert!(track_ids(&c, 2).unwrap().is_empty()); + assert!(hydration_queue(&c) + .unwrap() + .iter() + .any(|q| q.qobuz_playlist_id == 2)); + } + + #[test] + fn created_playlist_is_captured_and_survives_one_list_miss() { + let c = conn(); + record(&c, &[entry(1, "A", 0)]); + record_created_playlist(&c, 9, "Brand new", Some("me")).unwrap(); + + let h = get_header(&c, 9).unwrap().unwrap(); + assert!(h.is_owned); + assert_eq!(h.membership_count, Some(0)); + // Immediate add applies incrementally — no fetch needed. + assert!(apply_added_tracks(&c, 9, &[5]).unwrap()); + assert_eq!(track_ids(&c, 9).unwrap(), vec![5]); + + // One authoritative list that does not include it yet (Qobuz + // post-write lag): still active. + record(&c, &[entry(1, "A", 0)]); + assert!(!get_header(&c, 9).unwrap().unwrap().inactive); + } + + #[test] + fn legacy_schema_backfill() { + // A DB created by the pre-2.1.1 module: single-stamp schema. + let c = Connection::open_in_memory().unwrap(); + c.execute_batch( + "CREATE TABLE qobuz_playlist_snapshot ( + qobuz_playlist_id INTEGER PRIMARY KEY, + name TEXT NOT NULL, owner TEXT, track_count INTEGER, + snapped_at INTEGER NOT NULL); + CREATE TABLE qobuz_playlist_snapshot_tracks ( + qobuz_playlist_id INTEGER NOT NULL, + position INTEGER NOT NULL, + track_id INTEGER NOT NULL); + INSERT INTO qobuz_playlist_snapshot VALUES (1, 'With tracks', NULL, 2, 111); + INSERT INTO qobuz_playlist_snapshot VALUES (2, 'Names only', NULL, 7, 222); + INSERT INTO qobuz_playlist_snapshot_tracks VALUES (1, 0, 10), (1, 1, 20);", + ) + .unwrap(); + init_schema(&c).unwrap(); + + let with_tracks = get_header(&c, 1).unwrap().unwrap(); + assert_eq!(with_tracks.header_updated_at, Some(111)); + assert_eq!(with_tracks.membership_synced_at, Some(111)); + assert_eq!(with_tracks.membership_count, Some(2)); + + let names_only = get_header(&c, 2).unwrap().unwrap(); + assert_eq!(names_only.header_updated_at, Some(222)); + assert!(names_only.membership_synced_at.is_none()); + + // Idempotent re-run. + init_schema(&c).unwrap(); + } } From 44df1e53a4f37926bcc1db086072f544b1366389 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 16:37:59 -0600 Subject: [PATCH 02/10] feat(models,core): playlist revision evidence and track-ids fetch Playlist and PlaylistWithTrackIds deserialize the API updated_at stamp (absent on some list shapes, hence optional), and the core facade exposes the lightweight playlist/get?extra=track_ids fetch the membership hydrator drives. cc --- crates/qbz-core/src/core.rs | 16 ++++++++++++++++ crates/qbz-library/src/playlist_membership.rs | 10 +++++----- .../qbz-library/src/qobuz_playlist_snapshot.rs | 9 ++------- crates/qbz-models/src/types.rs | 7 +++++++ 4 files changed, 30 insertions(+), 12 deletions(-) diff --git a/crates/qbz-core/src/core.rs b/crates/qbz-core/src/core.rs index f7b2337c7..c50e2fe8c 100644 --- a/crates/qbz-core/src/core.rs +++ b/crates/qbz-core/src/core.rs @@ -1419,6 +1419,22 @@ impl QbzCore { .map_err(CoreError::Api) } + /// Lightweight membership fetch: one playlist's track IDS only + /// (`playlist/get?extra=track_ids`). The membership hydrator's probe — + /// no Track objects, no pagination. + pub async fn get_playlist_track_ids( + &self, + playlist_id: u64, + ) -> Result { + let client = self.client.read().await; + let client = client.as_ref().ok_or(CoreError::NotInitialized)?; + + client + .get_playlist_track_ids(playlist_id) + .await + .map_err(CoreError::Api) + } + /// Check how many of `track_ids` are already in the Qobuz playlist /// `playlist_id`. Mirrors Tauri's `v2_check_playlist_duplicates` /// (commands_v2/playlists.rs): fetch the playlist's existing track ids and diff --git a/crates/qbz-library/src/playlist_membership.rs b/crates/qbz-library/src/playlist_membership.rs index 831821f27..52784ae83 100644 --- a/crates/qbz-library/src/playlist_membership.rs +++ b/crates/qbz-library/src/playlist_membership.rs @@ -34,10 +34,7 @@ pub enum PlaylistTrackRef { /// A library-projected row: a local file, or a Jellyfin/Subsonic track /// (their playlist storage identity is the projection). `path` is the /// `local_tracks.file_path` value local playlists key on. - Library { - track_id: i64, - path: Option, - }, + Library { track_id: i64, path: Option }, /// A Plex track by rating key. Plex { rating_key: String }, } @@ -467,7 +464,10 @@ mod tests { // The Qobuz playlist holds the library row and the Plex key (2 of 3); // the local playlist holds all three. assert_eq!(contained(&rows, ContainmentTarget::Qobuz(7)), Some(2)); - assert_eq!(contained(&rows, ContainmentTarget::Local(lp.clone())), Some(3)); + assert_eq!( + contained(&rows, ContainmentTarget::Local(lp.clone())), + Some(3) + ); assert_eq!(rows[0].target, ContainmentTarget::Local(lp)); } diff --git a/crates/qbz-library/src/qobuz_playlist_snapshot.rs b/crates/qbz-library/src/qobuz_playlist_snapshot.rs index b46d00bfd..feb103a3a 100644 --- a/crates/qbz-library/src/qobuz_playlist_snapshot.rs +++ b/crates/qbz-library/src/qobuz_playlist_snapshot.rs @@ -215,10 +215,7 @@ pub fn current_generation(conn: &Connection) -> Result { /// An EMPTY list is still recorded (a user can genuinely delete every /// playlist), but the caller must only invoke this for a fetch that /// succeeded — a network failure must never masquerade as an empty library. -pub fn record_authoritative_list( - conn: &Connection, - entries: &[AuthoritativeEntry], -) -> Result { +pub fn record_authoritative_list(conn: &Connection, entries: &[AuthoritativeEntry]) -> Result { let ts = now_ms(); conn.execute_batch("BEGIN IMMEDIATE")?; let result = (|| -> Result { @@ -620,9 +617,7 @@ pub fn track_ids(conn: &Connection, qobuz_playlist_id: u64) -> Result> WHERE qobuz_playlist_id = ?1 ORDER BY position", )?; let mut out = Vec::new(); - for r in stmt.query_map(params![qobuz_playlist_id as i64], |r| { - r.get::<_, i64>(0) - })? { + for r in stmt.query_map(params![qobuz_playlist_id as i64], |r| r.get::<_, i64>(0))? { out.push(r? as u64); } Ok(out) diff --git a/crates/qbz-models/src/types.rs b/crates/qbz-models/src/types.rs index 83b7d23a3..8d890761d 100644 --- a/crates/qbz-models/src/types.rs +++ b/crates/qbz-models/src/types.rs @@ -828,6 +828,10 @@ pub struct Playlist { pub image_rectangle_mini: Option>, pub slug: Option, pub users_count: Option, + /// API revision stamp (unix seconds). The membership index reads it as + /// change evidence when the API provides it; absent on some list shapes. + #[serde(default)] + pub updated_at: Option, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -869,6 +873,9 @@ pub struct PlaylistWithTrackIds { pub images300: Option>, pub slug: Option, pub users_count: Option, + /// API revision stamp (unix seconds), when the response carries one. + #[serde(default)] + pub updated_at: Option, } /// Result of checking for duplicate tracks in a playlist From ee621ae28b35a1c5df624e1b179fef2b1e421421 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 16:41:19 -0600 Subject: [PATCH 03/10] feat(library): offline copies match both membership identities An offline copy (qobuz_download row) attaches to Qobuz playlists as a library-row sidecar but to local playlists as its catalog id; the Library ref now carries the optional catalog id so containment looks both ways. Also adds mark_inactive for the delete-playlist hook. cc --- crates/qbz-library/src/playlist_membership.rs | 80 +++++++++++++++++-- .../src/qobuz_playlist_snapshot.rs | 10 +++ 2 files changed, 82 insertions(+), 8 deletions(-) diff --git a/crates/qbz-library/src/playlist_membership.rs b/crates/qbz-library/src/playlist_membership.rs index 52784ae83..baa074e88 100644 --- a/crates/qbz-library/src/playlist_membership.rs +++ b/crates/qbz-library/src/playlist_membership.rs @@ -33,8 +33,15 @@ pub enum PlaylistTrackRef { Qobuz(u64), /// A library-projected row: a local file, or a Jellyfin/Subsonic track /// (their playlist storage identity is the projection). `path` is the - /// `local_tracks.file_path` value local playlists key on. - Library { track_id: i64, path: Option }, + /// `local_tracks.file_path` value local playlists key on; + /// `qobuz_track_id` is set for offline copies (`qobuz_download` rows), + /// which local playlists store as CATALOG ids while Qobuz-playlist + /// sidecars store the library row — containment must look both ways. + Library { + track_id: i64, + path: Option, + qobuz_track_id: Option, + }, /// A Plex track by rating key. Plex { rating_key: String }, } @@ -42,8 +49,14 @@ pub enum PlaylistTrackRef { impl PlaylistTrackRef { /// Build the ref for a library row the way the playlist writers key it: /// Plex rows carry the rating key in `file_path`; every other source is - /// the projected library row itself. - pub fn from_library_row(source: &str, track_id: i64, file_path: &str) -> Self { + /// the projected library row itself (offline copies also carrying their + /// catalog id). + pub fn from_library_row( + source: &str, + track_id: i64, + file_path: &str, + qobuz_track_id: Option, + ) -> Self { if source == "plex" { Self::Plex { rating_key: file_path.to_string(), @@ -52,6 +65,7 @@ impl PlaylistTrackRef { Self::Library { track_id, path: Some(file_path.to_string()), + qobuz_track_id: qobuz_track_id.filter(|_| source == "qobuz_download"), } } } @@ -105,11 +119,19 @@ pub fn playlists_containing( for (ordinal, r) in refs.iter().enumerate() { match r { PlaylistTrackRef::Qobuz(id) => qobuz_ids.push((*id as i64, ordinal)), - PlaylistTrackRef::Library { track_id, path } => { + PlaylistTrackRef::Library { + track_id, + path, + qobuz_track_id, + } => { lib_ids.push((*track_id, ordinal)); if let Some(p) = path { lib_paths.push((p.as_str(), ordinal)); } + // Offline copies live in local playlists as catalog ids. + if let Some(qid) = qobuz_track_id { + qobuz_ids.push((*qid as i64, ordinal)); + } } PlaylistTrackRef::Plex { rating_key } => plex_keys.push((rating_key.as_str(), ordinal)), } @@ -356,18 +378,59 @@ mod tests { #[test] fn ref_construction_routes_plex_by_stored_key() { assert_eq!( - PlaylistTrackRef::from_library_row("plex", 99, "12345"), + PlaylistTrackRef::from_library_row("plex", 99, "12345", None), PlaylistTrackRef::Plex { rating_key: "12345".into() } ); assert_eq!( - PlaylistTrackRef::from_library_row("jellyfin", 7, "/j/item"), + PlaylistTrackRef::from_library_row("jellyfin", 7, "/j/item", None), PlaylistTrackRef::Library { track_id: 7, - path: Some("/j/item".into()) + path: Some("/j/item".into()), + qobuz_track_id: None, } ); + // The catalog id sticks only to offline copies; a stray value on any + // other source is dropped rather than trusted. + assert_eq!( + PlaylistTrackRef::from_library_row("qobuz_download", 8, "/dl/a.flac", Some(555)), + PlaylistTrackRef::Library { + track_id: 8, + path: Some("/dl/a.flac".into()), + qobuz_track_id: Some(555), + } + ); + assert_eq!( + PlaylistTrackRef::from_library_row("local", 9, "/m/b.flac", Some(555)), + PlaylistTrackRef::Library { + track_id: 9, + path: Some("/m/b.flac".into()), + qobuz_track_id: None, + } + ); + } + + #[test] + fn offline_copy_matches_catalog_membership_too() { + let c = conn(); + owned_playlists(&c, &[(1, "Qobuz side", &[555])]); + let lp = crate::local_playlists::create(&c, "Local side", None, false).unwrap(); + crate::local_playlists::add_tracks( + &c, + &lp, + &[crate::local_playlists::LocalPlaylistTrackInput::Qobuz(555)], + ) + .unwrap(); + + let refs = [PlaylistTrackRef::Library { + track_id: 8, + path: Some("/dl/a.flac".into()), + qobuz_track_id: Some(555), + }]; + let rows = playlists_containing(&c, &refs).unwrap(); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(1)), Some(1)); + assert_eq!(contained(&rows, ContainmentTarget::Local(lp)), Some(1)); } #[test] @@ -455,6 +518,7 @@ mod tests { PlaylistTrackRef::Library { track_id: 42, path: Some("/music/a.flac".into()), + qobuz_track_id: None, }, PlaylistTrackRef::Plex { rating_key: "rk-9".into(), diff --git a/crates/qbz-library/src/qobuz_playlist_snapshot.rs b/crates/qbz-library/src/qobuz_playlist_snapshot.rs index feb103a3a..f2d26b4ef 100644 --- a/crates/qbz-library/src/qobuz_playlist_snapshot.rs +++ b/crates/qbz-library/src/qobuz_playlist_snapshot.rs @@ -502,6 +502,16 @@ pub fn record_created_playlist( Ok(()) } +/// MUTATION producer: a playlist deleted through QBZ leaves the target set +/// immediately instead of waiting out the two-generation grace. +pub fn mark_inactive(conn: &Connection, qobuz_playlist_id: u64) -> Result<()> { + conn.execute( + "UPDATE qobuz_playlist_snapshot SET inactive = 1 WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + )?; + Ok(()) +} + // ───────────────────────── Hydration planning ───────────────────────── /// The membership refreshes the hydrator still owes, oldest debt first: From dade0edb2686265dea7b60a4c8cdb5249ddc279f Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 17:23:50 -0600 Subject: [PATCH 04/10] feat(qt): membership hydrator, honest picker containment, last playlist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit playlist_index_qt walks the library's hydration queue one playlist/get?extra=track_ids fetch at a time (300ms pace, two attempts per playlist per round, nothing written on failure), poked by every recorded authoritative list. The sidebar and playlist-manager loads now record ownership-aware authoritative generations (skipped while the session user is unknown, and never from a failed fetch). The picker doc gains lastUsed — session-local, set only by a confirmed successful add or create, validated against the live row list — plus alreadyIn rows with distinct-ref counts and the complete/updating/unavailable tri-state (offline degrades updating to unavailable). Followed playlists are no longer offered as add targets. Successful add/remove/ create/delete mutations move the snapshot synchronously; local-mode refs resolve to typed membership refs at the index boundary. Verified: cargo test -p qbz-library (158) and -p qbz-qt (615) green. cc --- crates/qbz-library/src/playlist_membership.rs | 2 +- crates/qbz-qt/src/local_playlist_qt.rs | 38 +++ crates/qbz-qt/src/main.rs | 1 + crates/qbz-qt/src/playlist_index_qt.rs | 165 +++++++++++ crates/qbz-qt/src/playlist_manager_qt.rs | 22 +- crates/qbz-qt/src/playlist_picker_qt.rs | 279 +++++++++++++++++- crates/qbz-qt/src/playlist_qt.rs | 63 +++- crates/qbz-qt/src/playlist_snapshot_qt.rs | 50 +++- crates/qbz-qt/src/sidebar_qt.rs | 25 +- 9 files changed, 583 insertions(+), 62 deletions(-) create mode 100644 crates/qbz-qt/src/playlist_index_qt.rs diff --git a/crates/qbz-library/src/playlist_membership.rs b/crates/qbz-library/src/playlist_membership.rs index baa074e88..4dd293081 100644 --- a/crates/qbz-library/src/playlist_membership.rs +++ b/crates/qbz-library/src/playlist_membership.rs @@ -24,7 +24,7 @@ use std::collections::{HashMap, HashSet}; -use rusqlite::{params, Connection, Result}; +use rusqlite::{Connection, Result}; /// One selected track at the picker/index boundary. #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/crates/qbz-qt/src/local_playlist_qt.rs b/crates/qbz-qt/src/local_playlist_qt.rs index 9ce7e307f..14601ccf8 100644 --- a/crates/qbz-qt/src/local_playlist_qt.rs +++ b/crates/qbz-qt/src/local_playlist_qt.rs @@ -256,6 +256,44 @@ pub fn add_local_refs_blocking(id: &str, refs: &[String]) -> usize { add_inputs_blocking(id, &entries) } +/// Resolve carried local-mode refs into the TYPED membership refs the +/// containment index takes (`qbz_library::playlist_membership`). Shares +/// [`local_row_input`]'s worldview: a Plex ref is its rating key, and a +/// library row contributes its path plus — for offline copies — its catalog +/// id. An unresolvable row id still yields a ref (row-id-only), so sidecar +/// membership can answer even when the row vanished from the library. +pub fn membership_refs_blocking( + refs: &[String], +) -> Vec { + use qbz_library::playlist_membership::PlaylistTrackRef; + with_db(false, |db| { + let mut out = Vec::new(); + for r in refs { + if let Some(key) = r.strip_prefix("plex:") { + out.push(PlaylistTrackRef::Plex { + rating_key: key.to_string(), + }); + } else if let Ok(rid) = r.parse::() { + out.push(match db.get_track(rid)? { + Some(track) => PlaylistTrackRef::from_library_row( + track.source.as_deref().unwrap_or("local"), + rid, + &track.file_path, + track.qobuz_track_id.map(|v| v as u64), + ), + None => PlaylistTrackRef::Library { + track_id: rid, + path: None, + qobuz_track_id: None, + }, + }); + } + } + Ok(out) + }) + .unwrap_or_default() +} + // ──────────────────────────── custom artwork ──────────────────────────── // There is deliberately NO `set_custom_artwork_blocking` twin of the clear diff --git a/crates/qbz-qt/src/main.rs b/crates/qbz-qt/src/main.rs index 2283c5e96..54563f018 100644 --- a/crates/qbz-qt/src/main.rs +++ b/crates/qbz-qt/src/main.rs @@ -318,6 +318,7 @@ mod external_reco_qt; mod artist_qt; mod lyrics_qt; mod playback_qt; +mod playlist_index_qt; mod playlist_picker_qt; mod tunnelflow_qt; // Playlist Importer controller (the `qbz-playlist-import` crate's frontend diff --git a/crates/qbz-qt/src/playlist_index_qt.rs b/crates/qbz-qt/src/playlist_index_qt.rs new file mode 100644 index 000000000..ea6cb353a --- /dev/null +++ b/crates/qbz-qt/src/playlist_index_qt.rs @@ -0,0 +1,165 @@ +//! Background Qobuz playlist-membership hydrator (2.1.1 picker redesign). +//! +//! The queue itself is pure and lives in +//! `qbz_library::qobuz_playlist_snapshot::hydration_queue` — missing, stale +//! and count/revision-mismatched memberships of OWNED playlists. This driver +//! only walks it: one `playlist/get?extra=track_ids` fetch at a time, paced, +//! with a bounded per-round retry budget, committing each snapshot +//! transactionally through `replace_tracks`. A network failure never touches +//! the previous good snapshot (nothing is written on the error arm). +//! +//! `poke()` is the only entry point. The authoritative-list producers call it +//! after every recorded generation (login, sidebar reload, playlist-manager +//! load), so reconnects and mutations re-arm it for free; a poke while a walk +//! is running coalesces into one more round instead of a second walker. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; + +use qbz_library::qobuz_playlist_snapshot as repo; + +type Runtime = std::sync::Arc>; + +/// Per-round fetch budget for one playlist before it is parked until the next +/// poke. Transient API errors get a second try; a persistent one must not +/// starve the rest of the queue. +const MAX_ATTEMPTS: u32 = 2; +/// Pace between fetches — the rate-limit courtesy the research doc requires. +const PACE_MS: u64 = 300; + +static RUNNING: AtomicBool = AtomicBool::new(false); +static REPOKE: AtomicBool = AtomicBool::new(false); + +/// Ask the hydrator to reconcile the membership snapshot with the latest +/// authoritative headers. Cheap and idempotent; safe from any thread. +pub fn poke() { + if crate::offline_fwd::engine().is_offline() { + return; + } + if RUNNING.swap(true, Ordering::SeqCst) { + REPOKE.store(true, Ordering::SeqCst); + return; + } + let runtime = crate::app(); + crate::spawn(async move { + loop { + run_round(&runtime).await; + if !REPOKE.swap(false, Ordering::SeqCst) { + break; + } + } + RUNNING.store(false, Ordering::SeqCst); + // A poke can race the store above: it saw RUNNING=true and only set + // REPOKE. Pick that flag up rather than dropping the request. + if REPOKE.swap(false, Ordering::SeqCst) { + poke(); + } + }); +} + +/// Pick the next candidate that still has retry budget. Pure — the driver's +/// only decision, kept out of the loop so it is testable. +fn next_candidate(queue: &[repo::HydrationCandidate], failures: &HashMap) -> Option { + queue + .iter() + .map(|c| c.qobuz_playlist_id) + .find(|pid| failures.get(pid).map_or(true, |&n| n < MAX_ATTEMPTS)) +} + +async fn run_round(runtime: &Runtime) { + let mut failures: HashMap = HashMap::new(); + loop { + if crate::offline_fwd::engine().is_offline() { + return; + } + let queue = tokio::task::spawn_blocking(|| { + crate::library_db_qt::with_db(false, |db| Ok(db.with_connection(repo::hydration_queue))) + .and_then(Result::ok) + .unwrap_or_default() + }) + .await + .unwrap_or_default(); + let Some(pid) = next_candidate(&queue, &failures) else { + crate::playlist_picker_qt::membership_index_progressed(); + return; + }; + + match runtime.core().get_playlist_track_ids(pid).await { + Ok(playlist) => { + let wrote = tokio::task::spawn_blocking(move || { + crate::library_db_qt::with_db(true, |db| { + Ok(db.with_connection(|conn| { + let owner = + Some(playlist.owner.name.as_str()).filter(|o| !o.is_empty()); + repo::replace_tracks( + conn, + pid, + &playlist.name, + owner, + &playlist.track_ids, + playlist.updated_at, + ) + })) + }) + }) + .await + .ok() + .flatten() + .and_then(Result::ok) + .unwrap_or(false); + if !wrote { + // Header vanished mid-round (deleted / retired). Spend + // the whole budget so the round moves on. + log::debug!("[qbz-qt] playlist index: {pid} lost its header; skipped"); + failures.insert(pid, MAX_ATTEMPTS); + } + crate::playlist_picker_qt::membership_index_progressed(); + } + Err(e) => { + let n = failures.entry(pid).or_insert(0); + *n += 1; + log::warn!( + "[qbz-qt] playlist index: membership fetch for {pid} failed (attempt {n}): {e}" + ); + // Linear backoff on top of the pace below; bounded by + // MAX_ATTEMPTS so this cannot become a spin. + tokio::time::sleep(std::time::Duration::from_millis(700 * *n as u64)).await; + } + } + tokio::time::sleep(std::time::Duration::from_millis(PACE_MS)).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use repo::{HydrationCandidate, StaleReason}; + + fn candidates(ids: &[u64]) -> Vec { + ids.iter() + .map(|&id| HydrationCandidate { + qobuz_playlist_id: id, + reason: StaleReason::NeverSynced, + }) + .collect() + } + + #[test] + fn next_candidate_skips_exhausted_budgets() { + let queue = candidates(&[1, 2, 3]); + let mut failures = HashMap::new(); + assert_eq!(next_candidate(&queue, &failures), Some(1)); + + failures.insert(1, MAX_ATTEMPTS); + assert_eq!(next_candidate(&queue, &failures), Some(2)); + + failures.insert(2, MAX_ATTEMPTS - 1); + // Budget not exhausted yet: 2 is still first in line. + assert_eq!(next_candidate(&queue, &failures), Some(2)); + + failures.insert(2, MAX_ATTEMPTS); + failures.insert(3, MAX_ATTEMPTS); + // Everything parked: the round ends instead of spinning. + assert_eq!(next_candidate(&queue, &failures), None); + } +} diff --git a/crates/qbz-qt/src/playlist_manager_qt.rs b/crates/qbz-qt/src/playlist_manager_qt.rs index 490e9e6b8..91352a686 100644 --- a/crates/qbz-qt/src/playlist_manager_qt.rs +++ b/crates/qbz-qt/src/playlist_manager_qt.rs @@ -666,17 +666,17 @@ async fn load(runtime: &Runtime) -> PmData { Vec::new() }) }; - crate::playlist_snapshot_qt::record_names_detached( - remote - .iter() - .map(|playlist| crate::playlist_snapshot_qt::SnapshotNameEntry { - qobuz_playlist_id: playlist.id, - name: playlist.name.clone(), - owner: Some(playlist.owner.name.clone()).filter(|owner| !owner.is_empty()), - track_count: Some(playlist.tracks_count), - }) - .collect(), - ); + if !(offline && remote.is_empty()) { + // A failed online fetch also lands here as an empty list; recording it + // would start the two-generation retirement clock on every playlist, + // so only a NON-empty list (or a genuinely deleted-everything account, + // which still lists a session user) is recorded. + if let Some(entries) = crate::playlist_snapshot_qt::authoritative_entries(&remote) { + if !entries.is_empty() { + crate::playlist_snapshot_qt::record_authoritative_detached(entries); + } + } + } let (folders, settings, play_counts, local_counts, locals, fav_ids) = tokio::task::spawn_blocking(|| { diff --git a/crates/qbz-qt/src/playlist_picker_qt.rs b/crates/qbz-qt/src/playlist_picker_qt.rs index e24825ee0..fb102e741 100644 --- a/crates/qbz-qt/src/playlist_picker_qt.rs +++ b/crates/qbz-qt/src/playlist_picker_qt.rs @@ -120,6 +120,18 @@ pub struct PickerRow { pub is_local: bool, } +/// One "Already in" strip card: a writable playlist that already holds some +/// of the carried tracks. +#[derive(Clone, Serialize)] +pub struct AlreadyRow { + pub id: String, + pub name: String, + #[serde(rename = "isLocal")] + pub is_local: bool, + /// How many of the carried tracks it holds (distinct; the "N of M" card). + pub contained: u32, +} + #[derive(Default, Serialize)] pub struct DupDoc { pub open: bool, @@ -154,6 +166,19 @@ pub struct PickerDoc { pub creating_open: bool, pub creating: bool, pub dup: DupDoc, + /// The session's last successful add target, pinned above the list. + /// Present only while it still exists as a writable row, and retained + /// under a search only when it matches the query. + #[serde(rename = "lastUsed")] + pub last_used: Option, + /// Writable playlists that already hold carried tracks — the containment + /// strip. Meaningful only per `already_state`. + #[serde(rename = "alreadyIn")] + pub already_in: Vec, + /// "loading" | "complete" | "updating" | "unavailable" — the honest + /// tri-state (plus the in-flight arm) the strip renders under. + #[serde(rename = "alreadyState")] + pub already_state: String, } /// Everything the modal owns between opens. One mutex: every field is written @@ -173,6 +198,13 @@ struct PickerState { /// answer (the reference's `DUP_CONFIRM_STASH`). `None` = sub-modal closed. dup: Option, dup_busy: bool, + /// Containment strip rows, `None` while the query is in flight. + already_rows: Option>, + /// "complete" | "updating" | "unavailable" once resolved. + already_state: &'static str, + /// Monotonic open counter — a containment result landing after the picker + /// was closed and reopened must not dress the NEW payload. + epoch: u64, } struct DupContext { @@ -188,6 +220,24 @@ struct DupContext { static STATE: std::sync::LazyLock> = std::sync::LazyLock::new(|| Mutex::new(PickerState::default())); +/// Session-local "Last playlist": the id of the last target an add SUCCEEDED +/// against. Never persisted (process exit resets it, by design), never set on +/// a mere open or a failed operation, and validated against the live row list +/// on every publish — a deleted or no-longer-writable playlist simply stops +/// resolving. +static LAST_USED: Mutex> = Mutex::new(None); + +/// Record a confirmed successful add. `n` guards the "nothing actually +/// landed" arms (0-row sidecar writes, empty diffs). +fn set_last_used(playlist_id: &str, n: usize) { + if n == 0 { + return; + } + if let Ok(mut g) = LAST_USED.lock() { + *g = Some(playlist_id.to_string()); + } +} + /// Case-insensitive substring over the playlist name — the reference's /// `filter-changed` rank pass reduced to a filter, because QML can drop rows /// directly and does not need Slint's rank-and-reorder workaround. @@ -200,10 +250,21 @@ fn publish() { let doc = { let st = STATE.lock().unwrap(); let query = st.filter.trim().to_lowercase(); + // The pinned last target: resolved against the LIVE row list, so a + // playlist that disappeared or stopped being writable stops pinning; + // under a search it survives only when it matches the query. + let last_used: Option = LAST_USED + .lock() + .ok() + .and_then(|g| g.clone()) + .and_then(|id| st.all_rows.iter().find(|r| r.id == id).cloned()) + .filter(|r| matches(&r.name, &query)); let playlists: Vec = st .all_rows .iter() .filter(|r| matches(&r.name, &query)) + // De-duplicated from the pinned row, never listed twice. + .filter(|r| last_used.as_ref().map(|l| l.id != r.id).unwrap_or(true)) .cloned() .collect(); PickerDoc { @@ -226,6 +287,13 @@ fn publish() { }, None => DupDoc::default(), }, + last_used, + already_in: st.already_rows.clone().unwrap_or_default(), + already_state: if st.already_rows.is_none() { + "loading".to_string() + } else { + st.already_state.to_string() + }, } }; let json = serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into()); @@ -259,7 +327,7 @@ fn open_payload(runtime: &Runtime, payload: Payload) { if payload.is_empty() { return; } - { + let epoch = { let mut st = STATE.lock().unwrap(); st.open = true; st.loading = true; @@ -272,7 +340,11 @@ fn open_payload(runtime: &Runtime, payload: Payload) { st.creating = false; st.dup = None; st.dup_busy = false; - } + st.already_rows = None; + st.already_state = ""; + st.epoch += 1; + st.epoch + }; publish(); let runtime = runtime.clone(); @@ -282,13 +354,125 @@ fn open_payload(runtime: &Runtime, payload: Payload) { let mut st = STATE.lock().unwrap(); // The user may have closed the picker while the fetch was in // flight; landing rows into a closed picker would re-open it. - if !st.open { + if !st.open || st.epoch != epoch { return; } st.all_rows = rows; st.loading = false; } publish(); + refresh_containment(epoch).await; + }); +} + +/// Compute the containment strip for the CURRENT payload against the live +/// row list, and the honest tri-state it renders under. Row names come from +/// the already-loaded picker rows, which doubles as the writability/liveness +/// join: a containment hit whose playlist is not offered as a target (offline +/// Qobuz half, followed list, deleted) resolves to nothing and is dropped. +async fn refresh_containment(epoch: u64) { + let (payload, rows) = { + let st = STATE.lock().unwrap(); + if !st.open || st.epoch != epoch || st.loading { + return; + } + (st.payload.clone(), st.all_rows.clone()) + }; + let (already, state) = tokio::task::spawn_blocking(move || { + use qbz_library::playlist_membership::{ + playlists_containing, ContainmentTarget, PlaylistTrackRef, + }; + use qbz_library::qobuz_playlist_snapshot::{index_state, MembershipIndexState}; + + let refs: Vec = match &payload { + Payload::Qobuz(ids) => ids.iter().map(|&id| PlaylistTrackRef::Qobuz(id)).collect(), + Payload::LocalRefs(strings) => { + crate::local_playlist_qt::membership_refs_blocking(strings) + } + }; + // Only the Qobuz snapshot can be incomplete; the sidecar and local + // tables are locally authoritative (QBZ is their only writer). + let snapshot_dependent = refs.iter().any(|r| { + matches!(r, PlaylistTrackRef::Qobuz(_)) + || matches!( + r, + PlaylistTrackRef::Library { + qobuz_track_id: Some(_), + .. + } + ) + }); + let result = crate::library_db_qt::with_db(false, |db| { + Ok(db.with_connection(|conn| { + let contained = playlists_containing(conn, &refs)?; + let state = index_state(conn)?; + Ok::<_, rusqlite::Error>((contained, state)) + })) + }) + .and_then(Result::ok); + let Some((contained, state)) = result else { + return (Vec::new(), "unavailable"); + }; + let state = if !snapshot_dependent { + "complete" + } else { + match state { + MembershipIndexState::Complete => "complete", + // "Still updating" would be a lie while offline — nothing is. + MembershipIndexState::Updating { .. } => { + if crate::offline_fwd::engine().is_offline() { + "unavailable" + } else { + "updating" + } + } + MembershipIndexState::Unavailable => "unavailable", + } + }; + let already: Vec = contained + .into_iter() + .filter_map(|c| { + let id = match &c.target { + ContainmentTarget::Qobuz(pid) => pid.to_string(), + ContainmentTarget::Local(id) => id.clone(), + }; + rows.iter().find(|r| r.id == id).map(|r| AlreadyRow { + id, + name: r.name.clone(), + is_local: r.is_local, + contained: c.contained, + }) + }) + .take(20) + .collect(); + (already, state) + }) + .await + .unwrap_or_else(|_| (Vec::new(), "unavailable")); + { + let mut st = STATE.lock().unwrap(); + if !st.open || st.epoch != epoch { + return; + } + st.already_rows = Some(already); + st.already_state = state; + } + publish(); +} + +/// Hydrator progress callback: while the picker is open, each committed +/// membership snapshot (and the final state flip to Complete) re-answers the +/// containment question live. +pub fn membership_index_progressed() { + let epoch = { + let st = STATE.lock().unwrap(); + if !st.open || st.loading { + return; + } + st.epoch + }; + crate::spawn(async move { + refresh_containment(epoch).await; }); } @@ -316,12 +500,25 @@ async fn load(runtime: &Runtime) -> Vec { return out; } match runtime.core().get_user_playlists().await { - Ok(playlists) => out.extend(playlists.into_iter().map(|p| PickerRow { - id: p.id.to_string(), - name: p.name, - tracks_line: tracks_line(p.tracks_count), - is_local: false, - })), + Ok(playlists) => out.extend( + playlists + .into_iter() + // Followed playlists are read-only on the API and must never + // be offered as add targets. Before the session user id is + // known ownership cannot be told apart, so the pre-existing + // behaviour (list everything) is kept for that window rather + // than blanking the Qobuz half. + .filter(|p| { + !crate::playlist_qt::session_user_known() + || crate::playlist_qt::owns(p.owner.id) + }) + .map(|p| PickerRow { + id: p.id.to_string(), + name: p.name, + tracks_line: tracks_line(p.tracks_count), + is_local: false, + }), + ), Err(e) => log::warn!("[qbz-qt] playlist picker load failed: {e}"), } out @@ -417,6 +614,7 @@ pub fn pick(playlist_id: &str) { }) .await .unwrap_or(0); + set_last_used(&open_target, added); toast_added(added, &name); refresh_local_target(&runtime, &open_target).await; }); @@ -438,6 +636,7 @@ pub fn pick(playlist_id: &str) { let qobuz_count = crate::sidebar_qt::playlist_track_count(pid).unwrap_or(0); crate::spawn(async move { let written = write_sidecar_refs(pid, qobuz_count, refs).await; + set_last_used(&pid.to_string(), written); toast_added(written, &name); // E12: the open detail re-merges so the rows show up now. crate::playlist_qt::refresh_after_membership_change(&runtime, pid).await; @@ -573,17 +772,22 @@ pub fn create_and_add(name: &str) { crate::toast_qt::error(qbz_i18n::t("Couldn't create the playlist")); return; }; - let added = tokio::task::spawn_blocking(move || match payload { - Payload::LocalRefs(refs) => { - crate::local_playlist_qt::add_local_refs_blocking(&new_id, &refs) - } - Payload::Qobuz(ids) => { - crate::local_playlist_qt::add_qobuz_tracks_blocking(&new_id, &ids) + let added = tokio::task::spawn_blocking({ + let new_id = new_id.clone(); + move || match payload { + Payload::LocalRefs(refs) => { + crate::local_playlist_qt::add_local_refs_blocking(&new_id, &refs) + } + Payload::Qobuz(ids) => { + crate::local_playlist_qt::add_qobuz_tracks_blocking(&new_id, &ids) + } } }) .await .unwrap_or(0); close(); + // Create-and-add counts as a use even when the payload was empty. + set_last_used(&new_id, added.max(1)); toast_added(added, &name); // The new playlist has to appear in the sidebar, or the user's // only evidence it exists is the toast — and `reload_sidebar` @@ -597,6 +801,28 @@ pub fn create_and_add(name: &str) { match runtime.core().create_playlist(&name, None, false).await { Ok(playlist) => { let pid = playlist.id; + // Snapshot the newborn header FIRST (owned, empty, captured): + // the incremental producer below refuses playlists it has + // never captured, and the authoritative list will not name + // this one until Qobuz's post-write lag clears. + { + let owner_name = playlist.owner.name.clone(); + let created_name = name.clone(); + let _ = tokio::task::spawn_blocking(move || { + crate::library_db_qt::with_db(true, |db| { + Ok(db.with_connection(|conn| { + qbz_library::qobuz_playlist_snapshot::record_created_playlist( + conn, + pid, + &created_name, + Some(owner_name.as_str()).filter(|o| !o.is_empty()), + ) + })) + }) + }) + .await; + } + set_last_used(&pid.to_string(), 1); match payload { Payload::Qobuz(ids) if !ids.is_empty() => { add_and_toast(&runtime, pid, ids, name).await; @@ -681,12 +907,35 @@ async fn add_and_toast(runtime: &Runtime, pid: u64, ids: Vec, name: String) crate::toast_qt::error(qbz_i18n::t("Failed to add tracks")); return; } + set_last_used(&pid.to_string(), n); + snapshot_added_detached(pid, ids); // The sidebar's per-playlist track count is now stale, and a playlist page // open on this id must re-merge (the reference's E12 refresh). crate::playlist_qt::refresh_after_membership_change(runtime, pid).await; toast_added(n, &name); } +/// Move the membership snapshot with a CONFIRMED add, off-thread, so the +/// containment answer is already right the next time the picker opens — +/// without waiting for the hydrator or a detail load. +fn snapshot_added_detached(pid: u64, ids: Vec) { + tokio::task::spawn_blocking(move || { + let applied = crate::library_db_qt::with_db(true, |db| { + Ok(db.with_connection(|conn| { + qbz_library::qobuz_playlist_snapshot::apply_added_tracks(conn, pid, &ids) + })) + }) + .and_then(Result::ok) + .unwrap_or(false); + if applied { + membership_index_progressed(); + } else { + // Membership never captured: the hydrator owns this playlist. + crate::playlist_index_qt::poke(); + } + }); +} + /// The shared success toast (the reference's `toast_added_tracks`). Every arm /// of the matrix ends here, so the wording cannot drift between them. A zero /// count is silent: the repo layer already logged WHY nothing landed. diff --git a/crates/qbz-qt/src/playlist_qt.rs b/crates/qbz-qt/src/playlist_qt.rs index fe5c5dd4a..89e3eacc1 100644 --- a/crates/qbz-qt/src/playlist_qt.rs +++ b/crates/qbz-qt/src/playlist_qt.rs @@ -531,6 +531,12 @@ pub fn set_user_playlists(pairs: &[(u64, u64)]) { } } +/// Is the session user id known yet? Ownership answers are meaningless (all +/// false) before it is. +pub fn session_user_known() -> bool { + USER_ID.load(std::sync::atomic::Ordering::SeqCst) != 0 +} + /// Does the signed-in user own this playlist, by OWNER id? The cheap arm — /// every card producer already has `owner.id` on the row it is mapping, so it /// needs no set lookup at all. @@ -1770,6 +1776,18 @@ pub async fn delete_by_id( "[qbz-qt] playlist {pid} {}", if owned { "deleted" } else { "unsubscribed" } ); + if owned { + // Leave the membership index's target set now instead of waiting out + // the authoritative-list retirement grace. + let _ = tokio::task::spawn_blocking(move || { + crate::library_db_qt::with_db(true, |db| { + Ok(db.with_connection(|conn| { + qbz_library::qobuz_playlist_snapshot::mark_inactive(conn, pid) + })) + }) + }) + .await; + } Ok(()) } @@ -1824,24 +1842,53 @@ pub async fn remove_track(runtime: &Arc>, playlist_tr return; }; let Some(pid) = pid else { return }; - // Optimistic removal; the API is the source of truth on failure. - with_doc(|d| { + // Optimistic removal; the API is the source of truth on failure. The + // row's CATALOG id is captured before it goes — the membership snapshot + // speaks track ids, not membership-row ids. + let removed_track_id = with_doc(|d| { + let track_id = d + .tracks + .iter() + .find(|t| t.playlist_track_id == playlist_track_id) + .and_then(|t| t.id.parse::().ok()); d.tracks .retain(|t| t.playlist_track_id != playlist_track_id); d.track_count = d.tracks.len() as i32; d.total_duration = total_duration_label(&d.tracks); let doc = d.clone(); publish(&doc); - }); - if let Err(e) = runtime + track_id + }) + .flatten(); + match runtime .core() .remove_tracks_from_playlist(pid, &[playlist_track_id]) .await { - log::error!("[qbz-qt] remove track {playlist_track_id} from playlist {pid} failed: {e}"); - // Reload to reconcile (bounded-retry equivalent — the Slint - // reconciles the same way after failed playlist ops). - let _ = load(runtime, pid).await; + Ok(()) => { + if let Some(track_id) = removed_track_id { + let _ = tokio::task::spawn_blocking(move || { + crate::library_db_qt::with_db(true, |db| { + Ok(db.with_connection(|conn| { + qbz_library::qobuz_playlist_snapshot::apply_removed_tracks( + conn, + pid, + &[track_id], + ) + })) + }) + }) + .await; + } + } + Err(e) => { + log::error!( + "[qbz-qt] remove track {playlist_track_id} from playlist {pid} failed: {e}" + ); + // Reload to reconcile (bounded-retry equivalent — the Slint + // reconciles the same way after failed playlist ops). + let _ = load(runtime, pid).await; + } } } diff --git a/crates/qbz-qt/src/playlist_snapshot_qt.rs b/crates/qbz-qt/src/playlist_snapshot_qt.rs index 629f4c062..d34352706 100644 --- a/crates/qbz-qt/src/playlist_snapshot_qt.rs +++ b/crates/qbz-qt/src/playlist_snapshot_qt.rs @@ -9,18 +9,50 @@ use std::collections::{HashMap, HashSet}; use qbz_library::qobuz_playlist_snapshot as repo; -pub use repo::SnapshotNameEntry; +pub use repo::AuthoritativeEntry; -pub fn record_names_detached(entries: Vec) { - if entries.is_empty() { - return; +/// Turn one `get_user_playlists()` response into authoritative snapshot +/// entries. Ownership comes from the session user id; when that id is not +/// known yet the caller must SKIP recording — an all-foreign list would both +/// starve the hydrator and start the two-generation retirement clock. +pub fn authoritative_entries( + playlists: &[qbz_models::Playlist], +) -> Option> { + if !crate::playlist_qt::session_user_known() { + log::debug!( + "[qbz-qt] playlist snapshot: session user unknown; authoritative list not recorded" + ); + return None; } + Some( + playlists + .iter() + .map(|playlist| AuthoritativeEntry { + qobuz_playlist_id: playlist.id, + name: playlist.name.clone(), + owner: Some(playlist.owner.name.clone()).filter(|owner| !owner.is_empty()), + track_count: Some(playlist.tracks_count), + remote_updated_at: playlist.updated_at, + is_owned: crate::playlist_qt::owns(playlist.owner.id), + }) + .collect(), + ) +} + +pub fn record_authoritative_detached(entries: Vec) { let write = move || { let result = crate::library_db_qt::with_db(true, |db| { - Ok(db.with_connection(|conn| repo::upsert_names(conn, &entries))) + Ok(db.with_connection(|conn| repo::record_authoritative_list(conn, &entries))) }); - if let Some(Err(error)) = result { - log::warn!("[qbz-qt] playlist snapshot names write failed: {error}"); + match result { + Some(Ok(generation)) => { + log::debug!("[qbz-qt] playlist snapshot: authoritative generation {generation}"); + crate::playlist_index_qt::poke(); + } + Some(Err(error)) => { + log::warn!("[qbz-qt] playlist snapshot authoritative write failed: {error}") + } + None => {} } }; if tokio::runtime::Handle::try_current().is_ok() { @@ -35,11 +67,11 @@ pub fn record_detail_detached(playlist_id: u64, name: String, owner: String, tra let owner = Some(owner.as_str()).filter(|value| !value.is_empty()); let result = crate::library_db_qt::with_db(true, |db| { Ok(db.with_connection(|conn| { - repo::replace_tracks(conn, playlist_id, &name, owner, &track_ids) + repo::replace_tracks(conn, playlist_id, &name, owner, &track_ids, None) })) }); match result { - Some(Ok(true)) => {} + Some(Ok(true)) => crate::playlist_picker_qt::membership_index_progressed(), Some(Ok(false)) => log::debug!( "[qbz-qt] playlist snapshot: {playlist_id} is not in the user list; membership skipped" ), diff --git a/crates/qbz-qt/src/sidebar_qt.rs b/crates/qbz-qt/src/sidebar_qt.rs index f508d26c5..e78e312f4 100644 --- a/crates/qbz-qt/src/sidebar_qt.rs +++ b/crates/qbz-qt/src/sidebar_qt.rs @@ -220,26 +220,15 @@ pub async fn load(runtime: &Arc>) { log::debug!("[qbz-qt] sidebar load: fetching user playlists"); match runtime.core().get_user_playlists().await { Ok(pls) => { - crate::playlist_snapshot_qt::record_names_detached( - pls.iter() - .map(|playlist| crate::playlist_snapshot_qt::SnapshotNameEntry { - qobuz_playlist_id: playlist.id, - name: playlist.name.clone(), - owner: Some(playlist.owner.name.clone()) - .filter(|owner| !owner.is_empty()), - track_count: Some(playlist.tracks_count), - }) - .collect(), - ); - // Same response, second consumer: the playlist ownership / - // follow snapshot every PlaylistCard's tri-state overlay reads - // (`playlist_qt::set_user_playlists`). This is the earliest point - // in the session where the user's own playlist list exists, and - // it costs no extra request — the alternative was every card - // rendering the "follow a foreign playlist" arm until the Library - // view had been opened at least once. + // Ownership snapshot FIRST — every PlaylistCard's tri-state + // overlay reads it, this is the earliest point in the session + // where the user's own list exists, and `authoritative_entries` + // below depends on the sets this call seeds. let pairs: Vec<(u64, u64)> = pls.iter().map(|p| (p.id, p.owner.id)).collect(); crate::playlist_qt::set_user_playlists(&pairs); + if let Some(entries) = crate::playlist_snapshot_qt::authoritative_entries(&pls) { + crate::playlist_snapshot_qt::record_authoritative_detached(entries); + } pls } Err(e) => { From 49847363703cd14f2a5e151b34ed91c38ca1c3c5 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 17:23:58 -0600 Subject: [PATCH 05/10] feat(qt): picker modal pins last playlist and shows containment strip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dropdown pins the session's last successful target above the results (clock glyph, de-duplicated by Rust, retained under a search only when it matches). The body gains the collapsible Already in strip: one card per writable playlist already holding carried tracks, with an N-of-M badge on partial multi-track containment; clicking a card selects that playlist so completing a partial add is one click plus the duplicate-confirm's only-new answer. The strip renders only when the index can back the claim — complete with matches, or updating under an explicit caveat — and an empty answer from an incomplete index renders nothing. Four new strings in all eight locales. cc --- .../translations/de/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/en/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/es/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/fr/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/ja/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/nl/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/pt/LC_MESSAGES/qbz-ui.po | 12 ++ .../translations/ru/LC_MESSAGES/qbz-ui.po | 12 ++ .../qml/controls/PlaylistPickerModal.qml | 199 +++++++++++++++++- 9 files changed, 292 insertions(+), 3 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 94f03cfee..c17181f2f 100644 --- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po @@ -6254,3 +6254,15 @@ msgstr "Filterbereiche anzeigen" msgid "Hide filter panels" msgstr "Filterbereiche ausblenden" + +msgid "Already in" +msgstr "Bereits in" + +msgid "Playlist index updating..." +msgstr "Playlist-Index wird aktualisiert..." + +msgid "{} of {}" +msgstr "{} von {}" + +msgid "Last playlist" +msgstr "Letzte Playlist" 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 054b1f46d..fcb30bcd9 100644 --- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po @@ -1874,3 +1874,15 @@ msgstr "Show filter panels" msgid "Hide filter panels" msgstr "Hide filter panels" + +msgid "Already in" +msgstr "Already in" + +msgid "Playlist index updating..." +msgstr "Playlist index updating..." + +msgid "{} of {}" +msgstr "{} of {}" + +msgid "Last playlist" +msgstr "Last playlist" 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 f40a596d6..47f05f0ec 100644 --- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po @@ -6260,3 +6260,15 @@ msgstr "Mostrar los paneles de filtros" msgid "Hide filter panels" msgstr "Ocultar los paneles de filtros" + +msgid "Already in" +msgstr "Ya está en" + +msgid "Playlist index updating..." +msgstr "Actualizando el índice de playlists..." + +msgid "{} of {}" +msgstr "{} de {}" + +msgid "Last playlist" +msgstr "Última playlist" 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 071328ca5..6dc3f3020 100644 --- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po @@ -6252,3 +6252,15 @@ msgstr "Afficher les panneaux de filtres" msgid "Hide filter panels" msgstr "Masquer les panneaux de filtres" + +msgid "Already in" +msgstr "Déjà dans" + +msgid "Playlist index updating..." +msgstr "Mise à jour de l'index des playlists..." + +msgid "{} of {}" +msgstr "{} sur {}" + +msgid "Last playlist" +msgstr "Dernière playlist" 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 b2560bf54..0f56e5b04 100644 --- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po @@ -6236,3 +6236,15 @@ msgstr "フィルターパネルを表示" msgid "Hide filter panels" msgstr "フィルターパネルを非表示" + +msgid "Already in" +msgstr "追加済み" + +msgid "Playlist index updating..." +msgstr "プレイリストの索引を更新中..." + +msgid "{} of {}" +msgstr "{} / {}" + +msgid "Last playlist" +msgstr "前回のプレイリスト" 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 ee86f7e14..1dce9cbfc 100644 --- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po @@ -6242,3 +6242,15 @@ msgstr "Filterpanelen tonen" msgid "Hide filter panels" msgstr "Filterpanelen verbergen" + +msgid "Already in" +msgstr "Al in" + +msgid "Playlist index updating..." +msgstr "Playlist-index wordt bijgewerkt..." + +msgid "{} of {}" +msgstr "{} van {}" + +msgid "Last playlist" +msgstr "Laatste playlist" 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 fab48cc4f..40a91ceab 100644 --- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po @@ -6252,3 +6252,15 @@ msgstr "Mostrar os painéis de filtros" msgid "Hide filter panels" msgstr "Ocultar os painéis de filtros" + +msgid "Already in" +msgstr "Já está em" + +msgid "Playlist index updating..." +msgstr "Atualizando o índice de playlists..." + +msgid "{} of {}" +msgstr "{} de {}" + +msgid "Last playlist" +msgstr "Última playlist" 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 72aee95a7..c31218e93 100644 --- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po @@ -6272,3 +6272,15 @@ msgstr "Показать панели фильтров" msgid "Hide filter panels" msgstr "Скрыть панели фильтров" + +msgid "Already in" +msgstr "Уже в" + +msgid "Playlist index updating..." +msgstr "Индекс плейлистов обновляется..." + +msgid "{} of {}" +msgstr "{} из {}" + +msgid "Last playlist" +msgstr "Последний плейлист" diff --git a/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml b/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml index ea5a1fdfb..94de80060 100644 --- a/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml +++ b/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml @@ -42,6 +42,21 @@ Item { readonly property var rows: doc.playlists || [] readonly property var dup: doc.dup || ({}) readonly property int trackCount: doc.trackCount || 0 + // Session-local pinned target (last successful add); null when unset, + // deleted, unwritable, or filtered out by the current query. + readonly property var lastUsed: doc.lastUsed || null + // Containment strip: writable playlists already holding carried tracks, + // honest per alreadyState ("loading"|"complete"|"updating"|"unavailable"). + readonly property var alreadyIn: doc.alreadyIn || [] + readonly property string alreadyState: doc.alreadyState || "" + // The strip renders only when it can back a claim: complete with matches, + // or updating (where partial matches show under an explicit caveat). + readonly property bool alreadyShowing: !root.creatingOpen + && (root.alreadyState === "updating" + || (root.alreadyState === "complete" && root.alreadyIn.length > 0)) + // Independently collapsible (session-local: the modal mounts once per + // app run and this deliberately survives resetLocals()). + property bool alreadyCollapsed: false // The carried payload is LocalLibrary refs (counter wording only). readonly property bool localMode: doc.localMode === true readonly property bool creatingOpen: doc.creatingOpen === true @@ -368,6 +383,127 @@ Item { } } } + + // --- "Already in" containment strip ---------------- + // Writable playlists that already hold carried tracks. + // Shown only when the index can back the claim: complete + // with matches, or updating under an explicit caveat — + // an empty answer from an incomplete index says NOTHING + // and renders nothing (ADD_TO_PLAYLIST_REDESIGN.md). + Column { + width: parent.width - 48 + spacing: 8 + visible: root.alreadyShowing + + Item { + width: parent.width + height: 20 + Row { + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + spacing: 6 + Text { + anchors.verticalCenter: parent.verticalCenter + text: QbzSession.tr("Already in", QbzSession.trRev) + color: theme.textSecondary + font.pixelSize: theme.fontLegal + font.weight: theme.weightMedium + } + QbzIcon { + anchors.verticalCenter: parent.verticalCenter + name: root.alreadyCollapsed ? "chevron-down" : "chevron-up" + width: 12 + height: 12 + tintName: alreadyToggle.containsMouse ? "textPrimary" : "muted" + } + } + MouseArea { + id: alreadyToggle + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.alreadyCollapsed = !root.alreadyCollapsed + } + Text { + visible: root.alreadyState === "updating" + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + text: QbzSession.tr("Playlist index updating...", QbzSession.trRev) + color: theme.textMuted + font.pixelSize: theme.fontLegal + font.italic: true + } + } + + ListView { + visible: !root.alreadyCollapsed && root.alreadyIn.length > 0 + width: parent.width + height: visible ? 32 : 0 + orientation: ListView.Horizontal + spacing: 8 + clip: true + boundsBehavior: Flickable.StopAtBounds + model: root.alreadyIn + delegate: Rectangle { + required property var modelData + width: alreadyRow.implicitWidth + 20 + height: 30 + radius: 6 + color: alreadyArea.containsMouse + ? theme.surfaceHover : theme.surfaceElevated + border.width: 1 + border.color: theme.borderSubtle + Row { + id: alreadyRow + anchors.centerIn: parent + spacing: 6 + QbzIcon { + visible: modelData.isLocal === true + anchors.verticalCenter: parent.verticalCenter + name: "hard-drive" + width: 12 + height: 12 + tintName: "muted" + } + Text { + anchors.verticalCenter: parent.verticalCenter + // Cap so one long name cannot push the + // whole strip off-card; implicitWidth + // is layout-independent, so this is + // not a binding loop. + width: Math.min(implicitWidth, 180) + text: modelData.name + color: theme.textPrimary + font.pixelSize: theme.fontLegal + elide: Text.ElideRight + } + // The multi-track card: "2 of 5". A full + // or single-track containment says it by + // presence alone. + Text { + visible: root.trackCount > 1 + && modelData.contained < root.trackCount + anchors.verticalCenter: parent.verticalCenter + text: QbzSession.tr("{} of {}", QbzSession.trRev) + .replace("{}", modelData.contained) + .replace("{}", root.trackCount) + color: theme.textMuted + font.pixelSize: theme.fontLegal + } + } + MouseArea { + id: alreadyArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + // Selecting it is the useful action: "add + // the missing 3 of 5" is one click plus + // the dup-confirm's "only new" answer. + onClicked: root.selectRow(modelData) + } + } + } + } } } @@ -426,9 +562,11 @@ Item { // 43 input + 4 gap. y: 68 + 1 + 24 + 20 + 8 + 43 + 4 width: parent.width - 48 - // create row 41 + 1 divider, 41 per shown row, 41 no-results, - // 1 + 34 overflow. Tauri max-height 320 + border. - height: Math.min(2 + 42 + root.shown * 41 + // create row 41 + 1 divider, pinned last-used 41 + 1, 41 per + // shown row, 41 no-results, 1 + 34 overflow. Tauri max-height + // 320 + border. + height: Math.min(2 + 42 + (root.lastUsed !== null ? 42 : 0) + + root.shown * 41 + ((root.rows.length === 0 && root.filterText !== "") ? 41 : 0) + (root.overflow > 0 ? 35 : 0), 322) radius: theme.radiusSm @@ -487,6 +625,61 @@ Item { } Rectangle { width: parent.width; height: 1; color: theme.borderSubtle } + // Session's last successful target, pinned above the + // results. Rust already validated it (still listed, + // still writable) and de-duplicated it from `rows`; + // under a search it only survives a matching query. + Rectangle { + visible: root.lastUsed !== null + width: parent.width + height: visible ? 41 : 0 + color: lastUsedArea.containsMouse ? theme.surfaceHover : "transparent" + QbzIcon { + id: lastUsedGlyph + anchors.left: parent.left + anchors.leftMargin: 12 + anchors.verticalCenter: parent.verticalCenter + name: "clock" + width: 14 + height: 14 + tintName: "muted" + } + Text { + anchors.left: lastUsedGlyph.right + anchors.leftMargin: 8 + anchors.right: lastUsedCaption.left + anchors.rightMargin: 8 + anchors.verticalCenter: parent.verticalCenter + text: root.lastUsed ? root.lastUsed.name : "" + color: theme.textPrimary + font.pixelSize: theme.fontLink + elide: Text.ElideRight + } + Text { + id: lastUsedCaption + anchors.right: parent.right + anchors.rightMargin: 12 + anchors.verticalCenter: parent.verticalCenter + text: QbzSession.tr("Last playlist", QbzSession.trRev) + color: theme.textMuted + font.pixelSize: theme.fontLegal + font.italic: true + } + MouseArea { + id: lastUsedArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.selectRow(root.lastUsed) + } + } + Rectangle { + visible: root.lastUsed !== null + width: parent.width + height: visible ? 1 : 0 + color: theme.borderSubtle + } + Repeater { model: root.rows.slice(0, root.windowSize) delegate: Rectangle { From c6ae362b7eb5872c70125596796451af43681126 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 18:58:21 -0600 Subject: [PATCH 06/10] fix(qt): converging playlist index; explorer picker; remote rows first-class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The membership hydrator looped forever on one playlist (smoke 2026-08-30): playlist/get and getUserPlaylists do not report comparable updated_at stamps, so the revision evidence never settled, and the driver had no forward-progress guard. replace_tracks now copies the HEADER's revision into the membership evidence, staleness requires comparable evidence on both sides (count is the fallback when either is missing), and a playlist successfully written in a round is never fetched again within it — after the initial index build, only the playlists the authoritative list reports changed re-sync. Library Explorer rows never opened the picker: the bulk resolver did not know the explorer's own row caches and dropped every merged Plex/remote row. It reads them now, and Jellyfin/Subsonic tracks are first-class playlist citizens: source-prefixed refs (the Plex pattern), a playlist_remote_tracks sidecar for Qobuz playlists, source-qualified rows in local playlists, read resolution through the media cache, and containment arms in the membership index. cc --- crates/qbz-library/src/database.rs | 183 +++++++++++++++++- crates/qbz-library/src/local_playlists.rs | 29 ++- crates/qbz-library/src/playlist_membership.rs | 178 ++++++++++++++--- .../src/qobuz_playlist_snapshot.rs | 144 +++++++++----- crates/qbz-qt/src/local_album_actions.rs | 10 + crates/qbz-qt/src/local_bulk.rs | 23 ++- crates/qbz-qt/src/local_playlist_qt.rs | 144 +++++++++++++- crates/qbz-qt/src/media_servers_qt.rs | 50 +++++ crates/qbz-qt/src/playlist_index_qt.rs | 63 ++++-- crates/qbz-qt/src/playlist_picker_qt.rs | 47 +++++ crates/qbz-qt/src/playlist_snapshot_qt.rs | 2 +- crates/qbz-qt/src/search_qt.rs | 3 +- 12 files changed, 771 insertions(+), 105 deletions(-) diff --git a/crates/qbz-library/src/database.rs b/crates/qbz-library/src/database.rs index 7328a508b..bb4c058f0 100644 --- a/crates/qbz-library/src/database.rs +++ b/crates/qbz-library/src/database.rs @@ -290,6 +290,27 @@ impl LibraryDatabase { CREATE INDEX IF NOT EXISTS idx_playlist_plex_tracks_key ON playlist_plex_tracks(plex_rating_key, qobuz_playlist_id); + -- Jellyfin/Subsonic tracks added to playlists (2026-08-30). Their + -- library rows are media-cache projections with no local_tracks + -- rowid, so they get their own sidecar keyed by the server item + -- id — the plex_rating_key pattern, source-qualified because two + -- protocols share the table. + CREATE TABLE IF NOT EXISTS playlist_remote_tracks ( + id INTEGER PRIMARY KEY, + qobuz_playlist_id INTEGER NOT NULL, + source TEXT NOT NULL, + item_id TEXT NOT NULL, + position INTEGER NOT NULL, + added_at INTEGER NOT NULL, + UNIQUE(qobuz_playlist_id, source, item_id) + ); + + CREATE INDEX IF NOT EXISTS idx_playlist_remote_tracks_playlist + ON playlist_remote_tracks(qobuz_playlist_id); + + CREATE INDEX IF NOT EXISTS idx_playlist_remote_tracks_item + ON playlist_remote_tracks(source, item_id, qobuz_playlist_id); + -- Custom track order per playlist (user-defined arrangement) CREATE TABLE IF NOT EXISTS playlist_track_custom_order ( id INTEGER PRIMARY KEY, @@ -5003,6 +5024,104 @@ impl LibraryDatabase { Ok(()) } + /// Attach a Jellyfin/Subsonic track to a Qobuz playlist by its server + /// item id — the Plex pattern, source-qualified. Re-adding MOVES the row + /// to the new slot rather than duplicating it (INSERT OR REPLACE on the + /// UNIQUE key, edge E4). + pub fn add_remote_track_to_playlist( + &self, + qobuz_playlist_id: u64, + source: &str, + item_id: &str, + position: i32, + ) -> Result<(), LibraryError> { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + + self.conn + .execute( + "INSERT OR REPLACE INTO playlist_remote_tracks + (qobuz_playlist_id, source, item_id, position, added_at) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![qobuz_playlist_id as i64, source, item_id, position, now], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to add remote track to playlist: {}", e)) + })?; + + Ok(()) + } + + /// Remove a Jellyfin/Subsonic track from a playlist. + pub fn remove_remote_track_from_playlist( + &self, + qobuz_playlist_id: u64, + source: &str, + item_id: &str, + ) -> Result<(), LibraryError> { + self.conn + .execute( + "DELETE FROM playlist_remote_tracks + WHERE qobuz_playlist_id = ?1 AND source = ?2 AND item_id = ?3", + params![qobuz_playlist_id as i64, source, item_id], + ) + .map_err(|e| { + LibraryError::Database(format!( + "Failed to remove remote track from playlist: {}", + e + )) + })?; + Ok(()) + } + + /// `(source, item_id, position)` of every remote sidecar row of one + /// playlist, position ASC. + pub fn get_playlist_remote_tracks_with_position( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT source, item_id, position FROM playlist_remote_tracks + WHERE qobuz_playlist_id = ?1 + ORDER BY position ASC, added_at ASC, id ASC", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?; + let rows = stmt + .query_map(params![qobuz_playlist_id as i64], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, i32>(2)?, + )) + }) + .map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?; + let mut out = Vec::new(); + for row in rows { + out.push( + row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?, + ); + } + Ok(out) + } + + /// Number of remote sidecar rows of one playlist. + pub fn get_playlist_remote_track_count( + &self, + qobuz_playlist_id: u64, + ) -> Result { + self.conn + .query_row( + "SELECT COUNT(*) FROM playlist_remote_tracks WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |row| row.get::<_, u32>(0), + ) + .map_err(|e| LibraryError::Database(format!("Failed to count remote tracks: {}", e))) + } + /// Remove a Plex track from a playlist. pub fn remove_plex_track_from_playlist( &self, @@ -5306,6 +5425,29 @@ impl LibraryDatabase { *result.entry(playlist_id).or_insert(0) += count; } + let mut remote_stmt = self + .conn + .prepare( + "SELECT qobuz_playlist_id, COUNT(*) as count + FROM playlist_remote_tracks + GROUP BY qobuz_playlist_id", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?; + + let remote_rows = remote_stmt + .query_map([], |row| { + let playlist_id: i64 = row.get(0)?; + let count: u32 = row.get(1)?; + Ok((playlist_id as u64, count)) + }) + .map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?; + + for row in remote_rows { + let (playlist_id, count) = + row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?; + *result.entry(playlist_id).or_insert(0) += count; + } + Ok(result) } @@ -5365,6 +5507,7 @@ impl LibraryDatabase { ) -> Result { let local_count = self.get_playlist_local_track_count(qobuz_playlist_id)?; let plex_count = self.get_playlist_plex_track_count(qobuz_playlist_id)?; + let remote_count = self.get_playlist_remote_track_count(qobuz_playlist_id)?; let max_pos: Option = self .conn .query_row( @@ -5374,6 +5517,9 @@ impl LibraryDatabase { UNION ALL SELECT MAX(position) AS p FROM playlist_plex_tracks WHERE qobuz_playlist_id = ?1 + UNION ALL + SELECT MAX(position) AS p FROM playlist_remote_tracks + WHERE qobuz_playlist_id = ?1 )", params![qobuz_playlist_id as i64], |row| row.get(0), @@ -5381,7 +5527,7 @@ impl LibraryDatabase { .map_err(|e| { LibraryError::Database(format!("Failed to read max sidecar position: {}", e)) })?; - let count_based = (qobuz_track_count + local_count + plex_count) as i32; + let count_based = (qobuz_track_count + local_count + plex_count + remote_count) as i32; Ok(count_based.max(max_pos.map(|p| p + 1).unwrap_or(0))) } @@ -5463,6 +5609,33 @@ impl LibraryDatabase { rows.push(("plex", rowid, key, pos)); } } + { + let mut stmt = self + .conn + .prepare( + "SELECT id, source || ':' || item_id, position FROM playlist_remote_tracks + WHERE qobuz_playlist_id = ?1 + ORDER BY position ASC, added_at ASC, id ASC", + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to prepare heal query: {}", e)) + })?; + let mapped = stmt + .query_map(params![qobuz_playlist_id as i64], |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, String>(1)?, + row.get::<_, i32>(2)?, + )) + }) + .map_err(|e| LibraryError::Database(format!("Failed to query heal rows: {}", e)))?; + for r in mapped { + let (rowid, key, pos) = r.map_err(|e| { + LibraryError::Database(format!("Failed to read heal row: {}", e)) + })?; + rows.push(("remote", rowid, key, pos)); + } + } if rows.is_empty() { return Ok(Vec::new()); } @@ -5481,10 +5654,10 @@ impl LibraryDatabase { let mut next = ((qobuz_track_count as i32) + sidecar_total as i32).max(max_pos + 1); let mut healed = Vec::with_capacity(moves.len()); for (kind, rowid, reference, old) in moves { - let sql = if kind == "local" { - "UPDATE playlist_local_tracks SET position = ?1 WHERE id = ?2" - } else { - "UPDATE playlist_plex_tracks SET position = ?1 WHERE id = ?2" + let sql = match kind { + "local" => "UPDATE playlist_local_tracks SET position = ?1 WHERE id = ?2", + "plex" => "UPDATE playlist_plex_tracks SET position = ?1 WHERE id = ?2", + _ => "UPDATE playlist_remote_tracks SET position = ?1 WHERE id = ?2", }; self.conn.execute(sql, params![next, rowid]).map_err(|e| { LibraryError::Database(format!("Failed to heal sidecar position: {}", e)) diff --git a/crates/qbz-library/src/local_playlists.rs b/crates/qbz-library/src/local_playlists.rs index f3ab169a0..3dc69ecaf 100644 --- a/crates/qbz-library/src/local_playlists.rs +++ b/crates/qbz-library/src/local_playlists.rs @@ -23,11 +23,18 @@ pub fn is_local_playlist_id(id: &str) -> bool { } /// Track source inside a local playlist. +/// +/// Jellyfin/Subsonic rows (2026-08-30) store the SERVER ITEM ID in the +/// `local_path` column — the same convention their library projection uses +/// for `file_path`: that column is "the source-native locator", not always a +/// filesystem path. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LocalPlaylistTrackSource { Qobuz, Local, Plex, + Jellyfin, + Subsonic, } impl LocalPlaylistTrackSource { @@ -36,12 +43,16 @@ impl LocalPlaylistTrackSource { Self::Qobuz => "qobuz", Self::Local => "local", Self::Plex => "plex", + Self::Jellyfin => "jellyfin", + Self::Subsonic => "subsonic", } } fn parse(s: &str) -> Self { match s { "local" => Self::Local, "plex" => Self::Plex, + "jellyfin" => Self::Jellyfin, + "subsonic" => Self::Subsonic, _ => Self::Qobuz, } } @@ -86,12 +97,15 @@ pub struct LocalPlaylistTrack { pub added_at: i64, } -/// Input for `add_tracks` — exactly one of the three refs per source. +/// Input for `add_tracks` — exactly one source-native ref per variant. +/// Jellyfin/Subsonic carry the server item id (stored in `local_path`). #[derive(Debug, Clone)] pub enum LocalPlaylistTrackInput { Qobuz(u64), Local(String), Plex(String), + Jellyfin(String), + Subsonic(String), } fn now_ms() -> i64 { @@ -344,7 +358,12 @@ fn hydrate_counts(conn: &Connection, p: &mut LocalPlaylist) -> Result<()> { match LocalPlaylistTrackSource::parse(&source) { LocalPlaylistTrackSource::Qobuz => p.qobuz_count = count, LocalPlaylistTrackSource::Local => p.local_count = count, - LocalPlaylistTrackSource::Plex => p.plex_count = count, + // The three server-backed sources share one bucket: every + // consumer of these counts distinguishes "on this machine" from + // "needs a server", not server brands. + LocalPlaylistTrackSource::Plex + | LocalPlaylistTrackSource::Jellyfin + | LocalPlaylistTrackSource::Subsonic => p.plex_count += count, } p.track_count += count; } @@ -444,6 +463,12 @@ pub fn add_tracks( LocalPlaylistTrackInput::Qobuz(id) => ("qobuz", Some(*id as i64), None, None), LocalPlaylistTrackInput::Local(path) => ("local", None, Some(path.as_str()), None), LocalPlaylistTrackInput::Plex(key) => ("plex", None, None, Some(key.as_str())), + LocalPlaylistTrackInput::Jellyfin(item) => { + ("jellyfin", None, Some(item.as_str()), None) + } + LocalPlaylistTrackInput::Subsonic(item) => { + ("subsonic", None, Some(item.as_str()), None) + } }; let exists: bool = conn .prepare( diff --git a/crates/qbz-library/src/playlist_membership.rs b/crates/qbz-library/src/playlist_membership.rs index 4dd293081..7955ba55e 100644 --- a/crates/qbz-library/src/playlist_membership.rs +++ b/crates/qbz-library/src/playlist_membership.rs @@ -14,13 +14,13 @@ //! - `local_playlist_tracks` — everything inside `local:` playlists (same: //! locally authoritative). //! -//! Identity notes. Jellyfin and Subsonic rows reach playlists through their -//! `local_tracks` projection, so their playlist identity IS the library row -//! (`track_id` + the stored path/key) — structurally collision-free across -//! servers because each server's items are distinct projected rows. Plex -//! sidecars store the bare rating key (the Plex merge keeps it in -//! `file_path`); rating keys are scoped to the single configured server, the -//! same assumption the sidecar tables have always made. +//! Identity notes. Plex rows are keyed by rating key (their merge keeps it +//! in `file_path`), Jellyfin/Subsonic rows by their source-qualified server +//! item id (`playlist_remote_tracks`, and `local_playlist_tracks.local_path` +//! under their own `source` value); both key spaces are scoped to the single +//! configured server per protocol, the same assumption the sidecar tables +//! have always made. Everything else that lives in the library is its +//! projected row (`track_id` + path). use std::collections::{HashMap, HashSet}; @@ -44,29 +44,35 @@ pub enum PlaylistTrackRef { }, /// A Plex track by rating key. Plex { rating_key: String }, + /// A Jellyfin/Subsonic track by its server item id (their projected rows + /// carry it in `file_path`; playlists store it source-qualified). + Remote { source: String, item_id: String }, } impl PlaylistTrackRef { /// Build the ref for a library row the way the playlist writers key it: - /// Plex rows carry the rating key in `file_path`; every other source is - /// the projected library row itself (offline copies also carrying their - /// catalog id). + /// Plex rows carry the rating key in `file_path`, Jellyfin/Subsonic rows + /// their server item id; every other source is the projected library row + /// itself (offline copies also carrying their catalog id). pub fn from_library_row( source: &str, track_id: i64, file_path: &str, qobuz_track_id: Option, ) -> Self { - if source == "plex" { - Self::Plex { + match source { + "plex" => Self::Plex { rating_key: file_path.to_string(), - } - } else { - Self::Library { + }, + "jellyfin" | "subsonic" => Self::Remote { + source: source.to_string(), + item_id: file_path.to_string(), + }, + _ => Self::Library { track_id, path: Some(file_path.to_string()), qobuz_track_id: qobuz_track_id.filter(|_| source == "qobuz_download"), - } + }, } } } @@ -116,6 +122,7 @@ pub fn playlists_containing( let mut lib_ids: Vec<(i64, usize)> = Vec::new(); let mut lib_paths: Vec<(&str, usize)> = Vec::new(); let mut plex_keys: Vec<(&str, usize)> = Vec::new(); + let mut remote_items: Vec<(&str, &str, usize)> = Vec::new(); for (ordinal, r) in refs.iter().enumerate() { match r { PlaylistTrackRef::Qobuz(id) => qobuz_ids.push((*id as i64, ordinal)), @@ -134,6 +141,9 @@ pub fn playlists_containing( } } PlaylistTrackRef::Plex { rating_key } => plex_keys.push((rating_key.as_str(), ordinal)), + PlaylistTrackRef::Remote { source, item_id } => { + remote_items.push((source.as_str(), item_id.as_str(), ordinal)) + } } } @@ -222,6 +232,39 @@ pub fn playlists_containing( collect_qobuz(found); } + // Remote refs → the Jellyfin/Subsonic sidecars on Qobuz playlists, + // source-qualified (the sources come from a fixed vocabulary, so the + // literal in the SQL is safe). + for source in ["jellyfin", "subsonic"] { + let items: Vec<(&str, usize)> = remote_items + .iter() + .filter(|(s, _, _)| *s == source) + .map(|(_, item, ordinal)| (*item, *ordinal)) + .collect(); + for chunk in items.chunks(IN_CHUNK) { + let sql = format!( + "SELECT qobuz_playlist_id, item_id FROM playlist_remote_tracks + WHERE source = '{source}' AND item_id IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(item, _)| *item)), + |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, item) = row?; + for (i, ordinal) in &chunk[..] { + if *i == item { + found.push((pid, *ordinal)); + } + } + } + collect_qobuz(found); + } + } + // All three identity columns of local playlists. let mut collect_local = |rows: Vec<(String, usize)>| { for (pid, ordinal) in rows { @@ -253,9 +296,11 @@ pub fn playlists_containing( collect_local(found); } for chunk in lib_paths.chunks(IN_CHUNK) { + // source-qualified: remote rows store their server item id in the + // same column, and a filesystem path must never match one. let sql = format!( "SELECT playlist_id, local_path FROM local_playlist_tracks - WHERE local_path IN ({})", + WHERE source = 'local' AND local_path IN ({})", placeholders(chunk.len()) ); let mut stmt = conn.prepare(&sql)?; @@ -296,6 +341,35 @@ pub fn playlists_containing( } collect_local(found); } + for source in ["jellyfin", "subsonic"] { + let items: Vec<(&str, usize)> = remote_items + .iter() + .filter(|(s, _, _)| *s == source) + .map(|(_, item, ordinal)| (*item, *ordinal)) + .collect(); + for chunk in items.chunks(IN_CHUNK) { + let sql = format!( + "SELECT playlist_id, local_path FROM local_playlist_tracks + WHERE source = '{source}' AND local_path IN ({})", + placeholders(chunk.len()) + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(chunk.iter().map(|(item, _)| *item)), + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)), + )?; + let mut found = Vec::new(); + for row in rows { + let (pid, item) = row?; + for (i, ordinal) in &chunk[..] { + if *i == item { + found.push((pid.clone(), *ordinal)); + } + } + } + collect_local(found); + } + } let mut out: Vec = hits .into_iter() @@ -342,7 +416,15 @@ mod tests { plex_rating_key TEXT NOT NULL, position INTEGER NOT NULL, added_at INTEGER NOT NULL, - UNIQUE(qobuz_playlist_id, plex_rating_key));", + UNIQUE(qobuz_playlist_id, plex_rating_key)); + CREATE TABLE playlist_remote_tracks ( + id INTEGER PRIMARY KEY, + qobuz_playlist_id INTEGER NOT NULL, + source TEXT NOT NULL, + item_id TEXT NOT NULL, + position INTEGER NOT NULL, + added_at INTEGER NOT NULL, + UNIQUE(qobuz_playlist_id, source, item_id));", ) .unwrap(); c @@ -365,7 +447,7 @@ mod tests { .collect(); snapshot::record_authoritative_list(c, &entries).unwrap(); for (id, name, ids) in playlists { - snapshot::replace_tracks(c, *id, name, None, ids, None).unwrap(); + snapshot::replace_tracks(c, *id, name, None, ids).unwrap(); } } @@ -384,11 +466,10 @@ mod tests { } ); assert_eq!( - PlaylistTrackRef::from_library_row("jellyfin", 7, "/j/item", None), - PlaylistTrackRef::Library { - track_id: 7, - path: Some("/j/item".into()), - qobuz_track_id: None, + PlaylistTrackRef::from_library_row("jellyfin", 7, "jelly-item", None), + PlaylistTrackRef::Remote { + source: "jellyfin".into(), + item_id: "jelly-item".into(), } ); // The catalog id sticks only to offline copies; a stray value on any @@ -480,7 +561,7 @@ mod tests { }], ) .unwrap(); - snapshot::replace_tracks(&c, 5, "Followed", None, &[10], None).unwrap(); + snapshot::replace_tracks(&c, 5, "Followed", None, &[10]).unwrap(); let rows = playlists_containing(&c, &[PlaylistTrackRef::Qobuz(10)]).unwrap(); assert!(rows.is_empty()); @@ -535,6 +616,53 @@ mod tests { assert_eq!(rows[0].target, ContainmentTarget::Local(lp)); } + #[test] + fn remote_rows_answer_by_source_qualified_item_id() { + let c = conn(); + c.execute_batch( + "INSERT INTO playlist_remote_tracks VALUES (NULL, 7, 'jellyfin', 'item-1', 0, 1);", + ) + .unwrap(); + let lp = crate::local_playlists::create(&c, "Remote mix", None, false).unwrap(); + crate::local_playlists::add_tracks( + &c, + &lp, + &[ + crate::local_playlists::LocalPlaylistTrackInput::Jellyfin("item-1".into()), + crate::local_playlists::LocalPlaylistTrackInput::Subsonic("song-9".into()), + ], + ) + .unwrap(); + + let jelly = PlaylistTrackRef::from_library_row("jellyfin", 12345, "item-1", None); + let sub = PlaylistTrackRef::Remote { + source: "subsonic".into(), + item_id: "song-9".into(), + }; + // The same item id under the WRONG source must not match. + let wrong = PlaylistTrackRef::Remote { + source: "subsonic".into(), + item_id: "item-1".into(), + }; + let rows = playlists_containing(&c, &[jelly, sub]).unwrap(); + assert_eq!(contained(&rows, ContainmentTarget::Qobuz(7)), Some(1)); + assert_eq!( + contained(&rows, ContainmentTarget::Local(lp.clone())), + Some(2) + ); + assert!(playlists_containing(&c, &[wrong]).unwrap().is_empty()); + + // A local FILE path that happens to equal a remote item id never + // cross-matches (the source qualifier on the shared column). + let path_ref = PlaylistTrackRef::Library { + track_id: 1, + path: Some("item-1".into()), + qobuz_track_id: None, + }; + let rows = playlists_containing(&c, &[path_ref]).unwrap(); + assert!(contained(&rows, ContainmentTarget::Local(lp)).is_none()); + } + #[test] fn empty_refs_answer_nothing() { let c = conn(); diff --git a/crates/qbz-library/src/qobuz_playlist_snapshot.rs b/crates/qbz-library/src/qobuz_playlist_snapshot.rs index f2d26b4ef..f21e334f2 100644 --- a/crates/qbz-library/src/qobuz_playlist_snapshot.rs +++ b/crates/qbz-library/src/qobuz_playlist_snapshot.rs @@ -280,18 +280,20 @@ pub fn record_authoritative_list(conn: &Connection, entries: &[AuthoritativeEntr /// MEMBERSHIP producer: full-replace the snapshot track ids of ONE playlist /// (detail load or hydrator fetch) and refresh its header. Stamps -/// `membership_synced_at` / `membership_count`, and records the API -/// `updated_at` in force (`remote_updated_at_evidence`) when the caller has -/// one. Returns `false` (writing NOTHING) when the playlist has no header -/// row — i.e. it was never captured by the headers producer, so it is not -/// one of the user's listed playlists. +/// `membership_synced_at` / `membership_count`, and copies the HEADER's +/// current `remote_updated_at` into the membership evidence — never a stamp +/// from the fetch itself: `playlist/get` and `getUserPlaylists` do not report +/// comparable `updated_at` values, and trusting the fetch's made the queue +/// re-fetch the same playlist forever (smoke 2026-08-30). Returns `false` +/// (writing NOTHING) when the playlist has no header row — i.e. it was never +/// captured by the headers producer, so it is not one of the user's listed +/// playlists. pub fn replace_tracks( conn: &Connection, qobuz_playlist_id: u64, name: &str, owner: Option<&str>, track_ids: &[u64], - remote_updated_at_evidence: Option, ) -> Result { let ts = now_ms(); conn.execute_batch("BEGIN IMMEDIATE")?; @@ -300,8 +302,7 @@ pub fn replace_tracks( "UPDATE qobuz_playlist_snapshot SET name = ?2, owner = ?3, track_count = ?4, snapped_at = ?5, membership_synced_at = ?5, membership_count = ?4, - membership_remote_updated_at = - COALESCE(?6, remote_updated_at) + membership_remote_updated_at = remote_updated_at WHERE qobuz_playlist_id = ?1", params![ qobuz_playlist_id as i64, @@ -309,7 +310,6 @@ pub fn replace_tracks( owner, track_ids.len() as u32, ts, - remote_updated_at_evidence, ], )?; if updated == 0 { @@ -514,25 +514,41 @@ pub fn mark_inactive(conn: &Connection, qobuz_playlist_id: u64) -> Result<()> { // ───────────────────────── Hydration planning ───────────────────────── -/// The membership refreshes the hydrator still owes, oldest debt first: -/// never-synced playlists, then count mismatches, then remote-revision -/// mismatches. Only owned, active playlists — followed/read-only playlists -/// are informational and must not spend the rate budget. +/// The membership refreshes the hydrator still owes, oldest debt first. +/// Only owned, active playlists — followed/read-only playlists are +/// informational and must not spend the rate budget. +/// +/// Staleness is deliberately NOT "any evidence disagrees" (the 2026-08-30 +/// smoke found that fetching forever): a playlist is stale when +/// +/// - membership was never captured; or +/// - BOTH sides carry a remote revision and they differ — the authoritative +/// list said the playlist changed since the membership sync; or +/// - a revision comparison is impossible on either side, and the counts +/// disagree (the coarse fallback). +/// +/// A successful `replace_tracks` copies the header's current revision into +/// the membership evidence and equalises the counts, so every sync strictly +/// converges: only a NEW authoritative list can make a playlist stale again, +/// and then only the playlists it actually reports changed. pub fn hydration_queue(conn: &Connection) -> Result> { let mut stmt = conn.prepare( "SELECT qobuz_playlist_id, membership_synced_at IS NULL AS never_synced, - membership_count IS NOT track_count AS count_mismatch, - (remote_updated_at IS NOT NULL - AND membership_remote_updated_at IS NOT remote_updated_at) + (membership_remote_updated_at IS NOT NULL + AND remote_updated_at IS NOT NULL + AND membership_remote_updated_at != remote_updated_at) AS revision_mismatch FROM qobuz_playlist_snapshot WHERE is_owned = 1 AND inactive = 0 AND (membership_synced_at IS NULL - OR membership_count IS NOT track_count - OR (remote_updated_at IS NOT NULL - AND membership_remote_updated_at IS NOT remote_updated_at)) - ORDER BY never_synced DESC, count_mismatch DESC, qobuz_playlist_id", + OR (membership_remote_updated_at IS NOT NULL + AND remote_updated_at IS NOT NULL + AND membership_remote_updated_at != remote_updated_at) + OR ((membership_remote_updated_at IS NULL + OR remote_updated_at IS NULL) + AND membership_count IS NOT track_count)) + ORDER BY never_synced DESC, revision_mismatch DESC, qobuz_playlist_id", )?; let mut out = Vec::new(); for r in stmt.query_map([], |r| { @@ -542,15 +558,15 @@ pub fn hydration_queue(conn: &Connection) -> Result> { r.get::<_, bool>(2)?, )) })? { - let (pid, never, count) = r?; + let (pid, never, revision) = r?; out.push(HydrationCandidate { qobuz_playlist_id: pid, reason: if never { StaleReason::NeverSynced - } else if count { - StaleReason::CountMismatch - } else { + } else if revision { StaleReason::RemoteRevision + } else { + StaleReason::CountMismatch }, }); } @@ -679,7 +695,7 @@ mod tests { fn roundtrip_header_and_tracks() { let c = conn(); record(&c, &[entry(42, "Road Trip", 3)]); - let wrote = replace_tracks(&c, 42, "Road Trip", Some("me"), &[30, 10, 20], None).unwrap(); + let wrote = replace_tracks(&c, 42, "Road Trip", Some("me"), &[30, 10, 20]).unwrap(); assert!(wrote); let h = get_header(&c, 42).unwrap().unwrap(); @@ -702,8 +718,8 @@ mod tests { fn replace_is_full_replace() { let c = conn(); record(&c, &[entry(7, "Mix", 3)]); - replace_tracks(&c, 7, "Mix", None, &[1, 2, 3], None).unwrap(); - replace_tracks(&c, 7, "Mix renamed", None, &[9], None).unwrap(); + replace_tracks(&c, 7, "Mix", None, &[1, 2, 3]).unwrap(); + replace_tracks(&c, 7, "Mix renamed", None, &[9]).unwrap(); assert_eq!(track_ids(&c, 7).unwrap(), vec![9]); let h = get_header(&c, 7).unwrap().unwrap(); @@ -744,7 +760,7 @@ mod tests { let c = conn(); // No header row -> the detail producer writes NOTHING (a merely // viewed public playlist must not land in the snapshot). - let wrote = replace_tracks(&c, 99, "Someone's list", None, &[1, 2], None).unwrap(); + let wrote = replace_tracks(&c, 99, "Someone's list", None, &[1, 2]).unwrap(); assert!(!wrote); assert!(get_header(&c, 99).unwrap().is_none()); assert!(track_ids(&c, 99).unwrap().is_empty()); @@ -756,7 +772,7 @@ mod tests { // timestamp that also vouched for membership. Now they must not. let c = conn(); record(&c, &[entry(5, "Mix", 2)]); - replace_tracks(&c, 5, "Mix", None, &[1, 2], None).unwrap(); + replace_tracks(&c, 5, "Mix", None, &[1, 2]).unwrap(); let synced = get_header(&c, 5).unwrap().unwrap().membership_synced_at; record(&c, &[entry(5, "Mix", 2)]); @@ -791,8 +807,9 @@ mod tests { let c = conn(); let mut never = entry(1, "Never", 4); never.remote_updated_at = Some(100); - let mut mismatch = entry(2, "Mismatch", 5); - mismatch.remote_updated_at = Some(100); + // Revision unavailable on this one: the coarse count fallback governs. + let mut counted = entry(2, "Counted", 5); + counted.remote_updated_at = None; let mut revised = entry(3, "Revised", 1); revised.remote_updated_at = Some(100); let mut fresh = entry(4, "Fresh", 1); @@ -805,28 +822,26 @@ mod tests { &c, &[ never.clone(), - mismatch.clone(), + counted.clone(), revised.clone(), fresh.clone(), followed, ], ); - // Membership for 2 (3 of 5 -> count mismatch), 3 (agrees, but synced - // under an older remote revision), 4 (agrees, current revision). - replace_tracks(&c, 2, "Mismatch", None, &[1, 2, 3], Some(100)).unwrap(); - replace_tracks(&c, 3, "Revised", None, &[7], Some(90)).unwrap(); - replace_tracks(&c, 4, "Fresh", None, &[8], Some(100)).unwrap(); - // The list reasserts the authoritative counts/revisions the entries - // declared (replace_tracks overwrote track_count with the membership - // size, which is exactly the drift the queue must notice). - record(&c, &[never, mismatch, revised, fresh]); + replace_tracks(&c, 2, "Counted", None, &[7]).unwrap(); + replace_tracks(&c, 3, "Revised", None, &[7]).unwrap(); + replace_tracks(&c, 4, "Fresh", None, &[8]).unwrap(); + // Next authoritative list: 2's declared count (5) disagrees with its + // membership (1) and it has no revision signal; 3 changed remotely. + revised.remote_updated_at = Some(200); + record(&c, &[never, counted, revised, fresh]); let queue = hydration_queue(&c).unwrap(); let ids: Vec = queue.iter().map(|q| q.qobuz_playlist_id).collect(); - assert_eq!(ids, vec![1, 2, 3]); + assert_eq!(ids, vec![1, 3, 2]); assert_eq!(queue[0].reason, StaleReason::NeverSynced); - assert_eq!(queue[1].reason, StaleReason::CountMismatch); - assert_eq!(queue[2].reason, StaleReason::RemoteRevision); + assert_eq!(queue[1].reason, StaleReason::RemoteRevision); + assert_eq!(queue[2].reason, StaleReason::CountMismatch); match index_state(&c).unwrap() { MembershipIndexState::Updating { pending } => assert_eq!(pending, 3), @@ -834,6 +849,43 @@ mod tests { } } + #[test] + fn successful_sync_settles_the_queue_even_when_the_list_count_lags() { + // The 2026-08-30 smoke: one playlist re-fetched forever. A sync must + // CONVERGE — with revision evidence on both sides equal, a lagging + // list count is the list's problem, not a reason to fetch again. + let c = conn(); + let mut e = entry(1, "Lagging", 10); + e.remote_updated_at = Some(100); + record(&c, &[e.clone()]); + replace_tracks(&c, 1, "Lagging", None, &[5, 6, 7]).unwrap(); + // The list still reports the stale count 10 and the same revision. + record(&c, &[e]); + assert!(hydration_queue(&c).unwrap().is_empty()); + assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Complete); + } + + #[test] + fn only_the_playlists_the_list_reports_changed_requeue() { + let c = conn(); + let mut a = entry(1, "A", 2); + a.remote_updated_at = Some(100); + let mut b = entry(2, "B", 2); + b.remote_updated_at = Some(100); + record(&c, &[a.clone(), b.clone()]); + replace_tracks(&c, 1, "A", None, &[1, 2]).unwrap(); + replace_tracks(&c, 2, "B", None, &[3, 4]).unwrap(); + assert!(hydration_queue(&c).unwrap().is_empty()); + + // Only B changed remotely. + b.remote_updated_at = Some(200); + record(&c, &[a, b]); + let queue = hydration_queue(&c).unwrap(); + assert_eq!(queue.len(), 1); + assert_eq!(queue[0].qobuz_playlist_id, 2); + assert_eq!(queue[0].reason, StaleReason::RemoteRevision); + } + #[test] fn index_state_lifecycle() { let c = conn(); @@ -843,7 +895,7 @@ mod tests { index_state(&c).unwrap(), MembershipIndexState::Updating { pending: 1 } )); - replace_tracks(&c, 1, "A", None, &[10], None).unwrap(); + replace_tracks(&c, 1, "A", None, &[10]).unwrap(); assert_eq!(index_state(&c).unwrap(), MembershipIndexState::Complete); } @@ -851,7 +903,7 @@ mod tests { fn incremental_add_and_remove() { let c = conn(); record(&c, &[entry(1, "A", 2), entry(2, "Uncaptured", 3)]); - replace_tracks(&c, 1, "A", None, &[10, 20], None).unwrap(); + replace_tracks(&c, 1, "A", None, &[10, 20]).unwrap(); assert!(apply_added_tracks(&c, 1, &[30, 40]).unwrap()); assert_eq!(track_ids(&c, 1).unwrap(), vec![10, 20, 30, 40]); diff --git a/crates/qbz-qt/src/local_album_actions.rs b/crates/qbz-qt/src/local_album_actions.rs index 0e5ab8298..871f3adbb 100644 --- a/crates/qbz-qt/src/local_album_actions.rs +++ b/crates/qbz-qt/src/local_album_actions.rs @@ -876,10 +876,20 @@ pub fn add_to_playlist(id: String) { log::warn!("[qbz-qt] local album add-to-playlist: no version open for album '{id}'"); return; } + open_picker_for_rows(&tracks); +} + +/// The shared tail of every local add-to-playlist entry: source-aware refs +/// (`local_picker_ref_for_track` — Plex and Jellyfin/Subsonic ride their +/// source-native keys, everything else its library row id), then the picker. +pub(crate) fn open_picker_for_rows(tracks: &[qbz_library::LocalTrack]) { let refs: Vec = tracks .iter() .map(crate::local_playlist_qt::local_picker_ref_for_track) .collect(); + if refs.is_empty() { + return; + } crate::playlist_picker_qt::open_for_local_refs(&crate::app(), refs); } diff --git a/crates/qbz-qt/src/local_bulk.rs b/crates/qbz-qt/src/local_bulk.rs index f9508d9fb..26dd99a0d 100644 --- a/crates/qbz-qt/src/local_bulk.rs +++ b/crates/qbz-qt/src/local_bulk.rs @@ -165,6 +165,16 @@ fn resolve_blocking(scope: &str, ids: &[String]) -> Vec { s.tracks_raw .iter() .chain(s.detail_raw.iter()) + // The Library Explorer's expanded albums live in their own row + // cache. Without these, an Explorer track menu resolved through + // this function silently dropped every merged Plex/remote row — + // "Add to playlist" opened nothing (smoke 2026-08-30). + .chain(s.genre_detail_raw.values().flatten()) + .chain( + s.genre_detail_all_tracks + .values() + .flat_map(|arc| arc.iter()), + ) .map(|t| (t.id, t.clone())) .collect() }); @@ -182,6 +192,12 @@ fn resolve_blocking(scope: &str, ids: &[String]) -> Vec { .collect() } +/// Track-scope resolution for callers outside the bulk bars (the shared +/// drag's local payload): same caches, same last-resort DB lookup. +pub(crate) fn resolve_track_rows_blocking(ids: &[String]) -> Vec { + resolve_blocking("track", ids) +} + pub(crate) fn resolve_album_ids_blocking(ids: &[String]) -> Vec { ids.iter() .flat_map(|key| fetch_album_tracks_blocking(key)) @@ -245,11 +261,8 @@ pub(crate) async fn apply(rows: Vec, action: &str) -> bool { if rows.is_empty() { return false; } - let refs: Vec = rows - .iter() - .map(crate::local_playlist_qt::local_picker_ref_for_track) - .collect(); - crate::playlist_picker_qt::open_for_local_refs(&crate::app(), refs); + // Shared tail: source-aware refs, then the picker. + crate::local_album_actions::open_picker_for_rows(&rows); false } // NO CALLER as of 2026-07-31: no bulk bar offers this action any more. diff --git a/crates/qbz-qt/src/local_playlist_qt.rs b/crates/qbz-qt/src/local_playlist_qt.rs index 14601ccf8..45b860412 100644 --- a/crates/qbz-qt/src/local_playlist_qt.rs +++ b/crates/qbz-qt/src/local_playlist_qt.rs @@ -242,6 +242,10 @@ pub fn add_local_refs_blocking(id: &str, refs: &[String]) -> usize { for r in refs { if let Some(key) = r.strip_prefix("plex:") { out.push(repo::LocalPlaylistTrackInput::Plex(key.to_string())); + } else if let Some(item) = r.strip_prefix("jellyfin:") { + out.push(repo::LocalPlaylistTrackInput::Jellyfin(item.to_string())); + } else if let Some(item) = r.strip_prefix("subsonic:") { + out.push(repo::LocalPlaylistTrackInput::Subsonic(item.to_string())); } else if let Ok(rid) = r.parse::() { if let Some(input) = local_row_input(db, rid)? { out.push(input); @@ -273,6 +277,16 @@ pub fn membership_refs_blocking( out.push(PlaylistTrackRef::Plex { rating_key: key.to_string(), }); + } else if let Some(item) = r.strip_prefix("jellyfin:") { + out.push(PlaylistTrackRef::Remote { + source: "jellyfin".to_string(), + item_id: item.to_string(), + }); + } else if let Some(item) = r.strip_prefix("subsonic:") { + out.push(PlaylistTrackRef::Remote { + source: "subsonic".to_string(), + item_id: item.to_string(), + }); } else if let Ok(rid) = r.parse::() { out.push(match db.get_track(rid)? { Some(track) => PlaylistTrackRef::from_library_row( @@ -359,6 +373,24 @@ pub fn resolve_cover_urls_blocking(id: &str, limit: usize) -> Vec { } } } + repo::LocalPlaylistTrackSource::Jellyfin | repo::LocalPlaylistTrackSource::Subsonic => { + if let Some(item) = t.local_path { + let source = t.source.as_str().to_string(); + let resolved = crate::media_servers_qt::tracks_by_item_ids_blocking(&[( + source.clone(), + item.clone(), + 0, + )]); + if let Some(art) = resolved + .get(&(source, item)) + .and_then(|lt| lt.artwork_path.clone()) + { + if !covers.contains(&art) { + covers.push(art); + } + } + } + } // Qobuz rows would fill their slot from the async offline cache in // the reference; this blocking sidebar helper cannot enter it. repo::LocalPlaylistTrackSource::Qobuz => {} @@ -539,7 +571,7 @@ pub fn read_sidecar_rows_blocking( qobuz_track_count: u32, include_plex: bool, ) -> Vec { - let (mut rows, plex_refs) = with_db(false, |db| { + let (mut rows, plex_refs, remote_refs) = with_db(false, |db| { match db.heal_playlist_sidecar_positions(playlist_id, qobuz_track_count) { Ok(healed) => { for entry in &healed { @@ -565,7 +597,8 @@ pub fn read_sidecar_rows_blocking( } else { Vec::new() }; - Ok((rows, plex_refs)) + let remote_refs = db.get_playlist_remote_tracks_with_position(playlist_id)?; + Ok((rows, plex_refs, remote_refs)) }) .unwrap_or_default(); @@ -603,6 +636,36 @@ pub fn read_sidecar_rows_blocking( }, })); } + + // Jellyfin/Subsonic sidecars — the Plex pattern against the media cache. + // A miss renders the honest Unresolved row, never a vanished one. + if !remote_refs.is_empty() { + let resolved = crate::media_servers_qt::tracks_by_item_ids_blocking(&remote_refs); + rows.extend( + remote_refs + .into_iter() + .map(|(source, item, position)| LoadedRow { + position, + item: match resolved.get(&(source.clone(), item.clone())) { + Some(track) => RowItem::Local(Box::new(track.clone())), + None => { + log::warn!( + "[qbz-qt] playlist {playlist_id}: {source} item {item:?} not in \ + the media cache — rendered as unavailable" + ); + RowItem::Unresolved { + kind: if source == "jellyfin" { + "jellyfin" + } else { + "subsonic" + }, + reference: item, + } + } + }, + }), + ); + } rows } @@ -653,6 +716,12 @@ pub fn local_picker_ref_for_row(id: &str) -> Option { .source_item_id_hint .as_ref() .map(|key| format!("plex:{key}")), + // Remote rows carry the server item id in the hint slot, same as + // Plex carries the rating key (media_servers_qt::cached_to_local_track). + Some(source @ ("jellyfin" | "subsonic")) => q + .source_item_id_hint + .as_ref() + .map(|item| format!("{source}:{item}")), Some("local") => Some(q.id.to_string()), // An OFFLINE COPY row (`local_playback::local_queue_track` tags these // "qobuz_download"). It reaches this function because `row_to_display` @@ -682,11 +751,17 @@ pub fn local_picker_ref_for_row(id: &str) -> Option { /// library row id. A Plex row must NEVER ride its numeric id — the synthetic /// 2^40 ids do not resolve through `get_track`, and typing one as a Qobuz id /// is the legacy bug that wrote permanently unresolvable rows. +/// +/// Jellyfin/Subsonic rows likewise NEVER ride their numeric id — it is a +/// media-cache rowid, which `local_row_input`'s `get_track` would happily +/// resolve against `local_tracks` (the same number, a DIFFERENT track). Like +/// Plex, their playlist identity is the source-native key their projection +/// keeps in `file_path`: the server item id, carried source-prefixed. pub fn local_picker_ref_for_track(track: &qbz_library::LocalTrack) -> String { - if track.source.as_deref() == Some("plex") { - format!("plex:{}", track.file_path) - } else { - track.id.to_string() + match track.source.as_deref() { + Some("plex") => format!("plex:{}", track.file_path), + Some(source @ ("jellyfin" | "subsonic")) => format!("{source}:{}", track.file_path), + _ => track.id.to_string(), } } @@ -782,7 +857,14 @@ pub(crate) fn row_to_display(item: &RowItem) -> (PlaylistTrackRow, Option "jellyfin", + Some("subsonic") => "subsonic", + _ => "local", + } }; let row = PlaylistTrackRow { id: queue.id.to_string(), @@ -1024,6 +1106,32 @@ pub async fn load(runtime: &Runtime, playlist_id: &str) -> bool { .unwrap_or_default() }; + // Jellyfin/Subsonic rows: ONE bulk media-cache lookup by item id (their + // item id rides the local_path column, source-qualified). + let remote_refs: Vec<(String, String, i32)> = tracks + .iter() + .filter_map(|t| { + let source = match t.source { + repo::LocalPlaylistTrackSource::Jellyfin => "jellyfin", + repo::LocalPlaylistTrackSource::Subsonic => "subsonic", + _ => return None, + }; + t.local_path + .clone() + .map(|item| (source.to_string(), item, 0)) + }) + .collect(); + let remote_resolved: HashMap<(String, String), qbz_library::LocalTrack> = + if remote_refs.is_empty() { + HashMap::new() + } else { + tokio::task::spawn_blocking(move || { + crate::media_servers_qt::tracks_by_item_ids_blocking(&remote_refs) + }) + .await + .unwrap_or_default() + }; + let mut rows: Vec = Vec::new(); let (mut hidden, mut missing_files, mut unresolved) = (0usize, 0usize, 0usize); for t in tracks { @@ -1085,6 +1193,28 @@ pub async fn load(runtime: &Runtime, playlist_id: &str) -> bool { } } } + repo::LocalPlaylistTrackSource::Jellyfin | repo::LocalPlaylistTrackSource::Subsonic => { + let source = t.source.as_str(); + let item_id = t.local_path.clone().unwrap_or_default(); + match remote_resolved.get(&(source.to_string(), item_id.clone())) { + Some(track) => RowItem::Local(Box::new(track.clone())), + None => { + unresolved += 1; + log::warn!( + "[qbz-qt] local playlist {id}: {source} item {item_id:?} not in \ + the media cache — rendered as unavailable" + ); + RowItem::Unresolved { + kind: if source == "jellyfin" { + "jellyfin" + } else { + "subsonic" + }, + reference: item_id, + } + } + } + } }; rows.push(LoadedRow { position: t.position, diff --git a/crates/qbz-qt/src/media_servers_qt.rs b/crates/qbz-qt/src/media_servers_qt.rs index f70fa6863..da8fc0a76 100644 --- a/crates/qbz-qt/src/media_servers_qt.rs +++ b/crates/qbz-qt/src/media_servers_qt.rs @@ -340,6 +340,56 @@ pub fn purge_cache(kind: MediaServerKind) { /// - `album_group_key` is the PREFIXED key (`jellyfin:`), matching the /// one the grid's SQL union publishes, so "go to album" from a track row /// lands on the same page the card opens. +/// Bulk media-cache resolution for playlist refs: `(source, item_id, _)` +/// rows to `(source, item_id) -> LocalTrack`. Misses are simply absent — +/// the caller renders them as honest Unresolved rows. Blocking. +pub fn tracks_by_item_ids_blocking( + refs: &[(String, String, i32)], +) -> std::collections::HashMap<(String, String), qbz_library::LocalTrack> { + let mut out = std::collections::HashMap::new(); + for source_name in ["jellyfin", "subsonic"] { + let items: Vec<&str> = refs + .iter() + .filter(|(s, _, _)| s == source_name) + .map(|(_, item, _)| item.as_str()) + .collect(); + if items.is_empty() { + continue; + } + let (remote, read_source) = if source_name == "jellyfin" { + (qbz_media_cache::RemoteSource::Jellyfin, source_name) + } else { + (qbz_media_cache::RemoteSource::Subsonic, source_name) + }; + let read = |conn: &rusqlite::Connection| { + items + .iter() + .filter_map(|item| { + qbz_media_cache::track_by_item_id(conn, remote, item) + .ok() + .flatten() + .map(cached_to_local_track) + .map(|track| ((read_source.to_string(), (*item).to_string()), track)) + }) + .collect::>() + }; + let resolved = match remote { + qbz_media_cache::RemoteSource::Jellyfin => qbz_source::registry() + .jellyfin() + .cache() + .with(read) + .unwrap_or_default(), + qbz_media_cache::RemoteSource::Subsonic => qbz_source::registry() + .subsonic() + .cache() + .with(read) + .unwrap_or_default(), + }; + out.extend(resolved); + } + out +} + pub fn cached_to_local_track(t: qbz_media_cache::CachedTrack) -> qbz_library::LocalTrack { let source = t.source.clone(); let source_instance = if t.server_id.trim().is_empty() { diff --git a/crates/qbz-qt/src/playlist_index_qt.rs b/crates/qbz-qt/src/playlist_index_qt.rs index ea6cb353a..fadd17897 100644 --- a/crates/qbz-qt/src/playlist_index_qt.rs +++ b/crates/qbz-qt/src/playlist_index_qt.rs @@ -13,7 +13,7 @@ //! load), so reconnects and mutations re-arm it for free; a poke while a walk //! is running coalesces into one more round instead of a second walker. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::atomic::{AtomicBool, Ordering}; use qbz_library::qobuz_playlist_snapshot as repo; @@ -57,17 +57,29 @@ pub fn poke() { }); } -/// Pick the next candidate that still has retry budget. Pure — the driver's -/// only decision, kept out of the loop so it is testable. -fn next_candidate(queue: &[repo::HydrationCandidate], failures: &HashMap) -> Option { +/// Pick the next candidate that still has retry budget and was not already +/// written this round. Pure — the driver's decisions, kept out of the loop so +/// they are testable. +/// +/// The `written` set is the FORWARD-PROGRESS GUARD: a playlist successfully +/// synced this round must never be fetched again within it, even if the +/// staleness query still flags it — a queue that cannot be satisfied by a +/// successful write is a data bug to log, not a loop to run. The 2026-08-30 +/// smoke hit exactly that: one playlist re-fetched every 500ms for minutes. +fn next_candidate( + queue: &[repo::HydrationCandidate], + failures: &HashMap, + written: &HashSet, +) -> Option { queue .iter() .map(|c| c.qobuz_playlist_id) - .find(|pid| failures.get(pid).map_or(true, |&n| n < MAX_ATTEMPTS)) + .find(|pid| !written.contains(pid) && failures.get(pid).map_or(true, |&n| n < MAX_ATTEMPTS)) } async fn run_round(runtime: &Runtime) { let mut failures: HashMap = HashMap::new(); + let mut written: HashSet = HashSet::new(); loop { if crate::offline_fwd::engine().is_offline() { return; @@ -79,7 +91,20 @@ async fn run_round(runtime: &Runtime) { }) .await .unwrap_or_default(); - let Some(pid) = next_candidate(&queue, &failures) else { + let Some(pid) = next_candidate(&queue, &failures, &written) else { + if let Some(stuck) = queue + .iter() + .find(|c| written.contains(&c.qobuz_playlist_id)) + { + // A successful sync that does not settle its queue entry is a + // staleness-rule bug; surface it instead of looping on it. + log::warn!( + "[qbz-qt] playlist index: {} still queued ({:?}) after a successful sync; \ + leaving it for the next authoritative list", + stuck.qobuz_playlist_id, + stuck.reason + ); + } crate::playlist_picker_qt::membership_index_progressed(); return; }; @@ -97,7 +122,6 @@ async fn run_round(runtime: &Runtime) { &playlist.name, owner, &playlist.track_ids, - playlist.updated_at, ) })) }) @@ -107,7 +131,9 @@ async fn run_round(runtime: &Runtime) { .flatten() .and_then(Result::ok) .unwrap_or(false); - if !wrote { + if wrote { + written.insert(pid); + } else { // Header vanished mid-round (deleted / retired). Spend // the whole budget so the round moves on. log::debug!("[qbz-qt] playlist index: {pid} lost its header; skipped"); @@ -148,18 +174,31 @@ mod tests { fn next_candidate_skips_exhausted_budgets() { let queue = candidates(&[1, 2, 3]); let mut failures = HashMap::new(); - assert_eq!(next_candidate(&queue, &failures), Some(1)); + let written = HashSet::new(); + assert_eq!(next_candidate(&queue, &failures, &written), Some(1)); failures.insert(1, MAX_ATTEMPTS); - assert_eq!(next_candidate(&queue, &failures), Some(2)); + assert_eq!(next_candidate(&queue, &failures, &written), Some(2)); failures.insert(2, MAX_ATTEMPTS - 1); // Budget not exhausted yet: 2 is still first in line. - assert_eq!(next_candidate(&queue, &failures), Some(2)); + assert_eq!(next_candidate(&queue, &failures, &written), Some(2)); failures.insert(2, MAX_ATTEMPTS); failures.insert(3, MAX_ATTEMPTS); // Everything parked: the round ends instead of spinning. - assert_eq!(next_candidate(&queue, &failures), None); + assert_eq!(next_candidate(&queue, &failures, &written), None); + } + + #[test] + fn next_candidate_never_refetches_a_successful_write() { + // The 2026-08-30 infinite loop: a queue entry that survives its own + // successful sync must end the round, not restart it. + let queue = candidates(&[1]); + let failures = HashMap::new(); + let mut written = HashSet::new(); + assert_eq!(next_candidate(&queue, &failures, &written), Some(1)); + written.insert(1); + assert_eq!(next_candidate(&queue, &failures, &written), None); } } diff --git a/crates/qbz-qt/src/playlist_picker_qt.rs b/crates/qbz-qt/src/playlist_picker_qt.rs index fb102e741..c53294c85 100644 --- a/crates/qbz-qt/src/playlist_picker_qt.rs +++ b/crates/qbz-qt/src/playlist_picker_qt.rs @@ -859,6 +859,49 @@ pub fn create_and_add(name: &str) { }); } +/// Shared-drag DROP: the picker's add matrix without the modal. Routes a +/// payload onto a sidebar target the same way `pick` would — local refs to a +/// local playlist or the Qobuz sidecar, Qobuz ids to a local playlist — with +/// the same success tail (last-used, toast, refreshes). The Qobuz-ids-onto- +/// Qobuz-playlist case stays with its pre-existing `playlist_qt::add_tracks` +/// caller and never reaches here. +pub async fn add_dropped_payload_to_target(runtime: &Runtime, target_id: &str, payload: Payload) { + if payload.is_empty() { + return; + } + match crate::local_playlist_qt::PlaylistRef::parse(target_id) { + Some(crate::local_playlist_qt::PlaylistRef::Local(target)) => { + let added = tokio::task::spawn_blocking({ + let target = target.clone(); + move || match payload { + Payload::LocalRefs(refs) => { + crate::local_playlist_qt::add_local_refs_blocking(&target, &refs) + } + Payload::Qobuz(ids) => { + crate::local_playlist_qt::add_qobuz_tracks_blocking(&target, &ids) + } + } + }) + .await + .unwrap_or(0); + set_last_used(&target, added); + toast_added(added, ""); + refresh_local_target(runtime, &target).await; + } + Some(crate::local_playlist_qt::PlaylistRef::Qobuz(pid)) => { + let Payload::LocalRefs(refs) = payload else { + return; + }; + let qobuz_count = crate::sidebar_qt::playlist_track_count(pid).unwrap_or(0); + let written = write_sidecar_refs(pid, qobuz_count, refs).await; + set_last_used(&pid.to_string(), written); + toast_added(written, ""); + crate::playlist_qt::refresh_after_membership_change(runtime, pid).await; + } + None => {} + } +} + /// Seam C — attach local-mode refs to a QOBUZ playlist through the library.db /// sidecar tables. Returns how many refs were written. /// @@ -879,6 +922,10 @@ async fn write_sidecar_refs(pid: u64, qobuz_count: u32, refs: Vec) -> us for r in &refs { if let Some(key) = r.strip_prefix("plex:") { db.add_plex_track_to_playlist(pid, key, next)?; + } else if let Some(item) = r.strip_prefix("jellyfin:") { + db.add_remote_track_to_playlist(pid, "jellyfin", item, next)?; + } else if let Some(item) = r.strip_prefix("subsonic:") { + db.add_remote_track_to_playlist(pid, "subsonic", item, next)?; } else if let Ok(lid) = r.parse::() { db.add_local_track_to_playlist(pid, lid, next)?; } else { diff --git a/crates/qbz-qt/src/playlist_snapshot_qt.rs b/crates/qbz-qt/src/playlist_snapshot_qt.rs index d34352706..74b7ff12c 100644 --- a/crates/qbz-qt/src/playlist_snapshot_qt.rs +++ b/crates/qbz-qt/src/playlist_snapshot_qt.rs @@ -67,7 +67,7 @@ pub fn record_detail_detached(playlist_id: u64, name: String, owner: String, tra let owner = Some(owner.as_str()).filter(|value| !value.is_empty()); let result = crate::library_db_qt::with_db(true, |db| { Ok(db.with_connection(|conn| { - repo::replace_tracks(conn, playlist_id, &name, owner, &track_ids, None) + repo::replace_tracks(conn, playlist_id, &name, owner, &track_ids) })) }); match result { diff --git a/crates/qbz-qt/src/search_qt.rs b/crates/qbz-qt/src/search_qt.rs index 57fc26bc9..f62dd61bf 100644 --- a/crates/qbz-qt/src/search_qt.rs +++ b/crates/qbz-qt/src/search_qt.rs @@ -1519,8 +1519,7 @@ fn open_local_cort_row_in_playlist_picker(row_id: &str) { ); return; }; - let reference = crate::local_playlist_qt::local_picker_ref_for_track(&track); - crate::playlist_picker_qt::open_for_local_refs(&crate::app(), vec![reference]); + crate::local_album_actions::open_picker_for_rows(std::slice::from_ref(&track)); } /// "View more" on a section: full search page on the matching tab From e9fa3fb57bcac6c14d7bbcd9a5cde15af4b9d159 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 18:58:32 -0600 Subject: [PATCH 07/10] feat(qt): local rows drag to the sidebar and the queue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared drag gains a LOCAL payload arm: a Local Library / Explorer row enters via dragStartLocal carrying its ROW ID, resolved to source-aware refs at drop time — a library row id can never be read as a catalog id, the same invariant the picker's Payload enum enforces. TrackRow's localDragSource reuses every existing guardrail (horizontal arming, select-mode/dead-row/playBlocked gates, preventStealing, cancel teardown) without touching catalogRow's meaning. Drops route through the picker's own add matrix: refs onto a local playlist or the Qobuz sidecar, and Qobuz ids onto a local playlist (previously a documented POC gap); queue drops land at the exact slot through the same insert path as Qobuz drags. Native-catalog tracks rows keep the gesture off until their identity can ride it. cc --- crates/qbz-qt/qml/rows/TrackRow.qml | 24 ++++- .../qbz-qt/qml/views/local/LocalTrackRow.qml | 11 ++- crates/qbz-qt/src/main.rs | 99 ++++++++++++++++++- crates/qbz-qt/src/queue_qt.rs | 20 ++-- crates/qbz-qt/src/shell_bridge.rs | 31 ++++++ 5 files changed, 171 insertions(+), 14 deletions(-) diff --git a/crates/qbz-qt/qml/rows/TrackRow.qml b/crates/qbz-qt/qml/rows/TrackRow.qml index ab59ebe0a..9ff5364e6 100644 --- a/crates/qbz-qt/qml/rows/TrackRow.qml +++ b/crates/qbz-qt/qml/rows/TrackRow.qml @@ -141,6 +141,14 @@ Rectangle { // `playlist add-tracks` as a QOBUZ catalog id — a local row dropped on a // playlist would silently add an unrelated catalog track. property bool draggable: true + /// LOCAL-mode drag arm (2026-08-30): the row IS a drag source, but its + /// `item.id` is a LOCAL library row id, so it enters the shared drag via + /// `dragStartLocal` — a typed payload the drop handlers resolve + /// source-aware, never a number that could be read as a catalog id. + /// Independent of `draggable` on purpose: `catalogRow` below keeps + /// meaning "item.id is a Qobuz catalog id". + property bool localDragSource: false + readonly property bool dragSource: root.draggable || root.localDragSource /// A live transport guard separate from catalogue availability. The full /// queue uses it when QConnect is active: incompatible rows stay visible /// and keep their non-transport menu actions, but cannot play or drag. @@ -1471,7 +1479,7 @@ Rectangle { // later, `onCanceled` fired, and the drag died at roughly the row // boundary — never reaching the sidebar. Arming at 6px and claiming // the grab there wins the race by construction, because 6 < 10. - preventStealing: (root.reorderDrag && root.draggable && !root.selectMode) + preventStealing: (root.reorderDrag && root.dragSource && !root.selectMode) || root.dragging onPressed: function (mouse) { if (mouse.button === Qt.RightButton) { @@ -1491,7 +1499,7 @@ Rectangle { // A dead row is not a drag source either: dropping it on a sidebar // playlist would add a track that cannot play, which is precisely // the state this treatment exists to stop spreading. - if (!pressed || !(pressedButtons & Qt.LeftButton) || !root.draggable + if (!pressed || !(pressedButtons & Qt.LeftButton) || !root.dragSource || root.selectMode || root.pulledDead || root.playBlocked) return const g = mapToItem(null, mouse.x, mouse.y) const dx = mouse.x - root.downPos.x @@ -1519,9 +1527,15 @@ Rectangle { if (!root.dragging && armed) { root.dragging = true root.bodyDragStarted(root.number) - QbzShell.dragStart(root.item.id, root.item.title || "", - (root.item.artist || "") + " · " + (root.item.album || ""), - g.x, g.y, root.inlineDragVisual) + if (root.localDragSource) + QbzShell.dragStartLocal(String(root.item.id), + root.item.title || "", + (root.item.artist || "") + " · " + (root.item.album || ""), + g.x, g.y, root.inlineDragVisual) + else + QbzShell.dragStart(root.item.id, root.item.title || "", + (root.item.artist || "") + " · " + (root.item.album || ""), + g.x, g.y, root.inlineDragVisual) } if (root.dragging) QbzShell.dragMove(g.x, g.y) } diff --git a/crates/qbz-qt/qml/views/local/LocalTrackRow.qml b/crates/qbz-qt/qml/views/local/LocalTrackRow.qml index cdbb71fd8..a4344566e 100644 --- a/crates/qbz-qt/qml/views/local/LocalTrackRow.qml +++ b/crates/qbz-qt/qml/views/local/LocalTrackRow.qml @@ -134,9 +134,16 @@ Item { showFavorite: false showDownload: false showMenu: false - // Local rows are NOT drag sources: item.id is a local DB row id and - // the sidebar drop handler forwards it as a Qobuz catalog id. + // Local rows drag through the LOCAL arm: item.id is a local DB row + // id, so the shared drag carries it typed (`dragStartLocal`) and the + // drop handlers resolve it source-aware — the same guardrails as the + // picker. `draggable` stays false so `catalogRow` keeps meaning + // "item.id is a Qobuz catalog id". draggable: false + // NOT for native-catalog rows: their `item.id` is the catalog seam's + // identity, not a legacy row id the drop resolver can look up — a + // ghost that lands as a silent no-op is worse than no gesture. + localDragSource: !root.nativeActions qualityStyle: "icon" // A failed physical row stays clickable so the user can retry after a // drive returns. The preflight prevents any queue/NPB mutation until diff --git a/crates/qbz-qt/src/main.rs b/crates/qbz-qt/src/main.rs index 54563f018..6b13662de 100644 --- a/crates/qbz-qt/src/main.rs +++ b/crates/qbz-qt/src/main.rs @@ -2075,6 +2075,12 @@ pub(crate) fn playlist_move_row(row_id: String, delta: i32) { // DragTrack enum also carries local-library rows and Plex keys into // sidecar writes — out of scope, see module POC-NOTEs). static DRAGGED: Mutex> = Mutex::new(Vec::new()); +/// LOCAL-mode drag payload: Local Library row ids, resolved to source-aware +/// picker refs at DROP time (the rows can leave the visible cache between +/// press and release; ids survive that, refs are cheap to build once). +/// Mutually exclusive with `DRAGGED` — a drag carries one payload kind, the +/// same invariant the picker's `Payload` enum enforces. +static DRAGGED_LOCAL_ROWS: Mutex> = Mutex::new(Vec::new()); /// The claimed drop target (sidebar playlist id) — mirrored Rust-side so /// drag_end never reads the bridge off-thread. static DRAG_OVER: Mutex = Mutex::new(String::new()); @@ -2093,6 +2099,7 @@ pub(crate) fn drag_start( ) { let id = track_id.parse::().unwrap_or(0); *DRAGGED.lock().unwrap() = if id > 0 { vec![id] } else { Vec::new() }; + DRAGGED_LOCAL_ROWS.lock().unwrap().clear(); log::info!("[qbz-qt][drag] start {track_id} ({title})"); shell_bridge::ui(move |mut b| { b.as_mut().set_drag_count(if id > 0 { 1 } else { 0 }); @@ -2108,6 +2115,35 @@ pub(crate) fn drag_start( }); } +/// LOCAL-mode twin of [`drag_start`]: a Local Library / Explorer row enters +/// the shared drag carrying its ROW ID, never a number that could be read as +/// a catalog id (the picker's `Payload` invariant, kept at the drag seam). +pub(crate) fn drag_start_local( + row_id: String, + title: String, + subtitle: String, + x: f32, + y: f32, + inline_visual: bool, +) { + DRAGGED.lock().unwrap().clear(); + let ok = !row_id.is_empty(); + *DRAGGED_LOCAL_ROWS.lock().unwrap() = if ok { vec![row_id.clone()] } else { Vec::new() }; + log::info!("[qbz-qt][drag] start local row {row_id} ({title})"); + shell_bridge::ui(move |mut b| { + b.as_mut().set_drag_count(if ok { 1 } else { 0 }); + b.as_mut().set_drag_title(QString::from(title.as_str())); + b.as_mut() + .set_drag_subtitle(QString::from(subtitle.as_str())); + b.as_mut().set_drag_x(x); + b.as_mut().set_drag_y(y); + b.as_mut().set_drag_inline_visual(inline_visual); + b.as_mut().set_drag_over_playlist_id(QString::default()); + b.as_mut().set_drag_over_queue_index(-1); + b.as_mut().set_drag_active(true); + }); +} + pub(crate) fn drag_move(x: f32, y: f32) { shell_bridge::ui(move |mut b| { b.as_mut().set_drag_x(x); @@ -2140,9 +2176,70 @@ pub(crate) fn drag_end() { b.as_mut().set_drag_over_queue_index(-1); }); let tracks = std::mem::take(&mut *DRAGGED.lock().unwrap()); - if tracks.is_empty() { + let local_rows = std::mem::take(&mut *DRAGGED_LOCAL_ROWS.lock().unwrap()); + if tracks.is_empty() && local_rows.is_empty() { return; } + + // LOCAL-mode payload: Explorer / Local Library rows, resolved to + // source-aware refs at drop time and routed through the picker's own + // add matrix — the "same guardrails" contract: a library row id can + // never reach a Qobuz endpoint, a Plex/remote row rides its server key. + if !local_rows.is_empty() { + let runtime = app(); + let pid = pid.clone(); + spawn(async move { + let rows = tokio::task::spawn_blocking(move || { + local_bulk::resolve_track_rows_blocking(&local_rows) + }) + .await + .unwrap_or_default(); + if rows.is_empty() { + log::warn!("[qbz-qt][drag] local drop resolved no rows; ignored"); + return; + } + if queue_slot >= 0 { + let was_empty = runtime + .core() + .get_queue_state_full() + .await + .upcoming + .is_empty() + && runtime.core().current_track().await.is_none(); + let mut landed = false; + for (n, row) in rows.into_iter().enumerate() { + let qt = local_playback::local_queue_track(&row); + let slot = queue_slot as usize + n; + match queue_qt::insert_dragged_queue_track(&runtime, qt, slot).await { + Ok(()) => landed = true, + Err(e) => log::error!( + "[qbz-qt][drag] queue insert of local row {} at {slot} failed: {e}", + row.id + ), + } + } + if was_empty && landed { + queue_qt::set_drop_play_prompt(true); + } + return; + } + if pid.is_empty() { + return; + } + let refs: Vec = rows + .iter() + .map(local_playlist_qt::local_picker_ref_for_track) + .collect(); + playlist_picker_qt::add_dropped_payload_to_target( + &runtime, + &pid, + playlist_picker_qt::Payload::LocalRefs(refs), + ) + .await; + }); + return; + } + // The QUEUE target wins when both are claimed. They cannot both be under // the pointer geometrically, so this only decides a stale claim — and the // queue one is the more recent, since the panel overlays the sidebar. diff --git a/crates/qbz-qt/src/queue_qt.rs b/crates/qbz-qt/src/queue_qt.rs index bfffa77dc..11df787ee 100644 --- a/crates/qbz-qt/src/queue_qt.rs +++ b/crates/qbz-qt/src/queue_qt.rs @@ -1282,12 +1282,20 @@ pub async fn insert_dragged_track( // filters now (F2 + D5), so one row in can legitimately be ZERO rows out — // and a DRAG of a pulled track into the queue would have PANICKED. The seam // has already toasted the reason. - let Some(qt) = crate::playback_qt::stamped( - vec![crate::playback_qt::queue_track_for(runtime, track_id).await?], - None, - ) - .pop() else { - log::info!("[qbz-qt] queue: dragged track {track_id} was filtered out"); + let qt = crate::playback_qt::queue_track_for(runtime, track_id).await?; + insert_dragged_queue_track(runtime, qt, to_slot).await +} + +/// The same drop, from an already-built `QueueTrack` — the LOCAL-mode drag's +/// arm (Explorer / Local Library rows), and the shared tail of the Qobuz one. +pub async fn insert_dragged_queue_track( + runtime: &Arc>, + track: qbz_models::QueueTrack, + to_slot: usize, +) -> Result<(), String> { + let id = track.id; + let Some(qt) = crate::playback_qt::stamped(vec![track], None).pop() else { + log::info!("[qbz-qt] queue: dragged track {id} was filtered out"); return Ok(()); }; diff --git a/crates/qbz-qt/src/shell_bridge.rs b/crates/qbz-qt/src/shell_bridge.rs index 40e1bb3f7..27a0f6d1d 100644 --- a/crates/qbz-qt/src/shell_bridge.rs +++ b/crates/qbz-qt/src/shell_bridge.rs @@ -714,6 +714,18 @@ pub mod qbz_shell { y: f32, inline_visual: bool, ); + /// LOCAL-mode twin: a Local Library / Explorer row enters the shared + /// drag by ROW ID (resolved to source-aware refs at drop time). + #[qinvokable] + fn drag_start_local( + self: Pin<&mut QbzShell>, + row_id: QString, + title: QString, + subtitle: QString, + x: f32, + y: f32, + inline_visual: bool, + ); #[qinvokable] fn drag_move(self: Pin<&mut QbzShell>, x: f32, y: f32); /// A sidebar playlist row claims / releases the drop target. @@ -1449,6 +1461,25 @@ impl qbz_shell::QbzShell { ); } + pub fn drag_start_local( + self: Pin<&mut Self>, + row_id: QString, + title: QString, + subtitle: QString, + x: f32, + y: f32, + inline_visual: bool, + ) { + crate::drag_start_local( + row_id.to_string(), + title.to_string(), + subtitle.to_string(), + x, + y, + inline_visual, + ); + } + pub fn drag_move(self: Pin<&mut Self>, x: f32, y: f32) { crate::drag_move(x, y); } From c650856c840d0202cf9ca680f9de85ec49c8225c Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 18:58:33 -0600 Subject: [PATCH 08/10] feat(qt): picker modal wheel lock, wider card, containment side column MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The picker and its duplicate sub-modal eat the wheel on scrim and card (the DiscoverConfigModal contract) so the page behind no longer scrolls. The card widens to 735px, and Already in moves from an in-flow horizontal strip to a right-hand column that exists only when there are containments to show — the playlist dropdown overlays the main column only, so the answer stays readable while the list is open. cc --- .../qml/controls/PlaylistPickerModal.qml | 256 +++++++++--------- 1 file changed, 133 insertions(+), 123 deletions(-) diff --git a/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml b/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml index 94de80060..ea1ea44a9 100644 --- a/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml +++ b/crates/qbz-qt/qml/controls/PlaylistPickerModal.qml @@ -49,14 +49,13 @@ Item { // honest per alreadyState ("loading"|"complete"|"updating"|"unavailable"). readonly property var alreadyIn: doc.alreadyIn || [] readonly property string alreadyState: doc.alreadyState || "" - // The strip renders only when it can back a claim: complete with matches, - // or updating (where partial matches show under an explicit caveat). - readonly property bool alreadyShowing: !root.creatingOpen - && (root.alreadyState === "updating" - || (root.alreadyState === "complete" && root.alreadyIn.length > 0)) - // Independently collapsible (session-local: the modal mounts once per - // app run and this deliberately survives resetLocals()). - property bool alreadyCollapsed: false + // The column renders only when it can back a claim: complete with + // matches, or updating (where partial matches show under an explicit + // caveat). It is a SIDE column, not an in-flow strip, so the dropdown + // can never cover it. + readonly property bool alreadyShowing: + root.alreadyState === "updating" + || (root.alreadyState === "complete" && root.alreadyIn.length > 0) // The carried payload is LocalLibrary refs (counter wording only). readonly property bool localMode: doc.localMode === true readonly property bool creatingOpen: doc.creatingOpen === true @@ -115,20 +114,23 @@ Item { anchors.fill: parent visible: root.doc.open === true && root.dup.open !== true - // Scrim — click outside dismisses. + // Scrim — click outside dismisses. The wheel is eaten too: these + // overlays are plain Items, not Popups, so no modal grab stops the + // page underneath from scrolling (the DiscoverConfigModal contract). Rectangle { anchors.fill: parent color: "#bf000000" MouseArea { anchors.fill: parent onClicked: QbzPlaylistPicker.close() + onWheel: function (wheel) { wheel.accepted = true } } } Rectangle { id: card anchors.centerIn: parent - width: Math.min(parent.width - 80, 490) + width: Math.min(parent.width - 80, 735) // Tauri: min-height 400 / max-height 90vh. The body stretches so // the footer pins to the bottom. height: Math.min(Math.max(400, panel.implicitHeight), parent.height * 0.9) @@ -138,11 +140,17 @@ Item { border.color: theme.borderSubtle // NO clip: the dropdown legitimately overflows the card bottom. + // The "Already in" side column's slot. Zero when absent, so the + // main content takes the whole card. + readonly property real rightPanelW: root.alreadyShowing ? 221 : 0 + // Swallow clicks so they never reach the scrim; doubles as // "a click inside the card closes the list" (Tauri parity). + // The wheel stops here too — same reason as the scrim. MouseArea { anchors.fill: parent onClicked: root.dropdownOpen = false + onWheel: function (wheel) { wheel.accepted = true } } Column { @@ -189,10 +197,11 @@ Item { } Rectangle { width: parent.width; height: 1; color: theme.borderSubtle } - // --- Body --------------------------------------------- + // --- Body (the MAIN column; the "Already in" side column + // takes the right slot when present) ------------------- Column { id: body - width: parent.width + width: parent.width - card.rightPanelW padding: 24 spacing: 16 @@ -384,123 +393,117 @@ Item { } } - // --- "Already in" containment strip ---------------- - // Writable playlists that already hold carried tracks. - // Shown only when the index can back the claim: complete - // with matches, or updating under an explicit caveat — - // an empty answer from an incomplete index says NOTHING - // and renders nothing (ADD_TO_PLAYLIST_REDESIGN.md). - Column { - width: parent.width - 48 - spacing: 8 - visible: root.alreadyShowing + } + } - Item { - width: parent.width - height: 20 - Row { + // --- "Already in" side column ----------------------------- + // The containment answer as a right-hand column instead of an + // in-flow strip: the dropdown overlays the MAIN column only, so + // this list stays readable while the playlist list is open. + // Shown if and only if the index can back a claim (complete with + // matches, or updating under the explicit caveat) — an empty + // answer from an incomplete index renders nothing. + Item { + visible: root.alreadyShowing + anchors.top: parent.top + anchors.topMargin: 69 + anchors.bottom: footerDivider.top + anchors.right: parent.right + width: card.rightPanelW + + Rectangle { + anchors.left: parent.left + anchors.top: parent.top + anchors.bottom: parent.bottom + width: 1 + color: theme.borderSubtle + } + + Column { + anchors.fill: parent + anchors.leftMargin: 17 + anchors.rightMargin: 16 + anchors.topMargin: 16 + spacing: 8 + + Text { + text: QbzSession.tr("Already in", QbzSession.trRev) + color: theme.textSecondary + font.pixelSize: theme.fontLegal + font.weight: theme.weightMedium + } + Text { + visible: root.alreadyState === "updating" + width: parent.width + text: QbzSession.tr("Playlist index updating...", QbzSession.trRev) + color: theme.textMuted + font.pixelSize: theme.fontLegal + font.italic: true + wrapMode: Text.WordWrap + } + + ListView { + width: parent.width + height: Math.max(0, parent.height - y - 12) + clip: true + spacing: 2 + boundsBehavior: Flickable.StopAtBounds + model: root.alreadyIn + delegate: Rectangle { + required property var modelData + width: parent ? parent.width : 0 + height: 34 + radius: theme.radiusSm + color: alreadyArea.containsMouse + ? theme.surfaceHover : "transparent" + QbzIcon { + id: alreadyGlyph + visible: modelData.isLocal === true anchors.left: parent.left + anchors.leftMargin: 6 anchors.verticalCenter: parent.verticalCenter - spacing: 6 - Text { - anchors.verticalCenter: parent.verticalCenter - text: QbzSession.tr("Already in", QbzSession.trRev) - color: theme.textSecondary - font.pixelSize: theme.fontLegal - font.weight: theme.weightMedium - } - QbzIcon { - anchors.verticalCenter: parent.verticalCenter - name: root.alreadyCollapsed ? "chevron-down" : "chevron-up" - width: 12 - height: 12 - tintName: alreadyToggle.containsMouse ? "textPrimary" : "muted" - } + name: "hard-drive" + width: 12 + height: 12 + tintName: "muted" + } + Text { + anchors.left: alreadyGlyph.visible + ? alreadyGlyph.right : parent.left + anchors.leftMargin: 6 + anchors.right: alreadyCount.visible + ? alreadyCount.left : parent.right + anchors.rightMargin: 6 + anchors.verticalCenter: parent.verticalCenter + text: modelData.name + color: theme.textPrimary + font.pixelSize: theme.fontLegal + elide: Text.ElideRight + } + // The multi-track answer: "2 of 5". A full or + // single-track containment says it by presence. + Text { + id: alreadyCount + visible: root.trackCount > 1 + && modelData.contained < root.trackCount + anchors.right: parent.right + anchors.rightMargin: 6 + anchors.verticalCenter: parent.verticalCenter + text: QbzSession.tr("{} of {}", QbzSession.trRev) + .replace("{}", modelData.contained) + .replace("{}", root.trackCount) + color: theme.textMuted + font.pixelSize: theme.fontLegal } MouseArea { - id: alreadyToggle + id: alreadyArea anchors.fill: parent hoverEnabled: true cursorShape: Qt.PointingHandCursor - onClicked: root.alreadyCollapsed = !root.alreadyCollapsed - } - Text { - visible: root.alreadyState === "updating" - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - text: QbzSession.tr("Playlist index updating...", QbzSession.trRev) - color: theme.textMuted - font.pixelSize: theme.fontLegal - font.italic: true - } - } - - ListView { - visible: !root.alreadyCollapsed && root.alreadyIn.length > 0 - width: parent.width - height: visible ? 32 : 0 - orientation: ListView.Horizontal - spacing: 8 - clip: true - boundsBehavior: Flickable.StopAtBounds - model: root.alreadyIn - delegate: Rectangle { - required property var modelData - width: alreadyRow.implicitWidth + 20 - height: 30 - radius: 6 - color: alreadyArea.containsMouse - ? theme.surfaceHover : theme.surfaceElevated - border.width: 1 - border.color: theme.borderSubtle - Row { - id: alreadyRow - anchors.centerIn: parent - spacing: 6 - QbzIcon { - visible: modelData.isLocal === true - anchors.verticalCenter: parent.verticalCenter - name: "hard-drive" - width: 12 - height: 12 - tintName: "muted" - } - Text { - anchors.verticalCenter: parent.verticalCenter - // Cap so one long name cannot push the - // whole strip off-card; implicitWidth - // is layout-independent, so this is - // not a binding loop. - width: Math.min(implicitWidth, 180) - text: modelData.name - color: theme.textPrimary - font.pixelSize: theme.fontLegal - elide: Text.ElideRight - } - // The multi-track card: "2 of 5". A full - // or single-track containment says it by - // presence alone. - Text { - visible: root.trackCount > 1 - && modelData.contained < root.trackCount - anchors.verticalCenter: parent.verticalCenter - text: QbzSession.tr("{} of {}", QbzSession.trRev) - .replace("{}", modelData.contained) - .replace("{}", root.trackCount) - color: theme.textMuted - font.pixelSize: theme.fontLegal - } - } - MouseArea { - id: alreadyArea - anchors.fill: parent - hoverEnabled: true - cursorShape: Qt.PointingHandCursor - // Selecting it is the useful action: "add - // the missing 3 of 5" is one click plus - // the dup-confirm's "only new" answer. - onClicked: root.selectRow(modelData) - } + // Selecting it is the useful action: "add the + // missing 3 of 5" is one click plus the + // dup-confirm's only-new answer. + onClicked: root.selectRow(modelData) } } } @@ -509,6 +512,7 @@ Item { // --- Footer, pinned to the card bottom -------------------- Rectangle { + id: footerDivider anchors.left: parent.left anchors.right: parent.right anchors.bottom: footerRow.top @@ -561,7 +565,9 @@ Item { // 1 divider + 24 body pad + 20 label row + 8 spacing + // 43 input + 4 gap. y: 68 + 1 + 24 + 20 + 8 + 43 + 4 - width: parent.width - 48 + // MAIN column only — the "Already in" side column stays + // readable while the list is open (that is its whole point). + width: parent.width - card.rightPanelW - 48 // create row 41 + 1 divider, pinned last-used 41 + 1, 41 per // shown row, 41 no-results, 1 + 34 overflow. Tauri max-height // 320 + border. @@ -783,6 +789,7 @@ Item { MouseArea { anchors.fill: parent onClicked: QbzPlaylistPicker.cancelDuplicates() + onWheel: function (wheel) { wheel.accepted = true } } } @@ -794,7 +801,10 @@ Item { color: theme.surfaceCard border.width: 1 border.color: theme.borderSubtle - MouseArea { anchors.fill: parent } + MouseArea { + anchors.fill: parent + onWheel: function (wheel) { wheel.accepted = true } + } Column { id: dupPanel From 0c28f9e64b601adba0f8c773bb060bb319e86975 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 19:55:48 -0600 Subject: [PATCH 09/10] fix(qt): artist Popular Tracks quality cell mounts the real badge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PopularTrackRow fork rendered a lone tier word (HI-RES/CD) in a plain Text while the document has carried qualityDetail all along; it now mounts the same bare QualityBadgeFull as the shared TrackRow's quality cell — tier label over the exact bit-depth/rate line. Audit: every other popular/track list already goes through rows/TrackRow.qml, so this fork was the only divergent quality cell. cc --- crates/qbz-qt/qml/views/ArtistView.qml | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/qbz-qt/qml/views/ArtistView.qml b/crates/qbz-qt/qml/views/ArtistView.qml index 955fa2db8..916ecf51f 100644 --- a/crates/qbz-qt/qml/views/ArtistView.qml +++ b/crates/qbz-qt/qml/views/ArtistView.qml @@ -1331,14 +1331,22 @@ Rectangle { font.pixelSize: 13 horizontalAlignment: Text.AlignHCenter } - Text { + // The SAME bare badge the shared TrackRow's quality cell mounts + // (rows/TrackRow.qml:1048): tier label stacked over the exact + // "24-bit / 96 kHz" line. This fork used to render a lone tier + // word ("HI-RES") even though the document has carried + // qualityDetail all along. + Item { width: cols.colQuality - anchors.verticalCenter: parent.verticalCenter - text: row.qualityTier === "hires" ? "HI-RES" : (row.qualityTier === "cd" ? "CD" : "") - color: theme.textMuted - font.pixelSize: 10 - font.weight: theme.weightBold - horizontalAlignment: Text.AlignHCenter + height: parent.height + QualityBadgeFull { + anchors.centerIn: parent + tier: row.qualityTier || "" + detail: row.qualityDetail || "" + showIcon: false + bare: true + maxTextWidth: cols.colQuality + } } // Favorite (live). Reads through the override map so the state // survives a document republish (see root.localToggles). @@ -1959,6 +1967,7 @@ Rectangle { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityDetail || "" artSource: root.coverMap[modelData.artUrl] || "" // artist_qt `map_release` stamps the pin state on every // release row; SectionRail is the only other reader and @@ -2636,6 +2645,7 @@ Rectangle { genre: root.artist.lastRelease ? root.artist.lastRelease.genre : "" year: root.artist.lastRelease ? root.artist.lastRelease.year : "" qualityTier: root.artist.lastRelease ? root.artist.lastRelease.qualityTier : "" + qualityDetail: root.artist.lastRelease ? (root.artist.lastRelease.qualityDetail || "") : "" artSource: root.artist.lastRelease ? (root.coverMap[root.artist.lastRelease.artUrl] || "") : "" // Same row shape as the release grids (map_release). isPinned: root.artist.lastRelease ? root.artist.lastRelease.isPinned === true : false @@ -2785,6 +2795,7 @@ Rectangle { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityDetail || "" artSource: root.coverMap[modelData.artUrl] || "" isPinned: modelData.isPinned === true artworkUrl: modelData.artUrl || "" @@ -2865,6 +2876,7 @@ Rectangle { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityDetail || "" artSource: root.coverMap[modelData.imageUrl] || "" // These rows are LIBRARY feed items (FeedItem), // not release cards: the remote url is From bbe8b6a0f2dd16564ca9fe75f476e6e4228fe43e Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 19:55:48 -0600 Subject: [PATCH 10/10] feat(qt): album card quality badges reveal the exact quality on hover MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QualityBadge has always owned a hover tooltip, but every AlbumCard host passed only the tier, so the tip had nothing to say. The card gains a qualityDetail input feeding the badge's label, and all fifteen mounts now pass their model's detail (HomeCard rides its qualityLabel twin). Un-hydrated Plex/remote rows surface their bare filetype — the known honest fallback; an empty detail still shows no tooltip at all. The Scene panel's own card already wired this and is untouched. cc --- crates/qbz-qt/qml/cards/AlbumCard.qml | 10 +++++++++- crates/qbz-qt/qml/views/AlbumCollection.qml | 2 ++ crates/qbz-qt/qml/views/HomeView.qml | 2 ++ crates/qbz-qt/qml/views/LabelView.qml | 1 + crates/qbz-qt/qml/views/SearchView.qml | 3 +++ crates/qbz-qt/qml/views/SectionRail.qml | 1 + crates/qbz-qt/qml/views/library/FeedGridCell.qml | 1 + .../qbz-qt/qml/views/library/LibraryArtistsPanel.qml | 1 + crates/qbz-qt/qml/views/local/LocalAlbumCollection.qml | 1 + crates/qbz-qt/qml/views/myqbz/MyQbzDetailView.qml | 2 ++ 10 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/qbz-qt/qml/cards/AlbumCard.qml b/crates/qbz-qt/qml/cards/AlbumCard.qml index 21a3c2d67..794d6385e 100644 --- a/crates/qbz-qt/qml/cards/AlbumCard.qml +++ b/crates/qbz-qt/qml/cards/AlbumCard.qml @@ -41,6 +41,11 @@ Rectangle { property string genre: "" property string year: "" property string qualityTier: "" + /// Exact stored quality ("24-bit / 96 kHz"), shown by the badge's hover + /// tooltip. Hosts whose model has no detail (un-hydrated Plex/remote + /// rows) may pass the bare filetype ("FLAC") — known limitation, and + /// still truthful; empty shows no tooltip at all. + property string qualityDetail: "" property string ribbon: "" property string ribbonKind: "" // Artwork image source (file://… or "") — the host's cache lookup. @@ -831,10 +836,13 @@ Rectangle { elide: Text.ElideRight } } - // Icon-only quality badge (QualityBadge.slint). + // Icon-only quality badge (QualityBadge.slint). `label` feeds the + // badge's own hover tooltip with the exact stored quality; the + // badge shows nothing when the host has no detail to give. QualityMini { id: qBadge tier: root.qualityTier + label: root.qualityDetail anchors.verticalCenter: parent.verticalCenter } } diff --git a/crates/qbz-qt/qml/views/AlbumCollection.qml b/crates/qbz-qt/qml/views/AlbumCollection.qml index a872b6e06..984e167e6 100644 --- a/crates/qbz-qt/qml/views/AlbumCollection.qml +++ b/crates/qbz-qt/qml/views/AlbumCollection.qml @@ -388,6 +388,7 @@ Column { genre: gcell.modelData.genre year: gcell.modelData.year qualityTier: gcell.modelData.qualityTier + qualityDetail: gcell.modelData.qualityDetail || "" ribbon: gcell.modelData.ribbon || "" ribbonKind: gcell.modelData.ribbonKind || "" artSource: root.artOf(gcell.modelData) @@ -562,6 +563,7 @@ Column { genre: cell.cardData.genre year: cell.cardData.year qualityTier: cell.cardData.qualityTier + qualityDetail: cell.cardData.qualityDetail || "" ribbon: cell.cardData.ribbon || "" ribbonKind: cell.cardData.ribbonKind || "" artSource: root.artOf(cell.cardData) diff --git a/crates/qbz-qt/qml/views/HomeView.qml b/crates/qbz-qt/qml/views/HomeView.qml index 4e1ff473c..defacaddb 100644 --- a/crates/qbz-qt/qml/views/HomeView.qml +++ b/crates/qbz-qt/qml/views/HomeView.qml @@ -607,6 +607,7 @@ Rectangle { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityLabel || modelData.qualityDetail || "" ribbon: modelData.ribbon ribbonKind: modelData.ribbonKind artSource: root.sectionArtOf(modelData) @@ -1262,6 +1263,7 @@ Rectangle { genre: modelData.album.genre year: modelData.album.year qualityTier: modelData.album.qualityTier + qualityDetail: modelData.album.qualityLabel || modelData.album.qualityDetail || "" artSource: root.forYouArtOf(modelData.album) artworkUrl: modelData.album.artUrl || "" isPinned: modelData.album.isPinned === true diff --git a/crates/qbz-qt/qml/views/LabelView.qml b/crates/qbz-qt/qml/views/LabelView.qml index 365e8cc7d..0b1ffb493 100644 --- a/crates/qbz-qt/qml/views/LabelView.qml +++ b/crates/qbz-qt/qml/views/LabelView.qml @@ -218,6 +218,7 @@ Rectangle { genre: crCell.modelData.genre year: crCell.modelData.year qualityTier: crCell.modelData.qualityTier + qualityDetail: crCell.modelData.qualityDetail || "" ribbon: crCell.modelData.ribbon || "" ribbonKind: crCell.modelData.ribbonKind || "" artSource: crCell.modelData.artPath || "" diff --git a/crates/qbz-qt/qml/views/SearchView.qml b/crates/qbz-qt/qml/views/SearchView.qml index cb743ce3e..e5880ad69 100644 --- a/crates/qbz-qt/qml/views/SearchView.qml +++ b/crates/qbz-qt/qml/views/SearchView.qml @@ -351,6 +351,7 @@ Rectangle { genre: resultCell.cardData.genre year: resultCell.cardData.year qualityTier: resultCell.cardData.qualityTier + qualityDetail: resultCell.cardData.qualityDetail || "" artSource: resultCell.cardData.artPath || "" isFavorite: resultCell.cardData.isFavorite === true isPinned: resultCell.cardData.isPinned === true @@ -757,6 +758,7 @@ Rectangle { genre: (root.mp.album || ({})).genre || "" year: (root.mp.album || ({})).year || "" qualityTier: (root.mp.album || ({})).qualityTier || "" + qualityDetail: (root.mp.album || ({})).qualityDetail || "" artSource: (root.mp.album || ({})).artPath || "" // search_qt::map_album stamps the heart // from fav_cache; false inverted the @@ -879,6 +881,7 @@ Rectangle { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityDetail || "" artSource: modelData.artPath || "" // search_qt::map_album stamps the heart // from fav_cache; false made the glyph lie diff --git a/crates/qbz-qt/qml/views/SectionRail.qml b/crates/qbz-qt/qml/views/SectionRail.qml index 50b729579..9612c665a 100644 --- a/crates/qbz-qt/qml/views/SectionRail.qml +++ b/crates/qbz-qt/qml/views/SectionRail.qml @@ -63,6 +63,7 @@ Column { genre: modelData.genre year: modelData.year qualityTier: modelData.qualityTier + qualityDetail: modelData.qualityDetail || "" artSource: root.coverMap[modelData.artUrl] || "" // The row carries the heart (home_qt / recommendations_qt // stamp it from fav_cache at build time); hardcoding false diff --git a/crates/qbz-qt/qml/views/library/FeedGridCell.qml b/crates/qbz-qt/qml/views/library/FeedGridCell.qml index ce9db4a98..4ca3d0f94 100644 --- a/crates/qbz-qt/qml/views/library/FeedGridCell.qml +++ b/crates/qbz-qt/qml/views/library/FeedGridCell.qml @@ -81,6 +81,7 @@ Item { genre: cell.item.genre year: cell.item.year qualityTier: cell.item.qualityTier + qualityDetail: cell.item.qualityDetail || cell.item.qualityLabel || "" artSource: cell.view.artMap[cell.item.artKey] || "" isFavorite: cell.item.isFavorite isPinned: cell.item.isPinned diff --git a/crates/qbz-qt/qml/views/library/LibraryArtistsPanel.qml b/crates/qbz-qt/qml/views/library/LibraryArtistsPanel.qml index e314cfa60..0644e7bda 100644 --- a/crates/qbz-qt/qml/views/library/LibraryArtistsPanel.qml +++ b/crates/qbz-qt/qml/views/library/LibraryArtistsPanel.qml @@ -436,6 +436,7 @@ Item { genre: gcell.modelData.genre year: gcell.modelData.year qualityTier: gcell.modelData.qualityTier + qualityDetail: gcell.modelData.qualityDetail || "" artSource: root.coverMap[gcell.modelData.artUrl] || "" // The pin payload persists the REMOTE // url, never the file:// cache path. diff --git a/crates/qbz-qt/qml/views/local/LocalAlbumCollection.qml b/crates/qbz-qt/qml/views/local/LocalAlbumCollection.qml index e724c485c..3d97982ce 100644 --- a/crates/qbz-qt/qml/views/local/LocalAlbumCollection.qml +++ b/crates/qbz-qt/qml/views/local/LocalAlbumCollection.qml @@ -477,6 +477,7 @@ Item { genre: "" year: cardCell.slot.year qualityTier: cardCell.slot.qualityTier + qualityDetail: cardCell.slot.qualityDetail || "" artSource: cardCell.slot.artPath || (root.view ? (root.view.artMap[cardCell.slot.artKey] || "") : "") pinArtworkUrl: artSource diff --git a/crates/qbz-qt/qml/views/myqbz/MyQbzDetailView.qml b/crates/qbz-qt/qml/views/myqbz/MyQbzDetailView.qml index 76fac13dd..4a6f6f942 100644 --- a/crates/qbz-qt/qml/views/myqbz/MyQbzDetailView.qml +++ b/crates/qbz-qt/qml/views/myqbz/MyQbzDetailView.qml @@ -957,6 +957,7 @@ Rectangle { readonly property string cSubtitle: root.patchRev >= 0 ? (gcell.live.subtitle || "") : "" readonly property string cYear: root.patchRev >= 0 ? (gcell.live.yearText || "") : "" readonly property string cQuality: root.patchRev >= 0 ? (gcell.live.qualityTier || "") : "" + readonly property string cDetail: root.patchRev >= 0 ? (gcell.live.qualityDetail || "") : "" /// The GRID rung of the cover, NOT the list row's. /// `artPath` is the 50px thumbnail every list row draws /// at 40px; this cell's artwork well is 200px, so @@ -1084,6 +1085,7 @@ Rectangle { genre: "" year: gcell.cYear qualityTier: gcell.cQuality + qualityDetail: gcell.cDetail artSource: gcell.cArt // The pin payload / block snapshot url (see // `cArtUrl`). Without it a pinned My QBZ album