A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Linux: the Spotify pill over MPRIS, and Mochi dances to it
Claudec81076705cba
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex 777a49ea..8a6e1813 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -612,6 +612,7 @@ dependencies = [name = "coucou"version = "0.2.0"dependencies = [+ "dbus","gtk","keyring","libc",diff --git a/windows/README.md b/windows/README.mdindex cf48b882..4dba489b 100644--- a/windows/README.md+++ b/windows/README.md@@ -401,7 +401,8 @@ own window.- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or`Esc` in the island, and reopened by clicking the island or Open in the tray.- Apple Music, the one pill from the Mac catalog with nothing behind it here,- is left out.+ is left out. Spotify is on Linux only (see [Linux](#linux)): Windows has+ nothing to read it from yet.- Not in this version: sending a dropped file by email and dragging Mochi ontoa window to attach it as context. On the Mac, email goes through Resend orApple Mail's scripting; neither has a safe equivalent that attaches a file@@ -462,8 +463,10 @@ own window.without a restart (the Mac's **Restart Coucou** isn't needed). Arabic turnsthe island's text right to left but not its layout: Mochi and the pills keeptheir sides.-- Mochi on the desktop doesn't dance: there is no music integration to dance- to. Dropping him on a window doesn't attach it to the chat, and the Mac's+- Mochi on the desktop dances only on Linux, to Spotify; on Windows there is+ no music integration to dance to yet. While he dances he stays awake (the+ Mac lets him doze off mid-dance). Dropping him on a window doesn't attach it+ to the chat, and the Mac's⌃⌥D shortcut isn't there — drag him out, double-click him home. While hesleeps, the transparent square around him (120 px) takes the first mousemove, which wakes him and gives the rest back to the desktop.@@ -533,6 +536,20 @@ What changes on Linux:`goToAlert`, `jumpToTerminal`, `nextPill`, `prevPill`, `muteToggle` and`wardrobeToggle`.- **Keys** live in the Secret Service (GNOME Keyring, KWallet).+- **Spotify** (Settings → Integrations) is read over MPRIS, Spotify's D-Bus+ interface on the session bus: the pill shows the track and plays, pauses+ or skips on hover, the card has the cover, the progress bar (drag to+ seek), shuffle, previous, next, repeat and the volume, and Mochi dances+ while it plays — in the compact island, on the Spotify card, on the pill+ and on the desktop. Nothing is polled: one thread waits on the bus for+ Spotify's own signals while the pill is declared, and stops when it isn't.+ **Open Spotify** brings it forward or starts `spotify` from your `PATH`,+ else the Flatpak (`com.spotify.Client`) or the Snap; without one, **Get+ Spotify** opens its download page. Covers come from Spotify's image CDN+ (or a local track's file) and are fetched by Coucou itself, not the page.+ Spotify builds that don't report the position over MPRIS show the bar+ from where the track started; the Mac's Automation prompt has no+ equivalent here.- **Plan usage**: the status line relay is `~/.local/share/coucou/bin/coucou-hook--statusline` and runs your previous status line with `/bin/sh -c`, like ClaudeCode. Codex is found on `$PATH`, in `~/.local/bin`, npm's global prefix, Volta,diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex 741b0081..7beea0e5 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -50,3 +50,6 @@ libc = "0.2"# The GTK that Tauri already runs on, to reach its window for layer-shell and# the input region. libgtk-layer-shell itself is called directly (platform/linux.rs).gtk = "0.18"+# The Spotify pill talks MPRIS on the session bus (spotify.rs). libdbus, the+# version keyring already pulls in, so nothing new is downloaded.+dbus = "0.9.12"diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 3667b5e8..162099fd 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -25,6 +25,7 @@ mod secrets;mod session_window;mod settings;mod shortcuts;+mod spotify;mod tray;#[cfg(windows)]mod webview_drop;@@ -107,6 +108,7 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {island::apply_geometry(&app, &settings.screen, collapsed);}integrations::settings_saved(&app, &settings.active_integrations);+ spotify::sync(&app, &settings.active_integrations);if shortcuts_changed {shortcuts::apply(&app, &settings.shortcuts);}@@ -710,6 +712,10 @@ pub fn run() {desktop::desktop_mochi_fly_out,desktop::desktop_mochi_fly_home,desktop::desktop_mochi_set_asleep,+ spotify::spotify_refresh,+ spotify::spotify_control,+ spotify::spotify_open,+ spotify::spotify_installed,]).setup(move |app| {let handle = app.handle().clone();@@ -746,6 +752,7 @@ pub fn run() {hooks::ensure_hook_exe(&handle);pipe::start(handle.clone());integrations::start(handle.clone());+ spotify::sync(&handle, &loaded.active_integrations);shortcuts::apply(&handle, &loaded.shortcuts);Ok(())})diff --git a/windows/src-tauri/src/spotify.rs b/windows/src-tauri/src/spotify.rsnew file mode 100644index 00000000..ba25f362--- /dev/null+++ b/windows/src-tauri/src/spotify.rs@@ -0,0 +1,1503 @@+// The Spotify pill — port of SpotifyController.swift, Linux only.+//+// The Mac listens to Spotify's distributed notification and drives it over+// AppleScript. Linux has MPRIS instead: Spotify owns+// `org.mpris.MediaPlayer2.spotify` on the session bus, publishes its track,+// playback status, shuffle, loop status and volume as properties, and takes+// PlayPause, Next, Previous, SetPosition… as method calls.+//+// Nothing runs on a timer. While the pill is declared, one thread blocks on the+// bus and wakes only for Spotify's PropertiesChanged and Seeked signals and for+// the bus telling us Spotify started or quit (NameOwnerChanged). Position is+// not signalled, so it is read when the status or the track changes and when+// the card comes on screen; the page runs it on from a timestamp while playing,+// as the Mac's `position(at:)` does. Turning the pill off ends the thread.+//+// Windows has no music source yet: the commands answer "nothing playing".++// The pure parts below are only reached from the Linux client and the tests.+#![cfg_attr(not(target_os = "linux"), allow(dead_code))]++use serde::Serialize;+use tauri::AppHandle;++pub const PILL_ID: &str = "integration_spotify";+/// Where "Get Spotify" leads when it isn't installed.+pub const DOWNLOAD_URL: &str = "https://www.spotify.com/download/linux/";+/// Island events: the player's state, and a track's cover as a data URL.+const STATE_EVENT: &str = "spotify";+const ARTWORK_EVENT: &str = "spotify-artwork";+/// The biggest cover we read (Spotify's are 640 px JPEGs, ~100 KB).+const ARTWORK_LIMIT: usize = 3 * 1024 * 1024;++// ── Values ────────────────────────────────────────────────────────────────────++/// A D-Bus value as far as MPRIS needs it, so the parsing is plain Rust that+/// can be tested without a bus.+#[derive(Clone, Debug, PartialEq)]+pub enum Value {+ Str(String),+ Strs(Vec<String>),+ Int(i64),+ Float(f64),+ Bool(bool),+ Map(Vec<(String, Value)>),+ Other,+}++impl Value {+ fn str(&self) -> Option<&str> {+ match self {+ Value::Str(s) => Some(s),+ _ => None,+ }+ }++ fn int(&self) -> Option<i64> {+ match self {+ Value::Int(n) => Some(*n),+ Value::Float(f) => Some(*f as i64),+ _ => None,+ }+ }++ /// Text, or a list of texts joined (xesam:artist is a list).+ fn text(&self) -> String {+ match self {+ Value::Str(s) => s.clone(),+ Value::Strs(list) => list+ .iter()+ .map(|s| s.trim())+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join(", "),+ _ => String::new(),+ }+ }+}++fn find<'a>(map: &'a [(String, Value)], key: &str) -> Option<&'a Value> {+ map.iter().find(|(k, _)| k == key).map(|(_, v)| v)+}++// ── State ─────────────────────────────────────────────────────────────────────++/// The track Spotify has loaded (SpotifyTrack on macOS).+#[derive(Serialize, Clone, Debug, PartialEq, Default)]+#[serde(rename_all = "camelCase")]+pub struct Track {+ /// spotify:track:…, spotify:episode:…, spotify:ad:… — the Mac's ids.+ pub id: String,+ pub title: String,+ pub artist: String,+ pub album: String,+ /// Seconds.+ pub duration: f64,+ pub art_url: Option<String>,+ /// mpris:trackid as Spotify gave it, for SetPosition.+ #[serde(skip)]+ pub object_path: String,+}++/// What the island is told, whenever it changes.+#[derive(Serialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct PlayerState {+ /// Spotify owns its name on the bus.+ pub running: bool,+ /// A `spotify` (or the Flatpak / Snap) is there to launch.+ pub installed: bool,+ pub track: Option<Track>,+ pub playing: bool,+ /// Seconds at `position_at`; while playing, the real position runs on from there.+ pub position: f64,+ /// Unix milliseconds.+ pub position_at: f64,+ pub shuffle: bool,+ /// LoopStatus is not "None" (the Mac's `repeating`).+ pub repeat: bool,+ /// 0…100.+ pub volume: i32,+}++impl Default for PlayerState {+ fn default() -> Self {+ PlayerState {+ running: false,+ installed: false,+ track: None,+ playing: false,+ position: 0.0,+ position_at: 0.0,+ shuffle: false,+ repeat: false,+ volume: 50,+ }+ }+}++/// What a change touched, so the caller knows what to read next.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Applied {+ pub track_changed: bool,+ pub status_changed: bool,+ pub position_set: bool,+}++impl PlayerState {+ /// Where playback is at `now_ms`, extrapolated from the last anchor and+ /// capped at the track's end (SpotifyController.position(at:)).+ pub fn position_at_time(&self, now_ms: f64) -> f64 {+ let elapsed = if self.playing { ((now_ms - self.position_at) / 1000.0).max(0.0) } else { 0.0 };+ let p = self.position + elapsed;+ match &self.track {+ Some(t) if t.duration > 0.0 => p.min(t.duration),+ _ => p,+ }+ }++ fn anchor(&mut self, position: f64, now_ms: f64) {+ self.position = position.max(0.0);+ self.position_at = now_ms;+ }++ /// Spotify is gone, or the pill is off: nothing is playing.+ pub fn clear(&mut self, now_ms: f64) {+ self.track = None;+ self.playing = false;+ self.anchor(0.0, now_ms);+ }++ /// Applies Player properties (GetAll, or a PropertiesChanged). The+ /// metadata goes first and the position last, whatever order they came in.+ pub fn apply(&mut self, props: &[(String, Value)], now_ms: f64) -> Applied {+ let mut applied = Applied::default();+ let rank = |k: &str| match k {+ "Metadata" => 0,+ "PlaybackStatus" => 1,+ "Position" => 3,+ _ => 2,+ };+ let mut ordered: Vec<&(String, Value)> = props.iter().collect();+ ordered.sort_by_key(|(k, _)| rank(k));+ let mut stopped = false;+ for (key, value) in ordered {+ match key.as_str() {+ "Metadata" => {+ let track = match value {+ Value::Map(map) => parse_metadata(map),+ _ => None,+ };+ let same = match (&self.track, &track) {+ (Some(a), Some(b)) => a.id == b.id && a.object_path == b.object_path,+ (None, None) => true,+ _ => false,+ };+ if !same {+ applied.track_changed = true;+ self.anchor(0.0, now_ms);+ }+ self.track = track;+ }+ "PlaybackStatus" => {+ let Some(status) = value.str() else { continue };+ stopped = status == "Stopped";+ let playing = status == "Playing";+ if playing != self.playing {+ // Freeze or restart the clock where it is now.+ let at = self.position_at_time(now_ms);+ self.anchor(at, now_ms);+ self.playing = playing;+ applied.status_changed = true;+ }+ }+ "Shuffle" => {+ if let Value::Bool(on) = value {+ self.shuffle = *on;+ }+ }+ "LoopStatus" => {+ if let Some(s) = value.str() {+ self.repeat = s != "None";+ }+ }+ "Volume" => {+ if let Value::Float(v) = value {+ self.volume = (v * 100.0).round().clamp(0.0, 100.0) as i32;+ }+ }+ "Position" => {+ if let Some(us) = value.int() {+ self.anchor(us as f64 / 1_000_000.0, now_ms);+ applied.position_set = true;+ }+ }+ _ => {}+ }+ }+ if stopped && self.track.is_some() {+ self.clear(now_ms);+ applied.track_changed = true;+ }+ if self.track.is_none() {+ self.playing = false;+ }+ applied+ }+}++/// xesam / mpris metadata → the track, or None when nothing is loaded.+pub fn parse_metadata(map: &[(String, Value)]) -> Option<Track> {+ let object_path = find(map, "mpris:trackid").map(Value::text).unwrap_or_default();+ let title = find(map, "xesam:title").map(Value::text).unwrap_or_default();+ if object_path.is_empty() && title.is_empty() {+ return None;+ }+ // An unloaded player says /org/mpris/MediaPlayer2/TrackList/NoTrack.+ if object_path.ends_with("/NoTrack") {+ return None;+ }+ let duration = find(map, "mpris:length")+ .and_then(Value::int)+ .map(|us| us.max(0) as f64 / 1_000_000.0)+ .unwrap_or(0.0);+ let art_url = find(map, "mpris:artUrl").map(Value::text).filter(|s| !s.is_empty());+ let id = spotify_id(&object_path, find(map, "xesam:url").map(Value::text).as_deref());+ Some(Track {+ id,+ title: short_title(&title),+ artist: short_artist(&find(map, "xesam:artist").map(Value::text).unwrap_or_default()),+ album: find(map, "xesam:album").map(Value::text).unwrap_or_default(),+ duration,+ art_url,+ object_path,+ })+}++/// "/com/spotify/track/ID" → "spotify:track:ID", the id the Mac gets. Older+/// Spotify builds already gave "spotify:track:ID"; failing both, the page URL.+pub fn spotify_id(trackid: &str, url: Option<&str>) -> String {+ if trackid.starts_with("spotify:") {+ return trackid.to_string();+ }+ if let Some(rest) = trackid.strip_prefix("/com/spotify/") {+ let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();+ if parts.len() >= 2 {+ return format!("spotify:{}:{}", parts[0], parts[1..].join(":"));+ }+ }+ if let Some(rest) = url.and_then(|u| u.strip_prefix("https://open.spotify.com/")) {+ let parts: Vec<&str> = rest.split(['/', '?']).collect();+ if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {+ return format!("spotify:{}:{}", parts[0], parts[1]);+ }+ }+ trackid.to_string()+}++/// "Song - Remastered 2011 (Live) [Mono]" → "Song" (SpotifyController.shortTitle).+pub fn short_title(raw: &str) -> String {+ if raw.is_empty() {+ return String::new();+ }+ let mut s: &str = raw;+ if let Some(i) = s.find(" - ") {+ s = &s[..i];+ }+ loop {+ let t = s.trim();+ let Some(last) = t.chars().last() else { break };+ if last != ')' && last != ']' {+ break;+ }+ let open = if last == ')' { '(' } else { '[' };+ let Some(idx) = t.rfind(open) else { break };+ let candidate = t[..idx].trim();+ if candidate.is_empty() {+ break;+ }+ s = candidate;+ }+ let result = s.trim();+ if result.is_empty() { raw.to_string() } else { result.to_string() }+}++/// "Artist feat. Someone" → "Artist" (SpotifyController.shortArtist).+pub fn short_artist(raw: &str) -> String {+ if raw.is_empty() {+ return String::new();+ }+ let lower = raw.to_lowercase();+ for tag in [" feat.", " ft."] {+ if let Some(i) = lower.find(tag) {+ // Lowercasing can move byte offsets; only cut where it lines up.+ if lower.len() == raw.len() && raw.is_char_boundary(i) {+ let result = raw[..i].trim();+ return if result.is_empty() { raw.to_string() } else { result.to_string() };+ }+ }+ }+ raw.to_string()+}++// ── Artwork ───────────────────────────────────────────────────────────────────++/// Where a cover may be read from. The URL comes from another program: only+/// Spotify's own image CDN, or a local file (a local track's cover).+#[derive(Debug, PartialEq)]+pub enum ArtSource {+ Https(String),+ File(std::path::PathBuf),+}++pub fn artwork_source(raw: &str) -> Option<ArtSource> {+ // Some Spotify builds point at open.spotify.com/image/ID, which only+ // redirects to the CDN.+ let raw = match raw.strip_prefix("https://open.spotify.com/image/") {+ Some(id) => format!("https://i.scdn.co/image/{id}"),+ None => raw.to_string(),+ };+ let url = reqwest::Url::parse(&raw).ok()?;+ match url.scheme() {+ "https" => {+ let host = url.host_str()?.to_ascii_lowercase();+ let ours = host == "i.scdn.co" || host.ends_with(".scdn.co") || host.ends_with(".spotifycdn.com");+ (ours && url.port().is_none() && url.username().is_empty()).then(|| ArtSource::Https(url.to_string()))+ }+ "file" => {+ if url.host_str().is_some_and(|h| !h.is_empty() && h != "localhost") {+ return None;+ }+ let path = url.to_file_path().ok()?;+ path.is_absolute().then_some(ArtSource::File(path))+ }+ _ => None,+ }+}++/// The image type, from its first bytes — never from what the file claims.+pub fn sniff_image(bytes: &[u8]) -> Option<&'static str> {+ if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {+ Some("image/jpeg")+ } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {+ Some("image/png")+ } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {+ Some("image/webp")+ } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {+ Some("image/gif")+ } else {+ None+ }+}++fn data_url(bytes: &[u8]) -> Option<String> {+ let mime = sniff_image(bytes)?;+ Some(format!("data:{mime};base64,{}", crate::claude::base64_for(bytes)))+}++#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]+struct Artwork {+ art_url: String,+ data_url: String,+}++fn now_ms() -> f64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs_f64() * 1000.0)+ .unwrap_or(0.0)+}++fn emit_state(app: &AppHandle, state: &PlayerState) {+ use tauri::Emitter;+ let _ = app.emit_to(crate::island::WINDOW_LABEL, STATE_EVENT, state);+}++// ── Commands ──────────────────────────────────────────────────────────────────++/// The player as it is now, read again from Spotify (the card coming on+/// screen: seeks made in Spotify's own window are never signalled).+#[tauri::command]+pub async fn spotify_refresh(app: AppHandle) -> Option<PlayerState> {+ #[cfg(target_os = "linux")]+ {+ tauri::async_runtime::spawn_blocking(move || linux::refresh(&linux::Out::App(app))).await.ok().flatten()+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = app;+ None+ }+}++/// A control from the card or the pill: `playPause`, `next`, `previous`,+/// `seek` (seconds), `shuffle` / `repeat` (1 on, 0 off), `volume` (0…100).+#[tauri::command]+pub async fn spotify_control(app: AppHandle, action: String, value: Option<f64>) -> bool {+ #[cfg(target_os = "linux")]+ {+ tauri::async_runtime::spawn_blocking(move || linux::control(&linux::Out::App(app), &action, value)).await.unwrap_or(false)+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = (app, action, value);+ false+ }+}++/// "Open Spotify": brings it forward, or starts it. Without Spotify, its+/// download page. True when Spotify was reached or started.+#[tauri::command]+pub async fn spotify_open() -> bool {+ #[cfg(target_os = "linux")]+ {+ tauri::async_runtime::spawn_blocking(linux::open).await.unwrap_or(false)+ }+ #[cfg(not(target_os = "linux"))]+ {+ false+ }+}++/// For Settings: whether there is a Spotify to launch.+#[tauri::command]+pub fn spotify_installed() -> bool {+ #[cfg(target_os = "linux")]+ {+ linux::installed()+ }+ #[cfg(not(target_os = "linux"))]+ {+ false+ }+}++/// Starts the listener when the pill is declared, stops it when it is not.+/// Called at launch and after every settings save.+pub fn sync(app: &AppHandle, active_integrations: &[String]) {+ #[cfg(target_os = "linux")]+ linux::sync(app, active_integrations.iter().any(|id| id == PILL_ID));+ #[cfg(not(target_os = "linux"))]+ let _ = (app, active_integrations);+}++// ── Linux: MPRIS over D-Bus ───────────────────────────────────────────────────++#[cfg(target_os = "linux")]+mod linux {+ use super::*;+ use std::collections::VecDeque;+ use std::path::PathBuf;+ use std::process::{Command, Stdio};+ use std::sync::{LazyLock, Mutex};+ use std::time::Duration;++ use dbus::arg::{ArgType, PropMap, RefArg};+ use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;+ use dbus::blocking::Connection;+ use dbus::message::MessageType;+ use dbus::Message;+ use tauri::Emitter;++ const BUS: &str = "org.mpris.MediaPlayer2.spotify";+ const PATH: &str = "/org/mpris/MediaPlayer2";+ const ROOT: &str = "org.mpris.MediaPlayer2";+ const PLAYER: &str = "org.mpris.MediaPlayer2.Player";+ const PROPERTIES: &str = "org.freedesktop.DBus.Properties";+ const DBUS: &str = "org.freedesktop.DBus";+ /// A call to Spotify never holds anything up for longer.+ const CALL: Duration = Duration::from_millis(1500);+ /// The listener sleeps on the bus; this only bounds a lost wake-up.+ const IDLE_WAIT: Duration = Duration::from_secs(3600);+ const FLATPAK_ID: &str = "com.spotify.Client";++ const RULES: [&str; 3] = [+ "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.mpris.MediaPlayer2.spotify'",+ "type='signal',sender='org.mpris.MediaPlayer2.spotify',path='/org/mpris/MediaPlayer2',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'",+ "type='signal',sender='org.mpris.MediaPlayer2.spotify',path='/org/mpris/MediaPlayer2',interface='org.mpris.MediaPlayer2.Player',member='Seeked'",+ ];++ struct Shared {+ /// Bumped on every start and stop: a listener from an older one quits.+ generation: u64,+ active: bool,+ /// The listener's unique name, to wake it when it has to stop.+ listener: Option<String>,+ /// Spotify's unique name while it runs: signals from anyone else are ignored.+ owner: Option<String>,+ state: PlayerState,+ }++ static SHARED: LazyLock<Mutex<Shared>> = LazyLock::new(|| {+ Mutex::new(Shared { generation: 0, active: false, listener: None, owner: None, state: PlayerState::default() })+ });++ /// The connection the controls and reads go through, made on first use.+ static CONTROL: LazyLock<Mutex<Option<Connection>>> = LazyLock::new(|| Mutex::new(None));++ struct ArtCache {+ entries: VecDeque<(String, String)>,+ loading: Option<String>,+ }++ static ART: LazyLock<Mutex<ArtCache>> =+ LazyLock::new(|| Mutex::new(ArtCache { entries: VecDeque::new(), loading: None }));++ /// Where the listener's news goes: the island, or a test.+ #[derive(Clone)]+ pub enum Out {+ App(AppHandle),+ #[cfg(test)]+ Test(std::sync::mpsc::Sender<PlayerState>),+ }++ impl Out {+ fn state(&self, state: &PlayerState) {+ match self {+ Out::App(app) => {+ emit_state(app, state);+ want_artwork(app, state);+ }+ #[cfg(test)]+ Out::Test(tx) => {+ let _ = tx.send(state.clone());+ }+ }+ }+ }++ // ── Values from the bus ───────────────────────────────────────────────────++ /// A D-Bus argument as a plain Value (variants unwrapped).+ pub fn value_of(arg: &dyn RefArg) -> Value {+ match arg.arg_type() {+ ArgType::Variant => arg.as_iter().and_then(|mut it| it.next().map(value_of)).unwrap_or(Value::Other),+ ArgType::String | ArgType::ObjectPath | ArgType::Signature => {+ arg.as_str().map(|s| Value::Str(s.to_string())).unwrap_or(Value::Other)+ }+ ArgType::Boolean => arg.as_i64().map(|n| Value::Bool(n != 0)).unwrap_or(Value::Other),+ ArgType::Double => arg.as_f64().map(Value::Float).unwrap_or(Value::Other),+ ArgType::UInt64 => arg.as_u64().map(|n| Value::Int(n.min(i64::MAX as u64) as i64)).unwrap_or(Value::Other),+ ArgType::Byte | ArgType::Int16 | ArgType::UInt16 | ArgType::Int32 | ArgType::UInt32 | ArgType::Int64 => {+ arg.as_i64().map(Value::Int).unwrap_or(Value::Other)+ }+ ArgType::Array => {+ let Some(items) = arg.as_iter() else { return Value::Other };+ if arg.signature().starts_with("a{") {+ let mut map = Vec::new();+ let mut items = items;+ while let (Some(k), Some(v)) = (items.next(), items.next()) {+ if let Some(key) = k.as_str() {+ map.push((key.to_string(), value_of(v)));+ }+ }+ Value::Map(map)+ } else {+ Value::Strs(+ items+ .filter_map(|v| match value_of(v) {+ Value::Str(s) => Some(s),+ _ => None,+ })+ .collect(),+ )+ }+ }+ _ => Value::Other,+ }+ }++ pub fn props_of(map: &PropMap) -> Vec<(String, Value)> {+ map.iter().map(|(k, v)| (k.clone(), value_of(&v.0))).collect()+ }++ // ── Start / stop ──────────────────────────────────────────────────────────++ pub fn sync(app: &AppHandle, on: bool) {+ set_active(Out::App(app.clone()), on);+ }++ pub fn set_active(out: Out, on: bool) {+ let wake = {+ let mut s = SHARED.lock().unwrap();+ if s.active == on {+ return;+ }+ s.active = on;+ s.generation += 1;+ s.owner = None;+ s.state = PlayerState { installed: installed(), ..PlayerState::default() };+ s.listener.take()+ };+ if on {+ let generation = SHARED.lock().unwrap().generation;+ let spawned = std::thread::Builder::new()+ .name("coucou-spotify".into())+ .spawn(move || listen(out, generation));+ if let Err(err) = spawned {+ crate::log::line(format!("spotify: no listener thread: {err}"));+ }+ } else {+ if let Some(name) = wake {+ wake_listener(&name);+ }+ let state = SHARED.lock().unwrap().state.clone();+ out.state(&state);+ }+ }++ fn current(generation: u64) -> bool {+ let s = SHARED.lock().unwrap();+ s.active && s.generation == generation+ }++ /// Any message to its unique name gets the listener off the bus.+ fn wake_listener(name: &str) {+ let Ok(msg) = Message::new_method_call(name, "/", "org.freedesktop.DBus.Peer", "Ping") else { return };+ let mut msg = msg;+ msg.set_no_reply(true);+ with_control(|c| {+ let _ = c.channel().send(msg);+ c.channel().flush();+ Ok(())+ });+ }++ /// Listener threads alive (tests: turning the pill off really ends one).+ #[cfg(test)]+ static ALIVE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++ fn listen(out: Out, generation: u64) {+ #[cfg(test)]+ ALIVE.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ listen_on_bus(out, generation);+ #[cfg(test)]+ ALIVE.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ }++ fn listen_on_bus(out: Out, generation: u64) {+ let conn = match Connection::new_session() {+ Ok(c) => c,+ Err(err) => {+ crate::log::line(format!("spotify: no session bus: {err}"));+ return;+ }+ };+ {+ let mut s = SHARED.lock().unwrap();+ if !(s.active && s.generation == generation) {+ return;+ }+ s.listener = Some(conn.unique_name().to_string());+ }+ for rule in RULES {+ if let Err(err) = conn.add_match_no_cb(rule) {+ crate::log::line(format!("spotify: match refused: {err}"));+ }+ }+ // Spotify may have started before the pill was declared.+ read_everything(&conn, &out, generation);++ while current(generation) {+ match conn.channel().blocking_pop_message(IDLE_WAIT) {+ Ok(Some(msg)) => handle(&conn, &out, generation, &msg),+ Ok(None) => {}+ Err(err) => {+ crate::log::line(format!("spotify: bus lost: {err}"));+ break;+ }+ }+ }+ }++ fn handle(conn: &Connection, out: &Out, generation: u64, msg: &Message) {+ if msg.msg_type() != MessageType::Signal || !current(generation) {+ return;+ }+ let interface = msg.interface().map(|i| i.to_string()).unwrap_or_default();+ let member = msg.member().map(|m| m.to_string()).unwrap_or_default();+ let sender = msg.sender().map(|s| s.to_string());++ match (interface.as_str(), member.as_str()) {+ (DBUS, "NameOwnerChanged") => {+ let Ok((name, _old, new)) = msg.read3::<String, String, String>() else { return };+ if name != BUS {+ return;+ }+ if new.is_empty() {+ // Spotify quit: nothing is playing anymore.+ let state = {+ let mut s = SHARED.lock().unwrap();+ s.owner = None;+ s.state.running = false;+ s.state.clear(now_ms());+ s.state.clone()+ };+ out.state(&state);+ } else {+ read_everything(conn, out, generation);+ }+ }+ (PROPERTIES, "PropertiesChanged") => {+ if !from_owner(sender.as_deref()) {+ return;+ }+ let Ok((iface, changed, invalidated)) = msg.read3::<String, PropMap, Vec<String>>() else { return };+ if iface != PLAYER {+ return;+ }+ let mut props = props_of(&changed);+ // Properties that changed without their value: read them.+ for name in invalidated {+ if let Some(v) = get_property(conn, &name) {+ props.push((name, v));+ }+ }+ apply_and_emit(conn, out, &props);+ }+ (PLAYER, "Seeked") => {+ if !from_owner(sender.as_deref()) {+ return;+ }+ let Ok(us) = msg.read1::<i64>() else { return };+ apply_and_emit(conn, out, &[("Position".into(), Value::Int(us))]);+ }+ _ => {}+ }+ }++ fn from_owner(sender: Option<&str>) -> bool {+ let s = SHARED.lock().unwrap();+ match (&s.owner, sender) {+ (Some(owner), Some(sender)) => owner == sender,+ // The owner isn't known yet: the bus only routes Spotify's to us.+ (None, _) => true,+ _ => false,+ }+ }++ /// Applies a change; when the status or the track moved, reads the+ /// position (never signalled), then tells the island.+ fn apply_and_emit(conn: &Connection, out: &Out, props: &[(String, Value)]) {+ let applied = SHARED.lock().unwrap().state.apply(props, now_ms());+ if (applied.status_changed || applied.track_changed) && !applied.position_set {+ if let Some(position) = get_property(conn, "Position") {+ SHARED.lock().unwrap().state.apply(&[("Position".into(), position)], now_ms());+ }+ }+ let state = SHARED.lock().unwrap().state.clone();+ out.state(&state);+ }++ fn get_property(conn: &Connection, name: &str) -> Option<Value> {+ let proxy = conn.with_proxy(BUS, PATH, CALL);+ let v: Box<dyn RefArg> = proxy.get(PLAYER, name).ok()?;+ Some(value_of(&v))+ }++ fn name_owner(conn: &Connection) -> Option<String> {+ let proxy = conn.with_proxy(DBUS, "/org/freedesktop/DBus", CALL);+ let (owner,): (String,) = proxy.method_call(DBUS, "GetNameOwner", (BUS,)).ok()?;+ Some(owner)+ }++ /// Whom Spotify is, and all of its Player properties.+ fn read_everything(conn: &Connection, out: &Out, generation: u64) {+ let owner = name_owner(conn);+ let props = owner.as_ref().and_then(|_| {+ let proxy = conn.with_proxy(BUS, PATH, CALL);+ proxy.get_all(PLAYER).ok().map(|m| props_of(&m))+ });+ let state = {+ let mut s = SHARED.lock().unwrap();+ if !(s.active && s.generation == generation) {+ return;+ }+ s.owner = owner.clone();+ s.state.running = owner.is_some();+ s.state.installed = owner.is_some() || installed();+ let now = now_ms();+ match props {+ Some(props) => {+ s.state.apply(&props, now);+ }+ None => s.state.clear(now),+ }+ s.state.clone()+ };+ out.state(&state);+ }++ /// Runs `f` on the control connection, made (again) when needed.+ fn with_control<R>(f: impl FnOnce(&Connection) -> Result<R, dbus::Error>) -> Option<R> {+ let mut slot = CONTROL.lock().unwrap();+ if slot.as_ref().is_none_or(|c| !c.channel().is_connected()) {+ *slot = Connection::new_session().ok();+ }+ let conn = slot.as_ref()?;+ f(conn).ok()+ }++ pub fn refresh(out: &Out) -> Option<PlayerState> {+ let generation = {+ let s = SHARED.lock().unwrap();+ if !s.active {+ return None;+ }+ s.generation+ };+ let read = with_control(|c| {+ let owner = name_owner(c);+ let props = match owner {+ Some(_) => Some(props_of(&c.with_proxy(BUS, PATH, CALL).get_all(PLAYER)?)),+ None => None,+ };+ Ok((owner, props))+ });+ let state = {+ let mut s = SHARED.lock().unwrap();+ if !(s.active && s.generation == generation) {+ return None;+ }+ if let Some((owner, props)) = read {+ s.owner = owner.clone();+ s.state.running = owner.is_some();+ s.state.installed = owner.is_some() || installed();+ let now = now_ms();+ match props {+ Some(props) => {+ s.state.apply(&props, now);+ }+ None => s.state.clear(now),+ }+ }+ s.state.clone()+ };+ out.state(&state);+ Some(state)+ }++ pub fn control(out: &Out, action: &str, value: Option<f64>) -> bool {+ let (active, state) = {+ let s = SHARED.lock().unwrap();+ (s.active && s.owner.is_some(), s.state.clone())+ };+ if !active {+ return false;+ }+ let v = value.unwrap_or(0.0);+ let now = now_ms();+ let done = with_control(|c| {+ let p = c.with_proxy(BUS, PATH, CALL);+ match action {+ "playPause" => p.method_call(PLAYER, "PlayPause", ()),+ "next" => p.method_call(PLAYER, "Next", ()),+ "previous" => p.method_call(PLAYER, "Previous", ()),+ "seek" => {+ let Some(track) = state.track.as_ref() else { return Err(dbus::Error::new_failed("no track")) };+ let target = v.clamp(0.0, (track.duration - 1.0).max(0.0));+ let target_us = (target * 1_000_000.0) as i64;+ match dbus::Path::new(track.object_path.clone()) {+ Ok(path) => p.method_call(PLAYER, "SetPosition", (path, target_us)),+ // Not an object path (old Spotify builds): seek by the difference.+ Err(_) => {+ let from = (state.position_at_time(now) * 1_000_000.0) as i64;+ p.method_call(PLAYER, "Seek", (target_us - from,))+ }+ }+ }+ "shuffle" => p.set(PLAYER, "Shuffle", v != 0.0),+ "repeat" => p.set(PLAYER, "LoopStatus", if v != 0.0 { "Playlist" } else { "None" }),+ "volume" => p.set(PLAYER, "Volume", (v / 100.0).clamp(0.0, 1.0)),+ _ => Err(dbus::Error::new_failed("unknown action")),+ }+ })+ .is_some();+ if !done {+ return false;+ }+ // Spotify doesn't always signal these: show them at once, as the Mac does.+ let optimistic: Option<(String, Value)> = match action {+ "seek" => state.track.as_ref().map(|t| {+ let target = v.clamp(0.0, (t.duration - 1.0).max(0.0));+ ("Position".into(), Value::Int((target * 1_000_000.0) as i64))+ }),+ "shuffle" => Some(("Shuffle".into(), Value::Bool(v != 0.0))),+ "repeat" => Some(("LoopStatus".into(), Value::Str(if v != 0.0 { "Playlist" } else { "None" }.into()))),+ "volume" => Some(("Volume".into(), Value::Float((v / 100.0).clamp(0.0, 1.0)))),+ _ => None,+ };+ if let Some(prop) = optimistic {+ let state = {+ let mut s = SHARED.lock().unwrap();+ s.state.apply(&[prop], now_ms());+ s.state.clone()+ };+ out.state(&state);+ }+ true+ }++ // ── Launching ─────────────────────────────────────────────────────────────++ /// How to start Spotify: the `spotify` on PATH, else the Flatpak, else the Snap.+ fn launcher() -> Option<Vec<std::ffi::OsString>> {+ if let Some(bin) = crate::platform::find_on_path("spotify") {+ return Some(vec![bin.into()]);+ }+ let home = crate::platform::home_dir();+ let flatpak = [+ PathBuf::from("/var/lib/flatpak/app").join(FLATPAK_ID),+ home.join(".local/share/flatpak/app").join(FLATPAK_ID),+ ];+ if flatpak.iter().any(|p| p.is_dir()) {+ if let Some(bin) = crate::platform::find_on_path("flatpak") {+ return Some(vec![bin.into(), "run".into(), FLATPAK_ID.into()]);+ }+ }+ let snap = PathBuf::from("/snap/bin/spotify");+ if snap.is_file() {+ return Some(vec![snap.into()]);+ }+ None+ }++ pub fn installed() -> bool {+ launcher().is_some()+ }++ pub fn open() -> bool {+ // Running: bring it forward when it says it can.+ let raised = with_control(|c| {+ if name_owner(c).is_none() {+ return Ok(false);+ }+ let p = c.with_proxy(BUS, PATH, CALL);+ let can: bool = p.get(ROOT, "CanRaise").unwrap_or(false);+ if can {+ p.method_call::<(), _, _, _>(ROOT, "Raise", ())?;+ }+ Ok(can)+ })+ .unwrap_or(false);+ if raised {+ return true;+ }+ // Otherwise start it; a second `spotify` brings the running one forward.+ if let Some(argv) = launcher() {+ use std::os::unix::process::CommandExt;+ let mut cmd = Command::new(&argv[0]);+ cmd.args(&argv[1..])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .process_group(0);+ match cmd.spawn() {+ Ok(mut child) => {+ // Reaped when it exits, so it never lingers as a zombie.+ let _ = std::thread::Builder::new()+ .name("coucou-spotify-child".into())+ .spawn(move || {+ let _ = child.wait();+ });+ return true;+ }+ Err(err) => crate::log::line(format!("spotify: could not start it: {err}")),+ }+ }+ crate::platform::open_url(DOWNLOAD_URL);+ false+ }++ // ── Artwork ───────────────────────────────────────────────────────────────++ /// The current track's cover, as a data URL: the page may not load a remote+ /// image (CSP), and only Spotify's CDN or a local file is read.+ fn want_artwork(app: &AppHandle, state: &PlayerState) {+ let Some(url) = state.track.as_ref().and_then(|t| t.art_url.clone()) else { return };+ {+ let mut art = ART.lock().unwrap();+ if let Some((_, data)) = art.entries.iter().find(|(u, _)| *u == url) {+ let _ = app.emit_to(+ crate::island::WINDOW_LABEL,+ ARTWORK_EVENT,+ Artwork { art_url: url.clone(), data_url: data.clone() },+ );+ return;+ }+ if art.loading.as_deref() == Some(url.as_str()) {+ return;+ }+ art.loading = Some(url.clone());+ }+ let app = app.clone();+ match artwork_source(&url) {+ Some(ArtSource::Https(remote)) => {+ // Pause means nothing reaches the network.+ if crate::integrations::PAUSED.load(std::sync::atomic::Ordering::Relaxed) {+ ART.lock().unwrap().loading = None;+ return;+ }+ tauri::async_runtime::spawn(async move {+ let bytes = fetch(&remote).await;+ finish_artwork(&app, url, bytes);+ });+ }+ Some(ArtSource::File(path)) => {+ tauri::async_runtime::spawn_blocking(move || {+ let bytes = std::fs::metadata(&path)+ .ok()+ .filter(|m| m.is_file() && m.len() as usize <= ARTWORK_LIMIT)+ .and_then(|_| std::fs::read(&path).ok());+ finish_artwork(&app, url, bytes);+ });+ }+ None => {+ ART.lock().unwrap().loading = None;+ }+ }+ }++ async fn fetch(url: &str) -> Option<Vec<u8>> {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(10))+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .ok()?;+ let response = client.get(url).send().await.ok()?;+ if !response.status().is_success() {+ return None;+ }+ crate::net::read_capped(response, ARTWORK_LIMIT).await.ok()+ }++ fn finish_artwork(app: &AppHandle, url: String, bytes: Option<Vec<u8>>) {+ let data = bytes.as_deref().and_then(data_url);+ let mut art = ART.lock().unwrap();+ if art.loading.as_deref() == Some(url.as_str()) {+ art.loading = None;+ }+ let Some(data) = data else { return };+ art.entries.retain(|(u, _)| *u != url);+ art.entries.push_back((url.clone(), data.clone()));+ while art.entries.len() > 12 {+ art.entries.pop_front();+ }+ drop(art);+ // Only if it is still the track on screen.+ let current = SHARED.lock().unwrap().state.track.as_ref().and_then(|t| t.art_url.clone());+ if current.as_deref() == Some(url.as_str()) {+ let _ = app.emit_to(crate::island::WINDOW_LABEL, ARTWORK_EVENT, Artwork { art_url: url, data_url: data });+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;+ use dbus::arg::Variant;+ use std::collections::HashMap;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;++ fn var<T: RefArg + 'static>(v: T) -> Variant<Box<dyn RefArg>> {+ Variant(Box::new(v))+ }++ #[test]+ fn dbus_variants_become_plain_values() {+ assert_eq!(value_of(&var("Playing".to_string())), Value::Str("Playing".into()));+ assert_eq!(value_of(&var(true)), Value::Bool(true));+ assert_eq!(value_of(&var(0.5f64)), Value::Float(0.5));+ assert_eq!(value_of(&var(42u64)), Value::Int(42));+ assert_eq!(value_of(&var(-7i64)), Value::Int(-7));+ assert_eq!(value_of(&var(3i32)), Value::Int(3));+ assert_eq!(+ value_of(&var(dbus::Path::new("/com/spotify/track/abc").unwrap())),+ Value::Str("/com/spotify/track/abc".into())+ );+ assert_eq!(+ value_of(&var(vec!["A".to_string(), "B".to_string()])),+ Value::Strs(vec!["A".into(), "B".into()])+ );+ }++ #[test]+ fn spotify_metadata_from_the_bus_parses_into_a_track() {+ // What Spotify 1.2 sends, types included.+ let mut meta: PropMap = HashMap::new();+ meta.insert("mpris:trackid".into(), var(dbus::Path::new("/com/spotify/track/4uLU6hMCjMI75M1A2tKUQC").unwrap()));+ meta.insert("mpris:length".into(), var(213_000_000u64));+ meta.insert("mpris:artUrl".into(), var("https://i.scdn.co/image/ab67616d0000b273abc".to_string()));+ meta.insert("xesam:title".into(), var("Never Gonna Give You Up - Remastered 2022".to_string()));+ meta.insert("xesam:artist".into(), var(vec!["Rick Astley".to_string()]));+ meta.insert("xesam:album".into(), var("Whenever You Need Somebody".to_string()));+ meta.insert("xesam:url".into(), var("https://open.spotify.com/track/4uLU6hMCjMI75M1A2tKUQC".to_string()));+ let mut props: PropMap = HashMap::new();+ props.insert("Metadata".into(), var(meta));+ props.insert("PlaybackStatus".into(), var("Playing".to_string()));+ props.insert("Shuffle".into(), var(true));+ props.insert("LoopStatus".into(), var("Track".to_string()));+ props.insert("Volume".into(), var(0.42f64));+ props.insert("Position".into(), var(12_500_000i64));++ let mut state = PlayerState::default();+ let applied = state.apply(&props_of(&props), 1_000.0);+ assert!(applied.track_changed && applied.status_changed && applied.position_set);+ let track = state.track.clone().unwrap();+ assert_eq!(track.id, "spotify:track:4uLU6hMCjMI75M1A2tKUQC");+ assert_eq!(track.title, "Never Gonna Give You Up");+ assert_eq!(track.artist, "Rick Astley");+ assert_eq!(track.album, "Whenever You Need Somebody");+ assert_eq!(track.duration, 213.0);+ assert_eq!(track.art_url.as_deref(), Some("https://i.scdn.co/image/ab67616d0000b273abc"));+ assert_eq!(track.object_path, "/com/spotify/track/4uLU6hMCjMI75M1A2tKUQC");+ assert!(state.playing && state.shuffle && state.repeat);+ assert_eq!(state.volume, 42);+ assert_eq!(state.position, 12.5);+ assert_eq!(state.position_at, 1_000.0);+ }++ /// End to end against a fake Spotify on a private session bus:+ /// `dbus-run-session -- cargo test -p coucou --lib spotify -- --ignored`+ #[test]+ #[ignore]+ fn the_listener_follows_and_drives_a_fake_spotify_over_the_session_bus() {+ let calls = Arc::new(Mutex::new(Vec::<String>::new()));+ let stop = Arc::new(AtomicBool::new(false));+ let service = {+ let calls = calls.clone();+ let stop = stop.clone();+ std::thread::spawn(move || fake_spotify(calls, stop))+ };+ std::thread::sleep(Duration::from_millis(300));++ let (tx, rx) = std::sync::mpsc::channel();+ let out = Out::Test(tx);+ let next = || rx.recv_timeout(Duration::from_secs(3)).expect("a state from the listener");++ // Declared: the listener reads what is already playing.+ set_active(out.clone(), true);+ let state = next();+ assert!(state.running);+ let track = state.track.clone().unwrap();+ assert_eq!(track.id, "spotify:track:fake1");+ assert_eq!(track.title, "Fake Song");+ assert_eq!(track.artist, "Fake Artist, Guest");+ assert_eq!(track.duration, 180.0);+ assert!(state.playing);+ assert_eq!(state.volume, 80);+ assert_eq!(state.position, 30.0);++ // A control goes out; Spotify's PropertiesChanged comes back, and+ // the position is read again because the status moved.+ assert!(control(&out, "playPause", None));+ let state = next();+ assert!(!state.playing);+ assert_eq!(state.position, 31.0);++ assert!(control(&out, "seek", Some(60.0)));+ assert_eq!(next().position, 60.0);+ assert!(control(&out, "shuffle", Some(1.0)));+ assert!(next().shuffle);+ assert!(control(&out, "volume", Some(25.0)));+ assert_eq!(next().volume, 25);+ assert!(!control(&out, "dance", None));+ assert_eq!(+ *calls.lock().unwrap(),+ vec!["PlayPause", "SetPosition /com/spotify/track/fake1 60000000", "Set Shuffle", "Set Volume"]+ );++ // Spotify quits: nothing plays any more.+ stop.store(true, Ordering::Relaxed);+ let _ = service.join();+ let state = next();+ assert!(!state.running);+ assert_eq!(state.track, None);+ assert!(!control(&out, "next", None));++ // Undeclared: the thread leaves the bus at once.+ set_active(out.clone(), false);+ let _ = next();+ let deadline = std::time::Instant::now() + Duration::from_secs(3);+ while ALIVE.load(Ordering::SeqCst) > 0 && std::time::Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(20));+ }+ assert_eq!(ALIVE.load(Ordering::SeqCst), 0);+ assert_eq!(refresh(&out), None);+ }++ /// A minimal MPRIS player: GetAll, Get, Set and the Player methods,+ /// signalling its status like Spotify. Releases its name when told to stop.+ fn fake_spotify(calls: Arc<Mutex<Vec<String>>>, stop: Arc<AtomicBool>) {+ let conn = Connection::new_session().unwrap();+ conn.request_name(BUS, false, true, true).unwrap();+ let mut playing = true;+ let mut position: i64 = 30_000_000;+ let player = |playing: bool, position: i64| {+ let mut meta: PropMap = HashMap::new();+ meta.insert("mpris:trackid".into(), var(dbus::Path::new("/com/spotify/track/fake1").unwrap()));+ meta.insert("mpris:length".into(), var(180_000_000u64));+ meta.insert("xesam:title".into(), var("Fake Song (Live)".to_string()));+ meta.insert("xesam:artist".into(), var(vec!["Fake Artist".to_string(), "Guest".to_string()]));+ meta.insert("xesam:album".into(), var("Fake Album".to_string()));+ let mut props: PropMap = HashMap::new();+ props.insert("Metadata".into(), var(meta));+ props.insert("PlaybackStatus".into(), var(if playing { "Playing" } else { "Paused" }.to_string()));+ props.insert("Volume".into(), var(0.8f64));+ props.insert("Position".into(), var(position));+ props+ };+ while !stop.load(Ordering::Relaxed) {+ let Ok(Some(msg)) = conn.channel().blocking_pop_message(Duration::from_millis(50)) else { continue };+ if msg.msg_type() != MessageType::MethodCall {+ continue;+ }+ let member = msg.member().map(|m| m.to_string()).unwrap_or_default();+ let mut signal = None;+ let reply = match member.as_str() {+ "GetAll" => msg.method_return().append1(player(playing, position)),+ "Get" => {+ let (_, name): (String, String) = msg.read2().unwrap();+ let props = player(playing, position);+ match props.get(&name) {+ Some(v) => msg.method_return().append1(var(value_box(&v.0))),+ None => Message::error(+ &msg,+ &"org.freedesktop.DBus.Error.UnknownProperty".into(),+ &std::ffi::CString::new("no").unwrap(),+ ),+ }+ }+ "Set" => {+ let (_, name): (String, String) = msg.read2().unwrap();+ calls.lock().unwrap().push(format!("Set {name}"));+ msg.method_return()+ }+ "SetPosition" => {+ let (path, us): (dbus::Path, i64) = msg.read2().unwrap();+ calls.lock().unwrap().push(format!("SetPosition {path} {us}"));+ position = us;+ msg.method_return()+ }+ "PlayPause" => {+ calls.lock().unwrap().push("PlayPause".into());+ playing = !playing;+ position += 1_000_000;+ let mut changed: PropMap = HashMap::new();+ changed.insert(+ "PlaybackStatus".into(),+ var(if playing { "Playing" } else { "Paused" }.to_string()),+ );+ signal = Some(+ Message::new_signal(PATH, PROPERTIES, "PropertiesChanged")+ .unwrap()+ .append3(PLAYER, changed, Vec::<String>::new()),+ );+ msg.method_return()+ }+ other => {+ calls.lock().unwrap().push(other.to_string());+ msg.method_return()+ }+ };+ let _ = conn.channel().send(reply);+ if let Some(signal) = signal {+ let _ = conn.channel().send(signal);+ }+ }+ let _ = conn.release_name(BUS);+ conn.channel().flush();+ }++ fn value_box(v: &Box<dyn RefArg>) -> Box<dyn RefArg> {+ v.box_clone()+ }+ }+}++// ── Tests (the pure parts) ────────────────────────────────────────────────────++#[cfg(test)]+mod tests {+ use super::*;++ fn s(v: &str) -> Value {+ Value::Str(v.into())+ }++ fn metadata(trackid: &str, title: &str) -> Value {+ Value::Map(vec![+ ("mpris:trackid".into(), s(trackid)),+ ("xesam:title".into(), s(title)),+ ("xesam:artist".into(), Value::Strs(vec!["Daft Punk".into(), "Pharrell Williams".into()])),+ ("xesam:album".into(), s("Random Access Memories")),+ ("mpris:length".into(), Value::Int(369_000_000)),+ ("mpris:artUrl".into(), s("https://i.scdn.co/image/abc")),+ ])+ }++ #[test]+ fn titles_and_artists_are_cut_like_the_mac() {+ assert_eq!(short_title("Song - Remastered 2011"), "Song");+ assert_eq!(short_title("Song (Live) [Mono]"), "Song");+ assert_eq!(short_title("(Intro)"), "(Intro)");+ assert_eq!(short_title(""), "");+ assert_eq!(short_title("Plain"), "Plain");+ assert_eq!(short_artist("Artist feat. Someone"), "Artist");+ assert_eq!(short_artist("Artist FT. Someone"), "Artist");+ assert_eq!(short_artist("Solo"), "Solo");+ }++ #[test]+ fn mpris_track_ids_become_spotify_ids() {+ assert_eq!(spotify_id("/com/spotify/track/ABC", None), "spotify:track:ABC");+ assert_eq!(spotify_id("/com/spotify/episode/XYZ", None), "spotify:episode:XYZ");+ assert_eq!(spotify_id("/com/spotify/ad/123", None), "spotify:ad:123");+ assert_eq!(spotify_id("spotify:track:ABC", None), "spotify:track:ABC");+ assert_eq!(+ spotify_id("/org/mpris/x", Some("https://open.spotify.com/track/QQQ?si=1")),+ "spotify:track:QQQ"+ );+ assert_eq!(spotify_id("/org/mpris/x", None), "/org/mpris/x");+ }++ #[test]+ fn metadata_parses_and_an_empty_player_has_no_track() {+ let Value::Map(map) = metadata("/com/spotify/track/ID1", "Get Lucky - Radio Edit") else { unreachable!() };+ let track = parse_metadata(&map).unwrap();+ assert_eq!(track.id, "spotify:track:ID1");+ assert_eq!(track.title, "Get Lucky");+ assert_eq!(track.artist, "Daft Punk, Pharrell Williams");+ assert_eq!(track.album, "Random Access Memories");+ assert_eq!(track.duration, 369.0);+ assert_eq!(track.art_url.as_deref(), Some("https://i.scdn.co/image/abc"));++ assert_eq!(parse_metadata(&[]), None);+ assert_eq!(+ parse_metadata(&[("mpris:trackid".into(), s("/org/mpris/MediaPlayer2/TrackList/NoTrack"))]),+ None+ );+ }++ #[test]+ fn the_position_runs_on_while_playing_and_stops_at_the_end() {+ let mut state = PlayerState::default();+ state.apply(+ &[+ ("Metadata".into(), metadata("/com/spotify/track/ID1", "Get Lucky")),+ ("PlaybackStatus".into(), s("Playing")),+ ("Position".into(), Value::Int(10_000_000)),+ ],+ 1_000.0,+ );+ assert_eq!(state.position_at_time(1_000.0), 10.0);+ assert_eq!(state.position_at_time(3_500.0), 12.5);+ // A clock that went backwards never moves it back.+ assert_eq!(state.position_at_time(0.0), 10.0);+ // Capped at the track's length.+ assert_eq!(state.position_at_time(1_000.0 + 1_000_000.0), 369.0);++ // Pausing freezes it where it got to.+ let applied = state.apply(&[("PlaybackStatus".into(), s("Paused"))], 5_000.0);+ assert!(applied.status_changed && !applied.track_changed);+ assert!(!state.playing);+ assert_eq!(state.position, 14.0);+ assert_eq!(state.position_at_time(60_000.0), 14.0);+ }++ #[test]+ fn a_new_track_restarts_the_clock_and_stopped_clears_it() {+ let mut state = PlayerState::default();+ state.apply(+ &[+ ("PlaybackStatus".into(), s("Playing")),+ ("Metadata".into(), metadata("/com/spotify/track/ID1", "One")),+ ("Position".into(), Value::Int(50_000_000)),+ ],+ 0.0,+ );+ assert!(state.playing, "the status after the metadata, whatever the order");+ let applied = state.apply(&[("Metadata".into(), metadata("/com/spotify/track/ID2", "Two"))], 2_000.0);+ assert!(applied.track_changed);+ assert_eq!(state.position, 0.0);+ assert_eq!(state.track.as_ref().unwrap().title, "Two");++ // The same track again is not a change.+ let applied = state.apply(&[("Metadata".into(), metadata("/com/spotify/track/ID2", "Two"))], 3_000.0);+ assert!(!applied.track_changed);++ let applied = state.apply(&[("PlaybackStatus".into(), s("Stopped"))], 4_000.0);+ assert!(applied.track_changed);+ assert_eq!(state.track, None);+ assert!(!state.playing);+ }++ #[test]+ fn shuffle_loop_and_volume() {+ let mut state = PlayerState::default();+ assert_eq!(state.volume, 50);+ state.apply(+ &[+ ("Shuffle".into(), Value::Bool(true)),+ ("LoopStatus".into(), s("Playlist")),+ ("Volume".into(), Value::Float(1.4)),+ ],+ 0.0,+ );+ assert!(state.shuffle && state.repeat);+ assert_eq!(state.volume, 100);+ state.apply(&[("LoopStatus".into(), s("None")), ("Volume".into(), Value::Float(0.004))], 0.0);+ assert!(!state.repeat);+ assert_eq!(state.volume, 0);+ }++ #[test]+ fn the_state_reaches_the_page_in_camel_case() {+ let mut state = PlayerState { running: true, installed: true, ..PlayerState::default() };+ state.apply(&[("Metadata".into(), metadata("/com/spotify/track/ID1", "One"))], 7.0);+ let json = serde_json::to_value(&state).unwrap();+ assert_eq!(json["positionAt"], 7.0);+ assert_eq!(json["track"]["artUrl"], "https://i.scdn.co/image/abc");+ assert_eq!(json["track"]["id"], "spotify:track:ID1");+ assert!(json["track"].get("objectPath").is_none());+ }++ #[test]+ fn covers_come_only_from_spotify_or_a_local_file() {+ assert_eq!(+ artwork_source("https://i.scdn.co/image/ab67"),+ Some(ArtSource::Https("https://i.scdn.co/image/ab67".into()))+ );+ assert_eq!(+ artwork_source("https://open.spotify.com/image/ab67"),+ Some(ArtSource::Https("https://i.scdn.co/image/ab67".into()))+ );+ assert!(matches!(artwork_source("https://mosaic.scdn.co/640/x"), Some(ArtSource::Https(_))));+ assert!(matches!(artwork_source("https://image-cdn-ak.spotifycdn.com/image/x"), Some(ArtSource::Https(_))));+ assert_eq!(artwork_source("http://i.scdn.co/image/ab67"), None);+ assert_eq!(artwork_source("https://evil.example/i.scdn.co"), None);+ assert_eq!(artwork_source("https://i.scdn.co.evil.example/x"), None);+ assert_eq!(artwork_source("https://[email protected]/x"), None);+ assert_eq!(artwork_source("https://i.scdn.co:8443/x"), None);+ // A local track's cover (Linux paths: the client only runs there).+ #[cfg(unix)]+ assert_eq!(+ artwork_source("file:///home/me/Music/cover%20art.jpg"),+ Some(ArtSource::File("/home/me/Music/cover art.jpg".into()))+ );+ assert_eq!(artwork_source("file://server/share/a.jpg"), None);+ assert_eq!(artwork_source("data:image/png;base64,AAAA"), None);+ assert_eq!(artwork_source("not a url"), None);+ }++ #[test]+ fn images_are_typed_by_their_bytes() {+ assert_eq!(sniff_image(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg"));+ assert_eq!(sniff_image(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));+ assert_eq!(sniff_image(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));+ assert_eq!(sniff_image(b"GIF89a.."), Some("image/gif"));+ assert_eq!(sniff_image(b"<svg xmlns="), None);+ assert_eq!(data_url(&[0xFF, 0xD8, 0xFF]).as_deref(), Some("data:image/jpeg;base64,/9j/"));+ }+}diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex 1bbf25fc..02e04f64 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -7,6 +7,7 @@ import { emitTo, listen } from "@tauri-apps/api/event";import { getCurrentWebview } from "@tauri-apps/api/webview";import type { Settings } from "./state";import type { RecapHistory, RecapPrefs } from "../recap/summary";+import type { SpotifyState } from "./spotify";export const IS_TAURI =typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;@@ -200,8 +201,21 @@ export const Bridge = {desktopFlyHome: (forget: boolean) => call<boolean>("desktop_mochi_fly_home", { forget }),/** Asleep, the cursor poll stops. */desktopSetAsleep: (asleep: boolean) => call<void>("desktop_mochi_set_asleep", { asleep }),++ // ── Spotify (src-tauri/src/spotify.rs, Linux) ─────────────────────────────+ /** Reads the player again (the card came on screen) and reports it. */+ spotifyRefresh: () => call<SpotifyState | null>("spotify_refresh"),+ /** True when Spotify took it. `value`: seconds for seek, 0/1 for shuffle and repeat, 0…100 for volume. */+ spotifyControl: (action: SpotifyAction, value?: number) =>+ call<boolean>("spotify_control", { action, value: value ?? null }),+ /** Brings Spotify forward or starts it; without it, its download page. */+ spotifyOpen: () => call<boolean>("spotify_open"),+ /** Whether there is a Spotify to launch (Settings). */+ spotifyInstalled: () => call<boolean>("spotify_installed"),};+export type SpotifyAction = "playPause" | "next" | "previous" | "seek" | "shuffle" | "repeat" | "volume";+export type ShortcutStatus =| "active" | "off" | "inUse" | "duplicate" | "invalid"| "typesCharacter" | "unsupported" | "notPorted";diff --git a/windows/src/core/pills.ts b/windows/src/core/pills.tsindex 7a7976de..8242ad30 100644--- a/windows/src/core/pills.ts+++ b/windows/src/core/pills.ts@@ -25,10 +25,11 @@ export const PILL_CATEGORIES: { id: PillCategory; title: string }[] = [* Whether the pill does anything on this build:* - `yes`: works on Windows and Linux;* - `windows`: Windows only (the app behind it has no Linux build);+ * - `linux`: Linux only (what drives it is Linux's: Spotify through MPRIS);* - `soon`: can be declared, shows "Coming soon" (macOS has it, this build not yet);* - `no`: macOS only, never offered here.*/-export type PillSupport = "yes" | "windows" | "soon" | "no";+export type PillSupport = "yes" | "windows" | "linux" | "soon" | "no";/** What makes the pill connected. */export type PillConnect =@@ -129,6 +130,10 @@ export const PILL_CATALOG: readonly PillDefinition[] = [subtitle: N_("Integration"), source: "n8n", support: "yes", connect: key("stripe-api-key") },{ id: "integration_music", name: "Apple Music", color: "#FA2D48", category: "service",subtitle: N_("Integration"), source: "n8n", support: "no", connect: none },+ // Spotify's MPRIS interface on the session bus (src-tauri/src/spotify.rs).+ // Windows has nothing to read it from yet.+ { id: "integration_spotify", name: "Spotify", color: "#1DB954", category: "service",+ subtitle: N_("Integration"), source: "n8n", support: "linux", connect: none },];/** The always-on pill unless the user picks another workspace tool. */@@ -146,7 +151,7 @@ export function pillDefinition(id: string): PillDefinition | undefined {}function offeredOn(def: PillDefinition, os: HostOs): boolean {- return def.support === "yes" || def.support === "soon" || (def.support === "windows" && os === "windows");+ return def.support === "yes" || def.support === "soon" || def.support === os;}/** The pills this build offers, in catalog order. */diff --git a/windows/src/core/spotify.ts b/windows/src/core/spotify.tsnew file mode 100644index 00000000..b49ece36--- /dev/null+++ b/windows/src/core/spotify.ts@@ -0,0 +1,124 @@+// The Spotify pill on the page: what src-tauri/src/spotify.rs reports (Linux,+// through MPRIS), and the pure rules the views and Mochi follow — ports of+// SpotifyController.swift, NowPlayingViews.swift and the Mac's dance rules+// (BotCanvasView, DesktopMochi.swift).+//+// Windows has no music source yet: nothing ever reports a track there, so+// nothing plays and Mochi never dances, through the same code.++import type { BotStateName, IslandMode, IslandViewName } from "./layout";++export const SPOTIFY_ID = "integration_spotify";+/** SpotifyController.green. */+export const SPOTIFY_GREEN = "#1DB954";++export interface SpotifyTrack {+ /** spotify:track:…, spotify:episode:…, spotify:ad:… */+ id: string;+ title: string;+ artist: string;+ album: string;+ /** Seconds. */+ duration: number;+ artUrl: string | null;+}++export interface SpotifyState {+ /** Spotify is running. */+ running: boolean;+ /** There is a Spotify to launch. */+ installed: boolean;+ track: SpotifyTrack | null;+ playing: boolean;+ /** Seconds at `positionAt` (Unix ms); while playing it runs on from there. */+ position: number;+ positionAt: number;+ shuffle: boolean;+ repeat: boolean;+ /** 0…100. */+ volume: number;+}++export const IDLE_SPOTIFY: SpotifyState = {+ running: false, installed: false, track: null, playing: false,+ position: 0, positionAt: 0, shuffle: false, repeat: false, volume: 50,+};++/** The page's copy of the player, and the cover of the track that has one. */+export const Spotify = {+ state: { ...IDLE_SPOTIFY } as SpotifyState,+ artwork: null as { artUrl: string; dataUrl: string } | null,+};++/** The cover to show for the current track, if it has arrived. */+export function currentArtwork(s: SpotifyState = Spotify.state): string | null {+ const art = Spotify.artwork;+ return art && s.track?.artUrl && art.artUrl === s.track.artUrl ? art.dataUrl : null;+}++/** SpotifyController.position(at:): extrapolated while playing, capped at the end. */+export function spotifyPosition(s: SpotifyState, nowMs: number): number {+ const elapsed = s.playing ? Math.max(0, (nowMs - s.positionAt) / 1000) : 0;+ const p = s.position + elapsed;+ const d = s.track?.duration ?? 0;+ return d > 0 ? Math.min(p, d) : p;+}++/**+ * The clock frozen or restarted where it is now — what a play/pause click+ * does at once, before Spotify confirms it (SpotifyController.setPlaying).+ */+export function withPlaying(s: SpotifyState, playing: boolean, nowMs: number): SpotifyState {+ if (s.playing === playing) return s;+ return { ...s, position: spotifyPosition(s, nowMs), positionAt: nowMs, playing };+}++export function isAd(track: SpotifyTrack | null | undefined): boolean {+ return track?.id.startsWith("spotify:ad:") ?? false;+}++/** NowPlayingProgress.format: m:ss, or h:mm:ss past an hour. */+export function formatTime(seconds: number): string {+ const s = Math.max(0, Math.floor(Number.isFinite(seconds) ? seconds : 0));+ const pad = (n: number) => String(n).padStart(2, "0");+ return s >= 3600+ ? `${Math.floor(s / 3600)}:${pad(Math.floor((s % 3600) / 60))}:${pad(s % 60)}`+ : `${Math.floor(s / 60)}:${pad(s % 60)}`;+}++/** NowPlayingVolume.icon: 0 = muted, then one, two or three waves. */+export function volumeLevel(volume: number): 0 | 1 | 2 | 3 {+ if (volume <= 0) return 0;+ if (volume < 34) return 1;+ if (volume < 67) return 2;+ return 3;+}++/** Music is playing on a declared Spotify pill. */+export function musicPlaying(s: SpotifyState, activeIntegrations: readonly string[]): boolean {+ return s.playing && s.track != null && activeIntegrations.includes(SPOTIFY_ID);+}++/** The states Mochi dances in; the rest (an alert, an error, sleep) win. */+const DANCE_STATES: ReadonlySet<BotStateName> = new Set(["idle", "working", "thinking", "searching", "finished"]);++/**+ * The island's Mochi (BotCanvasView, macOS): in the compact island whenever+ * music plays, expanded only on the overview with the music pill in front.+ */+export function islandDances(o: {+ music: boolean;+ state: BotStateName;+ mode: IslandMode;+ view: IslandViewName;+ focusId: string | null | undefined;+}): boolean {+ if (!o.music || !DANCE_STATES.has(o.state)) return false;+ if (o.mode === "compact") return true;+ return o.mode === "expanded" && o.view === "overview" && o.focusId === SPOTIFY_ID;+}++/** Mochi on the desktop: the compact island's rules (DesktopMochi.swift). */+export function desktopDances(music: boolean, state: BotStateName): boolean {+ return music && DANCE_STATES.has(state);+}diff --git a/windows/src/core/state.ts b/windows/src/core/state.tsindex b395a4e3..845a849b 100644--- a/windows/src/core/state.ts+++ b/windows/src/core/state.ts@@ -12,6 +12,7 @@ import type { FileDiff } from "./diff";import type { Bindings } from "./shortcuts";import { DEFAULT_OUTFIT, type Outfit } from "../mochi/wardrobe";import { pillColor } from "./pill-colors";+import { Spotify, musicPlaying } from "./spotify";export type AgentSource = "claudeCode" | "n8n" | "agent";export type PillBadge = "approval" | "finished" | "error";@@ -265,6 +266,11 @@ class AppState {return this.stateOverride ?? this.focusTask?.state ?? "idle";}+ /** Spotify plays on a declared pill: Mochi dances (Linux; never on Windows yet). */+ get spotifyPlaying(): boolean {+ return musicPlaying(Spotify.state, sanitizeDeclared(this.settings, this.os).activeIntegrations);+ }+get otherTasks(): AgentTask[] {return this.tasks.filter((t) => t.id !== this.focusId);}diff --git a/windows/src/desktop/main.ts b/windows/src/desktop/main.tsindex 34273e14..51996722 100644--- a/windows/src/desktop/main.ts+++ b/windows/src/desktop/main.ts@@ -36,7 +36,7 @@ class DesktopMochi {private mode: DesktopMode = "off";private snap: DesktopSnapshot = {- state: "idle", outfit: "none", soundEnabled: true, soundVolume: 0.12, paused: false,+ state: "idle", outfit: "none", soundEnabled: true, soundVolume: 0.12, paused: false, dancing: false,};private visible = false;@@ -136,6 +136,8 @@ class DesktopMochi {private updateSleep(now: number) {if (!this.visible) return;+ // Dancing keeps him up: asleep he would bounce at a few frames a second.+ if (this.snap.dancing && !this.snap.paused) this.lastAgentActive = now;const distance = pointerDistance(this.mode === "poll", this.cursor, now - this.lastPointer);const sleep =!this.dragging &&@@ -204,12 +206,16 @@ class DesktopMochi {engine.lookX = g.lookX;engine.lookY = g.lookY;}- // No dancing: the Windows and Linux app has no music signal to dance to.+ // Dances while Spotify plays (Linux), by the compact island's rules.+ engine.setDancing(this.snap.dancing && !this.asleep);engine.update(dt);const dpr = this.dpr();ctx.setTransform(dpr, 0, 0, dpr, SIDE * dpr, 0);ctx.clearRect(-SIDE, 0, PANEL_SIZE, PANEL_SIZE);+ ctx.save();+ engine.applyDance(ctx, DRAW_W, PANEL_SIZE);engine.draw(ctx, DRAW_W, PANEL_SIZE);+ ctx.restore();}private dpr(): number {diff --git a/windows/src/island/desktop.ts b/windows/src/island/desktop.tsindex eac54d24..894b344b 100644--- a/windows/src/island/desktop.ts+++ b/windows/src/island/desktop.ts@@ -7,6 +7,7 @@ import { Bridge, emitToWindow, onEvent, type DesktopMode } from "../core/bridge"import type { BotEmoteName } from "../core/layout";import { Sound } from "../core/sound";import { State } from "../core/state";+import { desktopDances } from "../core/spotify";import {DESKTOP_EVENTS, DesktopMochiController, alertActive, type DesktopSnapshot,} from "../mochi/desktop-logic";@@ -161,6 +162,7 @@ export class DesktopLink {soundEnabled: State.settings.soundEnabled,soundVolume: State.settings.soundVolume,paused: State.paused,+ dancing: desktopDances(State.spotifyPlaying, State.effectiveState),};const key = JSON.stringify(snapshot);if (key === this.pushed) return;diff --git a/windows/src/island/island.ts b/windows/src/island/island.tsindex 43279c29..519c7c6b 100644--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@ -12,6 +12,7 @@ import {} from "../core/layout";import { Sound } from "../core/sound";import { State } from "../core/state";+import { SPOTIFY_ID, islandDances } from "../core/spotify";import { BotEngine, hexToRGB } from "../mochi/engine";import { Greeting } from "../mochi/greeting";import { createMiniBot, pruneMiniBots, syncMiniBotStates, tickMiniBots } from "../mochi/minibots";@@ -104,6 +105,9 @@ export class Island {/** Where a press on Mochi started: moving past DRAG_THRESHOLD drags him out. */private botPress: { x: number; y: number } | null = null;+ /** The next reveal from hidden makes no peek (music starting, as on macOS). */+ private silentReveal = false;+/** Drop sequence bookkeeping: last tick played, and whether the ✓ has fired. */private uploadTens = 0;private uploadDone = false;@@ -186,6 +190,7 @@ export class Island {else if (task.id === "integration_claude" || task.sessionId) {void Bridge.openSession(task.sessionId ?? null, task.sessionCwd ?? null);} else if (task.id === "integration_n8n") void Bridge.openN8n();+ else if (task.id === SPOTIFY_ID) void Bridge.spotifyOpen();else if (urls[task.id]) void Bridge.openUrl(urls[task.id]);},openUrl: (url) => {@@ -312,7 +317,7 @@ export class Island {break;case "petit":if (from === "coucou") this.greeting.interrupt();- else if (from === "hidden") Sound.play("peek");+ else if (from === "hidden" && !this.silentReveal) Sound.play("peek");this.setMode("compact");if (from === "coucou") State.view = State.defaultView();if (!this.wasInIsland) this.fsm.mouseLeft();@@ -426,6 +431,13 @@ export class Island {this.fsm.reveal();}+ /** Music started playing: the compact island, without the peek sound (musicReveal). */+ revealSilently() {+ this.silentReveal = true;+ this.fsm.reveal();+ this.silentReveal = false;+ }+/** Right-click on Mochi: wardrobe open ↔ back to the usual view. */toggleWardrobe() {if (State.paused || State.mode === "hidden") return;@@ -1048,11 +1060,23 @@ export class Island {const showOutfit = mainFocused || State.mode !== "expanded" || inWardrobe;const outfit = State.wardrobePreview ?? this.seasons.get(parseOutfit(State.settings.mochiOutfit));this.engine.setOutfit(showOutfit ? outfit : "none", !inWardrobe);+ // Dances while music plays: always in the compact island, expanded only on+ // the music pill's card (BotCanvasView, macOS). Asked every frame.+ this.engine.setDancing(islandDances({+ music: State.spotifyPlaying,+ state: State.effectiveState,+ mode: State.mode,+ view: State.view,+ focusId: State.focusTask?.id,+ }));this.engine.update(dt);ctx.setTransform(dpr, 0, 0, dpr, BOT_SIDE * dpr, 0);ctx.clearRect(-BOT_SIDE, 0, wCss, hCss);+ ctx.save();+ this.engine.applyDance(ctx, w, hCss);this.engine.draw(ctx, w, hCss);+ ctx.restore();}/** BotCanvasView.lookX / lookY — tanh of the distance to the bot. */diff --git a/windows/src/island/spotify.ts b/windows/src/island/spotify.tsnew file mode 100644index 00000000..8cae4325--- /dev/null+++ b/windows/src/island/spotify.ts@@ -0,0 +1,58 @@+// Spotify's reports → the page (src-tauri/src/spotify.rs, Linux). The parts of+// SpotifyController.swift that touch the app: the pill wears the track's+// title, music starting shows the compact island without a sound, and the+// card reads the player again whenever it comes on screen (seeks made in+// Spotify's own window are never signalled).++import { Bridge, onEvent } from "../core/bridge";+import { pillDefinition } from "../core/pills";+import { SPOTIFY_ID, Spotify, isAd, type SpotifyState } from "../core/spotify";+import { State } from "../core/state";+import { t } from "../i18n/i18n";++export interface SpotifyHost {+ /** Compact island from hidden, no peek sound. */+ revealSilently(): void;+}++export function registerSpotifyHandlers(island: SpotifyHost) {+ void onEvent<SpotifyState>("spotify", (s) => applySpotify(island, s));+ void onEvent<{ artUrl: string; dataUrl: string }>("spotify-artwork", (art) => {+ Spotify.artwork = art;+ State.notify();+ });+ State.subscribe(() => {+ syncPillName();+ refreshWhenShown();+ });+}++/** A report from Rust (or the answer to a refresh). */+export function applySpotify(island: SpotifyHost, next: SpotifyState) {+ const wasPlaying = State.spotifyPlaying;+ Spotify.state = next;+ syncPillName();+ // Only on not playing → playing (SpotifyController.setPlaying).+ if (!wasPlaying && State.spotifyPlaying && !State.paused && State.mode === "hidden") {+ island.revealSilently();+ }+ State.notify();+}++/** SpotifyController.syncTaskName: the track's title, else the pill's name. */+export function syncPillName() {+ const task = State.tasks.find((x) => x.id === SPOTIFY_ID);+ if (!task) return;+ const track = Spotify.state.track;+ const title = isAd(track) ? t("Advertisement") : (track?.title ?? "");+ const name = title || (pillDefinition(SPOTIFY_ID)?.name ?? "Spotify");+ if (task.name !== name) task.name = name;+}++let shown = false;++function refreshWhenShown() {+ const now = State.mode === "expanded" && State.view === "overview" && State.focusTask?.id === SPOTIFY_ID;+ if (now && !shown) void Bridge.spotifyRefresh();+ shown = now;+}diff --git a/windows/src/main.ts b/windows/src/main.tsindex 36d446dc..fbc23dbf 100644--- a/windows/src/main.ts+++ b/windows/src/main.ts@@ -8,6 +8,8 @@ import { Island } from "./island/island";import { registerHookHandlers } from "./island/hooks";import { registerIntegrationHandlers, refreshConfigured } from "./island/integrations";import { registerShortcutHandlers } from "./island/shortcuts";+import { applySpotify, registerSpotifyHandlers } from "./island/spotify";+import { SPOTIFY_ID } from "./core/spotify";import { Recap } from "./recap/recap";import { onLanguageChange, resolveLanguage, setLanguage, systemLanguages } from "./i18n/i18n";@@ -93,6 +95,11 @@ async function main() {registerHookHandlers(island);registerIntegrationHandlers(island);registerShortcutHandlers(island, () => setPaused(false));+ registerSpotifyHandlers(island);+ // Rust may have read Spotify before this page listened: ask once.+ if (State.settings.activeIntegrations.includes(SPOTIFY_ID)) {+ void Bridge.spotifyRefresh().then((s) => s && applySpotify(island, s));+ }// Monday recap: app start (greeting over), an agent starting work, waking up.const checkRecap = () => void Recap.check(island);diff --git a/windows/src/mochi/desktop-logic.ts b/windows/src/mochi/desktop-logic.tsindex 0bd6c91a..d0633312 100644--- a/windows/src/mochi/desktop-logic.ts+++ b/windows/src/mochi/desktop-logic.ts@@ -19,6 +19,8 @@ export interface DesktopSnapshot {soundVolume: number;/** Tray → Pause: he dozes off and stays asleep. */paused: boolean;+ /** Music plays: he dances (the compact island's rules, core/spotify.ts). */+ dancing: boolean;}/** Events between the two windows. Rust adds `desktop-mochi-dropped`. */diff --git a/windows/src/mochi/engine.ts b/windows/src/mochi/engine.tsindex 02a47612..86d8ce6b 100644--- a/windows/src/mochi/engine.ts+++ b/windows/src/mochi/engine.ts@@ -165,6 +165,33 @@ function starPath(x: CanvasRenderingContext2D, ro: number, ri: number) {const FONT = `system-ui, "Segoe UI Variable Text", "Segoe UI", sans-serif`;+// ── Dance (BotEngine.applyDance, macOS) ──────────────────────────────────────++/** The dance fades in over 0.3 s and out over 0.5 s. */+export function stepDanceLevel(level: number, dancing: boolean, dt: number): number {+ const target = dancing ? 1 : 0;+ if (level < target) return Math.min(target, level + dt / 0.3);+ if (level > target) return Math.max(target, level - dt / 0.5);+ return level;+}++/**+ * The 112-BPM bounce at `seconds`, for a body of radius R and a dance `level`+ * (0…1): a sideways sway, a hop, a tilt, and a squash on landing.+ */+export function danceTransform(seconds: number, level: number, R: number) {+ const beat = (seconds * 112) / 60;+ const hop = Math.abs(Math.sin(Math.PI * beat));+ const land = Math.pow(1 - hop, 6);+ return {+ dx: 0.08 * R * Math.sin(Math.PI * beat) * level,+ dy: -0.2 * R * hop * level,+ rotate: 0.1 * Math.sin(Math.PI * beat) * level,+ sx: 1 + 0.045 * land * level,+ sy: 1 - 0.06 * land * level,+ };+}+// ── Engine ────────────────────────────────────────────────────────────────────export class BotEngine {@@ -199,6 +226,10 @@ export class BotEngine {/** Extra canvas height above the body so hearts can fly out without clipping. */particleOverhang = 0;+ /** Dancing to music; `dancingLevel` follows it, 0→1 in 0.3 s, 1→0 in 0.5 s. */+ isDancing = false;+ dancingLevel = 0;+// Mouth spring (fraction of R)slotH = 0; slotHTarget = 0; slotHVel = 0; isChewing = false;@@ -513,6 +544,7 @@ export class BotEngine {this.particles.length > 0 ||this.cfg.bounces || this.cfg.scans || this.cfg.breathes || this.cfg.zz || this.cfg.sweat ||this.isMini ||+ this.isDancing || this.dancingLevel > 0.001 ||Math.abs(this.tgYaw - this.yaw) > 0.002 ||Math.abs(this.tgPitch - this.pitch) > 0.002 ||Math.abs(this.tgTilt - this.tilt) > 0.002 ||@@ -652,6 +684,8 @@ export class BotEngine {this.slotHVel += acc * dt;this.slotH = Math.max(0, this.slotH + this.slotHVel * dt);+ this.dancingLevel = stepDanceLevel(this.dancingLevel, this.isDancing, dt);+// Soft-part spring: lags behind head turns, hops and rolls (stiffness 60, damping 9).if (dt > 0) {const yawVel = (this.yaw - this.prevYaw) / dt;@@ -708,6 +742,28 @@ export class BotEngine {}}+ // ── Dancing ─────────────────────────────────────────────────────────────────++ setDancing(dancing: boolean) {+ if (this.isDancing !== dancing) this.isDancing = dancing;+ }++ /**+ * Applies the dance bounce and sway around the bottom of the body. Call it on+ * a saved context, before draw(), with the same size (BotEngine.applyDance).+ */+ applyDance(x: CanvasRenderingContext2D, W: number, H: number) {+ if (this.dancingLevel <= 0.001) return;+ const R = W * 0.3;+ const px = W / 2 + this.ox * R;+ const py = H / 2 + this.particleOverhang / 2 + this.oy * R + R * 0.06 + R * 0.88;+ const d = danceTransform(now(), this.dancingLevel, R);+ x.translate(px + d.dx, py + d.dy);+ x.rotate(d.rotate);+ x.scale(d.sx, d.sy);+ x.translate(-px, -py);+ }+// ── Draw ────────────────────────────────────────────────────────────────────/**@@ -859,6 +915,10 @@ export class BotEngine {private drawEyes(x: CanvasRenderingContext2D, body: Path2D, R: number, rx: number, ry: number) {let shape: EyeShape = this.eyeOverride ?? this.cfg.eye;+ // Dancing: happy eyes in the calm states.+ if (this.isDancing && this.dancingLevel > 0.15 && !this.isMini && (this.state === "idle" || this.state === "finished")) {+ shape = "happy";+ }if (this.morph > 0.5) {if (this.isChewing) shape = "happy";else if (this.slotHTarget > 0.05 || this.slotH > 0.1) shape = "cup";diff --git a/windows/src/mochi/minibots.ts b/windows/src/mochi/minibots.tsindex fbf2e03b..f166b823 100644--- a/windows/src/mochi/minibots.ts+++ b/windows/src/mochi/minibots.ts@@ -9,6 +9,8 @@ interface MiniBot {engine: BotEngine;cssSize: number;taskId: string;+ /** Asked every frame: whether this one dances (the music pill's, MiniBotCanvasView). */+ dancing?: () => boolean;}const live = new Map<HTMLCanvasElement, MiniBot>();@@ -22,7 +24,7 @@ const live = new Map<HTMLCanvasElement, MiniBot>();* `.frame(width: 22)`. Sizing the canvas itself to `bodySize` would shrink the* whole drawing to 60 %, which is what used to happen.*/-export function createMiniBot(task: AgentTask, bodySize: number): HTMLElement {+export function createMiniBot(task: AgentTask, bodySize: number, dancing?: () => boolean): HTMLElement {const slot = document.createElement("span");slot.className = "mini";slot.style.width = `${bodySize}px`;@@ -48,7 +50,7 @@ export function createMiniBot(task: AgentTask, bodySize: number): HTMLElement {engine.eyeOverrideUntil = Number.POSITIVE_INFINITY;}- live.set(canvas, { canvas, engine, cssSize: engineSize, taskId: task.id });+ live.set(canvas, { canvas, engine, cssSize: engineSize, taskId: task.id, dancing });return slot;}@@ -77,10 +79,14 @@ export function tickMiniBots(dt: number) {for (const mb of live.values()) {const ctx = mb.canvas.getContext("2d");if (!ctx) continue;+ mb.engine.setDancing(mb.dancing?.() ?? false);mb.engine.update(dt);ctx.setTransform(dpr, 0, 0, dpr, 0, 0);ctx.clearRect(0, 0, mb.cssSize, mb.cssSize);+ ctx.save();+ mb.engine.applyDance(ctx, mb.cssSize, mb.cssSize);mb.engine.draw(ctx, mb.cssSize, mb.cssSize);+ ctx.restore();}}diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 8571126a..ea98d345 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -772,6 +772,8 @@ const INTEGRATIONS: IntegrationDef[] = [fields: [{ key: "notion-api-key", label: N_("Integration token"), placeholder: "ntn_…", secret: true }] },{ id: "integration_calcom", name: "Cal.com", color: "#C9956A",fields: [{ key: "calcom-api-key", label: N_("API key"), placeholder: "cal_…", secret: true }] },+ // Nothing to enter: Spotify is read over D-Bus (Linux only, see core/pills.ts).+ { id: "integration_spotify", name: "Spotify", color: "#1DB954", fields: [] },];const MAX_ACTIVE = MAX_DECLARED;@@ -794,7 +796,8 @@ function integrationsSection(present: Record<string, boolean>): HTMLElement {}declaredViews.push(updateNote);- for (const def of INTEGRATIONS) {+ const offered = new Set(availablePills().map((p) => p.id));+ for (const def of INTEGRATIONS.filter((d) => offered.has(d.id))) {const active = settings.activeIntegrations.includes(def.id);const sw = h("button", { class: active ? "switch on" : "switch" });sw.addEventListener("click", () => {@@ -841,6 +844,14 @@ function integrationsSection(present: Record<string, boolean>): HTMLElement {}if (def.hint) rows.append(h("div", { class: "hint", text: t(def.hint) }));+ if (def.id === "integration_spotify") {+ // As on the Mac's row: said only when there is no Spotify to launch.+ const hint = h("div", { class: "hint", style: "padding-top:5px" });+ rows.append(hint);+ void Bridge.spotifyInstalled().then((ok) => {+ hint.textContent = ok === false ? t("Not installed") : "";+ });+ }list.append(h("div", { style: "display:flex;gap:12px;align-items:flex-start" },diff --git a/windows/src/style.css b/windows/src/style.cssindex da456b00..e02cd808 100644--- a/windows/src/style.css+++ b/windows/src/style.css@@ -2326,6 +2326,280 @@ input[type="range"]::-webkit-slider-thumb {pointer-events: none;}+/* ── Spotify: the pill's controls and the now-playing card ──────────────────+ SpotifyPill, MusicControlButton and SpotifyCardView (SpotifyViews.swift,+ NowPlayingViews.swift): sizes and colours are the Mac's. */++.np-pill .lbl {+ transition: padding 0.2s cubic-bezier(0.3, 1.2, 0.4, 1);+}++.np-pill.controls .lbl {+ padding: 0 52px 0 34px;+}++.np-pill-controls {+ position: absolute;+ right: 4px;+ top: 50%;+ display: flex;+ gap: 2px;+ opacity: 0;+ pointer-events: none;+ transform: translateY(-50%) scale(0.85);+ transform-origin: right center;+ transition: opacity 0.18s, transform 0.2s cubic-bezier(0.3, 1.2, 0.4, 1);+}++.np-pill.controls .np-pill-controls {+ opacity: 1;+ pointer-events: auto;+ transform: translateY(-50%) scale(1);+}++.np-pill-btn {+ width: 20px;+ height: 20px;+ padding: 0;+ border-radius: 50%;+ border: 1px solid transparent;+ background: var(--card-flat);+ color: var(--dim-3);+ display: grid;+ place-items: center;+ cursor: default;+ transition: transform 0.2s cubic-bezier(0.3, 1.2, 0.4, 1), background 0.18s, border-color 0.18s,+ box-shadow 0.18s, color 0.18s;+}++.np-pill-btn:hover {+ transform: scale(1.1);+}++.np-root {+ height: 100%;+}++.np-card {+ padding: 10px 12px 0 108px;+ display: flex;+ flex-direction: column;+}++.np-head {+ display: flex;+ align-items: center;+ gap: 9px;+ padding-right: 24px;+ min-width: 0;+}++.np-art {+ position: relative;+ flex: 0 0 36px;+ width: 36px;+ height: 36px;+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.06);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.35);+ display: grid;+ place-items: center;+ overflow: hidden;+ cursor: default;+}++.np-art::after {+ content: "";+ position: absolute;+ inset: 0;+ border-radius: 6px;+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);+ pointer-events: none;+}++.np-art img {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: cover;+ opacity: 0;+ transition: opacity 0.25s ease-in-out;+}++.np-art.has-art img {+ opacity: 1;+}++.np-art.has-art svg {+ opacity: 0;+}++.np-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ flex: 1 1 auto;+}++.np-title-row {+ display: flex;+ align-items: center;+ gap: 5px;+ min-width: 0;+}++.np-title,+.np-sub {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.np-title {+ font: 600 12px var(--font);+ color: var(--ink);+}++.np-sub {+ font: 400 11px var(--font);+ color: var(--dim-2);+}++.np-progress {+ display: flex;+ align-items: center;+ gap: 6px;+ padding-top: 7px;+ font: 400 9.5px var(--font);+ font-variant-numeric: tabular-nums;+ color: var(--dim-3);+}++.np-time.elapsed {+ min-width: 26px;+ text-align: right;+}++.np-time.remaining {+ min-width: 28px;+ text-align: left;+}++.np-bar {+ position: relative;+ flex: 1 1 auto;+ height: 10px;+ touch-action: none;+ cursor: default;+}++.np-track,+.np-fill {+ position: absolute;+ left: 0;+ top: 50%;+ height: 3px;+ transform: translateY(-50%);+ border-radius: 999px;+}++.np-track {+ width: 100%;+ background: rgba(255, 255, 255, 0.12);+}++.np-bar.active .np-track,+.np-bar.active .np-fill {+ height: 4px;+}++.np-knob {+ position: absolute;+ top: 50%;+ width: 9px;+ height: 9px;+ margin-top: -4.5px;+ border-radius: 50%;+ background: var(--ink);+ box-shadow: 0 0 2px rgba(0, 0, 0, 0.4);+ opacity: 0;+ transition: opacity 0.12s ease-out;+}++.np-bar.active .np-knob {+ opacity: 1;+}++.np-controls {+ display: flex;+ align-items: center;+ padding-top: 4px;+}++.np-controls .grow {+ min-width: 8px;+}++.np-buttons {+ display: flex;+ align-items: center;+ gap: 10px;+}++.np-icon,+.np-play {+ padding: 0;+ border: 0;+ display: grid;+ place-items: center;+ cursor: default;+ transition: transform 0.2s cubic-bezier(0.3, 1.2, 0.4, 1), filter 0.12s ease-out;+}++.np-icon {+ width: 16px;+ height: 18px;+ background: transparent;+}++.np-icon:hover {+ filter: brightness(1.3);+}++.np-play {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ background: var(--ink);+ color: var(--card-flat);+}++.np-icon:active,+.np-play:active {+ transform: scale(0.9);+}++.np-volume {+ display: flex;+ align-items: center;+ gap: 5px;+}++.np-vol-icon {+ width: 13px;+ display: flex;+ justify-content: flex-end;+ color: var(--dim-3);+}++.np-volume .np-bar {+ flex: 0 0 44px;+ width: 44px;+}+/* ── Arabic: right to left ─────────────────────────────────────────────────────i18n.ts sets <html data-dir="rtl">. The text of the cards reads and alignsright to left; Mochi, the pills, the header and the cards themselves keep@@ -2340,6 +2614,11 @@ html[data-dir="rtl"] #views :is(.code, .gh-grid, .diff-card, .md-pre) {direction: ltr;}+html[data-dir="rtl"] #views :is(.np-title, .np-sub) {+ unicode-bidi: plaintext;+ text-align: start;+}+html[data-dir="rtl"] #views :is(.bubble, .reply .md-p, .reply .md-h, .reply .md-item, .reply .md-quote, .chat-input) {unicode-bidi: plaintext;text-align: start;diff --git a/windows/src/views/icons.ts b/windows/src/views/icons.tsindex 923ad026..86394d75 100644--- a/windows/src/views/icons.ts+++ b/windows/src/views/icons.ts@@ -54,4 +54,24 @@ export const ICONS = {octagonX: "M21.61 15.98 15.98 21.61 8.02 21.61 2.39 15.98 2.39 8.02 8.02 2.39 15.98 2.39 21.61 8.02zM8.53 7.66 12 11.13 15.47 7.66 16.34 8.53 12.87 12 16.34 15.47 15.47 16.34 12 12.87 8.53 16.34 7.66 15.47 11.13 12 7.66 8.53z",// doc.textdoc: "M6.5 2.6h7l4 4v14.8h-11V2.6zm6.6 1.6v3.3h3.3l-3.3-3.3zM8.6 11h6.8v1.5H8.6V11zm0 3.4h6.8v1.5H8.6v-1.5z",+ // ── Now playing (the Spotify pill and card) ──+ // play.fill+ play: "M7 4.6c0-.8.9-1.3 1.6-.9l11 6.9c.6.4.6 1.4 0 1.8l-11 6.9c-.7.4-1.6-.1-1.6-.9V4.6z",+ // pause.fill+ pause: "M6 4.5h4v15H6zM14 4.5h4v15h-4z",+ // forward.fill+ forward: "M2.5 6.2c0-.7.8-1.1 1.4-.7l7.6 5.8c.5.4.5 1 0 1.4l-7.6 5.8c-.6.4-1.4 0-1.4-.7V6.2zm10 0c0-.7.8-1.1 1.4-.7l7.6 5.8c.5.4.5 1 0 1.4l-7.6 5.8c-.6.4-1.4 0-1.4-.7V6.2z",+ // backward.fill+ backward: "M21.5 6.2c0-.7-.8-1.1-1.4-.7l-7.6 5.8c-.5.4-.5 1 0 1.4l7.6 5.8c.6.4 1.4 0 1.4-.7V6.2zm-10 0c0-.7-.8-1.1-1.4-.7l-7.6 5.8c-.5.4-.5 1 0 1.4l7.6 5.8c.6.4 1.4 0 1.4-.7V6.2z",+ // shuffle (stroked)+ shuffle: "M3 7h3.2c1.9 0 3.1.9 4.1 2.5l3.4 5c1 1.6 2.2 2.5 4.1 2.5H21M3 17h3.2c1.6 0 2.7-.6 3.6-1.8M14.2 8.8C15.1 7.6 16.2 7 17.8 7H21M18.6 4.6 21 7l-2.4 2.4M18.6 14.6 21 17l-2.4 2.4",+ // repeat (stroked)+ repeat: "M4 11.5V10a3 3 0 0 1 3-3h13.5M17.6 4.1 20.5 7l-2.9 2.9M20 12.5V14a3 3 0 0 1-3 3H3.5M6.4 19.9 3.5 17l2.9-2.9",+ // music.note+ musicNote: "M12.2 3.6h1.7c.3 2.3 1.8 3.5 4.2 4.6l-.6 1.6c-1.4-.5-2.7-1.2-3.6-2.1v9.5a3.3 3.3 0 1 1-1.7-2.88V3.6z",+ // speaker.slash.fill / speaker.wave.1-3.fill (stroked, the body outlined round)+ volume0: "M3.5 9.5h3L11 5.8v12.4l-4.5-3.7h-3zM15 9.5l5 5M20 9.5l-5 5",+ volume1: "M3.5 9.5h3L11 5.8v12.4l-4.5-3.7h-3zM14.5 9.6a3.4 3.4 0 0 1 0 4.8",+ volume2: "M3.5 9.5h3L11 5.8v12.4l-4.5-3.7h-3zM14.5 9.6a3.4 3.4 0 0 1 0 4.8M17 7.2a6.8 6.8 0 0 1 0 9.6",+ volume3: "M3.5 9.5h3L11 5.8v12.4l-4.5-3.7h-3zM14.5 9.6a3.4 3.4 0 0 1 0 4.8M17 7.2a6.8 6.8 0 0 1 0 9.6M19.4 4.8a10.2 10.2 0 0 1 0 14.4",} as const;diff --git a/windows/src/views/spotify.ts b/windows/src/views/spotify.tsnew file mode 100644index 00000000..e5f20012--- /dev/null+++ b/windows/src/views/spotify.ts@@ -0,0 +1,430 @@+// The Spotify pill and card — DOM ports of SpotifyPill / SpotifyCardView+// (SpotifyViews.swift) and the shared now-playing pieces (NowPlayingViews.swift+// and MusicControlButton). Sizes, colours and wording are the Mac's.+//+// What they show comes from src-tauri/src/spotify.rs (Linux, MPRIS) through+// island/spotify.ts. A click changes the page's copy at once and Spotify+// confirms it, as the Mac's controller does.++import { h, svg, clear, dot } from "./dom";+import { ICONS } from "./icons";+import { Bridge } from "../core/bridge";+import { State, type AgentTask } from "../core/state";+import {+ SPOTIFY_GREEN, SPOTIFY_ID, Spotify, currentArtwork, formatTime, isAd, spotifyPosition, volumeLevel, withPlaying,+ type SpotifyTrack,+} from "../core/spotify";+import { createMiniBot } from "../mochi/minibots";+import { pillDefinition } from "../core/pills";+import { N_, t } from "../i18n/i18n";+++function lighter(hex: string, amount: number): string {+ const v = parseInt(hex.replace("#", ""), 16);+ const c = [(v >> 16) & 255, (v >> 8) & 255, v & 255].map((x) => Math.min(255, Math.round(x + amount * 255)));+ return `rgb(${c[0]},${c[1]},${c[2]})`;+}++// ── Controls (shared by the pill and the card) ───────────────────────────────++/** Play/pause, at once on the page, then in Spotify (SpotifyController.playPause). */+export function togglePlay() {+ const s = Spotify.state;+ if (!s.running) return;+ Spotify.state = withPlaying(s, !s.playing, Date.now());+ State.notify();+ void Bridge.spotifyControl("playPause");+}++function seek(seconds: number) {+ const s = Spotify.state;+ const track = s.track;+ if (!s.running || !track || isAd(track)) return;+ const target = Math.min(Math.max(0, seconds), Math.max(0, track.duration - 1));+ Spotify.state = { ...s, position: target, positionAt: Date.now() };+ State.notify();+ void Bridge.spotifyControl("seek", target);+}++function setFlag(which: "shuffle" | "repeat", on: boolean) {+ if (!Spotify.state.running) return;+ Spotify.state = { ...Spotify.state, [which]: on };+ State.notify();+ void Bridge.spotifyControl(which, on ? 1 : 0);+}++// A slider drag sends at most one volume every 120 ms (SpotifyController.setVolume).+let pendingVolume: number | null = null;+let volumeTimer: number | null = null;++function setVolume(value: number) {+ if (!Spotify.state.running) return;+ const v = Math.min(100, Math.max(0, Math.round(value)));+ Spotify.state = { ...Spotify.state, volume: v };+ State.notify();+ pendingVolume = v;+ if (volumeTimer != null) return;+ const send = () => {+ const next = pendingVolume;+ pendingVolume = null;+ if (next == null) {+ volumeTimer = null;+ return;+ }+ void Bridge.spotifyControl("volume", next);+ volumeTimer = window.setTimeout(send, 120);+ };+ send();+}++// ── Pill (overview right column) ──────────────────────────────────────────────++export interface SpotifyPillHost {+ el: HTMLElement;+ sync(): void;+}++/** MusicControlButton: a 20 px round button in the pill's colour. */+function pillButton(color: string, icon: string, onClick: () => void): HTMLElement {+ const b = h("button", { class: "np-pill-btn" }, svg(icon, 8));+ b.style.borderColor = `${color}24`;+ b.addEventListener("click", (e) => {+ e.stopPropagation();+ onClick();+ });+ b.addEventListener("mouseenter", () => {+ b.style.background = `${color}2e`;+ b.style.borderColor = `${color}8c`;+ b.style.color = lighter(color, 0.3);+ b.style.boxShadow = `0 0 6px ${color}59`;+ });+ b.addEventListener("mouseleave", () => {+ b.style.background = "";+ b.style.borderColor = `${color}24`;+ b.style.color = "";+ b.style.boxShadow = "";+ });+ return b;+}++/**+ * SpotifyPill: the agent pill's look, with a mini Mochi that dances while+ * Spotify plays, and play/pause + next on hover when a track is loaded.+ */+export function buildSpotifyPill(task: AgentTask, onTap: () => void): SpotifyPillHost {+ const color = task.color;+ const mini = createMiniBot(task, 24, () => State.spotifyPlaying);+ const label = h("span", { class: "lbl", text: task.name });+ const playBtn = pillButton(color, ICONS.play, togglePlay);+ const nextBtn = pillButton(color, ICONS.forward, () => void Bridge.spotifyControl("next"));+ const controls = h("div", { class: "np-pill-controls" }, playBtn, nextBtn);+ const pill = h("div", { class: "pill np-pill", onclick: onTap }, mini, label, controls);+ pill.style.borderColor = `${color}24`;+ let hovered = false;+ let playing: boolean | null = null;++ const sync = () => {+ const s = Spotify.state;+ const current = State.tasks.find((x) => x.id === task.id);+ const name = current?.name ?? task.name;+ if (label.textContent !== name) label.textContent = name;+ const show = hovered && s.track != null;+ pill.classList.toggle("controls", show);+ if (playing !== s.playing) {+ playing = s.playing;+ clear(playBtn);+ playBtn.append(svg(s.playing ? ICONS.pause : ICONS.play, 8));+ }+ playBtn.title = s.playing ? t("Pause") : t("Play");+ nextBtn.title = t("Next");+ };++ pill.addEventListener("mouseenter", () => {+ hovered = true;+ pill.style.background = `${color}2e`;+ pill.style.borderColor = `${color}8c`;+ pill.style.boxShadow = `0 2px 10px ${color}59`;+ label.style.color = lighter(color, 0.3);+ sync();+ });+ pill.addEventListener("mouseleave", () => {+ hovered = false;+ pill.style.background = "";+ pill.style.borderColor = `${color}24`;+ pill.style.boxShadow = "";+ label.style.color = "";+ sync();+ });+ sync();+ return { el: pill, sync };+}++// ── Card (overview left card) ─────────────────────────────────────────────────++/**+ * NowPlayingBar: a grey track whose filled part turns green and grows a knob+ * under the pointer; drag or click anywhere on it.+ */+class NowPlayingBar {+ readonly el: HTMLElement;+ private fill: HTMLElement;+ private knob: HTMLElement;+ private hovering = false;+ private dragging = false;+ private fraction = 0;+ enabled = true;+ private onChange: (f: number) => void;+ private onCommit: (f: number) => void;++ constructor(onChange: (f: number) => void, onCommit: (f: number) => void) {+ this.onChange = onChange;+ this.onCommit = onCommit;+ this.fill = h("i", { class: "np-fill" });+ this.knob = h("i", { class: "np-knob" });+ this.fill.style.background = "#C5C8CD";+ this.el = h("div", { class: "np-bar" }, h("i", { class: "np-track" }), this.fill, this.knob);+ this.el.addEventListener("mouseenter", () => {+ this.hovering = true;+ this.paint();+ });+ this.el.addEventListener("mouseleave", () => {+ this.hovering = false;+ this.paint();+ });+ this.el.addEventListener("pointerdown", (e) => {+ if (!this.enabled || e.button !== 0) return;+ e.stopPropagation();+ this.dragging = true;+ try {+ this.el.setPointerCapture(e.pointerId);+ } catch {+ /* capture is a nicety */+ }+ this.onChange(this.at(e.clientX));+ this.paint();+ });+ this.el.addEventListener("pointermove", (e) => {+ if (this.dragging) this.onChange(this.at(e.clientX));+ });+ const end = (e: PointerEvent) => {+ if (!this.dragging) return;+ this.dragging = false;+ this.onCommit(this.at(e.clientX));+ this.paint();+ };+ this.el.addEventListener("pointerup", end);+ this.el.addEventListener("pointercancel", end);+ }++ get active(): boolean {+ return this.enabled && (this.hovering || this.dragging);+ }++ private at(clientX: number): number {+ const r = this.el.getBoundingClientRect();+ return Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width)));+ }++ set(fraction: number) {+ this.fraction = Math.min(1, Math.max(0, fraction));+ this.paint();+ }++ private paint() {+ const active = this.active;+ this.el.classList.toggle("active", active);+ const pct = `${this.fraction * 100}%`;+ this.fill.style.width = pct;+ this.fill.style.background = active ? SPOTIFY_GREEN : "#C5C8CD";+ this.knob.style.left = `clamp(0px, calc(${pct} - 4.5px), calc(100% - 9px))`;+ }+}++/** NowPlayingIconButton: an icon that brightens under the pointer. */+function iconButton(icon: string, size: number, stroke: number, onClick: () => void): HTMLElement {+ const b = h("button", { class: "np-icon" }, svg(icon, size, stroke ? { stroke } : {}));+ b.addEventListener("click", onClick);+ return b;+}++export interface SpotifyCardHost {+ el: HTMLElement;+ sync(): void;+}++/** SpotifyCardView: now playing, or the idle card (not playing / not installed). */+export function buildSpotifyCard(): SpotifyCardHost {+ const green = SPOTIFY_GREEN;++ // Now playing: artwork row, progress row, controls row.+ const art = h("div", { class: "np-art" });+ const artImg = h("img", { alt: "", draggable: "false" }) as HTMLImageElement;+ const artNote = svg(ICONS.musicNote, 16);+ artNote.style.color = `${green}b3`;+ art.append(artNote, artImg);+ art.addEventListener("click", () => void Bridge.spotifyOpen());+ const title = h("span", { class: "np-title" });+ const subtitle = h("div", { class: "np-sub" });+ const head = h("div", { class: "np-head" },+ art,+ h("div", { class: "np-text" }, h("div", { class: "np-title-row" }, dot(green, 6), title), subtitle),+ );++ let dragFraction: number | null = null;+ const elapsed = h("span", { class: "np-time elapsed" });+ const remaining = h("span", { class: "np-time remaining" });+ const progress = new NowPlayingBar(+ (f) => {+ dragFraction = f;+ paintProgress();+ },+ (f) => {+ const d = Spotify.state.track?.duration ?? 0;+ dragFraction = null;+ seek(f * d);+ },+ );+ const progressRow = h("div", { class: "np-progress" }, elapsed, progress.el, remaining);++ const shuffle = iconButton(ICONS.shuffle, 10, 2.2, () => setFlag("shuffle", !Spotify.state.shuffle));+ const prev = iconButton(ICONS.backward, 11, 0, () => void Bridge.spotifyControl("previous"));+ const next = iconButton(ICONS.forward, 11, 0, () => void Bridge.spotifyControl("next"));+ const repeat = iconButton(ICONS.repeat, 10, 2.2, () => setFlag("repeat", !Spotify.state.repeat));+ prev.style.color = "#C5C8CD";+ next.style.color = "#C5C8CD";+ const play = h("button", { class: "np-play", onclick: togglePlay });+ const volIcon = h("span", { class: "np-vol-icon" });+ const volume = new NowPlayingBar(+ (f) => setVolume(f * 100),+ (f) => setVolume(f * 100),+ );+ const volumeBox = h("div", { class: "np-volume" }, volIcon, volume.el);+ const controls = h("div", { class: "np-controls" },+ h("div", { class: "np-buttons" }, shuffle, prev, play, next, repeat),+ h("div", { class: "grow" }),+ volumeBox,+ );+ const playingEl = h("div", { class: "np-card" }, head, progressRow, controls);++ // Idle: the same layout as the other idle cards.+ const idleDot = dot("#22C55E", 5);+ const idleText = h("span");+ const idleAction = h("button", { class: "link-btn", style: `color:${green}d9` });+ idleAction.addEventListener("click", () => void Bridge.spotifyOpen());+ const idleSub = h("span");+ const idleEl = h("div", { class: "int-card" },+ h("div", { class: "int-head" }, dot(green, 7), h("b", { text: "Spotify" }), idleSub),+ h("div", { class: "int-status" }, idleDot, idleText),+ h("div", { class: "int-actions" }, idleAction),+ );++ const el = h("div", { class: "np-root" });+ let showing: "playing" | "idle" | null = null;+ let shownTrack: SpotifyTrack | null = null;+ let playIcon: boolean | null = null;+ let volIconLevel = -1;+ let timer: number | null = null;++ function paintProgress() {+ const s = Spotify.state;+ const d = s.track?.duration ?? 0;+ const pos = dragFraction != null ? dragFraction * d : spotifyPosition(s, Date.now());+ const f = dragFraction ?? (d > 0 ? Math.min(1, Math.max(0, pos / d)) : 0);+ progress.set(f);+ elapsed.textContent = formatTime(f * d);+ remaining.textContent = d > 0 ? `-${formatTime(Math.max(0, d - f * d))}` : "";+ }++ /** The position runs on its own clock, twice a second, only while it plays on screen. */+ function syncTimer() {+ const run = Spotify.state.playing && showing === "playing" && el.isConnected &&+ State.mode === "expanded" && State.view === "overview";+ if (run && timer == null) {+ timer = window.setInterval(() => {+ if (!(Spotify.state.playing && el.isConnected && State.mode === "expanded" && State.view === "overview")) {+ if (timer != null) window.clearInterval(timer);+ timer = null;+ return;+ }+ paintProgress();+ }, 500);+ } else if (!run && timer != null) {+ window.clearInterval(timer);+ timer = null;+ }+ }++ function syncPlaying(track: SpotifyTrack) {+ const s = Spotify.state;+ if (shownTrack !== track) {+ shownTrack = track;+ title.textContent = isAd(track) ? t("Advertisement") : track.title;+ const sub = [track.artist, track.album].filter((x) => x).join(" · ");+ subtitle.textContent = sub;+ subtitle.style.display = sub ? "" : "none";+ } else if (isAd(track)) {+ title.textContent = t("Advertisement");+ }+ art.title = track.album ? t("{0} — open Spotify", { 0: track.album }) : t("Open Spotify");+ const cover = currentArtwork(s);+ if (cover) {+ if (artImg.getAttribute("src") !== cover) artImg.setAttribute("src", cover);+ art.classList.add("has-art");+ } else {+ art.classList.remove("has-art");+ artImg.removeAttribute("src");+ }++ progress.enabled = !isAd(track) && track.duration > 0;+ paintProgress();++ shuffle.style.color = s.shuffle ? green : "#6B7079";+ shuffle.title = s.shuffle ? t("Shuffle on") : t("Shuffle off");+ repeat.style.color = s.repeat ? green : "#6B7079";+ repeat.title = s.repeat ? t("Repeat on") : t("Repeat off");+ prev.title = t("Previous");+ next.title = t("Next");+ if (playIcon !== s.playing) {+ playIcon = s.playing;+ clear(play);+ const icon = svg(s.playing ? ICONS.pause : ICONS.play, 9);+ if (!s.playing) icon.style.transform = "translateX(1px)";+ play.append(icon);+ }+ play.title = s.playing ? t("Pause") : t("Play");++ const level = volumeLevel(s.volume);+ if (level !== volIconLevel) {+ volIconLevel = level;+ clear(volIcon);+ volIcon.append(svg([ICONS.volume0, ICONS.volume1, ICONS.volume2, ICONS.volume3][level], 10, { stroke: 2.2 }));+ }+ volume.set(s.volume / 100);+ volumeBox.title = t("Volume {0}%", { 0: s.volume });+ }++ function syncIdle() {+ const installed = Spotify.state.installed || Spotify.state.running;+ idleDot.style.background = installed ? "#22C55E" : "#F4505E";+ idleText.textContent = installed ? t("Not playing") : t("Spotify not installed");+ idleAction.textContent = installed ? t("Open Spotify") : t("Get Spotify");+ idleSub.textContent = t(pillDefinition(SPOTIFY_ID)?.subtitle ?? N_("Integration"));+ }++ return {+ el,+ sync() {+ const track = Spotify.state.track;+ const want = track ? "playing" : "idle";+ if (want !== showing) {+ showing = want;+ clear(el);+ el.append(want === "playing" ? playingEl : idleEl);+ shownTrack = null;+ }+ if (track) syncPlaying(track);+ else syncIdle();+ syncTimer();+ },+ };+}diff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex 7570c546..0da43d7d 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -20,6 +20,8 @@ import { lastTextStep } from "../core/diff";import { Bridge } from "../core/bridge";import { buildRecap } from "./recap";import { buildWardrobe } from "./wardrobe";+import { buildSpotifyCard, buildSpotifyPill, type SpotifyPillHost } from "./spotify";+import { SPOTIFY_ID } from "../core/spotify";import type { Outfit, OutfitSelection } from "../mochi/wardrobe";import { language, t, tl, type Msg } from "../i18n/i18n";@@ -189,6 +191,10 @@ function buildOverview(actions: ViewActions): ViewHost {// Opened from a plan pill in the header: stands in for the left card.const plan = new PlanCard();let planTimer: number | null = null;+ // Spotify's card and pill are kept and updated in place: the progress bar+ // runs on, and a slider being dragged must not be rebuilt under the pointer.+ const spotifyCard = buildSpotifyCard();+ let spotifyPill: SpotifyPillHost | null = null;const el = h("div", { class: "view overview" },h("div", { class: "left" }, left),@@ -198,7 +204,7 @@ function buildOverview(actions: ViewActions): ViewHost {let pillIds = "";let detailOpen = false;let lastFocus: string | null = null;- let mode: "ticker" | "card" | "plan" | "diff" | null = null;+ let mode: "ticker" | "card" | "plan" | "diff" | "spotify" | null = null;let cardKey = "";// Leaving the overview or folding the island closes the diff, as on macOS.@@ -324,6 +330,15 @@ function buildOverview(actions: ViewActions): ViewHost {}));}ticker.sync(task);+ } else if (task && task.id === SPOTIFY_ID) {+ // Its own card for every state: playing, idle, not installed.+ if (mode !== "spotify") {+ clear(leftBody);+ leftBody.append(spotifyCard.el);+ mode = "spotify";+ cardKey = "";+ }+ spotifyCard.sync();} else if (task) {const info = State.integrations[task.id];const key = [@@ -346,9 +361,18 @@ function buildOverview(actions: ViewActions): ViewHost {if (pillKey !== pillIds) {pillIds = pillKey;clear(pills);- for (const t of others) pills.append(buildPill(t, actions));+ spotifyPill = null;+ for (const t of others) {+ if (t.id === SPOTIFY_ID) {+ spotifyPill = buildSpotifyPill(t, () => actions.setFocus(t.id));+ pills.append(spotifyPill.el);+ } else {+ pills.append(buildPill(t, actions));+ }+ }pruneMiniBots();}+ spotifyPill?.sync();},};}diff --git a/windows/tests/fakedom.mjs b/windows/tests/fakedom.mjsindex a8869b44..3617e359 100644--- a/windows/tests/fakedom.mjs+++ b/windows/tests/fakedom.mjs@@ -70,6 +70,13 @@ class FakeElement {getAttribute(k) {return this.attributes.get(k) ?? null;}+ removeAttribute(k) {+ this.attributes.delete(k);+ }+ getBoundingClientRect() {+ return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 };+ }+ setPointerCapture() {}addEventListener(type, fn) {this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]);}diff --git a/windows/tests/pills.test.mjs b/windows/tests/pills.test.mjsindex 5c625995..3186d801 100644--- a/windows/tests/pills.test.mjs+++ b/windows/tests/pills.test.mjs@@ -39,6 +39,7 @@ test("the catalog holds the Mac's pills, in the Mac's order, with the Mac's valu["integration_calcom", "Cal.com", "#C9956A", "service", "Integration"],["integration_stripe", "Stripe", "#0570DE", "service", "Integration"],["integration_music", "Apple Music", "#FA2D48", "service", "Integration"],+ ["integration_spotify", "Spotify", "#1DB954", "service", "Integration"],];assert.deepEqual(PILL_CATALOG.map((p) => [p.id, p.name, p.color, p.category, p.subtitle]),@@ -72,7 +73,7 @@ test("IDs are unique", () => {assert.equal(new Set(ids).size, ids.length);});-test("this build leaves out what only macOS has, and Claude Desktop on Linux", () => {+test("this build leaves out what only macOS has, Claude Desktop on Linux and Spotify on Windows", () => {const windows = availablePills("windows").map((p) => p.id);const linux = availablePills("linux").map((p) => p.id);for (const id of ["integration_music"]) {@@ -87,7 +88,35 @@ test("this build leaves out what only macOS has, and Claude Desktop on Linux", (}assert.ok(windows.includes("agent_claude-desktop"));assert.ok(!linux.includes("agent_claude-desktop"));- assert.deepEqual(linux, windows.filter((id) => id !== "agent_claude-desktop"));+ // Spotify is read over MPRIS, which only Linux has.+ assert.ok(linux.includes("integration_spotify"));+ assert.ok(!windows.includes("integration_spotify"));+ assert.deepEqual(+ linux.filter((id) => id !== "integration_spotify"),+ windows.filter((id) => id !== "agent_claude-desktop"),+ );+});++test("Spotify: a Linux-only service with nothing to set up", () => {+ const def = pillDefinition("integration_spotify");+ assert.equal(def.support, "linux");+ assert.deepEqual(def.connect, { kind: "none" });+ assert.equal(def.category, "service");+ assert.ok(!isComingSoon("integration_spotify"));+ assert.ok(!isHookPill("integration_spotify"));+ assert.ok(!mainPillChoices("linux").some((p) => p.id === "integration_spotify"));+});++test("a Linux-only pill can be declared on Linux and is dropped on Windows", () => {+ const d = { mainPill: "integration_claude", activeIntegrations: ["integration_spotify", "integration_n8n"] };+ assert.deepEqual(sanitizeDeclared(d, "linux").activeIntegrations, ["integration_spotify", "integration_n8n"]);+ assert.deepEqual(sanitizeDeclared(d, "windows").activeIntegrations, ["integration_n8n"]);+ const empty = { mainPill: "integration_claude", activeIntegrations: [] };+ assert.deepEqual(toggleDeclared(empty, "integration_spotify", "linux"), ["integration_spotify"]);+ assert.equal(toggleDeclared(empty, "integration_spotify", "windows"), null);+ // And the other way round: Claude Desktop stays Windows only.+ assert.equal(toggleDeclared(empty, "agent_claude-desktop", "linux"), null);+ assert.deepEqual(toggleDeclared(empty, "agent_claude-desktop", "windows"), ["agent_claude-desktop"]);});test("no chat provider that works here says Coming soon", () => {diff --git a/windows/tests/spotify.test.mjs b/windows/tests/spotify.test.mjsnew file mode 100644index 00000000..36cd5d49--- /dev/null+++ b/windows/tests/spotify.test.mjs@@ -0,0 +1,304 @@+// The Spotify pill (Linux) and Mochi's dance: the page's rules in+// src/core/spotify.ts, the dance in src/mochi/engine.ts, the report handling in+// src/island/spotify.ts and the views in src/views/spotify.ts. The MPRIS side —+// metadata, position, the bus itself — is tested in src-tauri/src/spotify.rs.++import { beforeEach, test } from "node:test";+import assert from "node:assert/strict";+import { emit, sent } from "./tauri.mjs";+import { installFakeDom } from "./fakedom.mjs";+import {+ IDLE_SPOTIFY, SPOTIFY_ID, Spotify, currentArtwork, desktopDances, formatTime, isAd, islandDances,+ musicPlaying, spotifyPosition, volumeLevel, withPlaying,+} from "../src/core/spotify.ts";+import { BotEngine, danceTransform, stepDanceLevel } from "../src/mochi/engine.ts";+import { registerSpotifyHandlers } from "../src/island/spotify.ts";+import { buildSpotifyCard, buildSpotifyPill } from "../src/views/spotify.ts";+import { DEFAULT_SETTINGS, State } from "../src/core/state.ts";+import { lookup, setLanguage } from "../src/i18n/i18n.ts";++installFakeDom();++const track = (over = {}) => ({+ id: "spotify:track:abc", title: "Get Lucky", artist: "Daft Punk", album: "Random Access Memories",+ duration: 180, artUrl: "https://i.scdn.co/image/abc", ...over,+});++const playing = (over = {}) => ({+ ...IDLE_SPOTIFY, running: true, installed: true, track: track(), playing: true,+ position: 10, positionAt: 1_000, volume: 70, ...over,+});++// ── Position ──────────────────────────────────────────────────────────────────++test("the position runs on from its timestamp while playing, and stops at the end", () => {+ const s = playing();+ assert.equal(spotifyPosition(s, 1_000), 10);+ assert.equal(spotifyPosition(s, 3_500), 12.5);+ assert.equal(spotifyPosition(s, 0), 10, "a clock behind the anchor never moves it back");+ assert.equal(spotifyPosition(s, 1_000_000), 180, "capped at the track's length");+ assert.equal(spotifyPosition({ ...s, playing: false }, 60_000), 10, "paused, it stays put");+ assert.equal(spotifyPosition({ ...s, track: null }, 3_000), 12, "no length, no cap");+});++test("a play/pause click freezes or restarts the clock where it is", () => {+ const paused = withPlaying(playing(), false, 5_000);+ assert.equal(paused.playing, false);+ assert.equal(paused.position, 14);+ assert.equal(paused.positionAt, 5_000);+ assert.equal(spotifyPosition(paused, 9_000), 14);+ const again = withPlaying(paused, true, 9_000);+ assert.equal(spotifyPosition(again, 10_000), 15);+ const same = playing();+ assert.equal(withPlaying(same, true, 99), same, "no change, same object");+});++test("times read like the Mac's player", () => {+ assert.equal(formatTime(0), "0:00");+ assert.equal(formatTime(65.9), "1:05");+ assert.equal(formatTime(599), "9:59");+ assert.equal(formatTime(3725), "1:02:05");+ assert.equal(formatTime(-3), "0:00");+ assert.equal(formatTime(Number.NaN), "0:00");+});++test("the volume icon has the Mac's thresholds", () => {+ assert.deepEqual([0, 1, 33, 34, 66, 67, 100].map(volumeLevel), [0, 1, 1, 2, 2, 3, 3]);+});++test("ads are told by their id", () => {+ assert.ok(isAd(track({ id: "spotify:ad:123" })));+ assert.ok(!isAd(track()));+ assert.ok(!isAd(null));+});++test("a cover shows only on the track it belongs to", () => {+ Spotify.artwork = { artUrl: "https://i.scdn.co/image/abc", dataUrl: "data:image/jpeg;base64,AA" };+ assert.equal(currentArtwork(playing()), "data:image/jpeg;base64,AA");+ assert.equal(currentArtwork(playing({ track: track({ artUrl: "https://i.scdn.co/image/zzz" }) })), null);+ assert.equal(currentArtwork(playing({ track: null })), null);+ Spotify.artwork = null;+});++// ── When Mochi dances ─────────────────────────────────────────────────────────++test("music counts only when it plays on a declared Spotify pill", () => {+ assert.ok(musicPlaying(playing(), [SPOTIFY_ID]));+ assert.ok(!musicPlaying(playing(), ["integration_n8n"]));+ assert.ok(!musicPlaying(playing({ playing: false }), [SPOTIFY_ID]));+ assert.ok(!musicPlaying(playing({ track: null }), [SPOTIFY_ID]));+});++test("the island's Mochi dances by the Mac's rules", () => {+ const base = { music: true, state: "idle", mode: "compact", view: "overview", focusId: "integration_claude" };+ // Compact: whenever music plays, in the calm and busy states.+ for (const state of ["idle", "working", "thinking", "searching", "finished"]) {+ assert.ok(islandDances({ ...base, state }), state);+ }+ // An alert, an error, sleep or a daze win.+ for (const state of ["approval", "question", "error", "ratelimit", "sleeping", "dizzy"]) {+ assert.ok(!islandDances({ ...base, state }), state);+ }+ assert.ok(!islandDances({ ...base, music: false }));+ assert.ok(!islandDances({ ...base, mode: "hidden" }));+ // Expanded: only on the overview, with the music pill in front.+ assert.ok(!islandDances({ ...base, mode: "expanded" }));+ assert.ok(islandDances({ ...base, mode: "expanded", focusId: SPOTIFY_ID }));+ assert.ok(!islandDances({ ...base, mode: "expanded", focusId: SPOTIFY_ID, view: "prompt" }));+});++test("Mochi on the desktop dances by the compact island's rules", () => {+ assert.ok(desktopDances(true, "working"));+ assert.ok(!desktopDances(true, "approval"));+ assert.ok(!desktopDances(false, "idle"));+});++// ── The dance itself (BotEngine.applyDance) ───────────────────────────────────++test("the dance fades in over 0.3 s and out over 0.5 s", () => {+ assert.equal(stepDanceLevel(0, true, 0.15), 0.5);+ assert.equal(stepDanceLevel(0.9, true, 0.15), 1);+ assert.equal(stepDanceLevel(1, false, 0.25), 0.5);+ assert.equal(stepDanceLevel(0.1, false, 0.25), 0);+ assert.equal(stepDanceLevel(1, true, 0.05), 1);+});++test("112 BPM: still on the beat, highest half a beat later, nothing at level 0", () => {+ const R = 10;+ const onBeat = danceTransform(0, 1, R);+ assert.equal(onBeat.dx, 0);+ assert.equal(onBeat.dy, -0);+ assert.equal(onBeat.rotate, 0);+ assert.ok(Math.abs(onBeat.sx - 1.045) < 1e-9 && Math.abs(onBeat.sy - 0.94) < 1e-9, "squashed on landing");+ const top = danceTransform(0.5 * 60 / 112, 1, R);+ assert.ok(Math.abs(top.dy + 2) < 1e-9, "hops 0.2 R");+ assert.ok(Math.abs(top.dx - 0.8) < 1e-9 && Math.abs(top.rotate - 0.1) < 1e-9);+ assert.ok(Math.abs(top.sx - 1) < 1e-9 && Math.abs(top.sy - 1) < 1e-9);+ const off = danceTransform(0.3, 0, R);+ assert.deepEqual([off.dx, off.dy, off.rotate, off.sx, off.sy].map((v) => Math.abs(v)), [0, 0, 0, 1, 1]);+});++test("the engine dances only once asked, and keeps its frames going meanwhile", () => {+ const ops = [];+ const ctx = {+ translate: (x, y) => ops.push(["translate", x, y]),+ rotate: (a) => ops.push(["rotate", a]),+ scale: (x, y) => ops.push(["scale", x, y]),+ };+ const engine = new BotEngine();+ engine.applyDance(ctx, 100, 100);+ assert.deepEqual(ops, [], "not dancing: the context is left alone");+ engine.setDancing(true);+ engine.update(0.05);+ assert.ok(engine.dancingLevel > 0 && engine.busy);+ engine.applyDance(ctx, 100, 100);+ assert.deepEqual(ops.map((o) => o[0]), ["translate", "rotate", "scale", "translate"]);+ // Around the bottom of the body: back where it started.+ assert.equal(ops[3][1], -(50 + engine.ox * 30));+ engine.setDancing(false);+ for (let i = 0; i < 20; i++) engine.update(0.05);+ assert.equal(engine.dancingLevel, 0);+});++// ── Reports from Rust ─────────────────────────────────────────────────────────++const island = { reveals: 0, revealSilently() { this.reveals += 1; } };+registerSpotifyHandlers(island);++beforeEach(() => {+ setLanguage("en");+ State.settings = { ...DEFAULT_SETTINGS, activeIntegrations: [SPOTIFY_ID] };+ State.os = "linux";+ State.tasks = [];+ State.focusId = null;+ State.mode = "hidden";+ State.view = "overview";+ State.paused = false;+ State.loadIntegrationTasks();+ Spotify.state = { ...IDLE_SPOTIFY };+ Spotify.artwork = null;+ island.reveals = 0;+});++const spotifyTask = () => State.tasks.find((t) => t.id === SPOTIFY_ID);++test("the pill wears the track's title, and its own name when nothing plays", () => {+ assert.equal(spotifyTask().name, "Spotify");+ emit("spotify", playing());+ assert.equal(Spotify.state.track.title, "Get Lucky");+ assert.equal(spotifyTask().name, "Get Lucky");+ emit("spotify", playing({ track: track({ id: "spotify:ad:1", title: "" }) }));+ assert.equal(spotifyTask().name, "Advertisement");+ emit("spotify", { ...IDLE_SPOTIFY, running: true });+ assert.equal(spotifyTask().name, "Spotify");+});++test("music starting shows the hidden island once, silently; nothing on Windows-like setups", () => {+ emit("spotify", playing({ playing: false }));+ assert.equal(island.reveals, 0);+ emit("spotify", playing());+ assert.equal(island.reveals, 1);+ emit("spotify", playing({ position: 30 }));+ assert.equal(island.reveals, 1, "only on not playing → playing");+ assert.ok(State.spotifyPlaying);++ // Not declared: nothing dances, nothing shows.+ emit("spotify", { ...IDLE_SPOTIFY });+ State.settings.activeIntegrations = [];+ emit("spotify", playing());+ assert.equal(island.reveals, 1);+ assert.ok(!State.spotifyPlaying);+});++test("the cover arrives on its own event", () => {+ emit("spotify", playing());+ emit("spotify-artwork", { artUrl: "https://i.scdn.co/image/abc", dataUrl: "data:image/png;base64,AA" });+ assert.equal(currentArtwork(), "data:image/png;base64,AA");+});++test("the card reads the player again each time it comes on screen", () => {+ const before = sent("spotify_refresh").length;+ State.mode = "expanded";+ State.view = "overview";+ State.setFocus(SPOTIFY_ID);+ assert.equal(sent("spotify_refresh").length, before + 1);+ State.notify();+ assert.equal(sent("spotify_refresh").length, before + 1, "not again while it stays");+ State.mode = "compact";+ State.notify();+ State.mode = "expanded";+ State.notify();+ assert.equal(sent("spotify_refresh").length, before + 2);+});++// ── Views ─────────────────────────────────────────────────────────────────────++test("the idle card: not playing, or not installed with a way to get it", () => {+ const card = buildSpotifyCard();+ Spotify.state = { ...IDLE_SPOTIFY, installed: true };+ card.sync();+ assert.match(card.el.textContent, /Spotify.*Integration.*Not playing.*Open Spotify/);+ Spotify.state = { ...IDLE_SPOTIFY };+ card.sync();+ assert.match(card.el.textContent, /Spotify not installed.*Get Spotify/);+ card.el.find("BUTTON")[0].fire("click");+ assert.ok(sent("spotify_open").length > 0);++ setLanguage("fr");+ card.sync();+ assert.ok(card.el.textContent.includes(lookup("Get Spotify", "fr")));+});++test("the playing card: title, artist · album, times, and the controls", () => {+ const card = buildSpotifyCard();+ Spotify.state = playing({ playing: false, shuffle: true });+ card.sync();+ const text = card.el.textContent;+ assert.ok(text.includes("Get Lucky"));+ assert.ok(text.includes("Daft Punk · Random Access Memories"));+ assert.ok(text.includes("0:10") && text.includes("-2:50"));++ const [shuffle, prev, play, next, repeat] = card.el.querySelector("np-buttons").children;+ assert.equal(shuffle.title, "Shuffle on");+ assert.equal(repeat.title, "Repeat off");+ assert.equal(play.title, "Play");+ const before = sent("spotify_control").length;+ shuffle.fire("click");+ repeat.fire("click");+ prev.fire("click");+ next.fire("click");+ play.fire("click");+ assert.deepEqual(sent("spotify_control").slice(before), [+ { action: "shuffle", value: 0 },+ { action: "repeat", value: 1 },+ { action: "previous", value: null },+ { action: "next", value: null },+ { action: "playPause", value: null },+ ]);+ // The page shows the clicks at once.+ assert.equal(Spotify.state.shuffle, false);+ assert.equal(Spotify.state.repeat, true);+ assert.equal(Spotify.state.playing, true);++ Spotify.state = playing({ track: track({ id: "spotify:ad:9", title: "x", artist: "", album: "" }) });+ card.sync();+ assert.ok(card.el.textContent.includes("Advertisement"));+});++test("the pill shows play/pause and next on hover, only with a track", () => {+ const task = spotifyTask();+ const pill = buildSpotifyPill(task, () => {});+ pill.el.fire("mouseenter");+ assert.ok(!pill.el.classList.contains("controls"), "nothing loaded: no controls");+ Spotify.state = playing();+ pill.sync();+ assert.ok(pill.el.classList.contains("controls"));+ const [playBtn] = pill.el.querySelector("np-pill-controls").children;+ assert.equal(playBtn.title, "Pause");+ const before = sent("spotify_control").length;+ playBtn.fire("click");+ assert.deepEqual(sent("spotify_control").slice(before), [{ action: "playPause", value: null }]);+ assert.equal(Spotify.state.playing, false);+ pill.el.fire("mouseleave");+ assert.ok(!pill.el.classList.contains("controls"));+});