//! `media.viewed` and `settings.mediaBudget`, end to end through the handle. //! //! The two writes the budgeted phone cache needs, and neither of them touches a //! network: one stamps a column and the other writes a file beside //! `connection.json`. Every fixture is synthetic //! ([nothing-real-ever-goes-in-cotton-s-public-tree]) — an invented workspace, //! an invented digest, no bytes at all. use std::path::Path; use cotton_client::layout::Layout; use serde_json::json; use super::media::{media_moved_event, MediaFetch, NotFetched, MEDIA_EVENT_ORIGIN, PREVIEW_MAX_BASE64_BYTES}; use super::*; const GIB: u64 = 1024 * 1024 * 1024; fn object_key() -> String { format!("{}/photos/{}.heic", crate::fixture::WORKSPACE, "a".repeat(64)) } /// A phone with a replica, opened the way a launch opens one. fn phone() -> (tempfile::TempDir, crate::handle::CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let layout = Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).expect("the client folder"); std::fs::write( layout.connection_json(), serde_json::to_vec_pretty(&json!({ "mode": "remote", "baseUrl": "https://server.invalid", "workspaceId": crate::fixture::WORKSPACE, "ownerId": crate::fixture::OWNER, "connectedAt": "2026-09-11T10:00:00.000Z", })) .expect("json"), ) .expect("the connection record"); let replica = layout.replica(crate::fixture::WORKSPACE); std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder"); drop(crate::fixture::seeded(&replica)); 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: None, vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: None, }) .expect("an open core"); (dir, handle) } fn file_a_row(handle: &crate::handle::CottonHandle, key: &str) { handle .client() .with_writer(|replica| { cotton_store::media_ledger::enqueue_media( replica.driver, &cotton_store::media_ledger::MediaEnqueueInput { key: key.to_string(), workspace_id: replica.workspace_id.to_string(), sha256: "a".repeat(64), content_type: "image/heic".to_string(), size_bytes: 4_194_304, local_path: Some("/invented/media/aa.heic".to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, // The ORIGINAL's row, and not a capture: these tests are // about a picture that arrived, which is the only kind the // budget may ever take. tier: Some(cotton_store::media_holdings::Tier::Original), captured_here: false, now: "2026-09-11T10:00:00.000Z".to_string(), }, ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("the ledger row"); } fn last_viewed(handle: &crate::handle::CottonHandle, key: &str) -> Option { handle .client() .with_writer(|replica| { Ok(cotton_store::media_ledger::media_by_key(replica.driver, key) .ok() .flatten() .and_then(|row| row.last_viewed_at)) }) .expect("the read") } #[test] fn a_view_stamps_the_row_the_budget_orders_by() { let (_dir, handle) = phone(); let key = object_key(); file_a_row(&handle, &key); assert_eq!(last_viewed(&handle, &key), None, "nothing has opened it yet"); let answer = crate::methods::dispatch(&handle, "media.viewed", &json!({ "key": key })) .expect("the stamp"); assert_eq!(answer["viewed"], json!(true)); assert!( last_viewed(&handle, &key).is_some(), "the detail view's open is what the least-recently-viewed rule reads" ); } #[test] fn a_view_of_a_key_the_ledger_does_not_have_is_answered_not_refused() { let (_dir, handle) = phone(); // A screen may open bytes that arrived by a path with no ledger row yet. // Refusing would put a failure on a picture that drew perfectly well. let answer = crate::methods::dispatch(&handle, "media.viewed", &json!({ "key": object_key() })) .expect("an answer rather than a refusal"); assert_eq!(answer["viewed"], json!(false)); } #[test] fn a_view_with_no_key_is_refused_before_anything_is_stamped() { let (_dir, handle) = phone(); let refusal = crate::methods::dispatch(&handle, "media.viewed", &json!({})) .expect_err("a key is the whole argument"); assert_eq!(refusal.code, "bad_request"); } #[test] fn the_budget_moves_only_to_one_of_the_offered_choices() { let (dir, handle) = phone(); let layout = Layout::new(dir.path()); assert_eq!( cotton_client::media::read_budget(&layout), cotton_client::media::MEDIA_BUDGET_DEFAULT_BYTES, "four gigabytes until somebody says otherwise" ); let answer = crate::methods::dispatch( &handle, "settings.mediaBudget", &json!({ "bytes": 8 * GIB }), ) .expect("a choice"); assert_eq!(answer["budgetBytes"], json!(8 * GIB)); assert_eq!(cotton_client::media::read_budget(&layout), 8 * GIB); let refusal = crate::methods::dispatch( &handle, "settings.mediaBudget", &json!({ "bytes": 3 * GIB }), ) .expect_err("not one of the choices"); assert_eq!(refusal.code, "bad_request"); assert_eq!( cotton_client::media::read_budget(&layout), 8 * GIB, "and a refused write leaves the stored value alone" ); // Zero is the one a clamp would have accepted, and it is the one that would // make the phone delete everything it is allowed to. let refusal = crate::methods::dispatch(&handle, "settings.mediaBudget", &json!({ "bytes": 0 })) .expect_err("zero is not a budget"); assert_eq!(refusal.code, "bad_request"); } #[test] fn the_storage_read_carries_the_budget_and_what_it_excludes() { let (dir, handle) = phone(); let layout = Layout::new(dir.path()); cotton_client::media::set_budget(&layout, 2 * GIB).expect("a choice"); let answer = crate::methods::dispatch(&handle, "read.storage", &json!({})) .expect("the storage read"); assert_eq!(answer["budgetBytes"], json!(2 * GIB)); assert_eq!( answer["thumbCeilingBytes"], json!(cotton_client::media::THUMB_CEILING_BYTES) ); assert_eq!( answer["thumbCeilingWarning"], Value::Null, "an empty thumbnail cache is not worth a sentence" ); // THE HONEST ZERO: this phone holds nothing that a second live device also // holds, so nothing could go — which is exactly what a household with one // machine should be told. assert_eq!(answer["evictableBytes"], json!(0)); assert_eq!( answer["thumbBytes"], answer["bytes"]["thumbnails"], "the same walk, named beside the budget because the budget excludes it" ); } // ───────────────────────────────────────────────────────────────────────────── // The phone is TOLD when bytes land // ───────────────────────────────────────────────────────────────────────────── /// The test's own C callback: everything the stream delivered, in order. A C /// function pointer cannot carry a closure's captures, so the record is a /// static and the tests that use it hold `ORDER` for their length. static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); static ORDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); extern "C" fn collect(_ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) { let text = unsafe { std::ffi::CStr::from_ptr(line) } .to_string_lossy() .to_string(); SEEN.lock().expect("the record").push(text); } fn data_events_naming_media() -> Vec { std::mem::take(&mut *SEEN.lock().expect("the record")) .iter() .filter_map(|line| serde_json::from_str::(line).ok()) .filter(|event| { event["kind"] == "data" && event["payload"]["tables"] .as_array() .is_some_and(|tables| tables.iter().any(|table| table == "_media")) }) .collect() } /// A seam that writes fixed bytes. #[derive(Debug)] struct Delivers(Vec); impl MediaFetch for Delivers { fn fetch_to(&self, _database: &str, _key: &str, dest: &Path) -> Result<(), NotFetched> { std::fs::write(dest, &self.0).map_err(|error| error.to_string().into()) } } #[test] fn a_fetch_that_landed_tells_every_screen_once_through_the_ledgers_own_event() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); handle .client() .set_media_fetch(Some(std::sync::Arc::new(Delivers(b"downloaded bytes".to_vec())))); // Subscribe FIRST, which drains whatever `open` buffered, so what is // counted below is only what the ensure caused. handle.events().subscribe(std::ptr::null_mut(), Some(collect)); let _ = data_events_naming_media(); let key = object_key(); let answer = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": key })) .expect("the fetch"); assert_eq!(answer["fetched"], json!(true)); // ONE `data` event, the shape a pull carries, naming the ledger, with an // origin that says the cause was local bytes — so `InvalidationMap`'s one // `_media` entry reaches the screens with nothing new to decode. let events = data_events_naming_media(); assert_eq!(events.len(), 1, "{events:?}"); assert_eq!(events[0]["payload"]["origin"], json!(MEDIA_EVENT_ORIGIN)); assert_eq!(events[0]["payload"]["workspaceId"], json!(crate::fixture::WORKSPACE)); assert_eq!(events[0]["payload"]["moved"]["landed"], json!(1)); // A second ensure is answered off the ledger and moves no bytes, so it // says nothing: a screen redraws on arrivals, not on reads. let again = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": key })) .expect("the second call"); assert_eq!(again["fetched"], json!(false)); assert!(data_events_naming_media().is_empty()); handle.events().subscribe(std::ptr::null_mut(), None); } /// A seam that must never be asked. #[derive(Debug)] struct NeverAsked; impl MediaFetch for NeverAsked { fn fetch_to(&self, _database: &str, key: &str, _dest: &Path) -> Result<(), NotFetched> { panic!("{key} was fetched"); } } /// A seam that records what was asked of it and writes fixed bytes. #[derive(Debug, Default)] struct Asked(std::sync::Mutex>); impl MediaFetch for Asked { fn fetch_to(&self, _database: &str, key: &str, dest: &Path) -> Result<(), NotFetched> { self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(key.to_string()); std::fs::write(dest, b"picture").map_err(|error| error.to_string().into()) } } /// RULE: media.ensure with `tier: largest` (one picture drawn large) fetches the 1600 px display rendition of a photo, never the original; without a tier it fetches the key as it is. #[test] fn ensure_for_the_largest_fetches_the_display_rendition_not_the_original() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); let asked = std::sync::Arc::new(Asked::default()); handle.client().set_media_fetch(Some(asked.clone())); let key = object_key(); let display = cotton_core::media::keys::display_key_for(&key).expect("a photo has a display rendition"); let answer = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": key, "tier": "largest" })).expect("fetched"); assert!(answer["fetched"].as_bool().unwrap_or(false), "{answer}"); assert_eq!(asked.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_slice(), std::slice::from_ref(&display)); let plain = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": key })).expect("fetched"); assert!(plain["fetched"].as_bool().unwrap_or(false), "{plain}"); assert_eq!(asked.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_slice(), [display, key]); } /// RULE: media.ensure refuses a dead key (an erasure names it and no row does) with media_erased and never fetches it, so erased bytes are not landed back on the phone. #[test] fn ensure_never_fetches_dead_bytes() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); handle.client().set_media_fetch(Some(std::sync::Arc::new(NeverAsked))); let key = object_key(); handle .client() .with_writer(|replica| { replica .driver .run( "INSERT INTO cotton_media_erasures (id, workspace_id, key, record_table, record_id, erased_at, actor) \ VALUES ('erasure-1', ?, ?, 'cotton_photos', 'photo:gone', '2026-09-11T10:00:00.000Z', 'device:test')", &[ rusqlite::types::Value::Text(crate::fixture::WORKSPACE.to_string()), rusqlite::types::Value::Text(key.clone()), ], ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("the erasure"); let refused = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": key })) .expect_err("refused"); assert_eq!(refused.code, cotton_core::media::keys::DEAD_KEY_REFUSAL_CODE, "{refused:?}"); } /// RULE: media.ensure never fetches a status's media on a phone — a status is never on a phone, not its row, not its thumbnail and not its bytes — so it refuses with not_kept and asks nobody, while a chat's file on the same phone is fetched as ever and the same status on a Mac is fetched. #[test] fn ensure_never_fetches_a_statuss_bytes_on_a_phone() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); let client = handle.client(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); let file_as = |platform: &str| { client .with_writer(|f| { f.driver .run( "UPDATE cotton_devices SET platform = ? WHERE device_id = ?", &[ rusqlite::types::Value::Text(platform.to_string()), rusqlite::types::Value::Text(crate::fixture::SELF_DEVICE_ID.to_string()), ], ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("the device's platform"); }; client.with_writer(|f| { crate::fixture::this_devices_row(f.driver); Ok(()) }).expect("this device's row"); client.with_writer(|f| { crate::fixture::a_mac_behind(f.driver); Ok(()) }).expect("the Mac behind it"); file_as("ios"); let status = format!("{}/messages/statuses/{}.jpg", crate::fixture::WORKSPACE, "b".repeat(64)); let chat = format!("{}/messages/chat-1/{}.jpg", crate::fixture::WORKSPACE, "c".repeat(64)); client.set_media_fetch(Some(std::sync::Arc::new(NeverAsked))); let refused = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": status })) .expect_err("a status's bytes are refused on a phone"); assert_eq!(refused.code, super::media::STATUS_NOT_KEPT_CODE, "{refused:?}"); client.set_media_fetch(Some(std::sync::Arc::new(Delivers(b"a chat's picture".to_vec())))); let fetched = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": chat })).expect("a chat's file"); assert_eq!(fetched["fetched"], json!(true), "the rule is about statuses and nothing else in a chat"); file_as("mac"); let fetched = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": status })).expect("a Mac's status"); assert_eq!(fetched["fetched"], json!(true), "a Mac keeps everything"); } #[test] fn the_sweeps_event_is_the_same_shape_with_the_same_origin() { let event = media_moved_event( crate::fixture::WORKSPACE, cotton_client::media::MediaMoved { landed: 7, evicted: 2, }, ); assert_eq!(event["tables"], json!(["_media"])); assert_eq!(event["origin"], json!("media")); assert_eq!(event["moved"], json!({ "landed": 7, "evicted": 2 })); } /// The blur's cap is `cotton-core`'s and this crate declares no number of its /// own: the day the phone said 1,536 and the Mac said 1,024 is the day this /// test was written. #[test] fn the_preview_cap_is_the_cores_own_and_not_a_second_number() { assert_eq!( PREVIEW_MAX_BASE64_BYTES, cotton_core::media::tiers::PREVIEW_MAX_BASE64_BYTES ); } // Storage's UI must see the same per-tool rule it writes, including another // device's as-yet-unknown figures, and Free up now must require confirmation. #[test] fn storage_rules_cross_the_phone_boundary_without_inventing_remote_readings() { let (_dir,handle)=phone(); let client=handle.client(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); client.with_writer(|f| { crate::fixture::this_devices_row(f.driver); crate::fixture::device_row(f.driver,"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); Ok(()) }).unwrap(); let remote="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; let changed=crate::methods::dispatch(&handle,"storage.keepRule",&json!({"deviceId":remote,"tool":"photo","keepRule":"recent_90_days"})).unwrap(); assert_eq!(changed["keepRule"],"recent_90_days"); let read=crate::methods::dispatch(&handle,"read.storage",&json!({"deviceId":remote})).unwrap(); let row=read["rows"].as_array().unwrap().iter().find(|r|r["tool"]=="photo").unwrap(); assert_eq!(row["keepRule"],"recent_90_days"); assert_eq!(row["isThisDevice"],false); assert!(row["heldBytes"].is_null());assert!(row["measuredAt"].is_null()); assert!(read["totalFreeableBytes"].is_null()); // Only the tools that hold bytes are listed, and a rule for any other is refused by name. let tools: Vec<&str> = read["rows"].as_array().unwrap().iter().filter_map(|r| r["tool"].as_str()).collect(); assert_eq!(tools, ["photo", "video", "document", "thread"]); let refused = crate::methods::dispatch(&handle,"storage.keepRule",&json!({"deviceId":remote,"tool":"meeting","keepRule":"only_opened"})).unwrap_err(); assert_eq!(refused.code, "refused"); assert!(refused.message.contains("meeting"), "{}", refused.message); assert!(crate::methods::dispatch(&handle,"storage.freeUp",&json!({})).is_err()); assert!(crate::methods::dispatch(&handle,"storage.freeUp",&json!({"confirmed":true,"expectedFreeableBytes":0,"deviceId":remote})).is_err()); let receipt=crate::methods::dispatch(&handle,"storage.freeUp",&json!({"confirmed":true,"expectedFreeableBytes":0})).unwrap(); assert_eq!(receipt["undoable"],false);assert_eq!(receipt["freedBytes"],0); } // A confirmation is a ceiling on local bytes removed, not permission to apply // a newer, larger plan. The refusal must happen before any unlink. #[test] fn storage_free_up_refuses_more_bytes_than_the_person_confirmed() { let (_dir, handle) = phone(); let client = handle.client(); let device = crate::fixture::SELF_DEVICE_ID; let remote = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; let workspace = crate::fixture::WORKSPACE; client.set_self_device_id(Some(device.into())); let path = client.layout().client_media_dir().join(workspace).join("storage-original"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, b"invented").unwrap(); let key = object_key(); client.with_writer(|f| { let text = |s: &str| rusqlite::types::Value::Text(s.into()); crate::fixture::this_devices_row(f.driver); crate::fixture::device_row(f.driver, remote); f.driver.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('storage-confirm-serving',?,999,?,'device:synthetic','2026-01-01')", &[text(workspace),text(remote)]).map_err(|e|e.to_string())?; f.driver.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES (?, ?, ?, 'photo','only_opened','2026-01-01','2026-01-01')", &[text(&cotton_store::storage_rules::row_id(device,"photo")),text(workspace),text(device)]).map_err(|e|e.to_string())?; f.driver.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier) VALUES (?,?,'synthetic','image/jpeg',8,?,'synced','2026-01-01','2026-01-01','original')", &[text(&key),text(workspace),text(path.to_str().unwrap())]).map_err(|e|e.to_string())?; f.driver.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES ('storage-confirm-held',?,?,?,'original',8,'2026-01-01','2026-01-01')", &[text(workspace),text(&key),text(remote)]).map_err(|e|e.to_string())?; Ok(()) }).unwrap(); let read = crate::methods::dispatch(&handle, "read.storage", &json!({})).unwrap(); assert_eq!(read["totalFreeableBytes"], 8); let refused = crate::methods::dispatch(&handle, "storage.freeUp", &json!({"confirmed":true,"expectedFreeableBytes":7})).unwrap_err(); assert_eq!(refused.code, "refused"); assert!(path.exists()); let applied = crate::methods::dispatch(&handle, "storage.freeUp", &json!({"confirmed":true,"expectedFreeableBytes":8})).unwrap(); assert_eq!(applied["freedBytes"], 8); assert!(!path.exists()); } /// RULE: read.databaseStorage lists every live device of the database with what it keeps per tool: this device measured now, another from its synced rows, and a device that never measured says null, never 0, so the total is unknown too. #[test] fn database_storage_lists_every_device_and_never_invents_a_reading() { let (_dir, handle) = phone(); let client = handle.client(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); let remote = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; client .with_writer(|f| { crate::fixture::this_devices_row(f.driver); crate::fixture::device_row(f.driver, remote); Ok(()) }) .unwrap(); let read = crate::methods::dispatch(&handle, "read.databaseStorage", &json!({})).expect("the storage read"); let devices = read["devices"].as_array().expect("devices"); assert_eq!(devices.len(), 2, "{read}"); let mine = devices.iter().find(|d| d["thisDevice"] == true).expect("this device"); assert_eq!(mine["deviceId"], crate::fixture::SELF_DEVICE_ID); assert!(mine["keptBytes"].is_i64(), "this device is measured now: {mine}"); assert!(mine["byTool"].as_array().unwrap().iter().all(|t| t["heldBytes"].is_i64())); assert!( mine["byTool"].as_array().unwrap().iter().all(|t| t["onDemandBytes"].is_i64()), "this device says how much of what it holds is on demand: {mine}" ); let other = devices.iter().find(|d| d["deviceId"] == remote).expect("the other device"); assert_eq!(other["thisDevice"], false); assert!(other["keptBytes"].is_null(), "never measured is unknown, not 0: {other}"); assert!(other["freeableBytes"].is_null()); let tools: Vec<&str> = other["byTool"].as_array().unwrap().iter().filter_map(|t| t["tool"].as_str()).collect(); assert_eq!(tools, ["photo", "video", "document", "thread"]); assert!(other["byTool"][0]["heldBytes"].is_null()); assert!(other["byTool"][0]["onDemandBytes"].is_null(), "and another device's on-demand bytes are unknown"); assert!(read["totalKeptBytes"].is_null(), "one unknown device makes the total unknown"); } /// RULE: Space for kept things is the device's synced choice, accepts only offered caps or no limit, and a remote phone's usage must remain unknown rather than reading this Mac's local paths. #[test] fn kept_space_is_a_synced_device_choice_and_remote_usage_is_unknown() { let (_dir,handle)=phone();let client=handle.client(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); let remote="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; client.with_writer(|f| {crate::fixture::this_devices_row(f.driver);crate::fixture::device_row(f.driver,remote);Ok(())}).unwrap(); let default=crate::methods::dispatch(&handle,"read.keepFetch",&json!({"deviceId":remote})).unwrap(); assert_eq!(default["keptSpaceBytes"],2_000_000_000u64);assert!(default["fetchedBytes"].is_null()); let instagram_before=default["byteRules"].as_array().unwrap().iter().find(|r|r["tool"]=="instagram").unwrap()["keepRule"].clone(); crate::methods::dispatch(&handle,"storage.keepRule",&json!({"deviceId":remote,"tool":"whatsapp","keepRule":"all"})).unwrap(); let sources=crate::methods::dispatch(&handle,"read.keepFetch",&json!({"deviceId":remote})).unwrap(); assert_eq!(sources["byteRules"].as_array().unwrap().iter().find(|r|r["tool"]=="whatsapp").unwrap()["keepRule"],"all"); assert_eq!(sources["byteRules"].as_array().unwrap().iter().find(|r|r["tool"]=="instagram").unwrap()["keepRule"],instagram_before); for choice in [json!(1_000_000_000u64),json!(5_000_000_000u64),Value::Null] { crate::methods::dispatch(&handle,"storage.keptSpace",&json!({"deviceId":remote,"keptSpaceBytes":choice})).unwrap(); let read=crate::methods::dispatch(&handle,"read.keepFetch",&json!({"deviceId":remote})).unwrap(); assert_eq!(read["keptSpaceBytes"],choice); } for bad in [json!(0),json!(-1),json!(3_000_000_000u64),json!("2 GB")] { assert!(crate::methods::dispatch(&handle,"storage.keptSpace",&json!({"deviceId":remote,"keptSpaceBytes":bad})).is_err()); } let local=crate::methods::dispatch(&handle,"read.keepFetch",&json!({})).unwrap(); assert!(local["fetchedBytes"].is_null());assert!(local["full"].is_null()); } /// RULE: a tool's picture is drawn from the package bytes the database file carries (`cotton_tool_assets`), never fetched from a Mac and never blank while its photo record is yet to be written — and only bytes whose digest is the key's (290 walk: the Disk and Quotas tiles drew no picture). #[test] fn a_tools_picture_comes_from_the_package_the_file_carries() { use base64::Engine as _; use sha2::{Digest as _, Sha256}; let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); handle.client().set_media_fetch(Some(std::sync::Arc::new(NeverAsked))); let picture = b"invented tool picture bytes".to_vec(); let sha = hex::encode(Sha256::digest(&picture)); let wrong = "0".repeat(64); handle .client() .with_writer(|replica| { for (name, bytes) in [(format!("{sha}.png"), &picture), (format!("{wrong}.png"), &picture)] { replica .driver .run( "INSERT INTO cotton_tool_assets (id, workspace_id, tool_id, name, bytes, created_at, updated_at) \ VALUES (?, ?, 'invented', ?, ?, '2026-10-17T00:00:00.000Z', '2026-10-17T00:00:00.000Z')", &[ rusqlite::types::Value::Text(format!("asset-{name}")), rusqlite::types::Value::Text(crate::fixture::WORKSPACE.to_string()), rusqlite::types::Value::Text(name.clone()), rusqlite::types::Value::Text(base64::engine::general_purpose::STANDARD.encode(bytes)), ], ) .map_err(|error| error.to_string())?; } Ok(()) }) .expect("the package's pictures"); let answer = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": format!("photo:{sha}") })) .expect("drawn from the file"); let path = answer["path"].as_str().expect("a path"); assert_eq!(std::fs::read(path).expect("the bytes"), picture); handle.client().set_media_fetch(Some(std::sync::Arc::new(NotThere))); let refused = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": format!("photo:{wrong}") })); assert!(refused.is_err(), "bytes whose digest is not the key's are not that picture"); } /// A seam with nothing to hand over. #[derive(Debug)] struct NotThere; impl MediaFetch for NotThere { fn fetch_to(&self, _database: &str, _key: &str, _dest: &Path) -> Result<(), NotFetched> { Err("not there".to_string().into()) } } /// RULE: keep-fetch reads only the worker's stored facts, never the media catalogue; before its first pass usage is unknown, so opening Devices cannot start a twenty-second scan. #[test] fn keep_fetch_read_never_opens_the_media_catalogue() { let (_dir, handle) = phone(); let client = handle.client(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); client.with_writer(|f| { crate::fixture::this_devices_row(f.driver); f.driver.exec("DROP TABLE cotton_photos").map_err(|e| e.to_string()) }).unwrap(); let before = cotton_store::driver::Driver::thread_steps(); let answer = crate::methods::dispatch(&handle, "read.keepFetch", &json!({})).unwrap(); assert!(answer["fetchedBytes"].is_null(), "not yet measured: {answer}"); assert!(answer["full"].is_null()); assert!(cotton_store::driver::Driver::thread_steps() - before < 5_000); } // ── the pictures sweep ────────────────────────────────────────────────────── use super::media_sweep::{self, Caps}; fn write(handle: &crate::handle::CottonHandle, sql: &str, values: Vec) { handle .client() .with_writer(|f| f.driver.run(sql, &values).map(|_| ()).map_err(|error| error.to_string())) .expect("a fixture row"); } fn text(value: &str) -> rusqlite::types::Value { rusqlite::types::Value::Text(value.to_string()) } /// An invented photo, or film, taken at `at`. fn a_picture(handle: &crate::handle::CottonHandle, table: &str, sha: &str, at: &str) { let (kind, ext) = if table == "cotton_videos" { ("video", "mp4") } else { ("photo", "heic") }; let key = format!("{}/{kind}s/{sha}.{ext}", crate::fixture::WORKSPACE); write( handle, &format!( "INSERT INTO {table} (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, 'image/heic', 10, ?, ?, ?)" ), vec![text(&format!("{kind}:{sha}")), text(crate::fixture::WORKSPACE), text(&key), text(sha), text(at), text(at), text(at)], ); } /// An invented message in one thread carrying one file; answers the file's key. fn a_chat_file(handle: &crate::handle::CottonHandle, id: &str, sha: &str, ext: &str, content_type: &str, at: &str) -> String { write( handle, "INSERT OR IGNORE INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES ('thread-1', ?, 'group', 'Example group', ?, ?)", vec![text(crate::fixture::WORKSPACE), text(at), text(at)], ); let key = cotton_core::media::keys::message_media_key(crate::fixture::file_id(), "thread-1", sha, ext); let media = json!([{ "key": key, "contentType": content_type }]).to_string(); write( handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, media, sent_at, created_at) \ VALUES (?, 'thread-1', ?, 'in', 'whatsapp', 'imported', ?, ?, ?)", vec![text(id), text(crate::fixture::WORKSPACE), text(&media), text(at), text(at)], ); key } fn photo_thumb(sha: &str) -> String { cotton_core::media::keys::photo_thumb_key(crate::fixture::file_id(), sha) } fn film_thumb(sha: &str) -> String { cotton_core::media::keys::video_thumb_key(crate::fixture::file_id(), sha) } fn chat_thumb(key: &str) -> String { cotton_core::media::keys::thumb_key_for(key).expect("a chat's picture has a thumbnail") } /// A thumbnail already on this phone: its file, and the ledger row naming it. fn held(handle: &crate::handle::CottonHandle, dir: &tempfile::TempDir, key: &str) { let path = dir.path().join("held.jpg"); std::fs::write(&path, b"held").expect("the held file"); handle .client() .with_writer(|replica| { cotton_store::media_ledger::enqueue_media( replica.driver, &cotton_store::media_ledger::MediaEnqueueInput { key: key.to_string(), workspace_id: replica.workspace_id.to_string(), sha256: "f".repeat(64), content_type: "image/jpeg".to_string(), size_bytes: 4, local_path: Some(path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, tier: Some(cotton_store::media_holdings::Tier::Thumb), captured_here: false, now: "2026-10-26T10:00:00.000Z".to_string(), }, ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("the ledger row"); } fn asked_of(asked: &Asked) -> Vec { asked.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone() } /// Three photos (one thumbnail already here), a film, two chat pictures and a /// voice note; answers the thumbnails wanted, newest first. fn a_mixed_copy(handle: &crate::handle::CottonHandle, dir: &tempfile::TempDir) -> Vec { let sha = |c: char| c.to_string().repeat(64); a_picture(handle, "cotton_photos", &sha('1'), "2026-10-01T09:00:00.000Z"); a_picture(handle, "cotton_photos", &sha('2'), "2026-10-03T09:00:00.000Z"); held(handle, dir, &photo_thumb(&sha('2'))); a_picture(handle, "cotton_photos", &sha('3'), "2026-10-05T09:00:00.000Z"); a_picture(handle, "cotton_videos", &sha('4'), "2026-10-04T09:00:00.000Z"); let newest = a_chat_file(handle, "message-1", &sha('5'), "png", "image/png", "2026-10-06T09:00:00.000Z"); a_chat_file(handle, "message-2", &sha('6'), "ogg", "audio/ogg", "2026-10-07T09:00:00.000Z"); let older = a_chat_file(handle, "message-3", &sha('7'), "jpg", "image/jpeg", "2026-10-02T09:00:00.000Z"); vec![chat_thumb(&newest), photo_thumb(&sha('3')), film_thumb(&sha('4')), chat_thumb(&older), photo_thumb(&sha('1'))] } /// RULE: the pictures sweep asks only for the 256 px thumbnails this phone lacks — every photo's, every film's and every picture's a message carries, never a voice note's — newest first, and no more in one sweep than its cap; the rest come the next sweep. #[test] fn the_pictures_sweep_asks_only_for_missing_thumbnails_newest_first_and_no_more_than_its_cap() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let wanted = a_mixed_copy(&handle, &dir); let client = handle.client(); assert_eq!(media_sweep::wanted(&client, 100).expect("the work list"), wanted); let asked = std::sync::Arc::new(Asked::default()); client.set_media_fetch(Some(asked.clone())); let first = media_sweep::run(&client, handle.events(), Caps { fetches: 3, in_flight: 1 }).expect("a sweep"); assert_eq!(asked_of(&asked), wanted[..3].to_vec(), "the three newest, in order"); assert_eq!((first.wanted, first.landed, first.failed), (3, 3, 0)); let second = media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("the next sweep"); let mut rest = asked_of(&asked)[3..].to_vec(); rest.sort(); let mut expected = wanted[3..].to_vec(); expected.sort(); assert_eq!(rest, expected, "the next sweep asks for the rest"); assert_eq!(second.landed, 2); } /// RULE: a pictures sweep over a copy whose thumbnails are all on this phone asks for nothing. #[test] fn a_second_pictures_sweep_asks_for_nothing_when_every_thumbnail_is_here() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let wanted = a_mixed_copy(&handle, &dir); let client = handle.client(); let asked = std::sync::Arc::new(Asked::default()); client.set_media_fetch(Some(asked.clone())); media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("a sweep"); assert_eq!(asked_of(&asked).len(), wanted.len()); let again = media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("the next sweep"); assert_eq!(again, media_sweep::SweepPass::default(), "nothing is wanted"); assert_eq!(asked_of(&asked).len(), wanted.len(), "and nothing more was asked"); } /// A seam that refuses the first key it is asked for, once, and records every ask. #[derive(Debug, Default)] struct FailsOnce { asked: std::sync::Mutex>, refused: std::sync::Mutex>, } impl MediaFetch for FailsOnce { fn fetch_to(&self, _database: &str, key: &str, dest: &Path) -> Result<(), NotFetched> { self.asked.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(key.to_string()); let mut refused = self.refused.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if refused.is_none() { *refused = Some(key.to_string()); return Err(NotFetched { waiting: None, reason: "the object did not answer".to_string(), status: Some(0) }); } std::fs::write(dest, b"picture").map_err(|error| error.to_string().into()) } } /// RULE: a thumbnail whose fetch failed is skipped for the rest of that sweep and asked again by the next one. #[test] fn a_failed_thumbnail_is_asked_again_by_the_next_sweep() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let wanted = a_mixed_copy(&handle, &dir); let client = handle.client(); let fetch = std::sync::Arc::new(FailsOnce::default()); client.set_media_fetch(Some(fetch.clone())); let first = media_sweep::run(&client, handle.events(), Caps { fetches: 100, in_flight: 1 }).expect("a sweep"); assert_eq!((first.landed, first.failed), (wanted.len() - 1, 1)); let refused = fetch.refused.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone().expect("one was refused"); assert_eq!(refused, wanted[0]); assert_eq!(fetch.asked.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).len(), wanted.len(), "each asked once this sweep"); let second = media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("the next sweep"); assert_eq!((second.wanted, second.landed, second.failed), (1, 1, 0)); assert_eq!(fetch.asked.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).last(), Some(&refused)); } /// A seam the object answers 404 for one key through, and every ask recorded. #[derive(Debug, Default)] struct OneMissing { asked: std::sync::Mutex>, missing: std::sync::Mutex>, } impl MediaFetch for OneMissing { fn fetch_to(&self, _database: &str, key: &str, dest: &Path) -> Result<(), NotFetched> { self.asked.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(key.to_string()); if self.missing.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_deref() == Some(key) { return Err(NotFetched { waiting: None, reason: "no such media".to_string(), status: Some(404) }); } std::fs::write(dest, b"picture").map_err(|error| error.to_string().into()) } } /// RULE: a key the object answered 404 for is not asked again by the next sweep nor by a card drawing it (`media.ensure`): both are refused `bytes_not_uploaded` with no request until its wait is over (on live a phone asked the same missing pictures after every pass, a 404 storm); a key whose fetch failed any other way is still asked again. #[test] fn a_key_the_object_does_not_hold_is_not_asked_again_by_the_next_sweep_or_a_card() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let wanted = a_mixed_copy(&handle, &dir); let client = handle.client(); let fetch = std::sync::Arc::new(OneMissing::default()); *fetch.missing.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(wanted[0].clone()); client.set_media_fetch(Some(fetch.clone())); let asked = || fetch.asked.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone(); let first = media_sweep::run(&client, handle.events(), Caps { fetches: 100, in_flight: 1 }).expect("a sweep"); assert_eq!((first.landed, first.failed), (wanted.len() - 1, 1)); assert_eq!(asked().len(), wanted.len()); let second = media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("the next sweep"); assert_eq!((second.wanted, second.landed, second.failed), (1, 0, 1), "still wanted, still not here"); assert_eq!(asked().len(), wanted.len(), "but not asked of the object again"); let refused = crate::methods::dispatch(&handle, "media.ensure", &json!({ "key": wanted[0] })).expect_err("a card drawing it"); assert_eq!(refused.code, "bytes_not_uploaded"); assert_eq!(asked().len(), wanted.len(), "a card asks nothing either"); assert_eq!(client.absent_media().len(), 1); assert!(client.absent_media().waits(&wanted[0], client.now().timestamp_millis()).is_some()); // Once the wait is over, it is asked again, and bytes that come end it. client.absent_media().forget(&wanted[0]); *fetch.missing.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; let third = media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("a sweep after the wait"); assert_eq!((third.wanted, third.landed, third.failed), (1, 1, 0)); assert_eq!(asked().last(), Some(&wanted[0])); assert!(client.absent_media().is_empty()); } /// RULE: the pictures sweep never asks for an original or a 1600 px rendition: every key it asks is a 256 px thumbnail. #[test] fn the_pictures_sweep_asks_for_nothing_but_thumbnails() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); a_mixed_copy(&handle, &dir); let client = handle.client(); let asked = std::sync::Arc::new(Asked::default()); client.set_media_fetch(Some(asked.clone())); media_sweep::run(&client, handle.events(), Caps::SHIPPED).expect("a sweep"); let asked = asked_of(&asked); assert!(!asked.is_empty(), "the sweep asked for something"); for key in &asked { assert_eq!( cotton_core::media::keys::rendition_of(key), Some(cotton_store::media_holdings::Tier::Thumb), "{key} is not a thumbnail" ); } } /// RULE: photo columns on data tables join the sweep; text and file columns /// never do, and an arrived poster stops being requested. #[test] fn the_pictures_sweep_reads_declared_photo_columns_without_a_photos_row() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let original = format!("{}/photos/{}.jpg", crate::fixture::WORKSPACE, "e".repeat(64)); declared_film(&handle, &original); let thumb = cotton_core::media::keys::thumb_key_for(&original).unwrap(); assert_eq!(media_sweep::wanted(&handle.client(), 100).unwrap(), vec![thumb.clone()]); held(&handle, &dir, &thumb); assert!(media_sweep::wanted(&handle.client(), 100).unwrap().is_empty()); } /// A synthetic film with a poster and no Photos row. pub(super) fn declared_film(handle: &crate::handle::CottonHandle, original: &str) { handle.client().with_writer(|file| { let raw = include_str!("../../../cotton-core/kits/personal/tables/film.json"); let definition = cotton_core::definitions::TableDefinition::from_json(raw).unwrap(); if file.driver.get("SELECT 1 FROM sqlite_master WHERE name = 'cotton_film'", &[]).map_err(|error| error.to_string())?.is_none() { for sql in cotton_store::schema::package_tables::generate(&definition.physical_tables().unwrap(), true).unwrap() { file.driver.exec(&sql).map_err(|error| error.to_string())?; } } file.driver.run("INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES ('film', ?1, ?2, 0, 0, '2026-10-01', '2026-10-01')", &[text(file.workspace_id), text(raw)]).map_err(|error| error.to_string())?; file.driver.run("INSERT INTO cotton_film (id, workspace_id, title, poster, file, created_at, updated_at) VALUES ('film-test', ?1, ?2, ?2, ?3, '2026-10-01', '2026-10-01')", &[text(file.workspace_id), text(original), text(&format!("{}/photos/{}.jpg", crate::fixture::WORKSPACE, "f".repeat(64)))]).map_err(|error| error.to_string())?; Ok(()) }).expect("a data-defined film"); } // ── a book, captured from the share sheet ────────────────────────────────── /// An invented book file and cover in the test's own folder. fn book_files(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) { let book = dir.join("the-lantern-orchard.epub"); std::fs::write(&book, b"PK\x03\x04 an invented book, not a real one").expect("the book"); let cover = dir.join("cover.jpg"); std::fs::write(&cover, b"\xff\xd8\xff an invented cover").expect("the cover"); (book, cover) } // RULE: a shared EPUB or PDF becomes a book row with its file under `/books/.`, what the phone read from the file, source file, Want to read, added today in the phone's own zone, and its cover a picture key with no Photos row; the same file shared again is the same book. #[test] fn a_book_capture_makes_its_row_with_its_file_and_cover_and_once() { let (dir, client) = crate::shell::client::phone_tests::attached(); let (book, cover) = book_files(dir.path()); let request = json!({ "path": book.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "the-lantern-orchard.epub", "book": {"format": "epub", "title": "The Lantern Orchard", "author": "Irena Valcourt", "language": "en", "isbn": "9780000000002"}, "coverPath": cover.to_string_lossy(), }); let capture = |request: &Value| -> Value { let mut parsed = super::media::validate_capture(request).expect("a book's request"); // What `capture` sets from the zone the app opened the core with. parsed.book.as_mut().expect("a book").zone = "Asia/Kolkata".to_string(); let layout = client.layout().clone(); let written = client .write_rows("capture.media", &mut |ctx| super::media::write_media(ctx, &layout, &parsed, client.self_device_id().as_deref())) .expect("a book"); written["answer"].clone() }; let answer = capture(&request); let key = answer["key"].as_str().expect("its key").to_string(); assert!(key.starts_with(&format!("{}/books/", crate::fixture::WORKSPACE)) && key.ends_with(".epub"), "{key}"); let id = answer["recordId"].as_str().expect("its row").to_string(); assert_eq!(answer["existing"], json!(false)); let cover_key = answer["coverKey"].as_str().expect("its cover").to_string(); assert!(cover_key.contains("/photos/") && cover_key.ends_with(".jpg"), "{cover_key}"); let record = crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": id})).expect("the book"); let data = &record["data"]; assert_eq!(data["title"], "The Lantern Orchard"); assert_eq!(data["author"], "Irena Valcourt"); assert_eq!(data["file"], json!(key)); assert_eq!(data["format"], "epub"); assert_eq!(data["source"], "file"); assert_eq!(data["status"], "want_to_read"); assert_eq!(data["cover"], json!(cover_key)); assert_eq!(data["added_on"].as_str().map(str::len), Some(10), "{data}"); for queued in [&key, &cover_key] { let row = client.with_writer(|replica| Ok(cotton_store::media_ledger::media_by_key(replica.driver, queued).ok().flatten())).expect("the ledger"); assert!(row.is_some(), "{queued} is queued to go up"); } let photos = client .with_writer(|replica| replica.driver.get("SELECT COUNT(*) AS n FROM cotton_photos", &[]).map_err(|e| e.to_string())) .expect("photos") .and_then(|row| row.int("n")) .unwrap_or(0); assert_eq!(photos, 0, "a book's cover is no photo"); let again = capture(&request); assert_eq!(again["recordId"], json!(id), "the same file is the same book"); assert_eq!(again["existing"], json!(true)); } /// An invented EPUB 3 whose package says its title, author, language, ISBN, /// DOI, publisher, description, subjects, year, series and cover, deflated /// as a real one is. fn invented_epub(dir: &Path) -> std::path::PathBuf { use std::io::Write; let path = dir.join("0f3c-staged.epub"); let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).expect("the archive")); let deflated = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); let files: [(&str, &[u8]); 4] = [ ("mimetype", b"application/epub+zip"), ("META-INF/container.xml", br#""#), ("OPS/package.opf", br##" The Lantern OrchardIrena Valcourten urn:isbn:9780000000002doi:10.5555/lantern Invented Press<p>An orchard of lanterns.</p> FictionOrchards1911 Lantern Seasons2 "##), ("OPS/cover.jpg", b"\xff\xd8\xff an invented cover"), ]; for (name, body) in files { zip.start_file(name, deflated).expect("an entry"); zip.write_all(body).expect("its bytes"); } zip.finish().expect("the archive closed"); path } // RULE (6 Nov 2026; the whole package, 7 Nov): an EPUB sent with no title is read by the core — its package's title, author, language, ISBN, publisher, description, subjects, DOI, year and series make the row and its own cover is kept as the book's picture, written beside the file only while it is captured; a shell sending the EPUB's facts itself beside that is refused, and a file that is no EPUB is said to be unreadable. #[test] fn the_core_reads_an_epub_sent_with_no_title() { let (dir, client) = crate::shell::client::phone_tests::attached(); let book = invented_epub(dir.path()); let request = json!({"path": book.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "the-lantern-orchard.epub", "book": {"format": "epub"}}); let mut parsed = super::media::validate_capture(&request).expect("an EPUB the core reads"); let read = parsed.book.as_mut().expect("a book"); read.zone = "Asia/Kolkata".to_string(); let written_cover = read.cover.clone().expect("the EPUB's cover"); assert_eq!(written_cover.parent(), book.parent(), "written beside the book's file"); let layout = client.layout().clone(); let answer = client .write_rows("capture.media", &mut |ctx| super::media::write_media(ctx, &layout, &parsed, client.self_device_id().as_deref())) .expect("the book")["answer"].clone(); drop(parsed); assert!(!written_cover.exists(), "the cover written for the capture goes with it"); let id = answer["recordId"].as_str().expect("its row"); let data = crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": id})).expect("the book")["data"].clone(); assert_eq!((data["title"].as_str(), data["author"].as_str(), data["language"].as_str(), data["isbn"].as_str()), (Some("The Lantern Orchard"), Some("Irena Valcourt"), Some("en"), Some("9780000000002")), "{data}"); assert_eq!((data["publisher"].as_str(), data["description"].as_str(), data["subjects"].as_str(), data["doi"].as_str()), (Some("Invented Press"), Some("An orchard of lanterns."), Some("Fiction, Orchards"), Some("10.5555/lantern")), "the whole package: {data}"); assert_eq!((data["year"].as_str(), data["series"].as_str(), data["series_number"].as_f64()), (Some("1911"), Some("Lantern Seasons"), Some(2.0)), "{data}"); assert_eq!(data["format"], "epub"); assert!(answer["coverKey"].as_str().is_some_and(|key| key.contains("/photos/") && key.ends_with(".jpg")), "{answer}"); assert_eq!(data["cover"], answer["coverKey"]); // Where its facts came from: each package column says opf, and nothing else is said. let said: Value = serde_json::from_str(data["filled_from"].as_str().expect("filled_from stamped")).expect("JSON"); let expected: serde_json::Map = ["author", "language", "isbn", "publisher", "description", "subjects", "doi", "year", "series", "series_number"].into_iter().map(|k| (k.to_string(), json!("opf"))).collect(); assert_eq!(said, Value::Object(expected), "{data}"); let mut both = request.clone(); both["book"]["author"] = json!("Someone the shell read"); assert_eq!(super::media::validate_capture(&both).expect_err("two readers").code, "bad_request"); let not_epub = dir.path().join("not-a-book.epub"); std::fs::write(¬_epub, b"an invented text, no zip").unwrap(); let mut refused = request.clone(); refused["path"] = json!(not_epub.to_string_lossy()); assert_eq!(super::media::validate_capture(&refused).expect_err("no EPUB").code, "unreadable"); } // RULE: a book's Add file gives the named book with no file its file and format, what the file says filling only its empty columns (its title and its own cover kept); the same file again is that book, a book with a file already is refused, and so is a file that is another book's. #[test] fn a_books_add_file_gives_that_book_its_file() { let (dir, client) = crate::shell::client::phone_tests::attached(); let (book, cover) = book_files(dir.path()); let made = crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "Lantern Orchard (my copy)", "author": "I. Valcourt", "status": "reading"}})).expect("a book with no file"); let into = made.pointer("/record/id").and_then(Value::as_str).expect("its id").to_string(); let capture = |into: &str| -> Result { let request = json!({ "path": book.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "the-lantern-orchard.epub", "book": {"format": "epub", "title": "The Lantern Orchard", "author": "Irena Valcourt", "language": "en", "isbn": "9780000000002"}, "coverPath": cover.to_string_lossy(), "into": into, }); let mut parsed = super::media::validate_capture(&request).map_err(|refused| refused.message)?; parsed.book.as_mut().expect("a book").zone = "Asia/Kolkata".to_string(); let layout = client.layout().clone(); client .write_rows("capture.media", &mut |ctx| super::media::write_media(ctx, &layout, &parsed, client.self_device_id().as_deref())) .map(|written| written["answer"].clone()) }; let answer = capture(&into).expect("the file added"); assert_eq!(answer["recordId"], json!(into)); let data = crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": into})).expect("the book")["data"].clone(); assert_eq!(data["file"], answer["key"]); assert_eq!(data["format"], "epub"); assert_eq!(data["title"], "Lantern Orchard (my copy)", "the owner's title stands"); assert_eq!(data["author"], "I. Valcourt", "the owner's author stands"); assert_eq!(data["isbn"], "9780000000002", "an empty column is filled"); assert_eq!(data["cover"], answer["coverKey"]); assert_eq!(data["status"], "reading"); assert!(data["filled_from"].is_null(), "what a shell read off the file names no source: {data}"); assert_eq!(capture(&into).expect("again")["recordId"], json!(into), "the same file is that book"); let other = crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "Another"}})).expect("another book"); let other = other.pointer("/record/id").and_then(Value::as_str).expect("its id").to_string(); assert!(capture(&other).expect_err("another book's file").contains("another book's")); } // RULE (7 Nov 2026): an EPUB the core reads into a book's Add file stamps opf on the columns it filled, and only those, beside what the row said already. #[test] fn an_epub_read_into_a_book_says_opf_for_what_it_filled() { let (dir, client) = crate::shell::client::phone_tests::attached(); let book = invented_epub(dir.path()); let made = crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "Lantern Orchard (my copy)", "author": "I. Valcourt", "year": "2001"}})).expect("a book with no file"); let into = made.pointer("/record/id").and_then(Value::as_str).expect("its id").to_string(); let request = json!({"path": book.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "the-lantern-orchard.epub", "book": {"format": "epub"}, "into": into}); let mut parsed = super::media::validate_capture(&request).expect("an EPUB the core reads"); parsed.book.as_mut().expect("a book").zone = "Asia/Kolkata".to_string(); let layout = client.layout().clone(); client.write_rows("capture.media", &mut |ctx| super::media::write_media(ctx, &layout, &parsed, client.self_device_id().as_deref())).expect("the file added"); let data = crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": into})).expect("the book")["data"].clone(); assert_eq!((data["author"].as_str(), data["year"].as_str(), data["isbn"].as_str()), (Some("I. Valcourt"), Some("2001"), Some("9780000000002")), "{data}"); let said: Value = serde_json::from_str(data["filled_from"].as_str().expect("filled_from stamped")).expect("JSON"); let expected: serde_json::Map = ["language", "isbn", "publisher", "description", "subjects", "doi", "series", "series_number"].into_iter().map(|k| (k.to_string(), json!("opf"))).collect(); assert_eq!(said, Value::Object(expected), "the owner's author and year are not said: {data}"); } // RULE: a book's capture is refused before a byte moves when its facts are missing or disagree with its type, and a book's fields are refused on any other kind. #[test] fn a_book_capture_is_refused_by_name_when_it_does_not_say_what_it_is() { let (dir, handle) = phone(); let (book, cover) = book_files(dir.path()); let path = book.to_string_lossy().to_string(); for (request, said) in [ (json!({"path": path, "mime": "application/epub+zip", "kind": "book"}), "book: {"), (json!({"path": path, "mime": "application/pdf", "kind": "book", "book": {"format": "epub", "title": "X"}}), "a epub book"), // A PDF is the shell's to read: with no title and no file name it says nothing a book is shown under. (json!({"path": path, "mime": "application/pdf", "kind": "book", "book": {"format": "pdf"}}), "has a title"), (json!({"path": path, "mime": "application/octet-stream", "kind": "book", "book": {"format": "epub", "title": "X"}}), "will not take a book"), (json!({"path": path, "mime": "application/epub+zip", "kind": "book", "book": {"format": "epub", "title": "X", "pages": 0}}), "pages"), (json!({"path": path, "mime": "application/epub+zip", "kind": "book", "book": {"format": "epub", "title": "X"}, "coverPath": book.to_string_lossy()}), "cover"), (json!({"path": path, "mime": "application/pdf", "kind": "document", "book": {"format": "pdf", "title": "X"}}), "only a book"), (json!({"path": path, "mime": "application/pdf", "kind": "document", "coverPath": cover.to_string_lossy()}), "only a book"), ] { let refused = crate::methods::dispatch(&handle, "capture.media", &request).expect_err("refused"); assert_eq!(refused.code, "bad_request", "{request}"); assert!(refused.message.contains(said), "{} — {request}", refused.message); } } // ── a list's own picture ─────────────────────────────────────────────────── /// RULE (5 Nov 2026): a list's own picture (`record_group.picture`, kept in /// `cotton_groups`) joins the pictures sweep as its 256 px thumbnail — a /// document that is a picture (`put_document` over Cotton MCP) as a photo /// does — and an arrived thumbnail stops being asked for. #[test] fn the_pictures_sweep_takes_a_lists_own_picture_as_its_thumbnail() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (dir, handle) = phone(); let original = format!("{}/documents/{}.png", crate::fixture::WORKSPACE, "9".repeat(64)); handle.client().with_writer(|file| { let raw = include_str!("../../../cotton-core/kits/personal/tables/record_group.json"); file.driver.run("INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES ('record_group', ?1, ?2, 0, 0, '2026-11-05', '2026-11-05')", &[text(file.workspace_id), text(raw)]).map_err(|error| error.to_string())?; file.driver.run("INSERT INTO cotton_groups (id, workspace_id, table_id, name, picture, created_at, updated_at) VALUES ('list-test', ?1, 'book', 'Synthetic shelf', ?2, '2026-11-05', '2026-11-05')", &[text(file.workspace_id), text(&original)]).map_err(|error| error.to_string())?; Ok(()) }).expect("a list with its own picture"); let thumb = cotton_core::media::keys::thumb_key_for(&original).expect("a document that is a picture has a thumbnail"); assert_eq!(thumb, format!("{}/documents/{}.t256.jpg", crate::fixture::WORKSPACE, "9".repeat(64))); assert_eq!(media_sweep::wanted(&handle.client(), 100).unwrap(), vec![thumb.clone()]); held(&handle, &dir, &thumb); assert!(media_sweep::wanted(&handle.client(), 100).unwrap().is_empty()); } /// RULE (5 Nov 2026): Set picture from Photos keeps the picked picture under a picture key, queued up to the object as a book's cover is with no Photos row, and names it on the list in one write with the list's receipt. #[test] fn a_lists_picture_from_photos_is_kept_queued_and_named_on_the_list() { let (dir, client) = crate::shell::client::phone_tests::attached(); let made = crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": "Synthetic shelf"})).unwrap(); let group = made["group"]["id"].as_str().unwrap().to_string(); let picked = dir.path().join("picked.jpg"); std::fs::write(&picked, b"\xff\xd8\xff an invented picture").expect("the picture"); let answer = crate::phone::records::call(&client, "groups.update", &json!({"id": group, "picturePath": picked.to_string_lossy()})).unwrap(); assert_eq!(answer["change"]["receipt"]["said"], "Gave Synthetic shelf a picture"); let key = answer["group"]["picture"].as_str().expect("the list names its picture").to_string(); let file = client.with_file(|file| Ok(file.identity.id().to_string())).unwrap(); assert!(key.starts_with(&format!("{file}/photos/")) && key.ends_with(".jpg"), "{key}"); let row = client.with_writer(|replica| Ok(cotton_store::media_ledger::media_by_key(replica.driver, &key).ok().flatten())).unwrap().expect("queued up"); assert!(row.local_path.is_some(), "kept on this phone"); let photos = client.with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM cotton_photos", &[]).map_err(|error| error.to_string())).unwrap(); assert_eq!(photos.and_then(|row| row.int("n")), Some(0), "no Photos row"); let refused = crate::phone::records::call(&client, "groups.update", &json!({"id": group, "picturePath": dir.path().join("picked.heic").to_string_lossy()})).unwrap_err(); assert!(refused.message.contains("a list's picture is a .jpg, .png, .gif or .webp"), "{}", refused.message); } /// RULE: media.share {document} answers `arrived: false` until the document a tool act wrote has come by sync, then its file fetched and the name the object gave it, so no shell reads a document's columns. #[test] fn a_documents_share_waits_for_its_row_then_answers_its_file_and_name() { let _serial = ORDER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (_dir, handle) = phone(); handle.client().set_media_fetch(Some(std::sync::Arc::new(Delivers(b"".to_vec())))); let waiting = crate::methods::dispatch(&handle, "media.share", &json!({ "document": "document:not-here" })).expect("an answer"); assert_eq!(waiting, json!({ "arrived": false })); // The row as the object's Export OPML leaves it, come by sync. let key = format!("{}/documents/{}.opml", crate::fixture::WORKSPACE, "b".repeat(64)); let at = "2026-11-14T10:00:00.000Z"; write( &handle, "INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, status, created_at, updated_at) \ VALUES ('invented-shows', ?, 'Invented shows', 'Shows.opml', 'text/x-opml', 7, ?, ?, 'ready', ?, ?)", vec![text(crate::fixture::WORKSPACE), text(&"b".repeat(64)), text(&key), text(at), text(at)], ); let id = "invented-shows"; let shared = crate::methods::dispatch(&handle, "media.share", &json!({ "document": id })).expect("the share"); assert_eq!(shared["platform_action"], json!("share_file")); assert_eq!(shared["name"], json!("Shows.opml")); let path = shared["path"].as_str().expect("a path"); assert_eq!(std::fs::read(path).expect("the file"), b""); } /// RULE: `media.uploads` answers each asked key where it is on its way up, in the order asked, with the counts; a key this device never queued is unknown, not an error. #[test] fn uploads_say_where_each_asked_file_is() { let (_dir, handle) = phone(); let key = object_key(); file_a_row(&handle, &key); let nobody = format!("{}/photos/{}.heic", crate::fixture::WORKSPACE, "b".repeat(64)); let answer = crate::methods::dispatch(&handle, "media.uploads", &json!({ "keys": [nobody, key] })).expect("an answer"); assert_eq!(answer["files"][0]["phase"], json!("unknown")); assert_eq!(answer["files"][1]["key"], json!(key)); assert_eq!(answer["files"][1]["phase"], json!("uploaded"), "the row was filed as the object holding it"); assert_eq!(answer["files"][1]["total"], json!(4_194_304)); assert_eq!(answer["files"][1]["network"], json!("any")); assert_eq!(answer["counts"]["uploaded"], json!(1)); assert_eq!(answer["counts"]["unknown"], json!(1)); } #[test] fn uploads_with_no_keys_are_refused() { let (_dir, handle) = phone(); let refusal = crate::methods::dispatch(&handle, "media.uploads", &json!({})).expect_err("the keys are the whole argument"); assert_eq!(refusal.code, "bad_request"); }