//! A device's own settings, written by the app on that device's settings page //! (architect, 21 Oct 2026: a device setting is written by the app, never //! through a drawn table). Each writer validates its value, then writes the //! cell on every live row this file holds for the device. use super::device_words::approval_for; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{update_row, Valid}; use crate::mcp::protocol::ToolFailure; use cotton_core::records::Data; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; /// The live approval this database holds for `device_id`, refused when it /// holds none or only a revoked one. fn live_approval(ctx: &Ctx<'_>, device_id: &str) -> Valid { let Some(row) = approval_for(ctx, device_id)? else { return Err(ToolFailure::new("That device is not in this database")); }; let live = ctx .read .driver() .get( "SELECT revoked_at, platform FROM cotton_devices WHERE workspace_id = ? AND id = ?", &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(row)], ) .map_err(|error| ToolFailure::new(error.to_string()))?; live.filter(|found| found.text("revoked_at").is_none()) .ok_or_else(|| ToolFailure::new("That device is revoked; it joins again by pairing")) } /// Write `patch` on every live row of the device in this file. A setting /// belongs to the device while each approval keeps its own database identity, /// so the writer never stamps this database onto another row. fn write_live_rows(ctx: &mut Ctx<'_>, device_id: &str, patch: &Map) -> Valid<()> { let live_rows = ctx .read .driver() .all( "SELECT id, workspace_id FROM cotton_devices WHERE device_id = ? AND revoked_at IS NULL", &[SqlValue::Text(device_id.to_string())], ) .map_err(|error| ToolFailure::new(error.to_string()))?; for live in &live_rows { let id = live.text("id").ok_or_else(|| ToolFailure::new("Device row has no id"))?; let workspace = live .text("workspace_id") .ok_or_else(|| ToolFailure::new("Device row has no database"))?; let mut shared = patch.clone(); shared.insert("workspace_id".into(), Value::from(workspace)); update_row(ctx, "cotton_devices", id, shared)?; ctx.commit().map_err(|error| { ToolFailure::new(format!("Device setting could not be written in database {workspace}: {error}")) })?; } super::verify_device_settings(ctx.db(), device_id, &Data::from_iter(patch.clone())) } /// A Mac's Files choice: `everything` or `rows_only`. pub fn write_keep_bytes(ctx: &mut Ctx<'_>, device_id: &str, rule: &Value) -> Valid<()> { if !matches!(rule.as_str(), Some("everything" | "rows_only")) { return Err(ToolFailure::new("Files is everything or rows_only; it cannot be cleared")); } if live_approval(ctx, device_id)?.text("platform") != Some("mac") { return Err(ToolFailure::new("Files is a Mac's choice")); } write_live_rows(ctx, device_id, &Map::from_iter([("keep_bytes".to_string(), rule.clone())])) }