//! One receipt-bearing row per accepted UI event, always in the personal database. use crate::{handle::CottonHandle, methods::MethodError}; use cotton_store::link_rule::FileKind; use cotton_tools::mcp::handlers::common::now_iso; use serde_json::{json, Value}; pub fn record(handle: &CottonHandle, request: &Value) -> Result { record_with_client(&handle.client(), request) } fn record_with_client( client: &crate::shell::client::ClientController, request: &Value, ) -> Result { let _personal = client .name_database(None) .map_err(|e| MethodError::new("write_refused", e))?; let text = |key: &str| { request[key] .as_str() .filter(|s| !s.is_empty()) .map(str::to_owned) .ok_or_else(|| MethodError::new("bad_request", format!("usage.record needs {key}"))) }; let id = text("id")?; let kind = text("kind")?; if !["view_opened", "record_opened", "act_fired", "search"].contains(&kind.as_str()) { return Err(MethodError::new("bad_request", "unknown usage kind")); } let tool = text("tool")?; let view = text("view")?; let device = client.self_device_id().ok_or_else(|| { MethodError::new("no_device_identity", "Usage needs this device's identity") })?; client.write_rows("usage.record", &mut |ctx| { if ctx.file_kind().map_err(|e|e.to_string())? != FileKind::Personal { return Err("usage belongs to the personal database".into()); } if ctx.db().get("SELECT id FROM cotton_usage WHERE id=?",&[id.clone().into()]).map_err(|e|e.to_string())?.is_some() { return Ok(json!({"recorded":true,"id":id})); } let at = now_iso(ctx); if let Some(earlier) = same_open_just_before(ctx.db(), &device, &kind, &tool, &view, request.get("record").and_then(Value::as_str), &at).map_err(|e|e.to_string())? { return Ok(json!({"recorded":false,"id":earlier,"repeat":true})); } let patch = json!({"id":id,"workspace_id":ctx.workspace_id,"device":device,"kind":kind,"tool":tool,"view":view,"record":request.get("record").cloned().unwrap_or(Value::Null),"at":at,"record_byline":"user"}); ctx.writer().map_err(|e|e.to_string())?.upsert("cotton_usage",&id,patch.as_object().unwrap().clone()); Ok(json!({"recorded":true,"id":id})) }).map(crate::authoring::own_answer) .map_err(|why|MethodError::new("write_refused",why)) } /// How many opens Recent shows when its part does not say. const RECENT_LIMIT: i64 = 30; /// The person's last opens, newest first, ONE per target: a tool page by its /// view, a record by its tool and id. Only opens count — an act or a search /// is not a place the person went. pub fn recent(db: &cotton_store::Driver, workspace_id: &str, args: &serde_json::Map) -> Result { let limit = args.get("limit").and_then(Value::as_i64).filter(|n| *n > 0).unwrap_or(RECENT_LIMIT); let rows = db .all( "SELECT kind, tool, view, record, MAX(at) AS at FROM cotton_usage \ WHERE workspace_id = ? AND kind IN ('view_opened', 'record_opened') \ GROUP BY kind, CASE kind WHEN 'record_opened' THEN tool || '/' || coalesce(record, '') ELSE view END \ ORDER BY at DESC, view ASC", &[workspace_id.to_owned().into()], ) .map_err(|e| e.to_string())?; let visits: Vec = rows .iter() .take(usize::try_from(limit).unwrap_or(usize::MAX)) .map(|row| { let record = row.text("kind") == Some("record_opened"); json!({ "target": if record { "record" } else { "tool" }, "tool": row.text("tool"), "view": row.text("view"), "record": if record { row.text("record") } else { None }, "at": row.text("at"), }) }) .collect(); Ok(json!({ "visits": visits })) } /// A return to the same page within this long is the same visit, not a new one. const SAME_VISIT_MS: i64 = 5_000; /// The open this one repeats: the same device opening the same tool page or /// record within [`SAME_VISIT_MS`] of its last open of it. Acts and searches /// are never folded — each is its own event. fn same_open_just_before( db: &cotton_store::Driver, device: &str, kind: &str, tool: &str, view: &str, record: Option<&str>, at: &str, ) -> Result, cotton_store::StoreError> { if !["view_opened", "record_opened"].contains(&kind) { return Ok(None); } let Some(last) = db.get( "SELECT id, at FROM cotton_usage WHERE device=? AND kind=? AND tool=? AND view=? AND coalesce(record,'')=? ORDER BY at DESC LIMIT 1", &[device.to_owned().into(), kind.to_owned().into(), tool.to_owned().into(), view.to_owned().into(), record.unwrap_or_default().to_owned().into()], )? else { return Ok(None); }; let ms = |text: &str| chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis()); let (Some(then), Some(now)) = (last.text("at").and_then(ms), ms(at)) else { return Ok(None); }; Ok((now - then < SAME_VISIT_MS).then(|| last.text("id").unwrap_or_default().to_owned())) } #[cfg(test)] mod tests { use super::*; /// RULE: Each accepted open or act creates one receipt-bearing usage row; retrying its event id cannot inflate usage, on the same core used by phone and Mac. #[test] fn one_usage_row_per_event_despite_retries() { let (_dir, client) = crate::shell::client::phone_tests::attached(); client.with_writer(|replica| { replica.driver.run("UPDATE cotton_workspaces SET kind='personal' WHERE id=?",&[replica.workspace_id.to_string().into()]).map_err(|e|e.to_string())?; crate::fixture::receipted(replica.driver,"UPDATE cotton_workspaces SET kind='personal'"); Ok(()) }).unwrap(); let waiting = client.with_writer(|replica| { cotton_store::outbox::pending_count(replica.driver).map_err(|e| e.to_string()) }).unwrap(); let mut expected = Vec::new(); for kind in ["view_opened", "record_opened", "act_fired"] { let id = format!("invented-{kind}"); let event = json!({"id":id,"kind":kind,"tool":"todos","view":"tool/todos","record":"invented-todo"}); record_with_client(&client, &event).unwrap(); record_with_client(&client, &event).unwrap(); expected.push(id); } expected.sort(); let ids = client .with_writer(|replica| { let rows = replica .driver .all("SELECT id,_hlc FROM cotton_usage ORDER BY id", &[]) .map_err(|e| e.to_string())?; assert!(rows .iter() .all(|r| r.text("_hlc").is_some_and(|hlc| !hlc.is_empty()))); Ok(rows .iter() .map(|r| r.text("id").unwrap().to_string()) .collect::>()) }) .unwrap(); assert_eq!(ids, expected); assert_eq!(client.with_writer(|replica| { cotton_store::outbox::pending_count(replica.driver).map_err(|e| e.to_string()) }).unwrap(), waiting, "usage receipts stay on this phone, outside changes waiting to send"); } /// RULE: One visit per target per open — a return to the same page within 5 s is the same visit, so back-and-forth never inflates History or Home's counts; later it is a new one. #[test] fn a_return_within_five_seconds_is_the_same_visit() { let (_dir, client) = crate::shell::client::phone_tests::attached(); client.with_writer(|replica| { replica.driver.run("UPDATE cotton_workspaces SET kind='personal' WHERE id=?",&[replica.workspace_id.to_string().into()]).map_err(|e|e.to_string())?; crate::fixture::receipted(replica.driver,"UPDATE cotton_workspaces SET kind='personal'"); Ok(()) }).unwrap(); let open = |id: &str| record_with_client(&client, &json!({"id":id,"kind":"record_opened","tool":"todos","view":"tool/todos","record":"invented-todo"})).unwrap(); assert_eq!(open("invented-first")["recorded"], true); let again = open("invented-back"); assert_eq!((again["recorded"].clone(), again["id"].clone()), (json!(false), json!("invented-first"))); let other = record_with_client(&client, &json!({"id":"invented-other","kind":"record_opened","tool":"todos","view":"tool/todos","record":"invented-todo-2"})).unwrap(); assert_eq!(other["recorded"], true, "another record is another visit"); client.with_writer(|replica| { replica.driver.run("UPDATE cotton_usage SET at='2000-01-01T00:00:00.000Z'",&[]).map_err(|e|e.to_string()) }).unwrap(); assert_eq!(open("invented-later")["recorded"], true, "after 5 s it is a new visit"); let count = client.with_writer(|replica| Ok(replica.driver.get("SELECT count(*) AS n FROM cotton_usage",&[]).map_err(|e|e.to_string())?.and_then(|r|r.int("n")))).unwrap(); assert_eq!(count, Some(3)); } /// RULE: Recent is one entry per target, newest first — a page opened ten times is one tile, and acts or searches are not places the person went. #[test] fn recent_is_one_per_target_newest_first() { let (_dir, client) = crate::shell::client::phone_tests::attached(); client.with_writer(|replica| { let ws = replica.workspace_id.to_string(); for (id, kind, tool, view, record, at) in [ ("a", "view_opened", "todos", "tool/todos", None, "2026-10-01T09:00:00.000Z"), ("b", "record_opened", "notes", "tool/notes", Some("invented-note"), "2026-10-01T10:00:00.000Z"), ("c", "view_opened", "todos", "tool/todos", None, "2026-10-01T11:00:00.000Z"), ("d", "act_fired", "money", "tool/money", Some("invented-tx"), "2026-10-01T12:00:00.000Z"), ("e", "record_opened", "notes", "tool/notes", Some("invented-other"), "2026-10-01T08:00:00.000Z"), ] { replica.driver.run("INSERT INTO cotton_usage(id,workspace_id,device,kind,tool,view,record,at) VALUES(?,?,'invented-device',?,?,?,?,?)", &[id.to_owned().into(), ws.clone().into(), kind.to_owned().into(), tool.to_owned().into(), view.to_owned().into(), record.map(str::to_owned).into(), at.to_owned().into()]).map_err(|e|e.to_string())?; } let answer = recent(replica.driver, &ws, &serde_json::Map::new())?; let seen: Vec<(String, String)> = answer["visits"].as_array().unwrap().iter() .map(|v| (v["target"].as_str().unwrap().to_owned(), v["record"].as_str().unwrap_or(v["view"].as_str().unwrap()).to_owned())) .collect(); assert_eq!(seen, vec![ ("tool".into(), "tool/todos".into()), ("record".into(), "invented-note".into()), ("record".into(), "invented-other".into()), ]); assert_eq!(answer["visits"][0]["at"], "2026-10-01T11:00:00.000Z", "the newest open of a target stands for it"); Ok(()) }).unwrap(); } /// RULE: Unknown usage kinds are refused before writing; arbitrary telemetry must not become personal records. #[test] fn unknown_events_are_refused() { let (_dir, client) = crate::shell::client::phone_tests::attached(); let refused = record_with_client( &client, &json!({"id":"invented-event","kind":"screen_dump","tool":"todos","view":"tool/todos"}), ) .unwrap_err(); assert_eq!(refused.code, "bad_request"); } }