Skip to main content

adk_surface/verbs/
terminal.rs

1//! `/snooze <title> [tomorrow]` in a terminal (spec 3.3 §5.2, owner question 27): typed by the
2//! person, run as the terminal's caller.
3//!
4//! The terminal in process runs it through [`SnoozeCommand`]; a terminal attached to
5//! `adk-rust up` reaches the same code through the kernel's command host, in up's process. A
6//! terminal paired from another machine cannot snooze: the kernel's commands need its own
7//! socket or the operator's token, so it says to use the home. Text an agent writes, a
8//! "/snooze" in a reply included, is never a command.
9
10use super::{ObjectRef, VerbError, VerbGate, VerbIntent, find_by_title, words};
11use crate::origin::Caller;
12
13/// What `/snooze` was given: a title, and whether to the same time tomorrow.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_surface::verbs::{SnoozeText, parse_snooze};
19///
20/// assert_eq!(parse_snooze("News digest"), Some(SnoozeText { title: "News digest".into(), tomorrow: false }));
21/// assert_eq!(parse_snooze("Water plants Tomorrow"), Some(SnoozeText { title: "Water plants".into(), tomorrow: true }));
22/// assert_eq!(parse_snooze("  "), None);
23/// ```
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SnoozeText {
26    /// The title, as typed.
27    pub title: String,
28    /// To the same time tomorrow, else an hour later.
29    pub tomorrow: bool,
30}
31
32/// Reads the text after `/snooze`: a title, and `tomorrow` as its last word for the same time
33/// tomorrow. `None` without a title.
34pub fn parse_snooze(args: &str) -> Option<SnoozeText> {
35    let args = args.trim();
36    let (title, tomorrow) = match args.rsplit_once(char::is_whitespace) {
37        Some((title, last)) if last.eq_ignore_ascii_case("tomorrow") => (title.trim_end(), true),
38        _ if args.eq_ignore_ascii_case("tomorrow") => ("", true),
39        _ => (args, false),
40    };
41    (!title.is_empty()).then(|| SnoozeText { title: title.to_string(), tomorrow })
42}
43
44/// Runs `/snooze <args>` for `caller`: "✓ snoozed News digest → 19:00" once it ran.
45///
46/// # Errors
47///
48/// [`VerbError::Invalid`] without a title; [`VerbError::NotFound`] when no title matches;
49/// [`VerbError::Ambiguous`] when several do; [`VerbError::Refused`] naming the item when it
50/// cannot be snoozed: "can't snooze CI check: it has already started"; the gate's other
51/// errors. [`problem_line`] words each for the terminal.
52///
53/// # Example
54///
55/// ```rust,no_run
56/// use adk_surface::{Caller, Origin, SurfaceKind};
57///
58/// # async fn example(gate: adk_surface::verbs::VerbGate) {
59/// let ana = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard).with_paired_local();
60/// match adk_surface::verbs::snooze_text(&gate, &ana, "News digest").await {
61///     Ok(line) => println!("{line}"),
62///     Err(error) => println!("{}", adk_surface::verbs::problem_line(&error)),
63/// }
64/// # }
65/// ```
66pub async fn snooze_text(
67    gate: &VerbGate,
68    caller: &Caller,
69    args: &str,
70) -> Result<String, VerbError> {
71    let Some(typed) = parse_snooze(args) else {
72        return Err(VerbError::invalid(
73            "/snooze takes a title from Coming up: /snooze <title> [tomorrow]",
74        ));
75    };
76    let items = gate.coming_up(caller).await?;
77    let item = find_by_title(&items, &typed.title)?;
78    let refused = |why: &str| VerbError::refused(format!("can't snooze {}: {why}", item.title));
79    if let Some(why) = &item.why_not {
80        return Err(refused(why));
81    }
82    let Some(choice) = item.choices.iter().find(|choice| choice.tomorrow == typed.tomorrow) else {
83        let why = item.ends.map_or_else(
84            || words::NOT_ONE_TIME.to_string(),
85            |ends| words::ends_at(&gate.registry().scope(caller.user_id(), None).time_text(ends)),
86        );
87        return Err(refused(&why));
88    };
89    let intent = VerbIntent::new("snooze", serde_json::json!({ "to": choice.to }))
90        .on(ObjectRef::coming_up(&item.id));
91    match gate.call(caller, intent).await {
92        Ok(_) => Ok(format!("✓ {}", words::snoozed(&item.title, &choice.at_text))),
93        Err(VerbError::Refused(why)) => Err(refused(&why)),
94        Err(error) => Err(error),
95    }
96}
97
98/// `error` as a terminal says it: "nothing in Coming up is called “laundry”", "two things
99/// match “digest” — type the full title:" and the titles, one per line.
100///
101/// # Example
102///
103/// ```rust
104/// use adk_surface::verbs::{VerbError, problem_line};
105///
106/// let error = VerbError::Ambiguous { said: "digest".into(), matches: vec!["News digest".into(), "Weekly digest".into()] };
107/// assert_eq!(problem_line(&error), "two things match “digest” — type the full title:\n  News digest\n  Weekly digest");
108/// ```
109pub fn problem_line(error: &VerbError) -> String {
110    match error {
111        VerbError::Ambiguous { said, matches } => {
112            let head = words::things_match(matches.len(), said);
113            let mut chars = head.chars();
114            let head: String = match chars.next() {
115                Some(first) => first.to_lowercase().chain(chars).collect(),
116                None => head,
117            };
118            let list: Vec<String> = matches.iter().map(|title| format!("  {title}")).collect();
119            format!("{head} — type the full title:\n{}", list.join("\n"))
120        }
121        other => other.to_string(),
122    }
123}
124
125/// `/snooze` in the terminal (spec 3.3 §5.2): in process, through a [`VerbGate`] as the
126/// terminal's caller; or, on a terminal paired from another machine, only the words that say
127/// to use the home.
128///
129/// # Example
130///
131/// ```rust,no_run
132/// use std::sync::Arc;
133/// use adk_surface::verbs::SnoozeCommand;
134/// use adk_surface::{Caller, Origin, SurfaceKind};
135///
136/// # fn example(gate: adk_surface::verbs::VerbGate, terminal: adk_surface::tui::TerminalSurface) {
137/// let ana = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard).with_paired_local();
138/// let terminal = terminal.command(Arc::new(SnoozeCommand::new(gate, ana)));
139/// # let _ = terminal;
140/// # }
141/// ```
142#[cfg(feature = "tui")]
143pub struct SnoozeCommand {
144    reach: Option<(VerbGate, Caller)>,
145}
146
147#[cfg(feature = "tui")]
148impl SnoozeCommand {
149    /// `/snooze` through `gate`, as `caller`.
150    pub fn new(gate: VerbGate, caller: Caller) -> Self {
151        Self { reach: Some((gate, caller)) }
152    }
153
154    /// `/snooze` on a terminal paired from another machine: "Snooze isn't available from a
155    /// remote terminal — use the home."
156    pub fn remote() -> Self {
157        Self { reach: None }
158    }
159}
160
161#[cfg(feature = "tui")]
162#[async_trait::async_trait]
163impl crate::tui::TerminalCommand for SnoozeCommand {
164    fn name(&self) -> &str {
165        "snooze"
166    }
167
168    fn description(&self) -> &str {
169        words::SNOOZE_SOMETHING
170    }
171
172    async fn run(
173        &self,
174        args: &str,
175        _context: &crate::tui::CommandContext,
176    ) -> adk_core::Result<String> {
177        let Some((gate, caller)) = &self.reach else {
178            return Err(adk_core::AdkError::from(VerbError::NotHere(
179                words::NOT_FROM_A_REMOTE_TERMINAL.to_string(),
180            )));
181        };
182        snooze_text(gate, caller, args).await.map_err(|error| {
183            let line = problem_line(&error);
184            let mut error = adk_core::AdkError::from(error);
185            error.message = line;
186            error
187        })
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn the_title_and_tomorrow_are_read_from_what_was_typed() {
197        let cases: &[(&str, Option<(&str, bool)>)] = &[
198            ("News digest", Some(("News digest", false))),
199            ("  News digest  ", Some(("News digest", false))),
200            ("news digest tomorrow", Some(("news digest", true))),
201            ("News digest TOMORROW", Some(("News digest", true))),
202            ("Tomorrow's plan", Some(("Tomorrow's plan", false))),
203            ("tomorrow", None),
204            ("", None),
205        ];
206        for (typed, expected) in cases {
207            let expected =
208                expected.map(|(title, tomorrow)| SnoozeText { title: title.into(), tomorrow });
209            assert_eq!(parse_snooze(typed), expected, "{typed:?}");
210        }
211    }
212}