//! Shared appearance is a database's name — its workspace row's `name`, which//! every rename writes and every device pulls (137: the architect dropped the//! separate name record, 13 Oct 2026) — and its cap colour, which is its//! theme's (`cotton_tools::presentation`, design note 26203e21 §6): `read`//! answers both together. The small local projection only lets the switcher//! draw idle databases without opening them. Both are set over MCP only — the//! app never edits itself (owner, 16 Oct 2026) — so this module only reads.usecrate::shell::client::ClientController;use cotton_store::driver::Driver;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use std::{collections::BTreeMap, sync::Mutex};/// The local projection's file, beside `client/` under the data root.pubconst FILE: &str = "database-appearance.json";static CACHE_LOCK: Mutex<()> = Mutex::new(());/// The database's own name, off its workspace row (`{"name": …}`); `None`/// while it has none of its own — blank, or the personal placeholder.fn named(db: &Driver, workspace: &str) -> Result<Option<Value>, String> {let row = db .get("SELECT name FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(workspace.into())]) .map_err(|e| e.to_string())?;Ok(row .as_ref() .and_then(|row| row.text("name")) .and_then(super::reads::database_own_name) .map(|name| json!({ "name": name })))}/// `{"name"?, "colour"?}`: the name record's name and the theme's cap colour;/// `None` when the database has said neither.pubfn read(db: &Driver, workspace: &str) -> Result<Option<Value>, String> {letmut appearance = named(db, workspace)?.unwrap_or_else(|| json!({}));ifletSome(object) = appearance.as_object_mut() { object.remove("colour"); }ifletSome(colour) = cotton_tools::presentation::cap_colour(db, workspace)? { appearance["colour"] = Value::String(colour); }Ok((appearance.as_object().is_some_and(|object| !object.is_empty())).then_some(appearance))}fn cache( client: &ClientController, updates: BTreeMap<String, Value>,) -> Result<BTreeMap<String, Value>, String> {let _lock = CACHE_LOCK.lock().map_err(|e| e.to_string())?;let path = client.layout().root().join(FILE);letmut values: BTreeMap<String, Value> = match std::fs::read(&path) {Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| e.to_string())?,Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),Err(e) => returnErr(e.to_string()), };let before = values.clone(); values.extend(updates);if values != before {// not a copy: the database's appearance file. cotton_client::whole_file::replace(&path, &serde_json::to_vec(&values).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; }Ok(values)}/// Every shown database's appearance, and the ones whose file could not be/// read this time — each with its reason.////// ONE DATABASE THAT CANNOT BE READ NEVER EMPTIES THE LIST OF THE OTHERS. On/// 12 Oct 2026 the owner's phone opened a fresh copy of its personal database/// and its Databases sheet came up EMPTY: a read of one file failed and that/// one `?` failed the whole `read.databases`. An unreadable database keeps the/// appearance last cached for it and is named in `unreadable`.pubstructListed {pub appearances: BTreeMap<String, Value>,pub unreadable: BTreeMap<String, String>,}pubfn listed(client: &ClientController) -> Result<Listed, String> {letmut updates = BTreeMap::new();letmut unreadable = BTreeMap::new();for id in client.shown_databases() {// A database whose copy has not arrived has no file to read an// appearance from, and must not fail the list of the ones that have.if client.arriving(&id).is_some() {continue; }match client.glance_in(&id, read) {Ok(Some(appearance)) => { updates.insert(id, appearance); }// A database that says neither now — its look put back to the// shipped one (the one-time move, MCP) — leaves nothing cached// from before.Ok(None) => { updates.insert(id, json!({})); }Err(reason) => { unreadable.insert(id, reason); } } }Ok(Listed { appearances: cache(client, updates)?, unreadable })}/// `/database#page` — one database's page (Spec 10.2): its drawn name and cap/// colour, whether it is this person's own (never left), the address its/// relay name gives, and what THIS device keeps of it (`null` while the/// storage rules have not measured it). Refused for a database this device/// does not hold.pubfn page(client: &ClientController, args: &serde_json::Map<String, Value>) -> Result<Value, String> {let id = args .get("databaseId") .and_then(Value::as_str) .filter(|v| !v.is_empty()) .ok_or("read.database needs databaseId")?;let database = client .databases()? .into_iter() .find(|db| db.id == id) .ok_or("This device does not hold that database.")?;let device = client.self_device_id();let now = client.clock().now().timestamp_millis();let (appearance, kept) = client.with_file_in(id, |file| {let appearance = read(file.driver, file.workspace_id)?.unwrap_or_else(|| json!({}));let kept = match device.as_deref() {Some(device) => cotton_store::storage_rules::evaluate(file.driver, file.workspace_id, device, now) .ok() .map(|e| e.rows) .filter(|rows| rows.iter().all(|r| r.measured_at.is_some())) .map(|rows| json!({"heldBytes": rows.iter().map(|r| r.held_bytes).sum::<i64>(),"freeableBytes": rows.iter().map(|r| r.freeable_bytes).sum::<i64>(),"heldCount": rows.iter().map(|r| r.held_count).sum::<i64>(), })),None => None, };Ok((appearance, kept)) })?;Ok(json!({"databaseId": id,"name": appearance.get("name").and_then(Value::as_str).unwrap_or(&database.name),"colour": appearance.get("colour").cloned().unwrap_or(Value::Null),"personal": database.personal,"pending": database.pending,"canLeave": !database.personal,"keptHere": kept, }))}#[cfg(test)]mod tests {usesuper::*;usecrate::handle::CottonHandle;use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};fn open(path: &std::path::Path) -> CottonHandle {CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: path.to_string_lossy().into(), previous_container_path: None, }, app_version: None, time_zone: Some("Etc/UTC".into()), device_secret: Some(URL_SAFE_NO_PAD.encode([19u8; 32])), vault_secret: None, flavor: cotton_core::flavor::Flavor::Dev, manifest: None, }) .unwrap() }/// Give a database a name and a cap colour the way the MCP writer does —/// the workspace row's `name` and the database's own theme row — since the/// app never sets either (owner, 16 Oct 2026).fn appear(handle: &CottonHandle, id: &str, name: &str, colour: &str) {let client = handle.client();let _scope = client.name_database(Some(id)).unwrap(); client .write_rows("appearance fixture", &mut |ctx| {let workspace = ctx.workspace_id.to_string(); cotton_tools::mcp::handlers::common::update_row( ctx,"cotton_workspaces", &workspace, json!({ "name": name }).as_object().unwrap().clone(), ) .map_err(|e| e.to_string())?; cotton_tools::presentation::set_cap_colour(ctx, Some(colour)).map_err(|e| e.to_string())?;Ok(json!({})) }) .unwrap(); } #[test]fn appearance_is_read_off_the_file_and_survives_reopening() {let dir = tempfile::tempdir().unwrap();let handle = open(dir.path());let born = crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).unwrap();let id = born["workspaceId"].as_str().unwrap(); appear(&handle, id, "Asha", "green"); handle.client().with_file(|file| {// The name is the workspace row's; the colour is the theme's. assert_eq!(read(file.driver,file.workspace_id)?,Some(json!({"name":"Asha","colour":"green"})));Ok(()) }).unwrap(); drop(handle);let reopened = open(dir.path());let listed =super::super::databases::list(&reopened.client(), &serde_json::Map::new()).unwrap(); assert_eq!(listed["databases"][0]["name"], "Asha"); assert!(reopened.client().shown_databases().is_empty()); }/// RULE: The database page reads one database by id: its drawn name and cap colour, whether it is the personal one (which cannot be left), and what this device keeps of it; a database this device does not hold is refused. #[test]fn database_page_reads_name_colour_and_what_this_device_keeps() {let dir = tempfile::tempdir().unwrap();let handle = open(dir.path());let born = crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).unwrap();let id = born["workspaceId"].as_str().unwrap().to_string(); appear(&handle, &id, "Asha", "green");let page = crate::methods::dispatch(&handle, "read.database", &json!({"databaseId": id})).unwrap(); assert_eq!(page["databaseId"], id.as_str()); assert_eq!(page["name"], "Asha"); assert_eq!(page["colour"], "green"); assert_eq!(page["personal"], true); assert_eq!(page["canLeave"], false, "the personal database is never left"); assert!(page.get("relayAddress").is_none(), "no database is reached at a relay"); assert!(page.get("keptHere").is_some(), "what this device keeps is said, null while unmeasured");let refused = crate::methods::dispatch(&handle, "read.database", &json!({"databaseId": "not-held"})) .expect_err("not held"); assert_eq!(refused.code, "unreadable"); }}