//! The phone's own four writes and the three corrected reads.//!//! Every fixture here is synthetic — a workspace of zeroes, a file of three//! bytes, a note nobody wrote ([nothing-real-ever-goes-in-cotton-s-public-tree]).//! The controller comes from `shell::client::phone_tests::attached`, which is//! the one place a paired phone is assembled, so these cases and the `write`//! cases are looking at the same device.use std::path::{Path, PathBuf};use std::sync::Arc;use serde_json::{json, Map, Value};usecrate::shell::file::ReadFile;usecrate::phone::disk::Disk;usecrate::phone::media::{MediaFetch, NotFetched};usecrate::shell::client::phone_tests::attached;usecrate::shell::client::ClientController;fn read(client: &ClientController, name: &str, args: &Map<String, Value>) -> Value {let entry = super::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared"));// The dispatch itself, not a copy of it: `answer_read` is what// `cotton_call` runs, so a read that works here works on the phone.super::answer_read(client, entry, args) .unwrap_or_else(|reason| panic!("{name} answered: {reason}"))}fn ops(client: &ClientController) -> Vec<Map<String, Value>> { client .with_writer(|replica| {let rows = replica .driver .all("SELECT tbl, kind, author, row_id FROM _outbox ORDER BY op_id", &[], ) .map_err(|error| error.to_string())?;Ok(rows .iter() .map(|row| {letmut out = Map::new();for column in ["tbl", "kind", "author", "row_id"] { out.insert( column.to_string(), row.text(column).map_or(Value::Null, Value::from), ); } out }) .collect()) }) .expect("the op log")}fn one_row(client: &ClientController, sql: &str) -> Option<Map<String, Value>> { client .with_writer(|replica| {Ok(replica .driver .get(sql, &[]) .map_err(|error| error.to_string())? .map(|row| {letmut out = Map::new();let names: Vec<String> = row.columns().iter().map(|(name, _)| name.clone()).collect();for name in names { out.insert( name.clone(), row.text(&name).map_or(Value::Null, Value::from), ); } out })) }) .expect("the row")}fn count(client: &ClientController, table: &str) -> i64 { client .with_writer(|replica| { replica .driver .get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]) .map_err(|error| error.to_string())? .and_then(|row| row.int("n")) .ok_or_else(|| "no count came back".to_string()) }) .expect("the count")}fn run(client: &ClientController, label: &str, request: &Value) -> Value {let args = request.as_object().cloned().unwrap_or_default();match label {"dictation.create" => {let parsed = super::dictation::validate(request).expect("the arguments"); client.write_rows(label, &mut |ctx| {super::dictation::write_dictation(ctx, &parsed) }) }"page.save" => {let parsed = super::page::validate_pages(request).expect("the arguments"); client.write_rows(label, &mut |ctx| super::page::write_pages(ctx, &parsed)) }"session.create" => {let parsed = super::session_queue::validate_create(request).expect("the arguments"); client.write_rows(label, &mut |ctx| {super::session_queue::write_session(ctx, &parsed) }) }"session.withdraw" => {let id = super::session_queue::validate_withdraw(request).expect("the arguments"); client.write_rows(label, &mut |ctx| {super::session_queue::write_withdraw(ctx, &id) }) }"session.resume" => {let id = super::session_queue::validate_resume(request).expect("the arguments"); client.write_rows(label, &mut |ctx| super::session_queue::write_resume(ctx, &id)) } _ => panic!("{label} has no runner here: {args:?}"), } .unwrap_or_else(|reason| panic!("{label} refused: {reason}"))}// ── session.create / session.withdraw ───────────────────────────────────────#[test]fn a_session_lands_queued_with_the_macs_own_columns_untouched() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({"deviceId": "a-synthetic-device-key","account": "owner@example.test","model": "fable","title": " Money: September ","prompt": "Read the new statements.", }), ); assert_eq!(answer["answer"]["state"], json!("queued"));let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT device_id, requested_device_id, account, tool, model, title, prompt, \ repo_url, state, chosen_by, claimed_at, started_at, external_id, \ CAST(host_owned AS TEXT) AS host_owned, hold_reason \ FROM cotton_sessions WHERE id = '{id}'" ), ) .expect("the session"); assert_eq!(row["device_id"], json!("a-synthetic-device-key"));// THE REQUEST IS KEPT, not only the placement: "I asked for this Mac" and// "it is on this Mac" are different facts. assert_eq!(row["requested_device_id"], json!("a-synthetic-device-key")); assert_eq!(row["account"], json!("owner@example.test")); assert_eq!(row["tool"], json!("claude-code")); assert_eq!(row["model"], json!("fable")); assert_eq!(row["title"], json!("Money: September")); assert_eq!(row["prompt"], json!("Read the new statements.")); assert_eq!(row["state"], json!("queued")); assert_eq!(row["chosen_by"], json!("owner")); assert_eq!(row["host_owned"], json!("1"), "a session Cotton will host");// Everything the Mac and the dispatcher own is still empty. assert_eq!(row["claimed_at"], Value::Null); assert_eq!(row["started_at"], Value::Null); assert_eq!(row["external_id"], Value::Null); assert_eq!(row["hold_reason"], Value::Null);}#[test]fn a_session_with_no_title_takes_the_prompts_first_line() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "prompt": "Fix the flaky money test.\nIt fails on the second run only." }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row(&client, &format!("SELECT title FROM cotton_sessions WHERE id = '{id}'")) .expect("the session"); assert_eq!( row["title"], json!("Fix the flaky money test."),"the FIRST line — a card shows one" );// A prompt with nothing in it is not a title: the copy already has a word// for a session with none. assert_eq!(super::session_queue::title_from_prompt(" \n "),None );let long = "x".repeat(200); assert_eq!(super::session_queue::title_from_prompt(&long) .expect("a title") .chars() .count(),super::session_queue::TITLE_FROM_PROMPT_MAX );}#[test]fn a_projects_first_repo_becomes_the_checkout_and_an_empty_prompt_is_allowed() {let (_dir, client) = attached(); client .with_writer(|replica| {let workspace = replica.workspace_id.to_string();let sql = format!("INSERT INTO cotton_memory_projects \ (id, workspace_id, slug, name, repos, status, created_at, updated_at) \ VALUES ('11111111-1111-4111-8111-111111111111', '{workspace}', 'example', \ 'Example project', \ '[\"https://example.invalid/example/one\",\"https://example.invalid/example/two\"]', \ 'active', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the project");let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "projectSlug": "example", "prompt": "" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT project_id, repo_url, prompt, title FROM cotton_sessions WHERE id = '{id}'"), ) .expect("the session"); assert_eq!(row["project_id"], json!("11111111-1111-4111-8111-111111111111")); assert_eq!(row["repo_url"], json!("https://example.invalid/example/one"));// An empty prompt is allowed: the agent comes up listening for an// instruction rather than with one to work on. assert_eq!(row["prompt"], json!("")); assert_eq!(row["title"], Value::Null);}#[test]fn a_session_is_refused_over_a_model_a_tool_a_mode_or_a_branch_nobody_takes() {let model =super::session_queue::validate_create(&json!({ "model": "gpt-9", "prompt": "" })) .expect_err("a refusal"); assert!(model.message.contains("fable"), "{}", model.message);let branch =super::session_queue::validate_create(&json!({ "branch": "-rf ../x", "prompt": "" })) .expect_err("a refusal"); assert!(branch.message.contains("`branch`"), "{}", branch.message);let tool = super::session_queue::validate_create(&json!({ "tool": "kimi", "prompt": "" })) .expect_err("a refusal"); assert!(tool.message.contains("claude-code, codex"), "{}", tool.message);let mode = super::session_queue::validate_create( &json!({ "permissionMode": "whatever", "prompt": "" }), ) .expect_err("a refusal"); assert!(mode.message.contains("bypass, ask"), "{}", mode.message);}/// **A session with no Mac lands `queued` with no device at all** — which is/// what "any Mac" means, and the whole of the dispatcher's half: the owner/// asked for a session and left the Mac to Cotton.#[test]fn a_session_with_no_mac_waits_in_the_queue_for_the_dispatcher() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "tool": "codex", "permissionMode": "ask", "prompt": "Do the thing." }), ); assert_eq!(answer["answer"]["state"], json!("queued"));let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT device_id, requested_device_id, tool, permission_mode, chosen_by, state \ FROM cotton_sessions WHERE id = '{id}'" ), ) .expect("the session"); assert_eq!(row["device_id"], Value::Null); assert_eq!(row["requested_device_id"], Value::Null, "any Mac"); assert_eq!(row["tool"], json!("codex")); assert_eq!(row["permission_mode"], json!("ask")); assert_eq!(row["chosen_by"], Value::Null, "nobody has chosen one yet"); assert_eq!(row["state"], json!("queued"));}/// The household's default is what a form that named no mode gets — a default/// nobody can change is not a default/// ([sessions-start-in-bypass-permissions-mode-by-default-it-s-a-sett]).#[test]fn a_session_that_named_no_mode_opens_in_the_households_own_default() {let (_dir, client) = attached(); client .with_writer(|replica| {let workspace = replica.workspace_id.to_string();let sql = format!("UPDATE cotton_workspaces SET session_permission_default = 'ask' \ WHERE id = '{workspace}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the setting");let answer = run(&client, "session.create", &json!({ "prompt": "Do the thing." }));let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT permission_mode FROM cotton_sessions WHERE id = '{id}'"), ) .expect("the session"); assert_eq!(row["permission_mode"], json!("ask"));}#[test]fn a_session_is_withdrawn_only_while_no_mac_has_started_it() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let withdrawn = run(&client, "session.withdraw", &json!({ "id": id })); assert_eq!(withdrawn["answer"]["state"], json!("withdrawn"));let row = one_row( &client, &format!("SELECT state, ended_at FROM cotton_sessions WHERE id = '{id}'"), ) .expect("the session"); assert_eq!(row["state"], json!("withdrawn")); assert_ne!(row["ended_at"], Value::Null, "a withdrawal ends the row");// Already withdrawn — and by the same rule, already running — is refused// with the state named, never silently re-written.let error = client .write_rows("session.withdraw", &mut |ctx| {super::session_queue::write_withdraw(ctx, &id) }) .expect_err("a refusal"); assert!(error.contains("already withdrawn"), "{error}");let absent = client .write_rows("session.withdraw", &mut |ctx| {super::session_queue::write_withdraw(ctx, "session-absent") }) .expect_err("a refusal"); assert!(absent.contains("session-absent"), "{absent}");}/// `starting` is withdrawable only BEFORE the agent exists: a row the helper/// has already answered for has a process behind it, and taking it back would/// leave an agent running with nothing naming it.#[test]fn a_session_the_helper_has_already_spawned_cannot_be_taken_back() {let (_dir, client) = attached();let answer = run(&client, "session.create", &json!({ "prompt": "x" }));let id = answer["answer"]["id"].as_str().expect("an id").to_string(); client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET state = 'starting' WHERE id = '{id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the claim");// Still withdrawable: claimed, not spawned.let taken = run(&client, "session.withdraw", &json!({ "id": id })); assert_eq!(taken["answer"]["state"], json!("withdrawn"));let other = run(&client, "session.create", &json!({ "prompt": "y" }));let other_id = other["answer"]["id"].as_str().expect("an id").to_string(); client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET state = 'starting', external_id = 'agent-1' \ WHERE id = '{other_id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the spawn");let refused = client .write_rows("session.withdraw", &mut |ctx| {super::session_queue::write_withdraw(ctx, &other_id) }) .expect_err("a refusal"); assert!(refused.contains("already starting"), "{refused}");}// ── capture.media ───────────────────────────────────────────────────────────/// Three bytes with a name, somewhere a picker might have left them.fn a_file(dir: &Path, name: &str) -> PathBuf {let path = dir.join(name); std::fs::write(&path, b"png").expect("a synthetic file"); path}fn capture_media(client: &ClientController, request: &Value) -> Result<Value, String> {let parsed = super::media::validate_capture(request).map_err(|error| error.message)?;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()) })}#[test]fn a_picture_is_copied_in_keyed_by_its_bytes_and_queued_for_upload() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","filename": "picked.png","kind": "photo", }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let id = answer["answer"]["recordId"] .as_str() .expect("an id") .to_string();// The key comes from `cotton_core::media::keys` and nowhere else, and the// row's id is the digest — so the same picture picked twice is one row. assert!( key.starts_with(&format!("{}/photos/", crate::fixture::WORKSPACE)),"{key}" ); assert!(id.starts_with("photo:"), "{id}");let row = one_row( &client, &format!("SELECT key FROM cotton_photos WHERE id = '{id}'"), ) .expect("the photo row"); assert_eq!(row["key"], json!(key));// THE LEDGER, which is what makes the upload happen without a screen// waiting on it — and its `local_path` is a file that is really there.let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, &key) .map_err(|error| error.to_string()) }) .expect("the ledger read") .expect("a ledger row"); assert_eq!(ledger.state, "pending");let stored = PathBuf::from(ledger.local_path.expect("a local path")); assert!(stored.exists(), "the bytes were copied into the store"); assert_eq!(std::fs::read(&stored).expect("the copy"), b"png");// Copied, never referenced in place: the picker's temp file is gone the// moment the share extension exits. assert_ne!(stored, source);}#[test]fn a_document_capture_queues_the_trigger_that_processes_it() {let (dir, client) = attached();let source = a_file(dir.path(), "statement.pdf");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "application/pdf","filename": "statement.pdf","kind": "document", }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let id = answer["answer"]["recordId"] .as_str() .expect("an id") .to_string();let row = one_row( &client, &format!("SELECT storage_path, status, source, mime FROM cotton_documents WHERE id = '{id}'" ), ) .expect("the document row"); assert_eq!(row["storage_path"], json!(key));// `processing`, because that is what it is: the bytes have not gone up. assert_eq!(row["status"], json!("processing")); assert_eq!(row["source"], json!("app"));let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, &key) .map_err(|error| error.to_string()) }) .expect("the ledger read") .expect("a ledger row"); assert_eq!(ledger.after.as_deref(), Some("document_process")); assert_eq!(ledger.after_row_id.as_deref(), Some(id.as_str()));}#[test]fn a_video_is_captured_the_way_a_picture_is() {let (dir, client) = attached();let source = a_file(dir.path(), "clip.mp4");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "video/mp4","filename": "clip.mp4","kind": "video", }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let id = answer["answer"]["recordId"] .as_str() .expect("an id") .to_string();// Its own folder and its own id prefix — a video is not a photo with a// duration, it is a row in its own table. assert!( key.starts_with(&format!("{}/videos/", crate::fixture::WORKSPACE)),"{key}" ); assert!(id.starts_with("video:"), "{id}");let row = one_row( &client, &format!("SELECT key, content_type FROM cotton_videos WHERE id = '{id}'"), ) .expect("the video row"); assert_eq!(row["key"], json!(key)); assert_eq!(row["content_type"], json!("video/mp4"));// No trigger: a video has no post-upload pipeline, and inventing one would// queue work the server does not do.let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, &key) .map_err(|error| error.to_string()) }) .expect("the ledger read") .expect("a ledger row"); assert!( ledger.after.is_none(),"a video queued a trigger: {:?}", ledger.after );}#[test]fn a_statement_capture_is_refused_by_name_and_leaves_nothing_on_disk() {let (dir, client) = attached();let source = a_file(dir.path(), "bank.pdf");let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "application/pdf","kind": "statement", }), ) .expect_err("a refusal"); assert!( error.contains("something else writes first"),"the refusal names the reason: {error}" );// S1: THE REFUSAL HAPPENS BEFORE THE COPY. It used to be decided past the// key builder, by which point `put_media_file` had already written the// bytes into the store — a file nothing would ever reference or sweep. assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a refused capture left bytes in the store: {:?}", stored_files(&client) );}#[test]fn a_file_over_its_kind_s_ceiling_is_refused_before_the_copy() {let (dir, client) = attached();let source = dir.path().join("huge.png");// One byte over what the server will mint a photo URL for. Written as a// sparse file so the test costs nothing.let limit = cotton_core::media::keys::media_limits(cotton_core::media::keys::MediaKind::Photo) .max_bytes;let file = std::fs::File::create(&source).expect("a file"); file.set_len(limit + 1).expect("a length"); drop(file);let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo", }), ) .expect_err("a refusal"); assert!(error.contains("over the"), "{error}"); assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a file over the ceiling was copied in anyway" );}#[test]fn a_type_the_server_will_not_take_is_refused_before_the_copy() {let (dir, client) = attached();let source = a_file(dir.path(), "clip.mkv");let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "video/x-matroska","kind": "video", }), ) .expect_err("a refusal");// The message lists what IS accepted — a refusal the person can act on. assert!(error.contains("it accepts"), "{error}"); assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a refused type was copied in anyway" );}/// Every real file in the media store — scratch parts included.fn stored_files(client: &ClientController) -> Vec<String> {letmut out = Vec::new();letmut pending = vec![client.layout().client_media_dir()];whileletSome(directory) = pending.pop() {letOk(entries) = std::fs::read_dir(&directory) else {continue; };for entry in entries.flatten() {if entry.path().is_dir() { pending.push(entry.path()); } else { out.push(entry.path().to_string_lossy().to_string()); } } } out}// ── capture.media: the tiers, made on the phone ─────────────────────────────/// A JPEG's worth of bytes, standing in for a rendition ImageIO encoded.////// SYNTHETIC, like every fixture here: the tiers are made by/// `CottonKit/MediaTiers.swift` and proved by `MediaTiersTests`, which is the/// half that owns ImageIO. What this side owns is where the files GO, and for/// that a file of known bytes is the whole requirement.fn a_rendition(dir: &Path, name: &str, body: &[u8]) -> PathBuf {let path = dir.join(name); std::fs::write(&path, body).expect("a synthetic rendition"); path}#[test]fn a_capture_writes_a_blur_a_thumb_and_the_original() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let thumb = a_rendition(dir.path(), "picked.t256.jpg", b"thumb-bytes");let display = a_rendition(dir.path(), "picked.d1600.jpg", b"display-bytes");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","filename": "picked.png","kind": "photo","thumbPath": thumb.to_string_lossy(),"displayPath": display.to_string_lossy(),"preview": "AAAAblur", }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let id = answer["answer"]["recordId"].as_str().expect("an id").to_string();// THE BLUR IS A COLUMN, so it travels with the row and a tile on a phone// that has never held these bytes still draws something.let row = one_row( &client, &format!("SELECT preview FROM cotton_photos WHERE id = '{id}'"), ) .expect("the photo row"); assert_eq!(row["preview"], json!("AAAAblur"));// THE TWO RENDITIONS ARE OBJECTS, each with its own ledger row, each named// off the ORIGINAL's digest — so the drain uploads them the way it uploads// anything else and a renderer can name one before it exists.let sha = key .rsplit('/') .next() .and_then(|file| file.split('.').next()) .expect("the digest") .to_string();let thumb_key = cotton_core::media::keys::photo_thumb_key(crate::fixture::file_id(), &sha);let display_key = cotton_core::media::keys::photo_display_key(crate::fixture::file_id(), &sha);let queued = ledger(&client, &thumb_key).expect("a thumbnail ledger row"); assert_eq!(queued.state, "pending"); assert_eq!(queued.content_type, "image/jpeg"); assert_eq!(queued.tier, Some(cotton_store::media_holdings::Tier::Thumb)); assert_eq!( std::fs::read(queued.local_path.expect("a path")).expect("the copy"), b"thumb-bytes" );let queued = ledger(&client, &display_key).expect("a display ledger row"); assert_eq!( queued.tier,Some(cotton_store::media_holdings::Tier::Display) );// AND THE ORIGINAL IS STILL THE POINT.let original = ledger(&client, &key).expect("the original's ledger row"); assert_eq!( original.tier,Some(cotton_store::media_holdings::Tier::Original) );}#[test]fn a_small_original_may_arrive_with_no_display_rendition() {let (dir, client) = attached();let source = a_file(dir.path(), "small.png");let thumb = a_rendition(dir.path(), "small.t256.jpg", b"thumb-bytes");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","thumbPath": thumb.to_string_lossy(), }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let sha = key .rsplit('/') .next() .and_then(|file| file.split('.').next()) .expect("the digest") .to_string();// A picture already at or under two megapixels IS its own display tier, and// a second copy of it would be pure cost. The phone decides that; the// absence must be a state this side accepts rather than a gap it fills. assert!( ledger( &client, &cotton_core::media::keys::photo_display_key(crate::fixture::file_id(), &sha) ) .is_none(),"a display rendition appeared for a capture that sent none" );}#[test]fn a_blur_over_the_cap_is_refused_before_the_bytes_move() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let over = "A".repeat(super::media::PREVIEW_MAX_BASE64_BYTES + 1);let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","preview": over, }), ) .expect_err("a refusal"); assert!(error.contains("over the"), "{error}"); assert!( error.contains("24 px"),"the refusal says what a blur is: {error}" );// BEFORE THE BYTES MOVE — the whole point of the cap living in// `validate_capture` and not in a `CHECK` on the column. A `CHECK` would// reject the op that carries the photograph. assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a refused preview left bytes in the store: {:?}", stored_files(&client) ); assert!( one_row(&client, "SELECT id FROM cotton_photos LIMIT 1").is_none(),"a refused preview left a photo row behind" );}#[test]fn exactly_one_byte_of_blur_under_the_cap_is_taken() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let at_the_cap = "A".repeat(super::media::PREVIEW_MAX_BASE64_BYTES);let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","preview": at_the_cap, }), ) .expect("the capture");let id = answer["answer"]["recordId"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT preview FROM cotton_photos WHERE id = '{id}'"), ) .expect("the photo row"); assert_eq!( row["preview"].as_str().map(str::len),Some(super::media::PREVIEW_MAX_BASE64_BYTES) );}#[test]fn a_tier_path_that_is_not_there_is_refused_by_name_and_says_what_to_send() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","thumbPath": dir.path().join("never-written.jpg").to_string_lossy(), }), ) .expect_err("a refusal"); assert!(error.contains("thumbPath"), "{error}");// The way a caller says "I could not make this one" is to send nothing —// and the refusal has to say so, or the honest answer is unreachable. assert!(error.contains("Send no"), "{error}"); assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a refused tier path left bytes in the store" );}#[test]fn a_document_has_no_renditions_and_says_so() {let (dir, client) = attached();let source = a_file(dir.path(), "statement.pdf");let thumb = a_rendition(dir.path(), "statement.t256.jpg", b"thumb-bytes");let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "application/pdf","kind": "document","thumbPath": thumb.to_string_lossy(), }), ) .expect_err("a refusal"); assert!(error.contains("only a photo and a video"), "{error}");}#[test]fn a_photograph_has_no_poster_because_a_poster_is_a_film_s_first_frame() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let poster = a_rendition(dir.path(), "picked.poster.jpg", b"still-bytes");let error = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","posterPath": poster.to_string_lossy(), }), ) .expect_err("a refusal"); assert!(error.contains("still frame of a film"), "{error}");}#[test]fn a_film_capture_writes_its_still_under_the_poster_key() {let (dir, client) = attached();let source = a_file(dir.path(), "clip.mp4");let poster = a_rendition(dir.path(), "clip.poster.jpg", b"still-bytes");let thumb = a_rendition(dir.path(), "clip.t256.jpg", b"thumb-bytes");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "video/mp4","kind": "video","posterPath": poster.to_string_lossy(),"thumbPath": thumb.to_string_lossy(),"preview": "AAAAblur", }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let id = answer["answer"]["recordId"].as_str().expect("an id").to_string();let sha = key .rsplit('/') .next() .and_then(|file| file.split('.').next()) .expect("the digest") .to_string();let poster_key = cotton_core::media::keys::video_poster_key(crate::fixture::file_id(), &sha);// THE ROW POINTS AT IT. A film whose `poster_key` is null is a grey glyph// in every grid, and the describe worker skips it outright.let row = one_row( &client, &format!("SELECT poster_key, preview FROM cotton_videos WHERE id = '{id}'"), ) .expect("the video row"); assert_eq!(row["poster_key"], json!(poster_key)); assert_eq!(row["preview"], json!("AAAAblur"));// The answer names the same still, so the capture tile can draw it. assert_eq!(answer["answer"]["posterKey"], json!(poster_key));// AND IT IS A REAL OBJECT, queued like any other, so it flows because it// IS a photograph.let queued = ledger(&client, &poster_key).expect("the still's ledger row"); assert_eq!(queued.state, "pending"); assert_eq!(queued.content_type, "image/jpeg"); assert_eq!( std::fs::read(queued.local_path.expect("a path")).expect("the copy"), b"still-bytes" );// A film's thumbnail is derived FROM the still, and it lands under the// film's own digest so the tile can name it. assert!( ledger( &client, &cotton_core::media::keys::video_thumb_key(crate::fixture::file_id(), &sha) ) .is_some(),"a film got no grid thumbnail" );}#[test]fn a_film_with_no_still_keeps_a_null_poster_key() {let (dir, client) = attached();let source = a_file(dir.path(), "clip.mp4");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "video/mp4","kind": "video", }), ) .expect("the capture");let id = answer["answer"]["recordId"].as_str().expect("an id").to_string();// Null rather than a key naming an object nobody wrote: the Mac's backlog// worker fills this later, and until it does the grid draws a glyph// honestly.let row = one_row( &client, &format!("SELECT poster_key FROM cotton_videos WHERE id = '{id}'"), ) .expect("the video row"); assert_eq!(row["poster_key"], Value::Null); assert_eq!(answer["answer"]["posterKey"], Value::Null);}/// RULE: capture.media answers a film's poster key beside its own key, and null for a photo, so the capture tile draws a still and never a film.#[test]fn the_capture_answer_names_a_films_still_and_no_still_for_a_photo() {let (dir, client) = attached();let clip = a_file(dir.path(), "clip.mp4");let poster = a_rendition(dir.path(), "clip.poster.jpg", b"still-bytes");let film = capture_media( &client, &json!({"path": clip.to_string_lossy(),"mime": "video/mp4","kind": "video","posterPath": poster.to_string_lossy(), }), ) .expect("the film");let still = film["answer"]["posterKey"].as_str().expect("a poster key"); assert_ne!(Some(still), film["answer"]["key"].as_str(), "the still is not the film");let picked = a_rendition(dir.path(), "picked.png", b"another-picture");let photo = capture_media( &client, &json!({ "path": picked.to_string_lossy(), "mime": "image/png", "kind": "photo" }), ) .expect("the photo"); assert_eq!(photo["answer"]["posterKey"], Value::Null);}#[test]fn the_originals_ledger_row_is_marked_captured_here() {let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let thumb = a_rendition(dir.path(), "picked.t256.jpg", b"thumb-bytes");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","thumbPath": thumb.to_string_lossy(), }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let sha = key .rsplit('/') .next() .and_then(|file| file.split('.').next()) .expect("the digest") .to_string();// THIS PHONE TOOK THESE BYTES, so the budgeted cache may never drop them. assert!( ledger(&client, &key).expect("the ledger row").captured_here,"the original was not marked as this device's own capture" );// AND ONLY THERE. A thumbnail is remade from the original in a second and// is fetched back in a pack; marking it permanent would pin bytes the// person can always get again. assert!( !ledger( &client, &cotton_core::media::keys::photo_thumb_key(crate::fixture::file_id(), &sha) ) .expect("the thumbnail's ledger row") .captured_here,"a rendition was marked as a capture" );}#[test]fn the_capture_records_a_hold_for_the_original() {// A paired phone's own device row is in its copy (`attached` seeds it): a// hold names the phone by that key, and one no reader could see is not// written.let (dir, client) = attached();let source = a_file(dir.path(), "picked.png");let thumb = a_rendition(dir.path(), "picked.t256.jpg", b"thumb-bytes");let answer = capture_media( &client, &json!({"path": source.to_string_lossy(),"mime": "image/png","kind": "photo","thumbPath": thumb.to_string_lossy(), }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let rows = client .with_writer(|replica| { replica .driver .all("SELECT object_key, tier, bytes FROM cotton_media_holdings ORDER BY id", &[], ) .map_err(|error| error.to_string()) }) .expect("the holdings");// ONE ROW, for the ORIGINAL. The table's question is "who can give me these// bytes", and it is only ever asked about an original: a thumbnail is// "everybody, eventually", and a row per thumbnail would triple the table// for an answer nobody reads. assert_eq!(rows.len(), 1, "a hold was written for a rendition"); assert_eq!(rows[0].text("object_key"), Some(key.as_str())); assert_eq!(rows[0].text("tier"), Some("original")); assert_eq!(rows[0].int("bytes"), Some(3));}#[test]fn bytes_never_cross_the_boundary_as_json() {let error = super::media::validate_capture( &json!({ "bytes": "cG5n", "mime": "image/png", "kind": "photo" }), ) .expect_err("a refusal"); assert!(error.message.contains("never cross"), "{}", error.message);}/// The ledger row a capture queued, by key. Kept when `capture.messageMedia`/// went with the sharing data plane in 5m — the avatar cases below are its/// remaining callers, and the assertion they make with it (bytes queued once,/// under the key that came back) is the same one.fn ledger(client: &ClientController, key: &str) -> Option<cotton_store::media_ledger::MediaRow> { client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, key) .map_err(|error| error.to_string()) }) .expect("the ledger read")}// ── capture.avatar ──────────────────────────────────────────────────────────fn capture_avatar(client: &ClientController, request: &Value) -> Result<Value, String> {let parsed = super::media::validate_avatar(request).map_err(|error| error.message)?;let layout = client.layout().clone(); client.write_rows("capture.avatar", &mut |ctx| {super::media::write_avatar(ctx, &layout, &parsed) })}/// What the file says this person's face is, straight off the row.fn avatar_of(client: &ClientController, person_id: &str) -> Option<String> { client .with_writer(|replica| {let row = replica .driver .get("SELECT avatar_key FROM cotton_people WHERE id = ?", &[rusqlite::types::Value::Text(person_id.to_string())], ) .map_err(|error| error.to_string())? .ok_or_else(|| "no such person".to_string())?;Ok(row.text("avatar_key").map(str::to_string)) }) .expect("the person")}#[test]fn a_photograph_lands_under_its_person_and_the_row_points_at_it() {let (dir, client) = attached();let source = a_file(dir.path(), "face.jpg");let answer = capture_avatar( &client, &json!({"personId": "person-a","path": source.to_string_lossy(),"mime": "image/jpeg","filename": "face.jpg", }), ) .expect("the capture");let entry = &answer["answer"];let key = entry["key"].as_str().expect("a key").to_string();// The key is the person's, which is what makes the object theirs rather// than a loose photo in the library. assert!( key.contains("/people/person-a/"),"the key does not name the person: {key}" ); assert_eq!(entry["personId"], "person-a");// The ROW points at it — bytes nothing references are bytes nobody draws.let avatar_key = avatar_of(&client, "person-a"); assert_eq!(avatar_key.as_deref(), Some(key.as_str()));// And the ledger carries the upload, with no trigger: nothing on the server// runs off a face arriving.let queued = ledger(&client, &key).expect("a ledger row"); assert_eq!(queued.state, "pending"); assert_eq!(queued.after, None); assert_eq!(queued.content_type, "image/jpeg");}#[test]fn a_second_photograph_replaces_the_first_rather_than_joining_it() {let (dir, client) = attached();let first = capture_avatar( &client, &json!({"personId": "person-a","path": a_file(dir.path(), "one.jpg").to_string_lossy(),"mime": "image/jpeg", }), ) .expect("the first");let second_source = dir.path().join("two.jpg"); std::fs::write(&second_source, b"a different face").expect("a synthetic file");let second = capture_avatar( &client, &json!({"personId": "person-a","path": second_source.to_string_lossy(),"mime": "image/jpeg", }), ) .expect("the second");let (first, second) = (&first["answer"], &second["answer"]); assert_ne!(first["key"], second["key"], "the sha did not move");let avatar_key = avatar_of(&client, "person-a"); assert_eq!(avatar_key.as_deref(), second["key"].as_str());// The first object is still on this device and still queued — content is// addressed, never overwritten, and a photograph changed on a train must// not depend on a delete landing first. assert!(ledger(&client, first["key"].as_str().expect("a key")).is_some());}#[test]fn a_photograph_for_somebody_this_file_does_not_have_is_refused_before_the_copy() {let (dir, client) = attached();let source = a_file(dir.path(), "face.jpg");let error = capture_avatar( &client, &json!({// A well-formed id that is nobody's — the same answer an id from// another workspace gets, which is the point."personId": "99999999-9999-4999-8999-999999999999","path": source.to_string_lossy(),"mime": "image/jpeg", }), ) .expect_err("a refusal"); assert!(error.contains("no such person"), "{error}"); assert!( !client.layout().client_media_dir().exists() || stored_files(&client).is_empty(),"a face for nobody was copied in anyway" );}#[test]fn a_photograph_the_server_would_refuse_is_refused_here_first() {let (dir, client) = attached();let source = a_file(dir.path(), "face.tiff");let error = capture_avatar( &client, &json!({"personId": "person-a","path": source.to_string_lossy(),"mime": "image/tiff", }), ) .expect_err("a refusal"); assert!(error.contains("image/jpeg"), "{error}");let no_person = super::media::validate_avatar( &json!({ "path": "/tmp/x.jpg", "mime": "image/jpeg" }), ) .expect_err("a refusal"); assert!( no_person.message.contains("whose photograph"),"{}", no_person.message );let as_json = super::media::validate_avatar( &json!({ "personId": "person-a", "bytes": "cG5n", "mime": "image/jpeg" }), ) .expect_err("a refusal"); assert!(as_json.message.contains("never cross"), "{}", as_json.message);}// ── media.ensure and read.mediaPath ────────────────────────────────────────#[derive(Debug)]structNeverFetches;implMediaFetchforNeverFetches {fn fetch_to(&self, _database: &str, key: &str, _dest: &Path) -> Result<(), NotFetched> { panic!("nothing should have asked for {key}") }}/// A seam that writes fixed bytes and counts how many times it was asked.#[derive(Debug)]structDelivers { bytes: Vec<u8>, asked: std::sync::atomic::AtomicUsize,}implDelivers {fn new(bytes: &[u8]) -> Delivers {Delivers { bytes: bytes.to_vec(), asked: std::sync::atomic::AtomicUsize::new(0), } }fn asked(&self) -> usize {self.asked.load(std::sync::atomic::Ordering::SeqCst) }}implMediaFetchforDelivers {fn fetch_to(&self, _database: &str, _key: &str, dest: &Path) -> Result<(), NotFetched> {self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst); std::fs::write(dest, &self.bytes).map_err(|error| error.to_string().into()) }}/// A seam that fails, and leaves a half-written file behind when it does.#[derive(Debug)]structFailsHalfway;implMediaFetchforFailsHalfway {fn fetch_to(&self, _database: &str, _key: &str, dest: &Path) -> Result<(), NotFetched> {let _ = std::fs::write(dest, b"half");Err(NotFetched { waiting: None, reason: "the connection dropped".to_string(), status: Some(0) }) }}fn ensure(client: &ClientController, key: &str) -> Result<Value, crate::methods::MethodError> {// `media.ensure` reaches the controller through the handle in production;// here the two halves it uses are driven directly, which is what lets a// test have a media fetch at all.let layout = client.layout().clone();ifletSome(path) = client .with_writer(|replica| Ok(super::media::local_path_of(replica.driver, key))) .expect("the ledger read") {returnOk(json!({ "path": path.to_string_lossy(), "fetched": false })); }letSome(fetch) = client.media_fetch() else {returnErr(crate::methods::MethodError::new("no_media_fetch",super::media::NO_MEDIA_FETCH, )); };let workspace_id = client .with_writer(|replica| Ok(replica.workspace_id.to_string())) .expect("the workspace");let (path, sha256, size_bytes) =super::media::fetch_into_store(fetch.as_ref(), &layout, &workspace_id, key) .map_err(|trouble| super::media::not_fetched(key, &trouble, false))?; 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: sha256.clone(), content_type: "application/octet-stream".to_string(), size_bytes: i64::try_from(size_bytes).unwrap_or(i64::MAX), local_path: Some(path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, now: "2026-09-01T09:00:00.000Z".to_string(), tier: None, captured_here: false, }, ) .map_err(|error| error.to_string()) }) .expect("the ledger write");Ok(json!({ "path": path.to_string_lossy(), "fetched": true }))}fn scratch_files(client: &ClientController) -> Vec<String> {letmut out = Vec::new();letmut pending = vec![client.layout().client_media_dir()];whileletSome(directory) = pending.pop() {letOk(entries) = std::fs::read_dir(&directory) else {continue; };for entry in entries.flatten() {if entry.path().is_dir() { pending.push(entry.path()); } elseif entry.file_name().to_string_lossy().contains(".part") { out.push(entry.file_name().to_string_lossy().to_string()); } } } out}const KEY_SUFFIX: &str = "/photos/aaaa.png";fn absent_key() -> String { format!("{}{KEY_SUFFIX}", crate::fixture::WORKSPACE)}#[test]fn ensure_answers_from_disk_without_asking_anyone() {let (dir, client) = attached(); client.set_media_fetch(Some(Arc::new(NeverFetches)));let source = a_file(dir.path(), "already.png");let answer = capture_media( &client, &json!({ "path": source.to_string_lossy(), "mime": "image/png", "filename": "already.png", "kind": "photo" }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();// `NeverFetches` panics if it is reached, so this passing IS the assertion// that nothing went to the network for bytes that are here.let out = ensure(&client, &key).expect("the path"); assert_eq!(out["fetched"], json!(false)); assert!(PathBuf::from(out["path"].as_str().expect("a path")).exists());}/// A seam that writes each key's own bytes and then holds until every fetch/// in flight has written, so two downloads really do overlap.#[derive(Debug)]structOverlapping { bytes: std::collections::HashMap<String, Vec<u8>>, all_written: std::sync::Barrier,}implMediaFetchforOverlapping {fn fetch_to(&self, _database: &str, key: &str, dest: &Path) -> Result<(), NotFetched> { std::fs::write(dest, &self.bytes[key]).map_err(|error| NotFetched::from(error.to_string()))?;self.all_written.wait();Ok(()) }}#[test]fn two_fetches_in_flight_in_one_workspace_each_land_their_own_bytes() {// Every key in a workspace begins with the workspace id. The scratch file// was once named from the key's FIRST characters, so a grid of prints// shared one scratch file and a person's print showed someone else's face.let (_dir, client) = attached();let layout = client.layout().clone();let workspace = crate::fixture::WORKSPACE.to_string();let first = format!("{workspace}/people/aaaa/one.jpg");let second = format!("{workspace}/people/bbbb/two.jpg");let seam = Arc::new(Overlapping { bytes: [(first.clone(), b"the first face".to_vec()), (second.clone(), b"the second face".to_vec())] .into_iter() .collect(), all_written: std::sync::Barrier::new(2), });typeLanded = (String, Result<(PathBuf, String, u64), NotFetched>);let landed: Vec<Landed> = std::thread::scope(|scope| {let runs: Vec<_> = [first.clone(), second.clone()] .into_iter() .map(|key| {let (seam, layout, workspace) = (seam.clone(), layout.clone(), workspace.clone()); scope.spawn(move || {let out = super::media::fetch_into_store(seam.as_ref(), &layout, &workspace, &key); (key, out) }) }) .collect(); runs.into_iter().map(|run| run.join().expect("the fetch thread")).collect() });for (key, out) in landed {let (path, _, _) = out.unwrap_or_else(|reason| panic!("`{key}` did not land: {reason:?}")); assert_eq!( std::fs::read(&path).expect("the file"), seam.bytes[&key],"`{key}` answered a file holding another key's bytes" ); }}#[test]fn ensure_fetches_to_scratch_hashes_it_and_renames_it_into_the_store() {let (_dir, client) = attached();let deliverer = Arc::new(Delivers::new(b"downloaded bytes")); client.set_media_fetch(Some(deliverer.clone()));let key = absent_key();let out = ensure(&client, &key).expect("the fetch"); assert_eq!(out["fetched"], json!(true));let path = PathBuf::from(out["path"].as_str().expect("a path")); assert!(path.exists(), "the bytes landed"); assert_eq!(std::fs::read(&path).expect("the file"), b"downloaded bytes");// ADDRESSED BY ITS OWN DIGEST, not by the key: the store is// content-addressed and the file name is the hash. assert!( path.file_name() .and_then(std::ffi::OsStr::to_str) .is_some_and(|name| name.len() > 60),"the file is not named by its digest: {path:?}" );// AND NO SCRATCH IS LEFT: the `.part` was renamed, not copied. assert!( scratch_files(&client).is_empty(),"a scratch file survived a successful fetch: {:?}", scratch_files(&client) );// THE LEDGER SAYS SYNCED. A row downloaded from the bucket is by definition// up; leaving it `pending` would queue an upload of what is already there.let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, &key) .map_err(|error| error.to_string()) }) .expect("the ledger read") .expect("a ledger row"); assert_eq!(ledger.state, "synced"); assert_eq!(ledger.local_path.as_deref(), path.to_str());// ASKED ONCE. A second call is answered off the ledger, so the same bytes// are never fetched twice — the whole point of a content-addressed store.let again = ensure(&client, &key).expect("the second call"); assert_eq!(again["fetched"], json!(false)); assert_eq!(again["path"], out["path"]); assert_eq!(deliverer.asked(), 1, "the bytes were fetched twice");}/// RULE: When a file's bytes do not come down, media.ensure answers a sentence a page can print as it is — never the object key, a status number or the transport's words, which go in the details — and it says the Mac could not be reached only when this device's copy says so (read.sync_state's reachable flag), never from one failed fetch (walker pass 5: Documents said the Mac was unreachable while online).#[test]fn bytes_that_do_not_come_are_said_in_a_sentence() {let key = "f7489ccf-0000/videos/8570ad07.mp4";for status in [Some(404), Some(503), None] {let trouble = NotFetched { waiting: None, reason: "the file store answered 404 for these bytes".to_string(), status };let error = super::media::not_fetched(key, &trouble, false);let said = &error.message; assert!(said.starts_with("This file ") && said.ends_with('.'), "{said}"); assert!(!said.contains(key) && !said.contains('`') && !said.contains("404"), "{said}"); assert!(!said.contains("file store"), "{said}"); assert_eq!(error.details["key"], json!(key)); assert_eq!(error.details["reason"], json!(trouble.reason)); }for (code, sentence) in [("coming", "Coming from mac-a."), ("holder_asleep", "mac-a is asleep.")] {let trouble = NotFetched { reason: "keeper named in a 202".to_string(), status: Some(202), waiting: Some((code.to_string(), "mac-a".to_string())) };let error = super::media::not_fetched(key, &trouble, false); assert_eq!(error.code, code); assert_eq!(error.message, sentence); assert_eq!(error.details["holder"], "mac-a"); }let missing = super::media::not_fetched(key, &NotFetched { waiting: None, reason: String::new(), status: Some(404) }, false); assert_eq!(missing.code, "bytes_not_uploaded");// No server reached. The Mac is said away ONLY when this device's copy// says so (read.sync_state); one failed fetch is not the Mac away.let cut = NotFetched { waiting: None, reason: "the connection dropped".to_string(), status: Some(0) };let away = super::media::not_fetched(key, &cut, true); assert_eq!(away.code, "mac_away"); assert!(away.message.starts_with("Not on this phone yet") && !away.message.contains(key), "{}", away.message);let online = super::media::not_fetched(key, &cut, false); assert_eq!(online.code, "unreachable_server"); assert!(!online.message.contains("could not be reached"), "{}", online.message);}#[test]fn a_fetch_that_fails_names_the_key_and_keeps_only_the_keys_one_partial() {let (_dir, client) = attached(); client.set_media_fetch(Some(Arc::new(FailsHalfway)));let key = absent_key();let error = ensure(&client, &key).expect_err("a refusal"); assert_eq!(error.code, "unreachable_server");// THE KEY AND THE REASON ARE IN THE DETAILS, never in the sentence: a grid// asks for many and a log must say which, but a page prints the message. assert_eq!(error.details["key"], json!(key)); assert_eq!(error.details["reason"], json!("the connection dropped")); assert!(!error.message.contains(&key), "{}", error.message);// The copy never said the Mac is away, so one failed fetch does not say// it either (walker pass 5: Documents said the Mac was unreachable while// it answered). assert!(!error.message.contains("could not be reached"), "{}", error.message);// What arrived before the line dropped stays in the key's ONE partial// file, which the next fetch of this key resumes from its last byte// (`cotton_client::media::fetching`) — never a second scratch per call.let partial = cotton_client::media::fetching::partial_path(std::path::Path::new(""), &key); assert_eq!( scratch_files(&client), vec![partial.file_name().expect("a name").to_string_lossy().to_string()], );// Nothing claimed the bytes are here. assert!(client .with_writer(|replica| Ok(super::media::local_path_of(replica.driver, &key))) .expect("the ledger read") .is_none());}#[test]fn ensure_refuses_by_name_when_nothing_can_fetch() {let (_dir, client) = attached();// No `set_media_fetch` at all — the ordinary state of a build 4b has not// wired a transport into yet.let error = ensure(&client, &absent_key()).expect_err("a refusal"); assert_eq!(error.code, "no_media_fetch"); assert!( error.message.contains("cannot fetch it just now"),"{}", error.message );}#[test]fn the_path_read_answers_from_disk_and_never_starts_a_download() {let (dir, client) = attached();// A fetch that would PANIC if it were reached: a grid drawing two hundred// thumbnails must not be two hundred downloads. client.set_media_fetch(Some(Arc::new(NeverFetches)));let source = a_file(dir.path(), "here.png");let answer = capture_media( &client, &json!({ "path": source.to_string_lossy(), "mime": "image/png", "filename": "here.png", "kind": "photo" }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let here = read( &client,"read.mediaPath", &super::super::shell::client::phone_tests::args(&[("key", json!(key))]), ); assert_eq!(here["present"], json!(true)); assert!(PathBuf::from(here["path"].as_str().expect("a path")).exists());let absent = read( &client,"read.mediaPath", &super::super::shell::client::phone_tests::args(&[("key", json!(format!("{}/photos/nothing.png", crate::fixture::WORKSPACE)), )]), ); assert_eq!(absent["present"], json!(false)); assert!( absent.get("path").is_none(),"no path for bytes that are not here" );}/// The tile's resolve order, which lives in the crate rather than in each/// renderer: **thumbnail → original → nothing**, where "nothing" is what hands/// the tile over to the row's own blur and then to a glyph.#[test]fn a_tile_prefers_the_thumb_then_the_original_then_the_blur() {let (dir, client) = attached();// A fetch that would PANIC if it were reached. Not one of the three states// opens the radio, and a thumbnail is NEVER handed to `media.ensure`. client.set_media_fetch(Some(Arc::new(NeverFetches)));let source = a_file(dir.path(), "picture.png");let answer = capture_media( &client, &json!({ "path": source.to_string_lossy(), "mime": "image/png", "filename": "picture.png", "kind": "photo" }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let ask = |key: &str| { read( &client,"read.mediaPath", &super::super::shell::client::phone_tests::args(&[("key", json!(key))]), ) };// 2. THE ORIGINAL, while no thumbnail has arrived. The capture put these// bytes on this device, so this is the ordinary state for a picture the// person just took.let original = ask(&key); assert_eq!(original["present"], json!(true)); assert_eq!(original["tier"], json!("original"));let original_path = original["path"].as_str().expect("a path").to_string();// 1. THE THUMBNAIL, the moment the sweep lands one. Its key is DERIVED from// the picture's, never carried in a column.let thumb_key = cotton_core::media::keys::thumb_key_for(&key).expect("a photo has a thumbnail");let thumb_path = dir.path().join("thumb.t256.jpg"); std::fs::write(&thumb_path, b"a synthetic thumbnail").expect("the thumbnail file"); client .with_writer(|replica| { cotton_store::media_thumbs::record_thumb( replica.driver, &cotton_store::media_thumbs::ThumbArrived { key: &thumb_key, workspace_id: replica.workspace_id, sha256: &"b".repeat(64), size_bytes: 21, local_path: &thumb_path.to_string_lossy(), now: "2026-09-16T09:00:00.000Z", }, ) .map_err(|error| error.to_string()) }) .expect("records the thumbnail");let preferred = ask(&key); assert_eq!(preferred["tier"], json!("thumb")); assert_eq!( preferred["path"].as_str().expect("a path"), thumb_path.to_string_lossy(),"the tile draws the 12 KB thumbnail, not the 4 MB original" );// The one caller that must have the captured bytes says so, and is never// handed a rendition.let asked_for_original = read( &client,"read.mediaPath", &super::super::shell::client::phone_tests::args(&[ ("key", json!(key)), ("tier", json!("original")), ]), ); assert_eq!(asked_for_original["path"], json!(original_path)); assert_eq!(asked_for_original["tier"], json!("original"));// 3. NOTHING — a picture whose bytes and whose thumbnail are both elsewhere.// `present: false` is a real answer, and it is what the blur is for.let neither = ask(&format!("{}/photos/{}.heic",crate::fixture::WORKSPACE,"c".repeat(64) )); assert_eq!(neither["present"], json!(false)); assert!(neither.get("path").is_none());}/// A DETAIL VIEW's order, the tile's walked from the top: **original →/// display → thumbnail**. The hero asked with the tile's order and was handed/// the 256 px thumbnail enlarged to the width of the screen while the original/// sat on disk beside it.#[test]fn a_hero_asks_for_the_largest_copy_and_is_walked_down_the_ladder() {let (dir, client) = attached(); client.set_media_fetch(Some(Arc::new(NeverFetches)));let source = a_file(dir.path(), "picture.png");let answer = capture_media( &client, &json!({ "path": source.to_string_lossy(), "mime": "image/png", "filename": "picture.png", "kind": "photo" }), ) .expect("the capture");let key = answer["answer"]["key"].as_str().expect("a key").to_string();let ask = |key: &str, tier: &str| { read( &client,"read.mediaPath", &super::super::shell::client::phone_tests::args(&[ ("key", json!(key)), ("tier", json!(tier)), ]), ) };let land = |rendition: &str, name: &str| {let path = dir.path().join(name); std::fs::write(&path, b"a synthetic rendition").expect("the file"); client .with_writer(|replica| { cotton_store::media_ledger::enqueue_media( replica.driver, &cotton_store::media_ledger::MediaEnqueueInput { key: rendition.to_string(), workspace_id: replica.workspace_id.to_string(), sha256: "b".repeat(64), size_bytes: 21, local_path: Some(path.to_string_lossy().to_string()), content_type: "image/jpeg".to_string(), tier: None, now: "2026-09-16T09:00:00.000Z".to_string(), state: Some("synced".to_string()), after: None, after_row_id: None, captured_here: false, }, ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("records the rendition"); path };let thumb_key = cotton_core::media::keys::thumb_key_for(&key).expect("a photo has one");let display_key = cotton_core::media::keys::display_key_for(&key).expect("a photo has one");let thumb_path = land(&thumb_key, "thumb.t256.jpg");let display_path = land(&display_key, "display.d1600.jpg");// The grid's order still hands the tile the thumbnail… assert_eq!(ask(&key, "best")["tier"], json!("thumb"));// …and the hero, asking for the LARGEST, gets the original that is here.let largest = ask(&key, "largest"); assert_eq!(largest["tier"], json!("original")); assert_ne!(largest["path"].as_str(), thumb_path.to_str());// The original leaves (the budget took it): the display rendition is the// next rung, never the thumbnail while a bigger copy is on disk. client .with_writer(|replica| { cotton_store::media_evict::mark_evicted(replica.driver, &key, "2026-09-17T09:00:00.000Z") .map_err(|error| error.to_string()) }) .expect("evicts the original");let after = ask(&key, "largest"); assert_eq!(after["tier"], json!("display")); assert_eq!(after["path"].as_str(), display_path.to_str());// The display rendition leaves too: the thumbnail is the honest last rung,// and the answer SAYS it is a thumbnail so a viewer knows what it enlarges. client .with_writer(|replica| { cotton_store::media_evict::mark_evicted(replica.driver, &display_key, "2026-09-17T09:00:00.000Z") .map_err(|error| error.to_string()) }) .expect("evicts the display copy");let last = ask(&key, "largest"); assert_eq!(last["tier"], json!("thumb")); assert_eq!(last["path"].as_str(), thumb_path.to_str());// And `original` under the same state answers nothing rather than a// rendition: the film page must never be handed a JPEG as the film. assert_eq!(ask(&key, "original")["present"], json!(false));}/// A tier nobody declared is a refusal, not a silent fall-through to the/// original: a caller that asked for something this build does not have is/// a caller getting an answer to a different question.#[test]fn an_unknown_tier_is_refused_by_name() {let (_dir, client) = attached();let entry = super::reads::read_for("read.mediaPath").expect("declared");let error = super::answer_read( &client, entry, &super::super::shell::client::phone_tests::args(&[ ("key", json!(format!("{}/photos/x.heic", crate::fixture::WORKSPACE))), ("tier", json!("display")), ]), ) .expect_err("a refusal"); assert!(error.contains("display"), "{error}");}// ── N10: the owner tools over the REAL phone path ──────────────────────────/// `write { tool, args }` → `ClientController::write` → `write_through_outbox`.////// `tests/mcp_owner.rs` drives these two over a `Ctx::phone` built by hand,/// which proves the handler. This proves the ROUTE: that the phone's one/// authoring method reaches an owner-scope tool at all, that the answer comes/// back in the outbox envelope, and that the ops are queued for the sync loop./// Those are three different things and only the second file can see them.#[test]fn the_owner_s_own_app_reaches_an_owner_tool_through_write() {let (_dir, client) = attached();let capture = client .with_writer(|replica| {let id = "22222222-2222-4222-8222-222222222222".to_string(); replica .driver .run("INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status, routed_kind, routed_id, routed_records, created_at, updated_at) VALUES (?, ?, 'water the plants', '2026-09-01T09:00:00.000Z', 'routed', 'todo', '33333333-3333-4333-8333-333333333333', ?, '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')", &[ rusqlite::types::Value::Text(id.clone()), rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text( json!([{ "kind": "todo", "id": "33333333-3333-4333-8333-333333333333" }]).to_string(), ), ], ) .map_err(|error| error.to_string())?; replica .driver .run("INSERT INTO cotton_todos (id, workspace_id, title, created_at, updated_at) VALUES ('33333333-3333-4333-8333-333333333333', ?, 'Water the plants', '2026-09-01T09:00:00.000Z', '2026-09-01T09:00:00.000Z')", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?;Ok(id) }) .expect("a routed capture");let answer = client .write("keep_as_thought", &crate::shell::client::phone_tests::args(&[("id", json!(capture.clone()))]), ) .expect("the owner's own app may call an owner tool"); assert_eq!(answer["answer"]["routeStatus"], json!("corrected")); assert_eq!(answer["answer"]["removed"], json!(1));// The outbox envelope, not the handler's bare answer — this is what makes// the write reach the server. assert_eq!(answer["tool"], json!("keep_as_thought")); assert_eq!(answer["rail"], json!("client")); assert!( answer["queued"].as_u64().unwrap_or(0) >= 2,"the capture and the todo it made are two ops: {answer}" );// The todo it made went with it — asked of THAT id, because the fixture's// own synthetic life has todos of its own and a table count would be// measuring those. assert!( one_row( &client,"SELECT id FROM cotton_todos WHERE id = '33333333-3333-4333-8333-333333333333'", ) .is_none(),"the record the correction took back is still there" );}#[test]fn the_owner_s_own_app_cancels_a_queued_run_through_write() {let (_dir, client) = attached(); client .with_writer(|replica| { replica .driver .run("INSERT INTO cotton_assistant_runs (id, workspace_id, source_kind, source_id, class, state, task, receipt, queued_at) VALUES ('44444444-4444-4444-8444-444444444444', ?, 'thought', '22222222-2222-4222-8222-222222222222', 'quick', 'queued', 'draft the note', 'asked from a thought', '2026-09-01T09:00:00.000Z')", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string()) }) .expect("a queued run");let answer = client .write("cancel_run", &crate::shell::client::phone_tests::args(&[("id", json!("44444444-4444-4444-8444-444444444444"), )]), ) .expect("the owner's own app may cancel their own run"); assert_eq!(answer["answer"]["cancelled"], json!(true)); assert_eq!(answer["answer"]["task"], json!("draft the note")); assert_eq!(answer["tables"], json!(["cotton_assistant_runs"])); assert_eq!(count(&client, "cotton_assistant_runs"), 0);}// ── §4: the three corrected reads ──────────────────────────────────────────#[test]fn the_notes_read_lists_the_person_s_own_notes_and_not_an_agent_s_index() {let (_dir, client) = attached();// An agent's mirror, which is what `list_managed_notes` answers with and// what the notes screen must never show. The fixture's three plain notes// are the ones a person would expect. client .with_writer(|replica| { replica .driver .run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, managed_by, external_id, created_at, updated_at) VALUES ('note-mirrored', ?, 'note', 'Mirrored', 'from a manager', 'a-manager', 'some/path.md', '2026-09-04T00:00:00.000Z', '2026-09-04T00:00:00.000Z')", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string()) }) .expect("a managed note");let answer = read(&client, "read.notes", &Map::new());let notes = answer["notes"].as_array().expect("a list");let ids: Vec<&str> = notes .iter() .filter_map(|note| note["id"].as_str()) .collect(); assert!(!ids.is_empty(), "the person's own notes come back"); assert!( !ids.contains(&"note-mirrored"),"a manager's mirror is not the person's notes list: {ids:?}" );// THE OLD BEHAVIOUR could not even get this far: `list_managed_notes`// requires `managedBy`, so the screen's own call was a validation refusal. assert!( client.read_tool("list_managed_notes", &Map::new()).is_err(),"the tool this read used to be bound to refuses the screen's own call" );}/// Each note carries its projects, so the list can dye it its first project's/// cap colour — and a note filed nowhere carries `[]`, never a missing key.#[test]fn the_notes_read_carries_each_note_s_projects() {let (_dir, client) = attached(); client .with_writer(|replica| {let ws = rusqlite::types::Value::Text(replica.workspace_id.to_string());let db = &replica.driver;let run = |sql: &str| { db.run(sql, std::slice::from_ref(&ws)) .map(|_| ()) .map_err(|error| error.to_string()) }; run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) VALUES ('note-filed', ?, 'note', 'Filed', 'in a project', '2026-09-05T00:00:00.000Z', '2026-09-05T00:00:00.000Z')")?; run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) VALUES ('note-loose', ?, 'note', 'Loose', 'in nothing', '2026-09-05T00:00:00.000Z', '2026-09-05T00:00:00.000Z')")?; run("INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, created_at, updated_at) VALUES ('project-kiln', ?, 'kiln', 'Kiln', 'active', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')")?; run("INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id, applied_by, created_at, updated_at, pinned, position) VALUES ('link-kiln', ?, 'project-kiln', 'note', 'note-filed', 'user', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', 0, 1.0)") }) .expect("a filed note and a loose one");let answer = read(&client, "read.notes", &Map::new());let notes = answer["notes"].as_array().expect("a list");let find = |id: &str| { notes .iter() .find(|note| note["id"] == json!(id)) .unwrap_or_else(|| panic!("{id} is listed")) .clone() }; assert_eq!(find("note-filed")["projects"][0]["slug"], json!("kiln")); assert_eq!(find("note-loose")["projects"], json!([]));}#[test]fn a_goal_has_a_read_of_its_own_because_the_record_read_has_no_goal_kind() {let (_dir, client) = attached(); client .with_writer(|replica| { replica .driver .run("INSERT INTO cotton_goals (id, workspace_id, title, why, status, created_at, updated_at) VALUES ('goal-1', ?, 'Learn to swim', 'because the sea is right there', 'active', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string()) }) .expect("a goal");let answer = read( &client,"read.goal", &super::super::shell::client::phone_tests::args(&[("id", json!("goal-1"))]), ); assert_eq!(answer["goal"]["title"], json!("Learn to swim")); assert_eq!(answer["goal"]["status"], json!("active"));// THE OLD BEHAVIOUR: the goal route was on `read.record`, and `get_record`// has no goal kind — so tapping a goal was a validation refusal.let refused = client.read_tool("get_record", &super::super::shell::client::phone_tests::args(&[ ("kind", json!("goal")), ("id", json!("goal-1")), ]), ); assert!(refused.is_err(), "get_record still has no goal kind");// And no read claims that route twice.let record = super::reads::read_for("read.record").expect("the record read"); assert!( !record.audience.screens().contains(&"/goals/goal/[id]"),"the goal route moved off the record read" );// A goal that is not there is `null`, never a refusal: a stale link draws// "this goal is gone" rather than a crash.let gone = read( &client,"read.goal", &super::super::shell::client::phone_tests::args(&[("id", json!("goal-absent"))]), ); assert_eq!(gone["goal"], Value::Null);}/// A disk with numbers of its own and no filesystem behind it.#[derive(Debug)]structFakeDisk;implDiskforFakeDisk {fn size_of(&self, path: &Path) -> u64 {// Keyed on the last segment so the read's four questions are told// apart without this fake knowing the layout's shape.match path.file_name().and_then(std::ffi::OsStr::to_str) {Some("media") => 2_000,Some("snapshots") => 300,Some("thumbs") => 40, _ => 9_000, } }fn free_bytes(&self, _path: &Path) -> Option<u64> {Some(123_456) }}#[test]fn the_storage_read_is_about_this_phone_s_disk_and_not_the_workspace_s_rows() {let (_dir, client) = attached(); client.set_disk(Arc::new(FakeDisk));let answer = read(&client, "read.storage", &Map::new());// Every figure is a reading of THIS DEVICE, through the seam — which is// what makes the test possible at all: nothing here wrote two kilobytes. assert_eq!(answer["bytes"]["device"], json!(9_000)); assert_eq!(answer["bytes"]["media"], json!(2_000)); assert_eq!(answer["bytes"]["snapshots"], json!(300)); assert_eq!(answer["bytes"]["thumbnails"], json!(40)); assert_eq!(answer["freeBytes"], json!(123_456)); assert!(answer.get("freeBytesUnavailable").is_none());// And the ledger's own counts, which is this phone's backlog and not the// workspace's byte total. assert_eq!(answer["uploads"]["pending"], json!(0));// THE OLD BEHAVIOUR answered the workspace's record bytes — a number that// does not move when this phone fills up, and does not shrink when the// person clears their snapshots.let workspace = client .read_tool("storage_summary", &Map::new()) .expect("the tool still answers"); assert!( workspace.get("bytes").is_none() || workspace["bytes"] != answer["bytes"],"the two reads answer different questions" );}/// The free-space answer with the real disk: `null`, and never a zero.#[test]fn free_space_this_core_cannot_read_is_null_with_the_reason_beside_it() {let (_dir, client) = attached();let answer = read(&client, "read.storage", &Map::new()); assert_eq!(answer["freeBytes"], Value::Null); assert!( answer["freeBytesUnavailable"] .as_str() .is_some_and(|reason| reason.contains("volumeAvailableCapacityForImportantUsage")),"a null with no sentence is the masked fallback this repo does not allow: {answer}" );}/// A `Replica` is never built here directly — every case goes through the/// controller — so this silences the unused import rather than hiding a seam.#[allow(dead_code)]fn _replica_type_is_named(_: &ReadFile<'_>) {}// ── dictation.create ────────────────────────────────────────────────────────//// The corpus has one author and it is the app: grep// `cotton-tools/src/mcp/catalogue.rs`// for `dictat` and nothing comes back. `/take` writes deliberate speech and the// keyboard's outbox drain writes typed bursts, through this one method, because// the corpus is only worth mining if every row was shaped by the same rules.#[test]fn a_take_lands_in_the_corpus_with_its_own_word_count() {let (_dir, client) = attached();let answer = run( &client,"dictation.create", &json!({ "text": "ring the vet about the cat", "source": "take", "words": 6 }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT text, raw_text, source, host_app, CAST(words AS TEXT) AS words, duration_ms, external_id, spoken_at FROM cotton_dictations WHERE id = '{id}'" ), ) .expect("the dictation"); assert_eq!(row["text"], json!("ring the vet about the cat")); assert_eq!(row["source"], json!("take")); assert_eq!(row["words"], json!("6"));// There is no polish, so there is never a second copy of the text. assert_eq!(row["raw_text"], Value::Null);// iOS gives a keyboard extension no public API for its host app, so a value// here would be a guess. assert_eq!(row["host_app"], Value::Null);// The importer's idempotency key, which no phone write has. assert_eq!(row["external_id"], Value::Null); assert_eq!(row["duration_ms"], Value::Null);// A live take is stamped with now rather than carrying nothing. assert_ne!(row["spoken_at"], Value::Null); assert_eq!(answer["tables"], json!(["cotton_dictations"]));}/// A caller that did not count gets the same arithmetic here, so a take/// counted by the app and one counted below cannot disagree about a sentence.#[test]fn a_take_that_carries_no_count_is_counted_here() {let (_dir, client) = attached();let answer = run( &client,"dictation.create", &json!({ "text": " two words ", "source": "take" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT text, source, CAST(words AS TEXT) AS words FROM cotton_dictations WHERE id = '{id}'" ), ) .expect("the dictation");// Trimmed, as the TypeScript trims. assert_eq!(row["text"], json!("two words")); assert_eq!(row["source"], json!("take")); assert_eq!(row["words"], json!("2"));}/// A carried instant is when it was said, so a take written later sorts where/// it happened rather than where it was written.#[test]fn a_carried_instant_is_when_it_was_said_not_when_it_drained() {let (_dir, client) = attached();let answer = run( &client,"dictation.create", &json!({"text": "said while offline","source": "take","spokenAt": "2026-09-01T07:15:00.000Z", }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT spoken_at FROM cotton_dictations WHERE id = '{id}'"), ) .expect("the dictation"); assert_eq!(row["spoken_at"], json!("2026-09-01T07:15:00.000Z"));}#[test]fn an_empty_dictation_is_refused_before_anything_opens() {for request in [ json!({ "source": "take" }), json!({ "text": " ", "source": "take" }), ] {let error = super::dictation::validate(&request).expect_err("a refusal"); assert_eq!(error.code, "bad_request"); assert!( error.message.contains("cannot be empty"),"{}", error.message ); }}/// The refusal NAMES the one that exists rather than saying "invalid".#[test]fn an_unknown_source_is_refused_by_name() {let error = super::dictation::validate(&json!({ "text": "x", "source": "sms" })) .expect_err("a refusal"); assert!(error.message.contains("take"), "{}", error.message);}/// RULE: the keyboard is voice only — a typed burst is refused, though older `typed` rows stay in the column.#[test]fn a_typed_burst_is_refused() {let error = super::dictation::validate(&json!({ "text": "x", "source": "typed" })) .expect_err("a refusal"); assert_eq!(error.code, "bad_request"); assert!(error.message.contains("keeps nothing typed"), "{}", error.message);}/// `wispr` is a real value of the column and it is still refused HERE: it is an/// IMPORT provenance carrying an idempotency key this method has no argument/// for, and an import is not something a phone screen does.#[test]fn the_importers_provenance_is_refused_although_the_column_admits_it() {let error = super::dictation::validate(&json!({ "text": "x", "source": "wispr" })) .expect_err("a refusal"); assert!(error.message.contains("importer"), "{}", error.message);}/// NOT clamped to zero, refused: a negative word count is not a smaller one, it/// is a broken caller, and the corpus's whole value is that the figure beside/// each row can be trusted.#[test]fn a_negative_word_count_is_refused_rather_than_clamped() {let error = super::dictation::validate(&json!({ "text": "x", "source": "take", "words": -1 })) .expect_err("a refusal"); assert!(error.message.contains("non-negative"), "{}", error.message);}// ── page.save ───────────────────────────────────────────────────────────────//// The tool surface already refuses `create_page`, and the reason it gives names// this caller: "pages are saved from the share sheet — a URL from the owner's// phone, not an assistant write".#[test]fn a_shared_link_lands_as_a_page_with_its_host_derived() {let (_dir, client) = attached();let answer = run( &client,"page.save", &json!({ "url": "https://example.test/a/deep/page", "title": " A page " }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT url, host, title, read_at, source_inbox_id, archived_at FROM cotton_pages WHERE id = '{id}'" ), ) .expect("the page"); assert_eq!(row["url"], json!("https://example.test/a/deep/page"));// Derived, never passed in — two spellings of one page is two rows in the// reading pile. assert_eq!(row["host"], json!("example.test")); assert_eq!(row["title"], json!("A page"));// Not read, and it did not come through the inbox: the share sheet's URL// branch writes the row directly, with no capture for the router to file. assert_eq!(row["read_at"], Value::Null); assert_eq!(row["source_inbox_id"], Value::Null); assert_eq!(row["archived_at"], Value::Null);// The page, and its history row (slice 6b). assert_eq!(answer["tables"], json!(["cotton_pages", "cotton_changes"]));}#[test]fn a_link_shared_without_a_title_keeps_none() {let (_dir, client) = attached();let answer = run( &client,"page.save", &json!({ "url": "https://example.test/" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let row = one_row( &client, &format!("SELECT title FROM cotton_pages WHERE id = '{id}'"), ) .expect("the page");// NULL rather than an empty string: the page's real title arrives later,// when the reader opens it and writes back what it learned. assert_eq!(row["title"], Value::Null);}#[test]fn a_url_that_will_not_parse_is_refused_by_name() {for raw in ["", "example.test", "not a url", "ftp://example.test/x"] {let error = super::page::validate(&json!({ "url": raw })).expect_err("invalid URL must be refused"); assert_eq!(error.code, "bad_request"); assert!( error.message.contains("absolute http(s) URL"),"{raw}: {}", error.message ); }}/// NOT silently ignored. A saved page keeps the article's own text, pulled in/// from the address by the serving Mac — so accepting a sharer's excerpt and/// dropping it would tell the share sheet a summary was kept.#[test]fn an_excerpt_is_refused_rather_than_dropped() {let error = super::page::validate( &json!({ "url": "https://example.test/", "excerpt": "the first paragraph" }), ) .expect_err("a refusal"); assert!(error.message.contains("no excerpt"), "{}", error.message);}/// A second save of the same URL writes a SECOND row, and that is the/// TypeScript's behaviour rather than an omission: `cotton_pages` has no/// natural key and `createPage` mints a fresh id every time. Sharing a link/// twice is a person saving it twice; the Reader is where a duplicate is/// archived. Refusing here would need a uniqueness rule the file does not/// declare, which is exactly the new behaviour this lane may not add.#[test]fn saving_one_url_twice_writes_two_rows_as_the_file_declares_no_key() {let (_dir, client) = attached();let first = run( &client,"page.save", &json!({ "url": "https://example.test/x" }), );let second = run( &client,"page.save", &json!({ "url": "https://example.test/x" }), ); assert_ne!(first["answer"]["id"], second["answer"]["id"]); assert_eq!(count(&client, "cotton_pages"), 2);}#[test]fn dictation_lands_the_words_verbatim_and_rounds_only_the_duration() {// Fillers, no capital, no punctuation, a spoken number and a spoken mark —// every one of them a thing the retired polish pass would have changed. The// duration is recording METADATA and still rounds.let spoken = "um so i think we should uh call ramesh about the twenty five thousand full stop";let (_dir, client) = attached();let answer = run(&client, "dictation.create", &json!({"text":spoken,"source":"take","durationMs":1200.5}));let id = answer["answer"]["id"].as_str().expect("id");let row = one_row(&client, &format!("SELECT text, raw_text, CAST(duration_ms AS TEXT) AS duration_ms FROM cotton_dictations WHERE id = '{id}'")).expect("row"); assert_eq!(row["text"], json!(spoken)); assert_eq!(row["raw_text"], Value::Null); assert_eq!(row["duration_ms"],json!("1201"));// `rawText` is not a field any more: an unknown key is ignored, never a// second copy of the words.let args = super::dictation::validate(&json!({"text":spoken,"source":"take","rawText":"something else"})).expect("args"); assert_eq!(args.text, spoken);}#[test]fn dictation_refuses_wrong_duration_types() {for fields in [json!({"durationMs":"later"}), json!({"durationMs":1e30})] {letmut request = json!({"text":"Synthetic text","source":"take"}); request.as_object_mut().expect("request").extend(fields.as_object().expect("fields").clone()); assert!(super::dictation::validate(&request).is_err()); }}#[test]fn shared_prose_saves_every_url_through_core_extraction() {let (_dir, client) = attached();let answer = run(&client, "page.save", &json!({"text":"Synthetic https://alpha.example.test/One and https://beta.example.test/Two"})); assert_eq!(answer["answer"]["ids"].as_array().expect("ids").len(), 2); assert_eq!(count(&client,"cotton_pages"), 2);}#[test]fn page_save_canonicalises_authority_and_preserves_path_case() {let (_dir, client) = attached();let answer = run(&client, "page.save", &json!({"url":"HTTPS://SYNTHETIC.EXAMPLE.TEST/Case?Keep=YES"}));let id = answer["answer"]["id"].as_str().expect("id");let row = one_row(&client, &format!("SELECT url,host FROM cotton_pages WHERE id = '{id}'")).expect("row"); assert_eq!(row["url"],"https://synthetic.example.test/Case?Keep=YES"); assert_eq!(row["host"],"synthetic.example.test");}#[test]fn dictation_text_uses_javascript_trim() {let args=super::dictation::validate(&json!({"text":"\u{feff}Synthetic\u{feff}","source":"take"})).expect("args"); assert_eq!(args.text,"Synthetic");let args=super::dictation::validate(&json!({"text":"\u{85}","source":"take"})).expect("NEL is not JS whitespace"); assert_eq!(args.text,"\u{85}");}// ── session.resume ──────────────────────────────────────────────────────────//// **CARRYING A SESSION ON WHERE IT STOPPED.** It re-queues THE SAME ROW on the// Mac it ran on and keeps `external_id`, because that id is what the agent is// asked to continue and what every button on the card addresses over the// helper's socket./// A session that ran on a Mac and ended, ready to be carried on.fn ended_session(client: &crate::shell::client::ClientController, id: &str, state: &str) { client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET state = '{state}', external_id = 'agent-1', \ host_owned = 1, device_id = 'a-synthetic-device-key', \ machine = 'm-synthetic', started_at = '2026-09-08T09:00:00.000Z', \ ended_at = '2026-09-08T10:00:00.000Z', exit_code = 1, \ error = 'ended when the session host restarted on m-synthetic' \ WHERE id = '{id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the ended session");}#[test]fn a_resume_re_queues_the_same_row_on_the_mac_it_ran_on() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string(); ended_session(&client, &id, "ended");let resumed = run(&client, "session.resume", &json!({ "sessionId": id })); assert_eq!(resumed["answer"]["state"], json!("queued")); assert_eq!(resumed["answer"]["id"], json!(id));let row = one_row( &client, &format!("SELECT state, external_id, device_id, requested_device_id, chosen_by, ended_at, \ exit_code, error FROM cotton_sessions WHERE id = '{id}'" ), ) .expect("the session"); assert_eq!(row["state"], json!("queued"));// THE ID IS KEPT. It is what `claude --resume` is given and what every// button on the card addresses over the socket. assert_eq!(row["external_id"], json!("agent-1"));// AND THE MAC IS NAMED, both ways: the transcript is on that machine and// nowhere else, so this is not a placement the dispatcher may reconsider. assert_eq!(row["device_id"], json!("a-synthetic-device-key")); assert_eq!(row["requested_device_id"], json!("a-synthetic-device-key")); assert_eq!(row["chosen_by"], json!("owner"));// EVERY MARK OF THE LAST ENDING IS OFF. assert_eq!(row["ended_at"], Value::Null); assert_eq!(row["exit_code"], Value::Null); assert_eq!(row["error"], Value::Null);}#[test]fn a_failed_session_can_be_resumed_too() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string(); ended_session(&client, &id, "failed"); assert_eq!( run(&client, "session.resume", &json!({ "sessionId": id }))["answer"]["state"], json!("queued") );}#[test]fn a_session_that_is_still_going_is_refused_with_its_state_named() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string();let refused = client .write_rows("session.resume", &mut |ctx| {super::session_queue::write_resume(ctx, &id) }) .expect_err("a refusal"); assert!(refused.contains("queued"), "{refused}"); assert!(refused.contains("only one that has ended"), "{refused}");let absent = client .write_rows("session.resume", &mut |ctx| {super::session_queue::write_resume(ctx, "session-absent") }) .expect_err("a refusal"); assert!(absent.contains("session-absent"), "{absent}");}#[test]fn a_session_cotton_did_not_start_is_refused_by_name() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string(); ended_session(&client, &id, "ended"); client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET host_owned = 0 WHERE id = '{id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the adopted row");let refused = client .write_rows("session.resume", &mut |ctx| {super::session_queue::write_resume(ctx, &id) }) .expect_err("a refusal"); assert!(refused.contains("started in a terminal"), "{refused}");}/// RULE: a session that failed before its agent ran is restarted — the same row, queued afresh — while an ended one with no agent is refused.// The claim hands the agent id back when it could not spawn (no folder, no// clone, no login), so the old rule refused every such row and the wake pass// logged "never reached an agent" for ever while the phone showed the message// as waiting. Nothing was lost on that row, so Resume asks for it again; the// Mac it failed on is not sent for by name — `device_id` goes back to the// owner's own ask.#[test]fn a_session_that_failed_before_any_agent_ran_is_restarted_from_its_own_row() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string(); ended_session(&client, &id, "failed"); client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET external_id = NULL, chosen_by = 'dispatcher' \ WHERE id = '{id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the row with no agent");let answer = client .write_rows("session.resume", &mut |ctx| {super::session_queue::write_resume(ctx, &id) }) .expect("a restart"); assert_eq!(answer["answer"]["state"], json!("queued"), "{answer}");let row = client .with_writer(|replica| { replica .driver .get("SELECT state, device_id, requested_device_id, machine, chosen_by, \ external_id, error, ended_at FROM cotton_sessions WHERE id = ?", &[rusqlite::types::Value::Text(id.clone())], ) .map_err(|error| error.to_string()) }) .expect("the row") .expect("the row"); assert_eq!(row.text("state"), Some("queued"));// The owner asked for this Mac when they created it, so the restart asks// for it again; a session created for "any Mac" would go back to NULL. assert_eq!(row.text("requested_device_id"), Some("a-synthetic-device-key")); assert_eq!(row.text("device_id"), Some("a-synthetic-device-key")); assert_eq!(row.text("chosen_by"), Some("owner")); assert_eq!(row.text("machine"), None, "the placement's name is the dispatcher's to write"); assert_eq!(row.text("external_id"), None, "there was never an agent to continue"); assert_eq!(row.text("error"), None, "every mark of the failure comes off"); assert_eq!(row.text("ended_at"), None);}#[test]fn an_ended_session_that_never_reached_an_agent_has_nothing_to_carry_on_from() {let (_dir, client) = attached();let answer = run( &client,"session.create", &json!({ "deviceId": "a-synthetic-device-key", "prompt": "x" }), );let id = answer["answer"]["id"].as_str().expect("an id").to_string(); ended_session(&client, &id, "ended"); client .with_writer(|replica| {let sql = format!("UPDATE cotton_sessions SET external_id = NULL WHERE id = '{id}'" ); replica.driver.exec(&sql).map_err(|error| error.to_string())?;crate::fixture::receipted(replica.driver, &sql);Ok(()) }) .expect("the row with no agent");let refused = client .write_rows("session.resume", &mut |ctx| {super::session_queue::write_resume(ctx, &id) }) .expect_err("a refusal"); assert!(refused.contains("nothing to carry on from"), "{refused}");}#[test]fn the_rule_is_one_pure_function_and_every_arm_is_a_reason() {usesuper::session_queue::can_resume; assert!(can_resume("ended", true, Some("agent-1"), Some("mac-1"))); assert!(can_resume("failed", true, Some("agent-1"), Some("mac-1")));for state in ["queued", "starting", "running", "idle", "waiting", "withdrawn"] { assert!(!can_resume(state, true, Some("agent-1"), Some("mac-1")), "{state}"); } assert!(!can_resume("ended", false, Some("agent-1"), Some("mac-1"))); assert!(!can_resume("ended", true, None, Some("mac-1"))); assert!(!can_resume("ended", true, Some(""), Some("mac-1")));// **THE TRANSCRIPT IS ON ONE MAC.** With no Mac recorded there is nowhere// to place the resume, and a resume placed anywhere else would start over. assert!(!can_resume("ended", true, Some("agent-1"), None)); assert!(!can_resume("ended", true, Some("agent-1"), Some("")));}#[test]fn a_capture_before_the_phones_row_arrives_is_refused_and_writes_nothing() {let (dir, client) = attached();// The row has not reached this copy yet: take out the one `attached` seeds. client .with_writer(|replica| { replica .driver .run("DELETE FROM cotton_devices WHERE device_id = ?", &[rusqlite::types::Value::Text(crate::fixture::SELF_DEVICE_ID.to_string(), )], ) .map(|_| ()) .map_err(|error| error.to_string()) }) .expect("no row for this phone");let source = a_file(dir.path(), "picked.png");let refused = capture_media( &client, &json!({ "path": source.to_string_lossy(), "mime": "image/png", "kind": "photo" }), ) .expect_err("a capture with no device row is refused"); assert!( refused.to_string().contains(crate::authoring::NO_DEVICE_ROW),"{refused}" );let (holds, records) = client .with_writer(|replica| {let holds = replica .driver .all("SELECT id FROM cotton_media_holdings", &[]) .map_err(|error| error.to_string())?;let records = replica .driver .all("SELECT op_id FROM _outbox", &[]) .map_err(|error| error.to_string())?;Ok((holds, records)) }) .expect("the holdings"); assert!(holds.is_empty(), "no hold under a key this copy does not know"); assert!(records.is_empty(), "and nothing queued: the refusal wrote nothing");}/// RULE: Picking the same document bytes again reuses its record and preserves its metadata, while this phone keeps the bytes permanently.#[test]fn capturing_the_same_document_twice_reuses_its_record_and_local_bytes() {let (dir, client) = attached();let source = a_file(dir.path(), "first.pdf");let capture = |path: &Path, filename: &str| { capture_media( &client, &json!({"path": path.to_string_lossy(),"mime": "application/pdf","filename": filename,"kind": "document", }), ) };let first = capture(&source, "first.pdf").expect("the first capture");// A second picker staging path and name still identify the same file bytes.let picked_again = a_file(dir.path(), "picked-again.pdf");let second = capture(&picked_again, "picked-again.pdf").expect("the same file again"); assert_eq!(second["answer"]["recordId"], first["answer"]["recordId"]); assert_eq!(second["answer"]["key"], first["answer"]["key"]); assert_eq!(count(&client, "cotton_documents"), 1);let key = first["answer"]["key"].as_str().expect("the original key");let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, key) .map_err(|error| error.to_string()) }) .expect("the ledger read") .expect("the local file"); assert_eq!(ledger.after.as_deref(), Some("document_process")); assert_eq!( ledger.after_row_id.as_deref(), first["answer"]["recordId"].as_str() ); assert_eq!( std::fs::read(ledger.local_path.expect("local bytes")).expect("the bytes"), b"png" ); assert!(source.exists(), "capture copies the picker's file"); assert!( picked_again.exists(),"recapture also leaves the picker's file alone" );}#[test]fn recapturing_a_processed_document_keeps_its_title_summary_and_status() {let (dir, client) = attached();let source = a_file(dir.path(), "original.pdf");let request = json!({"path": source.to_string_lossy(),"mime": "application/pdf","filename": "original.pdf","kind": "document", });let first = capture_media(&client, &request).expect("the first capture");let id = first["answer"]["recordId"] .as_str() .expect("the document id"); client .write_rows("fixture:processed-document", &mut |ctx| {let patch = json!({"title": "Synthetic field guide","summary": "A synthetic document whose description is already kept.","status": "ready", }) .as_object() .expect("the patch") .clone(); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_documents", id, patch) .map_err(|error| error.to_string())?;Ok(Value::Null) }) .expect("the processed document");let query = format!("SELECT title, summary, status, original_name, storage_path, updated_at \ FROM cotton_documents WHERE id = '{id}'" );let before = one_row(&client, &query).expect("the processed row");let second = capture_media(&client, &request).expect("the same processed file again"); assert_eq!(second["answer"]["recordId"], json!(id)); assert_eq!(one_row(&client, &query).expect("the row remains"), before); assert_eq!(count(&client, "cotton_documents"), 1);}fn document_request(path: &Path) -> Value { json!({"path": path.to_string_lossy(), "mime": "application/pdf","filename": "synthetic.pdf", "kind": "document"})}#[test]fn recapturing_a_binned_document_restores_the_existing_id() {let (dir, client) = attached();let request = document_request(&a_file(dir.path(), "synthetic.pdf"));let first = capture_media(&client, &request).expect("first capture");let id = first["answer"]["recordId"].as_str().expect("id"); client .write_rows("fixture:bin-document", &mut |ctx| { cotton_tools::mcp::handlers::documents::tools::set_document_trashed(ctx, id, true) .map_err(|error| error.to_string())?;Ok(Value::Null) }) .expect("bin the document");let query = format!("SELECT trashed_at FROM cotton_documents WHERE id = '{id}'"); assert!(one_row(&client, &query).expect("binned row")["trashed_at"].is_string());let again = capture_media(&client, &request).expect("capture restores it"); assert_eq!(again["answer"]["recordId"], json!(id)); assert!(one_row(&client, &query).expect("restored row")["trashed_at"].is_null()); assert_eq!(count(&client, "cotton_documents"), 1);}#[test]fn recapturing_a_document_replenishes_bytes_without_requeueing_a_synced_upload() {let (dir, client) = attached();let request = document_request(&a_file(dir.path(), "synthetic.pdf"));let first = capture_media(&client, &request).expect("first capture");let key = first["answer"]["key"].as_str().expect("key");let before = client .with_writer(|replica| { cotton_store::media_ledger::mark_media_synced( replica.driver, key,"2026-10-07T00:00:00.000Z", ) .map_err(|error| error.to_string())?; cotton_store::media_ledger::media_by_key(replica.driver, key) .map_err(|error| error.to_string()) }) .expect("ledger read") .expect("the upload"); std::fs::remove_file(before.local_path.as_ref().expect("local path")) .expect("missing local copy");let again = capture_media(&client, &request).expect("capture copies the bytes back"); assert_eq!(again["answer"]["key"], json!(key));let after = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key(replica.driver, key) .map_err(|error| error.to_string()) }) .expect("ledger read") .expect("the upload remains"); assert_eq!(after.state, before.state); assert_eq!(after.attempts, before.attempts); assert_eq!(after.last_error, before.last_error); assert!(after.captured_here); assert_eq!( std::fs::read(after.local_path.expect("local bytes")).expect("bytes"), b"png" );}#[test]fn recapturing_refuses_an_invalid_existing_key_without_restoring_its_row() {let (dir, client) = attached();let request = document_request(&a_file(dir.path(), "synthetic.pdf"));let first = capture_media(&client, &request).expect("first capture");let id = first["answer"]["recordId"].as_str().expect("id"); client .write_rows("fixture:broken-document", &mut |ctx| {let patch = json!({"storage_path": "","trashed_at": "2026-10-07T00:00:00.000Z"}) .as_object() .expect("patch") .clone(); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_documents", id, patch) .map_err(|error| error.to_string())?;Ok(Value::Null) }) .expect("a broken stored key");let query = format!("SELECT * FROM cotton_documents WHERE id = '{id}'");let before = one_row(&client, &query).expect("row before"); assert!( capture_media(&client, &request).is_err(),"do not invent a replacement key" ); assert_eq!(one_row(&client, &query).expect("row after"), before); assert_eq!(count(&client, "cotton_documents"), 1);}#[test]fn phone_document_identity_uses_the_shared_intake_generation() {let (dir, client) = attached();let source = a_file(dir.path(), "synthetic.pdf");let (digest, _) = cotton_client::media::store::sha256_file(&source).expect("file digest");let expected = client .write_rows("fixture:identity", &mut |ctx| { cotton_store::erase::generation_id( ctx.db(),"cotton_documents", &[ctx.file.namespace().as_str(), &digest], ) .map(Value::from) .map_err(|error| error.to_string()) }) .expect("MCP intake identity");let captured = capture_media(&client, &document_request(&source)).expect("phone capture"); assert_eq!(captured["answer"]["recordId"], expected["answer"]);}#[test]fn recapturing_keeps_a_preexisting_document_id_and_original_metadata() {let (dir, client) = attached();let source = a_file(dir.path(), "synthetic.pdf");let (digest, _) = cotton_client::media::store::sha256_file(&source).expect("file digest");let id = "150c14de-2551-4fbe-a71b-2f98217a5d03";let expected_key = client .write_rows("fixture:existing-document", &mut |ctx| {let key = cotton_core::media::keys::document_original_key(ctx.file.id(), id, "pdf");let patch = json!({"sha256": digest, "original_name": "Already filed.pdf","mime": "application/pdf", "byte_size": 3, "storage_path": key,"status": "ready", "status_changed_at": "2026-10-07T00:00:00.000Z","source": "agent", "title": "Existing synthetic file","summary": "Already described."}) .as_object() .expect("patch") .clone(); cotton_tools::mcp::handlers::common::insert_row(ctx, "cotton_documents", id, patch) .map_err(|error| error.to_string())?;Ok(Value::from(key)) }) .expect("preexisting document");let query = format!("SELECT * FROM cotton_documents WHERE id = '{id}'");let before = one_row(&client, &query).expect("row before");let again = capture_media(&client, &document_request(&source)).expect("same bytes on this phone"); assert_eq!(again["answer"]["recordId"], json!(id)); assert_eq!(again["answer"]["key"], expected_key["answer"]); assert_eq!(one_row(&client, &query).expect("row after"), before);let ledger = client .with_writer(|replica| { cotton_store::media_ledger::media_by_key( replica.driver, expected_key["answer"].as_str().expect("original key"), ) .map_err(|error| error.to_string()) }) .expect("ledger") .expect("local copy"); assert!( ledger.after.is_none(),"a processed document needs no processing trigger" ); assert_eq!(count(&client, "cotton_documents"), 1);}/// A phone report is a document written on this device's own copy — titled,/// `processing`, and queued in `_media` for the next exchange — so "Send a/// report" works with no Mac in reach (phone diagnostics part 3).#[test]fn a_report_is_filed_offline_as_a_titled_text_document_queued_to_go_up() {let (_dir, client) = attached();let layout = client.layout().clone();let id = crate::shell::report::file(&client, &layout, "Phone report · 12 Oct 16:02", "Phone report\n") .expect("filed");let row = one_row(&client, &format!("SELECT title, mime, status, original_name FROM cotton_documents WHERE id = '{id}'")) .expect("the document row"); assert_eq!(row["title"], "Phone report · 12 Oct 16:02"); assert_eq!(row["mime"], "text/plain"); assert_eq!(row["status"], "processing"); assert_eq!(row["original_name"], "Phone report · 12 Oct 16:02.txt"); assert_eq!(count(&client, "_media"), 1, "the bytes wait in the upload queue"); assert!( std::fs::read_dir(layout.root().join("client").join("reports")).expect("dir").next().is_none(),"the scratch copy is gone once the store holds the bytes" );}/// RULE: Parsing capture words is a read; dates, names and amounts cannot create records before the owner sees a proposal in Asked of you.#[test]fn parsing_a_thought_with_a_date_name_and_amount_writes_nothing() {let (_dir, client) = attached();let before = ops(&client);let parsed = super::phrase::call(&client, &json!({"text":"pay Sam 450 tomorrow","now":"2026-10-01T12:00:00Z","time_zone":"UTC","projects":[],"people":["Sam"]})).unwrap(); assert_eq!(parsed["person"]["candidates"], json!(["Sam"])); assert_eq!(parsed["date"]["candidates"], json!(["2026-10-02"])); assert_eq!(ops(&client), before, "parsing writes nothing");}