//! Pictures at once (23 Nov 2026): a preview in every picture's message, the //! keep policy (thirty days of every chat, and what is opened or scrolled //! near), the fetch ahead of the scroll, the chat list's warm, and Free up //! space, over a phone's own copy and an invented chat store. Every name, //! number and byte is invented. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use base64::Engine as _; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange}; use cotton_client::transport::{Answer, Exchange}; use cotton_core::chat::files; use cotton_core::chat::payload::{self, Picture}; use cotton_core::chat::seal; use serde_json::{json, Value}; use crate::phone::cotton_chat::over; use super::{answer, contact, item, message, refused, sql, t, thread, OwnMedia, ASHA, WEEKEND}; use crate::handle::CottonHandle; use crate::phone::personal_object::ObjectDoor; /// The chat store, answering each file by its path, in any order, and counting what it was asked. #[derive(Debug, Default)] struct Store { files: Mutex>>, asked: Mutex>, /// How long each answer takes, as a network far away (the measured run only). latency_ms: std::sync::atomic::AtomicU64, } impl Store { fn asked(&self) -> Vec { self.asked.lock().unwrap().clone() } } impl Exchange for Store { fn send(&self, origin: &cotton_client::transport::wire::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, ceiling: std::time::Duration) -> Result, String> { self.asked.lock().unwrap().push(request.path.to_string()); let wait = self.latency_ms.load(std::sync::atomic::Ordering::SeqCst); if wait > 0 { std::thread::sleep(std::time::Duration::from_millis(wait)); } let reply = match self.files.lock().unwrap().get(request.path) { Some(bytes) => Reply::new(200, bytes.clone()), None => Reply::new(404, r#"{"code":"not_found"}"#), }; ScriptedExchange::new([reply]).send(origin, request, ceiling) } fn send_stream(&self, origin: &cotton_client::transport::wire::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, _body: &mut dyn std::io::Read, _length: u64, ceiling: std::time::Duration) -> Result, String> { self.send(origin, request, ceiling) } } fn door(handle: &CottonHandle) -> Arc { let store = Arc::new(Store::default()); let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: store.clone(), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string() }; handle.client().set_object_door(Some(Arc::new(door))); store } /// A tiny JPEG's base64, as a phone makes one (only its first bytes matter to the core). fn preview(seed: u8) -> String { let mut bytes = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F']; bytes.extend(std::iter::repeat_n(seed, 600)); bytes.extend([0xFF, 0xD9]); base64::engine::general_purpose::STANDARD.encode(bytes) } /// A picture their phone sealed into the store: its entry, with or without a preview. fn sealed(store: &Store, n: usize, preview: Option) -> Picture { sealed_of(store, n, preview, format!("an invented picture, number {n}").into_bytes()) } fn sealed_of(store: &Store, n: usize, preview: Option, plain: Vec) -> Picture { let s = files::seal_file(&plain).expect("sealed"); let file = format!("{n:032x}"); store.files.lock().unwrap().insert(format!("/v1/chat/files/{file}"), s.bytes); Picture { file, key: seal::key_text(&s.key), sha256: s.sha256, mime: "image/jpeg".into(), width: Some(1200), height: Some(900), bytes: plain.len() as u64, preview, ..Picture::default() } } fn with_pictures(handle: &CottonHandle, id: &str, pictures: &[Picture]) { let meta = json!({ "cotton": { "pictures": pictures } }); sql(handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = ?", &[t(&meta.to_string()), t(id)]); } fn iso_days(days: i64, minutes: i64) -> String { (chrono::Utc::now() - chrono::Duration::days(days) - chrono::Duration::minutes(minutes)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } fn kept(handle: &CottonHandle, id: &str) -> Option { let found = crate::phone::cotton_chat::read(&handle.client(), "test.kept", |ctx| { let row = crate::phone::cotton_chat::one(ctx, "SELECT meta FROM cotton_msg_messages WHERE id = ?", &[t(id)])?; Ok(row.map(|r| crate::phone::cotton_chat::meta_value(r.get("meta").unwrap_or(&Value::Null))["cotton"]["pictures"][0]["kept"].clone()).unwrap_or(Value::Null)) }) .unwrap(); found.as_str().map(str::to_string) } fn asha(handle: &CottonHandle) { contact(handle, "c-asha", "Asha Example", "15550100001"); thread(handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), &iso_days(0, 0)); } /// A picture opened into the test's own folder (its phone's tempdir), never a fixed path under /tmp: the box is /// shared, and a folder another user made there refuses this one ("unwritable Permission denied"). fn ask(dir: &std::path::Path, id: &str) -> Value { json!({ "message": id, "index": 0, "dir": dir.join("opened").to_string_lossy() }) } // RULE (a): a picture's preview is carried inside its message, sealed with the words: the bubble draws it from the // message alone, before any file is asked of anyone; a phone that sent none (an older one) is still read. #[test] fn a_pictures_preview_comes_with_its_message() { let (_dir, handle) = super::phone(); let store = door(&handle); asha(&handle); message(&handle, "m-p1", ASHA, false, "cotton", "live", "", &iso_days(0, 3), 1, None); let with = sealed(&store, 1, Some(preview(1))); with_pictures(&handle, "m-p1", std::slice::from_ref(&with)); message(&handle, "m-p2", ASHA, false, "cotton", "live", "", &iso_days(0, 2), 2, None); with_pictures(&handle, "m-p2", &[sealed(&store, 2, None)]); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(item(&page, "m-p1")["media"][0]["preview"], json!(preview(1)), "{page}"); assert_eq!((item(&page, "m-p1")["media"][0]["width"].as_f64(), item(&page, "m-p1")["media"][0]["height"].as_f64()), (Some(1200.0), Some(900.0)), "its true size, so nothing jumps"); assert!(item(&page, "m-p2")["media"][0].get("preview").is_none(), "an older phone's picture: no preview, still drawn"); assert!(store.asked().is_empty(), "nothing asked to draw them: {:?}", store.asked()); // In the box: the preview rides in the sealed payload, and a box with none still opens. let mut box_ = payload::Payload::message("aaaaaaaaaaaaaaaa", "+15550100001", "+15550100002", 1, None, None, vec![with.clone()]); let opened: payload::Payload = serde_json::from_slice(&box_.bytes()).unwrap(); assert_eq!(opened.pictures[0].preview, Some(preview(1))); box_.pictures[0].preview = None; assert!(!String::from_utf8(box_.bytes()).unwrap().contains("preview"), "left out when there is none"); } // RULE (a, d): the phone's preview goes with what it sends, at once in its own bubble; one that is not a small JPEG is // left out and the picture still goes. The bubble draws the phone's own file (d): nothing waits for the server. #[test] fn a_sent_picture_carries_its_preview_and_draws_from_the_phone() { let (dir, handle) = super::phone(); let store = door(&handle); asha(&handle); message(&handle, "m-a1", ASHA, false, "cotton", "live", "Send me the view", &iso_days(0, 1), 1, None); let (one, two, three) = (dir.path().join("one.jpg"), dir.path().join("two.jpg"), dir.path().join("three.jpg")); for path in [&one, &two, &three] { std::fs::write(path, b"the phone's own picture").unwrap(); } let too_long = "A".repeat(payload::PREVIEW_MAX + 4); let sent = answer( &handle, "chat.act", json!({ "act": "send", "thread": ASHA, "attachments": [ { "path": one.to_string_lossy(), "mime": "image/jpeg", "width": 4032, "height": 3024, "preview": preview(7) }, { "path": two.to_string_lossy(), "mime": "image/jpeg", "preview": "bm90IGEgSlBFRw==" }, { "path": three.to_string_lossy(), "mime": "image/jpeg", "preview": too_long }, ] }), ); let media = &sent["bubble"]["media"]; assert_eq!(media[0]["preview"], json!(preview(7)), "{sent}"); assert!(media[1].get("preview").is_none() && media[2].get("preview").is_none(), "not a JPEG, too long: left out: {sent}"); let id = sent["bubble"]["message"].as_str().unwrap().to_string(); let opened = answer(&handle, "chat.picture", ask(dir.path(), &id)); assert_eq!(opened["path"], json!(one.to_string_lossy()), "the phone's own file: {opened}"); assert!(store.asked().is_empty(), "the server is not asked to show what was just sent"); // The upload's pass takes the preview from the outbox into the sealed picture (cotton_chat::attempt). let source = include_str!("cotton_chat.rs"); assert!(source.contains("preview: picture[\"preview\"].as_str().and_then(payload::preview_of)"), "attempt carries the preview into the box"); } #[test] fn a_preview_travels_only_as_a_small_jpeg() { assert_eq!(payload::preview_of(&preview(3)), Some(preview(3))); assert_eq!(payload::preview_of(&format!("data:image/jpeg;base64,{}", preview(3))), Some(preview(3))); assert_eq!(payload::preview_of(""), None); assert_eq!(payload::preview_of("bm90IGEgSlBFRw=="), None, "not a JPEG"); assert_eq!(payload::preview_of("%%%"), None, "not base64"); let big = base64::engine::general_purpose::STANDARD.encode([&[0xFF, 0xD8, 0xFF][..], &vec![0u8; 2_200]].concat()); assert!(big.len() > payload::PREVIEW_MAX); assert_eq!(payload::preview_of(&big), None, "over 2 KB"); } // RULE (c): the open chat's fetch ahead brings the pictures it shows and those on each side of them onto the phone // (kept in the person's own media, as an opened picture is), so they draw with nothing asked; a second call brings // nothing new; pictures far from the scroll are left. #[test] fn the_fetch_ahead_brings_what_is_shown_and_both_sides() { let (dir, handle) = super::phone(); let store = door(&handle); asha(&handle); for n in 0..60usize { let id = format!("m-{n:02}"); message(&handle, &id, ASHA, n % 3 == 0, "cotton", "live", "", &iso_days(0, 600 - n as i64), n as i64 + 1, None); with_pictures(&handle, &id, &[sealed(&store, n, Some(preview(n as u8)))]); } let shown = ["m-30", "m-31"]; let got = answer(&handle, "chat.ahead", json!({ "thread": ASHA, "messages": shown })); let around = 2 + 2 * crate::phone::chat_ahead::AHEAD_MESSAGES; assert_eq!((got["asked"].as_u64(), got["fetched"].as_u64(), got["failed"].as_u64()), (Some(around as u64), Some(around as u64), Some(0)), "{got}"); for n in (31 - crate::phone::chat_ahead::AHEAD_MESSAGES - 1)..(31 + crate::phone::chat_ahead::AHEAD_MESSAGES) { assert!(kept(&handle, &format!("m-{n:02}")).is_some(), "m-{n:02} is on the phone"); } assert!(kept(&handle, "m-00").is_none() && kept(&handle, "m-59").is_none(), "far from the scroll: left"); let asked = store.asked().len(); for id in shown { let opened = answer(&handle, "chat.picture", ask(dir.path(), id)); assert!(std::path::Path::new(opened["path"].as_str().unwrap()).is_file(), "{opened}"); assert_eq!(opened["previewWanted"], false, "{opened}"); } assert_eq!(store.asked().len(), asked, "drawn from the phone: nothing asked"); let again = answer(&handle, "chat.ahead", json!({ "thread": ASHA, "messages": shown })); assert_eq!((again["here"].as_u64(), again["fetched"].as_u64()), (Some(around as u64), Some(0)), "{again}"); assert_eq!(store.asked().len(), asked, "nothing fetched twice"); // Nothing named: the chat's foot, as it opens. let foot = answer(&handle, "chat.ahead", json!({ "thread": ASHA })); assert!(kept(&handle, "m-59").is_some(), "{foot}"); } // RULE (c): a newer fetch ahead of the same chat stops the older between fetches; another chat's goes on. #[test] fn a_newer_fetch_ahead_stops_the_older() { use crate::phone::chat_ahead::tests_turns::{current, turn}; let first = turn("thread-a"); assert!(current("thread-a", first)); let other = turn("thread-b"); let second = turn("thread-a"); assert!(!current("thread-a", first) && current("thread-a", second)); assert!(current("thread-b", other), "another chat's goes on"); } // RULE (b, c): the chat list warms the newest pictures of its top chats, then the last thirty days of every chat, on // any network; in Low Data Mode it asks nothing at all. A picture older than thirty days outside the top chats waits // to be opened or scrolled near. #[test] fn the_list_warms_the_top_chats_and_thirty_days_but_never_in_low_data_mode() { let (_dir, handle) = super::phone(); let store = door(&handle); let mut n = 0usize; let mut id_of = HashMap::new(); for chat in 0..12usize { let thread_id = format!("11111111-1111-4111-8111-0000000001{chat:02}"); contact(&handle, &format!("c-{chat}"), &format!("Person {chat}"), &format!("1555010{chat:04}")); thread(&handle, &thread_id, "dm", Some(&format!("cotton:+1555010{chat:04}")), None, Some(&format!("c-{chat}")), &iso_days(0, chat as i64 * 10)); // Two recent pictures, and one from forty days ago, in every chat. for (k, at) in [(0, iso_days(0, chat as i64 * 10 + 1)), (1, iso_days(0, chat as i64 * 10 + 2)), (2, iso_days(40, chat as i64))] { let id = format!("m-{chat}-{k}"); message(&handle, &id, &thread_id, false, "cotton", "live", "", &at, k as i64 + 1, None); with_pictures(&handle, &id, &[sealed(&store, n, None)]); id_of.insert((chat, k), id); n += 1; } } let low = answer(&handle, "chat.warm", json!({ "constrained": true })); assert_eq!(low["skipped"], "constrained", "{low}"); assert!(store.asked().is_empty(), "Low Data Mode: nothing asked"); // A page at a time, each call going further back than the last, until nothing is left. let (mut fetched, mut calls) = (0, 0); loop { calls += 1; let warm = answer(&handle, "chat.warm", json!({ "limit": 5 })); assert!(warm["asked"].as_u64().unwrap() <= 5, "{warm}"); if warm["fetched"].as_u64() == Some(0) || calls > 20 { break; } fetched += warm["fetched"].as_u64().unwrap(); } let top = crate::phone::chat_ahead::WARM_CHATS; assert_eq!(fetched, (top * 3 + (12 - top) * 2) as u64, "in {calls} calls"); for chat in 0..12 { assert!(kept(&handle, &id_of[&(chat, 0)]).is_some() && kept(&handle, &id_of[&(chat, 1)]).is_some(), "chat {chat}'s last thirty days"); assert_eq!(kept(&handle, &id_of[&(chat, 2)]).is_some(), chat < top, "chat {chat}'s old picture: only a top chat's newest"); } let asked = store.asked().len(); let again = answer(&handle, "chat.warm", json!({})); assert_eq!(again["fetched"].as_u64(), Some(0), "{again}"); assert_eq!(store.asked().len(), asked, "a second warm asks nothing"); } // RULE (a, e): Free up space takes only full pictures already in the person's account: never a preview (it lives in // the message), never a picture still going up. What it took, the background does not bring back; the open chat's // fetch ahead and an open still do. #[test] fn free_up_space_keeps_previews_and_unsent_pictures() { let (dir, handle) = super::phone(); let store = door(&handle); asha(&handle); message(&handle, "m-up", ASHA, false, "cotton", "live", "", &iso_days(1, 0), 1, None); with_pictures(&handle, "m-up", &[sealed(&store, 1, Some(preview(1)))]); let got = answer(&handle, "chat.ahead", json!({ "thread": ASHA, "messages": ["m-up"] })); assert_eq!(got["fetched"].as_u64(), Some(1), "{got}"); let key = kept(&handle, "m-up").expect("kept"); // Still going up: the phone's own file. let mine = dir.path().join("going-up.jpg"); std::fs::write(&mine, b"the phone's own picture").unwrap(); message(&handle, "m-out", ASHA, true, "cotton", "live", "", &iso_days(0, 1), 2, None); let pending = json!({ "cotton": { "written_at": iso_days(0, 1), "pending_pictures": [{ "path": mine.to_string_lossy(), "mime": "image/jpeg", "preview": preview(2) }] } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ?, send_state = 'queued' WHERE id = 'm-out'", &[t(&pending.to_string())]); // The kept picture reaches the person's account; another of their phones holds it too. sql(&handle, "UPDATE _media SET state = 'synced' WHERE key = ?", &[t(&key)]); let freeable: i64 = handle .client() .with_file(|file| Ok(file.driver.get(&format!("SELECT COUNT(*) AS n FROM _media WHERE key = ? AND {}", crate::methods::shell_settings::FREEABLE), &[t(&key)]).map_err(|e| e.to_string())?.and_then(|row| row.int("n")).unwrap_or(0))) .unwrap(); assert_eq!(freeable, 1, "a kept chat picture in the person's account is what Free up space may take"); let pending_freeable: i64 = handle .client() .with_file(|file| Ok(file.driver.get(&format!("SELECT COUNT(*) AS n FROM _media WHERE local_path = ? AND {}", crate::methods::shell_settings::FREEABLE), &[t(&mine.to_string_lossy())]).map_err(|e| e.to_string())?.and_then(|row| row.int("n")).unwrap_or(0))) .unwrap(); assert_eq!(pending_freeable, 0, "a picture still going up is no file Free up space knows"); // Taken, as Free up space takes it (cotton_store::media_evict::mark_evicted, its file unlinked). let path = handle.client().with_file(|file| Ok(crate::phone::media::local_path_of(file.driver, &key))).unwrap().expect("here"); std::fs::remove_file(&path).unwrap(); handle.client().with_writer(|file| cotton_store::media_evict::mark_evicted(file.driver, &key, "2026-11-23T00:00:00Z").map_err(|e| e.to_string())).unwrap(); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(item(&page, "m-up")["media"][0]["preview"], json!(preview(1)), "the preview stays: {page}"); assert_eq!(item(&page, "m-out")["media"][0]["preview"], json!(preview(2)), "{page}"); assert_eq!(answer(&handle, "chat.picture", ask(dir.path(), "m-out"))["path"], json!(mine.to_string_lossy()), "the unsent picture still opens from the phone"); let warm = answer(&handle, "chat.warm", json!({})); assert_eq!(warm["fetched"].as_u64(), Some(0), "the background does not bring back what was freed: {warm}"); let fetched = Arc::new(OwnMedia::default()); handle.client().set_media_fetch(Some(fetched.clone())); assert!(fetched.0.lock().unwrap().is_empty()); let near = answer(&handle, "chat.ahead", json!({ "thread": ASHA, "messages": ["m-up"] })); assert_eq!(near["fetched"].as_u64(), Some(1), "scrolled near: back from the person's own media: {near}"); assert_eq!(*fetched.0.lock().unwrap(), [key]); } // RULE (a): a picture with no preview (sent before previews, or imported) gets one from the first phone holding its // file: chat.previews lists it, chat.preview writes it into the message once, so every phone has it from then on. #[test] fn an_old_picture_gets_its_preview_from_the_phone_that_holds_it() { let (dir, handle) = super::phone(); let store = door(&handle); asha(&handle); message(&handle, "m-old", ASHA, false, "cotton", "live", "", &iso_days(2, 0), 1, None); with_pictures(&handle, "m-old", &[sealed(&store, 1, None)]); assert_eq!(answer(&handle, "chat.previews", json!({}))["items"], json!([]), "nothing here yet to make one from"); let opened = answer(&handle, "chat.picture", ask(dir.path(), "m-old")); assert_eq!(opened["previewWanted"], true, "{opened}"); let wanted = answer(&handle, "chat.previews", json!({})); assert_eq!(wanted["items"][0]["message"], "m-old", "{wanted}"); assert!(std::path::Path::new(wanted["items"][0]["path"].as_str().unwrap()).is_file(), "{wanted}"); let set = answer(&handle, "chat.preview", json!({ "items": [{ "message": "m-old", "index": 0, "preview": "bm90IGEgSlBFRw==" }] })); assert_eq!(set["set"], 0, "not a JPEG: not written"); let set = answer(&handle, "chat.preview", json!({ "items": [{ "message": "m-old", "index": 0, "preview": preview(5) }] })); assert_eq!(set["set"], 1, "{set}"); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(item(&page, "m-old")["media"][0]["preview"], json!(preview(5)), "{page}"); assert_eq!(answer(&handle, "chat.previews", json!({}))["items"], json!([])); let again = answer(&handle, "chat.preview", json!({ "items": [{ "message": "m-old", "index": 0, "preview": preview(6) }] })); assert_eq!(again["set"], 0, "written once"); assert_eq!(answer(&handle, "chat.picture", ask(dir.path(), "m-old"))["previewWanted"], false); // An imported picture (a WhatsApp picture the Mac uploaded into the person's own media) the same way, in its own entry. let file_id = handle.client().with_file(|file| Ok(file.identity.id().to_string())).unwrap(); thread(&handle, WEEKEND, "group", Some("group:weekend"), Some("Hill trip"), None, &iso_days(3, 0)); message(&handle, "m-imp", WEEKEND, false, "whatsapp", "imported", "", &iso_days(3, 0), 0, None); let media = json!([{ "key": format!("{file_id}/messages/{WEEKEND}/00000012-PHOTO-2026-11-03-10-25-00.jpg"), "contentType": "image/jpeg", "width": 800.0, "height": 600.0 }]); sql(&handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-imp'", &[t(&media.to_string())]); handle.client().set_media_fetch(Some(Arc::new(OwnMedia::default()))); let _ = answer(&handle, "chat.picture", json!({ "message": "m-imp", "index": 0, "dir": dir.path().join("opened").to_string_lossy() })); let wanted = answer(&handle, "chat.previews", json!({})); assert!(wanted["items"].as_array().unwrap().iter().any(|i| i["message"] == "m-imp"), "{wanted}"); assert_eq!(answer(&handle, "chat.preview", json!({ "items": [{ "message": "m-imp", "index": 0, "preview": preview(8) }] }))["set"], 1); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); assert_eq!(item(&page, "m-imp")["media"][0]["preview"], json!(preview(8)), "{page}"); let _ = refused; } // A chat as large as the owner's (23 Nov 2026): 40 chats, 3,000 messages and about 1,500 pictures of // 150 KB (1,720 in all, 480 from the last thirty days), over a chat store that answers each file in 800 ms (the owner's one to // two seconds a picture). Measured before (the shipped path: a picture is fetched when its tile asks, and carries no // preview) and after (previews in the messages, the list's warm, the fetch ahead of the scroll). // Run by hand: cargo test -p cotton-ffi --lib owner_sized -- --ignored --nocapture --test-threads 1 #[test] #[ignore] fn owner_sized_pictures_measured() { use std::sync::atomic::Ordering; use std::time::{Duration, Instant}; const LATENCY: u64 = 800; const SHOWN: usize = 6; const PICTURE_BYTES: usize = 150_000; let owner = |previews: bool| { let (dir, handle) = super::phone(); let store = door(&handle); let (chats, per_chat) = (40usize, 75usize); let mut pictures = 0usize; let mut preview_bytes = 0usize; for chat in 0..chats { let thread_id = format!("11111111-1111-4111-8111-0000000002{chat:02}"); contact(&handle, &format!("c-{chat}"), &format!("Person {chat}"), &format!("1555020{chat:04}")); thread(&handle, &thread_id, "dm", Some(&format!("cotton:+1555020{chat:04}")), None, Some(&format!("c-{chat}")), &iso_days(0, chat as i64)); for k in 0..per_chat { let id = format!("m-{chat}-{k:02}"); // Newest first by k: the first 12 of each chat from the last thirty days, the rest older. let days = if k < 12 { k as i64 } else { 31 + k as i64 * 5 }; message(&handle, &id, &thread_id, k % 2 == 0, "cotton", "live", "Invented words", &iso_days(days, chat as i64), (per_chat - k) as i64, None); if k < 12 || k % 2 == 1 { let p = previews.then(|| preview((k % 250) as u8)); preview_bytes += p.as_ref().map_or(0, |p| p.len() * 3 / 4); let mut plain = vec![0u8; PICTURE_BYTES]; plain[..8].copy_from_slice(&(pictures as u64).to_le_bytes()); with_pictures(&handle, &id, &[sealed_of(&store, pictures, p, plain)]); pictures += 1; } } } store.latency_ms.store(LATENCY, Ordering::SeqCst); (dir, handle, store, pictures, preview_bytes) }; let full = |handle: &CottonHandle| -> i64 { handle.client().with_file(|file| Ok(file.driver.get("SELECT COALESCE(SUM(size_bytes), 0) AS n FROM _media WHERE local_path IS NOT NULL", &[]).map_err(|e| e.to_string())?.and_then(|row| row.int("n")).unwrap_or(0))).unwrap() }; // A chat opened: its newest SHOWN pictures asked at once, as their tiles do; the time until every one is drawn. let open = |handle: &CottonHandle, chat: usize| -> Duration { let ids: Vec = (0..SHOWN).map(|k| format!("m-{chat}-{k:02}")).collect(); let folder = tempfile::tempdir().unwrap(); let opened_in = folder.path(); let started = Instant::now(); std::thread::scope(|scope| { for id in &ids { scope.spawn(move || { let _ = over(&handle.client(), "chat.picture", &ask(opened_in, id)); }); } }); started.elapsed() }; let blank_on_open = |handle: &CottonHandle, chat: usize| -> usize { let thread_id = format!("11111111-1111-4111-8111-0000000002{chat:02}"); let page = answer(handle, "chat.thread", json!({ "thread": thread_id })); page["items"].as_array().unwrap().iter().filter(|i| i["media"][0]["kind"] == "photo" && i["media"][0].get("preview").is_none()).count() }; // Scrolling one chat from its foot up: a screen of 3 pictures every 400 ms. A picture not on the phone when it // comes into view is drawn as its preview (after) or a blank box (before) until its file comes. let scroll = |handle: &CottonHandle, chat: usize, ahead: bool| -> (usize, usize) { let thread_id = format!("11111111-1111-4111-8111-0000000002{chat:02}"); let with: Vec = (0..75usize).filter(|k| *k < 12 || k % 2 == 1).map(|k| format!("m-{chat}-{k:02}")).collect(); let (mut waited, mut seen) = (0, 0); let folder = tempfile::tempdir().unwrap(); let opened_in = folder.path(); std::thread::scope(|scope| { for screen in with.chunks(3) { for id in screen { seen += 1; let here = handle.client().with_file(|file| Ok(file.driver.get("SELECT meta FROM cotton_msg_messages WHERE id = ?", &[t(id)]).map_err(|e| e.to_string())?.and_then(|r| r.text("meta").map(str::to_string)))).unwrap().is_some_and(|m| m.contains("\"kept\"")); if !here { waited += 1; } let id = id.clone(); scope.spawn(move || { let _ = over(&handle.client(), "chat.picture", &ask(opened_in, &id)); }); } if ahead { let (thread_id, shown) = (thread_id.clone(), screen.to_vec()); scope.spawn(move || { let _ = over(&handle.client(), "chat.ahead", &json!({ "thread": thread_id, "messages": shown })); }); } std::thread::sleep(Duration::from_millis(400)); } }); (waited, seen) }; // Before: no previews, nothing fetched ahead, nothing warmed. { let (_d, before, store, pictures, _) = owner(false); println!("owner-sized: 40 chats, 3,000 messages, {pictures} pictures of {} KB, the store {LATENCY} ms an answer", PICTURE_BYTES / 1000); println!("BEFORE kept on the phone: previews 0 bytes, full pictures {} bytes", full(&before)); println!("BEFORE open, cold: {:?} until the {SHOWN} pictures are drawn, {} blank boxes meanwhile", open(&before, 0), blank_on_open(&before, 0)); println!("BEFORE open, again: {:?}", open(&before, 0)); println!("BEFORE open, another chat (the list seen first): {:?}, {} blank", open(&before, 1), blank_on_open(&before, 1)); let (waited, seen) = scroll(&before, 2, false); println!("BEFORE scroll: {waited} of {seen} pictures not on the phone when they came into view, each a blank box for {LATENCY} ms or more"); drop(store); } // After: previews in the messages; the list warms; the chat fetches ahead. let (_d, after, store, _, preview_bytes) = owner(true); println!("AFTER open, cold (just installed and synced): {:?} until drawn, {} blank boxes (previews at once)", open(&after, 0), blank_on_open(&after, 0)); let started = Instant::now(); let mut rounds = 0; loop { rounds += 1; if answer(&after, "chat.warm", json!({}))["fetched"].as_u64() == Some(0) || rounds > 20 { break; } } println!("AFTER the list's warm: {rounds} rounds, {:?}, store asked {} times", started.elapsed(), store.asked().len()); println!("AFTER kept on the phone: previews {preview_bytes} bytes (in the messages), full pictures {} bytes", full(&after)); println!("AFTER open, warm: {:?} until the {SHOWN} pictures are drawn, {} blank", open(&after, 1), blank_on_open(&after, 1)); println!("AFTER open, again: {:?}", open(&after, 1)); let (waited, seen) = scroll(&after, 2, true); println!("AFTER scroll (older than thirty days, fetched ahead): {waited} of {seen} pictures not on the phone when they came into view (drawn as their preview), 0 blank boxes"); }