diff --git a/crates/capri-tools/src/time.rs b/crates/capri-tools/src/time.rs new file mode 100644 index 0000000..228e458 --- /dev/null +++ b/crates/capri-tools/src/time.rs @@ -0,0 +1,568 @@ +//! `time_control`: persistent reminders, timers and stopwatches in +//! `/desktop/time.sqlite` (Capri schema), a 500 ms scheduler with an at-least-once outbox, +//! and the reminder notification/speech texts. +use std::collections::HashMap; +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::{anyhow, bail, Context, Result}; +use async_trait::async_trait; +use capri_agent::tools::{Tool, ToolContext}; +use chrono::{DateTime, Local, NaiveDateTime, TimeZone, Utc}; +use parking_lot::Mutex; +use rusqlite::{params, Connection, OptionalExtension}; +use serde_json::{json, Value}; +use tokio::sync::mpsc::UnboundedSender; + +use crate::{fingerprint, sha256_hex, ToolEvent}; + +const ACTIONS: [&str; 11] = ["clock", "list", "remind", "timer", "stopwatch", "status", "pause", "resume", "reset", "cancel", "snooze"]; +const YEAR_MS: f64 = 366.0 * 86_400_000.0; + +struct Run { + tick: f64, + elapsed: f64, + remaining: Option, +} + +type Clock = Box f64 + Send + Sync>; + +pub struct TimeService { + db: Mutex, + running: Mutex>, + events: UnboundedSender, + closed: AtomicBool, + ticking: tokio::sync::Mutex<()>, + /// Wall clock and monotonic clock in ms (injectable for tests). + now: Clock, + mono: Clock, +} + +fn wall_ms() -> f64 { + Utc::now().timestamp_millis() as f64 +} + +fn mono_ms() -> f64 { + static START: std::sync::LazyLock = std::sync::LazyLock::new(Instant::now); + START.elapsed().as_secs_f64() * 1000.0 +} + +/// IANA name of the system time zone (`TZ`, else the `/etc/localtime` link). +fn time_zone() -> String { + std::env::var("TZ") + .ok() + .filter(|tz| !tz.is_empty()) + .or_else(|| { + let link = std::fs::read_link("/etc/localtime").ok()?; + Some(link.to_string_lossy().split_once("zoneinfo/")?.1.to_string()) + }) + .unwrap_or_else(|| "UTC".into()) +} + +/// Absolute reminder time: an instant with `Z`/offset, or a local time that must exist exactly once. +pub fn reminder_instant(value: &str, zone: &Tz) -> Result { + if value.chars().count() > 80 { + bail!("Choose an exact reminder date and time."); + } + let invalid = || anyhow!("The reminder time is invalid or ambiguous in your time zone. Please choose an exact time."); + let offset = regex::Regex::new(r"(?:Z|[+-]\d\d:\d\d)$").unwrap(); + if offset.is_match(value) { + let value = value.strip_suffix('Z').map_or(value.to_string(), |v| format!("{v}+00:00")); + return ["%Y-%m-%dT%H:%M%:z", "%Y-%m-%dT%H:%M:%S%:z", "%Y-%m-%dT%H:%M:%S%.f%:z"] + .iter() + .find_map(|f| DateTime::parse_from_str(&value, f).ok()) + .map(|d| d.timestamp_millis() as f64) + .ok_or_else(invalid); + } + let local = ["%Y-%m-%dT%H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S%.f"] + .iter() + .find_map(|f| NaiveDateTime::parse_from_str(value, f).ok()) + .ok_or_else(invalid)?; + match zone.from_local_datetime(&local) { + chrono::LocalResult::Single(d) => Ok(d.timestamp_millis() as f64), + _ => Err(invalid()), + } +} + +fn duration(value: &Value) -> Result { + let s = value.as_f64().unwrap_or(f64::NAN); + if !s.is_finite() || !(1.0..=366.0 * 86400.0).contains(&s) || (s * 1000.0).fract() != 0.0 { + bail!("Choose a duration between one second and one year."); + } + Ok(s * 1000.0) +} + +fn hms(seconds: i64) -> String { + format!("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60) +} + +/// Spoken reminder text (conversation language translation is the app's job). +pub fn reminder_speech(object: &Value) -> String { + match object["title"].as_str().filter(|t| !t.is_empty()) { + Some(title) => format!("Choom, your reminder: {title}"), + None => "Timer finished.".into(), + } +} + +/// Desktop notification (summary, body). On a locked session the body hides the reminder text. +pub fn reminder_notification(object: &Value, locked: bool) -> (String, String) { + let body = if locked { "Reminder".into() } else { object["title"].as_str().filter(|t| !t.is_empty()).unwrap_or("Timer finished.").into() }; + ("Capri · Reminder".into(), body) +} + +/// Shows a desktop notification through `org.freedesktop.Notifications` (KDE and i3 notification daemons). +pub async fn notify(summary: &str, body: &str) -> Result { + let connection = zbus::Connection::session().await?; + let hints: HashMap<&str, zbus::zvariant::Value> = HashMap::from([("suppress-sound", true.into())]); + let reply = connection + .call_method( + Some("org.freedesktop.Notifications"), + "/org/freedesktop/Notifications", + Some("org.freedesktop.Notifications"), + "Notify", + &("Capri", 0u32, "capri", summary, body, Vec::<&str>::new(), hints, -1i32), + ) + .await?; + Ok(reply.body().deserialize()?) +} + +impl TimeService { + pub fn open(file: &Path, events: UnboundedSender) -> Result { + Self::with_clocks(file, events, Box::new(wall_ms), Box::new(mono_ms)) + } + + fn with_clocks(file: &Path, events: UnboundedSender, now: Clock, mono: Clock) -> Result { + for ancestor in file.ancestors() { + if std::fs::symlink_metadata(ancestor).is_ok_and(|m| m.file_type().is_symlink()) { + bail!("Time storage must not be linked."); + } + } + std::fs::create_dir_all(file.parent().context("Invalid time storage")?)?; + let db = Connection::open(file)?; + db.execute_batch( + "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1500; + CREATE TABLE IF NOT EXISTS clocks(id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL, state TEXT NOT NULL, due REAL, elapsed REAL NOT NULL DEFAULT 0, started REAL, relative INTEGER NOT NULL DEFAULT 0); + CREATE TABLE IF NOT EXISTS time_calls(id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, result TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS time_outbox(id TEXT PRIMARY KEY, object_id TEXT NOT NULL, due REAL NOT NULL, state TEXT NOT NULL);", + )?; + let (wall, tick) = (now(), mono()); + let mut running = HashMap::new(); + { + // Time spent closed counts: missed items fire at the next launch. + let mut stmt = db.prepare("SELECT id, elapsed, started, due FROM clocks WHERE state='running'")?; + let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, f64>(1)?, r.get::<_, Option>(2)?, r.get::<_, Option>(3)?)))?; + for (id, elapsed, started, due) in rows.flatten() { + let remaining = due.map(|d| (d - wall).max(0.0)); + running.insert(id, Run { tick, elapsed: elapsed + (wall - started.unwrap_or(wall)).max(0.0), remaining }); + } + } + Ok(Self { db: Mutex::new(db), running: Mutex::new(running), events, closed: AtomicBool::new(false), ticking: Default::default(), now, mono }) + } + + /// Every object (≤2000), active first, newest first, with live elapsed/remaining values. + pub fn snapshot(&self) -> Vec { + let (wall, tick) = ((self.now)(), (self.mono)()); + let db = self.db.lock(); + let running = self.running.lock(); + let Ok(mut stmt) = db.prepare( + "SELECT id,kind,title,created,updated,state,due,elapsed,relative FROM clocks ORDER BY CASE WHEN state IN ('running','paused') THEN 0 WHEN state='due' THEN 1 ELSE 2 END, created DESC LIMIT 2000", + ) else { + return vec![]; + }; + let rows = stmt.query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)?, r.get::<_, i64>(4)?, + r.get::<_, String>(5)?, r.get::<_, Option>(6)?, r.get::<_, f64>(7)?, r.get::<_, i64>(8)?)) + }); + let Ok(rows) = rows else { return vec![] }; + rows.flatten() + .map(|(id, kind, title, created, updated, state, due, elapsed, relative)| { + let run = running.get(&id); + let delta = run.map_or(0.0, |r| (tick - r.tick).max(0.0)); + let elapsed_ms = run.map_or(elapsed, |r| r.elapsed + delta); + let seconds = (elapsed_ms / 1000.0).floor().max(0.0) as i64; + let remaining = match (state.as_str(), due) { + ("running", Some(due)) => Some(match run { + Some(r) if relative == 1 => r.remaining.unwrap_or(0.0) - delta, + _ => due - wall, + } + .max(0.0)), + ("paused", Some(due)) => Some(due), + _ => None, + }; + json!({"id": id, "kind": kind, "title": title, "state": state, "createdAt": created, "dueAt": due, + "elapsedMs": elapsed_ms, "elapsedSeconds": seconds, "displayElapsed": hms(seconds), + "sampledAt": wall, "clockRevision": updated, "remainingMs": remaining}) + }) + .collect() + } + + fn select(&self, id: Option<&str>) -> Result { + let rows: Vec = self + .snapshot() + .into_iter() + .filter(|r| !["cancelled", "acknowledged"].contains(&r["state"].as_str().unwrap_or("")) && id.is_none_or(|id| r["id"] == id)) + .collect(); + match rows.len() { + 1 => Ok(rows.into_iter().next().unwrap()), + 0 => bail!("No matching timer, reminder or stopwatch is active."), + _ => bail!("There are several timers or reminders. Choose one by ID or name."), + } + } + + /// Runs one command; mutations are idempotent per `call_id` (also used by the timers panel). + pub fn execute(&self, call_id: &str, args: &Value) -> Result { + if self.closed.load(Ordering::SeqCst) { + bail!("The time service is closed."); + } + let map = args.as_object().filter(|m| m.keys().all(|k| ["action", "id", "title", "seconds", "at"].contains(&k.as_str()))); + let action = map.and_then(|m| m.get("action")).and_then(Value::as_str).filter(|a| ACTIONS.contains(a)); + let call_ok = regex::Regex::new("^[a-zA-Z0-9:_-]{1,160}$").unwrap().is_match(call_id); + let (Some(_), Some(action), true) = (map, action, call_ok) else { bail!("Invalid time command.") }; + let id = match args.get("id") { + None => None, + Some(v) => Some(v.as_str().filter(|s| regex::Regex::new("^[a-f0-9-]{36}$").unwrap().is_match(s)).context("Invalid timer ID.")?), + }; + let fp = fingerprint(args); + match action { + "clock" => { + let now = Local::now(); + return Ok(json!({"ok": true, "now": now.with_timezone(&Utc).to_rfc3339_opts(chrono::SecondsFormat::Millis, true), + "local": now.format("%Y-%m-%d %H:%M:%S").to_string(), "timeZone": time_zone()})); + } + "list" => return Ok(json!({"ok": true, "objects": self.snapshot()})), + "status" => { + return Ok(match id { + Some(_) => { + let mut object = self.select(id)?; + object["ok"] = true.into(); + object + } + None => json!({"ok": true, "objects": self.snapshot().into_iter().filter(|r| ["running", "paused", "due"].contains(&r["state"].as_str().unwrap_or(""))).collect::>()}), + }); + } + _ => {} + } + { + let db = self.db.lock(); + let prior: Option<(String, String)> = + db.query_row("SELECT fingerprint, result FROM time_calls WHERE id=?", [call_id], |r| Ok((r.get(0)?, r.get(1)?))).optional()?; + if let Some((prior_fp, result)) = prior { + if prior_fp != fp { + bail!("An operation ID cannot change its command."); + } + return Ok(serde_json::from_str(&result)?); + } + let count: i64 = db.query_row("SELECT count(*) FROM time_calls", [], |r| r.get(0))?; + if count >= 10_000 { + bail!("The time operation journal is full."); + } + } + let create = ["remind", "timer", "stopwatch"].contains(&action); + if !create && (args.get("at").is_some() || args.get("title").is_some() || (args.get("seconds").is_some() && action != "snooze")) { + bail!("Unexpected time command arguments."); + } + let existing = if create { None } else { Some(self.select(id)?) }; + let snapshot = self.snapshot(); + let (wall, tick) = ((self.now)(), (self.mono)()); + let mut db = self.db.lock(); + let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + let mut next_run = None; + let object_id; + if let Some(object) = existing { + object_id = object["id"].as_str().unwrap_or_default().to_string(); + let (state, kind) = (object["state"].as_str().unwrap_or(""), object["kind"].as_str().unwrap_or("")); + let (elapsed, remaining) = (object["elapsedMs"].as_f64().unwrap_or(0.0), object["remainingMs"].as_f64()); + match action { + "pause" => { + if state != "running" || kind == "reminder" { + bail!("Only a running timer or stopwatch can be paused."); + } + tx.execute("UPDATE clocks SET state='paused',elapsed=?,due=?,started=NULL,updated=? WHERE id=?", params![elapsed, remaining, wall as i64, object_id])?; + } + "resume" => { + if state != "paused" { + bail!("This object is not paused."); + } + tx.execute("UPDATE clocks SET state='running',due=?,started=?,updated=? WHERE id=?", params![remaining.map(|r| wall + r), wall, wall as i64, object_id])?; + next_run = Some(Run { tick, elapsed, remaining }); + } + "reset" => { + if kind != "stopwatch" || !["running", "paused"].contains(&state) { + bail!("Only an active stopwatch can be reset."); + } + tx.execute("UPDATE clocks SET elapsed=0,started=?,updated=? WHERE id=?", params![(state == "running").then_some(wall), wall as i64, object_id])?; + next_run = (state == "running").then_some(Run { tick, elapsed: 0.0, remaining: None }); + } + "cancel" => { + tx.execute("UPDATE clocks SET state='cancelled',elapsed=?,started=NULL,updated=? WHERE id=?", params![elapsed, wall as i64, object_id])?; + tx.execute("UPDATE time_outbox SET state='cancelled' WHERE object_id=? AND state='pending'", [&object_id])?; + } + _ => { + if kind == "stopwatch" { + bail!("A stopwatch cannot be snoozed."); + } + let remaining = duration(args.get("seconds").unwrap_or(&json!(300)))?; + tx.execute("UPDATE clocks SET state='running',relative=1,due=?,elapsed=0,started=?,updated=? WHERE id=?", params![wall + remaining, wall, wall as i64, object_id])?; + tx.execute("UPDATE time_outbox SET state='cancelled' WHERE object_id=? AND state='pending'", [&object_id])?; + next_run = Some(Run { tick, elapsed: 0.0, remaining: Some(remaining) }); + } + } + } else { + if snapshot.iter().filter(|r| ["running", "paused"].contains(&r["state"].as_str().unwrap_or(""))).count() >= 1000 { + bail!("Too many active reminders."); + } + if id.is_some() { + bail!("A new timer receives its own ID."); + } + let title = match args.get("title") { + None => "", + Some(t) => t + .as_str() + .filter(|t| capri_core::utf16_len(t) <= 1000 && !t.chars().any(|c| matches!(c, '\x00'..='\x08' | '\x0b' | '\x0c' | '\x0e'..='\x1f'))) + .context("Invalid reminder text.")?, + } + .trim(); + let (at, seconds) = (args.get("at"), args.get("seconds")); + if action == "remind" && title.is_empty() { + bail!("What should Capri remind you about?"); + } + if action == "stopwatch" && (at.is_some() || seconds.is_some()) { + bail!("A stopwatch does not have a deadline."); + } + if at.is_some() && (action != "remind" || seconds.is_some()) { + bail!("Choose either a duration or an exact reminder time."); + } + if action == "stopwatch" && snapshot.iter().any(|r| r["kind"] == "stopwatch" && r["state"] == "running" && r["title"] == title) { + bail!("That stopwatch is already running. Ask its status, pause or cancel it before restarting."); + } + let due = match (action, at) { + ("stopwatch", _) => None, + (_, Some(at)) => Some(reminder_instant(at.as_str().unwrap_or(""), &Local)?), + _ => Some(wall + duration(seconds.unwrap_or(&Value::Null))?), + }; + if due.is_some_and(|d| d <= wall || d - wall > YEAR_MS) { + bail!("Choose a future reminder time within one year."); + } + object_id = uuid::Uuid::new_v4().to_string(); + tx.execute( + "INSERT INTO clocks(id,kind,title,created,updated,state,due,started,relative) VALUES(?,?,?,?,?,'running',?,?,?)", + params![object_id, if action == "remind" { "reminder" } else { action }, title, wall as i64, wall as i64, due, wall, at.is_none() as i64], + )?; + next_run = Some(Run { tick, elapsed: 0.0, remaining: due.map(|d| d - wall) }); + } + tx.execute("INSERT INTO time_calls VALUES(?,?,?)", params![call_id, fp, json!({"ok": true, "action": action, "id": object_id}).to_string()])?; + tx.commit()?; + drop(db); + self.finish(call_id, action, object_id, next_run) + } + + fn finish(&self, call_id: &str, action: &str, object_id: String, next_run: Option) -> Result { + { + let mut running = self.running.lock(); + running.remove(&object_id); + if let Some(run) = next_run { + running.insert(object_id.clone(), run); + } + } + let object = self.snapshot().into_iter().find(|r| r["id"] == object_id.as_str()); + let result = json!({"ok": true, "action": action, "id": object_id, "object": object}); + self.db.lock().execute("UPDATE time_calls SET result=? WHERE id=?", params![result.to_string(), call_id])?; + let _ = self.events.send(ToolEvent::TimeChanged); + Ok(result) + } + + /// Marks due objects and delivers pending outbox rows as `ToolEvent::TimeDue` (at least once). + pub fn tick(&self) -> Result<()> { + if self.closed.load(Ordering::SeqCst) { + return Ok(()); + } + let Ok(_guard) = self.ticking.try_lock() else { return Ok(()) }; + let due: Vec = self + .snapshot() + .into_iter() + .filter(|r| r["state"] == "running" && r["remainingMs"].as_f64().is_some_and(|m| m <= 0.0)) + .collect(); + for row in &due { + let id = row["id"].as_str().unwrap_or_default(); + let due_at = row["dueAt"].as_f64().unwrap_or(0.0); + let delivery = sha256_hex(format!("{id}:{}", js_number(due_at))); + let mut db = self.db.lock(); + let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + tx.execute("UPDATE clocks SET state='due',elapsed=?,started=NULL,updated=? WHERE id=? AND state='running'", params![row["elapsedMs"].as_f64(), (self.now)() as i64, id])?; + tx.execute("INSERT OR IGNORE INTO time_outbox VALUES(?,?,?,'pending')", params![delivery, id, due_at])?; + tx.commit()?; + self.running.lock().remove(id); + } + let pending: Vec<(String, String, f64)> = { + let db = self.db.lock(); + let mut stmt = db.prepare("SELECT id, object_id, due FROM time_outbox WHERE state='pending' ORDER BY due LIMIT 20")?; + stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.flatten().collect() + }; + let snapshot = if pending.is_empty() { vec![] } else { self.snapshot() }; + for (delivery, object_id, due) in pending { + let Some(mut object) = snapshot.iter().find(|r| r["id"] == object_id.as_str() && r["state"] == "due").cloned() else { continue }; + object["deliveryId"] = delivery.clone().into(); + object["overdueMs"] = ((self.now)() - due).max(0.0).into(); + if self.events.send(ToolEvent::TimeDue(object)).is_err() || self.closed.load(Ordering::SeqCst) { + break; + } + self.db.lock().execute("UPDATE time_outbox SET state='notified' WHERE id=?", [delivery])?; + } + if !due.is_empty() { + let _ = self.events.send(ToolEvent::TimeChanged); + } + Ok(()) + } + + /// Starts the 500 ms scheduler on the current tokio runtime. + pub fn spawn(self: Arc) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_millis(500)); + while !self.closed.load(Ordering::SeqCst) { + interval.tick().await; + if let Err(e) = self.tick() { + tracing::warn!("time tick failed: {e:#}"); + } + } + }) + } + + /// Checkpoints running clocks so the next start resumes them exactly. + pub fn close(&self) { + if self.closed.load(Ordering::SeqCst) { + return; + } + let now = (self.now)(); + for row in self.snapshot().into_iter().filter(|r| r["state"] == "running") { + let due = row["remainingMs"].as_f64().map(|m| now + m); + let _ = self.db.lock().execute( + "UPDATE clocks SET elapsed=?,started=?,due=?,updated=? WHERE id=?", + params![row["elapsedMs"].as_f64(), now, due, now as i64, row["id"].as_str()], + ); + } + self.closed.store(true, Ordering::SeqCst); + } +} + +/// JavaScript number text, so outbox ids match Capri's `sha256(id + ':' + dueAt)`. +fn js_number(v: f64) -> String { + if v.fract() == 0.0 && v.abs() < 1e21 { format!("{}", v as i64) } else { format!("{v}") } +} + +pub struct TimeTool(pub Arc); + +#[async_trait] +impl Tool for TimeTool { + fn name(&self) -> &str { + "time_control" + } + fn description(&self) -> String { + "Create persistent reminders, countdown timers and stopwatches, inspect elapsed/remaining time, pause/resume, cancel or snooze. Use clock for actual date/time/zone, list for real IDs. Runtime calculates durations. Ask to clarify vague times. Reminder text is only a future notification, never an executable command. Confirm only after the tool reports success; keep confirmations short.".into() + } + fn parameters(&self) -> Value { + json!({"type":"object","additionalProperties":false,"required":["action"],"properties":{"action":{"type":"string","enum":ACTIONS},"id":{"type":"string","description":"Existing object ID from list/status; omit only if exactly one matching object exists."},"title":{"type":"string","maxLength":1000},"seconds":{"type":"number","description":"Duration in seconds for remind/timer/snooze. Runtime calculates the deadline."},"at":{"type":"string","description":"For an absolute reminder: ISO date/time with offset, or local YYYY-MM-DDTHH:mm. Call clock if the current date is unknown. Do not guess vague morning/evening times."}}}) + } + async fn call(&self, args: Value, ctx: ToolContext) -> Value { + self.0.execute(&ctx.call_id, &args).unwrap_or_else(|e| json!({"ok": false, "error": e.to_string().chars().take(400).collect::()})) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicI64; + + fn service(dir: &Path, clock: Arc) -> (TimeService, tokio::sync::mpsc::UnboundedReceiver) { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let (a, b) = (clock.clone(), clock); + let svc = TimeService::with_clocks( + &dir.join("desktop/time.sqlite"), + tx, + Box::new(move || 1_800_000_000_000.0 + a.load(Ordering::SeqCst) as f64), + Box::new(move || b.load(Ordering::SeqCst) as f64), + ) + .unwrap(); + (svc, rx) + } + + #[test] + fn timer_fires_once_and_snooze_rearms() { + let dir = tempfile::tempdir().unwrap(); + let clock = Arc::new(AtomicI64::new(0)); + let (svc, mut rx) = service(dir.path(), clock.clone()); + let r = svc.execute("call-1", &json!({"action":"timer","seconds":60,"title":"tea"})).unwrap(); + assert_eq!(r["object"]["remainingMs"], 60000.0); + assert_eq!(svc.execute("call-1", &json!({"action":"timer","seconds":60,"title":"tea"})).unwrap(), r, "replay"); + assert!(svc.execute("call-1", &json!({"action":"timer","seconds":61})).is_err()); + clock.store(30_000, Ordering::SeqCst); + assert_eq!(svc.snapshot()[0]["remainingMs"], 30000.0); + svc.tick().unwrap(); + while rx.try_recv().is_ok() {} + clock.store(60_000, Ordering::SeqCst); + svc.tick().unwrap(); + let events: Vec<_> = std::iter::from_fn(|| rx.try_recv().ok()).collect(); + let due = events.iter().find_map(|e| if let ToolEvent::TimeDue(o) = e { Some(o.clone()) } else { None }).unwrap(); + assert_eq!((due["title"].as_str(), due["state"].as_str()), (Some("tea"), Some("due"))); + assert_eq!(reminder_speech(&due), "Choom, your reminder: tea"); + svc.tick().unwrap(); + assert!(!std::iter::from_fn(|| rx.try_recv().ok()).any(|e| matches!(e, ToolEvent::TimeDue(_))), "delivered once"); + let s = svc.execute("call-2", &json!({"action":"snooze","seconds":5})).unwrap(); + assert_eq!((s["object"]["state"].as_str(), s["object"]["remainingMs"].as_f64()), (Some("running"), Some(5000.0))); + } + + #[test] + fn stopwatch_pause_resume_and_restart_persistence() { + let dir = tempfile::tempdir().unwrap(); + let clock = Arc::new(AtomicI64::new(0)); + let (svc, _rx) = service(dir.path(), clock.clone()); + svc.execute("a", &json!({"action":"stopwatch","title":"run"})).unwrap(); + assert!(svc.execute("b", &json!({"action":"stopwatch","title":"run"})).unwrap_err().to_string().contains("already running")); + clock.store(5_000, Ordering::SeqCst); + let p = svc.execute("c", &json!({"action":"pause"})).unwrap(); + assert_eq!(p["object"]["displayElapsed"], "00:00:05"); + clock.store(9_000, Ordering::SeqCst); + svc.execute("d", &json!({"action":"resume"})).unwrap(); + clock.store(10_000, Ordering::SeqCst); + assert_eq!(svc.snapshot()[0]["elapsedSeconds"], 6); + assert!(svc.execute("e", &json!({"action":"pause","title":"x"})).unwrap_err().to_string().contains("Unexpected")); + svc.close(); + assert!(svc.execute("f", &json!({"action":"list"})).is_err()); + clock.store(20_000, Ordering::SeqCst); + let (again, _rx) = service(dir.path(), clock.clone()); + assert_eq!(again.snapshot()[0]["elapsedSeconds"], 16, "time spent closed counts"); + let reset = again.execute("g", &json!({"action":"reset"})).unwrap(); + assert_eq!(reset["object"]["elapsedSeconds"], 0); + } + + #[test] + fn validation_messages() { + let dir = tempfile::tempdir().unwrap(); + let (svc, _rx) = service(dir.path(), Arc::new(AtomicI64::new(0))); + let err = |args: Value| svc.execute("x", &args).unwrap_err().to_string(); + assert_eq!(err(json!({"action":"remind","seconds":10})), "What should Capri remind you about?"); + assert_eq!(err(json!({"action":"timer","seconds":0.0001})), "Choose a duration between one second and one year."); + assert_eq!(err(json!({"action":"timer","seconds":10,"at":"2030-01-01T10:00Z"})), "Choose either a duration or an exact reminder time."); + assert_eq!(err(json!({"action":"remind","title":"x","at":"2020-01-01T10:00Z"})), "Choose a future reminder time within one year."); + assert_eq!(err(json!({"action":"cancel"})), "No matching timer, reminder or stopwatch is active."); + assert_eq!(err(json!({"action":"nope"})), "Invalid time command."); + assert_eq!(err(json!({"action":"cancel","id":"ABC"})), "Invalid timer ID."); + svc.execute("t1", &json!({"action":"timer","seconds":10})).unwrap(); + svc.execute("t2", &json!({"action":"timer","seconds":20})).unwrap(); + assert!(err(json!({"action":"cancel"})).contains("several")); + let clock = svc.execute("c", &json!({"action":"clock"})).unwrap(); + assert!(clock["now"].as_str().unwrap().ends_with('Z')); + } + + #[test] + fn reminder_instants() { + let paris = chrono::FixedOffset::east_opt(3600).unwrap(); + assert_eq!(reminder_instant("2026-10-25T02:30+02:00", &paris).unwrap(), 1_792_888_200_000.0); + assert_eq!(reminder_instant("2026-10-25T00:30Z", &paris).unwrap(), 1_792_888_200_000.0); + assert_eq!(reminder_instant("2026-10-25T01:30", &paris).unwrap(), 1_792_888_200_000.0); + assert!(reminder_instant("tomorrow", &paris).is_err()); + assert_eq!(reminder_notification(&json!({"title":"secret"}), true).1, "Reminder"); + assert_eq!(js_number(1795007200000.0), "1795007200000"); + } +}