//! `storage_summary` — what is taking up the owner's space, and what has been //! flagged for them to look at. //! //! Four rules this read keeps: //! //! IT DELETES NOTHING, AND IT SUGGESTS NOTHING BY ITSELF. It answers what is //! there. The deciding is the owner's, one named id at a time through //! `remove_photo` / `remove_video`, which is why this file has no write in it. //! //! EVERY FIGURE COMES FROM THE OWNER'S OWN DATABASE. No object listing, no //! `head` per row. Where the database never learned a size, the item is //! COUNTED and its bytes are not guessed at; `unmeasured` says how many, so a //! total that looks low is explicable rather than mysterious. //! //! PHOTOS AND VIDEOS ARE READ FROM THEIR OWN TABLES, not from the messages //! they came from — the same picture forwarded four times is one row, and //! reading the messages instead would count one file's bytes four times. //! //! …BUT ONE ROW IS NOT ALWAYS ONE OBJECT. A message media key is scoped to //! its THREAD, so a picture forwarded into four chats really did have its //! bytes copied four times, under four keys. This read is about SPACE, so a //! photo counts `size_bytes × (distinct keys)` and the `note` says so. //! //! The TypeScript refuses on a `Ctx` with no driver; this server has no such //! state — `ctx.db()` is the workspace's own file — so that refusal has no //! Rust counterpart. Three aggregates and a walk over the chat attachments' //! JSON (`json_each`) is exactly the shape design S2 says drops to SQL. use std::collections::{BTreeMap, BTreeSet}; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult}; use crate::mcp::handlers::common::put; use crate::mcp::protocol::ToolFailure; pub fn handlers() -> HandlerGroup { &[ ("storage_summary", storage_summary), ("backup_now", backup_now), ("media_repair", super::media_repair::media_repair), ] } /// `backup_now` — the serving server's copy of every database and its media /// folder to the backup disk, now (`cotton_server::daily_copies::backup_now`). fn backup_now(ctx: &mut Ctx<'_>, _args: &Map) -> ToolResult { let rail = ctx .services .backup_now .as_ref() .ok_or_else(|| ToolFailure::new("backup_now runs on the serving Mac's server only"))?; rail().map_err(ToolFailure::new) } /// How many chats the by-chat list names, biggest first. const TOP_CHATS: usize = 30; /// How many single items the largest list names. const LARGEST_ITEMS: usize = 50; /// Enough of a caption or description to recognise an item by. const SNIPPET_MAX: usize = 120; #[derive(Debug, Clone)] struct SizedRow { id: String, /// What the bucket holds for this item — the object's size times how many /// objects it lives in (a forwarded picture is one row and several copies). bytes: i64, text: Option, thread_id: Option, /// Objects behind this row beyond the first. Zero for everything that is /// not a photo or a video. copies: i64, } fn snippet(value: Option<&str>) -> Value { let Some(value) = value else { return Value::Null; }; let line = value.split_whitespace().collect::>().join(" "); if line.is_empty() { return Value::Null; } if line.chars().count() > SNIPPET_MAX { let head: String = line.chars().take(SNIPPET_MAX - 1).collect(); Value::from(format!("{head}…")) } else { Value::from(line) } } fn refuse(error: impl std::fmt::Display) -> ToolFailure { ToolFailure::new(error.to_string()) } pub fn storage_summary(ctx: &mut Ctx<'_>, _args: &Map) -> ToolResult { let driver = ctx.db(); let workspace = SqlValue::Text(ctx.workspace_id.to_string()); // Every DISTINCT object one row owns: its own key and every key its // sightings point at (v39). One row, N objects: the bytes are identical, // which is exactly why the row is one — and exactly why the SPACE is not. let mut keys_by_record: BTreeMap> = BTreeMap::new(); let mut chat_by_record: BTreeMap = BTreeMap::new(); for sighting in driver .all( "SELECT record_id, key, thread_id, seen_at FROM cotton_media_sightings WHERE workspace_id = ? ORDER BY seen_at ASC, id ASC", std::slice::from_ref(&workspace), ) .map_err(refuse)? { let (Some(record_id), Some(key)) = (sighting.text("record_id"), sighting.text("key")) else { continue; }; keys_by_record .entry(record_id.to_string()) .or_default() .insert(key.to_string()); // The FIRST chat a picture was seen in is the one its bytes are charged // to — one chat per row, so the by-chat list adds up to the total. if let Some(thread_id) = sighting.text("thread_id") { chat_by_record .entry(record_id.to_string()) .or_insert_with(|| thread_id.to_string()); } } let media = |table: &str| -> Result, ToolFailure> { let rows = driver .all( &format!( "SELECT id, key, size_bytes, caption, summary FROM {table} WHERE \ workspace_id = ?" ), std::slice::from_ref(&workspace), ) .map_err(refuse)?; Ok(rows .into_iter() .map(|row| { let id = row.text("id").unwrap_or_default().to_string(); let mut keys: BTreeSet = BTreeSet::new(); if let Some(key) = row.text("key") { keys.insert(key.to_string()); } if let Some(seen) = keys_by_record.get(&id) { keys.extend(seen.iter().cloned()); } let copies = keys.len().saturating_sub(1) as i64; SizedRow { bytes: row.int("size_bytes").unwrap_or(0) * (1 + copies), text: row .text("caption") .or_else(|| row.text("summary")) .map(str::to_string), thread_id: chat_by_record.get(&id).cloned(), copies, id, } }) .collect()) }; let photos = media("cotton_photos")?; let videos = media("cotton_videos")?; let documents: Vec = driver .all( "SELECT id, byte_size, title, original_name FROM cotton_documents WHERE \ workspace_id = ?", std::slice::from_ref(&workspace), ) .map_err(refuse)? .into_iter() .map(|row| SizedRow { id: row.text("id").unwrap_or_default().to_string(), bytes: row.int("byte_size").unwrap_or(0), text: row .text("title") .or_else(|| row.text("original_name")) .map(str::to_string), thread_id: None, copies: 0, }) .collect(); // Everything else a chat carries: voice notes, other audio, and files. The // pictures are deliberately excluded — they are already counted from their // own tables above, and counting a forwarded picture once per message is // exactly the double-count that would tell somebody they can free space // they cannot. let mut audio: Vec = Vec::new(); let mut other: Vec = Vec::new(); for row in driver .all( "SELECT m.id AS message_id, m.thread_id AS thread_id, json_extract(entry.value, '$.contentType') AS content_type, json_extract(entry.value, '$.sizeBytes') AS size_bytes, json_extract(entry.value, '$.name') AS name, entry.key AS idx FROM cotton_msg_messages m, json_each(m.media) entry WHERE m.workspace_id = ? AND m.media IS NOT NULL", std::slice::from_ref(&workspace), ) .map_err(refuse)? { let content_type = row.text("content_type").unwrap_or("").to_lowercase(); if content_type.starts_with("image/") || content_type.starts_with("video/") { continue; } let item = SizedRow { // The attachment, not the message: one message can carry several, // and an id that named the message would make two rows look like // one. id: format!( "{}#{}", row.text("message_id").unwrap_or_default(), row.int("idx").unwrap_or(0) ), bytes: row.int("size_bytes").unwrap_or(0), text: Some( row.text("name") .map(str::to_string) .unwrap_or_else(|| content_type.clone()), ), thread_id: row.text("thread_id").map(str::to_string), copies: 0, }; if content_type.starts_with("audio/") { audio.push(item); } else { other.push(item); } } // A meeting's recording lives in the object store and its size is in no // column of the database, so it is COUNTED and never guessed at. let meeting_recordings = driver .get( "SELECT COUNT(*) AS n FROM cotton_meetings WHERE workspace_id = ? AND audio_deleted_at IS NULL", std::slice::from_ref(&workspace), ) .map_err(refuse)? .and_then(|row| row.int("n")) .unwrap_or(0); let sum = |rows: &[SizedRow]| -> i64 { rows.iter().map(|row| row.bytes).sum() }; let kind_total = |kind: &str, rows: &[SizedRow], also_items: i64| -> (Value, i64) { let unmeasured = rows.iter().filter(|row| row.bytes == 0).count() as i64 + also_items; let bytes = sum(rows); let mut line = Map::new(); line.insert("kind".to_string(), Value::from(kind)); line.insert( "items".to_string(), Value::from(rows.len() as i64 + also_items), ); line.insert("bytes".to_string(), Value::from(bytes)); if unmeasured > 0 { line.insert("unmeasured".to_string(), Value::from(unmeasured)); } (Value::Object(line), bytes) }; let forwarded_copies: i64 = photos .iter() .chain(videos.iter()) .map(|row| row.copies) .sum(); let lines = [ kind_total("photos", &photos, 0), kind_total("videos", &videos, 0), kind_total("documents", &documents, 0), // Meeting recordings ride the audio line as counted-but-unmeasured // items, because "audio" is the word the owner would use for both. kind_total("audio", &audio, meeting_recordings), kind_total("other", &other, 0), ]; let total_bytes: i64 = lines.iter().map(|(_, bytes)| bytes).sum(); let by_kind: Vec = lines.into_iter().map(|(line, _)| line).collect(); // By chat: everything that arrived in one, whichever kind it is. Insertion // order is the TypeScript `Map`'s, so a tie between two chats reads the // same way here as there. let mut by_thread: Vec<(String, i64, i64)> = Vec::new(); for row in photos .iter() .chain(videos.iter()) .chain(audio.iter()) .chain(other.iter()) { let Some(thread_id) = &row.thread_id else { continue; }; match by_thread.iter_mut().find(|(id, _, _)| id == thread_id) { Some(entry) => { entry.1 += 1; entry.2 += row.bytes; } None => by_thread.push((thread_id.clone(), 1, row.bytes)), } } by_thread.sort_by_key(|entry| std::cmp::Reverse(entry.2)); by_thread.truncate(TOP_CHATS); let mut names: BTreeMap = BTreeMap::new(); if !by_thread.is_empty() { let holes = vec!["?"; by_thread.len()].join(", "); let mut params = vec![workspace.clone()]; params.extend( by_thread .iter() .map(|(id, _, _)| SqlValue::Text(id.clone())), ); for row in driver .all( &format!( "SELECT id, title FROM cotton_msg_threads WHERE workspace_id = ? AND id IN ({holes})" ), ¶ms, ) .map_err(refuse)? { if let (Some(id), Some(title)) = (row.text("id"), row.text("title")) { names.insert(id.to_string(), title.to_string()); } } } let kind_of = |row: &SizedRow| -> &'static str { if row.id.starts_with("photo:") { "photo" } else if row.id.starts_with("video:") { "video" } else if row.id.contains('#') { "message file" } else { "document" } }; let mut ranked: Vec<&SizedRow> = photos .iter() .chain(videos.iter()) .chain(documents.iter()) .chain(audio.iter()) .chain(other.iter()) .collect(); // A stable sort, as `Array.prototype.sort` has been since ES2019: two items // of the same size keep the order the kinds were listed in. ranked.sort_by_key(|row| std::cmp::Reverse(row.bytes)); let largest: Vec = ranked .into_iter() .take(LARGEST_ITEMS) .map(|row| { let mut item = Map::new(); item.insert("kind".to_string(), Value::from(kind_of(row))); item.insert("id".to_string(), Value::from(row.id.clone())); item.insert("bytes".to_string(), Value::from(row.bytes)); item.insert("text".to_string(), snippet(row.text.as_deref())); Value::Object(item) }) .collect(); // Everything an assistant has flagged, both kinds, newest note first. The // tool that made it is `update_photo` / `update_video`, never a worker and // never a rule. let mut flagged_rows: Vec<(String, Value)> = Vec::new(); for (kind, table) in [("photo", "cotton_photos"), ("video", "cotton_videos")] { for row in driver .all( &format!( "SELECT id, size_bytes, caption, summary, review_note, review_by, review_at FROM {table} WHERE workspace_id = ? AND review_note IS NOT NULL" ), std::slice::from_ref(&workspace), ) .map_err(refuse)? { let review_at = row.text("review_at").unwrap_or_default().to_string(); let mut item = Map::new(); item.insert("kind".to_string(), Value::from(kind)); item.insert( "id".to_string(), Value::from(row.text("id").unwrap_or_default()), ); item.insert( "bytes".to_string(), Value::from(row.int("size_bytes").unwrap_or(0)), ); item.insert( "text".to_string(), snippet(row.text("caption").or_else(|| row.text("summary"))), ); item.insert( "reviewNote".to_string(), Value::from(row.text("review_note").unwrap_or_default()), ); item.insert( "reviewBy".to_string(), row.text("review_by").map_or(Value::Null, Value::from), ); item.insert("reviewAt".to_string(), Value::from(review_at.clone())); flagged_rows.push((review_at, Value::Object(item))); } } flagged_rows.sort_by(|a, b| b.0.cmp(&a.0)); let flagged: Vec = flagged_rows.into_iter().map(|(_, row)| row).collect(); // Anything a figure above needs a sentence for. Both are about honesty // rather than detail: a number the owner cannot explain is a number they // cannot act on. let mut notes: Vec = Vec::new(); if forwarded_copies > 0 { notes.push(format!( "{forwarded_copies} extra cop{} of photos or videos are counted: a picture forwarded \ into another chat had its bytes copied under that chat's own key, so one record can \ be several objects, and deleting the record frees all of them.", if forwarded_copies == 1 { "y" } else { "ies" } )); } if meeting_recordings > 0 { notes.push(format!( "{meeting_recordings} meeting recording(s) are counted under audio without their \ bytes: their size lives in the object store rather than in the database, and a \ guessed figure would be worse than a missing one." )); } let mut out = Map::new(); out.insert("byKind".to_string(), Value::Array(by_kind)); out.insert("totalBytes".to_string(), Value::from(total_bytes)); out.insert( "byChat".to_string(), Value::Array( by_thread .into_iter() .map(|(id, items, bytes)| { let mut chat = Map::new(); chat.insert( "name".to_string(), names.get(&id).cloned().map_or(Value::Null, Value::from), ); chat.insert("threadId".to_string(), Value::from(id)); chat.insert("items".to_string(), Value::from(items)); chat.insert("bytes".to_string(), Value::from(bytes)); Value::Object(chat) }) .collect(), ), ); out.insert("largest".to_string(), Value::Array(largest)); out.insert("flagged".to_string(), Value::Array(flagged)); put( &mut out, "note", (!notes.is_empty()).then(|| Value::from(notes.join(" "))), ); Ok(Value::Object(out)) }