Cotton code
120 lines · 5.1 KB · RustRaw
//! `arrange_tools` — which tiles are on Home, from a conversation ("put//! Memory on Home"). It writes the one `cotton_home_arrangement` row//! (`crate::home_arrangement::save`), starting from what Home holds now, so a//! tile the conversation does not name stays on or off as the person left it.//! It sets no order: the fan is alphabetical in every database, always//! (owner, 17 Oct 2026), and no tool sets one.//!//! A tile is a VIEW (owner's ruling, 12 Oct 2026): a tool's list, named by the//! tool's key or `tool/<key>`, Everything (`everything` or `ready/everything`),//! or a group (`<table>/<groupId>`). Nothing is hidden: a tile is on Home or it//! is not. A name this database does not hold is refused whole, because a//! stored unknown would fall out of the read silently and the assistant would//! report a change the screen never draws.use cotton_core::rules::home_arrangement::{tool_view, HomeArrangement, EVERYTHING_VIEW};use cotton_store::link_rule::FileKind;use serde_json::{json, Map, Value};use crate::home_arrangement::{home, save, stored, Home};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::fail;use crate::mcp::protocol::ToolFailure;const ARGS: [&str; 2] = ["add", "remove"];/// A list longer than this is no arrangement of a Home (the phone's cap too).const MAX_KEYS: usize = 200;pub fn arrange_tools(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if let Some(key) = args.keys().find(|key| !ARGS.contains(&key.as_str())) {        return fail(format!("{key:?} is not an argument: arrange_tools takes add and remove"));    }    let add = views(keys(args, "add")?);    let remove = views(keys(args, "remove")?);    if let Some(both) = add.iter().find(|view| remove.contains(view)) {        return fail(format!("{both:?} is both added and removed; name it in one of them"));    }    let workspace_id = ctx.workspace_id.to_string();    let personal = !matches!(ctx.file_kind()?, FileKind::Shared);    let saved = stored(ctx.db(), &workspace_id).map_err(ToolFailure::new)?;    let now = home(ctx.db(), &workspace_id, saved.as_ref(), personal).map_err(ToolFailure::new)?;    let offered = |view: &String| now.view(view).is_some();    if let Some(unknown) = add.iter().find(|view| !offered(view)) {        return fail(format!(            "{unknown:?} is no tile this database can show; its tools are: {}",            now.tools.join(", ")        ));    }    if add.is_empty() && remove.is_empty() {        return Ok(json!({ "changed": false, "home": answer(&now) }));    }    let mut view_ids: Vec<String> = Vec::new();    for view in now.views.iter().chain(&add) {        if !remove.contains(view) && !view_ids.contains(view) {            view_ids.push(view.clone());        }    }    let saved = saved.unwrap_or_default();    let record = HomeArrangement { project_slugs: saved.project_slugs, tools: now.tools.clone(), view_ids };    let record = save(ctx, &record)?;    // A handler commits its own writes: the transport mints nothing after it.    ctx.commit()?;    let after = home(ctx.db(), &workspace_id, Some(&record), personal).map_err(ToolFailure::new)?;    Ok(json!({ "changed": true, "home": answer(&after) }))}/// A tile as the conversation named it, as the view id Home stores.fn views(names: Vec<String>) -> Vec<String> {    names        .into_iter()        .map(|name| {            if name == "everything" {                EVERYTHING_VIEW.to_string()            } else if name.contains('/') {                name            } else {                tool_view(&name)            }        })        .collect()}/// Home as an assistant reads it back: its tiles in the order they are drawn/// (alphabetical, an empty one faint in its place), and the database's tools.fn answer(home: &Home) -> Value {    let tiles: Vec<Value> = home        .tiles        .iter()        .map(|tile| {            let known = home.view(&tile.id);            json!({                "view": tile.id,                "empty": tile.empty,                "tool": known.and_then(|known| known.tool.clone()),                "name": known.and_then(|known| known.name.clone()),                "table": known.and_then(|known| known.table.clone()),            })        })        .collect();    json!({ "tiles": tiles, "tools": home.tools })}fn keys(args: &Map<String, Value>, name: &str) -> Result<Vec<String>, ToolFailure> {    let Some(raw) = args.get(name).filter(|raw| !raw.is_null()) else { return Ok(Vec::new()) };    let entries = raw.as_array().ok_or_else(|| ToolFailure::new(format!("{name} is a list of tool keys")))?;    if entries.len() > MAX_KEYS {        return Err(ToolFailure::new(format!("{name} holds at most {MAX_KEYS} keys")));    }    let mut out: Vec<String> = Vec::with_capacity(entries.len());    for entry in entries {        let key = entry            .as_str()            .map(str::trim)            .filter(|key| !key.is_empty())            .ok_or_else(|| ToolFailure::new(format!("every entry of {name} is a tool key, as text")))?;        if !out.iter().any(|seen| seen == key) {            out.push(key.to_string());        }    }    Ok(out)}