arnaucube
arnaucube/octo-tuiPublic Self-hosted repository
octo-tui/src/app.rs
src/app.rsRaw
   1use crate::{
   2    api::Api,
   3    artwork::Artwork,
   4    config,
   5    downloads::{Acquisition, Download, Phase},
   6    model::{Item, Song, View, home_items},
   7    player::{Playback, Player, PlayerEvent},
   8    playlists::{PlaylistChoice, PlaylistDialog, PlaylistTarget},
   9    theme::Theme,
  10};
  11use anyhow::Result;
  12use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
  13use ratatui::widgets::TableState;
  14use serde::{Deserialize, Serialize};
  15use serde_json::json;
  16use std::{
  17    collections::HashMap,
  18    path::PathBuf,
  19    sync::{
  20        Arc,
  21        mpsc::{self, Receiver, Sender},
  22    },
  23    time::{Duration, Instant},
  24};
  25
  26pub const NAV: &[&str] = &[
  27    "Home",
  28    "Search",
  29    "Artists",
  30    "Songs",
  31    "Playlists",
  32    "Genres",
  33    "Discover",
  34    "Stations",
  35    "Queue",
  36    "History",
  37];
  38#[derive(Clone)]
  39enum Job {
  40    Load(u64, View, bool),
  41    Star(Song, bool),
  42    Acquisitions,
  43    PlaylistChoices(u64),
  44    PlaylistAdd(u64, PlaylistTarget, String),
  45    ResolveLibrary(String, String),
  46}
  47enum Reply {
  48    Loaded(u64, Result<Vec<Item>>),
  49    Starred(Box<Song>, bool, Result<()>),
  50    Acquisitions(Result<Option<Vec<Acquisition>>>),
  51    PlaylistChoices(u64, Result<Vec<PlaylistChoice>>),
  52    PlaylistAdded(u64, PlaylistTarget, Result<()>),
  53    LibraryResolved(String, Result<Option<Box<Song>>>),
  54    NowPlayingFailed(String, anyhow::Error),
  55}
  56#[derive(Default, Serialize, Deserialize)]
  57struct Session {
  58    #[serde(default)]
  59    theme: Theme,
  60    queue: Vec<Song>,
  61    #[serde(default)]
  62    listening_history: Vec<Song>,
  63    volume: u8,
  64    #[serde(default)]
  65    library_only: bool,
  66}
  67
  68pub struct App {
  69    pub artwork: Artwork,
  70    pub theme: Theme,
  71    pub library_only: bool,
  72    pub view: View,
  73    pub items: Vec<Item>,
  74    pub table: TableState,
  75    pub nav: usize,
  76    pub sidebar: bool,
  77    pub queue: Vec<Song>,
  78    pub current: Option<usize>,
  79    pub position: f64,
  80    pub duration: f64,
  81    pub paused: bool,
  82    pub volume: u8,
  83    pub repeat: bool,
  84    pub status: String,
  85    pub input: Option<String>,
  86    pub server_search: bool,
  87    search_selection: Option<usize>,
  88    pub help: bool,
  89    pub help_scroll: u16,
  90    pub loading: bool,
  91    pub load_error: Option<String>,
  92    pub quit: bool,
  93    pub downloads: HashMap<String, Download>,
  94    pub playlist_dialog: Option<PlaylistDialog>,
  95    playlist_generation: u64,
  96    library_copies: HashMap<String, Song>,
  97    acquisition_poll_pending: bool,
  98    next_acquisition_poll: Instant,
  99    back_stack: Vec<(View, Vec<Item>, usize, bool)>,
 100    listening_history: Vec<Song>,
 101    pending_history: Option<Song>,
 102    queue_play_tokens: Vec<String>,
 103    history_ready: bool,
 104    now_playing: Option<Sender<String>>,
 105    tx: Sender<Job>,
 106    rx: Receiver<Reply>,
 107    generation: u64,
 108    api: Arc<Api>,
 109    player: Option<Box<dyn Playback>>,
 110    last_g: Option<Instant>,
 111    session_path: Option<PathBuf>,
 112}
 113
 114impl App {
 115    /// Server requests run off the UI thread; generations discard stale navigation responses.
 116    pub fn new(api: Arc<Api>, volume: u8) -> Self {
 117        let (tx, jobs) = mpsc::channel();
 118        let (results, rx) = mpsc::channel();
 119        let jobs = Arc::new(std::sync::Mutex::new(jobs));
 120        for _ in 0..3 {
 121            let jobs = Arc::clone(&jobs);
 122            let api = Arc::clone(&api);
 123            let results = results.clone();
 124            std::thread::spawn(move || {
 125                loop {
 126                    let job = jobs.lock().unwrap().recv();
 127                    let Ok(job) = job else {
 128                        break;
 129                    };
 130                    let reply = match job {
 131                        Job::Load(id, view, library_only) => {
 132                            Reply::Loaded(id, api.load_with_mode(&view, library_only))
 133                        }
 134                        Job::Acquisitions => Reply::Acquisitions(api.acquisitions()),
 135                        Job::ResolveLibrary(source, id) => Reply::LibraryResolved(
 136                            source,
 137                            api.library_song(&id).map(|song| song.map(Box::new)),
 138                        ),
 139                        Job::PlaylistChoices(id) => {
 140                            Reply::PlaylistChoices(id, api.playlist_choices())
 141                        }
 142                        Job::PlaylistAdd(id, target, song) => {
 143                            let result = api.add_to_playlist(&target, &song);
 144                            Reply::PlaylistAdded(id, target, result)
 145                        }
 146                        Job::Star(song, add) => {
 147                            let result = api
 148                                .call(
 149                                    if add { "star" } else { "unstar" },
 150                                    &[("id", song.id.clone())],
 151                                )
 152                                .map(|_| ());
 153                            Reply::Starred(Box::new(song), add, result)
 154                        }
 155                    };
 156                    if results.send(reply).is_err() {
 157                        break;
 158                    }
 159                }
 160            });
 161        }
 162
 163        let session_path = config::directory().join(format!("session-{}.json", api.session_key()));
 164        let (now_playing, tracks) = mpsc::channel::<String>();
 165        let playback_api = Arc::clone(&api);
 166        std::thread::spawn(move || {
 167            while let Ok(id) = tracks.recv() {
 168                // Serialize announcements and skip tracks superseded during a slow request.
 169                let id = tracks.try_iter().last().unwrap_or(id);
 170                if let Err(error) = playback_api.report_now_playing(&id)
 171                    && results.send(Reply::NowPlayingFailed(id, error)).is_err()
 172                {
 173                    break;
 174                }
 175            }
 176        });
 177        let mut app = Self::with_channels(api, volume, Some(session_path), tx, rx);
 178        app.now_playing = Some(now_playing);
 179        if app
 180            .queue
 181            .iter()
 182            .chain(&app.listening_history)
 183            .any(|song| song.is_external)
 184        {
 185            app.acquisition_poll_pending = app.tx.send(Job::Acquisitions).is_ok();
 186        }
 187        app
 188    }
 189
 190    /// Share state initialization with tests without connecting test state to audio or disk.
 191    fn with_channels(
 192        api: Arc<Api>,
 193        volume: u8,
 194        session_path: Option<PathBuf>,
 195        tx: Sender<Job>,
 196        rx: Receiver<Reply>,
 197    ) -> Self {
 198        let session = session_path
 199            .as_ref()
 200            .and_then(|p| std::fs::read(p).ok())
 201            .and_then(|s| serde_json::from_slice::<Session>(&s).ok());
 202        let saved_volume = session.as_ref().map(|s| s.volume).unwrap_or(volume);
 203        let saved_theme = session.as_ref().map(|s| s.theme).unwrap_or_default();
 204        let mut listening_history = session
 205            .as_ref()
 206            .map(|s| s.listening_history.clone())
 207            .unwrap_or_default();
 208        listening_history.truncate(1000);
 209        let mut app = Self {
 210            artwork: Artwork::default(),
 211            theme: saved_theme,
 212            library_only: session.as_ref().is_some_and(|s| s.library_only),
 213            view: View::Home,
 214            items: vec![],
 215            table: TableState::default().with_selected(0),
 216            nav: 0,
 217            sidebar: false,
 218            queue: session.map(|s| s.queue).unwrap_or_default(),
 219            current: None,
 220            position: 0.,
 221            duration: 0.,
 222            paused: false,
 223            volume: saved_volume.min(100),
 224            repeat: false,
 225            status: "Connecting…".into(),
 226            input: None,
 227            server_search: false,
 228            search_selection: None,
 229            help: false,
 230            help_scroll: 0,
 231            loading: false,
 232            load_error: None,
 233            quit: false,
 234            downloads: HashMap::new(),
 235            playlist_dialog: None,
 236            playlist_generation: 0,
 237            library_copies: HashMap::new(),
 238            acquisition_poll_pending: false,
 239            next_acquisition_poll: Instant::now(),
 240            back_stack: vec![],
 241            listening_history,
 242            pending_history: None,
 243            queue_play_tokens: vec![],
 244            history_ready: false,
 245            now_playing: None,
 246            tx,
 247            rx,
 248            generation: 0,
 249            api,
 250            player: None,
 251            last_g: None,
 252            session_path,
 253        };
 254        if app.library_only {
 255            app.prune_external_queue();
 256        }
 257        app.load();
 258        app
 259    }
 260    #[cfg(test)]
 261    pub fn for_tests() -> Self {
 262        let api = Arc::new(
 263            Api::new(crate::config::Config {
 264                server: "http://127.0.0.1:1".into(),
 265                api_key: "test-key".into(),
 266                ..Default::default()
 267            })
 268            .unwrap(),
 269        );
 270        let (tx, _jobs) = mpsc::channel();
 271        let (_results, rx) = mpsc::channel();
 272        let mut app = Self::with_channels(api, 70, None, tx, rx);
 273        app.player = Some(Box::new(crate::test_support::TestPlayback::default()));
 274        app
 275    }
 276    fn load(&mut self) {
 277        self.load_error = None;
 278        self.generation += 1;
 279        self.table.select(Some(0));
 280        if matches!(self.view, View::Home) {
 281            self.items = home_items();
 282            self.loading = false;
 283            self.status = "Choose a Home section · j/k move · Enter opens".into();
 284        } else if matches!(self.view, View::History) {
 285            self.items = self
 286                .listening_history
 287                .iter()
 288                .cloned()
 289                .map(Item::Song)
 290                .collect();
 291            self.filter_visible_items();
 292            self.loading = false;
 293            self.status = "Recently played songs · newest first · a adds to a playlist".into();
 294        } else if matches!(self.view, View::Queue) {
 295            self.items = self.queue.iter().cloned().map(Item::Song).collect();
 296            self.table.select(Some(
 297                self.current
 298                    .unwrap_or(0)
 299                    .min(self.queue.len().saturating_sub(1)),
 300            ));
 301            self.loading = false;
 302        } else {
 303            self.items.clear();
 304            self.loading = true;
 305            self.status = "Loading…".into();
 306            let _ = self.tx.send(Job::Load(
 307                self.generation,
 308                self.view.clone(),
 309                self.library_only,
 310            ));
 311        }
 312    }
 313    /// Keep visited collections so backing out does not require another network call.
 314    fn navigate(&mut self, view: View) {
 315        self.back_stack.push((
 316            self.view.clone(),
 317            self.items.clone(),
 318            self.table.selected().unwrap_or(0),
 319            self.library_only,
 320        ));
 321        self.view = view;
 322        self.sidebar = false;
 323        self.load();
 324    }
 325    fn back(&mut self) {
 326        if let Some((view, items, selection, library_only)) = self.back_stack.pop() {
 327            if library_only && !self.library_only {
 328                self.view = view;
 329                self.load();
 330                return;
 331            }
 332            self.generation += 1;
 333            self.loading = false;
 334            self.view = view;
 335            self.load_error = None;
 336            self.items = items;
 337            self.filter_visible_items();
 338            self.table.select(Some(selection));
 339            self.clamp_selection();
 340            if matches!(self.view, View::Queue) {
 341                self.refresh_queue();
 342            } else if matches!(self.view, View::History) {
 343                self.refresh_listening_history();
 344            }
 345        }
 346    }
 347    fn refresh_queue(&mut self) {
 348        self.sync_play_tokens();
 349        if matches!(self.view, View::Queue) {
 350            self.items = self.queue.iter().cloned().map(Item::Song).collect();
 351        }
 352        self.clamp_selection();
 353    }
 354    /// Apply the mode again when cached or in-flight results reach the browser.
 355    fn filter_visible_items(&mut self) {
 356        if self.library_only {
 357            self.items
 358                .retain(|item| !matches!(item, Item::Song(song) if song.is_external));
 359        }
 360    }
 361    /// Keep queue indices and playback tokens attached to their retained library entries.
 362    fn prune_external_queue(&mut self) {
 363        self.sync_play_tokens();
 364        let mut current = None;
 365        let mut index = 0;
 366        let mut tokens = std::mem::take(&mut self.queue_play_tokens).into_iter();
 367        self.queue.retain(|song| {
 368            let token = tokens.next().unwrap();
 369            let keep = !song.is_external;
 370            if keep {
 371                if self.current == Some(index) {
 372                    current = Some(self.queue_play_tokens.len());
 373                }
 374                self.queue_play_tokens.push(token);
 375            }
 376            index += 1;
 377            keep
 378        });
 379        if self.current.is_some() && current.is_none() {
 380            self.command(json!(["stop"]));
 381            self.pending_history = None;
 382            self.history_ready = false;
 383            self.position = 0.;
 384            self.duration = 0.;
 385            self.paused = false;
 386        }
 387        self.current = current;
 388    }
 389    fn toggle_library_only(&mut self) {
 390        self.library_only = !self.library_only;
 391        if self.library_only {
 392            self.prune_external_queue();
 393        }
 394        self.load();
 395        self.status = if self.library_only {
 396            "Library only · m includes online songs".into()
 397        } else {
 398            "Library and online songs · m switches to library only".into()
 399        };
 400        self.save();
 401    }
 402    fn clamp_selection(&mut self) {
 403        self.table.select(Some(
 404            self.table
 405                .selected()
 406                .unwrap_or(0)
 407                .min(self.items.len().saturating_sub(1)),
 408        ));
 409    }
 410    fn move_selection(&mut self, delta: isize) {
 411        if self.sidebar {
 412            self.nav = self.nav.saturating_add_signed(delta).min(NAV.len() - 1);
 413        } else {
 414            self.table.select(Some(
 415                self.table
 416                    .selected()
 417                    .unwrap_or(0)
 418                    .saturating_add_signed(delta)
 419                    .min(self.items.len().saturating_sub(1)),
 420            ));
 421        }
 422    }
 423    fn select_nav(&mut self) {
 424        let view = match self.nav {
 425            0 => View::Home,
 426            2 => View::Artists,
 427            1 => {
 428                self.server_search = true;
 429                self.input = Some(String::new());
 430                self.sidebar = false;
 431                return;
 432            }
 433            3 => View::Songs { offset: 0 },
 434            4 => View::Playlists,
 435            5 => View::Genres,
 436            6 => View::Discover,
 437            7 => View::Stations,
 438            8 => View::Queue,
 439            _ => View::History,
 440        };
 441        self.navigate(view);
 442    }
 443    fn open(&mut self) {
 444        if self.sidebar {
 445            self.select_nav();
 446            return;
 447        }
 448        let Some(item) = self.items.get(self.table.selected().unwrap_or(0)).cloned() else {
 449            return;
 450        };
 451        match item {
 452            Item::HomeSection(section) => self.navigate(section.view()),
 453            Item::Song(_) => {
 454                let index = self.table.selected().unwrap_or(0);
 455                if matches!(self.view, View::Queue) {
 456                    self.play(index);
 457                } else {
 458                    let songs: Vec<_> = self
 459                        .items
 460                        .iter()
 461                        .filter_map(|i| {
 462                            if let Item::Song(s) = i
 463                                && (!self.library_only || !s.is_external)
 464                            {
 465                                Some(s.clone())
 466                            } else {
 467                                None
 468                            }
 469                        })
 470                        .collect();
 471                    self.queue = songs;
 472                    self.queue_play_tokens.clear();
 473                    self.play(index);
 474                    self.save();
 475                }
 476            }
 477            Item::Album { id, .. } => self.navigate(View::Album(id)),
 478            Item::Artist { id, .. } => self.navigate(View::Artist(id)),
 479            Item::Playlist { id, .. } => self.navigate(View::Playlist(id)),
 480            Item::Genre(g) => self.navigate(View::Genre(g)),
 481            Item::Station { id, .. } => self.navigate(View::Station(id)),
 482        }
 483    }
 484    fn selected_song(&self) -> Option<Song> {
 485        match self.items.get(self.table.selected().unwrap_or(0)) {
 486            Some(Item::Song(s)) if !self.library_only || !s.is_external => Some(s.clone()),
 487            _ => None,
 488        }
 489    }
 490    /// Every queue occurrence owns a stable play identity, even when duplicate songs are reordered.
 491    fn sync_play_tokens(&mut self) {
 492        self.queue_play_tokens.truncate(self.queue.len());
 493        while self.queue_play_tokens.len() < self.queue.len() {
 494            self.queue_play_tokens
 495                .push(format!("{:032x}.0", rand::random::<u128>()));
 496        }
 497    }
 498    /// Resolve streams only at playback time so restored queues never reuse expired tokens.
 499    fn play(&mut self, index: usize) {
 500        let Some(song) = self.queue.get(index).cloned() else {
 501            return;
 502        };
 503        if self.library_only && song.is_external {
 504            self.status = "Library-only mode: external playback is disabled. Press m to include online songs.".into();
 505            return;
 506        }
 507        if self.player.is_none() {
 508            match Player::start(self.volume) {
 509                Ok(player) => self.player = Some(Box::new(player)),
 510                Err(e) => {
 511                    self.status = e.to_string();
 512                    return;
 513                }
 514            }
 515        }
 516        if matches!(self.view, View::Queue) && self.table.selected() == self.current {
 517            self.table.select(Some(index));
 518        }
 519        self.sync_play_tokens();
 520        self.pending_history = Some(song.clone());
 521        self.history_ready = false;
 522        self.current = Some(index);
 523        self.position = 0.;
 524        self.duration = song.duration as f64;
 525        self.paused = false;
 526        self.status = format!("{} · {}", song.title, song.artist);
 527        match self.api.url(
 528            "stream",
 529            &[
 530                ("id", song.id),
 531                ("format", "raw".into()),
 532                ("octoPlay", self.queue_play_tokens[index].clone()),
 533            ],
 534        ) {
 535            Ok(url) => {
 536                self.command(json!(["loadfile", url.as_str(), "replace"]));
 537                self.command(json!(["set_property", "pause", false]));
 538            }
 539            Err(e) => {
 540                self.status = e.to_string();
 541                self.current = None;
 542                self.pending_history = None;
 543            }
 544        }
 545    }
 546    fn command(&mut self, value: serde_json::Value) {
 547        if let Some(player) = &mut self.player
 548            && let Err(e) = player.command(value)
 549        {
 550            self.status = e.to_string();
 551        }
 552    }
 553    fn next(&mut self, delta: isize) {
 554        if let Some(index) = self.current {
 555            let next = index as isize + delta;
 556            if next >= 0 && (next as usize) < self.queue.len() {
 557                self.play(next as usize);
 558            } else if self.repeat && !self.queue.is_empty() {
 559                self.play(0);
 560            } else {
 561                self.current = None;
 562                self.pending_history = None;
 563                self.history_ready = false;
 564                self.command(json!(["stop"]));
 565                self.status = "Queue finished".into();
 566            }
 567        } else if !self.queue.is_empty() {
 568            self.play(0);
 569        }
 570    }
 571    /// Apply background results and playback events between terminal frames.
 572    pub fn tick(&mut self) {
 573        while let Ok(reply) = self.rx.try_recv() {
 574            match reply {
 575                Reply::Loaded(id, result) if id == self.generation => {
 576                    self.loading = false;
 577                    match result {
 578                        Ok(mut items) => {
 579                            for item in &mut items {
 580                                Self::apply_library_item(item, &self.library_copies);
 581                            }
 582                            self.items = items;
 583                            self.filter_visible_items();
 584                            self.find_in_view();
 585                            self.load_error = None;
 586                            self.status = format!(
 587                                "{} results · Enter opens or plays · ? help",
 588                                self.items.len()
 589                            );
 590                        }
 591                        Err(e) => {
 592                            self.load_error = Some(e.to_string());
 593                            self.status = e.to_string();
 594                        }
 595                    }
 596                }
 597                Reply::LibraryResolved(source, result) => {
 598                    if let Some(download) = self.downloads.get_mut(&source) {
 599                        download.resolve_pending = false;
 600                        download.next_resolve = Instant::now()
 601                            + Duration::from_secs(if result.is_err() { 15 } else { 5 });
 602                    }
 603                    if let Ok(Some(song)) = result {
 604                        self.install_library_copy(source, *song);
 605                    }
 606                }
 607                Reply::NowPlayingFailed(id, error)
 608                    if self
 609                        .current
 610                        .and_then(|index| self.queue.get(index))
 611                        .is_some_and(|song| song.id == id) =>
 612                {
 613                    self.status = format!("Now Playing report failed ({error})");
 614                }
 615                Reply::PlaylistChoices(id, result) => {
 616                    if let Some(dialog) = &mut self.playlist_dialog
 617                        && dialog.id == id
 618                    {
 619                        dialog.loading = false;
 620                        match result {
 621                            Ok(choices) => dialog.choices = choices,
 622                            Err(e) => dialog.error = Some(e.to_string()),
 623                        }
 624                    }
 625                }
 626                Reply::PlaylistAdded(id, target, result) => {
 627                    if self
 628                        .playlist_dialog
 629                        .as_ref()
 630                        .is_some_and(|dialog| dialog.id == id)
 631                    {
 632                        match result {
 633                            Ok(()) => {
 634                                self.playlist_dialog = None;
 635                                self.status = format!("Song added to playlist: {}", target.name());
 636                                if matches!(self.view, View::Playlists)
 637                                    || matches!((&self.view,&target),(View::Playlist(view_id),PlaylistTarget::Existing {id,..}) if view_id==id)
 638                                {
 639                                    self.load();
 640                                }
 641                            }
 642                            Err(e) => {
 643                                let dialog = self.playlist_dialog.as_mut().unwrap();
 644                                dialog.saving = false;
 645                                dialog.error = Some(e.to_string());
 646                            }
 647                        }
 648                    }
 649                }
 650                Reply::Starred(song, add, result) => match result {
 651                    Ok(()) => {
 652                        if song.is_external && add {
 653                            self.downloads
 654                                .entry(song.id.clone())
 655                                .or_insert_with(Download::requesting)
 656                                .phase = Phase::Requested;
 657                            self.next_acquisition_poll = Instant::now();
 658                        }
 659                        for item in &mut self.items {
 660                            if let Item::Song(s) = item
 661                                && s.id == song.id
 662                            {
 663                                s.starred = add.then(|| "starred".into());
 664                            }
 665                        }
 666                        for s in &mut self.queue {
 667                            if s.id == song.id {
 668                                s.starred = add.then(|| "starred".into());
 669                            }
 670                        }
 671                        self.save();
 672                        self.status = if song.is_external && add {
 673                            "Download requested; the library copy will be resolved automatically"
 674                                .into()
 675                        } else {
 676                            "Favorite updated".into()
 677                        };
 678                    }
 679                    Err(e) => {
 680                        if let Some(download) = self.downloads.get_mut(&song.id) {
 681                            download.phase = Phase::Failed;
 682                        }
 683                        self.status = e.to_string();
 684                    }
 685                },
 686                Reply::Acquisitions(result) => {
 687                    self.acquisition_poll_pending = false;
 688                    self.next_acquisition_poll =
 689                        Instant::now() + Duration::from_secs(if result.is_err() { 15 } else { 3 });
 690                    match result {
 691                        Ok(Some(entries)) => {
 692                            // Recover completed acquisitions for external entries restored in the saved queue.
 693                            for song in self
 694                                .queue
 695                                .iter()
 696                                .chain(&self.listening_history)
 697                                .filter(|song| song.is_external)
 698                            {
 699                                if self.downloads.contains_key(&song.id) {
 700                                    continue;
 701                                }
 702                                let id = song.id.strip_prefix("find:").unwrap_or(&song.id);
 703                                if let Some(entry) = entries
 704                                    .iter()
 705                                    .filter(|e| e.id == id)
 706                                    .max_by_key(|e| e.started_at.as_deref().unwrap_or(""))
 707                                {
 708                                    let mut download = Download::requesting();
 709                                    download.update(entry);
 710                                    self.downloads.insert(song.id.clone(), download);
 711                                }
 712                            }
 713                            for (id, download) in &mut self.downloads {
 714                                if !download.pollable() {
 715                                    continue;
 716                                }
 717                                let id = id.strip_prefix("find:").unwrap_or(id);
 718                                if let Some(entry) = entries
 719                                    .iter()
 720                                    .filter(|entry| entry.id == id)
 721                                    .max_by_key(|entry| entry.started_at.as_deref().unwrap_or(""))
 722                                {
 723                                    download.update(entry);
 724                                } else if download.last_seen.elapsed() > Duration::from_secs(60) {
 725                                    download.unavailable = true;
 726                                }
 727                            }
 728                        }
 729                        Ok(None) => {
 730                            for download in self.downloads.values_mut().filter(|d| d.pollable()) {
 731                                download.unavailable = true;
 732                            }
 733                        }
 734                        Err(_) => {}
 735                    }
 736                }
 737                _ => {}
 738            }
 739        }
 740        if !self.acquisition_poll_pending
 741            && Instant::now() >= self.next_acquisition_poll
 742            && self.downloads.values().any(Download::pollable)
 743        {
 744            self.acquisition_poll_pending = self.tx.send(Job::Acquisitions).is_ok();
 745        }
 746        for (source, download) in &mut self.downloads {
 747            if download.phase == Phase::Done
 748                && !download.library_resolved
 749                && !download.resolve_pending
 750                && Instant::now() >= download.next_resolve
 751            {
 752                let id = download
 753                    .library_id
 754                    .clone()
 755                    .unwrap_or_else(|| source.strip_prefix("find:").unwrap_or(source).into());
 756                download.resolve_pending = self
 757                    .tx
 758                    .send(Job::ResolveLibrary(source.clone(), id))
 759                    .is_ok();
 760            }
 761        }
 762        let events: Vec<_> = self
 763            .player
 764            .as_ref()
 765            .map(|p| p.drain_events())
 766            .unwrap_or_default();
 767        for event in events {
 768            match event {
 769                PlayerEvent::Loaded => self.history_ready = true,
 770                PlayerEvent::Position(p) => {
 771                    self.position = p.max(0.);
 772                    if p > 0.
 773                        && self.history_ready
 774                        && !self.paused
 775                        && let Some(song) = self.pending_history.take()
 776                    {
 777                        if !song.is_external
 778                            && !song.id.is_empty()
 779                            && let Some(reporter) = &self.now_playing
 780                        {
 781                            let _ = reporter.send(song.id.clone());
 782                        }
 783                        self.record_play(song);
 784                    }
 785                }
 786                PlayerEvent::Duration(d) => self.duration = d.max(0.),
 787                PlayerEvent::Paused(p) => self.paused = p,
 788                PlayerEvent::Finished => self.next(1),
 789                PlayerEvent::Error(e) => {
 790                    self.status = e;
 791                    self.current = None;
 792                    self.pending_history = None;
 793                    self.history_ready = false;
 794                }
 795            }
 796        }
 797        let cover = self
 798            .current
 799            .and_then(|i| self.queue.get(i))
 800            .and_then(|s| Item::Song(s.clone()).cover());
 801        self.artwork.set_background(self.theme.palette().bg);
 802        self.artwork.update(cover);
 803    }
 804
 805    /// Keep recently heard songs unique and newest first, independently of the playback queue.
 806    fn record_play(&mut self, mut song: Song) {
 807        if let Some(library) = self.library_copies.get(&song.id) {
 808            song = library.clone();
 809        }
 810        self.listening_history
 811            .retain(|previous| previous.id != song.id);
 812        self.listening_history.insert(0, song);
 813        self.listening_history.truncate(1000);
 814        if matches!(self.view, View::History) {
 815            self.refresh_listening_history();
 816        }
 817        self.save();
 818    }
 819    fn refresh_listening_history(&mut self) {
 820        let selected = self.selected_song().map(|s| s.id);
 821        self.items = self
 822            .listening_history
 823            .iter()
 824            .cloned()
 825            .map(Item::Song)
 826            .collect();
 827        self.filter_visible_items();
 828        self.table.select(Some(
 829            selected
 830                .and_then(|id| {
 831                    self.items
 832                        .iter()
 833                        .position(|item| matches!(item, Item::Song(song) if song.id == id))
 834                })
 835                .unwrap_or(0),
 836        ));
 837    }
 838    fn apply_library_item(item: &mut Item, copies: &HashMap<String, Song>) {
 839        if let Item::Song(song) = item
 840            && let Some(library) = copies.get(&song.id)
 841        {
 842            *song = library.clone();
 843        }
 844    }
 845    /// Replace every cached copy by server ID, preserving queue order and the active mpv stream.
 846    fn install_library_copy(&mut self, source: String, mut song: Song) {
 847        if song.is_external || song.id.is_empty() {
 848            return;
 849        }
 850        // Keep recommendation provenance; it is independent of where playback comes from.
 851        if song.octo_suggested_by.is_none() {
 852            song.octo_suggested_by = self
 853                .queue
 854                .iter()
 855                .find(|s| s.id == source)
 856                .and_then(|s| s.octo_suggested_by.clone())
 857                .or_else(|| {
 858                    self.items.iter().find_map(|item| match item {
 859                        Item::Song(s) if s.id == source => s.octo_suggested_by.clone(),
 860                        _ => None,
 861                    })
 862                });
 863        }
 864        self.library_copies.insert(source.clone(), song.clone());
 865        if let Some(download) = self.downloads.get_mut(&source) {
 866            download.library_resolved = true;
 867        }
 868        for item in &mut self.items {
 869            Self::apply_library_item(item, &self.library_copies);
 870        }
 871        for queued in &mut self.queue {
 872            if let Some(library) = self.library_copies.get(&queued.id) {
 873                *queued = library.clone();
 874            }
 875        }
 876        for played in &mut self.listening_history {
 877            if let Some(library) = self.library_copies.get(&played.id) {
 878                *played = library.clone();
 879            }
 880        }
 881        let mut seen = std::collections::HashSet::new();
 882        self.listening_history
 883            .retain(|song| seen.insert(song.id.clone()));
 884        if let Some(pending) = &mut self.pending_history
 885            && let Some(library) = self.library_copies.get(&pending.id)
 886        {
 887            *pending = library.clone();
 888        }
 889        for (_, items, _, _) in &mut self.back_stack {
 890            for item in items {
 891                Self::apply_library_item(item, &self.library_copies);
 892            }
 893        }
 894        if let Some(dialog) = &mut self.playlist_dialog
 895            && dialog.song.id == source
 896        {
 897            dialog.song = song;
 898            if let Some(target) = dialog.pending_target.take()
 899                && self
 900                    .tx
 901                    .send(Job::PlaylistAdd(dialog.id, target, dialog.song.id.clone()))
 902                    .is_err()
 903            {
 904                dialog.saving = false;
 905                dialog.error = Some("Cannot add song: server worker unavailable".into());
 906            }
 907        }
 908        self.save();
 909    }
 910    /// Persist only song metadata; signed stream URLs and credentials never enter the session.
 911    pub fn save(&mut self) {
 912        let Some(path) = &self.session_path else {
 913            return;
 914        };
 915        let result = (|| -> Result<()> {
 916            std::fs::create_dir_all(path.parent().unwrap())?;
 917            let temp = path.with_extension(format!("json.{}.tmp", std::process::id()));
 918            std::fs::write(
 919                &temp,
 920                serde_json::to_vec(&Session {
 921                    queue: self.queue.clone(),
 922                    listening_history: self.listening_history.clone(),
 923                    theme: self.theme,
 924                    library_only: self.library_only,
 925                    volume: self.volume,
 926                })?,
 927            )?;
 928            std::fs::rename(temp, path)?;
 929            Ok(())
 930        })();
 931        if result.is_err() {
 932            self.status = "Could not save queue to configuration directory".into();
 933        }
 934    }
 935    /// Capture the song when opening the modal so playback and browsing cannot change its target.
 936    fn open_playlist_dialog(&mut self) {
 937        let Some(song) = self.selected_song() else {
 938            self.status = "Select a song to add to a playlist".into();
 939            return;
 940        };
 941        self.playlist_generation += 1;
 942        let mut dialog = PlaylistDialog::new(self.playlist_generation, song);
 943        if self.tx.send(Job::PlaylistChoices(dialog.id)).is_err() {
 944            dialog.loading = false;
 945            dialog.error = Some("Cannot load playlists: server worker unavailable".into());
 946        }
 947        self.playlist_dialog = Some(dialog);
 948    }
 949    /// Modal input stays isolated from browsing, playback shortcuts and duplicate submissions.
 950    fn playlist_key(&mut self, key: KeyEvent) {
 951        let dialog = self.playlist_dialog.as_mut().unwrap();
 952        if dialog.saving {
 953            if key.code == KeyCode::Esc && dialog.pending_target.is_some() {
 954                self.playlist_dialog = None;
 955            }
 956            return;
 957        }
 958        if let Some(name) = &mut dialog.new_name {
 959            match key.code {
 960                KeyCode::Esc => {
 961                    dialog.new_name = None;
 962                    dialog.error = None;
 963                    return;
 964                }
 965                KeyCode::Backspace => {
 966                    name.pop();
 967                    return;
 968                }
 969                KeyCode::Char(c) => {
 970                    name.push(c);
 971                    dialog.error = None;
 972                    return;
 973                }
 974                KeyCode::Enter => {}
 975                _ => return,
 976            }
 977        } else {
 978            match key.code {
 979                KeyCode::Esc | KeyCode::Char('q') => {
 980                    self.playlist_dialog = None;
 981                    return;
 982                }
 983                KeyCode::Down | KeyCode::Char('j') => {
 984                    dialog.selected = (dialog.selected + 1).min(dialog.choices.len());
 985                    dialog.error = None;
 986                    return;
 987                }
 988                KeyCode::Up | KeyCode::Char('k') => {
 989                    dialog.selected = dialog.selected.saturating_sub(1);
 990                    dialog.error = None;
 991                    return;
 992                }
 993                KeyCode::Char('g') | KeyCode::Home => {
 994                    dialog.selected = 0;
 995                    return;
 996                }
 997                KeyCode::Char('G') | KeyCode::End => {
 998                    dialog.selected = dialog.choices.len();
 999                    return;
1000                }
1001                KeyCode::Char('n') => {
1002                    dialog.new_name = Some(String::new());
1003                    dialog.error = None;
1004                    return;
1005                }
1006                KeyCode::Enter if dialog.selected == 0 => {
1007                    dialog.new_name = Some(String::new());
1008                    dialog.error = None;
1009                    return;
1010                }
1011                KeyCode::Enter => {}
1012                _ => return,
1013            }
1014        }
1015        let target = if let Some(name) = &dialog.new_name {
1016            let name = name.trim();
1017            if name.is_empty() {
1018                dialog.error = Some("Enter a playlist name".into());
1019                return;
1020            }
1021            PlaylistTarget::New { name: name.into() }
1022        } else {
1023            let Some(choice) = dialog.choices.get(dialog.selected.saturating_sub(1)) else {
1024                return;
1025            };
1026            if let Some(error) = choice.addition_error() {
1027                dialog.error = Some(error.into());
1028                return;
1029            }
1030            PlaylistTarget::Existing {
1031                id: choice.id.clone(),
1032                name: choice.name.clone(),
1033            }
1034        };
1035        if self
1036            .downloads
1037            .get(&dialog.song.id)
1038            .is_some_and(|d| d.phase == Phase::Done && !d.library_resolved)
1039        {
1040            dialog.pending_target = Some(target);
1041            dialog.saving = true;
1042            dialog.error = None;
1043            return;
1044        }
1045        if self
1046            .tx
1047            .send(Job::PlaylistAdd(dialog.id, target, dialog.song.id.clone()))
1048            .is_err()
1049        {
1050            dialog.error = Some("Cannot add song: server worker unavailable".into());
1051            return;
1052        }
1053        dialog.saving = true;
1054        dialog.error = None;
1055    }
1056    /// Find the first matching loaded row without changing the collection or calling the server.
1057    fn find_in_view(&mut self) {
1058        if self.server_search {
1059            return;
1060        }
1061        let Some(query) = &self.input else {
1062            return;
1063        };
1064        let query = query.to_lowercase();
1065        if query.is_empty() {
1066            self.table.select(self.search_selection);
1067            self.clamp_selection();
1068        } else if let Some(index) = self.items.iter().position(|item| {
1069            item.title().to_lowercase().contains(&query)
1070                || item.detail().to_lowercase().contains(&query)
1071        }) {
1072            self.table.select(Some(index));
1073        }
1074    }
1075    /// Input mode consumes text before normal Vim-style command dispatch.
1076    pub fn key(&mut self, key: KeyEvent) {
1077        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
1078            self.quit = true;
1079            return;
1080        }
1081        if self.playlist_dialog.is_some() {
1082            self.playlist_key(key);
1083            return;
1084        }
1085        if let Some(input) = &mut self.input {
1086            match key.code {
1087                KeyCode::Esc => {
1088                    self.input = None;
1089                    if !self.server_search {
1090                        self.table.select(self.search_selection);
1091                        self.clamp_selection();
1092                    }
1093                }
1094                KeyCode::Enter => {
1095                    let query = input.trim().to_owned();
1096                    self.input = None;
1097                    if self.server_search && !query.is_empty() {
1098                        self.navigate(View::Search(query));
1099                    }
1100                }
1101                KeyCode::Backspace => {
1102                    input.pop();
1103                    self.find_in_view();
1104                }
1105                KeyCode::Char(c) => {
1106                    input.push(c);
1107                    self.find_in_view();
1108                }
1109                _ => {}
1110            }
1111            return;
1112        }
1113        if self.help {
1114            match key.code {
1115                KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q') => self.help = false,
1116                KeyCode::Down | KeyCode::Char('j') => {
1117                    self.help_scroll = self.help_scroll.saturating_add(1)
1118                }
1119                KeyCode::Up | KeyCode::Char('k') => {
1120                    self.help_scroll = self.help_scroll.saturating_sub(1)
1121                }
1122                KeyCode::PageDown => self.help_scroll = self.help_scroll.saturating_add(10),
1123                KeyCode::PageUp => self.help_scroll = self.help_scroll.saturating_sub(10),
1124                _ => {}
1125            }
1126            return;
1127        }
1128        match key.code {
1129            KeyCode::Char('q') => self.quit = true,
1130            KeyCode::Char('?') => {
1131                self.help = true;
1132                self.help_scroll = 0;
1133            }
1134            KeyCode::Char('/') => {
1135                self.server_search = false;
1136                self.search_selection = self.table.selected();
1137                self.input = Some(String::new());
1138                self.sidebar = false;
1139            }
1140            KeyCode::Tab => self.sidebar = !self.sidebar,
1141            KeyCode::Char('h') | KeyCode::Left => {
1142                if self.sidebar {
1143                    self.back();
1144                } else {
1145                    self.sidebar = true;
1146                }
1147            }
1148            KeyCode::Char('l') | KeyCode::Right | KeyCode::Enter => self.open(),
1149            KeyCode::Esc | KeyCode::Backspace => self.back(),
1150            KeyCode::Char('j') | KeyCode::Down => self.move_selection(1),
1151            KeyCode::Char('k') | KeyCode::Up => self.move_selection(-1),
1152            KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1153                self.move_selection(10)
1154            }
1155            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1156                self.move_selection(-10)
1157            }
1158            KeyCode::Char('G') => {
1159                if self.sidebar {
1160                    self.nav = NAV.len() - 1;
1161                } else {
1162                    self.table.select(Some(self.items.len().saturating_sub(1)));
1163                }
1164            }
1165            KeyCode::Char('g') => {
1166                if self
1167                    .last_g
1168                    .is_some_and(|t| t.elapsed() < Duration::from_millis(600))
1169                {
1170                    if self.sidebar {
1171                        self.nav = 0;
1172                    } else {
1173                        self.table.select(Some(0));
1174                    }
1175                    self.last_g = None;
1176                } else {
1177                    self.last_g = Some(Instant::now());
1178                }
1179            }
1180            KeyCode::Char(c @ '0'..='9') => {
1181                self.nav = (c as u8 - b'0') as usize;
1182                self.select_nav();
1183            }
1184            KeyCode::Char(' ') => {
1185                if self.current.is_some() {
1186                    self.paused = !self.paused;
1187                    self.command(json!(["set_property", "pause", self.paused]));
1188                } else if !self.queue.is_empty() {
1189                    self.play(0);
1190                }
1191            }
1192            KeyCode::Char('L') => self.next(1),
1193            KeyCode::Char('H') => self.next(-1),
1194            KeyCode::Char(']') | KeyCode::Char('[') => {
1195                let amount = if key.code == KeyCode::Char(']') {
1196                    10.
1197                } else {
1198                    -10.
1199                };
1200                self.position = (self.position + amount).clamp(0., self.duration.max(0.));
1201                self.command(json!(["seek", amount, "relative"]));
1202            }
1203            KeyCode::Char('=') | KeyCode::Char('-') => {
1204                self.volume = self
1205                    .volume
1206                    .saturating_add_signed(if key.code == KeyCode::Char('=') {
1207                        5
1208                    } else {
1209                        -5
1210                    })
1211                    .min(100);
1212                self.command(json!(["set_property", "volume", self.volume]));
1213                self.save();
1214            }
1215            KeyCode::Char('m') => self.toggle_library_only(),
1216            KeyCode::Char('i') => {
1217                if let Some(song) = self.selected_song() {
1218                    if let Some(id) = song.artist_id.filter(|id| !id.trim().is_empty()) {
1219                        self.navigate(View::Artist(id));
1220                    } else if !song.artist.trim().is_empty() {
1221                        self.navigate(View::ArtistByName(song.artist.trim().into()));
1222                    } else {
1223                        self.status = "No artist information is available for this song.".into();
1224                    }
1225                } else {
1226                    self.status = "Select a song to open its artist.".into();
1227                }
1228            }
1229            KeyCode::Char('a') => self.open_playlist_dialog(),
1230            KeyCode::Char('e') => {
1231                if let Some(song) = self.selected_song() {
1232                    self.queue.push(song);
1233                    self.refresh_queue();
1234                    self.save();
1235                    self.status = "Added to queue".into();
1236                }
1237            }
1238            KeyCode::Char('A') => {
1239                self.queue.extend(self.items.iter().filter_map(|i| {
1240                    if let Item::Song(s) = i
1241                        && (!self.library_only || !s.is_external)
1242                    {
1243                        Some(s.clone())
1244                    } else {
1245                        None
1246                    }
1247                }));
1248                self.refresh_queue();
1249                self.save();
1250                self.status = "Added visible tracks to queue".into();
1251            }
1252            KeyCode::Char('x') if matches!(self.view, View::Queue) => {
1253                let i = self.table.selected().unwrap_or(0);
1254                if i < self.queue.len() {
1255                    self.sync_play_tokens();
1256                    self.queue_play_tokens.remove(i);
1257                    self.queue.remove(i);
1258                    if let Some(current) = self.current {
1259                        if i == current {
1260                            self.current = None;
1261                            self.command(json!(["stop"]));
1262                        } else if i < current {
1263                            self.current = Some(current - 1);
1264                        }
1265                    }
1266                    self.refresh_queue();
1267                    self.save();
1268                }
1269            }
1270            KeyCode::Char('J') | KeyCode::Char('K') if matches!(self.view, View::Queue) => {
1271                let i = self.table.selected().unwrap_or(0);
1272                let j = i.saturating_add_signed(if key.code == KeyCode::Char('J') {
1273                    1
1274                } else {
1275                    -1
1276                });
1277                if i < self.queue.len() && j < self.queue.len() {
1278                    self.sync_play_tokens();
1279                    self.queue_play_tokens.swap(i, j);
1280                    self.queue.swap(i, j);
1281                    if self.current == Some(i) {
1282                        self.current = Some(j);
1283                    } else if self.current == Some(j) {
1284                        self.current = Some(i);
1285                    }
1286                    self.refresh_queue();
1287                    self.table.select(Some(j));
1288                    self.save();
1289                }
1290            }
1291            KeyCode::Char('f') | KeyCode::Char('+') | KeyCode::Char('d') => {
1292                if let Some(song) = self.selected_song() {
1293                    if key.code == KeyCode::Char('d') && !song.is_external {
1294                        self.status = "Already in library".into();
1295                        return;
1296                    }
1297                    let download = song.is_external
1298                        && matches!(key.code, KeyCode::Char('d') | KeyCode::Char('+'));
1299                    let add = matches!(key.code, KeyCode::Char('+') | KeyCode::Char('d'))
1300                        || song.starred.is_none();
1301                    if song.is_external && add {
1302                        if let Some(existing) = self.downloads.get(&song.id) {
1303                            if existing.in_flight() && !existing.unavailable {
1304                                self.status = format!("Download: {}", existing.detail());
1305                                return;
1306                            }
1307                            if existing.phase == Phase::Done {
1308                                self.status =
1309                                    "Downloaded; waiting for the indexed library copy".into();
1310                                return;
1311                            }
1312                        }
1313                        self.downloads
1314                            .insert(song.id.clone(), Download::requesting());
1315                    }
1316                    if self.tx.send(Job::Star(song.clone(), add)).is_err() {
1317                        if let Some(download) = self.downloads.get_mut(&song.id) {
1318                            download.phase = Phase::Failed;
1319                        }
1320                        self.status = "Could not send request to server worker".into();
1321                        return;
1322                    }
1323                    self.status = if download {
1324                        "Requesting download to server library…"
1325                    } else {
1326                        "Updating server…"
1327                    }
1328                    .into();
1329                }
1330            }
1331            KeyCode::Char('r') => {
1332                if let Some(song) = self.selected_song() {
1333                    self.navigate(View::Radio(song.id));
1334                }
1335            }
1336            KeyCode::Char('R') => self.load(),
1337            KeyCode::Char('t') => {
1338                self.theme = self.theme.next();
1339                self.save();
1340                self.status = format!("Theme: {} · t cycles themes", self.theme.name());
1341            }
1342            KeyCode::Char('s') => {
1343                use rand::seq::SliceRandom;
1344                self.sync_play_tokens();
1345                let start = self.current.map_or(0, |current| current + 1);
1346                let mut entries: Vec<_> = self
1347                    .queue
1348                    .drain(start..)
1349                    .zip(self.queue_play_tokens.drain(start..))
1350                    .collect();
1351                entries.shuffle(&mut rand::thread_rng());
1352                for (song, token) in entries {
1353                    self.queue.push(song);
1354                    self.queue_play_tokens.push(token);
1355                }
1356                self.refresh_queue();
1357                self.save();
1358                self.status = "Shuffled upcoming queue".into();
1359            }
1360            KeyCode::Char('z') => {
1361                self.repeat = !self.repeat;
1362            }
1363            KeyCode::Char('o') => {
1364                if let View::Albums { kind, offset } = &mut self.view {
1365                    let kinds = [
1366                        "newest",
1367                        "alphabeticalByName",
1368                        "alphabeticalByArtist",
1369                        "frequent",
1370                        "recent",
1371                        "random",
1372                    ];
1373                    let index = kinds.iter().position(|k| k == kind).unwrap_or(0);
1374                    *kind = kinds[(index + 1) % kinds.len()].into();
1375                    *offset = 0;
1376                    self.load();
1377                }
1378            }
1379            KeyCode::Char('>') | KeyCode::Char('<') => {
1380                let forward = key.code == KeyCode::Char('>');
1381                match &mut self.view {
1382                    View::Albums { offset, .. } | View::Songs { offset } => {
1383                        *offset = if forward {
1384                            offset.saturating_add(100)
1385                        } else {
1386                            offset.saturating_sub(100)
1387                        };
1388                        self.load();
1389                    }
1390                    _ => {}
1391                }
1392            }
1393            _ => {}
1394        }
1395    }
1396}
1397
1398#[cfg(test)]
1399mod tests {
1400    use super::*;
1401    fn key(app: &mut App, c: char) {
1402        app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));
1403    }
1404    #[test]
1405    fn play_tokens_follow_queue_entries_and_survive_replay_and_reorder() {
1406        let mut app = App::for_tests();
1407        app.queue = crate::test_support::songs();
1408        app.sync_play_tokens();
1409        let playback = crate::test_support::TestPlayback::default();
1410        let commands = playback.commands.clone();
1411        app.player = Some(Box::new(playback));
1412        let tokens = app.queue_play_tokens.clone();
1413        assert_ne!(tokens[0], tokens[1]);
1414        app.play(0);
1415        app.play(0);
1416        assert_eq!(app.queue_play_tokens, tokens);
1417        let commands = commands.lock().unwrap();
1418        let loads: Vec<_> = commands.iter().filter(|c| c[0] == "loadfile").collect();
1419        assert_eq!(loads.len(), 2);
1420        for load in loads {
1421            let url = reqwest::Url::parse(load[1].as_str().unwrap()).unwrap();
1422            assert!(url.query_pairs().any(|(k, v)| k == "format" && v == "raw"));
1423            assert!(
1424                url.query_pairs()
1425                    .any(|(k, v)| k == "octoPlay" && v == tokens[0])
1426            );
1427        }
1428        drop(commands);
1429        app.view = View::Queue;
1430        app.refresh_queue();
1431        app.table.select(Some(0));
1432        key(&mut app, 'J');
1433        assert_eq!(app.queue_play_tokens[1], tokens[0]);
1434        app.table.select(Some(0));
1435        key(&mut app, 'x');
1436        assert_eq!(app.queue_play_tokens[0], tokens[0]);
1437        key(&mut app, 's');
1438        assert_eq!(app.queue.len(), app.queue_play_tokens.len());
1439        for token in &app.queue_play_tokens {
1440            assert!(tokens.contains(token));
1441        }
1442    }
1443
1444    #[test]
1445    fn artwork_follows_playback_independently_of_cursor_and_view() {
1446        let mut app = App::for_tests();
1447        app.artwork.enabled = true;
1448        app.queue = crate::test_support::songs();
1449        app.items = app.queue.iter().cloned().map(Item::Song).collect();
1450        app.table.select(Some(2));
1451        app.tick();
1452        assert!(app.artwork.title.is_empty());
1453
1454        app.play(0);
1455        app.tick();
1456        assert_eq!(app.artwork.title, "Track 0");
1457        key(&mut app, 'j');
1458        app.tick();
1459        assert_eq!(app.artwork.title, "Track 0");
1460        app.sidebar = true;
1461        app.tick();
1462        assert_eq!(app.artwork.title, "Track 0");
1463        app.view = View::Albums {
1464            kind: "newest".into(),
1465            offset: 0,
1466        };
1467        app.items = vec![Item::Album {
1468            id: "other".into(),
1469            name: "Other album".into(),
1470            artist: "Artist".into(),
1471            cover_art: Some("other-cover".into()),
1472        }];
1473        app.table.select(Some(0));
1474        app.sidebar = false;
1475        app.paused = true;
1476        app.tick();
1477        assert_eq!(app.artwork.title, "Track 0");
1478
1479        app.play(1);
1480        app.tick();
1481        assert_eq!(app.artwork.title, "Track 1");
1482        app.current = None;
1483        app.tick();
1484        assert!(app.artwork.title.is_empty());
1485        assert!(app.artwork.protocol.is_none());
1486    }
1487
1488    #[test]
1489    fn artist_shortcut_uses_song_id_or_name_and_preserves_playback_and_back_navigation() {
1490        let mut app = App::for_tests();
1491        let song: Song = serde_json::from_value(
1492            json!({"id":"song","title":"Selected","artist":"Artist","artistId":"artist-id"}),
1493        )
1494        .unwrap();
1495        app.queue = crate::test_support::songs();
1496        app.current = Some(1);
1497        app.view = View::Search("Selected".into());
1498        app.items = vec![Item::Song(song)];
1499        app.table.select(Some(0));
1500        key(&mut app, 'i');
1501        assert!(matches!(&app.view, View::Artist(id) if id == "artist-id"));
1502        assert_eq!(app.current, Some(1));
1503        assert_eq!(app.queue.len(), 8);
1504        app.back();
1505        assert!(matches!(&app.view, View::Search(query) if query == "Selected"));
1506        assert_eq!(app.selected_song().unwrap().id, "song");
1507        if let Item::Song(song) = &mut app.items[0] {
1508            song.artist_id = None;
1509        }
1510        key(&mut app, 'i');
1511        assert!(matches!(&app.view, View::ArtistByName(name) if name == "Artist"));
1512        app.back();
1513        if let Item::Song(song) = &mut app.items[0] {
1514            song.artist.clear();
1515        }
1516        key(&mut app, 'i');
1517        assert!(app.status.contains("No artist information"));
1518        assert!(matches!(app.view, View::Search(_)));
1519        app.items.clear();
1520        key(&mut app, 'i');
1521        assert!(app.status.contains("Select a song"));
1522    }
1523
1524    #[test]
1525    fn library_mode_filters_all_server_views_after_resolving_downloaded_copies() {
1526        let views = [
1527            View::Search("test".into()),
1528            View::Songs { offset: 0 },
1529            View::Album("album".into()),
1530            View::Artist("artist".into()),
1531            View::ArtistByName("Artist".into()),
1532            View::Playlist("playlist".into()),
1533            View::Discover,
1534            View::Radio("seed".into()),
1535            View::Station("station".into()),
1536            View::Genre("Rock".into()),
1537        ];
1538        for view in views {
1539            let mut app = App::for_tests();
1540            app.library_only = true;
1541            let songs = crate::test_support::songs();
1542            app.library_copies
1543                .insert(songs[4].id.clone(), songs[1].clone());
1544            let (tx, rx) = mpsc::channel();
1545            app.rx = rx;
1546            app.navigate(view);
1547            tx.send(Reply::Loaded(
1548                app.generation,
1549                Ok(vec![
1550                    Item::Song(songs[0].clone()),
1551                    Item::Song(songs[4].clone()),
1552                    Item::Song(songs[5].clone()),
1553                    Item::Artist {
1554                        id: "artist".into(),
1555                        name: "Artist".into(),
1556                    },
1557                ]),
1558            ))
1559            .unwrap();
1560            app.tick();
1561            assert_eq!(app.items.len(), 3);
1562            assert!(matches!(&app.items[0],Item::Song(song) if song.id == songs[0].id));
1563            assert!(matches!(&app.items[1],Item::Song(song) if song.id == songs[1].id));
1564            assert!(matches!(&app.items[2], Item::Artist { .. }));
1565        }
1566    }
1567
1568    #[test]
1569    fn enabling_library_mode_preserves_local_playback_and_stops_external_playback() {
1570        for current in [0, 3] {
1571            let mut app = App::for_tests();
1572            let songs = crate::test_support::songs();
1573            app.queue = vec![
1574                songs[4].clone(),
1575                songs[0].clone(),
1576                songs[5].clone(),
1577                songs[1].clone(),
1578            ];
1579            let playback = crate::test_support::TestPlayback::default();
1580            let commands = playback.commands.clone();
1581            app.player = Some(Box::new(playback));
1582            app.play(current);
1583            let tokens = app.queue_play_tokens.clone();
1584            commands.lock().unwrap().clear();
1585            key(&mut app, 'm');
1586            assert!(app.library_only);
1587            assert_eq!(
1588                app.queue
1589                    .iter()
1590                    .map(|song| song.id.as_str())
1591                    .collect::<Vec<_>>(),
1592                ["track-0", "track-1"]
1593            );
1594            assert_eq!(
1595                app.queue_play_tokens,
1596                vec![tokens[1].clone(), tokens[3].clone()]
1597            );
1598            if current == 3 {
1599                assert_eq!(app.current, Some(1));
1600                assert!(commands.lock().unwrap().is_empty());
1601            } else {
1602                assert_eq!(app.current, None);
1603                assert!(app.pending_history.is_none());
1604                assert_eq!(*commands.lock().unwrap(), vec![json!(["stop"])]);
1605            }
1606            commands.lock().unwrap().clear();
1607            app.queue.push(songs[4].clone());
1608            app.play(2);
1609            assert!(commands.lock().unwrap().is_empty());
1610            assert!(app.status.contains("external playback is disabled"));
1611        }
1612    }
1613
1614    #[test]
1615    fn library_mode_filters_cached_history_and_ignores_results_from_before_toggle() {
1616        let mut app = App::for_tests();
1617        let songs = crate::test_support::songs();
1618        app.listening_history = songs.clone();
1619        app.view = View::Search("test".into());
1620        app.items = songs.iter().cloned().map(Item::Song).collect();
1621        app.table.select(Some(7));
1622        app.navigate(View::Home);
1623        key(&mut app, 'm');
1624        app.back();
1625        assert_eq!(app.items.len(), 4);
1626        assert_eq!(app.table.selected(), Some(3));
1627        key(&mut app, '9');
1628        assert_eq!(app.items.len(), 4);
1629        assert_eq!(app.listening_history.len(), 8);
1630        app.table.select(Some(2));
1631        app.refresh_listening_history();
1632        assert_eq!(app.selected_song().unwrap().id, "track-2");
1633        key(&mut app, 'm');
1634        assert_eq!(app.items.len(), 8);
1635
1636        let (tx, rx) = mpsc::channel();
1637        app.rx = rx;
1638        app.navigate(View::Search("test".into()));
1639        let old = app.generation;
1640        key(&mut app, 'm');
1641        tx.send(Reply::Loaded(
1642            old,
1643            Ok(songs.iter().cloned().map(Item::Song).collect()),
1644        ))
1645        .unwrap();
1646        app.tick();
1647        assert!(app.items.is_empty());
1648        assert!(app.loading);
1649        tx.send(Reply::Loaded(
1650            app.generation,
1651            Ok(songs.into_iter().map(Item::Song).collect()),
1652        ))
1653        .unwrap();
1654        app.tick();
1655        assert_eq!(app.items.len(), 4);
1656    }
1657
1658    #[test]
1659    fn backing_into_library_only_cache_after_disabling_mode_fetches_online_results_again() {
1660        let mut app = App::for_tests();
1661        app.library_only = true;
1662        app.view = View::Search("artist".into());
1663        app.items = vec![Item::Song(crate::test_support::songs()[0].clone())];
1664        app.navigate(View::Home);
1665        key(&mut app, 'm');
1666        let (tx, rx) = mpsc::channel();
1667        app.tx = tx;
1668        app.back();
1669        assert!(matches!(
1670            rx.try_recv().unwrap(),
1671            Job::Load(_, View::Search(_), false)
1672        ));
1673        assert!(app.loading);
1674    }
1675
1676    #[test]
1677    fn library_mode_is_saved_and_restored_per_session_without_losing_history() {
1678        let mut app = App::for_tests();
1679        let directory =
1680            std::env::temp_dir().join(format!("octo-mode-test-{:x}", rand::random::<u64>()));
1681        let path = directory.join("session.json");
1682        app.session_path = Some(path.clone());
1683        app.queue = crate::test_support::songs();
1684        app.listening_history = crate::test_support::songs();
1685        key(&mut app, 'm');
1686        let (tx, _) = mpsc::channel();
1687        let (_, rx) = mpsc::channel();
1688        let mut restored = App::with_channels(app.api.clone(), 70, Some(path), tx, rx);
1689        assert!(restored.library_only);
1690        assert_eq!(restored.queue.len(), 4);
1691        assert_eq!(restored.listening_history.len(), 8);
1692        assert!(restored.current.is_none());
1693        key(&mut restored, '9');
1694        assert_eq!(restored.items.len(), 4);
1695        key(&mut restored, 'm');
1696        assert_eq!(restored.items.len(), 8);
1697        std::fs::remove_dir_all(directory).unwrap();
1698        let old: Session = serde_json::from_value(json!({"queue":[],"volume":70})).unwrap();
1699        assert!(!old.library_only);
1700    }
1701
1702    #[test]
1703    fn home_opens_offline_and_keeps_number_shortcuts() {
1704        let mut app = App::for_tests();
1705        assert!(matches!(app.view, View::Home));
1706        assert!(!app.loading);
1707        assert_eq!(app.items[0].title(), "Recently played");
1708        // Returning Home is local even if a previous server request is outstanding.
1709        key(&mut app, '3');
1710        assert!(matches!(app.view, View::Songs { .. }));
1711        key(&mut app, '0');
1712        assert!(matches!(app.view, View::Home));
1713        assert!(!app.loading);
1714        key(&mut app, '2');
1715        assert!(matches!(app.view, View::Artists));
1716        key(&mut app, '1');
1717        assert_eq!(app.input.as_deref(), Some(""));
1718        assert!(app.server_search);
1719        app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
1720        for c in '1'..='9' {
1721            key(&mut app, c);
1722            assert_eq!(app.nav, c.to_digit(10).unwrap() as usize);
1723            if app.input.is_some() {
1724                app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
1725            }
1726        }
1727        assert!(matches!(app.view, View::History));
1728    }
1729    #[test]
1730    fn home_album_shelves_support_paging_and_back() {
1731        let mut app = App::for_tests();
1732        for (index, kind) in [
1733            (0, "recent"),
1734            (1, "newest"),
1735            (2, "frequent"),
1736            (3, "random"),
1737            (4, "highest"),
1738        ] {
1739            key(&mut app, '0');
1740            app.table.select(Some(index));
1741            app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
1742            assert!(matches!(&app.view,View::Albums {kind:k,offset:0} if k==kind));
1743            key(&mut app, '>');
1744            assert!(matches!(&app.view,View::Albums {kind:k,offset:100} if k==kind));
1745            app.back();
1746            assert!(matches!(app.view, View::Home));
1747            assert_eq!(app.table.selected(), Some(index));
1748        }
1749        app.table.select(Some(6));
1750        app.open();
1751        assert!(matches!(app.view, View::Discover));
1752    }
1753    #[test]
1754    fn browse_play_and_remove_current_queue_item() {
1755        let mut app = App::for_tests();
1756        app.table.select(Some(1));
1757        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
1758        app.items = vec![Item::Album {
1759            id: "album-1".into(),
1760            name: "Test album".into(),
1761            artist: "Test artist".into(),
1762            cover_art: None,
1763        }];
1764        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
1765        assert!(matches!(app.view, View::Album(_)));
1766        app.items = vec![Item::Song(crate::test_support::songs().remove(0))];
1767        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
1768        assert_eq!(app.current, Some(0));
1769        key(&mut app, '8');
1770        key(&mut app, 'x');
1771        assert!(app.queue.is_empty());
1772        assert_eq!(app.current, None);
1773        key(&mut app, 'j');
1774        assert_eq!(app.table.selected(), Some(0));
1775    }
1776    #[test]
1777    fn queue_reordering_preserves_current_song() {
1778        let mut app = App::for_tests();
1779        key(&mut app, '3');
1780        app.items = crate::test_support::songs()
1781            .into_iter()
1782            .map(Item::Song)
1783            .collect();
1784        key(&mut app, 'A');
1785        key(&mut app, '8');
1786        app.play(1);
1787        let id = app.queue[1].id.clone();
1788        app.table.select(Some(1));
1789        key(&mut app, 'J');
1790        assert_eq!(app.current, Some(2));
1791        assert_eq!(app.queue[2].id, id);
1792        key(&mut app, 's');
1793        assert_eq!(app.queue[2].id, id);
1794    }
1795    #[test]
1796    fn old_navigation_response_cannot_replace_new_view() {
1797        let mut app = App::for_tests();
1798        let (tx, rx) = mpsc::channel();
1799        app.rx = rx;
1800        let stale = app.generation;
1801        key(&mut app, '6');
1802        tx.send(Reply::Loaded(
1803            app.generation,
1804            Ok(crate::test_support::songs()
1805                .into_iter()
1806                .map(Item::Song)
1807                .collect()),
1808        ))
1809        .unwrap();
1810        tx.send(Reply::Loaded(stale, Ok(vec![]))).unwrap();
1811        app.tick();
1812        assert!(!app.items.is_empty());
1813        assert!(matches!(app.view, View::Discover));
1814        tx.send(Reply::Loaded(
1815            app.generation,
1816            Err(anyhow::anyhow!("Offline")),
1817        ))
1818        .unwrap();
1819        app.tick();
1820        assert_eq!(app.status, "Offline");
1821        assert!(!app.loading);
1822    }
1823    #[test]
1824    fn shifted_vim_keys_change_tracks_without_changing_browse_selection() {
1825        let mut app = App::for_tests();
1826        key(&mut app, '3');
1827        app.items = crate::test_support::songs()
1828            .into_iter()
1829            .map(Item::Song)
1830            .collect();
1831        key(&mut app, 'A');
1832        app.play(1);
1833        let selection = app.table.selected();
1834        app.key(KeyEvent::new(KeyCode::Char('L'), KeyModifiers::SHIFT));
1835        assert_eq!(app.current, Some(2));
1836        app.key(KeyEvent::new(KeyCode::Char('H'), KeyModifiers::SHIFT));
1837        assert_eq!(app.current, Some(1));
1838        assert_eq!(app.table.selected(), selection);
1839        key(&mut app, 'n');
1840        key(&mut app, 'p');
1841        assert_eq!(app.current, Some(1));
1842    }
1843    #[test]
1844    fn queue_cursor_follows_playback_until_user_browses_elsewhere() {
1845        let mut app = App::for_tests();
1846        app.queue = crate::test_support::songs();
1847        app.play(4);
1848        key(&mut app, '8');
1849        assert_eq!(app.table.selected(), Some(4));
1850        key(&mut app, 'L');
1851        assert_eq!(app.table.selected(), Some(5));
1852        key(&mut app, 'k');
1853        key(&mut app, 'L');
1854        assert_eq!(app.current, Some(6));
1855        assert_eq!(app.table.selected(), Some(4));
1856    }
1857    #[test]
1858    fn repeat_and_end_of_queue_are_explicit() {
1859        let mut app = App::for_tests();
1860        key(&mut app, '3');
1861        app.items = crate::test_support::songs()
1862            .into_iter()
1863            .map(Item::Song)
1864            .collect();
1865        key(&mut app, 'A');
1866        app.play(app.queue.len() - 1);
1867        app.next(1);
1868        assert!(app.current.is_none());
1869        app.repeat = true;
1870        app.play(app.queue.len() - 1);
1871        app.next(1);
1872        assert_eq!(app.current, Some(0));
1873        key(&mut app, ' ');
1874        assert!(app.paused);
1875    }
1876    #[test]
1877    fn download_shortcut_requests_external_song_only() {
1878        let mut app = App::for_tests();
1879        let (tx, rx) = mpsc::channel();
1880        app.tx = tx;
1881        // Use local view data so this test never connects to a server.
1882        app.items = crate::test_support::songs()
1883            .into_iter()
1884            .map(Item::Song)
1885            .collect();
1886        app.table.select(Some(0));
1887        key(&mut app, 'd');
1888        assert_eq!(app.status, "Already in library");
1889        assert!(rx.try_recv().is_err());
1890        app.table.select(Some(4));
1891        key(&mut app, 'd');
1892        match rx.try_recv().unwrap() {
1893            Job::Star(song, true) => assert_eq!(song.id, "track-4"),
1894            _ => panic!("Expected acquisition request"),
1895        }
1896        app.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
1897        assert!(rx.try_recv().is_err());
1898    }
1899    #[test]
1900    fn download_request_progress_completion_and_duplicate_keys() {
1901        let mut app = App::for_tests();
1902        let (jobs_tx, jobs_rx) = mpsc::channel();
1903        app.tx = jobs_tx;
1904        let (reply_tx, reply_rx) = mpsc::channel();
1905        app.rx = reply_rx;
1906        let song = crate::test_support::songs().remove(4);
1907        app.items = vec![Item::Song(song.clone())];
1908        key(&mut app, 'd');
1909        assert_eq!(app.downloads[&song.id].phase, Phase::Requesting);
1910        assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Star(_, true)));
1911        key(&mut app, '+');
1912        assert!(jobs_rx.try_recv().is_err());
1913        reply_tx
1914            .send(Reply::Starred(Box::new(song.clone()), true, Ok(())))
1915            .unwrap();
1916        app.tick();
1917        assert_eq!(app.downloads[&song.id].phase, Phase::Requested);
1918        assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Acquisitions));
1919        reply_tx
1920            .send(Reply::Acquisitions(Ok(Some(vec![Acquisition {
1921                id: song.id.clone(),
1922                state: "downloading".into(),
1923                progress: Some(0.42),
1924                source: Some("Soulseek".into()),
1925                ..Default::default()
1926            }]))))
1927            .unwrap();
1928        app.tick();
1929        assert_eq!(app.downloads[&song.id].label(), "↓ 42%");
1930        app.queue = vec![song.clone()];
1931        key(&mut app, '8');
1932        assert!(app.downloads[&song.id].detail().contains("Soulseek"));
1933        reply_tx
1934            .send(Reply::Acquisitions(Ok(Some(vec![Acquisition {
1935                id: song.id.clone(),
1936                state: "done".into(),
1937                ..Default::default()
1938            }]))))
1939            .unwrap();
1940        app.tick();
1941        assert_eq!(app.downloads[&song.id].phase, Phase::Done);
1942        assert!(matches!(
1943            jobs_rx.try_recv().unwrap(),
1944            Job::ResolveLibrary(_, _)
1945        ));
1946        reply_tx
1947            .send(Reply::LibraryResolved(
1948                song.id.clone(),
1949                Ok(Some(Box::new(Song {
1950                    id: "library-track".into(),
1951                    title: song.title.clone(),
1952                    ..Default::default()
1953                }))),
1954            ))
1955            .unwrap();
1956        app.tick();
1957        key(&mut app, 'd');
1958        assert!(jobs_rx.try_recv().is_err());
1959    }
1960    #[test]
1961    fn download_failures_can_retry_and_unsupported_status_stays_requested() {
1962        let mut app = App::for_tests();
1963        let song = crate::test_support::songs().remove(4);
1964        let (jobs_tx, jobs_rx) = mpsc::channel();
1965        app.tx = jobs_tx;
1966        let (reply_tx, reply_rx) = mpsc::channel();
1967        app.rx = reply_rx;
1968        app.items = vec![Item::Song(song.clone())];
1969        key(&mut app, '+');
1970        let _ = jobs_rx.recv().unwrap();
1971        reply_tx
1972            .send(Reply::Starred(
1973                Box::new(song.clone()),
1974                true,
1975                Err(anyhow::anyhow!("Rejected")),
1976            ))
1977            .unwrap();
1978        app.tick();
1979        assert_eq!(app.downloads[&song.id].phase, Phase::Failed);
1980        key(&mut app, 'd');
1981        assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Star(_, true)));
1982        reply_tx
1983            .send(Reply::Starred(Box::new(song.clone()), true, Ok(())))
1984            .unwrap();
1985        app.tick();
1986        let _ = jobs_rx.recv().unwrap();
1987        reply_tx.send(Reply::Acquisitions(Ok(None))).unwrap();
1988        app.tick();
1989        assert_eq!(app.downloads[&song.id].phase, Phase::Requested);
1990        assert!(
1991            app.downloads[&song.id]
1992                .detail()
1993                .contains("server status unavailable")
1994        );
1995        assert!(!app.downloads[&song.id].pollable());
1996    }
1997    #[test]
1998    fn library_copy_updates_queue_duplicates_history_and_late_results_without_restarting_audio() {
1999        let mut app = App::for_tests();
2000        let remote = crate::test_support::songs().remove(4);
2001        let directory =
2002            std::env::temp_dir().join(format!("octo-queue-test-{:x}", rand::random::<u64>()));
2003        app.session_path = Some(directory.join("session.json"));
2004        app.listening_history = vec![remote.clone()];
2005        app.queue = vec![remote.clone(), remote.clone()];
2006        app.current = Some(0);
2007        app.position = 12.;
2008        app.view = View::Queue;
2009        app.items = app.queue.iter().cloned().map(Item::Song).collect();
2010        app.back_stack.push((
2011            View::Songs { offset: 0 },
2012            vec![Item::Song(remote.clone())],
2013            0,
2014            false,
2015        ));
2016        let commands = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2017        app.player = Some(Box::new(crate::test_support::TestPlayback {
2018            commands: commands.clone(),
2019            ..Default::default()
2020        }));
2021        let (job_tx, job_rx) = mpsc::channel();
2022        app.tx = job_tx;
2023        let (reply_tx, reply_rx) = mpsc::channel();
2024        app.rx = reply_rx;
2025        reply_tx
2026            .send(Reply::Acquisitions(Ok(Some(vec![Acquisition {
2027                id: remote.id.clone(),
2028                state: "done".into(),
2029                library_id: Some("library-42".into()),
2030                ..Default::default()
2031            }]))))
2032            .unwrap();
2033        app.tick();
2034        assert!(
2035            matches!(job_rx.try_recv().unwrap(),Job::ResolveLibrary(source,id) if source==remote.id && id=="library-42")
2036        );
2037        assert!(app.queue[0].is_external);
2038        reply_tx
2039            .send(Reply::LibraryResolved(remote.id.clone(), Ok(None)))
2040            .unwrap();
2041        app.tick();
2042        assert!(app.queue[0].is_external);
2043        assert!(!app.downloads[&remote.id].library_resolved);
2044        let library = Song {
2045            id: "library-42".into(),
2046            title: remote.title.clone(),
2047            album: "Local album".into(),
2048            ..Default::default()
2049        };
2050        reply_tx
2051            .send(Reply::LibraryResolved(
2052                remote.id.clone(),
2053                Ok(Some(Box::new(library))),
2054            ))
2055            .unwrap();
2056        app.tick();
2057        assert!(
2058            app.queue
2059                .iter()
2060                .all(|s| s.id == "library-42" && !s.is_external)
2061        );
2062        assert_eq!(app.items[0].playback_source(), "Library");
2063        assert_eq!(app.back_stack[0].1[0].playback_source(), "Library");
2064        assert_eq!(app.listening_history[0].id, "library-42");
2065        assert!(!app.listening_history[0].is_external);
2066        assert_eq!(app.current, Some(0));
2067        assert_eq!(app.position, 12.);
2068        assert!(commands.lock().unwrap().is_empty());
2069        reply_tx
2070            .send(Reply::Loaded(app.generation, Ok(vec![Item::Song(remote)])))
2071            .unwrap();
2072        app.tick();
2073        assert_eq!(app.items[0].playback_source(), "Library");
2074        let saved: Session =
2075            serde_json::from_slice(&std::fs::read(directory.join("session.json")).unwrap())
2076                .unwrap();
2077        assert!(
2078            saved
2079                .queue
2080                .iter()
2081                .all(|song| song.id == "library-42" && !song.is_external)
2082        );
2083        std::fs::remove_dir_all(directory).unwrap();
2084        app.play(1);
2085        let messages = commands.lock().unwrap();
2086        let url = reqwest::Url::parse(messages[0][1].as_str().unwrap()).unwrap();
2087        assert!(
2088            url.query_pairs()
2089                .any(|(key, value)| key == "id" && value == "library-42")
2090        );
2091    }
2092    #[test]
2093    fn playlist_submission_waits_for_indexing_and_sends_library_id_only() {
2094        let mut app = App::for_tests();
2095        let remote = crate::test_support::songs().remove(4);
2096        app.items = vec![Item::Song(remote.clone())];
2097        app.queue = vec![remote.clone()];
2098        let mut download = Download::requesting();
2099        download.update(&Acquisition {
2100            state: "done".into(),
2101            library_id: Some("local-song".into()),
2102            ..Default::default()
2103        });
2104        app.downloads.insert(remote.id.clone(), download);
2105        app.next_acquisition_poll = Instant::now() + Duration::from_secs(60);
2106        let (job_tx, job_rx) = mpsc::channel();
2107        app.tx = job_tx;
2108        let (reply_tx, reply_rx) = mpsc::channel();
2109        app.rx = reply_rx;
2110        key(&mut app, 'a');
2111        let Job::PlaylistChoices(dialog_id) = job_rx.recv().unwrap() else {
2112            unreachable!()
2113        };
2114        reply_tx
2115            .send(Reply::PlaylistChoices(
2116                dialog_id,
2117                Ok(vec![PlaylistChoice {
2118                    id: "playlist".into(),
2119                    name: "Evening".into(),
2120                    ..Default::default()
2121                }]),
2122            ))
2123            .unwrap();
2124        app.tick();
2125        assert!(matches!(job_rx.recv().unwrap(),Job::ResolveLibrary(_,id) if id=="local-song"));
2126        key(&mut app, 'j');
2127        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2128        assert!(
2129            app.playlist_dialog
2130                .as_ref()
2131                .unwrap()
2132                .pending_target
2133                .is_some()
2134        );
2135        assert!(job_rx.try_recv().is_err());
2136        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2137        assert!(job_rx.try_recv().is_err());
2138        reply_tx
2139            .send(Reply::LibraryResolved(
2140                remote.id.clone(),
2141                Ok(Some(Box::new(Song {
2142                    id: "local-song".into(),
2143                    title: remote.title,
2144                    ..Default::default()
2145                }))),
2146            ))
2147            .unwrap();
2148        app.tick();
2149        assert!(
2150            matches!(job_rx.recv().unwrap(),Job::PlaylistAdd(id,_,song) if id==dialog_id && song=="local-song")
2151        );
2152        assert_eq!(app.queue[0].id, "local-song");
2153        assert!(!app.queue[0].is_external);
2154    }
2155    #[test]
2156    fn cancelling_index_wait_never_submits_the_playlist_change() {
2157        let mut app = App::for_tests();
2158        let remote = crate::test_support::songs().remove(4);
2159        app.items = vec![Item::Song(remote.clone())];
2160        let (job_tx, job_rx) = mpsc::channel();
2161        app.tx = job_tx;
2162        let (reply_tx, reply_rx) = mpsc::channel();
2163        app.rx = reply_rx;
2164        key(&mut app, 'a');
2165        let _ = job_rx.recv().unwrap();
2166        let mut download = Download::requesting();
2167        download.phase = Phase::Done;
2168        download.resolve_pending = true;
2169        app.downloads.insert(remote.id.clone(), download);
2170        key(&mut app, 'n');
2171        for c in "New list".chars() {
2172            key(&mut app, c);
2173        }
2174        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2175        assert!(
2176            app.playlist_dialog
2177                .as_ref()
2178                .unwrap()
2179                .pending_target
2180                .is_some()
2181        );
2182        app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
2183        assert!(app.playlist_dialog.is_none());
2184        reply_tx
2185            .send(Reply::LibraryResolved(
2186                remote.id,
2187                Ok(Some(Box::new(Song {
2188                    id: "local-song".into(),
2189                    ..Default::default()
2190                }))),
2191            ))
2192            .unwrap();
2193        app.tick();
2194        assert!(job_rx.try_recv().is_err());
2195    }
2196    #[test]
2197    fn readonly_playlist_stays_visible_but_normal_playlist_can_be_added_to() {
2198        let mut app = App::for_tests();
2199        app.items = vec![Item::Song(crate::test_support::songs().remove(0))];
2200        let (job_tx, job_rx) = mpsc::channel();
2201        app.tx = job_tx;
2202        let (reply_tx, reply_rx) = mpsc::channel();
2203        app.rx = reply_rx;
2204        key(&mut app, 'a');
2205        let Job::PlaylistChoices(id) = job_rx.recv().unwrap() else {
2206            unreachable!()
2207        };
2208        reply_tx
2209            .send(Reply::PlaylistChoices(
2210                id,
2211                Ok(vec![
2212                    PlaylistChoice {
2213                        id: "station".into(),
2214                        name: "Station".into(),
2215                        readonly: true,
2216                        ..Default::default()
2217                    },
2218                    PlaylistChoice {
2219                        id: "mine".into(),
2220                        name: "My playlist".into(),
2221                        readonly: false,
2222                        ..Default::default()
2223                    },
2224                ]),
2225            ))
2226            .unwrap();
2227        app.tick();
2228        assert_eq!(app.playlist_dialog.as_ref().unwrap().choices.len(), 2);
2229        key(&mut app, 'j');
2230        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2231        assert!(job_rx.try_recv().is_err());
2232        assert!(
2233            app.playlist_dialog
2234                .as_ref()
2235                .unwrap()
2236                .error
2237                .as_deref()
2238                .unwrap()
2239                .contains("read-only")
2240        );
2241        key(&mut app, 'j');
2242        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2243        assert!(
2244            matches!(job_rx.recv().unwrap(),Job::PlaylistAdd(_,PlaylistTarget::Existing {id,..},_) if id=="mine")
2245        );
2246    }
2247    #[test]
2248    fn playlist_picker_appends_captured_song_and_preserves_queue() {
2249        let mut app = App::for_tests();
2250        app.view = View::Songs { offset: 0 };
2251        app.items = crate::test_support::songs()
2252            .into_iter()
2253            .map(Item::Song)
2254            .collect();
2255        let (job_tx, job_rx) = mpsc::channel();
2256        app.tx = job_tx;
2257        let (reply_tx, reply_rx) = mpsc::channel();
2258        app.rx = reply_rx;
2259        key(&mut app, 'a');
2260        assert!(app.queue.is_empty());
2261        let Job::PlaylistChoices(id) = job_rx.try_recv().unwrap() else {
2262            panic!("Expected playlist list request")
2263        };
2264        reply_tx
2265            .send(Reply::PlaylistChoices(
2266                id,
2267                Ok(vec![PlaylistChoice {
2268                    id: "list-1".into(),
2269                    name: "Evening".into(),
2270                    readonly: false,
2271                    ..Default::default()
2272                }]),
2273            ))
2274            .unwrap();
2275        app.tick();
2276        key(&mut app, 'j');
2277        assert_eq!(app.table.selected(), Some(0));
2278        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2279        let Job::PlaylistAdd(request, target, song) = job_rx.try_recv().unwrap() else {
2280            panic!("Expected playlist append")
2281        };
2282        assert_eq!(song, "track-0");
2283        assert!(matches!(&target,PlaylistTarget::Existing {id,..} if id=="list-1"));
2284        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2285        assert!(job_rx.try_recv().is_err());
2286        reply_tx
2287            .send(Reply::PlaylistAdded(
2288                request,
2289                target.clone(),
2290                Err(anyhow::anyhow!("Permission denied")),
2291            ))
2292            .unwrap();
2293        app.tick();
2294        assert!(
2295            app.playlist_dialog
2296                .as_ref()
2297                .unwrap()
2298                .error
2299                .as_deref()
2300                .unwrap()
2301                .contains("Permission denied")
2302        );
2303        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2304        assert!(matches!(
2305            job_rx.try_recv().unwrap(),
2306            Job::PlaylistAdd(_, _, _)
2307        ));
2308        reply_tx
2309            .send(Reply::PlaylistAdded(request, target, Ok(())))
2310            .unwrap();
2311        app.tick();
2312        assert!(app.playlist_dialog.is_none());
2313        assert!(app.status.contains("Evening"));
2314        assert!(app.queue.is_empty());
2315        key(&mut app, 'e');
2316        assert_eq!(app.queue[0].id, "track-0");
2317    }
2318    #[test]
2319    fn new_playlist_name_is_text_input_and_blank_names_do_not_submit() {
2320        let mut app = App::for_tests();
2321        app.items = vec![Item::Song(crate::test_support::songs().remove(0))];
2322        let (job_tx, job_rx) = mpsc::channel();
2323        app.tx = job_tx;
2324        let (reply_tx, reply_rx) = mpsc::channel();
2325        app.rx = reply_rx;
2326        key(&mut app, 'a');
2327        let _ = job_rx.recv().unwrap();
2328        key(&mut app, 'n');
2329        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2330        assert!(job_rx.try_recv().is_err());
2331        assert!(app.playlist_dialog.as_ref().unwrap().error.is_some());
2332        for c in "  Café j/k  ".chars() {
2333            key(&mut app, c);
2334        }
2335        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2336        let Job::PlaylistAdd(id, target, song) = job_rx.try_recv().unwrap() else {
2337            panic!("Expected create with song")
2338        };
2339        assert!(matches!(&target,PlaylistTarget::New {name} if name=="Café j/k"));
2340        assert_eq!(song, "track-0");
2341        reply_tx
2342            .send(Reply::PlaylistAdded(id, target, Ok(())))
2343            .unwrap();
2344        app.tick();
2345        assert!(app.playlist_dialog.is_none());
2346    }
2347    #[test]
2348    fn closing_picker_discards_late_list_results() {
2349        let mut app = App::for_tests();
2350        app.items = vec![Item::Song(crate::test_support::songs().remove(0))];
2351        let (job_tx, job_rx) = mpsc::channel();
2352        app.tx = job_tx;
2353        let (reply_tx, reply_rx) = mpsc::channel();
2354        app.rx = reply_rx;
2355        key(&mut app, 'a');
2356        let Job::PlaylistChoices(old) = job_rx.recv().unwrap() else {
2357            unreachable!()
2358        };
2359        app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
2360        assert!(app.playlist_dialog.is_none());
2361        key(&mut app, 'a');
2362        let Job::PlaylistChoices(new) = job_rx.recv().unwrap() else {
2363            unreachable!()
2364        };
2365        assert_ne!(old, new);
2366        reply_tx
2367            .send(Reply::PlaylistChoices(
2368                old,
2369                Ok(vec![PlaylistChoice {
2370                    id: "old".into(),
2371                    ..Default::default()
2372                }]),
2373            ))
2374            .unwrap();
2375        app.tick();
2376        assert!(app.playlist_dialog.as_ref().unwrap().choices.is_empty());
2377        assert!(app.playlist_dialog.as_ref().unwrap().loading);
2378    }
2379    #[test]
2380    fn now_playing_reports_confirmed_library_tracks_once_per_start() {
2381        use PlayerEvent::{Error, Loaded, Paused, Position};
2382
2383        let mut app = App::for_tests();
2384        let (reports, tracks) = mpsc::channel();
2385        app.now_playing = Some(reports);
2386        app.queue = crate::test_support::songs();
2387        app.queue[1].is_external = true;
2388        let player = crate::test_support::TestPlayback::default();
2389        let events = player.events.clone();
2390        app.player = Some(Box::new(player));
2391        let tick = |app: &mut App, playback_events: Vec<PlayerEvent>, expected: &[&str]| {
2392            events.lock().unwrap().extend(playback_events);
2393            app.tick();
2394            assert_eq!(tracks.try_iter().collect::<Vec<_>>(), expected);
2395        };
2396
2397        app.play(0);
2398        tick(&mut app, vec![Position(1.)], &[]);
2399        tick(&mut app, vec![Loaded, Position(0.)], &[]);
2400        tick(&mut app, vec![Paused(true), Position(0.5)], &[]);
2401        tick(
2402            &mut app,
2403            vec![Paused(false), Position(1.), Position(2.)],
2404            &["track-0"],
2405        );
2406
2407        app.play(1);
2408        tick(&mut app, vec![Loaded, Position(1.)], &[]);
2409        app.play(2);
2410        tick(
2411            &mut app,
2412            vec![Error("Stream failed".into()), Position(1.)],
2413            &[],
2414        );
2415        app.play(2);
2416        tick(&mut app, vec![Loaded, Position(1.)], &["track-2"]);
2417        app.play(0);
2418        tick(&mut app, vec![Loaded, Position(1.)], &["track-0"]);
2419    }
2420    #[test]
2421    fn now_playing_failure_is_visible_only_for_the_current_track() {
2422        let mut app = App::for_tests();
2423        let (replies, rx) = mpsc::channel();
2424        app.rx = rx;
2425        app.queue = crate::test_support::songs();
2426        app.play(1);
2427        let report_failure = |id: &str| {
2428            replies
2429                .send(Reply::NowPlayingFailed(
2430                    id.into(),
2431                    anyhow::anyhow!("scrobble: HTTP 503"),
2432                ))
2433                .unwrap();
2434        };
2435
2436        report_failure("track-0");
2437        let status = app.status.clone();
2438        app.tick();
2439        assert_eq!(app.status, status);
2440
2441        report_failure("track-1");
2442        app.tick();
2443        assert_eq!(app.status, "Now Playing report failed (scrobble: HTTP 503)");
2444        assert_eq!(app.current, Some(1));
2445    }
2446    #[test]
2447    fn listening_history_records_confirmed_playback_and_survives_restarts() {
2448        let mut app = App::for_tests();
2449        app.queue = crate::test_support::songs();
2450        let directory =
2451            std::env::temp_dir().join(format!("octo-listening-test-{:x}", rand::random::<u64>()));
2452        let path = directory.join("session.json");
2453        app.session_path = Some(path.clone());
2454        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2455        app.player = Some(Box::new(crate::test_support::TestPlayback {
2456            events: events.clone(),
2457            ..Default::default()
2458        }));
2459        app.play(0);
2460        events.lock().unwrap().push(PlayerEvent::Position(1.));
2461        app.tick();
2462        assert!(app.listening_history.is_empty());
2463        events
2464            .lock()
2465            .unwrap()
2466            .extend([PlayerEvent::Loaded, PlayerEvent::Position(0.)]);
2467        app.tick();
2468        assert!(app.listening_history.is_empty());
2469        events.lock().unwrap().push(PlayerEvent::Position(0.5));
2470        app.tick();
2471        assert_eq!(app.listening_history[0].id, "track-0");
2472        app.play(1);
2473        events.lock().unwrap().extend([
2474            PlayerEvent::Error("Stream failed".into()),
2475            PlayerEvent::Position(1.),
2476        ]);
2477        app.tick();
2478        assert_eq!(app.listening_history.len(), 1);
2479        for index in [2, 0] {
2480            app.play(index);
2481            events
2482                .lock()
2483                .unwrap()
2484                .extend([PlayerEvent::Loaded, PlayerEvent::Position(1.)]);
2485            app.tick();
2486        }
2487        assert_eq!(
2488            app.listening_history
2489                .iter()
2490                .map(|s| s.id.as_str())
2491                .collect::<Vec<_>>(),
2492            ["track-0", "track-2"]
2493        );
2494        let (tx, jobs) = mpsc::channel();
2495        let (_reply, rx) = mpsc::channel();
2496        let mut restored = App::with_channels(app.api.clone(), 70, Some(path), tx, rx);
2497        key(&mut restored, '9');
2498        assert!(matches!(restored.view, View::History));
2499        assert_eq!(restored.items[0].title(), "Track 0");
2500        restored.queue.clear();
2501        key(&mut restored, 'a');
2502        assert!(matches!(jobs.try_recv().unwrap(), Job::PlaylistChoices(_)));
2503        assert_eq!(
2504            restored.playlist_dialog.as_ref().unwrap().song.id,
2505            "track-0"
2506        );
2507        std::fs::remove_dir_all(directory).unwrap();
2508    }
2509    #[test]
2510    fn listening_history_is_bounded_and_keeps_selection_while_new_tracks_arrive() {
2511        let mut app = App::for_tests();
2512        app.listening_history = (0..1000)
2513            .map(|n| Song {
2514                id: n.to_string(),
2515                title: format!("Track {n}"),
2516                ..Default::default()
2517            })
2518            .collect();
2519        key(&mut app, '9');
2520        app.table.select(Some(10));
2521        app.record_play(Song {
2522            id: "new".into(),
2523            title: "New track".into(),
2524            ..Default::default()
2525        });
2526        assert_eq!(app.listening_history.len(), 1000);
2527        assert_eq!(app.items[0].title(), "New track");
2528        assert_eq!(app.selected_song().unwrap().id, "10");
2529        assert!(!app.listening_history.iter().any(|s| s.id == "999"));
2530        app.record_play(Song {
2531            id: "10".into(),
2532            title: "Track 10".into(),
2533            ..Default::default()
2534        });
2535        assert_eq!(app.listening_history[0].id, "10");
2536        assert_eq!(
2537            app.listening_history
2538                .iter()
2539                .filter(|s| s.id == "10")
2540                .count(),
2541            1
2542        );
2543        assert_eq!(app.table.selected(), Some(0));
2544    }
2545    #[test]
2546    fn theme_shortcut_and_old_sessions_remain_compatible() {
2547        let mut app = App::for_tests();
2548        key(&mut app, 't');
2549        assert_eq!(app.theme, Theme::Nord);
2550        let saved = serde_json::to_vec(&Session {
2551            library_only: false,
2552            theme: app.theme,
2553            volume: 70,
2554            queue: crate::test_support::songs(),
2555            listening_history: vec![],
2556        })
2557        .unwrap();
2558        let restored: Session = serde_json::from_slice(&saved).unwrap();
2559        assert_eq!(restored.theme, Theme::Nord);
2560        assert_eq!(
2561            restored.queue[4].octo_suggested_by.as_deref(),
2562            Some("Last.fm")
2563        );
2564        assert_eq!(
2565            serde_json::from_str::<Session>(r#"{"queue":[],"volume":70}"#)
2566                .unwrap()
2567                .theme,
2568            Theme::Spotifyish
2569        );
2570    }
2571    #[test]
2572    fn view_search_moves_to_first_match_without_filtering_or_server_jobs() {
2573        let mut app = App::for_tests();
2574        app.view = View::Queue;
2575        app.queue = vec![
2576            Song {
2577                id: "a".into(),
2578                title: "Opening".into(),
2579                artist: "Björk".into(),
2580                ..Default::default()
2581            },
2582            Song {
2583                id: "b".into(),
2584                title: "Café".into(),
2585                album: "Evening".into(),
2586                ..Default::default()
2587            },
2588            Song {
2589                id: "c".into(),
2590                title: "Café reprise".into(),
2591                ..Default::default()
2592            },
2593        ];
2594        app.refresh_queue();
2595        app.table.select(Some(2));
2596        let (tx, jobs) = mpsc::channel();
2597        app.tx = tx;
2598        key(&mut app, '/');
2599        for c in "CAFÉ".chars() {
2600            key(&mut app, c);
2601        }
2602        assert_eq!(app.table.selected(), Some(1));
2603        assert_eq!(app.items.len(), 3);
2604        assert!(matches!(app.view, View::Queue));
2605        assert!(jobs.try_recv().is_err());
2606        key(&mut app, '!');
2607        assert_eq!(app.table.selected(), Some(1));
2608        app.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
2609        assert_eq!(app.input.as_deref(), Some("CAFÉ"));
2610        app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
2611        assert_eq!(app.table.selected(), Some(2));
2612
2613        for query in ["BJÖRK", "evening"] {
2614            key(&mut app, '/');
2615            for c in query.chars() {
2616                key(&mut app, c);
2617            }
2618            app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2619            assert_eq!(
2620                app.selected_song().unwrap().id,
2621                if query == "BJÖRK" { "a" } else { "b" }
2622            );
2623        }
2624        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2625        assert_eq!(app.current, Some(1));
2626        assert_eq!(app.queue.len(), 3);
2627        assert!(jobs.try_recv().is_err());
2628    }
2629
2630    #[test]
2631    fn unicode_search_and_history() {
2632        let mut app = App::for_tests();
2633        let (tx, jobs) = mpsc::channel();
2634        app.tx = tx;
2635        key(&mut app, '1');
2636        key(&mut app, 'é');
2637        app.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
2638        assert_eq!(app.input, Some(String::new()));
2639        for c in "radiohead".chars() {
2640            key(&mut app, c);
2641        }
2642        assert!(jobs.try_recv().is_err());
2643        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2644        assert!(matches!(&app.view,View::Search(query) if query=="radiohead"));
2645        assert!(
2646            matches!(jobs.try_recv().unwrap(), Job::Load(_, View::Search(query), _) if query == "radiohead")
2647        );
2648        app.back();
2649        assert!(matches!(app.view, View::Home));
2650    }
2651}