//! Pictures at once (coordinator for the owner, 23 Nov 2026): a chat's //! pictures are on the phone before the person scrolls to them. //! //! ```text //! chat.ahead { thread, messages: [id] } → { asked, here, fetched, failed, stopped } //! chat.warm { constrained?, chats?, each?, limit? } → { asked, here, fetched, failed, skipped? } //! chat.previews { limit? } → { items: [{ message, index, path }] } //! chat.preview { items: [{ message, index, preview }] } → { set } //! ``` //! //! **The keep policy is the core's.** Every picture's preview always (a tiny //! JPEG sealed in the message itself, `payload::Picture::preview`, so it //! arrives with the words and lives in the person's own rows); the full //! picture of every message of the last [`KEEP_DAYS`] days in every chat; and //! any picture the person opens or scrolls near. The bytes go where every //! chat file already goes on this phone: the person's own media //! (`chat_files::keep`, then `media::land` from this phone's store), so //! Storage counts them under Photos and files, and Free up space takes only //! what is in the person's account (`shell_settings::FREEABLE`). //! //! **`chat.ahead`** is what the open chat calls as it scrolls, with the //! messages it shows: their pictures first, then [`AHEAD_MESSAGES`] messages //! with pictures on each side. A newer call for the same chat stops the older //! between fetches, so a fast scroll never queues the whole chat. //! //! **`chat.warm`** is the chat list's, in the background: the newest //! [`WARM_EACH`] pictures of the top [`WARM_CHATS`] chats, then the last //! thirty days of every chat, newest first, at most [`WARM_LIMIT`] a call. On //! Wi-Fi and mobile data alike, and nothing at all while the phone is in Low //! Data Mode (`constrained`, iPhone's `NWPath.isConstrained`). A picture Free //! up space or the budget took (its ledger row here with no file) is not //! brought back by the background: only by opening it or scrolling near it. //! //! **Previews for old pictures.** The core decodes no pictures. A picture //! sent before previews (or imported without one) gets its preview from the //! phone that first holds its file: `chat.previews` lists those held here //! with none, the phone makes each (at most 32 px a side, a JPEG of at most //! 2 KB) and hands them to `chat.preview`, which writes each into the //! message's own row once, so every phone of the person has it from then on. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use cotton_core::chat::payload; use super::chat_files::{self, Attached}; use super::cotton_chat::{self, meta_value, one, read, rows, write, ws, MESSAGES, THREADS}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// How many days of every chat keep their full pictures on the phone. pub const KEEP_DAYS: i64 = 30; /// Messages with pictures fetched ahead on each side of what the chat shows. pub const AHEAD_MESSAGES: usize = 24; /// Fetches at once, ahead or warm. pub const IN_FLIGHT: usize = 4; /// The chats the list warms first, from its top. pub const WARM_CHATS: usize = 8; /// Pictures warmed in each of those chats, newest first. pub const WARM_EACH: usize = 12; /// Pictures one `chat.warm` asks for at most; the rest the next call. pub const WARM_LIMIT: usize = 200; /// Attachments one message carries at most, imports and Cotton files counted. const ATTACHED_MAX: usize = 64; /// What became of one picture. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Got { /// Already on this phone. Here, /// Fetched now. Fetched, /// Not a picture, gone, or (in the background) taken by Free up space. Skipped, /// Asked and not had: asked again next time. Failed, } /// The newest `chat.ahead` of each chat: an older call stops between fetches. static AHEAD: Mutex>> = Mutex::new(None); fn ahead_turn(thread: &str) -> u64 { let mut held = AHEAD.lock().unwrap_or_else(|p| p.into_inner()); let map = held.get_or_insert_with(HashMap::new); let next = map.get(thread).copied().unwrap_or(0) + 1; map.insert(thread.to_string(), next); next } fn ahead_current(thread: &str, turn: u64) -> bool { let held = AHEAD.lock().unwrap_or_else(|p| p.into_inner()); held.as_ref().and_then(|m| m.get(thread)).copied() == Some(turn) } /// The turn a chat-store file is fetched under: `chat.picture` and the /// fetches here wait for one another, never fetching the same file twice. pub(crate) fn file_turn(file: &str) -> cotton_client::media::fetching::Turn { cotton_client::media::fetching::turn(&format!("chat-file:{file}")) } const PICTURE_ROW: &str = "id, thread_id, media, meta, origin, channel, direction, send_state, sent_at, created_at"; const HAS_PICTURES: &str = "trashed_at IS NULL AND deleted_at IS NULL AND hidden_at IS NULL AND (meta LIKE '%\"pictures\"%' OR (media IS NOT NULL AND media NOT IN ('', '[]')))"; fn is_picture_mime(mime: &str) -> bool { mime.starts_with("image/") && mime != "image/svg+xml" } /// Whether a Cotton file is a picture the bubble draws as one (never a video, a voice message or a file). fn cotton_picture(picture: &payload::Picture) -> bool { matches!(picture.kind.as_deref(), None | Some("photo") | Some("image")) && is_picture_mime(&picture.mime) } fn imported_picture(media: &cotton_core::messages::MessageMedia) -> bool { let kind = media.kind.as_ref().and_then(|k| serde_json::to_value(k).ok()).and_then(|v| v.as_str().map(str::to_string)); matches!(kind.as_deref(), None | Some("photo") | Some("image")) && is_picture_mime(&media.content_type) } /// Whether this phone held `key`'s bytes once and no longer does (Free up /// space or the budget took them): the background does not bring them back. fn freed(client: &ClientController, key: &str) -> bool { let key = key.to_string(); client .with_file(|replica| { let key = super::media::object_key_of(replica.driver, &replica.identity.id().to_string(), key); Ok(cotton_store::media_ledger::media_by_key(replica.driver, &key).ok().flatten().is_some_and(|row| row.local_path.is_none())) }) .unwrap_or(false) } /// Whether `key`'s bytes are on this phone now. fn held(client: &ClientController, key: &str) -> Option { let key = key.to_string(); client .with_file(|replica| { let key = super::media::object_key_of(replica.driver, &replica.identity.id().to_string(), key); Ok(super::media::local_path_of(replica.driver, &key)) }) .ok() .flatten() } fn landed(client: &ClientController, key: &str, background: bool) -> Got { if background && freed(client, key) { return Got::Skipped; } match super::media::land(client, key.to_string(), super::media::Tier::Original, super::media::Asker::Sweep) { Ok(l) if l.fetched_into.is_some() => Got::Fetched, Ok(_) => Got::Here, Err(_) => Got::Failed, } } /// One attachment of `row` brought onto this phone, if it is a picture. fn bring(client: &ClientController, row: &Value, index: usize, background: bool) -> Got { match chat_files::attached(row, index) { None => Got::Skipped, Some(Attached::Pending(..)) => Got::Here, Some(Attached::Imported(media)) => { if !imported_picture(&media) { return Got::Skipped; } landed(client, &media.key, background) } Some(Attached::Cotton(at, picture)) => { if !cotton_picture(&picture) || picture.file.is_empty() { return Got::Skipped; } let meta = meta_value(&row["meta"]); if meta["cotton"]["pictures"][at]["gone"] == json!(true) { return Got::Skipped; } if let Some(key) = meta["cotton"]["pictures"][at]["kept"].as_str() { return landed(client, key, background); } // Not kept by any phone yet: from the chat store, then kept, under the file's one turn. let _turn = file_turn(&picture.file); let id = row["id"].as_str().unwrap_or_default(); let Ok(now) = chat_files::message_row(client, "chat.ahead", id) else { return Got::Failed }; if let Some(key) = meta_value(&now["meta"])["cotton"]["pictures"][at]["kept"].as_str() { return landed(client, key, background); } let dir = client.layout().root().join("chat-ahead"); let may_be_gone = chat_files::may_be_gone(client, &now); let Ok(opened) = cotton_chat::open_picture(client, &picture, &dir, may_be_gone) else { return Got::Failed }; let Some(path) = opened["path"].as_str().map(std::path::PathBuf::from) else { return Got::Failed }; let kept = chat_files::keep(client, id, now["thread_id"].as_str().unwrap_or_default(), at, &path, &picture); // not a copy: chat files. let _ = std::fs::remove_file(&path); if kept.is_ok() { Got::Fetched } else { Got::Failed } } } } /// Whether the background should bring this picture: not on the phone, not gone, not taken by Free up space. fn wanted_here(client: &ClientController, row: &Value, index: usize) -> bool { match chat_files::attached(row, index) { Some(Attached::Imported(media)) => held(client, &media.key).is_none() && !freed(client, &media.key), Some(Attached::Cotton(at, picture)) => { let meta = meta_value(&row["meta"]); let entry = &meta["cotton"]["pictures"][at]; if entry["gone"] == json!(true) || picture.file.is_empty() { return false; } match entry["kept"].as_str() { Some(key) => held(client, key).is_none() && !freed(client, key), None => true, } } Some(Attached::Pending(..)) | None => false, } } /// The pictures of `rows`, in order, as `(row, index)`. fn pictures_in(rows: &[Value]) -> Vec<(usize, usize)> { let mut out = Vec::new(); for (r, row) in rows.iter().enumerate() { for index in 0..ATTACHED_MAX { let Some(attached) = chat_files::attached(row, index) else { break }; let picture = match &attached { Attached::Imported(media) => imported_picture(media), Attached::Cotton(_, picture) => cotton_picture(picture), Attached::Pending(..) => false, }; if picture { out.push((r, index)); } } } out } #[derive(Default)] struct Counts { here: AtomicUsize, fetched: AtomicUsize, failed: AtomicUsize, stopped: AtomicUsize, } /// `work` brought onto the phone, [`IN_FLIGHT`] at a time, while `go` says so. fn run(client: &ClientController, rows: &[Value], work: &[(usize, usize)], background: bool, go: &(dyn Fn() -> bool + Sync)) -> Counts { let counts = Counts::default(); let next = AtomicUsize::new(0); std::thread::scope(|scope| { for _ in 0..IN_FLIGHT.min(work.len()) { scope.spawn(|| loop { let Some(&(r, index)) = work.get(next.fetch_add(1, Ordering::SeqCst)) else { break }; if !go() || !client.slice_has_room() { counts.stopped.fetch_add(1, Ordering::SeqCst); continue; } let into = match bring(client, &rows[r], index, background) { Got::Here => &counts.here, Got::Fetched => &counts.fetched, Got::Failed => &counts.failed, Got::Skipped => continue, }; into.fetch_add(1, Ordering::SeqCst); }); } }); counts } fn answer(asked: usize, counts: &Counts) -> Value { json!({ "asked": asked, "here": counts.here.load(Ordering::SeqCst), "fetched": counts.fetched.load(Ordering::SeqCst), "failed": counts.failed.load(Ordering::SeqCst), "stopped": counts.stopped.load(Ordering::SeqCst), }) } fn picture_rows(client: &ClientController, label: &str, sql: String, params: Vec) -> Result, MethodError> { let found = read(client, label, move |ctx| { let mut all = vec![ws(ctx)]; all.extend(params.iter().cloned()); Ok(Value::Array(rows(ctx, &sql, &all)?.into_iter().map(Value::Object).collect())) })?; Ok(found.as_array().cloned().unwrap_or_default()) } /// `chat.ahead`: the pictures of the messages the chat shows, then those on each side. pub(crate) fn ahead(client: &ClientController, request: &Value) -> Result { let thread = cotton_chat::text(request, "thread")?.to_string(); let shown: Vec = request.get("messages").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).take(200).collect(); // One chat of one phone's copy: the app's folder names the copy. let turned = format!("{}|{thread}", client.layout().root().display()); let turn = ahead_turn(&turned); // The span the chat shows, by when its messages were sent. let (t, ids) = (thread.clone(), shown.clone()); let span = read(client, "chat.ahead", move |ctx| { if ids.is_empty() { return Ok(Value::Null); } let marks = vec!["?"; ids.len()].join(","); let mut params = vec![ws(ctx), SqlValue::Text(t.clone())]; params.extend(ids.iter().cloned().map(SqlValue::Text)); let row = one(ctx, &format!("SELECT MIN(sent_at) AS lo, MAX(sent_at) AS hi FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id IN ({marks})"), ¶ms)?; Ok(row.map(Value::Object).unwrap_or(Value::Null)) })?; let (lo, hi) = (span["lo"].as_str().map(str::to_string), span["hi"].as_str().map(str::to_string)); let mut found: Vec = Vec::new(); let base = format!("SELECT {PICTURE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND {HAS_PICTURES}"); match (lo, hi) { (Some(lo), Some(hi)) => { let th = || SqlValue::Text(thread.clone()); found.extend(picture_rows(client, "chat.ahead", format!("{base} AND sent_at >= ? AND sent_at <= ? ORDER BY sent_at DESC"), vec![th(), SqlValue::Text(lo.clone()), SqlValue::Text(hi.clone())])?); // Then both sides, nearest first, one from each in turn. let older = picture_rows(client, "chat.ahead", format!("{base} AND sent_at < ? ORDER BY sent_at DESC LIMIT {AHEAD_MESSAGES}"), vec![th(), SqlValue::Text(lo)])?; let newer = picture_rows(client, "chat.ahead", format!("{base} AND sent_at > ? ORDER BY sent_at ASC LIMIT {AHEAD_MESSAGES}"), vec![th(), SqlValue::Text(hi)])?; for i in 0..older.len().max(newer.len()) { found.extend(newer.get(i).cloned()); found.extend(older.get(i).cloned()); } } // Nothing named, or nothing known of it: the chat's newest, as it opens at its foot. _ => found.extend(picture_rows(client, "chat.ahead", format!("{base} ORDER BY sent_at DESC LIMIT {AHEAD_MESSAGES}"), vec![SqlValue::Text(thread.clone())])?), } let work = pictures_in(&found); let go = || ahead_current(&turned, turn); let counts = run(client, &found, &work, false, &go); Ok(answer(work.len(), &counts)) } /// `chat.warm`: the top chats' newest pictures, then the last thirty days of every chat. pub(crate) fn warm(client: &ClientController, request: &Value) -> Result { if request.get("constrained").and_then(Value::as_bool).unwrap_or(false) { // Low Data Mode: nothing goes in the background. The previews came with the words. return Ok(json!({ "asked": 0, "here": 0, "fetched": 0, "failed": 0, "stopped": 0, "skipped": "constrained" })); } let chats = request.get("chats").and_then(Value::as_u64).map_or(WARM_CHATS, |n| n.clamp(0, 50) as usize); let each = request.get("each").and_then(Value::as_u64).map_or(WARM_EACH, |n| n.clamp(0, 100) as usize); let limit = request.get("limit").and_then(Value::as_u64).map_or(WARM_LIMIT, |n| n.clamp(1, 2_000) as usize); // The list's top: pinned first, then the newest, never archived. let top = read(client, "chat.warm", move |ctx| { let found = rows(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND trashed_at IS NULL AND coalesce(archived, 0) = 0 ORDER BY (pinned_at IS NULL) ASC, last_message_at DESC LIMIT {chats}"), &[ws(ctx)])?; Ok(Value::Array(found.into_iter().filter_map(|r| r.get("id").cloned()).collect())) })?; let mut found: Vec = Vec::new(); let mut work: Vec<(usize, usize)> = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut add = |rows: Vec, cap: usize, found: &mut Vec, work: &mut Vec<(usize, usize)>| { let start = found.len(); let mut taken = 0; for (r, index) in pictures_in(&rows) { if taken >= cap || work.len() >= limit { break; } let id = rows[r]["id"].as_str().unwrap_or_default().to_string(); // Only what is not here counts toward the call's limit, so each call goes further back. if seen.insert((id, index)) && wanted_here(client, &rows[r], index) { work.push((start + r, index)); taken += 1; } } found.extend(rows); }; for thread in top.as_array().into_iter().flatten().filter_map(Value::as_str) { let rows = picture_rows(client, "chat.warm", format!("SELECT {PICTURE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND {HAS_PICTURES} ORDER BY sent_at DESC LIMIT {each}"), vec![SqlValue::Text(thread.to_string())])?; add(rows, each, &mut found, &mut work); } if work.len() < limit { let since = cotton_chat::iso(cotton_chat::now_ms(client) - KEEP_DAYS * 24 * 3_600_000); let rows = picture_rows(client, "chat.warm", format!("SELECT {PICTURE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND sent_at > ? AND {HAS_PICTURES} ORDER BY sent_at DESC LIMIT 2000"), vec![SqlValue::Text(since)])?; add(rows, usize::MAX, &mut found, &mut work); } let go = || true; let counts = run(client, &found, &work, true, &go); Ok(answer(work.len(), &counts)) } fn has_preview(row: &Value, index: usize) -> bool { match chat_files::attached(row, index) { Some(Attached::Imported(media)) => media.preview.is_some(), Some(Attached::Cotton(_, picture)) => picture.preview.is_some(), Some(Attached::Pending(..)) | None => true, } } /// `chat.previews`: pictures whose file is on this phone and that have no preview yet, newest first. pub(crate) fn previews(client: &ClientController, request: &Value) -> Result { let limit = request.get("limit").and_then(Value::as_u64).map_or(50, |n| n.clamp(1, 500) as usize); let rows = picture_rows(client, "chat.previews", format!("SELECT {PICTURE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND {HAS_PICTURES} ORDER BY sent_at DESC LIMIT 4000"), vec![])?; let mut items = Vec::new(); for (r, index) in pictures_in(&rows) { if items.len() >= limit { break; } let row = &rows[r]; if has_preview(row, index) { continue; } let path = match chat_files::attached(row, index) { Some(Attached::Imported(media)) => held(client, &media.key), Some(Attached::Cotton(at, _)) => meta_value(&row["meta"])["cotton"]["pictures"][at]["kept"].as_str().and_then(|key| held(client, key)), _ => None, }; if let Some(path) = path { items.push(json!({ "message": row["id"], "index": index, "path": path.to_string_lossy() })); } } Ok(json!({ "items": items })) } /// `chat.preview`: each preview written into its message's row, once; one that is not a small JPEG is left out. pub(crate) fn set_previews(client: &ClientController, request: &Value) -> Result { let items: Vec<(String, usize, String)> = request .get("items") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(|item| Some((item["message"].as_str()?.to_string(), item["index"].as_u64()? as usize, payload::preview_of(item["preview"].as_str()?)?))) .take(500) .collect(); let answer = write(client, "chat.preview", move |ctx| { let mut set = 0; for (id, index, preview) in &items { let Some(row) = one(ctx, &format!("SELECT {PICTURE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { continue }; let row = Value::Object(row); let mut patch = Map::new(); match chat_files::attached(&row, *index) { Some(Attached::Imported(media)) if media.preview.is_none() => { let mut entries: Vec = match &row["media"] { Value::String(t) => serde_json::from_str(t).unwrap_or_default(), Value::Array(a) => a.clone(), _ => continue, }; // The index counts the import's own entries, never the Cotton files kept beside them. let Some(entry) = entries.iter_mut().filter(|e| e["cottonKept"] != json!(true)).nth(*index) else { continue }; entry["preview"] = json!(preview); patch.insert("media".into(), json!(entries)); } Some(Attached::Cotton(at, picture)) if picture.preview.is_none() => { let mut meta = meta_value(&row["meta"]); meta["cotton"]["pictures"][at]["preview"] = json!(preview); patch.insert("meta".into(), meta); } _ => continue, } cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())?; set += 1; } Ok(json!({ "set": set })) })?; Ok(answer) } /// The fetch ahead's turns, for the tests (`chat_app_tests::ahead`). #[cfg(test)] pub(crate) mod tests_turns { pub fn turn(thread: &str) -> u64 { super::ahead_turn(thread) } pub fn current(thread: &str, turn: u64) -> bool { super::ahead_current(thread, turn) } }