1305 lines · 45.5 KB · RustRaw
//! The photo and video tools, end to end over `dispatch::call_tool` on a real//! file with a fake `ToolServices` behind it.//!//! What these are really about is that a picture is a REFERENCE to bytes and//! the row is everything else — so the assertions are split deliberately: the//! tool's answer for what an assistant reads, and the FILE for what actually//! landed. A caption that answered right and stored wrong would look fine here//! and be gone on the owner's phone.//!//! ONE DIVERGENCE: the whitespace-note case calls `update_media` against a//! `Ctx` built over the harness's own file rather than over a hand-made stub,//! because a `Ctx` is a struct here and not a shape. The store is the fake one//! on `ToolServices` throughout — it holds bytes AND signs, so the `get_video`//! cases that assert a link need no second store the way the server's did.//!//! Every name, number and line of text is synthetic.mod support;use std::sync::Arc;use cotton_store::protocol::derived_id::media_sighting_id;use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use cotton_tools::mcp::handlers::common::Clearable;use cotton_tools::mcp::handlers::media_tools::{update_media, UpdateMediaArgs, PHOTO_SPEC};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, call_tool_result, mint_token};const AT: &str = "2026-09-01T00:00:00.000Z";const SHA_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";const SHA_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";const SHA_VIDEO: &str = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";fn t(value: &str) -> SqlValue { SqlValue::Text(value.to_string())}fn n(value: i64) -> SqlValue { SqlValue::Integer(value)}fn run(h: &Harness, sql: &str, params: Vec<SqlValue>) { h.run(sql, ¶ms);}fn one( h: &Harness, sql: &str, params: Vec<SqlValue>,) -> Option<Vec<(String, rusqlite::types::Value)>> { h.with(|db| db.get(sql, ¶ms)) .expect("the statement runs") .map(|row| row.columns().to_vec())}fn column(row: &[(String, rusqlite::types::Value)], name: &str) -> rusqlite::types::Value { row.iter() .find(|(key, _)| key == name) .map(|(_, value)| value.clone()) .unwrap_or(rusqlite::types::Value::Null)}fn as_text(row: &[(String, rusqlite::types::Value)], name: &str) -> Option<String> { match column(row, name) { rusqlite::types::Value::Text(value) => Some(value), _ => None, }}fn photo_row(h: &Harness, id: &str) -> Option<Vec<(String, rusqlite::types::Value)>> { one(h, "SELECT * FROM cotton_photos WHERE id = ?", vec![t(id)])}fn video_row(h: &Harness, id: &str) -> Option<Vec<(String, rusqlite::types::Value)>> { one(h, "SELECT * FROM cotton_videos WHERE id = ?", vec![t(id)])}/// The ids a list answered, in order.fn ids(answer: &Value, plural: &str) -> Vec<String> { answer[plural] .as_array() .expect("a list") .iter() .map(|row| row["id"].as_str().expect("an id").to_string()) .collect()}// ── seeding ─────────────────────────────────────────────────────────────────struct NewPhoto<'a> { sha256: &'a str, key: String, taken_at: &'a str, thread_id: Option<String>, source_id: Option<String>, caption: Option<&'a str>, summary: Option<&'a str>, size_bytes: i64,}impl<'a> NewPhoto<'a> { fn new(sha256: &'a str, key: String, taken_at: &'a str) -> NewPhoto<'a> { NewPhoto { sha256, key, taken_at, thread_id: None, source_id: None, caption: None, summary: None, size_bytes: 240_000, } }}fn insert_photo(h: &Harness, row: NewPhoto<'_>) -> String { let id = format!("photo:{}", row.sha256); run( h, "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, width, height, taken_at, preview, caption, summary, summary_by, summary_at, review_note, review_by, review_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'image/jpeg', ?, 1200, 900, ?, NULL, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?)", vec![ t(&id), t(&h.workspace_id), t(&row.key), t(row.sha256), n(row.size_bytes), t(row.taken_at), row.caption.map_or(SqlValue::Null, t), row.summary.map_or(SqlValue::Null, t), if row.summary.is_some() { t("job:media-describe") } else { SqlValue::Null }, if row.summary.is_some() { t(AT) } else { SqlValue::Null }, t(AT), t(AT), ], ); // WHERE it was seen is a row of its own (v39): the chat, or the library. match &row.thread_id { Some(thread_id) => insert_sighting( h, &id, "message", row.source_id.as_deref(), Some(thread_id), &row.key, row.taken_at, ), None => insert_sighting(h, &id, "library", None, None, &row.key, row.taken_at), }; id}fn insert_sighting( h: &Harness, record_id: &str, source: &str, source_id: Option<&str>, thread_id: Option<&str>, key: &str, seen_at: &str,) -> String { let kind = if record_id.starts_with("video:") { "video" } else { "photo" }; let id = media_sighting_id(kind, record_id, source, source_id); run( h, "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, source_id, thread_id, key, seen_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", vec![ t(&id), t(&h.workspace_id), t(kind), t(record_id), t(source), source_id.map_or(SqlValue::Null, t), thread_id.map_or(SqlValue::Null, t), t(key), t(seen_at), t(AT), t(AT), ], ); id}fn insert_face(h: &Harness, record_id: &str, source_id: &str, person_id: Option<&str>, x: f64) { run( h, "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, source_id, x, y, w, h, quality, cluster_id, person_id, created_at, updated_at) VALUES (?, ?, 'photo', ?, 'apple', ?, ?, 0.1, 0.2, 0.2, 0.7, NULL, ?, ?, ?)", vec![ t(&format!("face:{record_id}:{source_id}")), t(&h.workspace_id), t(record_id), t(source_id), SqlValue::Real(x), person_id.map_or(SqlValue::Null, t), t(AT), t(AT), ], );}fn insert_person(h: &Harness, name: &str) -> String { let id = synthetic_uuid("person"); run( h, "INSERT INTO cotton_people (id, workspace_id, full_name, contact_source, created_at, updated_at) VALUES (?, ?, ?, 'manual', ?, ?)", vec![t(&id), t(&h.workspace_id), t(name), t(AT), t(AT)], ); id}struct Seeded { h: Harness, secret: String, thread_id: String, photo_a: String, photo_b: String,}fn seeded() -> Seeded { let mut h = Harness::new(); let ws = h.workspace_id.clone(); let thread_id = synthetic_uuid("thread"); run( &h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, last_message_at, created_at, updated_at) VALUES (?, ?, 'group', 'Kitchen rebuild', ?, ?, ?)", vec![t(&thread_id), t(&ws), t(AT), t(AT), t(AT)], ); let message_id = synthetic_uuid("message"); let media = json!([{ "key": format!("{ws}/messages/{thread_id}/{SHA_A}.jpg"), "contentType": "image/jpeg", "sizeBytes": 240_000, "kind": "image", }]) .to_string(); run( &h, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, external_id, sent_at, created_at, reactions, meta) VALUES (?, ?, ?, 'in', 'whatsapp', 'imported', NULL, ?, ?, ?, ?, '[]', '{}')", vec![ t(&message_id), t(&thread_id), t(&ws), t(&media), t(&format!("txt2:{}", synthetic_uuid("fingerprint"))), t(AT), t(AT), ], ); let photo_a = insert_photo( &h, NewPhoto { thread_id: Some(thread_id.clone()), source_id: Some(message_id.clone()), summary: Some("A screenshot of a boarding pass, Bengaluru to Delhi, dated 2024."), ..NewPhoto::new( SHA_A, format!("{ws}/messages/{thread_id}/{SHA_A}.jpg"), "2026-08-30T10:00:00.000Z", ) }, ); let photo_b = insert_photo( &h, NewPhoto { caption: Some("the finished shelf"), size_bytes: 900_000, ..NewPhoto::new( SHA_B, format!("{ws}/photos/{SHA_B}.jpg"), "2026-08-31T10:00:00.000Z", ) }, ); let secret = mint_token(&mut h, &["read", "write"], "Claude"); Seeded { h, secret, thread_id, photo_a, photo_b, }}// ── list_photos ─────────────────────────────────────────────────────────────#[test]fn answers_newest_first_with_the_caption_and_the_description() { let s = seeded(); let answer = call_tool(&s.h, &s.secret, "list_photos", json!({})); assert_eq!( ids(&answer, "photos"), vec![s.photo_b.clone(), s.photo_a.clone()] ); assert_eq!(answer["photos"][0]["caption"], json!("the finished shelf")); assert_eq!(answer["photos"][0]["description"], Value::Null); assert!(answer["photos"][1]["description"] .as_str() .expect("a description") .contains("boarding pass"));}#[test]fn filters_by_chat_by_period_by_flagged_and_by_described() { let s = seeded(); let in_chat = call_tool( &s.h, &s.secret, "list_photos", json!({ "thread": s.thread_id }), ); assert_eq!(ids(&in_chat, "photos"), vec![s.photo_a.clone()]); let since = call_tool( &s.h, &s.secret, "list_photos", json!({ "since": "2026-08-31T00:00:00.000Z" }), ); assert_eq!(ids(&since, "photos"), vec![s.photo_b.clone()]); let until = call_tool( &s.h, &s.secret, "list_photos", json!({ "until": "2026-08-30T23:00:00.000Z" }), ); assert_eq!(ids(&until, "photos"), vec![s.photo_a.clone()]); // Asked in BOTH directions: "what has been flagged" is the storage screen's // list, and "what has nothing said about it" is the describe queue. let undescribed = call_tool( &s.h, &s.secret, "list_photos", json!({ "described": false }), ); assert_eq!(ids(&undescribed, "photos"), vec![s.photo_b.clone()]); let flagged = call_tool(&s.h, &s.secret, "list_photos", json!({ "reviewed": true })); assert_eq!(flagged["photos"], json!([]));}#[test]fn filters_by_person_anybody_screenshots_favourite_place_and_label() { let s = seeded(); let person = insert_person(&s.h, "Test Person"); insert_face(&s.h, &s.photo_a, "F1", Some(&person), 0.3); insert_face(&s.h, &s.photo_a, "F2", None, 0.3); run( &s.h, "UPDATE cotton_photos SET subtypes = ?, favourite = 1, place_city = 'Testville', labels = ? WHERE id = ?", vec![ t(&json!(["screenshot"]).to_string()), t(&json!(["whiteboard"]).to_string()), t(&s.photo_b), ], ); for (args, expected) in [ (json!({ "person": person }), vec![s.photo_a.clone()]), (json!({ "withPeople": true }), vec![s.photo_a.clone()]), (json!({ "withPeople": false }), vec![s.photo_b.clone()]), (json!({ "screenshots": true }), vec![s.photo_b.clone()]), (json!({ "favourite": true }), vec![s.photo_b.clone()]), (json!({ "place": "testville" }), vec![s.photo_b.clone()]), (json!({ "label": "whiteboard" }), vec![s.photo_b.clone()]), (json!({ "label": "white" }), vec![]), ] { let answer = call_tool(&s.h, &s.secret, "list_photos", args.clone()); assert_eq!(ids(&answer, "photos"), expected, "for {args}"); } // The row summary names the people, the place, the subtypes. let all = call_tool(&s.h, &s.secret, "list_photos", json!({})); let rows = all["photos"].as_array().expect("a list"); let a = rows .iter() .find(|row| row["id"] == json!(s.photo_a)) .expect("photo A"); assert_eq!(a["people"], json!(["Test Person"])); assert_eq!(a["favourite"], json!(false)); let b = rows .iter() .find(|row| row["id"] == json!(s.photo_b)) .expect("photo B"); assert_eq!(b["people"], json!([])); assert_eq!(b["favourite"], json!(true)); assert_eq!(b["place"], json!("Testville")); assert_eq!(b["subtypes"], json!(["screenshot"]));}#[test]fn refuses_an_id_that_is_not_a_photos() { let s = seeded(); let refused = call_tool_raw( &s.h, &s.secret, "get_photo", json!({ "id": s.photo_a.replace("photo:", "video:") }), ); assert!(refused.is_error); assert!(refused.text.contains("photo:"), "{}", refused.text);}// ── get_photo ───────────────────────────────────────────────────────────────#[test]fn answers_every_place_a_picture_was_seen() { let s = seeded(); let ws = s.h.workspace_id.clone(); // The same picture, later added from the library too: two sightings, one // record, and the tool answers both — the whole history, not the first // chapter. insert_sighting( &s.h, &s.photo_a, "apple_library", Some("ASSET-1"), None, &format!("{ws}/photos/{SHA_A}.jpg"), "2026-08-31T00:00:00.000Z", ); let answer = call_tool(&s.h, &s.secret, "get_photo", json!({ "id": s.photo_a })); assert_eq!(answer["id"], json!(s.photo_a)); assert_eq!(answer["projects"], json!([])); assert!(answer.get("from").is_none()); let sightings = answer["sightings"].as_array().expect("sightings"); assert_eq!(sightings.len(), 2); assert_eq!(sightings[0]["source"], json!("message")); assert_eq!(sightings[0]["threadId"], json!(s.thread_id)); assert_eq!(sightings[0]["name"], json!("Kitchen rebuild")); assert!(sightings[0]["messageId"] .as_str() .is_some_and(|id| !id.is_empty())); assert_eq!(sightings[1]["source"], json!("apple_library")); assert_eq!(sightings[1]["assetId"], json!("ASSET-1"));}#[test]fn answers_the_faces_the_location_the_place_and_the_camera() { let s = seeded(); let person = insert_person(&s.h, "Test Person"); insert_face(&s.h, &s.photo_b, "F1", Some(&person), 0.1); insert_face(&s.h, &s.photo_b, "F2", None, 0.6); run( &s.h, "UPDATE cotton_photos SET latitude = 12.5, longitude = 77.5, place_city = 'Testville', place_country = 'Testland', camera_make = 'Acme', camera_model = 'Snap 3', orientation = 6, taken_offset = 19800, labels = ?, original_filename = 'IMG_0001.HEIC', aesthetic_score = 0.4 WHERE id = ?", vec![t(&json!(["whiteboard"]).to_string()), t(&s.photo_b)], ); let answer = call_tool(&s.h, &s.secret, "get_photo", json!({ "id": s.photo_b })); assert_eq!( answer["location"], json!({ "latitude": 12.5, "longitude": 77.5 }) ); assert_eq!( answer["place"], json!({ "name": null, "city": "Testville", "region": null, "country": "Testland" }) ); assert_eq!( answer["camera"], json!({ "make": "Acme", "model": "Snap 3" }) ); assert_eq!(answer["orientation"], json!(6)); assert_eq!(answer["takenOffset"], json!(19800)); assert_eq!(answer["labels"], json!(["whiteboard"])); assert_eq!(answer["originalFilename"], json!("IMG_0001.HEIC")); assert_eq!( answer["scores"], json!({ "aesthetic": 0.4, "curation": null }) ); assert_eq!(answer["people"], json!(["Test Person"])); let faces = answer["faces"].as_array().expect("faces"); assert_eq!(faces.len(), 2); assert_eq!( faces[0]["box"], json!({ "x": 0.1, "y": 0.1, "width": 0.2, "height": 0.2 }) ); assert_eq!(faces[0]["quality"], json!(0.7)); assert_eq!( faces[0]["person"], json!({ "id": person, "name": "Test Person" }) ); assert_eq!(faces[1]["person"], Value::Null);}#[test]fn answers_nulls_not_omissions_for_a_picture_that_knows_nothing() { let s = seeded(); let answer = call_tool(&s.h, &s.secret, "get_photo", json!({ "id": s.photo_b })); assert_eq!(answer["location"], Value::Null); assert_eq!(answer["place"], Value::Null); assert_eq!(answer["camera"], Value::Null); assert_eq!(answer["scores"], Value::Null); assert_eq!(answer["faces"], json!([])); assert_eq!(answer["subtypes"], json!([])); assert_eq!(answer["labels"], json!([])); assert_eq!(answer["favourite"], json!(false)); assert_eq!( answer["sightings"] .as_array() .expect("sightings") .iter() .map(|row| row["source"].clone()) .collect::<Vec<_>>(), vec![json!("library")] );}// ── update_photo ────────────────────────────────────────────────────────────#[test]fn sets_a_caption_and_clears_it_with_null() { let s = seeded(); call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "caption": "the old boarding pass" }), ); assert_eq!( as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "caption"), Some("the old boarding pass".to_string()) ); call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "caption": null }), ); assert_eq!( as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "caption"), None );}#[test]fn stamps_a_review_note_with_the_assistants_own_name_and_clears_all_three() { let s = seeded(); let noted = call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "reviewNote": "a screenshot of a 2024 boarding pass, probably done with", }), ); assert_eq!(noted["reviewBy"], json!("Claude")); let row = photo_row(&s.h, &s.photo_a).expect("the row"); assert!(as_text(&row, "review_note") .expect("a note") .contains("boarding pass")); assert_eq!(as_text(&row, "review_by"), Some("Claude".to_string())); assert!(as_text(&row, "review_at").is_some()); // "Keep": the note, its author and its moment go together — a byline over a // cleared note is a suggestion nobody made. call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "reviewNote": null }), ); let cleared = photo_row(&s.h, &s.photo_a).expect("the row"); assert_eq!(as_text(&cleared, "review_note"), None); assert_eq!(as_text(&cleared, "review_by"), None); assert_eq!(as_text(&cleared, "review_at"), None);}#[test]fn normalises_a_caption_the_one_way_core_does_never_raw() { // The app's editor and this tool are two spellings of the same field. Two // normalisations would eventually store a trailing newline on one path and // not the other, and the same picture would compare unequal to itself. let s = seeded(); let answer = call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "caption": " the whiteboard\n after pricing " }), ); assert_eq!(answer["caption"], json!("the whiteboard after pricing")); assert_eq!( as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "caption"), Some("the whiteboard after pricing".to_string()) );}#[test]fn reads_a_note_of_nothing_but_spaces_as_keep() { let s = seeded(); call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "reviewNote": "worth a look" }), ); call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "reviewNote": " " }), ); let row = photo_row(&s.h, &s.photo_a).expect("the row"); assert_eq!(as_text(&row, "review_note"), None); assert_eq!(as_text(&row, "review_by"), None); assert_eq!(as_text(&row, "review_at"), None);}#[test]fn refuses_a_whitespace_only_note_in_words_when_one_reaches_the_handler() { // Called directly: the validator turns a blank string into `null` (Keep), // so no route reaches this. The refusal is the floor under it — the column // CHECK refuses a whitespace-only note, and writing it raw handed the // assistant a SQLite constraint message about a column it has never heard // of. let s = seeded(); let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; let scopes = vec!["read".to_string(), "write".to_string()]; let now = cotton_tools::clock::Clock::now(&s.h.clock); let refusal = s.h.with(|db| { let mut ctx = Ctx::new( db, &s.h.file, &s.h.owner_id, "Claude", "token", &scopes, now, Arc::clone(&s.h.random), Some(cotton_tools::mcp::writer::job("test")), &services, &audit, ); update_media( &mut ctx, PHOTO_SPEC, &UpdateMediaArgs { id: s.photo_a.clone(), caption: Clearable::Unchanged, review_note: Clearable::Set(" ".to_string()), description: Clearable::Unchanged, favourite: None, }, ) .err() .map(|failure| failure.message().to_string()) }) .expect("a refusal"); assert!(refusal.contains("has to say something"), "{refusal}");}#[test]fn stores_a_review_note_trimmed_the_one_way() { let s = seeded(); call_tool( &s.h, &s.secret, "update_photo", json!({ "id": s.photo_a, "reviewNote": " probably\n done with " }), ); assert_eq!( as_text( &photo_row(&s.h, &s.photo_a).expect("the row"), "review_note" ), Some("probably done with".to_string()) );}#[test]fn refuses_a_call_that_changes_nothing() { let s = seeded(); let refused = call_tool_raw(&s.h, &s.secret, "update_photo", json!({ "id": s.photo_a })); assert!(refused.is_error); assert!( refused.text.contains("nothing to change"), "{}", refused.text );}// ── remove_photo ────────────────────────────────────────────────────────────/// Every key waiting in this file's unlink queue.fn queued(h: &Harness) -> Vec<String> { h.with(cotton_store::media_erasure::pending_unlinks) .expect("the queue reads") .into_iter() .map(|pending| pending.key) .collect()}/// Whether `key` is dead here: an erasure names it and no row does.fn dead(h: &Harness, key: &str) -> bool { h.with(|db| cotton_store::media_erasure::is_dead(db, key)) .expect("the rule reads")}/// Erase one binned picture for good, as the owner's bin does — the only act/// that removes a picture (architect, 5 Oct 2026: the bin, one rule).fn erase_from_bin(h: &Harness, id: &str) { let answer = call_tool_as_owner(h, "device:phone", "delete_record", json!({ "table": "bin", "id": id })); assert!(!answer.is_error, "the bin refused to erase {id}: {}", answer.text);}/// Whether an erasure fact names `key` (one per record that named it: the/// picture and each sighting).fn erased(h: &Harness, key: &str) -> bool { h.count( "SELECT COUNT(*) AS n FROM cotton_media_erasures WHERE key = ?", &[t(key)], ) > 0}/// RULE: remove_photo moves the picture to the bin and touches no bytes; only the bin's erase writes an erasure fact for its key, which is then dead and queued for each device's unlink pass, and the object is still in the store when the erase answers.#[test]fn removes_the_row_and_queues_its_bytes_without_touching_them() { let s = seeded(); let key = as_text(&photo_row(&s.h, &s.photo_b).expect("the row"), "key").expect("a key"); s.h.services.media.put(&key, vec![1u8, 2, 3]); let answer = call_tool(&s.h, &s.secret, "remove_photo", json!({ "id": s.photo_b })); assert_eq!(answer["removed"], json!(true)); assert_eq!(answer["trashed"], json!(true)); assert_eq!(answer["bytesRemoved"], json!(false), "a picture in the bin keeps its bytes"); let binned = photo_row(&s.h, &s.photo_b).expect("a removed photo waits in the bin"); assert!(as_text(&binned, "trashed_at").is_some()); assert!(!erased(&s.h, &key) && queued(&s.h).is_empty(), "a binned picture's key was erased"); erase_from_bin(&s.h, &s.photo_b); assert!(photo_row(&s.h, &s.photo_b).is_none()); assert!(erased(&s.h, &key)); assert!(dead(&s.h, &key)); assert_eq!(queued(&s.h), vec![key.clone()]); assert!(s.h.services.media.has(&key), "the tool deleted bytes itself");}/// RULE: The bin's erase of a removed photo erases every key its sightings name, and the keys no chat message names are dead and queued, while the picture's own key a chat still names stays alive and unqueued, and the answer counts the chats.#[test]fn erases_every_key_the_row_names_and_keeps_what_a_chat_names() { // The same picture in three chats is one row and three keys: a message // media key is scoped to its thread, so the bytes were copied under each. let s = seeded(); let ws = s.h.workspace_id.clone(); let key = as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "key").expect("a key"); let forwarded: Vec<String> = ["th-2", "th-3"] .iter() .map(|thread| format!("{ws}/messages/{thread}/{SHA_A}.jpg")) .collect(); for (index, forwarded_key) in forwarded.iter().enumerate() { insert_sighting( &s.h, &s.photo_a, "message", Some(&format!("msg-{index}")), Some(&format!("th-{}", index + 2)), forwarded_key, AT, ); } insert_face(&s.h, &s.photo_a, "F1", None, 0.3); for object in std::iter::once(&key).chain(forwarded.iter()) { s.h.services.media.put(object, vec![1u8, 2, 3]); } let answer = call_tool(&s.h, &s.secret, "remove_photo", json!({ "id": s.photo_a })); assert_eq!(answer["removed"], json!(true)); assert_eq!(answer["alsoInChats"], json!(3)); assert_eq!(answer["bytesRemoved"], json!(false), "a picture in the bin keeps its bytes"); erase_from_bin(&s.h, &s.photo_a); for object in &forwarded { assert!(erased(&s.h, object), "{object} has no erasure fact"); assert!(dead(&s.h, object), "{object} is not dead"); } assert!(!dead(&s.h, &key), "the key the seeded message names died"); let mut want = forwarded.clone(); want.sort(); let mut got = queued(&s.h); got.sort(); assert_eq!(got, want); for object in std::iter::once(&key).chain(forwarded.iter()) { assert!(s.h.services.media.has(object), "{object} was deleted by the tool"); } // …and the children go with the row, in the one erase every phone folds. let sightings = one( &s.h, "SELECT COUNT(*) AS n FROM cotton_media_sightings WHERE record_id = ?", vec![t(&s.photo_a)], ) .expect("a count"); assert_eq!(column(&sightings, "n"), rusqlite::types::Value::Integer(0)); let faces = one( &s.h, "SELECT COUNT(*) AS n FROM cotton_media_faces WHERE record_id = ?", vec![t(&s.photo_a)], ) .expect("a count"); assert_eq!(column(&faces, "n"), rusqlite::types::Value::Integer(0)); // The removal travels as ONE erase of the picture (slice 5a-ii): its // children leave in its fold, each kept in `_gone`, not as deletes of their own. let ops = one( &s.h, "SELECT COUNT(*) AS n FROM _gone WHERE tbl = 'cotton_media_sightings'", vec![], ) .expect("a count"); assert!(matches!(column(&ops, "n"), rusqlite::types::Value::Integer(count) if count > 0));}/// RULE: A removed photo's faces and sightings wait in the bin with it; the bin's erase takes them with the picture, and the store keeps it gone so no later write recreates it.#[test]fn remove_photo_takes_its_faces_and_sightings_and_is_not_recreated() { let s = seeded(); insert_face(&s.h, &s.photo_a, "F1", None, 0.3); let face_id = format!("face:{}:F1", s.photo_a); let count_of = |sql: &str, id: &str| { column(&one(&s.h, sql, vec![t(id)]).expect("a count"), "n") }; let zero = rusqlite::types::Value::Integer(0); assert_ne!( count_of("SELECT COUNT(*) AS n FROM cotton_media_sightings WHERE record_id = ?", &s.photo_a), zero, "the seeded photo has a sighting" ); let answer = call_tool(&s.h, &s.secret, "remove_photo", json!({ "id": s.photo_a })); assert_eq!(answer["removed"], json!(true)); assert_eq!( count_of("SELECT COUNT(*) AS n FROM cotton_media_faces WHERE id = ?", &face_id), rusqlite::types::Value::Integer(1), "a binned picture's face left before the bin was emptied" ); erase_from_bin(&s.h, &s.photo_a); assert!(photo_row(&s.h, &s.photo_a).is_none()); assert_eq!( count_of("SELECT COUNT(*) AS n FROM cotton_media_faces WHERE id = ?", &face_id), zero ); assert_eq!( count_of("SELECT COUNT(*) AS n FROM cotton_media_sightings WHERE record_id = ?", &s.photo_a), zero ); assert!(s .h .with(|db| cotton_store::erase::is_gone(db, "cotton_photos", &s.photo_a)) .expect("_gone reads"));}/// RULE: remove_photo never deletes chat copies: the answer says the picture is also in that one chat, and after the bin's erase the chat message keeps naming the key, which stays alive with its bytes and nothing queued.#[test]fn a_chat_copy_stays_and_the_answer_says_in_how_many_chats() { let s = seeded(); let key = as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "key").expect("a key"); s.h.services.media.put(&key, vec![1u8, 2, 3]); let answer = call_tool(&s.h, &s.secret, "remove_photo", json!({ "id": s.photo_a })); assert_eq!(answer["alsoInChats"], json!(1)); assert!(answer["note"].as_str().expect("a note").contains("also in 1 chat"), "{answer}"); erase_from_bin(&s.h, &s.photo_a); assert!(erased(&s.h, &key), "the picture's erase names its key"); assert!(!dead(&s.h, &key), "a key the chat message names died"); assert!(queued(&s.h).is_empty(), "a key the chat names was queued"); assert!(s.h.services.media.has(&key)); assert_eq!( s.h.count( "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = ?", &[t(&s.thread_id)], ), 1, "the chat lost its message" );}/// The seed op of a write a peer device made: `upsert` or `delete`.fn peer_op(n: u64, kind: &str, table: &str, row_id: &str, patch: Value) -> Value { json!({ "opId": format!("01KPEER{n:019}"), "deviceId": "device:peer", "kind": kind, "table": table, "rowId": row_id, "patch": patch, "hlc": format!("1700000000{n:03}:0000:device:peer"), "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION, })}/// RULE: A key an erased photo shared with a chat message that is only dormant (retracted) survives the bin's erase — not dead, not queued, bytes kept — and when the message comes back (the undo of its retract) its picture is still there.#[test]fn key_named_only_by_a_dormant_row_survives_an_erasure_and_returns_with_undo() { const SHA_C: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; let s = seeded(); let ws = s.h.workspace_id.clone(); let key = format!("{ws}/messages/{}/{SHA_C}.jpg", s.thread_id); let photo = insert_photo(&s.h, NewPhoto::new(SHA_C, key.clone(), AT)); s.h.services.media.put(&key, vec![7u8, 8, 9]); let message = synthetic_uuid("dormant-message"); let created = json!({ "id": message, "thread_id": s.thread_id, "workspace_id": ws, "direction": "in", "channel": "whatsapp", "origin": "imported", "sent_at": AT, "created_at": AT, "reactions": [], "meta": {}, "media": [{ "key": key, "contentType": "image/jpeg", "sizeBytes": 3, "kind": "image" }], }); s.h.seed(&[peer_op(1, "upsert", "cotton_msg_messages", &message, created.clone())]); s.h.seed(&[peer_op(2, "delete", "cotton_msg_messages", &message, Value::Null)]); assert_eq!( s.h.count("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id = ?", &[t(&message)]), 0, "the premise: the message is dormant" ); call_tool(&s.h, &s.secret, "remove_photo", json!({ "id": photo })); erase_from_bin(&s.h, &photo); assert!(erased(&s.h, &key), "the photo's erase names the key"); assert!(!dead(&s.h, &key), "a key a dormant message names died"); assert!(queued(&s.h).is_empty(), "a key a dormant message names was queued"); // The undo of a retract is a create of the same row above it. s.h.seed(&[peer_op(3, "upsert", "cotton_msg_messages", &message, created)]); assert_eq!( s.h.count("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id = ?", &[t(&message)]), 1, "the message did not come back" ); assert!(!dead(&s.h, &key)); assert!(queued(&s.h).is_empty()); assert_eq!(s.h.services.media.get(&key), Some(vec![7u8, 8, 9]), "the restored message has no bytes");}#[test]fn refuses_an_id_this_database_does_not_hold() { let s = seeded(); let refused = call_tool_raw( &s.h, &s.secret, "remove_photo", json!({ "id": format!("photo:{}", "c".repeat(64)) }), ); assert!(refused.is_error); assert!( refused.text.contains("no photo with id"), "{}", refused.text );}// ── get_photo_bytes ─────────────────────────────────────────────────────────#[test]fn answers_with_an_image_block_a_client_can_render() { let s = seeded(); let key = as_text(&photo_row(&s.h, &s.photo_a).expect("the row"), "key").expect("a key"); s.h.services.media.put(&key, vec![137u8, 80, 78, 71]); let answer = call_tool_result( &s.h, &s.secret, "get_photo_bytes", json!({ "id": s.photo_a }), ); let content = &answer["content"]; assert_eq!(content[0]["type"], json!("image")); assert_eq!(content[0]["mimeType"], json!("image/jpeg")); assert_eq!( content[0]["data"], json!(base64_standard(&[137u8, 80, 78, 71])) ); let facts: Value = serde_json::from_str(content[1]["text"].as_str().expect("text")) .expect("the facts are JSON"); assert_eq!(facts["id"], json!(s.photo_a)); assert_eq!(facts["byteSize"], json!(4));}fn base64_standard(bytes: &[u8]) -> String { use base64::engine::general_purpose::STANDARD; use base64::Engine; STANDARD.encode(bytes)}#[test]fn refuses_a_picture_over_the_tools_byte_cap_before_pulling_it() { let s = seeded(); let ws = s.h.workspace_id.clone(); let sha = "d".repeat(64); let big = insert_photo( &s.h, NewPhoto { size_bytes: 8 * 1024 * 1024, ..NewPhoto::new(&sha, format!("{ws}/photos/{sha}.jpg"), AT) }, ); let refused = call_tool_raw(&s.h, &s.secret, "get_photo_bytes", json!({ "id": big })); assert!(refused.is_error); assert!( refused.text.contains("limit for carrying bytes"), "{}", refused.text );}#[test]fn says_the_bytes_have_not_arrived_yet_rather_than_failing_obscurely() { let s = seeded(); let refused = call_tool_raw( &s.h, &s.secret, "get_photo_bytes", json!({ "id": s.photo_a }), ); assert!(refused.is_error); assert!( refused.text.contains("not reached the server yet"), "{}", refused.text );}// ── the video tools ─────────────────────────────────────────────────────────struct SeededVideo { h: Harness, secret: String, video_id: String, key: String, poster_key: String,}/// A video, its chat and its sighting.////// One store throughout: the fake on `ToolServices` both holds bytes and signs/// for them, so a suite asserting a download link needs no second one — which/// is the divergence the server's copy of this file carried and this one does/// not.fn seeded_video(poster: bool) -> SeededVideo { let mut h = Harness::new(); let ws = h.workspace_id.clone(); let thread_id = synthetic_uuid("video-thread"); run( &h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, last_message_at, created_at, updated_at) VALUES (?, ?, 'dm', 'Wrenna', ?, ?, ?)", vec![t(&thread_id), t(&ws), t(AT), t(AT), t(AT)], ); let key = format!("{ws}/messages/{thread_id}/{SHA_VIDEO}.mp4"); let poster_key = format!("{ws}/videos/{SHA_VIDEO}.poster.jpg"); let id = format!("video:{SHA_VIDEO}"); run( &h, "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, width, height, duration_ms, taken_at, preview, poster_key, caption, summary, summary_by, summary_at, review_note, review_by, review_at, created_at, updated_at) VALUES (?, ?, ?, ?, 'video/mp4', 48000000, 1920, 1080, 42000, ?, NULL, ?, NULL, 'A hand-held clip of a kitchen under construction.', 'job:media-describe', ?, NULL, NULL, NULL, ?, ?)", vec![ t(&id), t(&ws), t(&key), t(SHA_VIDEO), t("2026-08-30T10:00:00.000Z"), if poster { t(&poster_key) } else { SqlValue::Null }, t(AT), t(AT), t(AT), ], ); let message_id = synthetic_uuid("video-message"); run( &h, "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, source_id, thread_id, key, seen_at, created_at, updated_at) VALUES (?, ?, 'video', ?, 'message', ?, ?, ?, ?, ?, ?)", vec![ t(&media_sighting_id( "video", &id, "message", Some(&message_id), )), t(&ws), t(&id), t(&message_id), t(&thread_id), t(&key), t("2026-08-30T10:00:00.000Z"), t(AT), t(AT), ], ); let secret = mint_token(&mut h, &["read", "write"], "Claude"); SeededVideo { h, secret, video_id: id, key, poster_key, }}fn put_object(h: &Harness, key: &str, bytes: &[u8]) { h.services.media.put(key, bytes.to_vec());}fn has_object(h: &Harness, key: &str) -> bool { h.services.media.has(key)}#[test]fn carries_how_long_each_video_runs() { let s = seeded_video(true); let answer = call_tool(&s.h, &s.secret, "list_videos", json!({})); assert_eq!(answer["videos"].as_array().expect("a list").len(), 1); assert_eq!(answer["videos"][0]["id"], json!(s.video_id)); assert_eq!(answer["videos"][0]["durationMs"], json!(42000)); assert_eq!(answer["videos"][0]["sizeBytes"], json!(48000000i64));}#[test]fn refuses_a_photos_id_on_a_video_tool() { let s = seeded_video(true); let refused = call_tool_raw( &s.h, &s.secret, "get_video", json!({ "id": format!("photo:{SHA_VIDEO}") }), ); assert!(refused.is_error); assert!(refused.text.contains("video:"), "{}", refused.text);}#[test]fn mints_a_five_minute_download_link_and_returns_the_still_frame() { let s = seeded_video(true); put_object(&s.h, &s.key, &[0u8, 1]); put_object(&s.h, &s.poster_key, &[255u8, 216]); let answer = call_tool_result(&s.h, &s.secret, "get_video", json!({ "id": s.video_id })); let content = &answer["content"]; assert_eq!(content[0]["type"], json!("image")); assert_eq!(content[0]["mimeType"], json!("image/jpeg")); let facts: Value = serde_json::from_str(content[1]["text"].as_str().expect("text")) .expect("the facts are JSON"); assert_eq!(facts["id"], json!(s.video_id)); assert!(facts["fileUrl"].is_string(), "{facts}"); assert!(facts["fileExpiresAt"].is_string(), "{facts}"); assert_eq!(facts["sightings"][0]["name"], json!("Wrenna"));}#[test]fn answers_everything_else_when_no_still_frame_has_been_made_yet() { // `poster_key` is the PHONE's column: only a device holding the bytes can // encode a frame. A server that invented one would be the second writer. let s = seeded_video(false); put_object(&s.h, &s.key, &[0u8, 1]); let answer = call_tool(&s.h, &s.secret, "get_video", json!({ "id": s.video_id })); assert_eq!(answer["id"], json!(s.video_id)); assert!(answer["fileUrl"].is_string(), "{answer}");}#[test]fn says_why_there_is_no_link_when_the_recording_has_not_been_uploaded() { let s = seeded_video(false); let answer = call_tool(&s.h, &s.secret, "get_video", json!({ "id": s.video_id })); assert_eq!(answer["fileUrl"], Value::Null); assert!( answer["fileUrlNote"] .as_str() .expect("a note") .contains("not reached the server yet"), "{answer}" );}#[test]fn sets_and_clears_a_caption_and_a_review_note_on_a_video() { let s = seeded_video(true); call_tool( &s.h, &s.secret, "update_video", json!({ "id": s.video_id, "caption": "the walkthrough clip" }), ); assert_eq!( as_text(&video_row(&s.h, &s.video_id).expect("the row"), "caption"), Some("the walkthrough clip".to_string()) ); call_tool( &s.h, &s.secret, "update_video", json!({ "id": s.video_id, "reviewNote": "48 MB of a wall — probably done with" }), ); let noted = video_row(&s.h, &s.video_id).expect("the row"); assert_eq!(as_text(¬ed, "review_by"), Some("Claude".to_string())); assert!(as_text(¬ed, "review_at").is_some()); call_tool( &s.h, &s.secret, "update_video", json!({ "id": s.video_id, "reviewNote": null, "caption": null }), ); let cleared = video_row(&s.h, &s.video_id).expect("the row"); assert_eq!(as_text(&cleared, "caption"), None); assert_eq!(as_text(&cleared, "review_note"), None); assert_eq!(as_text(&cleared, "review_by"), None);}/// RULE: remove_video moves the film to the bin with its recording and still frame; only the bin's erase removes the row, leaving both keys dead and queued with their bytes untouched by the tool.#[test]fn removes_the_row_and_queues_the_recording_and_its_still_frame() { let s = seeded_video(true); put_object(&s.h, &s.key, &[0u8, 1]); put_object(&s.h, &s.poster_key, &[255u8, 216]); let answer = call_tool(&s.h, &s.secret, "remove_video", json!({ "id": s.video_id })); assert_eq!(answer["removed"], json!(true)); assert_eq!(answer["bytesRemoved"], json!(false), "a film in the bin keeps its bytes"); assert!(video_row(&s.h, &s.video_id).is_some_and(|row| as_text(&row, "trashed_at").is_some())); assert!(queued(&s.h).is_empty(), "a binned film's keys were queued"); erase_from_bin(&s.h, &s.video_id); assert!(video_row(&s.h, &s.video_id).is_none()); // No bytes touched by the tool: both keys are dead and queued for each // device's unlink pass. for key in [&s.key, &s.poster_key] { assert!(has_object(&s.h, key), "{key} was deleted by the tool"); assert!(dead(&s.h, key), "{key} is not dead"); } let mut got = queued(&s.h); got.sort(); let mut want = vec![s.key.clone(), s.poster_key.clone()]; want.sort(); assert_eq!(got, want);}#[test]fn takes_one_named_id_and_nothing_else_there_is_no_batch_form() { let s = seeded_video(true); // `additionalProperties: false` on the schema, and the validator reads only // `id`: a sweep is not expressible, on purpose. let answer = call_tool_raw( &s.h, &s.secret, "remove_video", json!({ "id": s.video_id, "thread": "everything" }), ); assert!(!answer.is_error, "{}", answer.text); assert!(video_row(&s.h, &s.video_id).is_some_and(|row| as_text(&row, "trashed_at").is_some()));}