Skip to main content

aidaemon_channels/
slash.rs

1//! Slash commands shared by every chat platform: the command menu
2//! ([`shared_commands`], [`build_help_text`]) and the commands that behave the
3//! same everywhere ([`SharedCommands`]): models, chat operations, context,
4//! `/private`, `/mode`, `/clear`, `/wipe` and usage. A host supplies its
5//! services through [`CommandHost`] and adds its own commands (`/work`,
6//! `/reload`...) as [`SlashCommand`]s. Internal to aidaemon, no stability
7//! promise; the public contract is [`crate::channel`].
8
9use std::collections::HashMap;
10use std::sync::Arc;
11
12use aidaemon_events::conversation::{ConversationSummary, Message};
13use aidaemon_events::provider::TokenUsageRecord;
14use aidaemon_tools::duration_format::{ZeroUnitStyle, compact_chrono_duration};
15use aidaemon_tools::semantics::UserRole;
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18
19use crate::ports::ChannelAgentRuntime;
20use crate::tasks::{TaskRegistry, TaskStatus};
21
22/// Whether a chat message is a slash command: `/name` or `/name@bot`, where
23/// `name` is letters, digits and underscores (Telegram's command syntax).
24/// A message that merely starts with a path (`/tmp/x.py is broken`) is not.
25pub fn is_slash_command(text: &str) -> bool {
26    let Some(first) = text.split_whitespace().next() else {
27        return false;
28    };
29    let Some(rest) = first.strip_prefix('/') else {
30        return false;
31    };
32    let name = rest.split_once('@').map_or(rest, |(name, _bot)| name);
33    !name.is_empty()
34        && name.starts_with(|c: char| c.is_ascii_alphabetic())
35        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
36}
37
38#[cfg(test)]
39mod slash_command_tests {
40    use super::is_slash_command;
41
42    #[test]
43    fn commands_are_names_and_paths_are_messages() {
44        for command in [
45            "/help",
46            "/model gpt-5.6-terra",
47            "/clear",
48            "/start@aidaemon_bot",
49            "/set_up now",
50        ] {
51            assert!(is_slash_command(command), "{command}");
52        }
53        for message in [
54            "/tmp/aidaemon-live/prime/prime.py has a bug",
55            "/Users/alice/notes.txt",
56            "/ what",
57            "/",
58            "/123",
59            "hello /help",
60        ] {
61            assert!(!is_slash_command(message), "{message}");
62        }
63    }
64}
65
66/// Single source of truth for command definitions.
67///
68/// Each command is defined once here; the registry drives Telegram's
69/// `setMyCommands` API, the `/help` output, and (in the future) Slack/Discord
70/// command registration.
71pub struct CommandDef {
72    /// Command name without leading `/` or `!`.
73    pub name: &'static str,
74    /// Short description shown in Telegram's command menu and `/help` text.
75    /// Must be 3-256 characters for Telegram's `BotCommand`.
76    pub description: &'static str,
77    /// Optional usage string shown only in `/help` (e.g. `/model [name]`).
78    pub usage: Option<&'static str>,
79    /// Which platform group this command belongs to.
80    pub category: CommandCategory,
81}
82
83/// Determines which platforms show a command.
84#[derive(Clone, Copy, PartialEq, Eq)]
85pub enum CommandCategory {
86    /// Available on all platforms.
87    Core,
88    /// Telegram + Slack (process restart).
89    Restart,
90    /// Telegram-only (dynamic bot management).
91    Connect,
92    /// Telegram-only (terminal/agent bridge).
93    Terminal,
94}
95
96/// Returns the shared commands available on every platform.
97pub fn shared_commands() -> Vec<CommandDef> {
98    vec![
99        CommandDef {
100            name: "model",
101            description: "Show or switch AI model",
102            usage: Some("/model [name]"),
103            category: CommandCategory::Core,
104        },
105        CommandDef {
106            name: "models",
107            description: "List available models",
108            usage: None,
109            category: CommandCategory::Core,
110        },
111        CommandDef {
112            name: "auto",
113            description: "Re-enable automatic model routing",
114            usage: None,
115            category: CommandCategory::Core,
116        },
117        CommandDef {
118            name: "reload",
119            description: "Reload configuration",
120            usage: None,
121            category: CommandCategory::Core,
122        },
123        CommandDef {
124            name: "tasks",
125            description: "List running tasks",
126            usage: None,
127            category: CommandCategory::Core,
128        },
129        CommandDef {
130            name: "status",
131            description: "Show this chat's mode, running tasks and what's next",
132            usage: None,
133            category: CommandCategory::Core,
134        },
135        CommandDef {
136            name: "work",
137            description: "See and manage longer work that waits or runs on its own",
138            usage: Some("/work [ready|running|blocked|show|comment|unblock|retry]"),
139            category: CommandCategory::Core,
140        },
141        CommandDef {
142            name: "cancel",
143            description: "Stop what's running in this chat",
144            usage: Some("/cancel [all|number]"),
145            category: CommandCategory::Core,
146        },
147        CommandDef {
148            name: "clear",
149            description: "Start fresh conversation (history kept)",
150            usage: None,
151            category: CommandCategory::Core,
152        },
153        CommandDef {
154            name: "wipe",
155            description: "Permanently delete this conversation (send twice to confirm)",
156            usage: None,
157            category: CommandCategory::Core,
158        },
159        CommandDef {
160            name: "cost",
161            description: "Show token usage stats",
162            usage: None,
163            category: CommandCategory::Core,
164        },
165        CommandDef {
166            name: "context",
167            description: "Show conversation context coverage",
168            usage: None,
169            category: CommandCategory::Core,
170        },
171        CommandDef {
172            name: "checkpoints",
173            description: "List filesystem checkpoints",
174            usage: None,
175            category: CommandCategory::Core,
176        },
177        CommandDef {
178            name: "readonly",
179            description: "Make this chat read-only for 4 hours",
180            usage: None,
181            category: CommandCategory::Core,
182        },
183        CommandDef {
184            name: "private",
185            description: "Don't remember or learn from your next message",
186            usage: Some("/private [off]"),
187            category: CommandCategory::Core,
188        },
189        CommandDef {
190            name: "mode",
191            description: "Show or change this chat's access mode",
192            usage: Some("/mode [full|unrestricted|readonly]"),
193            category: CommandCategory::Core,
194        },
195        CommandDef {
196            name: "rollback",
197            description: "Preview or confirm a checkpoint rollback",
198            usage: Some("/rollback [checkpoint-id|confirm TOKEN]"),
199            category: CommandCategory::Core,
200        },
201    ]
202}
203
204/// A chat's tool authority as the owner set it with `/mode`.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum ChatMode {
207    ReadOnly,
208    Full,
209    Unrestricted,
210}
211
212/// What the shared commands need from the host besides the agent.
213#[async_trait]
214pub trait CommandHost: Send + Sync {
215    /// `/private`: whether the sender's next message in this chat is kept
216    /// out of memory (`on`), or that request cancelled.
217    async fn set_next_message_private(
218        &self,
219        session_id: &str,
220        sender_id: Option<&str>,
221        on: bool,
222    ) -> anyhow::Result<()>;
223    /// The chat's mode in force at `now` and when it ends; `None` is full.
224    async fn chat_mode(
225        &self,
226        session_id: &str,
227        now: DateTime<Utc>,
228    ) -> Option<(ChatMode, Option<DateTime<Utc>>)>;
229    /// Set the chat's mode from `now`; returns when it ends.
230    async fn set_chat_mode(
231        &self,
232        session_id: &str,
233        mode: ChatMode,
234        now: DateTime<Utc>,
235    ) -> anyhow::Result<DateTime<Utc>>;
236    /// How many hours a narrowed or widened mode lasts.
237    fn chat_mode_hours(&self) -> i64;
238    async fn history(&self, session_id: &str, limit: usize) -> anyhow::Result<Vec<Message>>;
239    async fn conversation_summary(
240        &self,
241        session_id: &str,
242    ) -> anyhow::Result<Option<ConversationSummary>>;
243    /// Estimated tokens of stored messages (`role`, `content`, `name`).
244    fn estimate_message_tokens(&self, messages: &[serde_json::Value]) -> usize;
245    fn estimate_text_tokens(&self, text: &str) -> usize;
246    /// Token usage recorded since `since` (`%Y-%m-%d %H:%M:%S`, UTC).
247    async fn token_usage_since(&self, since: &str) -> anyhow::Result<Vec<TokenUsageRecord>>;
248    /// The owner's next scheduled item, for `/status`; `None` when nothing
249    /// is scheduled (or the host keeps no schedules).
250    async fn next_scheduled(&self) -> Option<ScheduledItem> {
251        None
252    }
253
254    /// `at` in the owner's local time and format ("2:39 PM ET"), for the
255    /// first line of `/status`; `None` when the host has no owner zone.
256    fn owner_time(&self, _at: DateTime<Utc>) -> Option<String> {
257        None
258    }
259}
260
261/// One scheduled item as `/status` shows it.
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct ScheduledItem {
264    /// What runs, as [`scheduled_name`] names it.
265    pub what: String,
266    /// When, already in the owner's local time ("2:39 PM ET").
267    pub when: String,
268}
269
270/// The most a scheduled item's description may run to and still stand as
271/// its name on `/status`.
272const SCHEDULED_NAME_MAX: usize = 60;
273
274/// What `/status` calls a scheduled item: the name its owner gave it, else
275/// its description when that fits whole, else that it has no name. Never a
276/// sentence cut short (live 2026-11-13: "…blog at…").
277pub fn scheduled_name(name: Option<&str>, description: &str) -> String {
278    if let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) {
279        return name.to_string();
280    }
281    let description = description.split_whitespace().collect::<Vec<_>>().join(" ");
282    if !description.is_empty() && description.chars().count() <= SCHEDULED_NAME_MAX {
283        return description;
284    }
285    "An automation without a name (see /work)".to_string()
286}
287
288/// What `/status` reports, read from typed state.
289#[derive(Debug, Clone)]
290pub struct StatusView {
291    /// The current time in the owner's local format, when known.
292    pub now: Option<String>,
293    /// The chat's mode and when it ends; `None` is full access.
294    pub mode: Option<(ChatMode, Option<DateTime<Utc>>)>,
295    /// Everything running for the chat: its turn, sub-agents and background
296    /// commands. A turn is named by what it is, never by the message that
297    /// started it: that message may be a reply ("Yes, move the files").
298    pub running: crate::stop::WorkList,
299    pub next_scheduled: Option<ScheduledItem>,
300}
301
302/// The one line that says a chat's mode, as `/mode` and `/status` show it.
303fn mode_line(mode: Option<(ChatMode, Option<DateTime<Utc>>)>, now: DateTime<Utc>) -> String {
304    let left = |until: Option<DateTime<Utc>>| {
305        until.map_or_else(String::new, |at| {
306            format!(
307                " (about {} left)",
308                compact_chrono_duration(at - now, ZeroUnitStyle::Trim)
309            )
310        })
311    };
312    match mode {
313        Some((ChatMode::ReadOnly, until)) => format!("Mode: read-only{}.", left(until)),
314        Some((ChatMode::Unrestricted, until)) => format!("Mode: unrestricted{}.", left(until)),
315        Some((ChatMode::Full, _)) | None => "Mode: full.".to_string(),
316    }
317}
318
319/// How `/cancel` stops what is listed.
320fn cancel_hint(running: &crate::stop::WorkList) -> &'static str {
321    match running.entries.len() {
322        0 => "",
323        1 => "Send /cancel to stop it.",
324        _ if running.requests() > 1 => {
325            "Send /cancel <number> to stop one, or /cancel all to stop everything."
326        }
327        _ => "Send /cancel to stop all of it, or /cancel <number> for one.",
328    }
329}
330
331/// `/tasks`: everything running for the chat (its turn, sub-agents and
332/// background commands), numbered for `/cancel`, and its failed turns. The
333/// reply is a snapshot that stays in the chat, so it says when it was taken
334/// (`as_of`, the owner's clock) and never reads as live later.
335pub fn render_tasks(
336    running: &crate::stop::WorkList,
337    failed: &[crate::tasks::TaskEntry],
338    now: DateTime<Utc>,
339    as_of: Option<&str>,
340) -> String {
341    let stamp = as_of.map(|at| format!("As of {at}:\n"));
342    let stamp = stamp.as_deref().unwrap_or("");
343    if running.entries.is_empty() && failed.is_empty() {
344        return format!(
345            "{stamp}Nothing is running in this chat right now. Use /work for longer work that \
346             waits or runs on its own."
347        );
348    }
349    let mut sections = Vec::new();
350    if running.entries.is_empty() {
351        sections.push("Nothing is running in this chat right now.".to_string());
352    } else {
353        sections.push(format!(
354            "Running in this chat:\n{}\n\n{}",
355            running.lines(now).join("\n"),
356            cancel_hint(running)
357        ));
358    }
359    if !failed.is_empty() {
360        let lines: Vec<String> = failed
361            .iter()
362            .map(|entry| {
363                let at = entry.finished_at.unwrap_or(now);
364                format!(
365                    "#{} {} – it failed after {}",
366                    entry.id,
367                    crate::stop::TURN_LABEL,
368                    compact_chrono_duration(at - entry.started_at, ZeroUnitStyle::Trim)
369                )
370            })
371            .collect();
372        sections.push(format!("Recently failed:\n{}", lines.join("\n")));
373    }
374    sections.push("Use /work for longer work that waits or runs on its own.".to_string());
375    format!("{stamp}{}", sections.join("\n\n"))
376}
377
378/// `/status`: the chat's mode, what is running and what is scheduled next.
379pub fn render_status(view: &StatusView, now: DateTime<Utc>) -> String {
380    let mode = mode_line(view.mode, now);
381    let mut lines = vec![match &view.now {
382        Some(local) => format!("As of {local}: {mode}"),
383        None => mode,
384    }];
385    if view.running.entries.is_empty() {
386        lines.push("Running: nothing right now.".to_string());
387    } else {
388        lines.push("Running:".to_string());
389        for entry in &view.running.entries {
390            lines.push(format!(
391                "• {} ({} so far, /cancel {} to stop it)",
392                crate::presentation::word_preview(&entry.title, 120),
393                compact_chrono_duration(now - entry.started_at, ZeroUnitStyle::Trim),
394                entry.number
395            ));
396        }
397    }
398    lines.push(match &view.next_scheduled {
399        Some(item) => format!("Next scheduled: {} – {}", item.what, item.when),
400        None => "Next scheduled: nothing.".to_string(),
401    });
402    lines.join("\n")
403}
404
405/// What a `/clear` or `/wipe` stopped, as one list: the chat's cancelled
406/// turns (named as `/tasks` names them) before its sub-agents and commands,
407/// so no separate count can disagree with the list (live 2026-11-12: "(1
408/// running task cancelled.)" over two stopped sub-agents).
409fn stopped_with_turns(turns: usize, work: Vec<String>) -> Vec<String> {
410    let mut stopped = vec![crate::stop::TURN_LABEL.to_string(); turns];
411    stopped.extend(work);
412    stopped
413}
414
415/// The end of a `/clear` or `/wipe` reply: what else was cancelled, then
416/// the sub-agents and background commands stopped, named as `/cancel` names
417/// them.
418fn clear_suffix(cancellations: &[String], stopped_work: &[String]) -> String {
419    let mut suffix = if cancellations.is_empty() {
420        String::new()
421    } else {
422        format!(" ({} cancelled.)", cancellations.join(" and "))
423    };
424    let stopped = crate::stop::stopped_list(stopped_work);
425    if !stopped.is_empty() {
426        suffix.push_str("\n\n");
427        suffix.push_str(&stopped);
428    }
429    suffix
430}
431
432/// What `/cancel`'s arguments ask for; `None` when they are not a request.
433pub fn cancel_request(args: &str) -> Option<crate::stop::StopRequest> {
434    let args = args.trim();
435    if args.is_empty() {
436        return Some(crate::stop::StopRequest::Bare);
437    }
438    if args.eq_ignore_ascii_case("all") {
439        return Some(crate::stop::StopRequest::All);
440    }
441    let numbers: Option<Vec<u64>> = args
442        .split(|c: char| c.is_whitespace() || c == ',')
443        .filter(|part| !part.is_empty())
444        .map(|part| part.trim_start_matches('#').parse::<u64>().ok())
445        .collect();
446    numbers
447        .filter(|numbers| !numbers.is_empty())
448        .map(crate::stop::StopRequest::Numbers)
449}
450
451/// The command closest to an unknown `name` (without its prefix) by edit
452/// distance, when one is close enough to be a likely typo.
453pub fn closest_command<'a>(name: &str, commands: &'a [CommandDef]) -> Option<&'a str> {
454    let name = name.to_ascii_lowercase();
455    let len = name.chars().count();
456    if len == 0 {
457        return None;
458    }
459    let limit = if len <= 4 { 1 } else { 2 };
460    commands
461        .iter()
462        .map(|command| (edit_distance(&name, command.name), command.name))
463        .filter(|(distance, _)| *distance <= limit)
464        .min_by_key(|(distance, _)| *distance)
465        .map(|(_, command)| command)
466}
467
468fn edit_distance(a: &str, b: &str) -> usize {
469    let b: Vec<char> = b.chars().collect();
470    let mut previous: Vec<usize> = (0..=b.len()).collect();
471    for (i, ca) in a.chars().enumerate() {
472        let mut current = vec![i + 1; b.len() + 1];
473        for (j, cb) in b.iter().enumerate() {
474            let substitution = previous[j] + usize::from(ca != *cb);
475            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
476        }
477        previous = current;
478    }
479    previous[b.len()]
480}
481
482/// The reply to a command nobody handles: a likely intended command when one
483/// is close, and where to find the rest.
484pub fn unknown_command_reply(cmd: &str, commands: &[CommandDef], prefix: &str) -> String {
485    let name = cmd
486        .trim_start_matches(prefix)
487        .split('@')
488        .next()
489        .unwrap_or("");
490    match closest_command(name, commands) {
491        Some(suggestion) => format!(
492            "I don't know {cmd}. Did you mean {prefix}{suggestion}? Send {prefix}help to see \
493             the commands."
494        ),
495        None => format!("I don't know {cmd}. Send {prefix}help to see the commands."),
496    }
497}
498
499/// How `/private` was sent when it carries more than the bare command.
500#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501pub enum PrivateRequest<'a> {
502    /// Only `/private` (said once or more, "/private/private"): the next
503    /// message is kept private.
504    Next,
505    /// `/private` with the message itself ("/private what's my balance?",
506    /// "/privateWhat's…"): this message is the private one.
507    With(&'a str),
508}
509
510/// Read `/private` sent together with its message. `None` for anything
511/// else, including `/private off` and the bare `/private`, which the
512/// command itself answers.
513pub fn private_request(text: &str) -> Option<PrivateRequest<'_>> {
514    let mut rest = text.trim_start();
515    let mut seen = 0usize;
516    while let Some(after) = strip_prefix_ignore_case(rest, "/private") {
517        seen += 1;
518        // Telegram may append the bot name in groups: `/private@my_bot`.
519        rest = match after.strip_prefix('@') {
520            Some(bot) => bot.find(char::is_whitespace).map_or("", |at| &bot[at..]),
521            None => after,
522        };
523        rest = rest.trim_start();
524    }
525    if seen == 0 {
526        return None;
527    }
528    let message = rest.trim();
529    if message.is_empty() {
530        return (seen > 1).then_some(PrivateRequest::Next);
531    }
532    if message.eq_ignore_ascii_case("off") {
533        return None;
534    }
535    Some(PrivateRequest::With(message))
536}
537
538fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
539    let head = text.get(..prefix.len())?;
540    head.eq_ignore_ascii_case(prefix)
541        .then(|| &text[prefix.len()..])
542}
543
544/// The commands `/help` shows first: the ones used day to day.
545pub const EVERYDAY_COMMANDS: &[&str] = &["clear", "tasks", "status", "private", "readonly", "mode"];
546
547/// How much `/help` shows.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub enum HelpScope {
550    /// The everyday commands and how to see the rest.
551    Everyday,
552    /// Every command the platform has (`/help all`).
553    All,
554}
555
556impl HelpScope {
557    pub fn from_args(args: &str) -> Self {
558        if args.trim().eq_ignore_ascii_case("all") {
559            Self::All
560        } else {
561            Self::Everyday
562        }
563    }
564}
565
566/// Who sent a command, and where.
567pub struct SlashCall<'a> {
568    pub session_id: &'a str,
569    pub sender_id: Option<&'a str>,
570    pub user_role: UserRole,
571}
572
573/// A command the host adds to the shared ones.
574#[async_trait]
575pub trait SlashCommand: Send + Sync {
576    /// Whether this handles `cmd` (with its `/`).
577    fn handles(&self, cmd: &str) -> bool;
578    async fn run(&self, cmd: &str, args: &str, call: &SlashCall<'_>) -> String;
579    /// The commands this handles, for the platform's command menu and
580    /// `/help`. Every name here must be one [`Self::handles`] accepts.
581    fn commands(&self) -> Vec<CommandDef> {
582        Vec::new()
583    }
584}
585
586/// Shared command dispatcher for commands that behave identically across
587/// Telegram, Slack, and Discord channels.
588pub struct SharedCommands {
589    pub agent: Arc<dyn ChannelAgentRuntime>,
590    pub host: Arc<dyn CommandHost>,
591    pub task_registry: Arc<TaskRegistry>,
592    /// The host's own commands, asked in order for any other name.
593    pub extensions: Vec<Arc<dyn SlashCommand>>,
594}
595
596impl SharedCommands {
597    /// The menu and `/help` entries of the host's own commands.
598    pub fn extension_commands(&self) -> Vec<CommandDef> {
599        self.extensions
600            .iter()
601            .flat_map(|extension| extension.commands())
602            .collect()
603    }
604
605    /// Try to handle a shared command. Returns `Some(reply)` if the command was
606    /// recognised, `None` if the channel should handle it itself.
607    pub async fn dispatch(
608        &self,
609        cmd: &str,
610        args: &str,
611        session_id: &str,
612        sender_id: Option<&str>,
613        user_role: UserRole,
614    ) -> Option<String> {
615        // Everything here but a private aside and the chat's own task list
616        // changes or reveals something of the owner's (the model for every
617        // chat, running work, history, cost, the daemon itself), so it is
618        // the owner's: a guest in a shared chat does not get it.
619        // (`/cancel`, `/context`, `/readonly` and `/mode` say so themselves.)
620        if user_role != UserRole::Owner
621            && !matches!(
622                cmd,
623                "/private" | "/tasks" | "/cancel" | "/context" | "/readonly" | "/mode"
624            )
625        {
626            let shared = matches!(
627                cmd,
628                "/model" | "/models" | "/auto" | "/clear" | "/new" | "/status" | "/wipe" | "/cost"
629            ) || self.extensions.iter().any(|ext| ext.handles(cmd));
630            return shared.then(|| format!("Only the owner can use {cmd}."));
631        }
632        Some(match cmd {
633            "/model" => self.handle_model(args).await,
634            "/models" => self.handle_models().await,
635            "/auto" => self.handle_auto().await,
636            "/tasks" => self.handle_tasks(session_id).await,
637            "/cancel" => self.handle_cancel(args, session_id, user_role).await,
638            "/clear" | "/new" => self.handle_clear(session_id).await,
639            "/status" => self.handle_status(session_id).await,
640            "/wipe" => self.handle_wipe(session_id).await,
641            "/cost" => self.handle_cost().await,
642            "/context" => self.handle_context(session_id, user_role).await,
643            "/readonly" => self.handle_readonly(session_id, user_role).await,
644            "/private" => self.handle_private(args, session_id, sender_id).await,
645            "/mode" => self.handle_mode(args, session_id, user_role).await,
646            _ => {
647                let extension = self.extensions.iter().find(|ext| ext.handles(cmd))?;
648                let call = SlashCall {
649                    session_id,
650                    sender_id,
651                    user_role,
652                };
653                extension.run(cmd, args, &call).await
654            }
655        })
656    }
657
658    async fn handle_status(&self, session_id: &str) -> String {
659        let now = Utc::now();
660        let view = StatusView {
661            now: self.host.owner_time(now),
662            mode: self.host.chat_mode(session_id, now).await,
663            running: crate::stop::running_work(
664                &self.task_registry,
665                self.agent.as_ref(),
666                session_id,
667            )
668            .await,
669            next_scheduled: self.host.next_scheduled().await,
670        };
671        render_status(&view, now)
672    }
673
674    /// `/private [off]`: the sender's next message in this chat is not
675    /// remembered or learned from (it only narrows memory, so anyone may ask).
676    /// `off` cancels. Both are the sender's own: in a shared chat nobody else
677    /// consumes or cancels them.
678    async fn handle_private(
679        &self,
680        args: &str,
681        session_id: &str,
682        sender_id: Option<&str>,
683    ) -> String {
684        let on = match args.trim().to_ascii_lowercase().as_str() {
685            "" => true,
686            "off" => false,
687            _ => return "Usage: /private [off]".to_string(),
688        };
689        match self
690            .host
691            .set_next_message_private(session_id, sender_id, on)
692            .await
693        {
694            Ok(()) if on => "Your next message won't be remembered or learned from. \
695                             Memory can still be used to answer it."
696                .to_string(),
697            Ok(()) => "Cancelled: your next message is remembered as usual.".to_string(),
698            Err(error) => format!("Could not set that: {error}"),
699        }
700    }
701
702    async fn handle_readonly(&self, session_id: &str, user_role: UserRole) -> String {
703        self.handle_mode("readonly", session_id, user_role).await
704    }
705
706    /// `/mode [full|unrestricted|readonly]`: the owner narrows or restores this
707    /// chat's tool authority. Explicit command syntax, persisted with an expiry.
708    async fn handle_mode(&self, args: &str, session_id: &str, user_role: UserRole) -> String {
709        let session_mode_ttl_hours = self.host.chat_mode_hours();
710        const NOT_OWNER: &str = "Only the owner can change the mode.";
711        const USAGE: &str = "Usage: /mode [full|unrestricted|readonly]";
712        if user_role != UserRole::Owner {
713            return NOT_OWNER.to_string();
714        }
715        let now = Utc::now();
716        let requested = match args.trim().to_ascii_lowercase().as_str() {
717            "" => return mode_line(self.host.chat_mode(session_id, now).await, now),
718            "full" => ChatMode::Full,
719            "unrestricted" => ChatMode::Unrestricted,
720            "readonly" | "read-only" | "read_only" => ChatMode::ReadOnly,
721            _ => return USAGE.to_string(),
722        };
723        match self.host.set_chat_mode(session_id, requested, now).await {
724            Ok(_) => match requested {
725                ChatMode::ReadOnly => format!(
726                    "Read-only for this chat for the next {session_mode_ttl_hours} hours, starting now, including work already running. aidaemon can look but not change anything. Send /mode full to end it early."
727                ),
728                ChatMode::Unrestricted => format!(
729                    "Unrestricted for this chat for the next {session_mode_ttl_hours} hours, starting with your next message."
730                ),
731                ChatMode::Full => "Back to full access from your next message.".to_string(),
732            },
733            Err(error) => {
734                tracing::warn!(session_id, %error, "Could not change the session mode");
735                "Couldn't change the mode right now.".to_string()
736            }
737        }
738    }
739
740    async fn handle_context(&self, session_id: &str, user_role: UserRole) -> String {
741        if user_role != UserRole::Owner {
742            return "Only the owner can inspect conversation context coverage.".to_string();
743        }
744        let model = self.agent.current_model().await;
745        let (enabled, model_budget, trigger_tokens, recent_tokens, anchor) =
746            self.agent.context_debug_settings(session_id, &model).await;
747        let history = self.host.history(session_id, 10_000).await;
748        let summary = self.host.conversation_summary(session_id).await;
749        match (history, summary) {
750            (Ok(history), Ok(summary)) => {
751                let raw_values = history
752                    .iter()
753                    .map(|message| {
754                        serde_json::json!({
755                            "role": message.role,
756                            "content": message.content,
757                            "name": message.tool_name,
758                        })
759                    })
760                    .collect::<Vec<_>>();
761                let exact_tokens = self.host.estimate_message_tokens(&raw_values);
762                let compacted_messages = summary
763                    .as_ref()
764                    .map(|value| value.message_count)
765                    .unwrap_or(0);
766                let raw_recent_messages = history.len().saturating_sub(compacted_messages);
767                let summary_line = summary.as_ref().map_or_else(
768                    || "Summary: none yet".to_string(),
769                    |value| {
770                        format!(
771                            "Summary: {} messages through turn {} / message {} (~{} tokens)",
772                            value.message_count,
773                            value
774                                .last_turn_seq
775                                .map(|seq| seq.to_string())
776                                .unwrap_or_else(|| "legacy".to_string()),
777                            value.last_message_id,
778                            self.host.estimate_text_tokens(&value.summary)
779                        )
780                    },
781                );
782                format!(
783                    "Conversation context\nEnabled: {enabled}\nModel: {model}\nModel window: ~{model_budget} tokens\nCompaction high-water: ~{trigger_tokens} tokens\nRecent raw overlap target: ~{recent_tokens} tokens\n{summary_line}\nPersisted exact messages inspected: {} (~{exact_tokens} tokens)\nEstimated uncompacted messages: {raw_recent_messages}\nCurrent raw-turn anchor: {}\n\nExact retained history remains searchable even when it is not in the active prompt.",
784                    history.len(),
785                    anchor
786                        .map(|seq| seq.to_string())
787                        .unwrap_or_else(|| "not initialized".to_string())
788                )
789            }
790            (Err(error), _) | (_, Err(error)) => {
791                format!("Could not inspect conversation context: {error}")
792            }
793        }
794    }
795
796    async fn handle_model(&self, arg: &str) -> String {
797        if arg.is_empty() {
798            let current = self.agent.current_model().await;
799            format!(
800                "Current model: {}\n\nUsage: /model <model-name>\nExample: /model gemini-3-pro-preview",
801                current
802            )
803        } else {
804            self.agent.set_model(arg.to_string()).await;
805            format!(
806                "Model switched to: {}\nAuto-routing disabled. Use /auto to re-enable.",
807                arg
808            )
809        }
810    }
811
812    async fn handle_models(&self) -> String {
813        match self.agent.list_models().await {
814            Ok(models) => {
815                if models.is_empty() {
816                    "No models found from provider.".to_string()
817                } else {
818                    let current = self.agent.current_model().await;
819                    let list: Vec<String> = models
820                        .iter()
821                        .map(|m| {
822                            if *m == current {
823                                format!("• {} (active)", m)
824                            } else {
825                                format!("• {}", m)
826                            }
827                        })
828                        .collect();
829                    format!("Available models:\n{}", list.join("\n"))
830                }
831            }
832            Err(e) => format!("Failed to list models: {}", e),
833        }
834    }
835
836    async fn handle_auto(&self) -> String {
837        self.agent.clear_model_override().await;
838        "Auto-routing re-enabled. Model will be selected automatically based on query complexity."
839            .to_string()
840    }
841
842    async fn handle_tasks(&self, session_id: &str) -> String {
843        let running =
844            crate::stop::running_work(&self.task_registry, self.agent.as_ref(), session_id).await;
845        let failed = self
846            .task_registry
847            .list_for_session(session_id)
848            .await
849            .into_iter()
850            .filter(|entry| matches!(entry.status, TaskStatus::Failed(_)))
851            .collect::<Vec<_>>();
852        let now = Utc::now();
853        render_tasks(&running, &failed, now, self.host.owner_time(now).as_deref())
854    }
855
856    /// `/cancel`: everything running when it comes from one request (else
857    /// the list to pick from), `/cancel all` everything, `/cancel <n>` one
858    /// item. Each stop is read back before it is reported.
859    async fn handle_cancel(&self, arg: &str, session_id: &str, user_role: UserRole) -> String {
860        if user_role != UserRole::Owner {
861            return "Only the owner can stop running work in this chat.".to_string();
862        }
863        let Some(request) = cancel_request(arg) else {
864            return "Usage: /cancel, /cancel all or /cancel <number>. Send /tasks to see the \
865                    numbers."
866                .to_string();
867        };
868        crate::stop::stop(
869            &self.task_registry,
870            self.agent.as_ref(),
871            session_id,
872            request,
873        )
874        .await
875    }
876
877    async fn handle_clear(&self, session_id: &str) -> String {
878        // Stop the chat's sub-agents and background commands first (while
879        // the turn that waits on them still runs), then its turns, so the
880        // agent loop aborts instead of burning tokens after /clear.
881        let stopped_work =
882            crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
883                .await;
884        let cancelled_tasks = self
885            .task_registry
886            .cancel_running_for_session(session_id)
887            .await;
888        // Also cancel finite orchestration goals associated with this
889        // conversation. Recurring schedules and personal goals intentionally
890        // survive a context clear.
891        let cancelled_goals = self
892            .agent
893            .cancel_active_finite_work_for_session(session_id)
894            .await;
895
896        // Non-destructive: sets a context boundary so the next turn starts
897        // fresh, but the event history remains for memory and audit. Use /wipe
898        // to permanently delete.
899        match self.agent.clear_session_context(session_id).await {
900            Ok(_) => {
901                let mut cancellations = Vec::new();
902                if !cancelled_goals.is_empty() {
903                    cancellations.push(format!(
904                        "{} background goal{}",
905                        cancelled_goals.len(),
906                        if cancelled_goals.len() == 1 { "" } else { "s" }
907                    ));
908                }
909                let stopped = stopped_with_turns(cancelled_tasks.len(), stopped_work);
910                let suffix = clear_suffix(&cancellations, &stopped);
911                format!(
912                    "Context cleared. Starting fresh – your history is kept; use /wipe to \
913                     delete this chat's history.{suffix}"
914                )
915            }
916            Err(e) => format!("Failed to clear context: {}", e),
917        }
918    }
919
920    async fn handle_wipe(&self, session_id: &str) -> String {
921        // Irreversible, and one tap away from /clear in the command menu:
922        // the first /wipe only asks.
923        if self
924            .task_registry
925            .request_wipe(session_id, std::time::Instant::now())
926            == crate::tasks::WipeRequest::Requested
927        {
928            return format!(
929                "Nothing was erased. /wipe permanently deletes this conversation from the \
930                 database: its messages, search index, summaries and episodes. Facts already \
931                 saved to memory are kept. To start fresh and keep the history, use /clear \
932                 instead. To erase it, send /wipe again within {} minutes.",
933                crate::tasks::WIPE_CONFIRM_WINDOW.as_secs() / 60
934            );
935        }
936        let stopped_work =
937            crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
938                .await;
939        let cancelled = self
940            .task_registry
941            .cancel_running_for_session(session_id)
942            .await;
943
944        // Destructive: erases this session's active database artifacts.
945        match self.agent.clear_session(session_id).await {
946            Ok(_) => {
947                let stopped = stopped_with_turns(cancelled.len(), stopped_work);
948                let suffix = clear_suffix(&[], &stopped);
949                format!(
950                    "Conversation erased from the active database (events, exact-search index, \
951                     summaries, episodes, and raw memory spans). Facts already saved to memory \
952                     are kept without raw-message provenance. Existing encrypted backups may \
953                     retain older copies until their own lifecycle removes them.{suffix}"
954                )
955            }
956            Err(e) => format!("Failed to wipe conversation: {}", e),
957        }
958    }
959
960    async fn handle_cost(&self) -> String {
961        let now = Utc::now();
962        let since_24h = (now - chrono::Duration::hours(24))
963            .format("%Y-%m-%d %H:%M:%S")
964            .to_string();
965        let since_7d = (now - chrono::Duration::days(7))
966            .format("%Y-%m-%d %H:%M:%S")
967            .to_string();
968
969        let records_24h = match self.host.token_usage_since(&since_24h).await {
970            Ok(r) => r,
971            Err(e) => return format!("Failed to query token usage: {}", e),
972        };
973        let records_7d = match self.host.token_usage_since(&since_7d).await {
974            Ok(r) => r,
975            Err(e) => return format!("Failed to query token usage: {}", e),
976        };
977
978        let (input_24h, output_24h) = records_24h.iter().fold((0i64, 0i64), |(i, o), r| {
979            (i + r.input_tokens, o + r.output_tokens)
980        });
981        let (input_7d, output_7d) = records_7d.iter().fold((0i64, 0i64), |(i, o), r| {
982            (i + r.input_tokens, o + r.output_tokens)
983        });
984
985        // Top models (by total tokens in 7d)
986        let mut model_totals: HashMap<&str, i64> = HashMap::new();
987        for r in &records_7d {
988            *model_totals.entry(&r.model).or_insert(0) += r.input_tokens + r.output_tokens;
989        }
990        let mut models_sorted: Vec<(&&str, &i64)> = model_totals.iter().collect();
991        models_sorted.sort_by(|a, b| b.1.cmp(a.1));
992
993        let mut reply = format!(
994            "Token usage (last 24h):\n  Input:  {} tokens\n  Output: {} tokens\n\n\
995             Token usage (last 7d):\n  Input:  {} tokens\n  Output: {} tokens",
996            format_number(input_24h),
997            format_number(output_24h),
998            format_number(input_7d),
999            format_number(output_7d),
1000        );
1001
1002        if !models_sorted.is_empty() {
1003            reply.push_str("\n\nTop models (7d):");
1004            for (model, total) in models_sorted.iter().take(5) {
1005                reply.push_str(&format!("\n  {}: {} tokens", model, format_number(**total)));
1006            }
1007        }
1008
1009        reply
1010    }
1011}
1012
1013/// Format a number with comma separators (e.g. 12450 → "12,450").
1014pub fn format_number(n: i64) -> String {
1015    let s = n.to_string();
1016    let mut result = String::with_capacity(s.len() + s.len() / 3);
1017    for (i, c) in s.chars().rev().enumerate() {
1018        if i > 0 && i % 3 == 0 {
1019            result.push(',');
1020        }
1021        result.push(c);
1022    }
1023    result.chars().rev().collect()
1024}
1025
1026/// Build the /help response text from a list of command definitions.
1027///
1028/// `commands`: the command definitions to include (platform-specific).
1029/// `prefix`: command prefix character ("/" for Telegram/Discord, "!" for Slack).
1030/// `scope`: the everyday commands, or all of them (`/help all`). The text is
1031/// Markdown; each channel renders it in its own format.
1032pub fn build_help_text(commands: &[CommandDef], prefix: &str, scope: HelpScope) -> String {
1033    let p = prefix;
1034    let shown: Vec<&CommandDef> = match scope {
1035        HelpScope::Everyday => EVERYDAY_COMMANDS
1036            .iter()
1037            .filter_map(|name| commands.iter().find(|cmd| cmd.name == *name))
1038            .collect(),
1039        HelpScope::All => commands.iter().collect(),
1040    };
1041    let mut text = match scope {
1042        HelpScope::Everyday => String::from(
1043            "Just ask in plain words – I'll pick the right tools. For example: \
1044             _\"Check my disk space every 6 hours\"_ or _\"Send me the latest log file\"_.\n\n\
1045             **Everyday commands**",
1046        ),
1047        HelpScope::All => String::from("**All commands**"),
1048    };
1049    for cmd in shown {
1050        let label = match cmd.usage {
1051            Some(usage) => {
1052                // Replace the leading "/" with the platform prefix.
1053                if let Some(rest) = usage.strip_prefix('/') {
1054                    format!("{p}{rest}")
1055                } else {
1056                    usage.to_string()
1057                }
1058            }
1059            None => format!("{p}{}", cmd.name),
1060        };
1061        text.push_str(&format!("\n{} – {}", label, cmd.description));
1062    }
1063    if scope == HelpScope::Everyday {
1064        text.push_str(&format!("\n\nSend {p}help all for every command."));
1065    }
1066    text
1067}
1068
1069#[cfg(test)]
1070mod help_and_status_tests {
1071    use super::*;
1072
1073    /// `/clear` names the sub-agents and commands it stopped, the way
1074    /// `/cancel` does, rather than counting them.
1075    #[test]
1076    fn clear_names_what_it_stopped() {
1077        let suffix = clear_suffix(
1078            &["1 running task".to_string()],
1079            &[
1080                "Sub-agent: Counter A".to_string(),
1081                "Background command: a shell loop".to_string(),
1082            ],
1083        );
1084        assert_eq!(
1085            suffix,
1086            " (1 running task cancelled.)\n\n⏹️ Stopped:\n• Sub-agent: Counter A\n• \
1087             Background command: a shell loop"
1088        );
1089        assert_eq!(clear_suffix(&[], &[]), "");
1090    }
1091
1092    fn defs() -> Vec<CommandDef> {
1093        shared_commands()
1094    }
1095
1096    #[test]
1097    fn help_shows_the_everyday_commands_and_how_to_see_the_rest() {
1098        let help = build_help_text(&defs(), "/", HelpScope::Everyday);
1099        for name in EVERYDAY_COMMANDS {
1100            assert!(help.contains(&format!("\n/{name}")), "{name}: {help}");
1101        }
1102        assert!(!help.contains("/models"), "{help}");
1103        assert!(!help.contains('`'), "{help}");
1104        assert!(
1105            help.ends_with("Send /help all for every command."),
1106            "{help}"
1107        );
1108        let all = build_help_text(&defs(), "!", HelpScope::All);
1109        assert!(all.contains("!models – List available models"), "{all}");
1110        assert_eq!(HelpScope::from_args(" ALL "), HelpScope::All);
1111        assert_eq!(HelpScope::from_args(""), HelpScope::Everyday);
1112    }
1113
1114    #[test]
1115    fn an_unknown_command_suggests_the_closest_one() {
1116        let commands = defs();
1117        assert_eq!(closest_command("cleer", &commands), Some("clear"));
1118        assert_eq!(closest_command("stauts", &commands), Some("status"));
1119        assert_eq!(closest_command("weather", &commands), None);
1120        assert_eq!(
1121            unknown_command_reply("/claer", &commands, "/"),
1122            "I don't know /claer. Did you mean /clear? Send /help to see the commands."
1123        );
1124        assert_eq!(
1125            unknown_command_reply("/weather@my_bot", &commands, "/"),
1126            "I don't know /weather@my_bot. Send /help to see the commands."
1127        );
1128    }
1129
1130    #[test]
1131    fn private_can_carry_its_message() {
1132        assert_eq!(private_request("/private"), None);
1133        assert_eq!(private_request("/private off"), None);
1134        assert_eq!(private_request("/clear"), None);
1135        assert_eq!(
1136            private_request("/private/private"),
1137            Some(PrivateRequest::Next)
1138        );
1139        assert_eq!(
1140            private_request("/privateAnother test"),
1141            Some(PrivateRequest::With("Another test"))
1142        );
1143        assert_eq!(
1144            private_request("/private@my_bot what's my balance?"),
1145            Some(PrivateRequest::With("what's my balance?"))
1146        );
1147        assert_eq!(
1148            private_request("/private /private hi"),
1149            Some(PrivateRequest::With("hi"))
1150        );
1151    }
1152
1153    #[test]
1154    fn tasks_lists_every_running_thing_with_a_number() {
1155        let now = Utc::now();
1156        let running = crate::stop::WorkList::for_tests(vec![
1157            (
1158                7,
1159                crate::stop::TURN_LABEL,
1160                now - chrono::Duration::seconds(40),
1161                "req-1",
1162            ),
1163            (
1164                8,
1165                "Sub-agent: Counting agent A",
1166                now - chrono::Duration::seconds(30),
1167                "req-1",
1168            ),
1169            (
1170                9,
1171                "Background command: for i in $(seq 1 300); do echo $i; sleep 2; done",
1172                now - chrono::Duration::seconds(30),
1173                "req-1",
1174            ),
1175        ]);
1176        let tasks = render_tasks(&running, &[], now, None);
1177        assert!(
1178            tasks.starts_with("Running in this chat:\n#7 Working on your message (40s so far)"),
1179            "{tasks}"
1180        );
1181        assert!(
1182            tasks.contains("\n#8 Sub-agent: Counting agent A (30s so far)"),
1183            "{tasks}"
1184        );
1185        assert!(
1186            tasks.contains("\n#9 Background command: for i in"),
1187            "{tasks}"
1188        );
1189        assert!(
1190            tasks.contains("Send /cancel to stop all of it, or /cancel <number> for one."),
1191            "{tasks}"
1192        );
1193        let quiet = render_tasks(&crate::stop::WorkList::default(), &[], now, None);
1194        assert!(
1195            quiet.starts_with("Nothing is running in this chat right now."),
1196            "{quiet}"
1197        );
1198    }
1199
1200    /// A `/tasks` reply stays in the chat after the work it lists has moved
1201    /// on, so it says when it was read (live 2026-11-12: an old "#1 Working
1202    /// on your message" reply looked current).
1203    #[test]
1204    fn tasks_says_when_it_was_read() {
1205        let now = Utc::now();
1206        let running = crate::stop::WorkList::for_tests(vec![(
1207            1,
1208            crate::stop::TURN_LABEL,
1209            now - chrono::Duration::seconds(40),
1210            "req-1",
1211        )]);
1212        let tasks = render_tasks(&running, &[], now, Some("5:44 PM ET"));
1213        assert!(
1214            tasks.starts_with(
1215                "As of 5:44 PM ET:\nRunning in this chat:\n#1 Working on your message"
1216            ),
1217            "{tasks}"
1218        );
1219        let quiet = render_tasks(
1220            &crate::stop::WorkList::default(),
1221            &[],
1222            now,
1223            Some("5:44 PM ET"),
1224        );
1225        assert!(
1226            quiet.starts_with("As of 5:44 PM ET:\nNothing is running"),
1227            "{quiet}"
1228        );
1229    }
1230
1231    /// `/clear` names the turn it cancelled in the same list as the helpers
1232    /// it stopped, with no separate count to disagree with that list.
1233    #[test]
1234    fn clear_lists_the_cancelled_turn_with_the_stopped_helpers() {
1235        let stopped = stopped_with_turns(
1236            1,
1237            vec!["Sub-agent: Counter A".into(), "Sub-agent: Counter B".into()],
1238        );
1239        let suffix = clear_suffix(&[], &stopped);
1240        assert!(!suffix.contains("cancelled"), "{suffix}");
1241        assert_eq!(
1242            suffix,
1243            "\n\n⏹️ Stopped:\n• Working on your message\n• Sub-agent: Counter A\n• Sub-agent: Counter B"
1244        );
1245    }
1246
1247    #[test]
1248    fn cancel_arguments_are_bare_all_or_numbers() {
1249        use crate::stop::StopRequest;
1250        assert_eq!(cancel_request(""), Some(StopRequest::Bare));
1251        assert_eq!(cancel_request(" ALL "), Some(StopRequest::All));
1252        assert_eq!(cancel_request("3"), Some(StopRequest::Numbers(vec![3])));
1253        assert_eq!(
1254            cancel_request("#3, 4"),
1255            Some(StopRequest::Numbers(vec![3, 4]))
1256        );
1257        assert_eq!(cancel_request("both"), None);
1258    }
1259
1260    #[test]
1261    fn status_says_mode_running_work_and_whats_next() {
1262        let now = Utc::now();
1263        let quiet = StatusView {
1264            now: None,
1265            mode: None,
1266            running: crate::stop::WorkList::default(),
1267            next_scheduled: None,
1268        };
1269        assert_eq!(
1270            render_status(&quiet, now),
1271            "Mode: full.\nRunning: nothing right now.\nNext scheduled: nothing."
1272        );
1273        let busy = StatusView {
1274            now: Some("2:05 PM ET".to_string()),
1275            mode: Some((ChatMode::ReadOnly, Some(now + chrono::Duration::hours(3)))),
1276            running: crate::stop::WorkList::for_tests(vec![
1277                (
1278                    7,
1279                    crate::stop::TURN_LABEL,
1280                    now - chrono::Duration::minutes(2),
1281                    "a",
1282                ),
1283                (
1284                    8,
1285                    "Sub-agent: Install a Drupal demo site with DDEV",
1286                    now - chrono::Duration::minutes(4),
1287                    "a",
1288                ),
1289            ]),
1290            next_scheduled: Some(ScheduledItem {
1291                what: "Check disk space".to_string(),
1292                when: "2:39 PM ET".to_string(),
1293            }),
1294        };
1295        let status = render_status(&busy, now);
1296        assert!(
1297            status.starts_with("As of 2:05 PM ET: Mode: read-only (about 3h left)."),
1298            "{status}"
1299        );
1300        assert!(
1301            status.contains("• Working on your message (2m so far, /cancel 7 to stop it)"),
1302            "{status}"
1303        );
1304        assert!(
1305            status.contains(
1306                "• Sub-agent: Install a Drupal demo site with DDEV (4m so far, /cancel 8 to stop it)"
1307            ),
1308            "{status}"
1309        );
1310        assert!(
1311            status.ends_with("Next scheduled: Check disk space – 2:39 PM ET"),
1312            "{status}"
1313        );
1314    }
1315
1316    /// A scheduled item is named by a rule, never by a sentence cut short:
1317    /// its owner's name for it, else a description that fits whole, else
1318    /// that it has no name.
1319    #[test]
1320    fn a_scheduled_item_is_named_never_cut() {
1321        let long = "Every day, independently manage and publish to the synthetic blog at \
1322                    https://blog.example.test following the editorial plan";
1323        assert_eq!(scheduled_name(Some(" Daily blog "), long), "Daily blog");
1324        assert_eq!(scheduled_name(None, "Check disk space"), "Check disk space");
1325        let unnamed = scheduled_name(None, long);
1326        assert_eq!(unnamed, "An automation without a name (see /work)");
1327        for name in [unnamed, scheduled_name(Some("Daily blog"), long)] {
1328            assert!(!name.contains('…') && !name.contains("..."), "{name}");
1329        }
1330    }
1331}
1332
1333#[cfg(test)]
1334mod format_tests {
1335    use super::*;
1336
1337    #[test]
1338    fn test_format_number() {
1339        assert_eq!(format_number(0), "0");
1340        assert_eq!(format_number(999), "999");
1341        assert_eq!(format_number(1000), "1,000");
1342        assert_eq!(format_number(12450), "12,450");
1343        assert_eq!(format_number(1_000_000), "1,000,000");
1344    }
1345}