//! The Downloads chat over a Comms phone's own copy and a scripted object.//! Every link, name and number is invented.use std::sync::{Arc, Mutex};use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::ScriptedExchange;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};usesuper::{place, THREAD};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::cotton_chat::over;usecrate::phone::personal_object::ObjectDoor;fn comms() -> (tempfile::TempDir, CottonHandle) {let dir = tempfile::tempdir().expect("a temp container");let manifest = json!({"genesis": "personal", "flavour": "messages", "name": "Cotton Comms", "databases": "single", "database": "personal","fan": {"home": false, "tools": false}, "kit": "messages", });let 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");// The queue's tables are data-only: a signed-in Comms phone has them from its object's definitions, as its pull lays them.let ws = workspace(&handle);for table in ["fetch", "fetch_file"] {let definition = std::fs::read_to_string(cotton_store::manifest_dir().join(format!("../cotton-core/kits/personal/tables/{table}.json"))).expect("the kit's table"); sql( &handle,"INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES (?, ?, ?, 0, 0, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')", &[t(table), t(&ws), t(&definition)], ); } handle.client().bring_moves_done_for_tests().expect("the index rebuilt"); (dir, handle)}/// The phone holds a door to its object (signed in); the object answers nothing unless asked.fn signed_in(handle: &CottonHandle) {let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: ScriptedExchange::new([]), credential: "ctd_11111111-1111-4111-8111-111111111111_test".into() }; handle.client().set_object_door(Some(Arc::new(door)));}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn sql(handle: &CottonHandle, statement: &str, params: &[SqlValue]) { handle .client() .with_writer(|replica| { replica.driver.run(statement, params).map_err(|e| e.to_string())?;crate::fixture::receipted(replica.driver, statement);Ok(()) }) .expect(statement);}fn t(s: &str) -> SqlValue {SqlValue::Text(s.to_string())}fn workspace(handle: &CottonHandle) -> String {let found = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap(); found.as_str().unwrap().to_string()}fn iso(minutes_ago: i64) -> String { (chrono::Utc::now() - chrono::Duration::minutes(minutes_ago)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}#[allow(clippy::too_many_arguments)]fn fetch(handle: &CottonHandle, id: &str, source: &str, state: &str, progress: Option<f64>, error: Option<&str>, sent: &str, moved: &str) {let ws = workspace(handle); sql( handle,"INSERT INTO cotton_fetch (id, workspace_id, created_at, updated_at, source, state, progress, error, added_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", &[t(id), t(&ws), t(sent), t(moved), t(source), t(state), progress.map_or(SqlValue::Null, SqlValue::Real), error.map_or(SqlValue::Null, t), t(sent)], );}fn landed(handle: &CottonHandle, id: &str, fetch: &str, name: &str, bytes: f64, kind: &str, column: &str, record: &str) {let ws = workspace(handle); sql( handle, &format!("INSERT INTO cotton_fetch_file (id, workspace_id, created_at, updated_at, \"fetch\", name, kind, bytes, {column}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"), &[t(id), t(&ws), t(&iso(1)), t(&iso(1)), t(fetch), t(name), t(kind), SqlValue::Real(bytes), t(record)], );}fn row_of(list: &Value) -> Option<Value> { list["rows"].as_array().expect("rows").iter().find(|row| row["thread"] == THREAD).cloned()}/// An object that records what it is asked and answers `fetch_add` with a new id.#[derive(Default)]structObject { asked: Mutex<Vec<Value>>,}implObject {fn call(&self, request: &Value) -> Result<Value, MethodError> {letmut asked = self.asked.lock().unwrap(); asked.push(request.clone());Ok(json!({ "fetch": format!("fetch-new-{}", asked.len()) })) }}/// What a new signed-in Comms phone's list answers, holding none of the person's chats: Cotton's own Downloads chat/// alone, and the words saying how to begin (Comms Dev's `fresh`, written by `write_chat_warm_fixture`).pub(crate) fn fresh_list() -> Value {let (_dir, handle) = comms(); signed_in(&handle);let list = answer(&handle, "chat.list", json!({})); assert!(row_of(&list).is_some(), "the Downloads chat: {list}"); list}/// RULE (DLCHAT, 22 Nov 2026): a signed-in Comms phone lists a chat named Downloads, made by the core: Cotton's mark for its picture and no number, no unread figure, its only acts Mute and Unmute (never Delete), its last line the kit's invitation before the first download. A phone not signed in has none: the queue lives in the person's object.#[test]fn a_signed_in_comms_phone_lists_the_downloads_chat() {let (_dir, handle) = comms(); assert!(row_of(&answer(&handle, "chat.list", json!({}))).is_none(), "signed out: no Downloads chat"); signed_in(&handle);let row = row_of(&answer(&handle, "chat.list", json!({}))).expect("the Downloads chat"); assert_eq!((row["kind"].as_str(), row["name"].as_str()), (Some("downloads"), Some("Downloads"))); assert_eq!(row["picture"]["mark"], "downloads"); assert_eq!(row["picture"]["initials"], "", "no initials, no number"); assert_eq!(row["lastLine"]["text"], "Send a link here and Cotton will download it."); assert_eq!(row["unread"], 0);let acts: Vec<&str> = row["trailing"].as_array().unwrap().iter().chain(row["hold"].as_array().unwrap()).filter_map(|swipe| swipe["act"].as_str()).collect(); assert_eq!(acts, ["mute", "mute"], "Mute alone: the chat is never deleted"); assert!(row_of(&answer(&handle, "chat.list", json!({ "filter": "groups" }))).is_none(), "it is no group"); assert!(row_of(&answer(&handle, "chat.list", json!({ "sendable": true }))).is_none(), "nothing is forwarded into it");// Muted from the list's swipe, as any chat is; unmuted the same way.let muted = answer(&handle, "chat.act", json!({ "thread": THREAD, "act": "mute" })); assert_eq!(muted["muted"], true);let row = row_of(&answer(&handle, "chat.list", json!({}))).unwrap(); assert_eq!((row["muted"].as_bool(), row["trailing"][0]["act"].as_str()), (Some(true), Some("unmute"))); answer(&handle, "chat.act", json!({ "thread": THREAD, "act": "unmute" })); assert_eq!(row_of(&answer(&handle, "chat.list", json!({}))).unwrap()["muted"], false);}/// RULE: each download is the person's link and ONE line from Cotton under it, drawn from the fetch row and changed in place: Queued, a percentage, Done with the file's name and size and Open, Failed with the reason and Retry. The page is oldest first; the list row's last line is the newest download's state.#[test]fn each_download_is_its_link_and_cottons_one_line() {let (_dir, handle) = comms(); signed_in(&handle); fetch(&handle, "f-done", "https://files.example/invented-film.mkv", "done", Some(100.0), None, &iso(50), &iso(40)); landed(&handle, "ff-1", "f-done", "Invented Film.mkv", 1_436_000_000.0, "film", "film", "film-1"); fetch(&handle, "f-failed", "https://video.example/watch?v=invented", "failed", None, Some("The page asks for a sign-in."), &iso(30), &iso(29)); fetch(&handle, "f-on", "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567", "fetching", Some(42.7), None, &iso(20), &iso(2)); fetch(&handle, "f-new", "https://files.example/invented.epub", "queued", None, None, &iso(0), &iso(0));let page = answer(&handle, "chat.downloads", json!({})); assert_eq!(page["title"], "Downloads");let items = page["items"].as_array().expect("items");let said: Vec<(&str, &str, &str)> = items.iter().map(|item| (item["fetch"].as_str().unwrap(), item["link"]["text"].as_str().unwrap(), item["cotton"]["line"]["text"].as_str().unwrap())).collect(); assert_eq!( said, [ ("f-done", "https://files.example/invented-film.mkv", "Done · 1.4 GB · opens in Cinemas"), ("f-failed", "https://video.example/watch?v=invented", "Failed · The page asks for a sign-in."), ("f-on", "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567", "42%"), ("f-new", "https://files.example/invented.epub", "Queued"), ] ); assert_eq!(items[0]["cotton"]["line"]["act"], json!({ "act": "open", "label": "Open" })); assert_eq!(items[1]["cotton"]["line"]["act"], json!({ "act": "retry", "label": "Try again" })); assert!(items[2]["cotton"]["line"]["act"].is_null() && items[3]["cotton"]["line"]["act"].is_null()); assert!(page.get("earlier").is_none()); assert!(items[0]["day"]["date"].as_str().is_some_and(|date| !date.is_empty()), "the first item carries its day: {}", items[0]); assert!(page["askAgainAt"].as_i64().is_some_and(|at| at > chrono::Utc::now().timestamp_millis()), "the queued one turns within the minute: {}", page["askAgainAt"]);// RULE (owner, 22 Nov 2026): a queued one no fetcher took within a minute says it waits for the Mac. fetch(&handle, "f-old", "https://files.example/invented-old.epub", "queued", None, None, &iso(9), &iso(9));let waited = answer(&handle, "chat.downloads", json!({}));let old = waited["items"].as_array().unwrap().iter().find(|item| item["fetch"] == "f-old").expect("the old one").clone(); assert_eq!(old["cotton"]["line"]["text"], "Queued · waiting for your Mac");// The row moves in place: the same item, its line changed. sql(&handle, "UPDATE cotton_fetch SET progress = 88, updated_at = ? WHERE id = 'f-on'", &[t(&iso(0))]);let page = answer(&handle, "chat.downloads", json!({})); assert_eq!(page["items"][2]["cotton"]["line"]["text"], "88%"); assert_eq!(page["items"].as_array().unwrap().len(), 5, "no new line: the same one changed");let row = row_of(&answer(&handle, "chat.list", json!({}))).unwrap(); assert_eq!(row["lastLine"]["text"], "Queued: The download", "the newest download's state");}/// RULE: a link the person writes becomes a fetch row this phone writes in its own copy, spelled as the Worker's rule spells it (its kind, what it wants, queued), sealed on its way up, so nothing on a server reads it; it stands at once as Queued, each link once; words with no link are answered with the kit's line, nothing written and nothing kept. A share sent to the Downloads chat (`share.fetchLinks { to: "downloads" }`) is the same.#[test]fn a_link_written_goes_on_the_queue_and_words_without_one_are_answered() {let (_dir, handle) = comms(); signed_in(&handle);let sent = answer(&handle, "chat.downloads.send", json!({ "text": "this one https://files.example/a.pdf and magnet:?xt=urn:btih:abc&dn=Invented, again https://files.example/a.pdf" }));let made: Vec<String> = sent["fetch"].as_array().expect("made").iter().map(|id| id.as_str().unwrap().to_string()).collect(); assert_eq!(made.len(), 2, "each link once"); assert_eq!(sent["items"][0]["link"]["text"], "https://files.example/a.pdf"); assert_eq!(sent["items"][0]["link"]["shown"], "files.example/a.pdf"); assert_eq!((sent["items"][0]["cotton"]["line"]["text"].as_str(), sent["items"][0]["cotton"]["line"]["name"].as_str()), (Some("Queued"), Some("a.pdf")));let row = crate::phone::records::call(&handle.client(), "records.get", &json!({ "table": "fetch", "id": made[1] })).expect("the row")["data"].clone(); assert_eq!((row["source"].as_str(), row["source_kind"].as_str(), row["wants"].as_str(), row["state"].as_str(), row["title"].as_str()), (Some("magnet:?xt=urn:btih:abc&dn=Invented"), Some("torrent"), Some("files"), Some("queued"), Some("Invented")));let page = answer(&handle, "chat.downloads", json!({})); assert_eq!(page["items"].as_array().unwrap().len(), 2, "the rows stand in the chat");let none = answer(&handle, "chat.downloads.send", json!({ "text": "can you get me that film?" })); assert_eq!(none["said"], "Send a link here and Cotton will download it."); assert_eq!(none["fetch"], json!([])); assert_eq!(answer(&handle, "chat.downloads", json!({}))["items"].as_array().unwrap().len(), 2, "nothing was kept");let shared = crate::methods::dispatch(&handle, "share.fetchLinks", &json!({ "url": "https://video.example/watch?v=invented", "title": "An Invented Talk", "to": "downloads" })).expect("shared"); assert_eq!(shared["fetch"].as_array().map(Vec::len), Some(1));let page = answer(&handle, "chat.downloads", json!({})); assert_eq!(page["items"][2]["cotton"]["line"]["name"], "An Invented Talk", "the share's card names it");let plain = crate::methods::dispatch(&handle, "share.fetchLinks", &json!({ "url": "https://video.example/watch?v=other" })).expect("answered"); assert_eq!(plain["fetch"], json!([]), "a share into Comms not sent to Downloads is no download");let said = crate::methods::dispatch(&handle, "share.fetchLinks", &json!({ "text": "no link here", "to": "downloads" })).expect("answered"); assert_eq!(said["said"], "Send a link here and Cotton will download it.");}/// RULE: Open on a done download names the Cotton app that plays it by that app's own link to the record, and the file where this phone holds its record, for the phone's viewer, with the words for "Saved to Files"; Retry sends a failed one back to the queue by the object's fetch_retry and stands Queued; neither is offered out of turn.#[test]fn open_names_the_app_that_plays_it_and_retry_queues_a_failed_one_again() {let (_dir, handle) = comms(); signed_in(&handle); fetch(&handle, "f-film", "https://files.example/invented-film.mkv", "done", Some(100.0), None, &iso(50), &iso(40)); landed(&handle, "ff-film", "f-film", "Invented Film.mkv", 1_436_000_000.0, "film", "film", "film-1"); fetch(&handle, "f-photo", "https://files.example/invented.jpg", "done", Some(100.0), None, &iso(45), &iso(44));let sha = "a".repeat(64);let photo_id = format!("photo:{sha}"); landed(&handle, "ff-photo", "f-photo", "invented.jpg", 820_000.0, "photo", "photo", &photo_id);let ws = workspace(&handle);let photo_key = format!("{ws}/photos/{sha}.jpg"); sql( &handle,"INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'image/jpeg', 820000, ?, ?, ?)", &[t(&photo_id), t(&ws), t(&photo_key), t(&sha), t(&iso(44)), t(&iso(44)), t(&iso(44))], ); fetch(&handle, "f-failed", "https://video.example/watch?v=invented", "failed", None, Some("The page asks for a sign-in."), &iso(30), &iso(29));let object = Object::default();let ask = |request: &Value| object.call(request);let film = super::act(&handle.client(), &json!({ "act": "open", "fetch": "f-film" }), &ask).expect("opens"); assert_eq!(film["open"]["apps"], json!([{ "app": "cinemas", "url": "cottoncinemas://lists/film/film-1" }])); assert!(film["open"].get("file").is_none(), "Comms holds no film record: the app is the way"); assert!(film["open"].get("saved").is_none(), "the line says it: its `unopened`");let photo = super::act(&handle.client(), &json!({ "act": "open", "fetch": "f-photo" }), &ask).expect("opens"); assert_eq!(photo["open"]["apps"], json!([{ "app": "photos", "url": format!("cottonphotos://lists/photo/{photo_id}") }])); assert_eq!(photo["open"]["file"], json!({ "key": photo_key }), "the photo's own file, for the phone's viewer");let refused = super::act(&handle.client(), &json!({ "act": "open", "fetch": "f-failed" }), &ask).expect_err("nothing landed"); assert_eq!(refused.code, "not_landed");let refused = super::act(&handle.client(), &json!({ "act": "retry", "fetch": "f-film" }), &ask).expect_err("a done one is not tried again"); assert_eq!(refused.code, "not_stopped"); assert!(object.asked.lock().unwrap().is_empty());let retried = super::act(&handle.client(), &json!({ "act": "retry", "fetch": "f-failed" }), &ask).expect("queued again"); assert_eq!(object.asked.lock().unwrap().as_slice(), [json!({ "act": "fetch_retry", "args": { "fetch": "f-failed" } })]); assert_eq!(retried["item"]["cotton"]["line"]["text"], "Queued");}/// RULE: a download is told on a phone once, only when it is done or failed, never for one that finished before this phone first asked, and never while the chat is muted on this phone (those are taken as told, so unmuting brings none back).#[test]fn a_download_is_told_once_when_done_or_failed_and_never_while_muted() {let (_dir, handle) = comms(); signed_in(&handle); fetch(&handle, "f-old", "https://files.example/old.pdf", "done", Some(100.0), None, &iso(90), &iso(80));let downloads = |handle: &CottonHandle| answer(handle, "chat.notices", json!({}))["downloads"].clone(); assert_eq!(downloads(&handle), json!([]), "the first ask tells nothing that came before it"); fetch(&handle, "f-done", "https://files.example/new.pdf", "done", Some(100.0), None, &iso(5), &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); fetch(&handle, "f-on", "https://files.example/on.pdf", "fetching", Some(10.0), None, &iso(4), &chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true));let told = downloads(&handle);let told = told.as_array().expect("downloads"); assert_eq!(told.len(), 1, "only the done one: {told:?}"); assert_eq!((told[0]["fetch"].as_str(), told[0]["title"].as_str(), told[0]["text"].as_str(), told[0]["state"].as_str()), (Some("f-done"), Some("Downloads"), Some("Done"), Some("done"))); assert_eq!(told[0]["key"], "downloads:f-done"); assert_eq!(downloads(&handle), json!([]), "told once"); answer(&handle, "chat.act", json!({ "thread": THREAD, "act": "mute" })); sql(&handle, "UPDATE cotton_fetch SET state = 'failed', error = 'The server said no.', updated_at = ? WHERE id = 'f-on'", &[t(&chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true))]); assert_eq!(downloads(&handle), json!([]), "muted: nothing"); answer(&handle, "chat.act", json!({ "thread": THREAD, "act": "unmute" })); assert_eq!(downloads(&handle), json!([]), "what came while muted was taken as told");}/// RULE: the Downloads chat stands among the unpinned chats by its newest download's moment, after every pinned one, on the page that moment falls on; before any download it stands last.#[test]fn the_downloads_chat_stands_by_its_newest_download() {let at = |minutes: i64| Some(iso(minutes));let page = vec![(at(1), true), (at(5), false), (at(30), false)]; assert_eq!(place(&page, None, false, at(10).as_deref()), Some(2), "between the chat of 5 minutes ago and the one of 30"); assert_eq!(place(&page, None, false, at(0).as_deref()), Some(1), "newest: after the pinned one, first of the rest"); assert_eq!(place(&page, None, true, at(60).as_deref()), None, "older than this page: a later page holds it"); assert_eq!(place(&page, None, false, at(60).as_deref()), Some(3), "older than all: last"); assert_eq!(place(&page, Some((false, at(40))), false, at(10).as_deref()), None, "an earlier page held it"); assert_eq!(place(&page, None, true, None), None, "no download yet: last, on the last page"); assert_eq!(place(&page, None, false, None), Some(3));}/// RULE (HIDDEN, third review, finding 3; hide from the screen, owner 27 Nov 2026): a download that landed a title/// hidden in Cinemas is not listed on this phone. Comms holds no film table, but it holds the lists, and the landed/// file names its film; a download of anything else stays, and an older build's `in_hidden` mark hides nothing.#[test]fn a_download_of_a_hidden_title_is_not_listed() {let (_dir, handle) = comms(); signed_in(&handle);let ws = workspace(&handle); fetch(&handle, "f-hidden", "https://files.example/hush-reel.mkv", "done", Some(100.0), None, &iso(50), &iso(40)); landed(&handle, "ff-hidden", "f-hidden", "Hush Reel.mkv", 1_000_000.0, "film", "film", "film-hush"); fetch(&handle, "f-book", "https://files.example/invented.epub", "done", Some(100.0), None, &iso(30), &iso(29)); landed(&handle, "ff-book", "f-book", "Invented.epub", 2_000.0, "book", "book", "book-1"); sql(&handle, "UPDATE cotton_fetch SET in_hidden = 1 WHERE id = 'f-book'", &[]); sql(&handle, "INSERT INTO cotton_groups (id, workspace_id, table_id, name, position, created_at, updated_at, hidden) VALUES ('g-hush', ?, 'film', 'Hush', 1, ?, ?, 1)", &[t(&ws), t(&iso(5)), t(&iso(5))]); sql(&handle, "INSERT INTO cotton_group_members (id, workspace_id, group_id, record_id, place, created_at, updated_at) VALUES ('m-hush', ?, 'g-hush', 'film-hush', 1, ?, ?)", &[t(&ws), t(&iso(5)), t(&iso(5))]);let page = answer(&handle, "chat.downloads", json!({}));let fetches: Vec<&str> = page["items"].as_array().expect("items").iter().filter_map(|item| item["fetch"].as_str()).collect(); assert_eq!(fetches, ["f-book"], "{page}"); assert!(!page.to_string().contains("Hush"), "{page}");}/// RULE (HIDDEN 5, coordinator's open item 1): Comms holds no film table, yet a download of a hidden series' episode/// is not listed: the lists (which Comms holds) name the series hidden, and the episode's file names its series (the/// Worker fills it at landing).#[test]fn a_hidden_series_download_is_not_listed() {let (_dir, handle) = comms(); signed_in(&handle);let ws = workspace(&handle); fetch(&handle, "f-ep", "https://files.example/quiet-s02e01.mkv", "done", Some(100.0), None, &iso(50), &iso(40)); landed(&handle, "ff-ep", "f-ep", "Quiet S02E01.mkv", 1_000_000.0, "episode", "episode", "ep-new"); sql(&handle, "UPDATE cotton_fetch_file SET series = 'series-quiet' WHERE id = 'ff-ep'", &[]); fetch(&handle, "f-book", "https://files.example/invented.epub", "done", Some(100.0), None, &iso(30), &iso(29)); landed(&handle, "ff-book", "f-book", "Invented.epub", 2_000.0, "book", "book", "book-1"); sql(&handle, "INSERT INTO cotton_groups (id, workspace_id, table_id, name, position, created_at, updated_at, hidden) VALUES ('g-quiet', ?, 'film', 'Quiet', 1, ?, ?, 1)", &[t(&ws), t(&iso(5)), t(&iso(5))]); sql(&handle, "INSERT INTO cotton_group_members (id, workspace_id, group_id, record_id, place, created_at, updated_at) VALUES ('m-quiet', ?, 'g-quiet', 'series-quiet', 1, ?, ?)", &[t(&ws), t(&iso(5)), t(&iso(5))]);let page = answer(&handle, "chat.downloads", json!({}));let fetches: Vec<&str> = page["items"].as_array().expect("items").iter().filter_map(|item| item["fetch"].as_str()).collect(); assert_eq!(fetches, ["f-book"], "{page}"); assert!(!page.to_string().contains("Quiet"), "{page}");}/// RULE (HIDE FROM SCREEN, CORE 5 M2): a hidden download is left out in the read, before the page is cut. With the/// newest download hidden and forty-one visible ones older, the first page holds forty visible ones and says there are/// earlier ones; the next page holds the forty-first; the list's row stands by the newest visible one.#[test]fn a_hidden_download_among_the_newest_never_hides_older_ones() {let (_dir, handle) = comms(); signed_in(&handle);let ws = workspace(&handle);for n in0..41 { fetch(&handle, &format!("f-open-{n:02}"), &format!("https://files.example/invented-{n}.epub"), "done", Some(100.0), None, &iso(100 + n), &iso(100 + n)); } fetch(&handle, "f-hidden", "https://files.example/hush-reel.mkv", "done", Some(100.0), None, &iso(1), &iso(1)); landed(&handle, "ff-hidden", "f-hidden", "Hush Reel.mkv", 1_000_000.0, "film", "film", "film-hush"); sql(&handle, "INSERT INTO cotton_groups (id, workspace_id, table_id, name, position, created_at, updated_at, hidden) VALUES ('g-hush', ?, 'film', 'Hush', 1, ?, ?, 1)", &[t(&ws), t(&iso(5)), t(&iso(5))]); sql(&handle, "INSERT INTO cotton_group_members (id, workspace_id, group_id, record_id, place, created_at, updated_at) VALUES ('m-hush', ?, 'g-hush', 'film-hush', 1, ?, ?)", &[t(&ws), t(&iso(5)), t(&iso(5))]);let page = answer(&handle, "chat.downloads", json!({}));let fetches: Vec<&str> = page["items"].as_array().expect("items").iter().filter_map(|item| item["fetch"].as_str()).collect(); assert_eq!(fetches.len(), 40, "{page}"); assert!(!fetches.contains(&"f-hidden") && !page.to_string().contains("Hush"), "{page}");let earlier = page["earlier"].as_str().unwrap_or_else(|| panic!("earlier ones remain: {page}"));let next = answer(&handle, "chat.downloads", json!({ "before": earlier }));let older: Vec<&str> = next["items"].as_array().expect("items").iter().filter_map(|item| item["fetch"].as_str()).collect(); assert_eq!(older, ["f-open-40"], "{next}");let row = row_of(&answer(&handle, "chat.list", json!({}))).expect("the Downloads row"); assert!(!row.to_string().contains("Hush"), "{row}");let newest = super::newest(&handle.client()).expect("read").expect("a newest download"); assert_eq!(newest.0, iso_of(&handle, "f-open-00"), "the row stands by the newest visible download");}fn iso_of(handle: &CottonHandle, fetch: &str) -> String {let fetch = fetch.to_string();let answer = handle .client() .read_rows("test.moved", &mut |ctx| {let row = ctx.db().get("SELECT coalesce(updated_at, created_at) AS moved FROM cotton_fetch WHERE id = ?", &[SqlValue::Text(fetch.clone())]).map_err(|e| e.to_string())?;Ok(json!(row.and_then(|row| row.text("moved").map(str::to_string)))) }) .expect("read"); answer.as_str().expect("a moment").to_string()}