//! A TOOL'S OWN ACTS (`ToolDefinition::acts`): the Calendar's Connect Google//! Calendar and Disconnect Google, Music's Connect Spotify and Disconnect//! Spotify, offered on the long-press fan of every card the tool owns,//! beside the card's own acts, and run here — never a verb of the core.//!//! - Each act belongs to a FAMILY, named by the object's status that decides//! it ([`family`]): Google's by `google.status`, Spotify's by//! `spotify.status`. A family's status is asked only when a tool owning the//! table offers an act of it, and nothing of a family stands while its//! status cannot be read: none of its acts can be decided.//! - [`offered`] says which of a tool's acts stand now, as the fan's entries//! (`shell.opened` ranks them among the card's own, kind `tool`): Google's connect while the//! person's object can connect Google and holds no account, its disconnect//! — one per account, its label saying the account and how its calendar//! stands — while it holds one; Spotify's connect while the object can//! connect Spotify and holds no account, its disconnect — its label saying//! who is connected and how the pull stands — while it holds the one.//! - `tools.acts {table}` answers them where no card stands: a deck of the//! table that holds no card (the Calendar with no event, Music with no//! song) offers them on its empty placeholder's fan, resolved by//! [`standing`] exactly as a held card's `shell.opened` resolves them, so the//! two never differ.//! - `tools.act {tool, act, account?}` runs one: a connect answers//! `{ opens }`, the service's consent page, which the phone opens in the//! system browser (the Worker's callback page sends the person back to//! Cotton); a disconnect answers the object's `{ ok, account }`. An act the//! definition says asks (`ToolAct::asks`, a disconnect) is asked first.//! - THIS PHONE'S ACCOUNT is a family too (`account.status`), answered by//! the phone from its own state, never asked of the object: Sign in while//! the app backs up to a personal object and this phone is not signed in,//! Back up now and Sign out while it is (Cotton Books' On this phone,//! owner, 4 Nov 2026). Sign in and Sign out answer the flow this device's//! own row runs (`settings.openFlow`'s `open_flow`, origin the device row);//! Back up now asks a pass at once and answers the words it says.//! - A view may name the acts it offers (`ToolView::acts`): an act a view of//! the tool names stands only on that view's deck (`tools.acts {table,//! view}`, the view as `<tool>/<id>`); one no view names on every deck.//! - A LIST'S OWN ACTS are the shell's, on the deck of every list of every//! tool (`<tool>/group:<id>`, 5 Nov 2026) and on its tile held on the//! fan's lists tier (`tools.acts {table, view, held: "list"}`), answered//! by one function ([`list_acts`], list-acts, 7 Nov 2026), in this order://! the table's own first act (a list of songs plays, Music's Play), Rename,//! Set picture from Photos, Remove picture while the list has one, Move//! earlier and Move later — each absent at the end it cannot pass — and//! Remove list, red and last, asked first. They name their list (`group`);//! Rename asks its words in the shell's one short-text input (`words`://! the name it holds, and its hint), refused in the `lists` set's words//! when empty or another list of its table has it; Set picture answers the//! photo picker the phone opens (`open_picker`, picker `photos`), whose//! picture `groups.update {picturePath}` keeps; Remove picture, a move and//! Remove list are one write each, answered with their receipt's words//! and the change that undoes them (`undo`). Remove list puts the list in//! the bin; its records stay.//! - A CARD HELD ON A LIST'S DECK carries the list's acts but its moves://! Move earlier and Move later there move the card along the list (each//! absent at its end), beside Remove from the list.//! On a list of songs, a song's Play plays the LIST from that song//! (music-player-gone, 6 Nov 2026): the song's own Play act, in its place//! and rank, runs as the list's (`list_play`, naming the list and the//! song), which `tools.act` answers as `shell.player` answers the play.//! - EXPORT LIBRARY (Books, Music, Podcasts and Cinemas, 7 Nov 2026) stands//! on the view its tool names it on (On this phone; Podcasts' Shows) for a//! tool with an open bundle ([`export_kit`]), its family answered by the//! phone and never unread: the bundle is laid from this phone's own copy,//! signed in or not. `tools.act` answers `{//! platform_action: "export_open", kit, name }` — the bundle's kit as//! `package.exportOpen` names it and the tool's name — and the phone//! picks the folder, asks `package.exportOpen`, zips the folder and hands//! the zip to the share sheet.use std::collections::BTreeMap;use cotton_core::definitions::{TableDefinition, ToolDefinition};use serde_json::{json, Value};usecrate::methods::MethodError;usecrate::phone::personal_object::ObjectDoor;usecrate::shell::client::ClientController;pubconst GOOGLE_CONNECT: &str = "google_connect";pubconst GOOGLE_DISCONNECT: &str = "google_disconnect";pubconst SPOTIFY_CONNECT: &str = "spotify_connect";pubconst SPOTIFY_DISCONNECT: &str = "spotify_disconnect";pubconst ACCOUNT_SIGN_IN: &str = "account_sign_in";pubconst ACCOUNT_BACK_UP: &str = "account_back_up";pubconst ACCOUNT_SIGN_OUT: &str = "account_sign_out";pubconst MUSIC_KEEP_EVERYTHING: &str = "music_keep_everything";pubconst CINEMAS_KEEP_EVERYTHING: &str = "cinemas_keep_everything";pubconst CINEMAS_CELLULAR: &str = "cinemas_cellular";pubconst CINEMAS_BUDGET: &str = "cinemas_budget";pubconst EXPORT_LIBRARY: &str = "export_library";/// Cotton Keys' Turn on Cotton Keys: the system's provider settings, opened by the phone.pubconst KEYS_TURN_ON: &str = "keys_turn_on";/// A list's own acts (the shell's, on every list's deck).pubconst LIST_SET_PICTURE: &str = "list_set_picture";pubconst LIST_REMOVE_PICTURE: &str = "list_remove_picture";pubconst LIST_PLAY: &str = "list_play";pubconst LIST_RENAME: &str = "list_rename";pubconst LIST_MOVE_EARLIER: &str = "list_move_earlier";pubconst LIST_MOVE_LATER: &str = "list_move_later";pubconst LIST_REMOVE: &str = "list_remove";/// A card's acts on a list's deck: the card along the list, or off it.pubconst LIST_MEMBER_EARLIER: &str = "list_member_earlier";pubconst LIST_MEMBER_LATER: &str = "list_member_later";pubconst LIST_MEMBER_REMOVE: &str = "list_member_remove";/// A list's page's picks: the records picked put in the list, or taken out.pubconst LIST_ADD: &str = "list_add";pubconst LIST_TAKE_OUT: &str = "list_take_out";/// Every list act `tools.act` runs as the list's.const LIST_ACTS: &[&str] = &[ LIST_SET_PICTURE, LIST_REMOVE_PICTURE, LIST_PLAY, LIST_RENAME, LIST_MOVE_EARLIER, LIST_MOVE_LATER, LIST_REMOVE, LIST_MEMBER_EARLIER, LIST_MEMBER_LATER, LIST_MEMBER_REMOVE, LIST_ADD, LIST_TAKE_OUT,];/// What a list's deck is named after its tool (`books/group:<id>`).const LIST_VIEW: &str = "group:";/// The status of this phone's account family, which the phone answers itself.pubconst ACCOUNT_STATUS: &str = "account.status";/// The status of Cotton Music's own act, answered by the phone itself: Keep/// everything says how this phone keeps.pubconst MUSIC_STATUS: &str = "music.status";/// Cotton Cinemas' Keep everything, answered by the phone itself.pubconst CINEMAS_STATUS: &str = "cinemas.status";/// Export library's family, answered by the phone itself: it always stands/// where its tool has an open bundle.pubconst EXPORT_STATUS: &str = "export.status";/// Turn on Cotton Keys' family, answered by the phone itself: whether this/// build ships the system's providers (the Keys app on Android).pubconst KEYS_STATUS: &str = "keys.status";/// The open bundle a tool exports (`package.exportOpen`'s `kit`); None for a/// tool with none.pubfn export_kit(tool: &str) -> Option<&'static str> {match tool {"books" => Some("books"),"music" => Some("music"),"cinemas" => Some("films"), _ => None, }}/// The status that decides `act`, which names its family; None for an act/// this build does not run.pubfn family(act: &str) -> Option<&'static str> {match act { GOOGLE_CONNECT | GOOGLE_DISCONNECT => Some("google.status"), SPOTIFY_CONNECT | SPOTIFY_DISCONNECT => Some("spotify.status"), ACCOUNT_SIGN_IN | ACCOUNT_BACK_UP | ACCOUNT_SIGN_OUT => Some(ACCOUNT_STATUS), MUSIC_KEEP_EVERYTHING => Some(MUSIC_STATUS), CINEMAS_KEEP_EVERYTHING | CINEMAS_CELLULAR | CINEMAS_BUDGET => Some(CINEMAS_STATUS), EXPORT_LIBRARY => Some(EXPORT_STATUS), KEYS_TURN_ON => Some(KEYS_STATUS), _ => None, }}/// Each family's status as the object answered it; a family missing could/// not be read (or was never asked), and none of its acts stands.pubtypeStatuses = BTreeMap<&'static str, Value>;/// `tools.act {tool, act, account?}`.pubfn call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let bad = |why: &str| MethodError::new("bad_request", why);let tool = request["tool"].as_str().ok_or_else(|| bad("tools.act takes the tool's id"))?;let act = request["act"].as_str().ok_or_else(|| bad("tools.act takes the act's id"))?;if LIST_ACTS.contains(&act) {return list_act(client, act, request); }// The act runs on the tool that offered it: the tool of the view in// view, as stored, never the app's first tool by the act's id.let tools = own_tools(client, "tools.act")?;let definition = tools.iter().find(|definition| definition.id == tool).ok_or_else(|| bad("tools.act names a tool of this database"))?;if !definition.runnable_acts().any(|offered| offered.id == act) {returnErr(bad("tools.act names an act its tool offers")); }if family(act) == Some(ACCOUNT_STATUS) {return account(client, act); }if family(act) == Some(MUSIC_STATUS) {return music_keep_everything(client); }if family(act) == Some(CINEMAS_STATUS) {return cinemas(client, act); }if act == EXPORT_LIBRARY {return export_library(definition); }if act == KEYS_TURN_ON {return keys_turn_on(client); }letSome(door) = client.object_door() else {// Signed out: a connect needs the person's account first, so it opens// Sign in rather than failing (launch-ios walk, 22 Nov 2026: Days'// Connect Google Calendar said "That didn't work" to a new person).if matches!(act, GOOGLE_CONNECT | SPOTIFY_CONNECT) && offered_account(ACCOUNT_SIGN_IN, &account_status(client)) {return account(client, ACCOUNT_SIGN_IN); }returnErr(MethodError::new("not_connected", "this phone is not connected to its database yet")); }; run(&door, act, request.get("account").and_then(Value::as_str))}/// This phone's account, as its family's status: whether the app backs up/// to a personal object at all, and whether this phone is signed in to it.pubfn account_status(client: &ClientController) -> Value {let backs_up = client.syncs() && client.genesis() == cotton_core::genesis::Genesis::Personal;// An adopt on its way is neither signed out nor yet the object's copy:// its rows are going up, and Sign in over it would only ask for it again.let backing_up = backs_up && client.adopting().is_some_and(|adopting| adopting.running());// A phone signed in stays signed in while its copy is connected or made// again, and after a connect that did not take, as its connect left it// (`ClientController::kept_signed_in`): never offered Sign in over it.let signed_in = client.signed_in() || client.kept_signed_in().is_some(); json!({ "backs_up": backs_up, "signed_in": backs_up && signed_in, "backing_up": backing_up })}/// One of this phone's account acts, run here: Sign in and Sign out answer/// the flow this device's own row runs, Back up now asks a pass at once.pub(crate) fn account(client: &ClientController, act: &str) -> Result<Value, MethodError> {let status = account_status(client);let stands = offered_account(act, &status);if !stands {returnErr(MethodError::new("act_not_standing", format!("`{act}` does not stand on this phone now"))); }let flow = match act { ACCOUNT_SIGN_IN => "signIn", ACCOUNT_SIGN_OUT => "signOut", _ => { client.nudge_sync();// Out of reach (offline), "Syncing…" was untrue and Account went on saying "Synced at" (the launch walk,// 22 Nov 2026): Sync now says it could not reach Cotton, and that nothing is lost. The pass still goes.let line = ifcrate::methods::shell_account::unreached_now(client) { "trouble.unreached" } else { "acts.backing_up" };let said = cotton_core::rules::shell_lines::LineSet::shipped("backup") .and_then(|lines| lines.say(line, &[])) .ok_or_else(|| MethodError::new("unreadable", "the backup set says no words for backing up"))?;returnOk(json!({ "said": said })); } };let own = client.self_device_id().ok_or_else(|| MethodError::new("not_connected", "this phone has no device row yet"))?;Ok(json!({"platform_action": "open_flow","flow": flow,"origin": {"table": "device", "id": own},"database": client.reading_database_id(), }))}/// Turn on Cotton Keys' status, answered by this phone: whether this build/// ships Android's autofill service and credential provider, which only the/// Keys app on Android does (its manifest's `KeysAutofillService` and/// `KeysProviderService`). The iPhone's Keys turns on in Settings ›/// Passwords › Password Options, which no act opens.pubfn keys_status(client: &ClientController) -> Value {let keys = cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().is_some_and(|kit| kit.id == "keys"); json!({ "provider_settings": cfg!(target_os = "android") && keys })}/// Turn on Cotton Keys, run here: the phone opens the system's settings where/// Cotton Keys is made its password, passkey and autofill provider/// (`open_provider_settings`). Refused where it does not stand.fn keys_turn_on(client: &ClientController) -> Result<Value, MethodError> {if keys_status(client)["provider_settings"] != json!(true) {returnErr(MethodError::new("act_not_standing", format!("`{KEYS_TURN_ON}` does not stand on this phone now"))); }Ok(json!({ "platform_action": "open_provider_settings" }))}/// Cotton Music's status, answered by this phone: whether it keeps every song.pubfn music_status(client: &ClientController) -> Result<Value, MethodError> {Ok(json!({ "keep_everything": super::songs::keeps_everything(client)? }))}/// Cotton Music's own act, run here: this phone's Keep everything turned/// over. Songs come in through the deck's doors alone (`create.doors`).fn music_keep_everything(client: &ClientController) -> Result<Value, MethodError> {let on = !super::songs::keeps_everything(client)?;letmut answer = super::songs::call_keep_everything(client, on)?;// Turned on, the phone fetches every song not here yet (`SongKeeper`).if on { answer["platform_action"] = json!("keep_songs"); }Ok(answer)}/// Cotton Cinemas' status, answered by this phone: whether it keeps every film.pubfn cinemas_status(client: &ClientController) -> Result<Value, MethodError> {super::films::call_keeping(client)}/// One of Cotton Cinemas' acts, run here: Keep everything turned over (on,/// the phone fetches every film and episode not here yet, `FilmKeeper`),/// mobile data for downloads turned over, or the storage budget stepped.fn cinemas(client: &ClientController, act: &str) -> Result<Value, MethodError> {match act { CINEMAS_CELLULAR => returnsuper::films::turn_cellular(client), CINEMAS_BUDGET => returnsuper::films::next_budget(client), _ => {} }let on = !super::films::keeps_everything(client)?;letmut answer = super::films::call_keep_everything(client, on)?;if on { answer["platform_action"] = json!("keep_films"); }Ok(answer)}/// Export library, run here: the open bundle the phone lays, zips and shares.fn export_library(tool: &ToolDefinition) -> Result<Value, MethodError> {let kit = export_kit(&tool.id).ok_or_else(|| MethodError::new("bad_request", format!("{} has no open bundle to export", tool.name)))?;Ok(json!({ "platform_action": "export_open", "kit": kit, "name": tool.name }))}/// The list a deck stands on, from its view (`<tool>/group:<id>`): the tool/// and the list's id; None for any other deck.fn list_of(view: Option<&str>) -> Option<(&str, &str)> {let (tool, id) = view?.split_once('/')?; id.strip_prefix(LIST_VIEW).filter(|id| !id.is_empty()).map(|id| (tool, id))}/// A list's own acts (see the module's header), in the `lists` set's/// words: on its deck or its held tile, or — with `held`, the record of a/// card held on its deck — the card's moves along it in the list's own./// None on any other deck, nor for a list no longer here.pubfn list_acts(client: &ClientController, view: Option<&str>, held: Option<&str>) -> Result<Vec<Value>, MethodError> {letSome((tool, group)) = list_of(view) else { returnOk(Vec::new()) };use cotton_tools::mcp::handlers::tables::groups;letmut found = None; client .read_rows("tools.acts", &mut |ctx| {letSome((data, None)) = groups::group_of(ctx.read.driver(), group)? else { returnOk(Value::Null) };let table = data.get("table").and_then(Value::as_str).unwrap_or_default().to_string();let lists = groups::list_order(ctx, &table).map_err(|failure| failure.to_string())?;let members = groups::member_order(ctx, group).map_err(|failure| failure.to_string())?;// The table's own first act, where a list plays (a list of songs).let plays = if table == super::songs::SONG_TABLE {let definition = cotton_tools::mcp::handlers::tables::definition(ctx, &table).map_err(|failure| failure.to_string())?; definition.commands.iter().flatten().find(|command| command.id == "play").map(|command| (command.label.clone(), command.object.clone())) } else {None }; found = Some((data, table, lists, members, plays));Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;letSome((data, _table, lists, members, plays)) = found else { returnOk(Vec::new()) };let name = groups::name_of(&data).to_string();let entry = |act: &str, label: String| json!({"id": act, "label": label, "kind": "tool", "tool": tool, "group": group});let said = |line: &str| list_line(line, &[]);letmut acts = Vec::new();// The table's own first act: a list of songs plays from its first (a// card held on it plays from itself, by its own Play: `list_plays`).ifletSome((label, object)) = plays.filter(|_| held.is_none() && !members.is_empty()) {letmut play = entry(LIST_PLAY, label);ifletSome(object) = object { play["icon"] = json!(format!("act-{object}")); } acts.push(play); }letmut rename = entry(LIST_RENAME, said("list.rename")?); rename["words"] = json!({"prefill": name, "hint": said("list.name")?}); acts.push(rename); acts.push(entry(LIST_SET_PICTURE, said("group.set_picture")?));if data.get(groups::PICTURE).is_some_and(|picture| !picture.is_null()) { acts.push(entry(LIST_REMOVE_PICTURE, said("group.remove_picture")?)); }// Moves: the held card's along the list, else the list's among its table's.let (order, item, earlier, later) = match held {Some(record) => (&members, record, LIST_MEMBER_EARLIER, LIST_MEMBER_LATER),None => (&lists, group, LIST_MOVE_EARLIER, LIST_MOVE_LATER), };ifletSome(at) = order.iter().position(|id| id == item) {letmut moves = |act: &str, line: &str| -> Result<(), MethodError> {letmut move_entry = entry(act, said(line)?);ifletSome(record) = held { move_entry["record"] = json!(record); } acts.push(move_entry);Ok(()) };if at > 0 { moves(earlier, "list.move_earlier")?; }if at + 1 < order.len() { moves(later, "list.move_later")?; }ifletSome(record) = held {letmut off = entry(LIST_MEMBER_REMOVE, list_line("list.remove_from", &[("group", &name)])?); off["record"] = json!(record); acts.push(off); } }// RULE (Send, 13 Nov 2026): a list whose table has a `send` shape is sent from its held tile, a copy of// the list and its members to one of the person's people: Send's step on the list's own record.if held.is_none() {// The lists table as this database holds it (the object's definitions, synced): a database without it sends no list.letmut sendable = false; client .read_rows("tools.acts", &mut |ctx| {let tables = cotton_tools::definitions::shared_table_definitions(ctx).map_err(|failure| failure.to_string())?; sendable = tables.definitions.iter().any(|table| table.id == cotton_core::cotton_rules::open_bundle::LISTS && table.send.is_some());Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;if sendable {let label = cotton_core::rules::shell_lines::LineSet::shipped("editing").and_then(|lines| lines.say("acts.send", &[])).unwrap_or_default(); acts.push(json!({"id": "send", "label": label, "kind": "chooser", "step": "send", "icon": "act-send", "group": group, "table": cotton_core::cotton_rules::open_bundle::LISTS, "record": group})); } }letmut remove = entry(LIST_REMOVE, said("list.remove")?); remove["red"] = json!(true); remove["asks"] = json!(true); acts.push(remove);Ok(acts)}/// On a list's deck, a song's Play (the `play` command among the held/// card's `acts`) made the list's, played from that song.pubfn list_plays(view: Option<&str>, table: &str, record: &str, acts: &mutValue) {letSome((tool, group)) = list_of(view) else { return };if table != super::songs::SONG_TABLE {return; }for act in acts.as_array_mut().into_iter().flatten().filter(|act| act["id"] == "play" && act["kind"] == "command") { act["id"] = json!(LIST_PLAY); act["kind"] = json!("tool"); act["tool"] = json!(tool); act["group"] = json!(group); act["record"] = json!(record); }}/// A line of the shell's `lists` set.fn list_line(name: &str, values: &[(&str, &str)]) -> Result<String, MethodError> { cotton_core::rules::shell_lines::LineSet::shipped("lists") .and_then(|lines| lines.say(name, values)) .ok_or_else(|| MethodError::new("unreadable", format!("the lists set says no line {name}")))}/// `tools.act {act, group, record?, words?}` of a list's own act: Set/// picture answers the photo picker the phone opens for the list; Play/// plays the list from the song `record` (from its first without one),/// answered as `shell.player` answers it; Rename takes `words`, refused in/// the `lists` set's words when empty or another list of its table has the/// name; Add and Take out put the records picked (`records`) in the list/// or take them out; every other is one write of the list, answered with its/// receipt's words, the change that undoes it (`undo`) and that change whole/// (`change`), for a surface that wears its own receipt.fn list_act(client: &ClientController, act: &str, request: &Value) -> Result<Value, MethodError> {let group = request["group"].as_str().filter(|group| !group.is_empty()).ok_or_else(|| MethodError::new("bad_request", "a list's act names its list (`group`)"))?;let record = request["record"].as_str().filter(|record| !record.is_empty());let member = || record.ok_or_else(|| MethodError::new("bad_request", "a card's act on a list names the card (`record`)"));let picked = || -> Result<Value, MethodError> {let ids: Vec<&str> = request["records"].as_array().into_iter().flatten().filter_map(Value::as_str).filter(|id| !id.is_empty()).collect();if ids.is_empty() { returnErr(MethodError::new("bad_request", "a list's pick names the records picked (`records`)")); }Ok(json!(ids)) };let update = |change: Value| -> Result<Value, MethodError> {letmut asked = json!({ "id": group }); asked.as_object_mut().unwrap().extend(change.as_object().cloned().unwrap_or_default());super::records::call(client, "groups.update", &asked) };let answer = match act { LIST_SET_PICTURE => returnOk(json!({ "platform_action": "open_picker", "picker": "photos", "for": "list", "group": group })), LIST_PLAY => {letmut play = json!({ "op": "play", "table": super::shell_player::LIST, "id": group });ifletSome(from) = record { play["from"] = json!(from); }returnsuper::shell_player::call(client, &play); } LIST_RENAME => {let words = request["words"].as_str().map(str::trim).unwrap_or_default();if words.is_empty() {returnErr(MethodError::new("refused", list_line("list.name_empty", &[])?)); }if name_taken(client, group, words)? {returnErr(MethodError::new("refused", list_line("list.name_taken", &[("name", words)])?)); } update(json!({ "name": words }))? } LIST_REMOVE_PICTURE => update(json!({ (cotton_tools::mcp::handlers::tables::groups::PICTURE): null }))?, LIST_MOVE_EARLIER => update(json!({ "move": "earlier" }))?, LIST_MOVE_LATER => update(json!({ "move": "later" }))?, LIST_MEMBER_EARLIER => update(json!({ "move": "earlier", "record": member()? }))?, LIST_MEMBER_LATER => update(json!({ "move": "later", "record": member()? }))?, LIST_MEMBER_REMOVE => update(json!({ "remove": [member()?] }))?, LIST_ADD => update(json!({ "add": picked()? }))?, LIST_TAKE_OUT => update(json!({ "remove": picked()? }))?, _ => super::records::call(client, "groups.delete", &json!({ "id": group }))?, };let change = &answer["change"];Ok(json!({ "said": change["receipt"]["said"], "undo": change["id"], "change": change }))}/// Whether another live list of the same table as `group` is called `name`/// (letters' case aside); renaming a list to its own name is no clash.fn name_taken(client: &ClientController, group: &str, name: &str) -> Result<bool, MethodError> {use cotton_tools::mcp::handlers::tables::groups;letmut table = None; client .read_rows("tools.act", &mut |ctx| {ifletSome((data, _)) = groups::group_of(ctx.read.driver(), group)? { table = data.get("table").and_then(Value::as_str).map(str::to_string); }Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;match table {Some(table) => list_name_taken(client, &table, Some(group), name),None => Ok(false), }}/// Whether a live list of `table` other than `except` is called `name`/// (letters' case aside): a new list's name and a Rename are refused on it.pubfn list_name_taken(client: &ClientController, table: &str, except: Option<&str>, name: &str) -> Result<bool, MethodError> {use cotton_tools::mcp::handlers::tables::groups;letmut taken = false; client .read_rows("tools.act", &mut |ctx| {for other in groups::list_order(ctx, table).map_err(|failure| failure.to_string())?.iter().filter(|other| Some(other.as_str()) != except) {ifletSome((other, None)) = groups::group_of(ctx.read.driver(), other)? { taken |= groups::name_of(&other).to_lowercase() == name.to_lowercase(); } }Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;Ok(taken)}/// Whether an account act stands by its family's status.pub(crate) fn offered_account(act: &str, status: &Value) -> bool {let backs_up = status["backs_up"] == json!(true);let signed_in = status["signed_in"] == json!(true);// While a sign-in's rows go up (`backing_up`) the phone is signed in as// far as a person may act on it: Back up now says where it stands and// Sign out stops it; Sign in is not offered over a sign-in under way.let backing_up = status["backing_up"] == json!(true);match act { ACCOUNT_SIGN_IN => backs_up && !signed_in && !backing_up, ACCOUNT_BACK_UP | ACCOUNT_SIGN_OUT => backs_up && (signed_in || backing_up), _ => false, }}/// `tools.acts {table, view?}` — `{ actions }`: the acts of the tools owning/// `table` that stand now on the deck of `view` (`<tool>/<id>`), in/// a held card's tool acts' shape (kind `tool`). The Account card's acts are/// its view's (`<tool>/account`, `shell.account`).pubfn acts(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let bad = |why: &str| MethodError::new("bad_request", why);let table = request["table"].as_str().ok_or_else(|| bad("tools.acts takes the deck's table"))?;let view = match request.get("view") {None | Some(Value::Null) => None,Some(Value::String(view)) => Some(view.as_str()),Some(_) => returnErr(bad("tools.acts' view is `<tool>/<id>`")), };letmut definition = None; client .read_rows("tools.acts", &mut |ctx| { definition = Some(cotton_tools::mcp::handlers::tables::definition(ctx, table).map_err(|failure| failure.to_string())?);Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;let definition = definition.ok_or_else(|| bad("tools.acts names a table of this database"))?;if request.get("act").is_some() {returnErr(bad("tools.acts takes a table and its view")); }// A list's tile held on the fan's lists tier: the list's own acts alone.letmut actions = match request["held"].as_str() {Some("list") => Vec::new(),None => standing(client, &definition, view, "tools.acts")?,Some(_) => returnErr(bad("tools.acts' held is `list`, a list's tile held")), }; actions.extend(list_acts(client, view, None)?);letmut answer = json!({ "actions": actions });super::fan_tile::dress_acts(super::fan_tile::of_tools(&definition, &tools_of(client)?).as_ref(), &mut answer, "actions");Ok(answer)}/// This database's tools.fn tools_of(client: &ClientController) -> Result<Vec<ToolDefinition>, MethodError> { own_tools(client, "tools.acts")}/// This database's tools as this app draws their views: the tools its kit/// folds laid on its first ([`cotton_core::kit::AppKit::fold`]), the kit's/// account acts laid. What a deck reads its views from; an act is offered/// from and run on [`own_tools`].pub(crate) fn read_tools(client: &ClientController, method: &str) -> Result<Vec<ToolDefinition>, MethodError> {let kit = app_kit(client)?;letmut tools = Vec::new(); client .read_rows(method, &mut |ctx| { tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;ifletSome(kit) = kit.as_ref().filter(|kit| kit.folds_any()) {letmut tables = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?.definitions; kit.fold(&mut tables, &mut tools); }Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;ifletSome(kit) = &kit { kit.lay_acts(&mut tools); }Ok(tools)}/// This database's tools as stored, each its own (no tool folded into the/// app's first), with the kit's account acts laid: what an act is offered/// from and run on. RULE (owner, 11 Nov 2026): on the fan's one tier an act/// always runs on the tool of the view in view, never the first tool by the/// act's id; two tools may each define an act of one id.pub(crate) fn own_tools(client: &ClientController, method: &str) -> Result<Vec<ToolDefinition>, MethodError> {let kit = app_kit(client)?;letmut tools = Vec::new(); client .read_rows(method, &mut |ctx| { tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;ifletSome(kit) = &kit { kit.lay_acts(&mut tools); }Ok(tools)}/// `view` (`<tool>/<id>`) by the name its own tool gives it/// ([`unfolded_view`]): a view the app draws on its first tool's tier is its/// own tool's, and a tool's whole table is no view of it.fn own_view(client: &ClientController, view: Option<&str>) -> Result<Option<String>, MethodError> {letSome(named) = view else { returnOk(None) };Ok(match unfolded_view(client, &json!({ "view": named }))? {Some(asked) => asked["view"].as_str().map(str::to_string),None => Some(named.to_string()), })}/// The kit this phone's app keeps to ([`cotton_core::kit::AppKit::at`]); none is the whole object.pub(crate) fn app_kit(client: &ClientController) -> Result<Option<cotton_core::kit::AppKit>, MethodError> { cotton_core::kit::AppKit::at(client.layout().root()).map_err(|why| MethodError::new("unreadable", why))}/// `request` with its `view` named by its own tool, where the app's kit/// folds that view into its one tool ([`cotton_core::kit::AppKit::unfolded`]);/// none when the view is the tool's own or nothing is folded.pub(crate) fn unfolded_view(client: &ClientController, request: &Value) -> Result<Option<Value>, MethodError> {letSome(named) = request["view"].as_str().filter(|named| named.contains('/')) else { returnOk(None) };letSome(kit) = app_kit(client)?.filter(|kit| kit.folds_any()) else { returnOk(None) };letmut renamed = None; client .read_rows("records.list", &mut |ctx| {let tables = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;let tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|failure| failure.to_string())?.definitions; renamed = kit.unfolded(named, &tables, &tools);Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;Ok(renamed.map(|unfolded| {letmut asked = request.clone();match unfolded { cotton_core::kit::Unfolded::Named(name) => asked["view"] = json!(name), cotton_core::kit::Unfolded::Whole => { asked.as_object_mut().map(|asked| asked.remove("view")); } } asked }))}/// This database's tables as this app draws them: the views of the tools/// its kit folds laid on its one tool ([`cotton_core::kit::AppKit::fold`],/// Cotton People's Birthday wishes and Everyone on People). Read inside a/// read of the database; every other app's tables are as stored.pub(crate) fn folded_tables(kit: Option<&cotton_core::kit::AppKit>, ctx: &cotton_tools::mcp::dispatch::Ctx<'_>, tables: &mut [TableDefinition]) -> Result<(), String> {letSome(kit) = kit.filter(|kit| kit.folds_any()) else { returnOk(()) };letmut tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|failure| failure.to_string())?.definitions; kit.fold(tables, &mut tools);Ok(())}/// THE ONE RESOLUTION of a table's tool acts, a held card's (`shell.opened`)/// and an empty deck's (`tools.acts`): this database's tools, then/// [`for_table`] by each family's status, asked through the object's door.pubfn standing(client: &ClientController, table: &TableDefinition, view: Option<&str>, method: &str) -> Result<Vec<Value>, MethodError> {let tools = own_tools(client, method)?;let view = own_view(client, view)?;let view = view.as_deref();let door = client.object_door();Ok(for_table(table, &tools, view, |status| match status { ACCOUNT_STATUS => Some(account_status(client)), MUSIC_STATUS => music_status(client).ok(), CINEMAS_STATUS => cinemas_status(client).ok(), EXPORT_STATUS => Some(json!({})), KEYS_STATUS => Some(keys_status(client)), status => door.as_ref().and_then(|door| asked(door, status).ok()), }))}/// One family's status, asked of the object.fn asked(door: &ObjectDoor, status: &str) -> Result<Value, MethodError> {match status {"google.status" => super::google::over(door, status, &json!({})),"spotify.status" => super::spotify::over(door, status, &json!({})), other => Err(MethodError::new("bad_request", format!("`{other}` is no status this build asks"))), }}/// The acts of the tools owning `table` ([`owning`]) that stand now/// ([`offered`]). A family's status is asked once, and only where a tool/// owning the table offers an act of that family: any other table answers/// none, unasked.pubfn for_table(table: &TableDefinition, tools: &[ToolDefinition], view: Option<&str>, mut status: implFnMut(&'static str) -> Option<Value>) -> Vec<Value> {let owning = owning(table, tools);letmut statuses = Statuses::new();letmut asked = Vec::new();for family in owning.iter().flat_map(|tool| tool.runnable_acts().filter(|act| on_view(tool, act, view))).filter_map(|act| family(&act.id)) {if asked.contains(&family) {continue; } asked.push(family);ifletSome(answer) = status(family) { statuses.insert(family, answer); } } offered(&owning, &statuses, view)}/// Whether `act` stands on the deck of `view` (`<tool>/<id>`): an act a view/// of its tool names, only on that view's; any other, on every deck.////// RULE (owner, 11 Nov 2026): this phone's account acts — Sign in, Back up/// now, Sign out — stand on the Account card alone (`<tool>/account`,/// `shell.account`), in every app: never on a held card, never on a deck.fn on_view(tool: &ToolDefinition, act: &cotton_core::definitions::ToolAct, view: Option<&str>) -> bool {if cotton_core::kit::ACCOUNT_ACTS.contains(&act.id.as_str()) {return view.and_then(|view| view.split_once('/')).is_some_and(|(owner, id)| owner == tool.id && id == cotton_core::kit::ACCOUNT_CARD); }let named: Vec<&str> = tool.views.iter().filter(|candidate| candidate.acts.contains(&act.id)).map(|candidate| candidate.id.as_str()).collect();if named.is_empty() {returntrue; } view.and_then(|view| view.split_once('/')).is_some_and(|(owner, id)| owner == tool.id && named.contains(&id))}/// One act run through the door to the person's object.pubfn run(door: &ObjectDoor, act: &str, account: Option<&str>) -> Result<Value, MethodError> {match act { GOOGLE_CONNECT => opens(super::google::over(door, "google.connect", &json!({}))?), GOOGLE_DISCONNECT => super::google::over(door, "google.disconnect", &json!({ "account": account })), SPOTIFY_CONNECT => opens(super::spotify::over(door, "spotify.connect", &json!({}))?), SPOTIFY_DISCONNECT => super::spotify::over(door, "spotify.disconnect", &json!({})), other => Err(MethodError::new("bad_request", format!("`{other}` is no act this build runs"))), }}/// A connect's answer as the page the phone opens: the object's/// `authorizeUrl`, and only an https one.fn opens(answer: Value) -> Result<Value, MethodError> {let opens = answer["authorizeUrl"] .as_str() .filter(|url| url.starts_with("https://")) .ok_or_else(|| MethodError::new("unreadable", "the object answered no page to open"))?;Ok(json!({ "opens": opens }))}/// The tools that own `table` (`tool_views::owns`), each with its acts.pubfn owning<'a>(table: &TableDefinition, tools: &'a [ToolDefinition]) -> Vec<&'a ToolDefinition> { tools .iter() .filter(|tool| !tool.acts.is_empty() && super::tool_views::owns(&tool.id, table, tools)) .collect()}/// The acts of `tools` that stand now, as the fan's entries, each by its/// family's status in `statuses` (missing: it could not be read, and none of/// that family's acts stands).pubfn offered(tools: &[&ToolDefinition], statuses: &Statuses, view: Option<&str>) -> Vec<Value> {letmut fan = Vec::new();for tool in tools {for act in tool.runnable_acts().filter(|act| on_view(tool, act, view)) {letSome(status) = family(&act.id).and_then(|family| statuses.get(family)) else { continue };// Its picture, where the tool paints it (`object`): the fan's tile.let entry = |label: String| {letmut entry = json!({"id": act.id, "label": label, "kind": "tool", "tool": tool.id, "asks": act.asks});ifletSome(object) = &act.object { entry["icon"] = json!(format!("act-{object}")); } entry };let available = status["available"] == json!(true);match act.id.as_str() { GOOGLE_CONNECT if available && status["accounts"].as_array().is_none_or(Vec::is_empty) => fan.push(entry(act.label.clone())), GOOGLE_DISCONNECT => {for account in status["accounts"].as_array().into_iter().flatten() {letSome(email) = account["googleEmail"].as_str() else { continue };// The account and how its calendar stands, in the object's own words.letmut item = entry(said(&act.label, email, account["calendar"]["phase"].as_str())); item["account"] = json!(email); fan.push(item); } } SPOTIFY_CONNECT if available && status["account"].is_null() => fan.push(entry(act.label.clone())), SPOTIFY_DISCONNECT => {let account = &status["account"];// Who is connected, by the name Spotify gives them; an// account with no display name is named by its id.letSome(who) = account["displayName"].as_str().filter(|name| !name.is_empty()).or_else(|| account["userId"].as_str()) else { continue }; fan.push(entry(said(&act.label, who, account["phase"].as_str()))); } ACCOUNT_SIGN_IN | ACCOUNT_BACK_UP | ACCOUNT_SIGN_OUT if offered_account(&act.id, status) => fan.push(entry(act.label.clone())),// Its label says how this phone keeps now, in the music set's words. MUSIC_KEEP_EVERYTHING => {let on = status["keep_everything"] == json!(true);let said = super::songs::line(if on { "acts.keep_everything_on" } else { "acts.keep_everything_off" }, &[]).unwrap_or_else(|_| act.label.clone());letmut item = entry(said); item["on"] = json!(on); fan.push(item); } CINEMAS_KEEP_EVERYTHING | CINEMAS_CELLULAR => {let (column, words) = if act.id == CINEMAS_CELLULAR { ("cellular", ("keep.cellular_on", "keep.cellular_off")) } else { ("keep_everything", ("acts.keep_everything_on", "acts.keep_everything_off")) };let on = status[column] == json!(true);let said = super::film_player::line(if on { words.0 } else { words.1 }, &[]).unwrap_or_else(|_| act.label.clone());letmut item = entry(said); item["on"] = json!(on); fan.push(item); }// Its label says the budget now, in the cinemas set's words. CINEMAS_BUDGET => {let gb = status["budget_gb"].as_u64().and_then(|gb| u32::try_from(gb).ok()).unwrap_or(super::films::BUDGETS_GB[0]); fan.push(entry(super::films::budget_said(gb).unwrap_or_else(|_| act.label.clone()))); } EXPORT_LIBRARY if export_kit(&tool.id).is_some() => fan.push(entry(act.label.clone())),// Where this build ships the system's providers (the Keys app on Android). KEYS_TURN_ON if status["provider_settings"] == json!(true) => fan.push(entry(act.label.clone())), _ => {} } } } fan}/// A disconnect's label: the act's own, then whose account and how it/// stands, in the object's words.fn said(label: &str, who: &str, phase: Option<&str>) -> String {match phase.filter(|phase| !phase.is_empty()) {Some(phase) => format!("{label} ({who}, {phase})"),None => format!("{label} ({who})"), }}#[cfg(test)]#[path = "tool_acts_tests.rs"]mod tests;