diff --git a/README.md b/README.md index 8770486..335c9fd 100644 --- a/README.md +++ b/README.md @@ -510,8 +510,10 @@ identities and data; no running player or user library is used. The native Rust [OpenDeck plugin](integrations/opendeck/README.md) provides playback buttons, direct transfer to an online trusted device, a clean album -cover key opening Functions, similarity radio, role colors and a scrolling -Neo Infobar. Its shared settings offer a scrolling spectrogram or live frequency +cover key opening Functions, role colors and a scrolling Neo Infobar. +Start similarity radio from the playing track, or tap the sparkles to preview +a random liked track for two seconds. Tap again to choose a different wave. +Its shared settings offer a scrolling spectrogram or live frequency bars for local audio, album art across four keys and role-colored icons on black. It targets OpenDeck 2.14.2 on Windows, macOS and Linux. Download the `furumi-opendeck` ZIP for your operating system alongside the player from diff --git a/docs/local-control.md b/docs/local-control.md index 02d863a..99c06bf 100644 --- a/docs/local-control.md +++ b/docs/local-control.md @@ -153,13 +153,13 @@ available sample. Normal playback snapshots retain their own cadence. ## Similarity radio -Radio uses the current music track as its seed and creates a temporary play +The `start_radio` command uses the current music track as its seed and creates a temporary play queue, without saving or editing a library playlist. Similarity must already be enabled and the seed must have a local indexed embedding (a remote seed is resolved by content ID against this computer's library). Podcast seeds are rejected. Network queries respect the existing federation consent. -The `radio` snapshot field has an operation `id`, a `state` +The `radio` snapshot field has an operation `id`, an optional `request_id` matching the start command, a `state` (`idle`, `searching`, `starting`, `playing`, `failed`) and an optional English error. Local and federated candidates are collected asynchronously before the queue is replaced. A bounded peer search is awaited; if peers fail but @@ -173,6 +173,34 @@ or an active output's matching playback report with advancing position. The plugin animates the Radio key until that operation succeeds, then returns to the main screen. Errors keep the Functions screen available. +### Radio from a liked track + +When a snapshot advertises `liked_radio_supported: true`, a control surface +can preview a random liked music track, including while playback is idle. +Choosing reads the personal library and the active local similarity index. +The response goes to the requesting client. For example, + +```json +{"type":"command","id":"pick-1","command":{"type":"pick_liked_radio_seed"}} +{"type":"liked_radio_seed","id":"pick-1","seed":{"key":"lib:7","title":"Nightfall","artist":"Northline"}} +``` + +On a reroll, pass the previous `seed.key` as `exclude`. Furumi picks a different +eligible track whenever possible. Replaying the same request ID returns the +cached choice. The preview has no playback or network side effects. +After displaying the chosen track, send its exact opaque key to start radio. + +```json +{"type":"command","id":"start-1","command":{"type":"start_liked_radio","seed_key":"lib:7"}} +``` + +Furumi checks that the selected track is still liked and uses its embedding +for the same local and federated search as regular radio. Follow snapshots +where `radio.request_id` matches this start. To reroll a search already in +progress, send a fresh pick with `replace_request_id` set to that start ID. +It can supersede that liked-radio search until its queue is committed. +Selection errors use the usual rejected command result. + ## OpenDeck The native Rust [OpenDeck integration](../integrations/opendeck/README.md) diff --git a/integrations/control-protocol/src/lib.rs b/integrations/control-protocol/src/lib.rs index 848d747..72f9b1d 100644 --- a/integrations/control-protocol/src/lib.rs +++ b/integrations/control-protocol/src/lib.rs @@ -25,6 +25,8 @@ pub struct Snapshot { pub api_version: u16, #[serde(default, skip_serializing_if = "is_false")] pub spectrum_supported: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub liked_radio_supported: bool, pub revision: u64, pub updated_at_ms: u64, pub role: Role, @@ -67,10 +69,19 @@ pub enum Repeat { #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct Radio { pub id: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, pub state: RadioState, pub error: Option, } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct LikedRadioSeed { + pub key: String, + pub title: String, + pub artist: String, +} + #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum RadioState { @@ -158,6 +169,15 @@ pub enum Command { ToggleShuffle, CycleRepeat, StartRadio, + PickLikedRadioSeed { + #[serde(default, skip_serializing_if = "Option::is_none")] + exclude: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + replace_request_id: Option, + }, + StartLikedRadio { + seed_key: String, + }, SetLiked { track_key: String, liked: bool, @@ -195,6 +215,10 @@ pub enum ServerMessage { accepted: bool, error: Option, }, + LikedRadioSeed { + id: String, + seed: LikedRadioSeed, + }, Artwork { id: String, artwork_id: String, diff --git a/integrations/opendeck/README.md b/integrations/opendeck/README.md index f280d90..26f89aa 100644 --- a/integrations/opendeck/README.md +++ b/integrations/opendeck/README.md @@ -62,7 +62,8 @@ the full release cover and opens Functions. A music-note icon appears when a cov is unavailable. The Devices key inside Functions shows the role and current audio owner. -The top row of Functions starts with **Like**, **Devices**, and **Radio**. +The top row of Functions contains **Like**, **Devices**, **Radio**, and a +**sparkles** key for radio from a random liked track. The back caret is at the bottom right. The Like key sits directly under the album-cover key, so two taps on that physical key like the playing track. A filled heart marks a liked track. To remove the like, tap the heart and let @@ -72,6 +73,15 @@ After Furumi saves the change, the heart shows the new state for half a second and the deck returns to playback. The heart is dimmed for podcast episodes and when the connected player does not supply a liked state. +Tap the sparkles to choose a liked track, even when the player is idle. +The Infobar switches to a single message line with the track title and artist. +The bar underneath shrinks from right to left for two seconds. Tap again to +draw another track and reset the countdown, or leave Functions to cancel the +preview. When the bar runs out, Furumi searches for music similar to the +displayed track. You can reroll while the search is still collecting matches. +Playback resumes on the main screen once the new radio is playing. This uses +liked tracks present in the local similarity index. + Radio starts Furumi's similarity radio; its key shows an animated spinner while local/federation results are collected and the first track is prepared. It returns to the player only for a diff --git a/integrations/opendeck/assets/icons/build-atlas.cjs b/integrations/opendeck/assets/icons/build-atlas.cjs index b8b7224..9342035 100644 --- a/integrations/opendeck/assets/icons/build-atlas.cjs +++ b/integrations/opendeck/assets/icons/build-atlas.cjs @@ -30,6 +30,7 @@ const specs = [ ['Unavailable', 'prohibit', 20, 80, 13], ['Heart', 'heart', 56, 48, 48, 'regular'], ['HeartFill', 'heart', 56, 48, 48], + ['Sparkle', 'sparkle', 56, 48, 48], ['CoverFrame', null, 0, 0, 0], ['EnabledFrame', null, 0, 0, 0], ]; diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.json b/integrations/opendeck/assets/icons/phosphor-atlas.json index f722005..57c50a3 100644 --- a/integrations/opendeck/assets/icons/phosphor-atlas.json +++ b/integrations/opendeck/assets/icons/phosphor-atlas.json @@ -149,7 +149,7 @@ "height": 96 }, { - "name": "CoverFrame", + "name": "Sparkle", "index": 18, "x": 192, "y": 192, @@ -157,7 +157,7 @@ "height": 96 }, { - "name": "EnabledFrame", + "name": "CoverFrame", "index": 19, "x": 288, "y": 192, @@ -165,7 +165,7 @@ "height": 96 }, { - "name": "Spinner0", + "name": "EnabledFrame", "index": 20, "x": 384, "y": 192, @@ -173,7 +173,7 @@ "height": 96 }, { - "name": "Spinner1", + "name": "Spinner0", "index": 21, "x": 480, "y": 192, @@ -181,7 +181,7 @@ "height": 96 }, { - "name": "Spinner2", + "name": "Spinner1", "index": 22, "x": 576, "y": 192, @@ -189,7 +189,7 @@ "height": 96 }, { - "name": "Spinner3", + "name": "Spinner2", "index": 23, "x": 672, "y": 192, @@ -197,7 +197,7 @@ "height": 96 }, { - "name": "Spinner4", + "name": "Spinner3", "index": 24, "x": 0, "y": 288, @@ -205,7 +205,7 @@ "height": 96 }, { - "name": "Spinner5", + "name": "Spinner4", "index": 25, "x": 96, "y": 288, @@ -213,7 +213,7 @@ "height": 96 }, { - "name": "Spinner6", + "name": "Spinner5", "index": 26, "x": 192, "y": 288, @@ -221,12 +221,20 @@ "height": 96 }, { - "name": "Spinner7", + "name": "Spinner6", "index": 27, "x": 288, "y": 288, "width": 96, "height": 96 + }, + { + "name": "Spinner7", + "index": 28, + "x": 384, + "y": 288, + "width": 96, + "height": 96 } ], "sources": [ @@ -315,6 +323,11 @@ "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/skip-forward-fill.svg", "sha256": "2f13f5cbeab47627d30782e7942001e7f80f7da993df053d3be2b8c6cb737ae2" }, + { + "file": "phosphor-fill/sparkle.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/sparkle-fill.svg", + "sha256": "9872a9255717f4ecc0f01b028b9436042e0f49391e4ce7a57f61aa466684fad1" + }, { "file": "phosphor-fill/spinner-gap.svg", "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/spinner-gap-fill.svg", diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.png b/integrations/opendeck/assets/icons/phosphor-atlas.png index 216b4d6..cf4309e 100644 Binary files a/integrations/opendeck/assets/icons/phosphor-atlas.png and b/integrations/opendeck/assets/icons/phosphor-atlas.png differ diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.svg b/integrations/opendeck/assets/icons/phosphor-atlas.svg index 9137d6a..a91d55e 100644 --- a/integrations/opendeck/assets/icons/phosphor-atlas.svg +++ b/integrations/opendeck/assets/icons/phosphor-atlas.svg @@ -1 +1 @@ -Furumi / Phosphor alpha atlas96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames. +Furumi / Phosphor alpha atlas96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames. diff --git a/integrations/opendeck/assets/icons/phosphor-fill/sparkle.svg b/integrations/opendeck/assets/icons/phosphor-fill/sparkle.svg new file mode 100644 index 0000000..f684ecc --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/sparkle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/src/icons.rs b/integrations/opendeck/src/icons.rs index 47f85a6..655474b 100644 --- a/integrations/opendeck/src/icons.rs +++ b/integrations/opendeck/src/icons.rs @@ -41,6 +41,7 @@ pub enum Icon { Unavailable, Heart, HeartFill, + Sparkle, CoverFrame, EnabledFrame, } @@ -150,7 +151,7 @@ pub fn cover_glyph( #[cfg(test)] mod tests { use super::*; - const ALL: [Icon; 20] = [ + const ALL: [Icon; 21] = [ Icon::Previous, Icon::Play, Icon::Pause, @@ -169,6 +170,7 @@ mod tests { Icon::Unavailable, Icon::Heart, Icon::HeartFill, + Icon::Sparkle, Icon::CoverFrame, Icon::EnabledFrame, ]; diff --git a/integrations/opendeck/src/liked_radio.rs b/integrations/opendeck/src/liked_radio.rs new file mode 100644 index 0000000..0ecdfa7 --- /dev/null +++ b/integrations/opendeck/src/liked_radio.rs @@ -0,0 +1,130 @@ +use furumi_control_protocol::{LikedRadioSeed, RadioState, Snapshot}; +use std::time::{Duration, Instant}; + +pub const PREVIEW_TIME: Duration = Duration::from_secs(2); +pub const PICK_TIMEOUT: Duration = Duration::from_secs(10); +pub const START_TIMEOUT: Duration = Duration::from_secs(240); +pub enum Phase { + Picking { + id: String, + since: Instant, + }, + Preview { + seed: LikedRadioSeed, + since: Instant, + }, + Starting { + id: String, + since: Instant, + }, + Failed(String), +} + +pub struct Attempt { + pub shown: bool, + pub widget_since: Instant, + pub phase: Phase, + pub last_key: Option, + pub owner: Option, +} + +pub fn can_pick(snapshot: &Snapshot, attempt: Option<&Attempt>) -> bool { + snapshot.liked_radio_supported + && match snapshot.radio.state { + RadioState::Starting => false, + RadioState::Searching => matches!( + attempt.map(|attempt| &attempt.phase), + Some(Phase::Starting { id, .. }) if snapshot.radio.request_id.as_ref() == Some(id) + ), + _ => true, + } +} + +impl Attempt { + pub fn request_id(&self) -> Option<&str> { + match &self.phase { + Phase::Picking { id, .. } | Phase::Starting { id, .. } => Some(id), + _ => None, + } + } + pub fn preview_due(&self, now: Instant) -> Option<&LikedRadioSeed> { + match &self.phase { + Phase::Preview { seed, since } + if self.shown && now.saturating_duration_since(*since) >= PREVIEW_TIME => + { + Some(seed) + } + _ => None, + } + } + pub fn timed_out(&self, now: Instant) -> bool { + let (since, limit) = match &self.phase { + Phase::Picking { since, .. } => (*since, PICK_TIMEOUT), + Phase::Starting { since, .. } => (*since, START_TIMEOUT), + _ => return false, + }; + now.saturating_duration_since(since) >= limit + } + + pub fn message(&self, now: Instant) -> (String, Option) { + match &self.phase { + Phase::Picking { .. } => ("Choosing track…".into(), None), + Phase::Preview { seed, since } => { + let elapsed = if self.shown { + now.saturating_duration_since(*since) + } else { + Duration::ZERO + }; + let remaining = + PREVIEW_TIME.saturating_sub(elapsed).as_secs_f32() / PREVIEW_TIME.as_secs_f32(); + let text = match (seed.title.trim(), seed.artist.trim()) { + ("", "") => "Unknown track".into(), + ("", artist) => artist.to_owned(), + (title, "") => title.to_owned(), + (title, artist) => format!("{title} · {artist}"), + }; + (text, Some(remaining)) + } + Phase::Starting { .. } => ("Starting radio…".into(), None), + Phase::Failed(error) => (error.clone(), None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn preview_waits_exactly_two_seconds_and_countdown_keeps_left_anchor() { + let now = Instant::now(); + let a = Attempt { + shown: true, + widget_since: now, + phase: Phase::Preview { + seed: LikedRadioSeed { + key: "a".into(), + title: "Title".into(), + artist: "Artist".into(), + }, + since: now, + }, + last_key: Some("a".into()), + owner: Some("self".into()), + }; + assert!(a.preview_due(now + Duration::from_millis(1999)).is_none()); + assert_eq!(a.preview_due(now + PREVIEW_TIME).unwrap().key, "a"); + assert_eq!(a.message(now).1, Some(1.0)); + assert_eq!(a.message(now + Duration::from_secs(1)).1, Some(0.5)); + assert_eq!(a.message(now + PREVIEW_TIME).1, Some(0.0)); + let mut a = a; + if let Phase::Preview { seed, .. } = &mut a.phase { + seed.artist.clear(); + } + assert_eq!(a.message(now).0, "Title"); + if let Phase::Preview { seed, .. } = &mut a.phase { + seed.artist = "Artist".into(); + seed.title.clear(); + } + assert_eq!(a.message(now).0, "Artist"); + } +} diff --git a/integrations/opendeck/src/main.rs b/integrations/opendeck/src/main.rs index 76acbb0..7297910 100644 --- a/integrations/opendeck/src/main.rs +++ b/integrations/opendeck/src/main.rs @@ -4,6 +4,7 @@ mod client; mod heart; mod host; mod icons; +mod liked_radio; mod model; mod preview; mod profile_upgrade; @@ -77,6 +78,11 @@ impl Surface { self.sequence += 1; let kind = if matches!(command, Command::Artwork { .. }) { "art" + } else if matches!( + command, + Command::PickLikedRadioSeed { .. } | Command::StartLikedRadio { .. } + ) { + "likedradio" } else if matches!(command, Command::SetLiked { .. }) { "like" } else { @@ -95,6 +101,7 @@ impl Surface { for deck in self.decks.values_mut() { deck.presses.clear(); deck.heart = None; + deck.liked_radio = None; deck.pending = None; deck.radio = None; deck.remote = RemoteGate::default(); @@ -205,6 +212,9 @@ impl Surface { "willDisappear" => { if let Some(instance) = self.instances.remove(&event.context) { if let Some(deck) = self.decks.get_mut(&instance.device) { + if instance.slot == Some(3) || instance.slot.is_none() { + deck.liked_radio = None; + } deck.presses.remove(&event.context); if instance.slot == Some(0) && deck @@ -243,6 +253,25 @@ impl Surface { let instance = self.instances.get(&event.context)?.clone(); let deck = self.decks.get_mut(&instance.device)?; let binding = deck.presses.remove(&event.context)?; + if binding == model::Binding::Command(Command::StartRadio) + && self.decks.values().any(|d| { + d.liked_radio + .as_ref() + .is_some_and(|a| !matches!(a.phase, liked_radio::Phase::Failed(_))) + || d.heart.as_ref().is_some_and(|h| { + matches!(h.phase, heart::Phase::Waiting(..) | heart::Phase::Sending) + }) + }) + { + return None; + } + let deck = self.decks.get_mut(&instance.device)?; + if binding == model::Binding::LikedRadio { + return self.pick_liked_radio(&instance.device, Instant::now()); + } + if !matches!(binding, model::Binding::Disabled) { + deck.liked_radio = None; + } if matches!(binding, model::Binding::Heart { .. }) && self.decks.values().any(|d| { d.heart.as_ref().is_some_and(|h| { @@ -297,6 +326,151 @@ impl Surface { } } + fn pick_liked_radio(&mut self, device: &str, now: Instant) -> Option { + if self.decks.values().any(|d| { + d.radio.is_some() + || d.heart.as_ref().is_some_and(|h| { + matches!(h.phase, heart::Phase::Waiting(..) | heart::Phase::Sending) + }) + }) { + return None; + } + let snapshot = self.snapshot.as_ref()?; + let owner = snapshot.active_device_id.clone(); + let deck = self.decks.get_mut(device)?; + if deck.binding(3, Some(snapshot)) != model::Binding::LikedRadio { + return None; + } + deck.heart = None; + let old = deck.liked_radio.take(); + let exclude = old.as_ref().and_then(|a| a.last_key.clone()); + let replace_request_id = old.as_ref().and_then(|a| match &a.phase { + liked_radio::Phase::Starting { id, .. } => Some(id.clone()), + _ => None, + }); + let (id, message) = self.request(Command::PickLikedRadioSeed { + exclude: exclude.clone(), + replace_request_id, + }); + self.decks.get_mut(device)?.liked_radio = Some(liked_radio::Attempt { + shown: false, + widget_since: now, + phase: liked_radio::Phase::Picking { id, since: now }, + last_key: exclude, + owner, + }); + self.keys_dirty = true; + Some(message) + } + + fn liked_radio_tick(&mut self, now: Instant) -> Vec { + let mut due = Vec::new(); + for (device, deck) in &mut self.decks { + let Some(attempt) = deck.liked_radio.as_mut() else { + continue; + }; + let visible = self + .instances + .values() + .any(|i| &i.device == device && i.slot == Some(3)) + && self + .instances + .values() + .any(|i| &i.device == device && i.slot.is_none()); + if !visible + || !matches!(deck.screen, model::Screen::Functions) + || self + .snapshot + .as_ref() + .is_none_or(|s| !s.liked_radio_supported || s.active_device_id != attempt.owner) + || now.saturating_duration_since(self.snapshot_at) > Duration::from_secs(3) + { + deck.liked_radio = None; + self.keys_dirty = true; + continue; + } + if let liked_radio::Phase::Starting { id, .. } = &attempt.phase + && let Some(snapshot) = &self.snapshot + && snapshot.radio.request_id.as_deref() == Some(id) + { + match snapshot.radio.state { + furumi_control_protocol::RadioState::Playing => { + deck.liked_radio = None; + deck.screen = model::Screen::Player; + self.keys_dirty = true; + continue; + } + furumi_control_protocol::RadioState::Failed => { + attempt.widget_since = now; + attempt.phase = liked_radio::Phase::Failed( + snapshot + .radio + .error + .clone() + .unwrap_or_else(|| "Liked radio failed".into()), + ); + self.keys_dirty = true; + } + _ => {} + } + } + if attempt.timed_out(now) { + attempt.phase = liked_radio::Phase::Failed("Liked radio timed out".into()); + attempt.widget_since = now; + self.keys_dirty = true; + } + let held_action = deck + .presses + .values() + .any(|binding| *binding != model::Binding::Disabled); + if !held_action && let Some(seed) = attempt.preview_due(now) { + due.push((device.clone(), seed.key.clone())); + } + } + let mut messages = Vec::new(); + for (device, seed_key) in due { + if self.remote.waiting(self.snapshot.as_ref()) { + if let Some(a) = self + .decks + .get_mut(&device) + .and_then(|d| d.liked_radio.as_mut()) + { + a.phase = liked_radio::Phase::Failed("Playback command pending".into()); + a.widget_since = now; + } + continue; + } + let (id, message) = self.request(Command::StartLikedRadio { seed_key }); + if let Some(attempt) = self + .decks + .get_mut(&device) + .and_then(|d| d.liked_radio.as_mut()) + { + attempt.phase = liked_radio::Phase::Starting { id, since: now }; + attempt.widget_since = now; + messages.push(message); + } + } + messages + } + + fn infobar_emitted(&mut self, context: &str, now: Instant) { + let Some(instance) = self.instances.get(context).filter(|i| i.slot.is_none()) else { + return; + }; + if let Some(attempt) = self + .decks + .get_mut(&instance.device) + .and_then(|d| d.liked_radio.as_mut()) + && !attempt.shown + && let liked_radio::Phase::Preview { since, .. } = &mut attempt.phase + { + *since = now; + attempt.widget_since = now; + attempt.shown = true; + } + } + fn heart_tick(&mut self, now: Instant) -> Vec { let track = self.snapshot.as_ref().and_then(|s| s.track.as_ref()); let mut commands = Vec::new(); @@ -387,6 +561,23 @@ impl Surface { client::Update::Message(message) => *message, }; match message { + ServerMessage::LikedRadioSeed { id, seed } => { + for deck in self.decks.values_mut() { + if let Some(a) = deck.liked_radio.as_mut() + && matches!(&a.phase,liked_radio::Phase::Picking{id:request,..} if request==&id) + { + a.last_key = Some(seed.key.clone()); + a.shown = false; + a.widget_since = Instant::now(); + a.phase = liked_radio::Phase::Preview { + seed: seed.clone(), + since: Instant::now(), + }; + self.keys_dirty = true; + break; + } + } + } ServerMessage::Snapshot { snapshot } => { let snapshot = *snapshot; if snapshot.api_version != API_VERSION { @@ -441,6 +632,24 @@ impl Surface { accepted, error, } => { + let mut liked_match = false; + for deck in self.decks.values_mut() { + if let Some(a) = deck.liked_radio.as_mut() + && a.request_id() == Some(id.as_str()) + { + liked_match = true; + if !accepted { + a.phase = liked_radio::Phase::Failed( + error.clone().unwrap_or_else(|| "Liked radio failed".into()), + ); + a.widget_since = Instant::now(); + self.keys_dirty = true; + } + } + } + if liked_match || id.contains("-likedradio-") { + return None; + } if self.finish_heart(&id, accepted, error.as_deref()) { return None; } @@ -571,7 +780,7 @@ impl Surface { let mut messages = Vec::new(); let now = Instant::now(); for instance in self.instances.values() { - let Some(deck) = self.decks.get(&instance.device) else { + let Some(deck) = self.decks.get_mut(&instance.device) else { continue; }; let image = match instance.slot { @@ -607,7 +816,11 @@ impl Surface { ), }; let raw = image.as_raw(); - if self.sent.get(&instance.context) == Some(raw) { + let first_preview = instance.slot.is_none() + && deck.liked_radio.as_ref().is_some_and(|a| { + !a.shown && matches!(a.phase, liked_radio::Phase::Preview { .. }) + }); + if self.sent.get(&instance.context) == Some(raw) && !first_preview { continue; } self.sent.insert(instance.context.clone(), raw.clone()); @@ -630,6 +843,7 @@ fn key_state_changed(a: &Snapshot, b: &Snapshot) -> bool { || a.remote_command != b.remote_command || a.track != b.track || a.devices != b.devices + || a.liked_radio_supported != b.liked_radio_supported } #[tokio::main] @@ -759,11 +973,13 @@ async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> let artwork = surface.artwork_request(Instant::now()); let spectrum = surface.spectrum_request(); let hearts = surface.heart_tick(Instant::now()); + let liked_radio = surface.liked_radio_tick(Instant::now()); for command in command .into_iter() .chain(artwork) .chain(spectrum) .chain(hearts) + .chain(liked_radio) { if let Err(error) = command_tx.try_send(command) { match error.into_inner() { @@ -772,6 +988,19 @@ async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> continue; } ClientMessage::Command { id, .. } => { + if id.contains("-likedradio-") { + for deck in surface.decks.values_mut() { + if let Some(a) = deck.liked_radio.as_mut() + && a.request_id() == Some(id.as_str()) + { + a.phase = + liked_radio::Phase::Failed("Command not sent".into()); + a.widget_since = Instant::now(); + } + } + surface.keys_dirty = true; + continue; + } if surface.finish_heart(&id, false, Some("Command not sent")) { continue; } @@ -805,6 +1034,9 @@ async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> host.send(Message::text(serde_json::to_string(&message)?)), ) .await??; + if let Some(context) = message["context"].as_str() { + surface.infobar_emitted(context, Instant::now()); + } } } Ok(()) @@ -834,6 +1066,295 @@ mod tests { surface } + fn liked_surface() -> Surface { + let mut surface = spectrum_surface(); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("willAppear", 3)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface + } + fn pick(surface: &mut Surface) -> String { + surface.host_event(event("keyDown", 3)); + let Some(ClientMessage::Command { + id, + command: Command::PickLikedRadioSeed { .. }, + }) = surface.host_event(event("keyUp", 3)) + else { + panic!("pick only") + }; + id + } + fn picked(surface: &mut Surface, id: String, key: &str) { + surface.update(client::Update::Message(Box::new( + ServerMessage::LikedRadioSeed { + id, + seed: furumi_control_protocol::LikedRadioSeed { + key: key.into(), + title: format!("Title {key}"), + artist: "Artist".into(), + }, + }, + ))); + surface.images().unwrap(); + surface.infobar_emitted("infobar", Instant::now()); + } + #[test] + fn captured_reroll_press_before_deadline_suppresses_start_until_paired_release() { + let mut surface = liked_surface(); + let id = pick(&mut surface); + picked(&mut surface, id, "shown"); + let liked_radio::Phase::Preview { since, .. } = + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase + else { + panic!() + }; + surface.host_event(event("keyDown", 3)); + let due = since + liked_radio::PREVIEW_TIME; + surface.snapshot_at = due; + assert!(surface.liked_radio_tick(due).is_empty()); + assert!( + matches!(surface.host_event(event("keyUp",3)),Some(ClientMessage::Command{command:Command::PickLikedRadioSeed{exclude:Some(key),..},..}) if key=="shown") + ); + assert!(surface.host_event(event("keyUp", 3)).is_none()); + assert!(surface.liked_radio_tick(due).is_empty()); + } + + #[test] + fn radio_actions_do_not_replace_each_other_or_pending_heart_writes() { + let mut surface = liked_surface(); + surface.host_event(event("willAppear", 2)); + surface.decks.get_mut("deck-1").unwrap().radio = Some(PendingRadio { + request_id: "ordinary".into(), + baseline: 0, + started: Instant::now(), + }); + assert!(surface.pick_liked_radio("deck-1", Instant::now()).is_none()); + assert!(surface.decks["deck-1"].radio.is_some()); + surface.decks.get_mut("deck-1").unwrap().radio = None; + pick(&mut surface); + surface.host_event(event("keyDown", 2)); + assert!(surface.host_event(event("keyUp", 2)).is_none()); + assert!(surface.decks["deck-1"].liked_radio.is_some()); + surface.decks.get_mut("deck-1").unwrap().heart = Some(heart::Heart { + key: "preview-track".into(), + liked: true, + phase: heart::Phase::Waiting("saving".into(), Instant::now()), + }); + assert!(surface.pick_liked_radio("deck-1", Instant::now()).is_none()); + assert!(surface.decks["deck-1"].heart.is_some()); + } + + #[test] + fn preview_clock_starts_with_first_infobar_frame_and_late_keyup_cannot_rearm_it() { + let mut surface = liked_surface(); + let id = pick(&mut surface); + surface.update(client::Update::Message(Box::new( + ServerMessage::LikedRadioSeed { + id, + seed: furumi_control_protocol::LikedRadioSeed { + key: "a".into(), + title: "A".into(), + artist: String::new(), + }, + }, + ))); + let now = Instant::now() + Duration::from_secs(5); + surface.snapshot_at = now; + assert!(surface.liked_radio_tick(now).is_empty()); + assert!(!surface.decks["deck-1"].liked_radio.as_ref().unwrap().shown); + surface.images().unwrap(); + assert!(!surface.decks["deck-1"].liked_radio.as_ref().unwrap().shown); + surface.infobar_emitted("infobar", Instant::now()); + assert!(surface.decks["deck-1"].liked_radio.as_ref().unwrap().shown); + surface.host_event(event("keyDown", 3)); + surface.host_event(event("willAppear", 7)); + surface.host_event(event("keyDown", 7)); + surface.host_event(event("keyUp", 7)); + assert!(surface.host_event(event("keyUp", 3)).is_none()); + assert!(surface.host_event(event("keyUp", 3)).is_none()); + assert!(surface.decks["deck-1"].liked_radio.is_none()); + } + + #[test] + fn liked_pick_and_start_use_different_bounded_timeouts() { + let mut surface = liked_surface(); + pick(&mut surface); + let now = Instant::now(); + surface.snapshot_at = now + liked_radio::PICK_TIMEOUT; + surface.liked_radio_tick(now + liked_radio::PICK_TIMEOUT); + assert!(matches!( + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase, + liked_radio::Phase::Failed(_) + )); + surface + .decks + .get_mut("deck-1") + .unwrap() + .liked_radio + .as_mut() + .unwrap() + .phase = liked_radio::Phase::Starting { + id: "start".into(), + since: now, + }; + surface.snapshot_at = now + Duration::from_secs(239); + surface.liked_radio_tick(now + Duration::from_secs(239)); + assert!(matches!( + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase, + liked_radio::Phase::Starting { .. } + )); + surface.liked_radio_tick(now + liked_radio::START_TIMEOUT); + assert!(matches!( + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase, + liked_radio::Phase::Failed(_) + )); + } + + #[test] + fn liked_radio_latest_pick_owns_full_two_second_preview_and_starts_exactly_once() { + let mut surface = liked_surface(); + let first = pick(&mut surface); + let second = pick(&mut surface); + picked(&mut surface, first, "stale"); + assert!(matches!( + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase, + liked_radio::Phase::Picking { .. } + )); + picked(&mut surface, second, "chosen"); + let liked_radio::Phase::Preview { since, .. } = + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase + else { + panic!() + }; + surface.snapshot_at = since; + assert!( + surface + .liked_radio_tick(since + Duration::from_millis(1999)) + .is_empty() + ); + let messages = surface.liked_radio_tick(since + Duration::from_secs(2)); + assert_eq!(messages.len(), 1); + let ClientMessage::Command { + id, + command: Command::StartLikedRadio { seed_key }, + } = &messages[0] + else { + panic!() + }; + assert_eq!(seed_key, "chosen"); + assert!( + surface + .liked_radio_tick(since + Duration::from_secs(2)) + .is_empty() + ); + let mut status = surface.snapshot.clone().unwrap(); + status.radio.request_id = Some(id.clone()); + status.radio.state = furumi_control_protocol::RadioState::Starting; + surface.update(snapshot_update(status.clone())); + assert_eq!( + surface.decks["deck-1"].binding(3, surface.snapshot.as_ref()), + model::Binding::Disabled + ); + status.radio.state = furumi_control_protocol::RadioState::Searching; + surface.update(snapshot_update(status)); + surface.host_event(event("keyDown", 3)); + assert!( + matches!(surface.host_event(event("keyUp",3)),Some(ClientMessage::Command{command:Command::PickLikedRadioSeed{exclude:Some(key),replace_request_id:Some(_)},..}) if key=="chosen") + ); + } + #[test] + fn liked_radio_ignores_old_failures_and_requires_its_own_playback_confirmation() { + let mut surface = liked_surface(); + let old = pick(&mut surface); + let fresh = pick(&mut surface); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id: old, + accepted: false, + error: Some("Old failure".into()), + }))); + assert!(matches!( + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase, + liked_radio::Phase::Picking { .. } + )); + picked(&mut surface, fresh, "a"); + let liked_radio::Phase::Preview { since, .. } = + surface.decks["deck-1"].liked_radio.as_ref().unwrap().phase + else { + panic!() + }; + let now = since + liked_radio::PREVIEW_TIME; + surface.snapshot_at = now; + let ClientMessage::Command { id, .. } = surface.liked_radio_tick(now).pop().unwrap() else { + panic!() + }; + let mut snapshot = surface.snapshot.clone().unwrap(); + snapshot.radio.state = furumi_control_protocol::RadioState::Playing; + snapshot.radio.request_id = Some("other-deck".into()); + surface.update(snapshot_update(snapshot.clone())); + surface.liked_radio_tick(now); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Functions + )); + snapshot.radio.request_id = Some(id); + surface.update(snapshot_update(snapshot)); + surface.liked_radio_tick(now); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Player + )); + surface.disconnect(); + assert!(surface.decks.values().all(|d| d.liked_radio.is_none())); + } + + #[test] + fn liked_preview_cancels_on_owner_navigation_hidden_infobar_or_key_and_old_hosts_disable_it() { + for cancel in 0..4 { + let mut surface = liked_surface(); + let id = pick(&mut surface); + picked(&mut surface, id, "a"); + let now = Instant::now(); + match cancel { + 0 => { + let mut s = surface.snapshot.clone().unwrap(); + s.active_device_id = Some("other".into()); + surface.update(snapshot_update(s)); + } + 1 => { + surface.host_event(event("willAppear", 7)); + surface.host_event(event("keyDown", 7)); + surface.host_event(event("keyUp", 7)); + } + 2 => { + surface.host_event( + serde_json::from_value( + json!({"event":"willDisappear","context":"infobar"}), + ) + .unwrap(), + ); + } + _ => { + surface.host_event(event("willDisappear", 3)); + } + } + surface.snapshot_at = now + Duration::from_secs(2); + assert!( + surface + .liked_radio_tick(now + Duration::from_secs(2)) + .is_empty() + ); + assert!(surface.decks["deck-1"].liked_radio.is_none()); + } + let mut s = preview::fixture(); + s.liked_radio_supported = false; + let deck = model::Deck { + screen: model::Screen::Functions, + ..Default::default() + }; + assert_eq!(deck.binding(3, Some(&s)), model::Binding::Disabled); + } + #[test] fn heart_result_is_correlated_and_confirmed_display_returns_after_half_second() { let mut surface = Surface::new(); @@ -1531,6 +2052,22 @@ mod tests { } let mut writes=Vec::new();while writes.len()<2 {let item=host.next().await.unwrap().unwrap();if let Message::Text(text)=item {let event:Value=serde_json::from_str(&text).unwrap();if event["event"]=="setGlobalSettings" {assert_eq!(event["context"],host::PLUGIN);writes.push(event["payload"].clone());}}} assert_eq!(writes[1]["album_art_2x2"],true);assert_eq!(writes[1]["invert_colors"],true);assert_eq!(writes[1]["future"]["keep"],42); + for slot in [0,3] { + host.send(Message::text(json!({"event":"willAppear","action":host::CELL,"context":format!("liked-cell-{slot}"),"device":"sd-FAKE","payload":{"controller":"Keypad","coordinates":{"row":0,"column":slot}}}).to_string())).await.unwrap(); + } + for slot in [0,3] {for kind in ["keyDown","keyUp"] {host.send(Message::text(json!({"event":kind,"context":format!("liked-cell-{slot}"),"device":"sd-FAKE"}).to_string())).await.unwrap();}} + let pick:ClientMessage=serde_json::from_slice(&api.next().await.unwrap().unwrap().into_data()).unwrap(); + let ClientMessage::Command{id,command:Command::PickLikedRadioSeed{..}}=pick else {panic!("first request chooses without searching")}; + let selected=ServerMessage::LikedRadioSeed{id,seed:furumi_control_protocol::LikedRadioSeed{key:"shown-seed".into(),title:"Shown title".into(),artist:"Shown artist".into()}}; + let selected_at=Instant::now(); + api.send(Message::text(serde_json::to_string(&ServerMessage::Snapshot{snapshot:Box::new(snapshot.clone())}).unwrap())).await.unwrap(); + api.send(Message::text(serde_json::to_string(&selected).unwrap())).await.unwrap(); + let early=tokio::time::timeout(Duration::from_millis(1900),async {loop {tokio::select! {message=api.next()=>return message,_=host.next()=>{}}}}).await; + assert!(early.is_err(),"no search command during the preview"); + let next=loop {tokio::select! {message=api.next()=>break message,_=host.next()=>{}}}; + let command:ClientMessage=serde_json::from_slice(&next.unwrap().unwrap().into_data()).unwrap(); + assert!(selected_at.elapsed()>=liked_radio::PREVIEW_TIME); + assert!(matches!(command,ClientMessage::Command{command:Command::StartLikedRadio{seed_key},..} if seed_key=="shown-seed")); host.close(None).await.unwrap(); plugin.await.unwrap().unwrap(); }).await.expect("mock host/API must finish without real configuration, peers or hardware"); diff --git a/integrations/opendeck/src/model.rs b/integrations/opendeck/src/model.rs index 73f04a2..c3c9076 100644 --- a/integrations/opendeck/src/model.rs +++ b/integrations/opendeck/src/model.rs @@ -11,7 +11,10 @@ const REMOTE_FALLBACK: Duration = Duration::from_secs(45); pub fn conflicts_with_remote_playback(command: &Command) -> bool { !matches!( command, - Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. } + Command::Transfer { .. } + | Command::Artwork { .. } + | Command::SetLiked { .. } + | Command::PickLikedRadioSeed { .. } ) } @@ -186,6 +189,7 @@ fn remote_error(error: Option<&str>) -> String { #[derive(Clone, Debug, PartialEq, Eq)] pub enum Binding { + LikedRadio, Heart { key: String, liked: bool }, Command(Command), Functions, @@ -220,6 +224,7 @@ pub struct PendingRadio { } pub struct Deck { + pub liked_radio: Option, pub heart: Option, pub screen: Screen, pub presses: BTreeMap, @@ -234,6 +239,7 @@ pub struct Deck { impl Default for Deck { fn default() -> Self { Self { + liked_radio: None, heart: None, screen: Screen::Player, presses: BTreeMap::new(), @@ -290,7 +296,31 @@ impl Deck { }) }) .unwrap_or(Binding::Disabled), - 2 if self.radio.is_none() => Binding::Command(Command::StartRadio), + 2 if self.radio.is_none() + && self.liked_radio.as_ref().is_none_or(|a| { + matches!(a.phase, crate::liked_radio::Phase::Failed(_)) + }) + && self.heart.as_ref().is_none_or(|h| { + !matches!( + h.phase, + crate::heart::Phase::Waiting(..) | crate::heart::Phase::Sending + ) + }) => + { + Binding::Command(Command::StartRadio) + } + 3 if snapshot.is_some_and(|s| { + crate::liked_radio::can_pick(s, self.liked_radio.as_ref()) + }) && self.radio.is_none() + && self.heart.as_ref().is_none_or(|h| { + !matches!( + h.phase, + crate::heart::Phase::Waiting(..) | crate::heart::Phase::Sending + ) + }) => + { + Binding::LikedRadio + } 1 => Binding::Devices, 7 => Binding::Back, _ => Binding::Disabled, @@ -363,6 +393,7 @@ impl Deck { self.heart = None; } match binding { + Binding::LikedRadio => None, Binding::Heart { key, liked } => { if !matches!(self.screen, Screen::Functions) || snapshot @@ -450,12 +481,16 @@ impl Deck { } } if let Some(radio) = &self.radio { - if snapshot.radio.id > radio.baseline && snapshot.radio.state == RadioState::Playing { + let matches_request = + if snapshot.liked_radio_supported || snapshot.radio.request_id.is_some() { + snapshot.radio.request_id.as_deref() == Some(radio.request_id.as_str()) + } else { + snapshot.radio.id > radio.baseline + }; + if matches_request && snapshot.radio.state == RadioState::Playing { self.screen = Screen::Player; self.radio = None; - } else if snapshot.radio.id > radio.baseline - && snapshot.radio.state == RadioState::Failed - { + } else if matches_request && snapshot.radio.state == RadioState::Failed { self.notice = Some(( snapshot .radio @@ -738,6 +773,27 @@ mod tests { assert!(matches!(a.screen, Screen::Devices { page: 0, .. })); } + #[test] + fn old_radio_servers_without_request_ids_keep_generation_fallback() { + let mut snapshot = fixture(); + snapshot.liked_radio_supported = false; + snapshot.radio.request_id = None; + snapshot.radio.id = 2; + snapshot.radio.state = RadioState::Playing; + let mut deck = Deck { + screen: Screen::Functions, + radio: Some(PendingRadio { + request_id: "legacy".into(), + baseline: 1, + started: Instant::now(), + }), + ..Default::default() + }; + deck.update(&snapshot); + assert!(matches!(deck.screen, Screen::Player)); + assert!(deck.radio.is_none()); + } + #[test] fn radio_waits_for_new_operation_and_actual_playback() { let mut snapshot = fixture(); @@ -755,6 +811,10 @@ mod tests { deck.update(&snapshot); assert!(deck.radio.is_some()); snapshot.radio.id = 11; + snapshot.radio.request_id = Some("another-deck".into()); + deck.update(&snapshot); + assert!(deck.radio.is_some()); + snapshot.radio.request_id = Some("radio-11".into()); snapshot.radio.state = RadioState::Searching; deck.update(&snapshot); assert!(deck.radio.is_some()); diff --git a/integrations/opendeck/src/preview.rs b/integrations/opendeck/src/preview.rs index 81c4be9..770a60a 100644 --- a/integrations/opendeck/src/preview.rs +++ b/integrations/opendeck/src/preview.rs @@ -51,6 +51,7 @@ pub fn fixture() -> Snapshot { radio: Radio::default(), remote_command: Some(Default::default()), spectrum_supported: false, + liked_radio_supported: true, track: Some(Track { key: "preview-track".into(), title: "Midnight City".into(), @@ -398,6 +399,28 @@ pub fn write(directory: &Path) -> Result<()> { image::imageops::overlay(&mut hearts, &key, 16 + index as i64 * 112, 28); } hearts.save(directory.join("heart-states.png"))?; + let mut widgets = RgbImage::from_pixel(280, 6 * 98 + 8, Rgb([24, 27, 32])); + for (index, (label, message, countdown)) in [ + ("Functions", "Choose a function", None), + ("Choosing", "Choosing track…", None), + ("Preview / 2 seconds", "Midnight City · M83", Some(1.0)), + ("Preview / 1 second", "Midnight City · M83", Some(0.5)), + ("Searching", "Finding similar…", None), + ("Error", "Like a track first", None), + ] + .into_iter() + .enumerate() + { + let y = 8 + index as i32 * 98; + render::preview_label(&mut widgets, label, 16, y, 248); + let age = countdown.map_or(Duration::ZERO, |remaining| { + crate::liked_radio::PREVIEW_TIME.mul_f32(1.0 - remaining) + }); + let bar = render::message_bar(message, countdown, Role::Active, false, age); + bar.save(directory.join(format!("liked-radio-widget-{index}.png")))?; + image::imageops::overlay(&mut widgets, &bar, 16, i64::from(y + 24)); + } + widgets.save(directory.join("liked-radio-widgets.png"))?; infobar_backgrounds(directory)?; let mut covers = RgbImage::from_pixel(856, 168, Rgb([24, 27, 32])); render::preview_label( diff --git a/integrations/opendeck/src/render.rs b/integrations/opendeck/src/render.rs index 70ea289..2ccc75f 100644 --- a/integrations/opendeck/src/render.rs +++ b/integrations/opendeck/src/render.rs @@ -386,6 +386,15 @@ pub fn key_prepared( label(&mut im, "Radio", 16.0, 73, fg); } } + 3 => icons::draw( + &mut im, + Icon::Sparkle, + if deck.binding(slot, snapshot) == crate::model::Binding::LikedRadio { + fg + } else { + [88, 101, 112] + }, + ), 1 => { icons::draw(&mut im, Icon::Devices, fg); let role_label = match snapshot.map(|s| s.role) { @@ -510,6 +519,47 @@ pub fn metadata(snapshot: &Snapshot) -> String { parts.join(" · ").chars().take(1024).collect() } +pub fn message_bar( + message: &str, + countdown: Option, + role: Role, + invert: bool, + age: Duration, +) -> RgbImage { + let mut im = RgbImage::from_pixel( + BAR_WIDTH, + BAR_HEIGHT, + Rgb(if invert { [0, 0, 0] } else { [8, 10, 13] }), + ); + let distance = (measure(message, 26.0) - 232.0).ceil(); + let offset = if distance > 0.0 { + let period = distance / 35.0 + 2.0; + (((age.as_secs_f32() % period) - 0.3).max(0.0) * 35.0).min(distance) as i32 + } else { + 0 + }; + text( + &mut im, + message, + 26.0, + 8 - offset, + 14, + (8, 4, 232, 44), + [226, 232, 238], + ); + if let Some(left) = countdown { + rect( + &mut im, + 8, + PROGRESS_Y, + (232.0 * left.clamp(0.0, 1.0)).round() as i32, + PROGRESS_HEIGHT, + palette(role).accent, + ); + } + im +} + pub fn bar( deck: &Deck, snapshot: Option<&Snapshot>, @@ -526,6 +576,46 @@ pub fn bar_with_spectrum( since_snapshot: Duration, spectrum: Option<&crate::spectrum::History>, ) -> RgbImage { + if matches!(deck.screen, Screen::Functions) { + let now = Instant::now(); + let age = deck + .liked_radio + .as_ref() + .map(|a| now.saturating_duration_since(a.widget_since)) + .or_else(|| { + deck.notice + .as_ref() + .map(|(_, since)| now.saturating_duration_since(*since)) + }) + .unwrap_or_default(); + let (message, countdown) = if snapshot.is_none() { + ("Furumi offline".into(), None) + } else if let Some(attempt) = &deck.liked_radio { + if let crate::liked_radio::Phase::Starting { id, .. } = &attempt.phase + && snapshot.is_some_and(|s| { + s.radio.request_id.as_deref() == Some(id) + && s.radio.state == furumi_control_protocol::RadioState::Searching + }) + { + ("Finding similar…".into(), None) + } else { + attempt.message(now) + } + } else if let Some((message, _)) = &deck.notice { + (message.clone(), None) + } else if deck.radio.is_some() { + ("Starting radio…".into(), None) + } else { + ("Choose a function".into(), None) + }; + return message_bar( + &message, + countdown, + snapshot.map_or(Role::Active, |s| s.role), + deck.preferences.invert_colors, + age, + ); + } let mut im = RgbImage::from_pixel( BAR_WIDTH, BAR_HEIGHT, @@ -674,6 +764,57 @@ mod tests { use super::*; use crate::preview::fixture; + #[test] + fn function_message_widget_uses_full_width_and_shrinks_only_from_right() { + let long = "A long explanatory error message that must remain readable"; + assert_ne!( + message_bar(long, None, Role::Active, false, Duration::ZERO), + message_bar(long, None, Role::Active, false, Duration::from_secs(2)) + ); + let deck = Deck { + screen: Screen::Functions, + ..Default::default() + }; + assert_eq!( + bar(&deck, None, Duration::ZERO, Duration::ZERO), + message_bar("Furumi offline", None, Role::Active, false, Duration::ZERO) + ); + let full = message_bar( + "Choose a function", + Some(1.0), + Role::Active, + false, + Duration::ZERO, + ); + let half = message_bar( + "Choose a function", + Some(0.5), + Role::Active, + false, + Duration::ZERO, + ); + let empty = message_bar( + "Choose a function", + Some(0.0), + Role::Active, + false, + Duration::ZERO, + ); + assert_eq!(full.dimensions(), (248, 58)); + for y in PROGRESS_Y..PROGRESS_Y + PROGRESS_HEIGHT { + assert_eq!(full.get_pixel(8, y as u32).0, palette(Role::Active).accent); + assert_eq!(half.get_pixel(8, y as u32).0, palette(Role::Active).accent); + assert_eq!( + half.get_pixel(123, y as u32).0, + palette(Role::Active).accent + ); + assert_eq!(half.get_pixel(124, y as u32).0, [8, 10, 13]); + assert_eq!(empty.get_pixel(8, y as u32).0, [8, 10, 13]); + } + let inverted = message_bar("Choose a function", None, Role::Jam, true, Duration::ZERO); + assert_eq!(inverted.get_pixel(247, 57).0, [0, 0, 0]); + } + #[test] fn inverted_heart_fade_keeps_black_background_and_stable_outline_after_send() { let now = Instant::now(); diff --git a/src/app/control.rs b/src/app/control.rs index 9079a4a..e039560 100644 --- a/src/app/control.rs +++ b/src/app/control.rs @@ -73,6 +73,7 @@ pub(crate) fn published(state: &AppState, revision: u64) -> crate::control::Publ snapshot: Snapshot { api_version: API_VERSION, spectrum_supported: true, + liked_radio_supported: true, revision, updated_at_ms: now.max(0) as u64, role: match state.device_playback.role { @@ -136,6 +137,13 @@ pub(super) enum Intent { Action(Action), Transfer(Device), Radio, + PickLikedRadioSeed { + exclude: Option, + replace_request_id: Option, + }, + StartLikedRadio { + seed_key: String, + }, SetLiked { track: Box, liked: bool, @@ -145,7 +153,10 @@ pub(super) enum Intent { pub(super) fn intent(state: &AppState, command: Command) -> Result { if !matches!( command, - Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. } + Command::Transfer { .. } + | Command::Artwork { .. } + | Command::SetLiked { .. } + | Command::PickLikedRadioSeed { .. } ) { super::remote_playback::available(state)?; } @@ -163,6 +174,14 @@ pub(super) fn intent(state: &AppState, command: Command) -> Result Intent::Action(Action::ToggleShuffle), Command::CycleRepeat => Intent::Action(Action::CycleRepeat), Command::StartRadio => Intent::Radio, + Command::PickLikedRadioSeed { + exclude, + replace_request_id, + } => Intent::PickLikedRadioSeed { + exclude, + replace_request_id, + }, + Command::StartLikedRadio { seed_key } => Intent::StartLikedRadio { seed_key }, Command::SetLiked { track_key, liked } => Intent::SetLiked { track: Box::new(super::likes::target(state, &track_key)?), liked, @@ -222,7 +241,17 @@ pub(super) fn dispatch( super::likes::set(runtime, *track, liked, request.reply); return; } - Ok(Intent::Radio) => super::radio::start(state, runtime), + Ok(Intent::Radio) => super::radio::start(state, runtime, None, request.id), + Ok(Intent::PickLikedRadioSeed { + exclude, + replace_request_id, + }) => { + super::radio::pick_liked(state, runtime, exclude, replace_request_id, request.reply); + return; + } + Ok(Intent::StartLikedRadio { seed_key }) => { + super::radio::start(state, runtime, Some(seed_key), request.id) + } Ok(Intent::Action(action)) => { // Same state transitions, remote targeting and podcast checks as media keys. let id = state.device_playback.control.status.id; @@ -262,5 +291,7 @@ pub(super) fn dispatch( } } }; - let _ = request.reply.send(result); + let _ = request + .reply + .send(result.map(|()| crate::control::Reply::Done)); } diff --git a/src/app/likes.rs b/src/app/likes.rs index ea0e0e5..99e1ae0 100644 --- a/src/app/likes.rs +++ b/src/app/likes.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use anyhow::{Result, ensure}; -use tokio::sync::{mpsc, oneshot}; +use tokio::sync::mpsc; use super::event::AppEvent; use super::state::{self, AppState}; @@ -93,7 +93,7 @@ pub(super) fn set( runtime: &Runtime, track: FedTrack, liked: bool, - reply: oneshot::Sender>, + reply: crate::control::ReplySender, ) { in_background(runtime, move |library, devices, tx| { let write = set_in_library(library, devices, &track, liked, tx).map_err(err_string); @@ -106,7 +106,7 @@ pub(super) fn set( Err(error) => Err(error.clone()), }; let _ = tx.send(AppEvent::LikesLoaded(ids)); - let _ = reply.send(write.and(saved)); + let _ = reply.send(write.and(saved).map(|()| crate::control::Reply::Done)); }); } diff --git a/src/app/radio.rs b/src/app/radio.rs index 26c8b8b..9887ff4 100644 --- a/src/app/radio.rs +++ b/src/app/radio.rs @@ -3,17 +3,21 @@ use std::sync::Arc; use std::time::{Duration, Instant}; -use furumi_control_protocol::{Radio as Status, RadioState}; +use anyhow::Context as _; +use furumi_control_protocol::{LikedRadioSeed, Radio as Status, RadioState}; +use rand::seq::SliceRandom; use super::event::AppEvent; use super::state::{AppState, SimilaritySearchHit}; use super::{Runtime, update}; -use crate::library::models::TrackItem; +use crate::library::{LIKES_PLAYLIST_ID, Library, models::TrackItem}; #[derive(Debug, Default)] pub(super) struct Radio { pub status: Status, seed: String, + from_likes: bool, + original_track: Option, owner: Option, queue: Vec, expected: Option, @@ -40,28 +44,45 @@ fn busy(state: &AppState) -> bool { ) } -pub(super) fn begin(state: &mut AppState) -> Result { +pub(super) enum Seed { + Current(Box), + Liked(String), +} + +pub(super) fn begin( + state: &mut AppState, + liked_key: Option, + request_id: String, +) -> Result { if busy(state) { return Err("Radio is already being prepared".into()); } if !state.similarity.settings.enabled { return Err("Enable similarity search in Furumi Settings first".into()); } - let seed = state - .player - .current - .clone() - .ok_or("Play a music track before starting radio")?; - if seed.is_podcast() { - return Err("Similarity radio is available for music tracks only".into()); - } + let (seed_key, seed) = if let Some(key) = liked_key { + (key.clone(), Seed::Liked(key)) + } else { + let track = state + .player + .current + .as_ref() + .ok_or("Play a music track before starting radio")?; + if track.is_podcast() { + return Err("Similarity radio is available for music tracks only".into()); + } + (identity(track), Seed::Current(Box::new(track.clone()))) + }; state.radio = Radio { status: Status { id: state.radio.status.id.wrapping_add(1), state: RadioState::Searching, error: None, + request_id: Some(request_id), }, - seed: identity(&seed), + seed: seed_key, + from_likes: matches!(seed, Seed::Liked(_)), + original_track: state.player.current.as_ref().map(identity), owner: state.device_playback.active_device_id.clone(), queue: queue_identity(state), expected: None, @@ -72,8 +93,114 @@ pub(super) fn begin(state: &mut AppState) -> Result { Ok(seed) } -pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), String> { - let seed = begin(state)?; +// A controller's numeric row IDs are not the output's IDs. +fn local_id(library: &Library, track: &TrackItem) -> anyhow::Result> { + if track.id >= 0 && track.fed.is_none() && !track.is_podcast() { + return Ok(Some(track.id)); + } + match super::state::track_content_id(track) { + Some(content_id) => library.track_id_by_content_id(&content_id), + None => Ok(None), + } +} + +fn choose_liked( + library: &Library, + profile: Option<&str>, + exclude: Option<&str>, +) -> anyhow::Result { + let mut tracks = library.playlist(LIKES_PLAYLIST_ID)?.tracks; + anyhow::ensure!(!tracks.is_empty(), "Like a track first"); + let profile = profile.context("No similarity index is ready yet")?; + tracks.shuffle(&mut rand::rng()); + // A shuffled traversal gives every eligible choice a chance. Keep the + // previous one only as a fallback for libraries with one eligible like. + let mut previous = None; + for track in tracks { + let Some(id) = local_id(library, &track)? else { + continue; + }; + if library.similarity_embedding(id, profile)?.is_none() { + continue; + } + let seed = LikedRadioSeed { + key: identity(&track), + artist: track.artist_line(), + title: track.title, + }; + if exclude != Some(seed.key.as_str()) { + return Ok(seed); + } + previous = Some(seed); + } + previous.context("No liked tracks in the local similarity index") +} + +// Rerolls may supersede only their own unfinished liked-radio search. Once +// the queue has committed, ordinary playback owns it. +pub(super) fn supersede(state: &mut AppState, request_id: &str) -> bool { + if state.radio.from_likes + && state.radio.status.state == RadioState::Searching + && state.radio.status.request_id.as_deref() == Some(request_id) + { + state.radio.status.state = RadioState::Idle; + state.radio.deadline = None; + return true; + } + false +} + +pub(super) fn pick_liked( + state: &mut AppState, + runtime: &mut Runtime, + exclude: Option, + replace_request_id: Option, + reply: crate::control::ReplySender, +) { + if replace_request_id + .as_deref() + .is_some_and(|id| supersede(state, id)) + && let Some(previous) = runtime.radio_task.take() + { + previous.abort(); + } + if busy(state) { + let _ = reply.send(Err("Radio is already being prepared".into())); + return; + } + if !state.similarity.settings.enabled { + let _ = reply.send(Err( + "Enable similarity search in Furumi Settings first".into() + )); + return; + } + let library = Arc::clone(&runtime.library); + let profile = runtime.similarity.status().active_profile; + tokio::task::spawn_blocking(move || { + let result = choose_liked(&library, profile.as_deref(), exclude.as_deref()) + .map(crate::control::Reply::LikedRadioSeed) + .map_err(super::err_string); + let _ = reply.send(result); + }); +} + +fn liked_track_id(library: &Library, key: &str) -> anyhow::Result { + let track = library + .playlist(LIKES_PLAYLIST_ID)? + .tracks + .into_iter() + .find(|track| identity(track) == key) + .context("This track is no longer liked")?; + local_id(library, &track)?.context("This liked track is no longer available locally") +} + +pub(super) fn start( + state: &mut AppState, + runtime: &mut Runtime, + liked_key: Option, + request_id: String, +) -> Result<(), String> { + let seed = begin(state, liked_key, request_id)?; if let Some(previous) = runtime.radio_task.take() { previous.abort(); } @@ -88,14 +215,17 @@ pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), S runtime.radio_task = Some(tokio::spawn(async move { let work = async move { let (local, query) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { - // A controller's numeric row IDs are not the output's IDs. - let local_seed = if seed.id >= 0 && seed.fed.is_none() { seed.id } else { - let content_id = seed.content_id.as_deref().ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?; - library.track_by_content_id(content_id)?.ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?.id + let local_seed = match seed { + Seed::Current(track) => local_id(&library, &track)?.context( + "Import and index this track locally before starting similarity radio", + )?, + Seed::Liked(key) => liked_track_id(&library, &key)?, }; similarity.search_track(local_seed, 49) - }).await.map_err(|error| format!("Radio search worker failed: {error}"))? - .map_err(|error| format!("Radio search failed: {error:#}"))?; + }) + .await + .map_err(|error| format!("Radio search worker failed: {error}"))? + .map_err(|error| format!("Radio search failed: {error:#}"))?; let mut hits: Vec<_> = local .into_iter() .map(|hit| SimilaritySearchHit::Local { @@ -149,7 +279,7 @@ pub(super) fn prepare( if id != state.radio.status.id || state.radio.status.state != RadioState::Searching { return false; } - if !seed_current(state) { + if !playback_unchanged(state) { fail(state, "Playback changed while radio was being prepared"); return false; } @@ -206,8 +336,8 @@ pub(super) fn ready( } } -fn seed_current(state: &AppState) -> bool { - state.player.current.as_ref().map(identity).as_ref() == Some(&state.radio.seed) +fn playback_unchanged(state: &AppState) -> bool { + state.player.current.as_ref().map(identity) == state.radio.original_track && state.device_playback.active_device_id == state.radio.owner && queue_identity(state) == state.radio.queue } @@ -264,7 +394,7 @@ pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) { if !busy(state) { return; } - if state.radio.status.state == RadioState::Searching && !seed_current(state) { + if state.radio.status.state == RadioState::Searching && !playback_unchanged(state) { fail(state, "Playback changed while radio was being prepared"); } else if state.device_playback.active_device_id != state.radio.owner { fail( @@ -284,3 +414,75 @@ pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) { task.abort(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn picks_only_indexed_likes_and_rechecks_the_exact_choice_on_start() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("library.sqlite3"); + let library = Library::open(&path).unwrap(); + assert!(choose_liked(&library, None, None).is_err()); + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute("INSERT INTO releases (id, title) VALUES (1, 'Album')", []) + .unwrap(); + for id in 1..=4 { + db.execute("INSERT INTO tracks (id, title, release_id, file_path, content_id) VALUES (?1, ?2, 1, ?2, ?3)", + rusqlite::params![id, format!("Song {id}"), format!("b3:{id:064x}")]).unwrap(); + } + drop(db); + library.set_synced_like(1, true, 1).unwrap(); + library.set_synced_like(3, true, 2).unwrap(); // No embedding for this track. + let profile = "test-profile"; + library + .ensure_similarity_profile(profile, "model", "1", "hash", "test", 1280) + .unwrap(); + assert!(choose_liked(&library, Some(profile), None).is_err()); + let mut vector = vec![0.0; 1280]; + vector[0] = 1.0; + for track in library.pending_similarity_tracks(profile).unwrap() { + if track.id != 3 { + library + .store_similarity_embedding(&track, profile, &vector) + .unwrap(); + } + } + let first = choose_liked(&library, Some(profile), None).unwrap(); + assert_eq!(first.title, "Song 1"); + assert_eq!( + choose_liked(&library, Some(profile), Some(&first.key)).unwrap(), + first + ); + + // A liked entry learned from another device can use a local embedding + // by content ID even before the library has reconciled the like rows. + let remote_like = crate::federation::FedTrack { + item_id: "peer-track".into(), + owner: "peer".into(), + own: false, + title: "Remote title".into(), + artist_names: vec!["Artist".into()], + featured_artist_names: vec![], + content_id: Some(format!("b3:{:064x}", 2)), + release_title: None, + year: None, + duration_seconds: None, + track_number: None, + disc_number: None, + }; + library.upsert_synced_fed_like(&remote_like, 3).unwrap(); + let second = choose_liked(&library, Some(profile), Some(&first.key)).unwrap(); + assert_eq!(second.title, remote_like.title); + assert_eq!(second.artist, "Artist"); + assert_eq!(liked_track_id(&library, &second.key).unwrap(), 2); + assert_eq!( + choose_liked(&library, Some(profile), Some(&second.key)).unwrap(), + first + ); + library.remove_fed_like_by_content_id(&second.key).unwrap(); + assert!(liked_track_id(&library, &second.key).is_err()); + assert_eq!(liked_track_id(&library, &first.key).unwrap(), 1); + } +} diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index a0b2c9e..b2cc7d4 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -474,7 +474,7 @@ fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() { use furumi_control_protocol::RadioState; let mut state = radio_state(); let before: Vec<_> = state.player.queue.iter().map(|track| track.id).collect(); - crate::app::radio::begin(&mut state).unwrap(); + crate::app::radio::begin(&mut state, None, "radio".into()).unwrap(); let id = state.radio.status.id; assert_eq!(state.radio.status.state, RadioState::Searching); assert_eq!( @@ -501,19 +501,91 @@ fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() { assert_eq!(state.radio.status.state, RadioState::Playing); } +#[test] +fn liked_radio_uses_the_selected_seed_from_idle_and_waits_for_playback() { + use crate::app::radio; + use furumi_control_protocol::RadioState; + let mut state = radio_state(); + state.player.current = None; + state.player.playing = false; + state.player.queue.clear(); + radio::begin(&mut state, test_track(3).content_id, "from-idle".into()).unwrap(); + let id = state.radio.status.id; + assert!(state.player.current.is_none()); + assert!(state.player.queue.is_empty()); + assert_eq!(state.radio.status.request_id.as_deref(), Some("from-idle")); + assert!(radio::prepare( + &mut state, + id, + Ok(vec![radio_hit(3, 0.99), radio_hit(4, 0.85)]) + )); + assert_eq!( + state + .player + .queue + .iter() + .map(|track| track.id) + .collect::>(), + [4] + ); + assert_eq!(state.radio.status.state, RadioState::Starting); + assert!(!radio::supersede(&mut state, "from-idle")); + radio::started(&mut state); + assert_eq!(state.radio.status.state, RadioState::Starting); + state.player.current = Some(test_track(4)); + state.player.playing = true; + radio::started(&mut state); + assert_eq!(state.radio.status.state, RadioState::Playing); +} + +#[test] +fn reroll_only_supersedes_the_matching_liked_search_and_preserves_newer_playback() { + use crate::app::radio; + let mut state = radio_state(); + radio::begin(&mut state, None, "regular".into()).unwrap(); + assert!(!radio::supersede(&mut state, "regular")); + + let mut state = radio_state(); + radio::begin(&mut state, test_track(3).content_id, "first".into()).unwrap(); + let first = state.radio.status.id; + assert!(!radio::supersede(&mut state, "another-client")); + assert!(radio::supersede(&mut state, "first")); + assert!(!radio::prepare( + &mut state, + first, + Ok(vec![radio_hit(4, 0.9)]) + )); + radio::begin(&mut state, test_track(6).content_id, "second".into()).unwrap(); + let second = state.radio.status.id; + assert!(!radio::prepare( + &mut state, + first, + Ok(vec![radio_hit(5, 0.9)]) + )); + assert_eq!(state.player.current.as_ref().unwrap().id, 1); + state.player.current = Some(test_track(2)); + assert!(!radio::prepare( + &mut state, + second, + Ok(vec![radio_hit(7, 0.9)]) + )); + assert_eq!(state.player.current.unwrap().id, 2); + assert_eq!(state.player.queue.len(), 2); +} + #[test] fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() { use furumi_control_protocol::RadioState; for result in [Err("peer error".into()), Ok(vec![])] { let mut state = radio_state(); - crate::app::radio::begin(&mut state).unwrap(); + crate::app::radio::begin(&mut state, None, "radio".into()).unwrap(); let id = state.radio.status.id; assert!(!crate::app::radio::prepare(&mut state, id, result)); assert_eq!(state.player.queue[0].id, 1); assert_eq!(state.radio.status.state, RadioState::Failed); } let mut state = radio_state(); - crate::app::radio::begin(&mut state).unwrap(); + crate::app::radio::begin(&mut state, None, "radio".into()).unwrap(); let id = state.radio.status.id; assert!(!crate::app::radio::prepare( &mut state, @@ -535,14 +607,14 @@ fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() { fn radio_rechecks_owner_and_requires_music_and_enabled_similarity() { let mut state = radio_state(); state.similarity.settings.enabled = false; - assert!(crate::app::radio::begin(&mut state).is_err()); + assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err()); state.similarity.settings.enabled = true; state.player.current = Some(crate::app::podcast_fixtures::episode_track(1)); - assert!(crate::app::radio::begin(&mut state).is_err()); + assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err()); state.player.current = Some(test_track(1)); - crate::app::radio::begin(&mut state).unwrap(); + crate::app::radio::begin(&mut state, None, "radio".into()).unwrap(); let id = state.radio.status.id; - assert!(crate::app::radio::begin(&mut state).is_err()); + assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err()); state.device_playback.active_device_id = Some("another".into()); assert!(!crate::app::radio::prepare( &mut state, @@ -557,7 +629,7 @@ fn radio_remote_start_requires_the_output_report_and_advancing_position() { use crate::devices::PlaybackTrackExt as _; use furumi_control_protocol::RadioState; let mut state = radio_state(); - crate::app::radio::begin(&mut state).unwrap(); + crate::app::radio::begin(&mut state, None, "radio".into()).unwrap(); let id = state.radio.status.id; let mut snapshot = crate::devices::PlaybackSnapshot { coordination: None, diff --git a/src/control.rs b/src/control.rs index 85c2f84..c844c9a 100644 --- a/src/control.rs +++ b/src/control.rs @@ -8,7 +8,8 @@ use std::time::Duration; use anyhow::{Context as _, Result, bail, ensure}; use base64::Engine as _; use furumi_control_protocol::{ - API_VERSION, ClientMessage, Command, Discovery, MAX_MESSAGE_BYTES, ServerMessage, Snapshot, + API_VERSION, ClientMessage, Command, Discovery, LikedRadioSeed, MAX_MESSAGE_BYTES, + ServerMessage, Snapshot, }; use futures_util::{SinkExt, StreamExt}; use tokio::net::{TcpListener, TcpStream}; @@ -28,8 +29,17 @@ mod tests; #[derive(Debug)] pub struct Request { + pub id: String, pub command: Command, - pub reply: oneshot::Sender>, + pub reply: ReplySender, +} + +pub type ReplySender = oneshot::Sender>; + +#[derive(Debug)] +pub enum Reply { + Done, + LikedRadioSeed(LikedRadioSeed), } #[derive(Clone)] @@ -189,6 +199,7 @@ async fn broker( let (tx, rx) = oneshot::channel(); let result = if events .send(crate::app::event::AppEvent::Control(Request { + id: request.id.clone(), command: request.command.clone(), reply: tx, })) @@ -202,10 +213,17 @@ async fn broker( .and_then(|reply| reply.map_err(|_| "player unavailable".to_string())) .and_then(|result| result) }; - let result = ServerMessage::Result { - id: request.id.clone(), - accepted: result.is_ok(), - error: result.err(), + let result = match result { + Ok(Reply::Done) => ServerMessage::Result { + id: request.id.clone(), + accepted: true, + error: None, + }, + Ok(Reply::LikedRadioSeed(seed)) => ServerMessage::LikedRadioSeed { + id: request.id.clone(), + seed, + }, + Err(error) => failure(request.id.clone(), &error), }; if recent.len() == 256 { recent.pop_front(); diff --git a/src/control_tests.rs b/src/control_tests.rs index 5416af5..7cd1794 100644 --- a/src/control_tests.rs +++ b/src/control_tests.rs @@ -40,6 +40,23 @@ type TestConnection = ( JoinHandle<()>, ); +#[test] +fn older_local_snapshots_do_not_advertise_liked_radio() { + let snapshot = + crate::app::control::published(&crate::app::state::AppState::default(), 1).snapshot; + let mut legacy = serde_json::to_value(snapshot).unwrap(); + assert_eq!( + legacy + .as_object_mut() + .unwrap() + .remove("liked_radio_supported"), + Some(true.into()) + ); + let decoded: Snapshot = serde_json::from_value(legacy).unwrap(); + assert!(!decoded.liked_radio_supported); + assert!(decoded.radio.request_id.is_none()); +} + async fn connect() -> TestConnection { connect_with(art::Covers::with(|_, _| Box::pin(async { None }))).await } @@ -149,6 +166,47 @@ async fn authenticated_session_streams_idle_state_and_routes_commands() { task.abort(); } +#[tokio::test] +async fn retrying_a_liked_radio_pick_returns_the_same_preview_without_a_second_draw() { + let (commands, queue) = mpsc::channel(8); + let (events, mut event_rx) = mpsc::unbounded_channel(); + let task = tokio::spawn(broker(queue, events)); + let seed = LikedRadioSeed { + key: "lib:7".into(), + title: "One".into(), + artist: "Two".into(), + }; + for attempt in 0..2 { + let (tx, rx) = oneshot::channel(); + commands + .send(Queued { + id: "pick".into(), + command: Command::PickLikedRadioSeed { + exclude: None, + replace_request_id: None, + }, + reply: tx, + }) + .await + .unwrap(); + if attempt == 0 { + let Some(crate::app::event::AppEvent::Control(request)) = event_rx.recv().await else { + panic!() + }; + assert_eq!(request.id, "pick"); + request + .reply + .send(Ok(Reply::LikedRadioSeed(seed.clone()))) + .unwrap(); + } + assert!( + matches!(rx.await.unwrap(), ServerMessage::LikedRadioSeed { id, seed: picked } if id == "pick" && picked == seed) + ); + } + assert!(event_rx.try_recv().is_err()); + task.abort(); +} + #[tokio::test] async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_rejected() { let (commands, queue) = mpsc::channel(8); @@ -166,7 +224,7 @@ async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_reject let crate::app::event::AppEvent::Control(event) = event_rx.recv().await.unwrap() else { panic!() }; - event.reply.send(Ok(())).unwrap(); + event.reply.send(Ok(Reply::Done)).unwrap(); assert!(matches!( rx.await.unwrap(), ServerMessage::Result { accepted: true, .. }