Cotton code
593 lines · 39.6 KB · RustRaw
//! `shell.player`: the queue the core keeps, the listen it writes from the//! shell's one report, and the player's row of settings.use std::path::Path;use serde_json::json;use super::*;use crate::phone::songs::{write_songs, SongIn};use crate::shell::client::phone_tests::attached;fn song_in(dir: &Path, name: &str, tags: Value) -> SongIn {    let path = dir.join(name);    std::fs::write(&path, format!("ID3 invented {name}")).expect("the file");    serde_json::from_value(json!({ "path": path.to_string_lossy(), "sourcePath": name, "tags": tags })).expect("a song")}fn captured(client: &ClientController, songs: &[SongIn]) -> Vec<String> {    let layout = client.layout().clone();    let written = client.write_rows("music.capture", &mut |ctx| write_songs(ctx, &layout, songs, "Asia/Kolkata")).expect("a capture");    written["answer"]["songs"].as_array().expect("songs").iter().map(|song| song["id"].as_str().expect("an id").to_string()).collect()}fn record(client: &ClientController, table: &str, id: &str) -> Value {    crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id})).expect("the record")["data"].clone()}fn listed(client: &ClientController, table: &str) -> Vec<Value> {    crate::phone::records::call(client, "records.list", &json!({"table": table, "limit": 100})).expect("a list")["records"].as_array().cloned().unwrap_or_default()}/// Two albums by one artist (the later one's songs brought in out of/// order), and a song of theirs on no album.struct Library {    late: Vec<String>,    early: Vec<String>,    loose: String,}fn library(client: &ClientController, dir: &Path) -> Library {    let tags = |title: &str, album: &str, year: &str, disc: u32, track: u32| {        json!({"title": title, "artist": "Ana Vell", "album": album, "albumArtist": "Ana Vell", "year": year, "disc": disc, "track": track, "duration": 200.0, "trackGain": -4.5, "trackPeak": 0.9})    };    let late = captured(client, &[        song_in(dir, "c.mp3", tags("Gulls", "Night Ferry", "2021", 2, 1)),        song_in(dir, "a.mp3", tags("Low Tide", "Night Ferry", "2021", 1, 1)),        song_in(dir, "b.mp3", tags("The Pier", "Night Ferry", "2021", 1, 2)),    ]);    let early = captured(client, &[song_in(dir, "d.mp3", tags("Harbour Lights", "First Light", "2015", 1, 1))]);    let loose = captured(client, &[song_in(dir, "e.mp3", json!({"title": "Paper Moon", "artist": "Ana Vell", "duration": 40.0}))]).remove(0);    Library { late, early, loose }}fn ask(client: &ClientController, request: Value) -> Value {    call(client, &request).unwrap_or_else(|error| panic!("{request} was refused: {} {}", error.code, error.message))}fn now_title(answer: &Value) -> &str {    answer["now"]["title"].as_str().unwrap_or("")}fn titles(answer: &Value) -> Vec<String> {    answer["queue"].as_array().expect("a queue").iter().map(|song| song["title"].as_str().unwrap_or_default().to_string()).collect()}fn at(answer: &Value) -> (u64, u64) {    (answer["at"]["index"].as_u64().unwrap(), answer["at"]["of"].as_u64().unwrap())}fn album_of(client: &ClientController, song: &str) -> String {    record(client, SONG_TABLE, song)["album"].as_str().expect("its album").to_string()}// RULE (shell.player, 5 Nov 2026): asked nothing, the player answers its whole state: nothing playing, an empty queue, the hi-fi worn among five faces, thirty seconds to count, and the words the shell draws, all kit lines.#[test]fn asked_nothing_the_player_answers_its_state() {    let (_dir, client) = attached();    let answer = ask(&client, json!({}));    assert!(answer.get("now").is_none(), "{answer}");    assert_eq!((titles(&answer).len(), at(&answer)), (0, (0, 0)));    assert_eq!(answer["face"], "song.hifi");    let faces: Vec<(&str, &str)> = answer["faces"].as_array().unwrap().iter().map(|face| (face["id"].as_str().unwrap(), face["label"].as_str().unwrap())).collect();    assert_eq!(faces, [("song.hifi", "Hi-fi"), ("song.turntable", "Turntable"), ("song.amp", "Amp"), ("song.party", "Party"), ("song.tray", "Tray"), ("song.cassette", "Cassette")]);    assert_eq!(answer["played_after_s"].as_f64(), Some(30.0));    assert_eq!(answer["words"]["nothing"], "There is no song here to play.");    assert_eq!(answer["settings"], json!({"crossfade_s": 0.0, "gapless": true, "replay_gain": "off", "speed": 1.0, "sleep_minutes": 0.0, "shuffle": false}));    assert_eq!(call(&client, &json!({"op": "louder"})).expect_err("refused").code, "bad_request");    assert_eq!(call(&client, &json!({"loud": true})).expect_err("refused").code, "bad_request");}// RULE (shell.player, 5 Nov 2026): a song played plays on through its album in disc and track order from it; `now` carries what the instrument plays and draws (file, gain, cover, album) and `kind: song`; an act's answer says play.#[test]fn play_deals_a_song_on_through_its_album() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let answer = ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[2]}));    assert_eq!((now_title(&answer), titles(&answer), at(&answer)), ("The Pier", vec!["Gulls".to_string()], (0, 2)), "{answer}");    let now = &answer["now"];    assert_eq!((now["id"].as_str(), now["artist"].as_str(), now["album_title"].as_str(), now["kind"].as_str()), (Some(lib.late[2].as_str()), Some("Ana Vell"), Some("Night Ferry"), Some("song")));    assert_eq!(now["album"].as_str(), Some(album_of(&client, &lib.late[2]).as_str()));    assert!(now["file"].as_str().is_some_and(|file| file.contains("/music/")), "{now}");    assert_eq!((now["duration_s"].as_f64(), now["gain_db"].as_f64()), (Some(200.0), Some(0.0)), "ReplayGain is off until set");    assert_eq!(answer["platform_action"], "play");    assert_eq!(answer["played_after_s"].as_f64(), Some(30.0));    assert!(ask(&client, json!({})).get("platform_action").is_none(), "only an act's answer plays");}// RULE (shell.player, 5 Nov 2026): an album plays in disc and track order; an artist plays its albums by year, the earliest first, then its songs on no album.#[test]fn an_album_and_an_artist_deal_in_order() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let album = ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    assert_eq!((now_title(&album), titles(&album)), ("Low Tide", vec!["The Pier".to_string(), "Gulls".into()]));    let artist = listed(&client, ARTIST_TABLE)[0]["id"].as_str().expect("the artist").to_string();    let all = ask(&client, json!({"op": "play", "table": ARTIST_TABLE, "id": artist}));    assert_eq!((now_title(&all), titles(&all)), ("Harbour Lights", vec!["Low Tide".to_string(), "The Pier".into(), "Gulls".into(), "Paper Moon".into()]));    assert_eq!(at(&all), (1, 6), "the album that played before stands behind");}// RULE (shell.player, 5 Nov 2026): a list plays the song table's group in its own order; a group of another table is no list to play.#[test]fn a_list_plays_in_its_order() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let made = crate::phone::records::call(&client, "groups.create", &json!({"table": SONG_TABLE, "name": "Synthetic evening"})).expect("a list");    let list = made["group"]["id"].as_str().expect("its id").to_string();    crate::phone::records::call(&client, "groups.update", &json!({"id": list, "add": [lib.loose, lib.late[1], lib.early[0]]})).expect("its songs");    let played = ask(&client, json!({"op": "play", "table": LIST, "id": list}));    assert_eq!((now_title(&played), titles(&played)), ("Paper Moon", vec!["Low Tide".to_string(), "Harbour Lights".into()]));    let books = crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": "Synthetic shelf"})).expect("a shelf");    assert_eq!(call(&client, &json!({"op": "play", "table": LIST, "id": books["group"]["id"]})).expect_err("refused").code, "unreadable");    // RULE (music-player-gone, 6 Nov 2026): a list played from one of its songs plays from it, the rest of the list after.    let from = ask(&client, json!({"op": "play", "table": LIST, "id": list, "from": lib.late[1]}));    assert_eq!((now_title(&from), titles(&from)), ("Low Tide", vec!["Harbour Lights".to_string()]));    assert_eq!(call(&client, &json!({"op": "play", "table": LIST, "id": list, "from": lib.late[0]})).expect_err("not on it").code, "bad_request");}// RULE (music-player-gone, 6 Nov 2026): a song held on a list's deck offers Play first, in its own Play's place, and it plays the list from that song; held anywhere else, its Play is its own.#[test]fn a_song_held_on_a_lists_deck_plays_the_list() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let made = crate::phone::records::call(&client, "groups.create", &json!({"table": SONG_TABLE, "name": "Synthetic evening"})).expect("a list");    let list = made["group"]["id"].as_str().expect("its id").to_string();    crate::phone::records::call(&client, "groups.update", &json!({"id": list, "add": [lib.loose, lib.late[1], lib.early[0]]})).expect("its songs");    let held = crate::phone::opened::call(&client, &json!({"table": SONG_TABLE, "id": lib.late[1], "view": format!("music/group:{list}")})).expect("held");    let first = held["acts"][0].clone();    assert_eq!((first["id"].as_str(), first["label"].as_str(), first["kind"].as_str()), (Some(crate::phone::tool_acts::LIST_PLAY), Some("Play"), Some("tool")), "{held}");    assert_eq!((first["group"].as_str(), first["record"].as_str()), (Some(list.as_str()), Some(lib.late[1].as_str())), "{first}");    assert!(!held["acts"].as_array().unwrap().iter().any(|act| act["id"] == "play"), "the song's own Play is the list's here: {held}");    let played = crate::phone::tool_acts::call(&client, &json!({"tool": first["tool"], "act": first["id"], "group": first["group"], "record": first["record"]})).expect("played");    assert_eq!((now_title(&played), titles(&played), played["platform_action"].as_str()), ("Low Tide", vec!["Harbour Lights".to_string()], Some("play")), "{played}");    let elsewhere = crate::phone::opened::call(&client, &json!({"table": SONG_TABLE, "id": lib.late[1], "view": "music/songs"})).expect("held");    assert_eq!(elsewhere["acts"][0]["id"].as_str(), Some("play"), "{elsewhere}");}// RULE (music-player-gone, 6 Nov 2026): Music always has a player: the song playing, its queue and where it stands (a seek) are kept beside the copy, and a new process finds the last song resting there at its place until resume.#[test]fn the_player_is_kept_across_a_relaunch() {    let (dir, client) = attached();    assert!(ask(&client, json!({})).get("now").is_none(), "never played: no player");    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 40.0, "ended": "skipped"}}));    ask(&client, json!({"op": "seek", "at_s": 61.5}));    assert!(client.layout().client_dir().join(KEPT_FILE).exists(), "the player is written beside the copy");    // A new process: the queues in memory are gone.    queues().remove(&queue_key(&client));    let reopened = ask(&client, json!({}));    assert_eq!((now_title(&reopened), titles(&reopened), at(&reopened)), ("The Pier", vec!["Gulls".to_string()], (1, 3)), "{reopened}");    assert_eq!((reopened["resting"].as_bool(), reopened["position_s"].as_f64()), (Some(true), Some(61.5)));    let resumed = ask(&client, json!({"op": "resume"}));    assert!(resumed.get("resting").is_none() && resumed["position_s"].as_f64() == Some(61.5), "{resumed}");    let next = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[2], "seconds": 45.0, "ended": "skipped"}}));    assert_eq!(now_title(&next), "Gulls");    assert_eq!(listed(&client, LISTEN_TABLE).len(), 2, "the first song's forty seconds and the resumed song's play are listens");    let previous = ask(&client, json!({"op": "previous", "at_s": 1.0}));    assert_eq!(now_title(&previous), "The Pier", "what played before is kept too");}// RULE (shell.player, 5 Nov 2026; Music leftovers, 7 Nov 2026): a song on no album plays alone and is the player's `now` whole, with no album to front and none invented: no album, no album title, no cover (the face's no-cover look), and its listen stamps no album.#[test]fn a_song_with_no_album_plays_whole() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let answer = ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.loose}));    assert_eq!((now_title(&answer), titles(&answer).len()), ("Paper Moon", 0));    assert!(["album", "album_title", "cover"].iter().all(|key| answer["now"].get(key).is_none()), "{answer}");    assert_eq!(answer["played_after_s"].as_f64(), Some(20.0), "half of a forty-second song");    let albums = listed(&client, ALBUM_TABLE).len();    ask(&client, json!({"op": "clear", "listened": {"table": "song", "id": lib.loose, "seconds": 40.0, "ended": "finished"}}));    assert_eq!(record(&client, SONG_TABLE, &lib.loose)["play_count"].as_f64(), Some(1.0));    assert_eq!(listed(&client, ALBUM_TABLE).len(), albums, "no album is made for it");    assert!(listed(&client, ALBUM_TABLE).iter().all(|album| album["data"]["last_played_at"].is_null()), "nor any stamped");}// RULE (shell.player, 5 Nov 2026): Play next goes in front of everything queued, Add to queue after them, both before the rest of the run; with nothing playing either starts.#[test]fn queue_next_and_queue_add_order_the_queue() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let first = ask(&client, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.loose}));    assert_eq!((now_title(&first), first["platform_action"].as_str()), ("Paper Moon", Some("play")), "nothing playing, a queued song starts");    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    ask(&client, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.early[0]}));    ask(&client, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.loose}));    let answer = ask(&client, json!({"op": "queue_next", "table": SONG_TABLE, "id": lib.late[2]}));    assert_eq!(now_title(&answer), "Low Tide");    assert_eq!(titles(&answer), ["The Pier", "Harbour Lights", "Paper Moon", "The Pier", "Gulls"], "queued alone, not through its album");}// RULE (shell.player, 5 Nov 2026): next plays what was queued by hand first, then the run.// RULE (362 walk, 6 Nov 2026): at the end of the queue a Next the person pressed moves nothing and says so: the song plays on, the answer's refusal is the kit's line, and its report waits (no listen, no skip).// RULE (music-player-gone, 6 Nov 2026): a song that finished or could not play at the end ends the run, and the player rests on it at nought: Music always has a player.#[test]fn next_moves_on_and_says_so_at_the_end() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[2]}));    ask(&client, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.loose}));    let next = ask(&client, json!({"op": "next"}));    assert_eq!((now_title(&next), titles(&next), at(&next)), ("Paper Moon", vec!["Gulls".to_string()], (1, 3)));    assert!(next.get("refusal").is_none(), "{next}");    let last = ask(&client, json!({"op": "next"}));    assert_eq!((now_title(&last), at(&last)), ("Gulls", (2, 3)));    let pressed = ask(&client, json!({"op": "next"}));    assert_eq!((now_title(&pressed), at(&pressed)), ("Gulls", (2, 3)), "the last song plays on: {pressed}");    assert_eq!(pressed["refusal"], "Nothing comes after this song.");    let skipped = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[0], "seconds": 4.0, "ended": "skipped"}}));    assert_eq!((now_title(&skipped), skipped["refusal"].as_str()), ("Gulls", Some("Nothing comes after this song.")));    assert!(record(&client, SONG_TABLE, &lib.late[0])["skip_count"].is_null(), "the song was not left, so its report writes nothing");    assert!(listed(&client, LISTEN_TABLE).is_empty());    let finished = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[0], "seconds": 200.0, "ended": "finished"}}));    assert_eq!((now_title(&finished), at(&finished), finished["resting"].as_bool(), finished["position_s"].as_f64()), ("Gulls", (2, 3), Some(true), Some(0.0)), "{finished}");    assert!(titles(&finished).is_empty() && finished.get("refusal").is_none(), "{finished}");    assert_eq!(listed(&client, LISTEN_TABLE).len(), 1, "the finished play is a listen");    let resumed = ask(&client, json!({"op": "resume"}));    assert_eq!((now_title(&resumed), resumed.get("resting")), ("Gulls", None), "resume sets the resting song playing");    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.loose}));    let unplayable = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.loose, "seconds": 0.0, "ended": "stopped"}}));    assert_eq!((now_title(&unplayable), unplayable["resting"].as_bool()), ("Paper Moon", Some(true)), "a last song that could not play rests: {unplayable}");}// RULE (shell.player, 5 Nov 2026): Previous under three seconds into a song goes back to the song before; at three seconds or more, or with none before, the song starts again and nothing moves.#[test]fn previous_goes_back_within_three_seconds_and_restarts_after() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    let first = ask(&client, json!({"op": "previous", "at_s": 1.0}));    assert_eq!((now_title(&first), at(&first)), ("Low Tide", (0, 3)), "none before: it starts again");    ask(&client, json!({"op": "next"}));    let restart = ask(&client, json!({"op": "previous", "at_s": 3.0}));    assert_eq!((now_title(&restart), at(&restart)), ("The Pier", (1, 3)));    let restart_report = ask(&client, json!({"op": "previous", "at_s": 40.0, "listened": {"table": "song", "id": lib.late[2], "seconds": 40.0, "ended": "skipped"}}));    assert_eq!(now_title(&restart_report), "The Pier");    assert!(listed(&client, LISTEN_TABLE).is_empty(), "a restart leaves no play, so its report writes nothing");    let back = ask(&client, json!({"op": "previous", "at_s": 2.9}));    assert_eq!((now_title(&back), titles(&back), at(&back)), ("Low Tide", vec!["The Pier".to_string(), "Gulls".into()], (0, 3)));    ask(&client, json!({"op": "next"}));    ask(&client, json!({"op": "seek", "at_s": 120.0}));    assert_eq!(now_title(&ask(&client, json!({"op": "previous"}))), "The Pier", "a seek is where previous reads the song from");    assert_eq!(call(&client, &json!({"op": "seek"})).expect_err("no at_s").code, "bad_request");}// RULE (shell.player, 5 Nov 2026): shuffle with a record deals all of it in a new order, a permutation of the songs; without one it shuffles the rest of the run, and again puts it back in its order after the song playing.#[test]fn shuffle_is_a_permutation_and_turns_back() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let artist = listed(&client, ARTIST_TABLE)[0]["id"].as_str().expect("the artist").to_string();    let dealt = ask(&client, json!({"op": "shuffle", "table": ARTIST_TABLE, "id": artist}));    let mut all = titles(&dealt);    all.push(now_title(&dealt).to_string());    all.sort();    assert_eq!(all, ["Gulls", "Harbour Lights", "Low Tide", "Paper Moon", "The Pier"]);    assert_eq!((dealt["settings"]["shuffle"].as_bool(), dealt["platform_action"].as_str()), (Some(true), Some("play")));    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    let shuffled = ask(&client, json!({"op": "shuffle"}));    assert_eq!(shuffled["settings"]["shuffle"], true);    let mut rest = titles(&shuffled);    rest.sort();    assert_eq!(rest, ["Gulls", "The Pier"]);    let back = ask(&client, json!({"op": "shuffle"}));    assert_eq!((titles(&back), back["settings"]["shuffle"].as_bool()), (vec!["The Pier".to_string(), "Gulls".into()], Some(false)));}// RULE (shell.player, 5 Nov 2026): clear stops the player: nothing playing, nothing queued, nothing behind.#[test]fn clear_stops_everything() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[1]}));    ask(&client, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.loose}));    let cleared = ask(&client, json!({"op": "clear"}));    assert!(cleared.get("now").is_none() && titles(&cleared).is_empty() && at(&cleared) == (0, 0), "{cleared}");}// RULE (shell.player, 5 Nov 2026): a song counts after thirty seconds, or half of it when that is less.#[test]fn a_song_counts_after_thirty_seconds_or_half() {    assert_eq!((counts_after(200.0), counts_after(40.0), counts_after(0.0)), (30.0, 20.0, 30.0));}// RULE (shell.player, 5 Nov 2026): the shell reports a play once as it ends; heard enough, it is a listen row (played_at when it began, from where it came) and the song's play_count one more, its and its album's last_played_at the play's; a next naming another song is late and moves nothing again.#[test]fn a_listen_heard_enough_writes_the_row_and_the_counts() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let played = ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[1]}));    let next = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 199.6, "ended": "finished", "device": "iPhone"}}));    assert_eq!(now_title(&next), "The Pier");    let listens = listed(&client, LISTEN_TABLE);    assert_eq!(listens.len(), 1);    let listen = &listens[0]["data"];    assert_eq!((listen["seconds"].as_f64(), listen["ended"].as_str(), listen["from"].as_str(), listen["device"].as_str()), (Some(200.0), Some("finished"), Some("album"), Some("iPhone")));    let song = record(&client, SONG_TABLE, &lib.late[1]);    assert_eq!(song["play_count"].as_f64(), Some(1.0));    let began = song["last_played_at"].as_str().expect("last played").to_string();    assert_eq!(listen["played_at"].as_str(), Some(began.as_str()));    assert_eq!(record(&client, ALBUM_TABLE, &album_of(&client, &lib.late[1]))["last_played_at"].as_str(), Some(began.as_str()));    assert!(played.get("now").is_some());    let late = ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 31.0, "ended": "finished"}}));    assert_eq!(now_title(&late), "The Pier", "a late next moves nothing again");    assert_eq!(record(&client, SONG_TABLE, &lib.late[1])["play_count"].as_f64(), Some(2.0), "and its listen is still written");}// RULE (shell.player, 7 Nov 2026): the counts follow the listen rows: a listen that ended skipped (heard enough, then left by next) makes the song's play_count one more and its skip_count one more too; one that finished counts no skip.#[test]fn a_listen_that_ended_skipped_counts_a_play_and_a_skip() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 45.0, "ended": "skipped"}}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[2], "seconds": 3.0, "ended": "skipped"}}));    let listens = listed(&client, LISTEN_TABLE);    assert_eq!(listens.len(), 1, "the short skip writes no row");    assert_eq!(listens[0]["data"]["ended"].as_str(), Some("skipped"));    let low = record(&client, SONG_TABLE, &lib.late[1]);    assert_eq!((low["play_count"].as_f64(), low["skip_count"].as_f64()), (Some(1.0), Some(1.0)), "{low}");    let pier = record(&client, SONG_TABLE, &lib.late[2]);    assert_eq!((pier["play_count"].as_f64(), pier["skip_count"].as_f64()), (None, Some(1.0)), "{pier}");    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[1]}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 199.0, "ended": "finished"}}));    let low = record(&client, SONG_TABLE, &lib.late[1]);    assert_eq!((low["play_count"].as_f64(), low["skip_count"].as_f64()), (Some(2.0), Some(1.0)), "a finished listen counts no skip: {low}");}// RULE (shell.player, 5 Nov 2026): a play left by next before it counted is a skip: no listen, its skip_count one more; short and stopped or finished (scrubbed to the end), nothing is written.#[test]fn a_play_left_short_is_a_skip_or_nothing() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[1], "seconds": 4.2, "ended": "skipped"}}));    ask(&client, json!({"op": "next", "listened": {"table": "song", "id": lib.late[2], "seconds": 29.9, "ended": "finished"}}));    ask(&client, json!({"op": "clear", "listened": {"table": "song", "id": lib.late[0], "seconds": 3.0, "ended": "stopped"}}));    assert!(listed(&client, LISTEN_TABLE).is_empty(), "no listen");    let (low, pier, gulls) = (record(&client, SONG_TABLE, &lib.late[1]), record(&client, SONG_TABLE, &lib.late[2]), record(&client, SONG_TABLE, &lib.late[0]));    assert_eq!(low["skip_count"].as_f64(), Some(1.0));    assert!(pier["skip_count"].is_null() && gulls["skip_count"].is_null(), "{pier} {gulls}");    assert!(low["play_count"].is_null(), "a skip is no play");    let refused = |listened: Value| call(&client, &json!({"listened": listened})).expect_err("refused").code;    assert_eq!(refused(json!({"table": "song", "id": lib.late[1], "seconds": 3})), "bad_request");    assert_eq!(refused(json!({"table": "song", "id": lib.late[1], "seconds": -1, "ended": "skipped"})), "bad_request");    assert_eq!(refused(json!({"table": "song", "id": "no-such-song", "seconds": 40, "ended": "finished"})), "listen_refused");}// RULE (shell.player, 5 Nov 2026): a report alone, after an act moved the player, writes the play it names with when that play began.#[test]fn a_report_after_an_act_finds_the_play_it_left() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.loose}));    let began = ask(&client, json!({}));    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.early[0]}));    let answer = ask(&client, json!({"listened": {"table": "song", "id": lib.loose, "seconds": 25.0, "ended": "stopped"}}));    assert_eq!(now_title(&answer), "Harbour Lights");    let listen = &listed(&client, LISTEN_TABLE)[0]["data"];    assert_eq!((listen["from"].as_str(), listen["ended"].as_str()), (Some("songs"), Some("stopped")));    assert!(began.get("now").is_some());}// RULE (shell.player, 5 Nov 2026): the settings are the face_settings row keyed player: written by op settings (the face by id, the knobs by name) and rate, read back on the next answer, the face riding with every write; ReplayGain sets each song's gain_db, never past its peak.#[test]fn the_settings_row_round_trips() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let worn = ask(&client, json!({"op": "settings", "face": "song.turntable"}));    assert_eq!(worn["face"], "song.turntable");    let set = ask(&client, json!({"op": "settings", "settings": {"crossfade_s": 6, "gapless": false, "replay_gain": "song", "sleep_minutes": 20}}));    assert_eq!(set["settings"], json!({"crossfade_s": 6.0, "gapless": false, "replay_gain": "song", "speed": 1.0, "sleep_minutes": 20.0, "shuffle": false}));    assert_eq!(ask(&client, json!({"op": "rate", "rate": 1.5}))["settings"]["speed"].as_f64(), Some(1.5));    let row = record(&client, "face_settings", SETTINGS_ROW);    assert_eq!((row["face"].as_str(), row["loudness"].as_str(), row["crossfade_seconds"].as_f64(), row["speed"].as_f64()), (Some("turntable"), Some("track"), Some(6.0), Some(1.5)), "{row}");    let again = ask(&client, json!({}));    assert_eq!((again["face"].as_str(), again["settings"]["replay_gain"].as_str()), (Some("song.turntable"), Some("song")));    let played = ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[1]}));    let gain = played["now"]["gain_db"].as_f64().expect("a gain");    assert!((gain - (-4.5)).abs() < 1e-9, "-4.5 dB lifts no peak: {gain}");    let until = played["settings"]["sleep_until"].as_str().and_then(ms_of).expect("the default sleep timer set");    let refused = |request: Value| call(&client, &request).expect_err("refused").code;    assert_eq!(refused(json!({"op": "settings", "face": "song.gramophone"})), "bad_request");    // The tray (owner, 7 Nov 2026): worn like the rest, kept on the row by its word.    assert_eq!(ask(&client, json!({"op": "settings", "face": "song.tray"}))["face"], "song.tray");    assert_eq!(record(&client, "face_settings", SETTINGS_ROW)["face"].as_str(), Some("tray"));    assert_eq!(refused(json!({"op": "settings", "settings": {"speed": 3}})), "bad_request");    assert_eq!(refused(json!({"op": "settings", "settings": {"replay_gain": "loud"}})), "bad_request");    assert_eq!(refused(json!({"op": "settings"})), "bad_request");    assert_eq!(refused(json!({"op": "rate", "rate": 0.1})), "bad_request");    assert!(until > 0);}// RULE (shell.player, 5 Nov 2026): sleep sets this phone's timer at its minutes from now; nought clears it.#[test]fn sleep_sets_and_clears_the_timer() {    let (_dir, client) = attached();    let set = ask(&client, json!({"op": "sleep", "minutes": 15}));    let until = set["settings"]["sleep_until"].as_str().and_then(ms_of).expect("a timer");    let plain = ask(&client, json!({}));    assert_eq!(plain["settings"]["sleep_until"].as_str().and_then(ms_of), Some(until), "the timer stands across asks");    assert!(ask(&client, json!({"op": "sleep", "minutes": 0}))["settings"].get("sleep_until").is_none());    assert_eq!(call(&client, &json!({"op": "sleep"})).expect_err("refused").code, "bad_request");}// RULE (shell.player, 5 Nov 2026): a play of nothing playable answers the kit's line as its refusal and moves nothing.#[test]fn a_play_of_nothing_is_refused_in_the_kits_words() {    let (_dir, client) = attached();    let made = crate::phone::records::call(&client, "groups.create", &json!({"table": SONG_TABLE, "name": "Synthetic empty"})).expect("a list");    let answer = ask(&client, json!({"op": "play", "table": LIST, "id": made["group"]["id"]}));    assert_eq!(answer["refusal"], "There is no song here to play.");    assert!(answer.get("now").is_none());    assert_eq!(call(&client, &json!({"op": "play"})).expect_err("refused").code, "bad_request");    assert_eq!(call(&client, &json!({"op": "play", "table": "book", "id": "x"})).expect_err("refused").code, "bad_request");}/// A fresh phone opened as Cotton Music: the music kit alone (no podcast,/// episode, film or todo tables), local first.fn music_phone() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest = crate::fixture::own_app_manifest("music", "Cotton Music");    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn on_music(handle: &crate::handle::CottonHandle, request: Value) -> Value {    crate::methods::dispatch(handle, "shell.player", &request).unwrap_or_else(|error| panic!("{request} was refused on Music: {} {}", error.code, error.message))}// RULE (music-player-gone, 6 Nov 2026): on Cotton Music's own copy (the music kit alone) shell.player answers its state, plays a song, an album and the one "Unknown Album" many loose songs by different artists share, and moves through it.#[test]fn the_player_plays_on_the_music_kit_alone() {    let (dir, handle) = music_phone();    let client = handle.client();    let state = on_music(&handle, json!({}));    assert_eq!(state["face"], "song.hifi", "{state}");    let loose: Vec<SongIn> = ["Tin Bell", "Copper Wire", "Glass Kite"]        .iter()        .enumerate()        .map(|(at, title)| song_in(dir.path(), &format!("loose{at}.mp3"), json!({"title": title, "artist": format!("Invented Artist {at}"), "album": "Unknown Album", "duration": 180.0})))        .collect();    let ids = captured(&client, &loose);    // The import's fallback: one "Unknown Album" every loose song points at,    // each song still by its own artist.    let album = album_of(&client, &ids[0]);    for id in &ids[1..] {        crate::phone::records::call(&client, "records.update", &json!({"table": SONG_TABLE, "id": id, "patch": {"album": album}})).expect("onto the one album");    }    let albums: Vec<Value> = listed(&client, ALBUM_TABLE).into_iter().filter(|one| one["id"] == album.as_str()).collect();    let song = on_music(&handle, json!({"op": "play", "table": SONG_TABLE, "id": ids[1]}));    assert_eq!(song["now"]["id"].as_str(), Some(ids[1].as_str()), "{song}");    assert_eq!(song["platform_action"], "play");    let album = on_music(&handle, json!({"op": "play", "table": ALBUM_TABLE, "id": albums[0]["id"]}));    assert_eq!(titles(&album).len() + 1, 3, "{album}");    let next = on_music(&handle, json!({"op": "next", "listened": {"table": SONG_TABLE, "id": album["now"]["id"], "seconds": 40.0, "ended": "finished"}}));    assert!(next.get("refusal").is_none(), "{next}");    let listens = listed(&client, LISTEN_TABLE);    assert_eq!(listens.len(), 1, "{listens:?}");}/// A new process: the queues in memory are gone, the copy and its file stay.fn relaunched(client: &ClientController) {    queues().remove(&queue_key(client));}fn heard_at(client: &ClientController, song: &str, played_at: &str) {    let data = Map::from_iter([("song".to_string(), json!(song)), ("played_at".to_string(), json!(played_at)), ("seconds".to_string(), json!(60)), ("ended".to_string(), json!("finished"))]);    client.write_rows("a listen", &mut |ctx| made(ctx, LISTEN_TABLE, data.clone()).map(|_| Value::Null)).expect("a listen");}fn kept(client: &ClientController) -> bool {    client.layout().client_dir().join(KEPT_FILE).exists()}// RULE (music-player-first, 7 Nov 2026): with no player kept, the player is the newest listen's song, resting at nought, its run dealt as its Play from its album deals it, so Next works at once; nothing is kept until a play begins.#[test]fn with_none_kept_the_newest_listen_rests() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    heard_at(&client, &lib.early[0], "2026-11-01T10:00:00.000Z");    heard_at(&client, &lib.late[1], "2026-11-03T10:00:00.000Z");    let offered = ask(&client, json!({}));    assert_eq!((now_title(&offered), titles(&offered), at(&offered)), ("Low Tide", vec!["The Pier".to_string(), "Gulls".into()], (0, 3)), "{offered}");    assert_eq!((offered["resting"].as_bool(), offered["position_s"].as_f64()), (Some(true), Some(0.0)));    assert!(!kept(&client), "nothing is kept before a play");    assert_eq!(ask(&client, json!({}))["now"]["id"], offered["now"]["id"], "asked again, the same song rests");    let next = ask(&client, json!({"op": "next"}));    assert_eq!((now_title(&next), next.get("resting")), ("The Pier", None), "{next}");    assert!(kept(&client), "a play began: the player is kept");}// RULE (music-player-first, 7 Nov 2026): with no player kept and no listen, the player is the first song of the first album in the Albums view's order (artist, then year), its album the run, resting; play plays it, and from then it is kept.#[test]fn with_no_listen_the_first_albums_first_song_rests() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    let offered = ask(&client, json!({}));    assert_eq!((now_title(&offered), offered["resting"].as_bool()), ("Harbour Lights", Some(true)), "First Light (2015) before Night Ferry (2021): {offered}");    assert_eq!(offered["now"]["album"].as_str(), Some(album_of(&client, &lib.early[0]).as_str()));    assert!(!kept(&client));    let resumed = ask(&client, json!({"op": "resume"}));    assert!(resumed.get("resting").is_none() && now_title(&resumed) == "Harbour Lights", "{resumed}");    assert!(kept(&client), "play pressed: the player is kept");    let (other, fresh) = attached();    library(&fresh, other.path());    captured(&fresh, &[        song_in(other.path(), "q2.mp3", json!({"title": "Second Bell", "artist": "Aaron Quay", "album": "Quay Songs", "albumArtist": "Aaron Quay", "year": "2024", "disc": 1, "track": 2, "duration": 180.0})),        song_in(other.path(), "q1.mp3", json!({"title": "First Bell", "artist": "Aaron Quay", "album": "Quay Songs", "albumArtist": "Aaron Quay", "year": "2024", "disc": 1, "track": 1, "duration": 180.0})),    ]);    let first = ask(&fresh, json!({}));    assert_eq!((now_title(&first), titles(&first)), ("First Bell", vec!["Second Bell".to_string()]), "Aaron Quay's album is the Albums view's first: {first}");}// RULE (music-player-first, 7 Nov 2026): a copy with no song that can play has no player; the first song to arrive is offered, resting, without a relaunch.#[test]fn with_no_song_there_is_no_player_until_one_arrives() {    let (dir, client) = attached();    let none = ask(&client, json!({}));    assert!(none.get("now").is_none() && none.get("resting").is_none(), "{none}");    assert!(!kept(&client));    library(&client, dir.path());    assert_eq!(now_title(&ask(&client, json!({}))), "Harbour Lights", "the songs arrived: the player is there");}// RULE (music-player-first, 7 Nov 2026): a kept player whose song is gone, and a listen whose song is gone, fall through to the next case.#[test]fn a_song_gone_falls_through() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    ask(&client, json!({"op": "play", "table": SONG_TABLE, "id": lib.late[1]}));    assert!(kept(&client));    heard_at(&client, &lib.late[1], "2026-11-03T10:00:00.000Z");    crate::phone::records::call(&client, "records.delete", &json!({"table": SONG_TABLE, "id": lib.late[1]})).expect("deleted");    relaunched(&client);    let offered = ask(&client, json!({}));    assert_eq!((now_title(&offered), offered["resting"].as_bool()), ("Harbour Lights", Some(true)), "kept and heard are both gone: the first album's first song: {offered}");}// RULE (music-player-first, 7 Nov 2026): a play or a queued song from elsewhere starts in the offered song's place; the offered song never stands behind as played.#[test]fn a_play_takes_the_offered_songs_place() {    let (dir, client) = attached();    let lib = library(&client, dir.path());    assert_eq!(now_title(&ask(&client, json!({}))), "Harbour Lights");    let played = ask(&client, json!({"op": "play", "table": ALBUM_TABLE, "id": album_of(&client, &lib.late[0])}));    assert_eq!((now_title(&played), at(&played)), ("Low Tide", (0, 3)), "{played}");    let (other, fresh) = attached();    let lib = library(&fresh, other.path());    ask(&fresh, json!({}));    let queued = ask(&fresh, json!({"op": "queue_add", "table": SONG_TABLE, "id": lib.loose}));    assert_eq!((now_title(&queued), queued.get("resting"), at(&queued)), ("Paper Moon", None, (0, 1)), "{queued}");}