aidaemon-channels 0.29.0

Chat channel contract and the runner that connects channels to aidaemon agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
//! Slash commands shared by every chat platform: the command menu
//! ([`shared_commands`], [`build_help_text`]) and the commands that behave the
//! same everywhere ([`SharedCommands`]): models, chat operations, context,
//! `/private`, `/mode`, `/clear`, `/wipe` and usage. A host supplies its
//! services through [`CommandHost`] and adds its own commands (`/work`,
//! `/reload`...) as [`SlashCommand`]s. Internal to aidaemon, no stability
//! promise; the public contract is [`crate::channel`].

use std::collections::HashMap;
use std::sync::Arc;

use aidaemon_events::conversation::{ConversationSummary, Message};
use aidaemon_events::provider::TokenUsageRecord;
use aidaemon_tools::duration_format::{ZeroUnitStyle, compact_chrono_duration};
use aidaemon_tools::semantics::UserRole;
use async_trait::async_trait;
use chrono::{DateTime, Utc};

use crate::ports::ChannelAgentRuntime;
use crate::tasks::{TaskRegistry, TaskStatus};

/// Whether a chat message is a slash command: `/name` or `/name@bot`, where
/// `name` is letters, digits and underscores (Telegram's command syntax).
/// A message that merely starts with a path (`/tmp/x.py is broken`) is not.
pub fn is_slash_command(text: &str) -> bool {
    let Some(first) = text.split_whitespace().next() else {
        return false;
    };
    let Some(rest) = first.strip_prefix('/') else {
        return false;
    };
    let name = rest.split_once('@').map_or(rest, |(name, _bot)| name);
    !name.is_empty()
        && name.starts_with(|c: char| c.is_ascii_alphabetic())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

#[cfg(test)]
mod slash_command_tests {
    use super::is_slash_command;

    #[test]
    fn commands_are_names_and_paths_are_messages() {
        for command in [
            "/help",
            "/model gpt-5.6-terra",
            "/clear",
            "/start@aidaemon_bot",
            "/set_up now",
        ] {
            assert!(is_slash_command(command), "{command}");
        }
        for message in [
            "/tmp/aidaemon-live/prime/prime.py has a bug",
            "/Users/alice/notes.txt",
            "/ what",
            "/",
            "/123",
            "hello /help",
        ] {
            assert!(!is_slash_command(message), "{message}");
        }
    }
}

/// Single source of truth for command definitions.
///
/// Each command is defined once here; the registry drives Telegram's
/// `setMyCommands` API, the `/help` output, and (in the future) Slack/Discord
/// command registration.
pub struct CommandDef {
    /// Command name without leading `/` or `!`.
    pub name: &'static str,
    /// Short description shown in Telegram's command menu and `/help` text.
    /// Must be 3-256 characters for Telegram's `BotCommand`.
    pub description: &'static str,
    /// Optional usage string shown only in `/help` (e.g. `/model [name]`).
    pub usage: Option<&'static str>,
    /// Which platform group this command belongs to.
    pub category: CommandCategory,
}

/// Determines which platforms show a command.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CommandCategory {
    /// Available on all platforms.
    Core,
    /// Telegram + Slack (process restart).
    Restart,
    /// Telegram-only (dynamic bot management).
    Connect,
    /// Telegram-only (terminal/agent bridge).
    Terminal,
}

/// Returns the shared commands available on every platform.
pub fn shared_commands() -> Vec<CommandDef> {
    vec![
        CommandDef {
            name: "model",
            description: "Show or switch AI model",
            usage: Some("/model [name]"),
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "models",
            description: "List available models",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "auto",
            description: "Re-enable automatic model routing",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "reload",
            description: "Reload configuration",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "tasks",
            description: "List running tasks",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "status",
            description: "Show this chat's mode, running tasks and what's next",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "work",
            description: "See and manage longer work that waits or runs on its own",
            usage: Some("/work [ready|running|blocked|show|comment|unblock|retry]"),
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "cancel",
            description: "Stop what's running in this chat",
            usage: Some("/cancel [all|number]"),
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "clear",
            description: "Start fresh conversation (history kept)",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "wipe",
            description: "Permanently delete this conversation (send twice to confirm)",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "cost",
            description: "Show token usage stats",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "context",
            description: "Show conversation context coverage",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "checkpoints",
            description: "List filesystem checkpoints",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "readonly",
            description: "Make this chat read-only for 4 hours",
            usage: None,
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "private",
            description: "Don't remember or learn from your next message",
            usage: Some("/private [off]"),
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "mode",
            description: "Show or change this chat's access mode",
            usage: Some("/mode [full|unrestricted|readonly]"),
            category: CommandCategory::Core,
        },
        CommandDef {
            name: "rollback",
            description: "Preview or confirm a checkpoint rollback",
            usage: Some("/rollback [checkpoint-id|confirm TOKEN]"),
            category: CommandCategory::Core,
        },
    ]
}

/// A chat's tool authority as the owner set it with `/mode`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatMode {
    ReadOnly,
    Full,
    Unrestricted,
}

/// What the shared commands need from the host besides the agent.
#[async_trait]
pub trait CommandHost: Send + Sync {
    /// `/private`: whether the sender's next message in this chat is kept
    /// out of memory (`on`), or that request cancelled.
    async fn set_next_message_private(
        &self,
        session_id: &str,
        sender_id: Option<&str>,
        on: bool,
    ) -> anyhow::Result<()>;
    /// The chat's mode in force at `now` and when it ends; `None` is full.
    async fn chat_mode(
        &self,
        session_id: &str,
        now: DateTime<Utc>,
    ) -> Option<(ChatMode, Option<DateTime<Utc>>)>;
    /// Set the chat's mode from `now`; returns when it ends.
    async fn set_chat_mode(
        &self,
        session_id: &str,
        mode: ChatMode,
        now: DateTime<Utc>,
    ) -> anyhow::Result<DateTime<Utc>>;
    /// How many hours a narrowed or widened mode lasts.
    fn chat_mode_hours(&self) -> i64;
    async fn history(&self, session_id: &str, limit: usize) -> anyhow::Result<Vec<Message>>;
    async fn conversation_summary(
        &self,
        session_id: &str,
    ) -> anyhow::Result<Option<ConversationSummary>>;
    /// Estimated tokens of stored messages (`role`, `content`, `name`).
    fn estimate_message_tokens(&self, messages: &[serde_json::Value]) -> usize;
    fn estimate_text_tokens(&self, text: &str) -> usize;
    /// Token usage recorded since `since` (`%Y-%m-%d %H:%M:%S`, UTC).
    async fn token_usage_since(&self, since: &str) -> anyhow::Result<Vec<TokenUsageRecord>>;
    /// The owner's next scheduled item, for `/status`; `None` when nothing
    /// is scheduled (or the host keeps no schedules).
    async fn next_scheduled(&self) -> Option<ScheduledItem> {
        None
    }

    /// `at` in the owner's local time and format ("2:39 PM ET"), for the
    /// first line of `/status`; `None` when the host has no owner zone.
    fn owner_time(&self, _at: DateTime<Utc>) -> Option<String> {
        None
    }
}

/// One scheduled item as `/status` shows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduledItem {
    /// What runs, as [`scheduled_name`] names it.
    pub what: String,
    /// When, already in the owner's local time ("2:39 PM ET").
    pub when: String,
}

/// The most a scheduled item's description may run to and still stand as
/// its name on `/status`.
const SCHEDULED_NAME_MAX: usize = 60;

/// What `/status` calls a scheduled item: the name its owner gave it, else
/// its description when that fits whole, else that it has no name. Never a
/// sentence cut short (live 2026-11-13: "…blog at…").
pub fn scheduled_name(name: Option<&str>, description: &str) -> String {
    if let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) {
        return name.to_string();
    }
    let description = description.split_whitespace().collect::<Vec<_>>().join(" ");
    if !description.is_empty() && description.chars().count() <= SCHEDULED_NAME_MAX {
        return description;
    }
    "An automation without a name (see /work)".to_string()
}

/// What `/status` reports, read from typed state.
#[derive(Debug, Clone)]
pub struct StatusView {
    /// The current time in the owner's local format, when known.
    pub now: Option<String>,
    /// The chat's mode and when it ends; `None` is full access.
    pub mode: Option<(ChatMode, Option<DateTime<Utc>>)>,
    /// Everything running for the chat: its turn, sub-agents and background
    /// commands. A turn is named by what it is, never by the message that
    /// started it: that message may be a reply ("Yes, move the files").
    pub running: crate::stop::WorkList,
    pub next_scheduled: Option<ScheduledItem>,
}

/// The one line that says a chat's mode, as `/mode` and `/status` show it.
fn mode_line(mode: Option<(ChatMode, Option<DateTime<Utc>>)>, now: DateTime<Utc>) -> String {
    let left = |until: Option<DateTime<Utc>>| {
        until.map_or_else(String::new, |at| {
            format!(
                " (about {} left)",
                compact_chrono_duration(at - now, ZeroUnitStyle::Trim)
            )
        })
    };
    match mode {
        Some((ChatMode::ReadOnly, until)) => format!("Mode: read-only{}.", left(until)),
        Some((ChatMode::Unrestricted, until)) => format!("Mode: unrestricted{}.", left(until)),
        Some((ChatMode::Full, _)) | None => "Mode: full.".to_string(),
    }
}

/// How `/cancel` stops what is listed.
fn cancel_hint(running: &crate::stop::WorkList) -> &'static str {
    match running.entries.len() {
        0 => "",
        1 => "Send /cancel to stop it.",
        _ if running.requests() > 1 => {
            "Send /cancel <number> to stop one, or /cancel all to stop everything."
        }
        _ => "Send /cancel to stop all of it, or /cancel <number> for one.",
    }
}

/// `/tasks`: everything running for the chat (its turn, sub-agents and
/// background commands), numbered for `/cancel`, and its failed turns. The
/// reply is a snapshot that stays in the chat, so it says when it was taken
/// (`as_of`, the owner's clock) and never reads as live later.
pub fn render_tasks(
    running: &crate::stop::WorkList,
    failed: &[crate::tasks::TaskEntry],
    now: DateTime<Utc>,
    as_of: Option<&str>,
) -> String {
    let stamp = as_of.map(|at| format!("As of {at}:\n"));
    let stamp = stamp.as_deref().unwrap_or("");
    if running.entries.is_empty() && failed.is_empty() {
        return format!(
            "{stamp}Nothing is running in this chat right now. Use /work for longer work that \
             waits or runs on its own."
        );
    }
    let mut sections = Vec::new();
    if running.entries.is_empty() {
        sections.push("Nothing is running in this chat right now.".to_string());
    } else {
        sections.push(format!(
            "Running in this chat:\n{}\n\n{}",
            running.lines(now).join("\n"),
            cancel_hint(running)
        ));
    }
    if !failed.is_empty() {
        let lines: Vec<String> = failed
            .iter()
            .map(|entry| {
                let at = entry.finished_at.unwrap_or(now);
                format!(
                    "#{} {} – it failed after {}",
                    entry.id,
                    crate::stop::TURN_LABEL,
                    compact_chrono_duration(at - entry.started_at, ZeroUnitStyle::Trim)
                )
            })
            .collect();
        sections.push(format!("Recently failed:\n{}", lines.join("\n")));
    }
    sections.push("Use /work for longer work that waits or runs on its own.".to_string());
    format!("{stamp}{}", sections.join("\n\n"))
}

/// `/status`: the chat's mode, what is running and what is scheduled next.
pub fn render_status(view: &StatusView, now: DateTime<Utc>) -> String {
    let mode = mode_line(view.mode, now);
    let mut lines = vec![match &view.now {
        Some(local) => format!("As of {local}: {mode}"),
        None => mode,
    }];
    if view.running.entries.is_empty() {
        lines.push("Running: nothing right now.".to_string());
    } else {
        lines.push("Running:".to_string());
        for entry in &view.running.entries {
            lines.push(format!(
                "• {} ({} so far, /cancel {} to stop it)",
                crate::presentation::word_preview(&entry.title, 120),
                compact_chrono_duration(now - entry.started_at, ZeroUnitStyle::Trim),
                entry.number
            ));
        }
    }
    lines.push(match &view.next_scheduled {
        Some(item) => format!("Next scheduled: {} – {}", item.what, item.when),
        None => "Next scheduled: nothing.".to_string(),
    });
    lines.join("\n")
}

/// What a `/clear` or `/wipe` stopped, as one list: the chat's cancelled
/// turns (named as `/tasks` names them) before its sub-agents and commands,
/// so no separate count can disagree with the list (live 2026-11-12: "(1
/// running task cancelled.)" over two stopped sub-agents).
fn stopped_with_turns(turns: usize, work: Vec<String>) -> Vec<String> {
    let mut stopped = vec![crate::stop::TURN_LABEL.to_string(); turns];
    stopped.extend(work);
    stopped
}

/// The end of a `/clear` or `/wipe` reply: what else was cancelled, then
/// the sub-agents and background commands stopped, named as `/cancel` names
/// them.
fn clear_suffix(cancellations: &[String], stopped_work: &[String]) -> String {
    let mut suffix = if cancellations.is_empty() {
        String::new()
    } else {
        format!(" ({} cancelled.)", cancellations.join(" and "))
    };
    let stopped = crate::stop::stopped_list(stopped_work);
    if !stopped.is_empty() {
        suffix.push_str("\n\n");
        suffix.push_str(&stopped);
    }
    suffix
}

/// What `/cancel`'s arguments ask for; `None` when they are not a request.
pub fn cancel_request(args: &str) -> Option<crate::stop::StopRequest> {
    let args = args.trim();
    if args.is_empty() {
        return Some(crate::stop::StopRequest::Bare);
    }
    if args.eq_ignore_ascii_case("all") {
        return Some(crate::stop::StopRequest::All);
    }
    let numbers: Option<Vec<u64>> = args
        .split(|c: char| c.is_whitespace() || c == ',')
        .filter(|part| !part.is_empty())
        .map(|part| part.trim_start_matches('#').parse::<u64>().ok())
        .collect();
    numbers
        .filter(|numbers| !numbers.is_empty())
        .map(crate::stop::StopRequest::Numbers)
}

/// The command closest to an unknown `name` (without its prefix) by edit
/// distance, when one is close enough to be a likely typo.
pub fn closest_command<'a>(name: &str, commands: &'a [CommandDef]) -> Option<&'a str> {
    let name = name.to_ascii_lowercase();
    let len = name.chars().count();
    if len == 0 {
        return None;
    }
    let limit = if len <= 4 { 1 } else { 2 };
    commands
        .iter()
        .map(|command| (edit_distance(&name, command.name), command.name))
        .filter(|(distance, _)| *distance <= limit)
        .min_by_key(|(distance, _)| *distance)
        .map(|(_, command)| command)
}

fn edit_distance(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut previous: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut current = vec![i + 1; b.len() + 1];
        for (j, cb) in b.iter().enumerate() {
            let substitution = previous[j] + usize::from(ca != *cb);
            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
        }
        previous = current;
    }
    previous[b.len()]
}

/// The reply to a command nobody handles: a likely intended command when one
/// is close, and where to find the rest.
pub fn unknown_command_reply(cmd: &str, commands: &[CommandDef], prefix: &str) -> String {
    let name = cmd
        .trim_start_matches(prefix)
        .split('@')
        .next()
        .unwrap_or("");
    match closest_command(name, commands) {
        Some(suggestion) => format!(
            "I don't know {cmd}. Did you mean {prefix}{suggestion}? Send {prefix}help to see \
             the commands."
        ),
        None => format!("I don't know {cmd}. Send {prefix}help to see the commands."),
    }
}

/// How `/private` was sent when it carries more than the bare command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrivateRequest<'a> {
    /// Only `/private` (said once or more, "/private/private"): the next
    /// message is kept private.
    Next,
    /// `/private` with the message itself ("/private what's my balance?",
    /// "/privateWhat's…"): this message is the private one.
    With(&'a str),
}

/// Read `/private` sent together with its message. `None` for anything
/// else, including `/private off` and the bare `/private`, which the
/// command itself answers.
pub fn private_request(text: &str) -> Option<PrivateRequest<'_>> {
    let mut rest = text.trim_start();
    let mut seen = 0usize;
    while let Some(after) = strip_prefix_ignore_case(rest, "/private") {
        seen += 1;
        // Telegram may append the bot name in groups: `/private@my_bot`.
        rest = match after.strip_prefix('@') {
            Some(bot) => bot.find(char::is_whitespace).map_or("", |at| &bot[at..]),
            None => after,
        };
        rest = rest.trim_start();
    }
    if seen == 0 {
        return None;
    }
    let message = rest.trim();
    if message.is_empty() {
        return (seen > 1).then_some(PrivateRequest::Next);
    }
    if message.eq_ignore_ascii_case("off") {
        return None;
    }
    Some(PrivateRequest::With(message))
}

fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
    let head = text.get(..prefix.len())?;
    head.eq_ignore_ascii_case(prefix)
        .then(|| &text[prefix.len()..])
}

/// The commands `/help` shows first: the ones used day to day.
pub const EVERYDAY_COMMANDS: &[&str] = &["clear", "tasks", "status", "private", "readonly", "mode"];

/// How much `/help` shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HelpScope {
    /// The everyday commands and how to see the rest.
    Everyday,
    /// Every command the platform has (`/help all`).
    All,
}

impl HelpScope {
    pub fn from_args(args: &str) -> Self {
        if args.trim().eq_ignore_ascii_case("all") {
            Self::All
        } else {
            Self::Everyday
        }
    }
}

/// Who sent a command, and where.
pub struct SlashCall<'a> {
    pub session_id: &'a str,
    pub sender_id: Option<&'a str>,
    pub user_role: UserRole,
}

/// A command the host adds to the shared ones.
#[async_trait]
pub trait SlashCommand: Send + Sync {
    /// Whether this handles `cmd` (with its `/`).
    fn handles(&self, cmd: &str) -> bool;
    async fn run(&self, cmd: &str, args: &str, call: &SlashCall<'_>) -> String;
    /// The commands this handles, for the platform's command menu and
    /// `/help`. Every name here must be one [`Self::handles`] accepts.
    fn commands(&self) -> Vec<CommandDef> {
        Vec::new()
    }
}

/// Shared command dispatcher for commands that behave identically across
/// Telegram, Slack, and Discord channels.
pub struct SharedCommands {
    pub agent: Arc<dyn ChannelAgentRuntime>,
    pub host: Arc<dyn CommandHost>,
    pub task_registry: Arc<TaskRegistry>,
    /// The host's own commands, asked in order for any other name.
    pub extensions: Vec<Arc<dyn SlashCommand>>,
}

impl SharedCommands {
    /// The menu and `/help` entries of the host's own commands.
    pub fn extension_commands(&self) -> Vec<CommandDef> {
        self.extensions
            .iter()
            .flat_map(|extension| extension.commands())
            .collect()
    }

    /// Try to handle a shared command. Returns `Some(reply)` if the command was
    /// recognised, `None` if the channel should handle it itself.
    pub async fn dispatch(
        &self,
        cmd: &str,
        args: &str,
        session_id: &str,
        sender_id: Option<&str>,
        user_role: UserRole,
    ) -> Option<String> {
        // Everything here but a private aside and the chat's own task list
        // changes or reveals something of the owner's (the model for every
        // chat, running work, history, cost, the daemon itself), so it is
        // the owner's: a guest in a shared chat does not get it.
        // (`/cancel`, `/context`, `/readonly` and `/mode` say so themselves.)
        if user_role != UserRole::Owner
            && !matches!(
                cmd,
                "/private" | "/tasks" | "/cancel" | "/context" | "/readonly" | "/mode"
            )
        {
            let shared = matches!(
                cmd,
                "/model" | "/models" | "/auto" | "/clear" | "/new" | "/status" | "/wipe" | "/cost"
            ) || self.extensions.iter().any(|ext| ext.handles(cmd));
            return shared.then(|| format!("Only the owner can use {cmd}."));
        }
        Some(match cmd {
            "/model" => self.handle_model(args).await,
            "/models" => self.handle_models().await,
            "/auto" => self.handle_auto().await,
            "/tasks" => self.handle_tasks(session_id).await,
            "/cancel" => self.handle_cancel(args, session_id, user_role).await,
            "/clear" | "/new" => self.handle_clear(session_id).await,
            "/status" => self.handle_status(session_id).await,
            "/wipe" => self.handle_wipe(session_id).await,
            "/cost" => self.handle_cost().await,
            "/context" => self.handle_context(session_id, user_role).await,
            "/readonly" => self.handle_readonly(session_id, user_role).await,
            "/private" => self.handle_private(args, session_id, sender_id).await,
            "/mode" => self.handle_mode(args, session_id, user_role).await,
            _ => {
                let extension = self.extensions.iter().find(|ext| ext.handles(cmd))?;
                let call = SlashCall {
                    session_id,
                    sender_id,
                    user_role,
                };
                extension.run(cmd, args, &call).await
            }
        })
    }

    async fn handle_status(&self, session_id: &str) -> String {
        let now = Utc::now();
        let view = StatusView {
            now: self.host.owner_time(now),
            mode: self.host.chat_mode(session_id, now).await,
            running: crate::stop::running_work(
                &self.task_registry,
                self.agent.as_ref(),
                session_id,
            )
            .await,
            next_scheduled: self.host.next_scheduled().await,
        };
        render_status(&view, now)
    }

    /// `/private [off]`: the sender's next message in this chat is not
    /// remembered or learned from (it only narrows memory, so anyone may ask).
    /// `off` cancels. Both are the sender's own: in a shared chat nobody else
    /// consumes or cancels them.
    async fn handle_private(
        &self,
        args: &str,
        session_id: &str,
        sender_id: Option<&str>,
    ) -> String {
        let on = match args.trim().to_ascii_lowercase().as_str() {
            "" => true,
            "off" => false,
            _ => return "Usage: /private [off]".to_string(),
        };
        match self
            .host
            .set_next_message_private(session_id, sender_id, on)
            .await
        {
            Ok(()) if on => "Your next message won't be remembered or learned from. \
                             Memory can still be used to answer it."
                .to_string(),
            Ok(()) => "Cancelled: your next message is remembered as usual.".to_string(),
            Err(error) => format!("Could not set that: {error}"),
        }
    }

    async fn handle_readonly(&self, session_id: &str, user_role: UserRole) -> String {
        self.handle_mode("readonly", session_id, user_role).await
    }

    /// `/mode [full|unrestricted|readonly]`: the owner narrows or restores this
    /// chat's tool authority. Explicit command syntax, persisted with an expiry.
    async fn handle_mode(&self, args: &str, session_id: &str, user_role: UserRole) -> String {
        let session_mode_ttl_hours = self.host.chat_mode_hours();
        const NOT_OWNER: &str = "Only the owner can change the mode.";
        const USAGE: &str = "Usage: /mode [full|unrestricted|readonly]";
        if user_role != UserRole::Owner {
            return NOT_OWNER.to_string();
        }
        let now = Utc::now();
        let requested = match args.trim().to_ascii_lowercase().as_str() {
            "" => return mode_line(self.host.chat_mode(session_id, now).await, now),
            "full" => ChatMode::Full,
            "unrestricted" => ChatMode::Unrestricted,
            "readonly" | "read-only" | "read_only" => ChatMode::ReadOnly,
            _ => return USAGE.to_string(),
        };
        match self.host.set_chat_mode(session_id, requested, now).await {
            Ok(_) => match requested {
                ChatMode::ReadOnly => format!(
                    "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."
                ),
                ChatMode::Unrestricted => format!(
                    "Unrestricted for this chat for the next {session_mode_ttl_hours} hours, starting with your next message."
                ),
                ChatMode::Full => "Back to full access from your next message.".to_string(),
            },
            Err(error) => {
                tracing::warn!(session_id, %error, "Could not change the session mode");
                "Couldn't change the mode right now.".to_string()
            }
        }
    }

    async fn handle_context(&self, session_id: &str, user_role: UserRole) -> String {
        if user_role != UserRole::Owner {
            return "Only the owner can inspect conversation context coverage.".to_string();
        }
        let model = self.agent.current_model().await;
        let (enabled, model_budget, trigger_tokens, recent_tokens, anchor) =
            self.agent.context_debug_settings(session_id, &model).await;
        let history = self.host.history(session_id, 10_000).await;
        let summary = self.host.conversation_summary(session_id).await;
        match (history, summary) {
            (Ok(history), Ok(summary)) => {
                let raw_values = history
                    .iter()
                    .map(|message| {
                        serde_json::json!({
                            "role": message.role,
                            "content": message.content,
                            "name": message.tool_name,
                        })
                    })
                    .collect::<Vec<_>>();
                let exact_tokens = self.host.estimate_message_tokens(&raw_values);
                let compacted_messages = summary
                    .as_ref()
                    .map(|value| value.message_count)
                    .unwrap_or(0);
                let raw_recent_messages = history.len().saturating_sub(compacted_messages);
                let summary_line = summary.as_ref().map_or_else(
                    || "Summary: none yet".to_string(),
                    |value| {
                        format!(
                            "Summary: {} messages through turn {} / message {} (~{} tokens)",
                            value.message_count,
                            value
                                .last_turn_seq
                                .map(|seq| seq.to_string())
                                .unwrap_or_else(|| "legacy".to_string()),
                            value.last_message_id,
                            self.host.estimate_text_tokens(&value.summary)
                        )
                    },
                );
                format!(
                    "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.",
                    history.len(),
                    anchor
                        .map(|seq| seq.to_string())
                        .unwrap_or_else(|| "not initialized".to_string())
                )
            }
            (Err(error), _) | (_, Err(error)) => {
                format!("Could not inspect conversation context: {error}")
            }
        }
    }

    async fn handle_model(&self, arg: &str) -> String {
        if arg.is_empty() {
            let current = self.agent.current_model().await;
            format!(
                "Current model: {}\n\nUsage: /model <model-name>\nExample: /model gemini-3-pro-preview",
                current
            )
        } else {
            self.agent.set_model(arg.to_string()).await;
            format!(
                "Model switched to: {}\nAuto-routing disabled. Use /auto to re-enable.",
                arg
            )
        }
    }

    async fn handle_models(&self) -> String {
        match self.agent.list_models().await {
            Ok(models) => {
                if models.is_empty() {
                    "No models found from provider.".to_string()
                } else {
                    let current = self.agent.current_model().await;
                    let list: Vec<String> = models
                        .iter()
                        .map(|m| {
                            if *m == current {
                                format!("• {} (active)", m)
                            } else {
                                format!("• {}", m)
                            }
                        })
                        .collect();
                    format!("Available models:\n{}", list.join("\n"))
                }
            }
            Err(e) => format!("Failed to list models: {}", e),
        }
    }

    async fn handle_auto(&self) -> String {
        self.agent.clear_model_override().await;
        "Auto-routing re-enabled. Model will be selected automatically based on query complexity."
            .to_string()
    }

    async fn handle_tasks(&self, session_id: &str) -> String {
        let running =
            crate::stop::running_work(&self.task_registry, self.agent.as_ref(), session_id).await;
        let failed = self
            .task_registry
            .list_for_session(session_id)
            .await
            .into_iter()
            .filter(|entry| matches!(entry.status, TaskStatus::Failed(_)))
            .collect::<Vec<_>>();
        let now = Utc::now();
        render_tasks(&running, &failed, now, self.host.owner_time(now).as_deref())
    }

    /// `/cancel`: everything running when it comes from one request (else
    /// the list to pick from), `/cancel all` everything, `/cancel <n>` one
    /// item. Each stop is read back before it is reported.
    async fn handle_cancel(&self, arg: &str, session_id: &str, user_role: UserRole) -> String {
        if user_role != UserRole::Owner {
            return "Only the owner can stop running work in this chat.".to_string();
        }
        let Some(request) = cancel_request(arg) else {
            return "Usage: /cancel, /cancel all or /cancel <number>. Send /tasks to see the \
                    numbers."
                .to_string();
        };
        crate::stop::stop(
            &self.task_registry,
            self.agent.as_ref(),
            session_id,
            request,
        )
        .await
    }

    async fn handle_clear(&self, session_id: &str) -> String {
        // Stop the chat's sub-agents and background commands first (while
        // the turn that waits on them still runs), then its turns, so the
        // agent loop aborts instead of burning tokens after /clear.
        let stopped_work =
            crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
                .await;
        let cancelled_tasks = self
            .task_registry
            .cancel_running_for_session(session_id)
            .await;
        // Also cancel finite orchestration goals associated with this
        // conversation. Recurring schedules and personal goals intentionally
        // survive a context clear.
        let cancelled_goals = self
            .agent
            .cancel_active_finite_work_for_session(session_id)
            .await;

        // Non-destructive: sets a context boundary so the next turn starts
        // fresh, but the event history remains for memory and audit. Use /wipe
        // to permanently delete.
        match self.agent.clear_session_context(session_id).await {
            Ok(_) => {
                let mut cancellations = Vec::new();
                if !cancelled_goals.is_empty() {
                    cancellations.push(format!(
                        "{} background goal{}",
                        cancelled_goals.len(),
                        if cancelled_goals.len() == 1 { "" } else { "s" }
                    ));
                }
                let stopped = stopped_with_turns(cancelled_tasks.len(), stopped_work);
                let suffix = clear_suffix(&cancellations, &stopped);
                format!(
                    "Context cleared. Starting fresh – your history is kept; use /wipe to \
                     delete this chat's history.{suffix}"
                )
            }
            Err(e) => format!("Failed to clear context: {}", e),
        }
    }

    /// Erase conversation `session_id` for good, as a confirmed `/wipe`
    /// does (and deleting it from a client): its running work stops, then
    /// everything of it in the active database goes. Returns what was
    /// stopped, for the reply.
    pub async fn erase_session(&self, session_id: &str) -> anyhow::Result<Vec<String>> {
        let stopped_work =
            crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
                .await;
        let cancelled = self
            .task_registry
            .cancel_running_for_session(session_id)
            .await;
        // Destructive: erases this session's active database artifacts.
        self.agent.clear_session(session_id).await?;
        Ok(stopped_with_turns(cancelled.len(), stopped_work))
    }

    async fn handle_wipe(&self, session_id: &str) -> String {
        // Irreversible, and one tap away from /clear in the command menu:
        // the first /wipe only asks.
        if self
            .task_registry
            .request_wipe(session_id, std::time::Instant::now())
            == crate::tasks::WipeRequest::Requested
        {
            return format!(
                "Nothing was erased. /wipe permanently deletes this conversation from the \
                 database: its messages, search index, summaries and episodes. Facts already \
                 saved to memory are kept. To start fresh and keep the history, use /clear \
                 instead. To erase it, send /wipe again within {} minutes.",
                crate::tasks::WIPE_CONFIRM_WINDOW.as_secs() / 60
            );
        }
        match self.erase_session(session_id).await {
            Ok(stopped) => {
                let suffix = clear_suffix(&[], &stopped);
                format!(
                    "Conversation erased from the active database (events, exact-search index, \
                     summaries, episodes, and raw memory spans). Facts already saved to memory \
                     are kept without raw-message provenance. Existing encrypted backups may \
                     retain older copies until their own lifecycle removes them.{suffix}"
                )
            }
            Err(e) => format!("Failed to wipe conversation: {}", e),
        }
    }

    async fn handle_cost(&self) -> String {
        let now = Utc::now();
        let since_24h = (now - chrono::Duration::hours(24))
            .format("%Y-%m-%d %H:%M:%S")
            .to_string();
        let since_7d = (now - chrono::Duration::days(7))
            .format("%Y-%m-%d %H:%M:%S")
            .to_string();

        let records_24h = match self.host.token_usage_since(&since_24h).await {
            Ok(r) => r,
            Err(e) => return format!("Failed to query token usage: {}", e),
        };
        let records_7d = match self.host.token_usage_since(&since_7d).await {
            Ok(r) => r,
            Err(e) => return format!("Failed to query token usage: {}", e),
        };

        let (input_24h, output_24h) = records_24h.iter().fold((0i64, 0i64), |(i, o), r| {
            (i + r.input_tokens, o + r.output_tokens)
        });
        let (input_7d, output_7d) = records_7d.iter().fold((0i64, 0i64), |(i, o), r| {
            (i + r.input_tokens, o + r.output_tokens)
        });

        // Top models (by total tokens in 7d)
        let mut model_totals: HashMap<&str, i64> = HashMap::new();
        for r in &records_7d {
            *model_totals.entry(&r.model).or_insert(0) += r.input_tokens + r.output_tokens;
        }
        let mut models_sorted: Vec<(&&str, &i64)> = model_totals.iter().collect();
        models_sorted.sort_by(|a, b| b.1.cmp(a.1));

        let mut reply = format!(
            "Token usage (last 24h):\n  Input:  {} tokens\n  Output: {} tokens\n\n\
             Token usage (last 7d):\n  Input:  {} tokens\n  Output: {} tokens",
            format_number(input_24h),
            format_number(output_24h),
            format_number(input_7d),
            format_number(output_7d),
        );

        if !models_sorted.is_empty() {
            reply.push_str("\n\nTop models (7d):");
            for (model, total) in models_sorted.iter().take(5) {
                reply.push_str(&format!("\n  {}: {} tokens", model, format_number(**total)));
            }
        }

        reply
    }
}

/// Format a number with comma separators (e.g. 12450 → "12,450").
pub fn format_number(n: i64) -> String {
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(c);
    }
    result.chars().rev().collect()
}

/// Build the /help response text from a list of command definitions.
///
/// `commands`: the command definitions to include (platform-specific).
/// `prefix`: command prefix character ("/" for Telegram/Discord, "!" for Slack).
/// `scope`: the everyday commands, or all of them (`/help all`). The text is
/// Markdown; each channel renders it in its own format.
pub fn build_help_text(commands: &[CommandDef], prefix: &str, scope: HelpScope) -> String {
    let p = prefix;
    let shown: Vec<&CommandDef> = match scope {
        HelpScope::Everyday => EVERYDAY_COMMANDS
            .iter()
            .filter_map(|name| commands.iter().find(|cmd| cmd.name == *name))
            .collect(),
        HelpScope::All => commands.iter().collect(),
    };
    let mut text = match scope {
        HelpScope::Everyday => String::from(
            "Just ask in plain words – I'll pick the right tools. For example: \
             _\"Check my disk space every 6 hours\"_ or _\"Send me the latest log file\"_.\n\n\
             **Everyday commands**",
        ),
        HelpScope::All => String::from("**All commands**"),
    };
    for cmd in shown {
        let label = match cmd.usage {
            Some(usage) => {
                // Replace the leading "/" with the platform prefix.
                if let Some(rest) = usage.strip_prefix('/') {
                    format!("{p}{rest}")
                } else {
                    usage.to_string()
                }
            }
            None => format!("{p}{}", cmd.name),
        };
        text.push_str(&format!("\n{} – {}", label, cmd.description));
    }
    if scope == HelpScope::Everyday {
        text.push_str(&format!("\n\nSend {p}help all for every command."));
    }
    text
}

#[cfg(test)]
mod help_and_status_tests {
    use super::*;

    /// `/clear` names the sub-agents and commands it stopped, the way
    /// `/cancel` does, rather than counting them.
    #[test]
    fn clear_names_what_it_stopped() {
        let suffix = clear_suffix(
            &["1 running task".to_string()],
            &[
                "Sub-agent: Counter A".to_string(),
                "Background command: a shell loop".to_string(),
            ],
        );
        assert_eq!(
            suffix,
            " (1 running task cancelled.)\n\n⏹️ Stopped:\n• Sub-agent: Counter A\n• \
             Background command: a shell loop"
        );
        assert_eq!(clear_suffix(&[], &[]), "");
    }

    fn defs() -> Vec<CommandDef> {
        shared_commands()
    }

    #[test]
    fn help_shows_the_everyday_commands_and_how_to_see_the_rest() {
        let help = build_help_text(&defs(), "/", HelpScope::Everyday);
        for name in EVERYDAY_COMMANDS {
            assert!(help.contains(&format!("\n/{name}")), "{name}: {help}");
        }
        assert!(!help.contains("/models"), "{help}");
        assert!(!help.contains('`'), "{help}");
        assert!(
            help.ends_with("Send /help all for every command."),
            "{help}"
        );
        let all = build_help_text(&defs(), "!", HelpScope::All);
        assert!(all.contains("!models – List available models"), "{all}");
        assert_eq!(HelpScope::from_args(" ALL "), HelpScope::All);
        assert_eq!(HelpScope::from_args(""), HelpScope::Everyday);
    }

    #[test]
    fn an_unknown_command_suggests_the_closest_one() {
        let commands = defs();
        assert_eq!(closest_command("cleer", &commands), Some("clear"));
        assert_eq!(closest_command("stauts", &commands), Some("status"));
        assert_eq!(closest_command("weather", &commands), None);
        assert_eq!(
            unknown_command_reply("/claer", &commands, "/"),
            "I don't know /claer. Did you mean /clear? Send /help to see the commands."
        );
        assert_eq!(
            unknown_command_reply("/weather@my_bot", &commands, "/"),
            "I don't know /weather@my_bot. Send /help to see the commands."
        );
    }

    #[test]
    fn private_can_carry_its_message() {
        assert_eq!(private_request("/private"), None);
        assert_eq!(private_request("/private off"), None);
        assert_eq!(private_request("/clear"), None);
        assert_eq!(
            private_request("/private/private"),
            Some(PrivateRequest::Next)
        );
        assert_eq!(
            private_request("/privateAnother test"),
            Some(PrivateRequest::With("Another test"))
        );
        assert_eq!(
            private_request("/private@my_bot what's my balance?"),
            Some(PrivateRequest::With("what's my balance?"))
        );
        assert_eq!(
            private_request("/private /private hi"),
            Some(PrivateRequest::With("hi"))
        );
    }

    #[test]
    fn tasks_lists_every_running_thing_with_a_number() {
        let now = Utc::now();
        let running = crate::stop::WorkList::for_tests(vec![
            (
                7,
                crate::stop::TURN_LABEL,
                now - chrono::Duration::seconds(40),
                "req-1",
            ),
            (
                8,
                "Sub-agent: Counting agent A",
                now - chrono::Duration::seconds(30),
                "req-1",
            ),
            (
                9,
                "Background command: for i in $(seq 1 300); do echo $i; sleep 2; done",
                now - chrono::Duration::seconds(30),
                "req-1",
            ),
        ]);
        let tasks = render_tasks(&running, &[], now, None);
        assert!(
            tasks.starts_with("Running in this chat:\n#7 Working on your message (40s so far)"),
            "{tasks}"
        );
        assert!(
            tasks.contains("\n#8 Sub-agent: Counting agent A (30s so far)"),
            "{tasks}"
        );
        assert!(
            tasks.contains("\n#9 Background command: for i in"),
            "{tasks}"
        );
        assert!(
            tasks.contains("Send /cancel to stop all of it, or /cancel <number> for one."),
            "{tasks}"
        );
        let quiet = render_tasks(&crate::stop::WorkList::default(), &[], now, None);
        assert!(
            quiet.starts_with("Nothing is running in this chat right now."),
            "{quiet}"
        );
    }

    /// A `/tasks` reply stays in the chat after the work it lists has moved
    /// on, so it says when it was read (live 2026-11-12: an old "#1 Working
    /// on your message" reply looked current).
    #[test]
    fn tasks_says_when_it_was_read() {
        let now = Utc::now();
        let running = crate::stop::WorkList::for_tests(vec![(
            1,
            crate::stop::TURN_LABEL,
            now - chrono::Duration::seconds(40),
            "req-1",
        )]);
        let tasks = render_tasks(&running, &[], now, Some("5:44 PM ET"));
        assert!(
            tasks.starts_with(
                "As of 5:44 PM ET:\nRunning in this chat:\n#1 Working on your message"
            ),
            "{tasks}"
        );
        let quiet = render_tasks(
            &crate::stop::WorkList::default(),
            &[],
            now,
            Some("5:44 PM ET"),
        );
        assert!(
            quiet.starts_with("As of 5:44 PM ET:\nNothing is running"),
            "{quiet}"
        );
    }

    /// `/clear` names the turn it cancelled in the same list as the helpers
    /// it stopped, with no separate count to disagree with that list.
    #[test]
    fn clear_lists_the_cancelled_turn_with_the_stopped_helpers() {
        let stopped = stopped_with_turns(
            1,
            vec!["Sub-agent: Counter A".into(), "Sub-agent: Counter B".into()],
        );
        let suffix = clear_suffix(&[], &stopped);
        assert!(!suffix.contains("cancelled"), "{suffix}");
        assert_eq!(
            suffix,
            "\n\n⏹️ Stopped:\n• Working on your message\n• Sub-agent: Counter A\n• Sub-agent: Counter B"
        );
    }

    #[test]
    fn cancel_arguments_are_bare_all_or_numbers() {
        use crate::stop::StopRequest;
        assert_eq!(cancel_request(""), Some(StopRequest::Bare));
        assert_eq!(cancel_request(" ALL "), Some(StopRequest::All));
        assert_eq!(cancel_request("3"), Some(StopRequest::Numbers(vec![3])));
        assert_eq!(
            cancel_request("#3, 4"),
            Some(StopRequest::Numbers(vec![3, 4]))
        );
        assert_eq!(cancel_request("both"), None);
    }

    #[test]
    fn status_says_mode_running_work_and_whats_next() {
        let now = Utc::now();
        let quiet = StatusView {
            now: None,
            mode: None,
            running: crate::stop::WorkList::default(),
            next_scheduled: None,
        };
        assert_eq!(
            render_status(&quiet, now),
            "Mode: full.\nRunning: nothing right now.\nNext scheduled: nothing."
        );
        let busy = StatusView {
            now: Some("2:05 PM ET".to_string()),
            mode: Some((ChatMode::ReadOnly, Some(now + chrono::Duration::hours(3)))),
            running: crate::stop::WorkList::for_tests(vec![
                (
                    7,
                    crate::stop::TURN_LABEL,
                    now - chrono::Duration::minutes(2),
                    "a",
                ),
                (
                    8,
                    "Sub-agent: Install a Drupal demo site with DDEV",
                    now - chrono::Duration::minutes(4),
                    "a",
                ),
            ]),
            next_scheduled: Some(ScheduledItem {
                what: "Check disk space".to_string(),
                when: "2:39 PM ET".to_string(),
            }),
        };
        let status = render_status(&busy, now);
        assert!(
            status.starts_with("As of 2:05 PM ET: Mode: read-only (about 3h left)."),
            "{status}"
        );
        assert!(
            status.contains("• Working on your message (2m so far, /cancel 7 to stop it)"),
            "{status}"
        );
        assert!(
            status.contains(
                "• Sub-agent: Install a Drupal demo site with DDEV (4m so far, /cancel 8 to stop it)"
            ),
            "{status}"
        );
        assert!(
            status.ends_with("Next scheduled: Check disk space – 2:39 PM ET"),
            "{status}"
        );
    }

    /// A scheduled item is named by a rule, never by a sentence cut short:
    /// its owner's name for it, else a description that fits whole, else
    /// that it has no name.
    #[test]
    fn a_scheduled_item_is_named_never_cut() {
        let long = "Every day, independently manage and publish to the synthetic blog at \
                    https://blog.example.test following the editorial plan";
        assert_eq!(scheduled_name(Some(" Daily blog "), long), "Daily blog");
        assert_eq!(scheduled_name(None, "Check disk space"), "Check disk space");
        let unnamed = scheduled_name(None, long);
        assert_eq!(unnamed, "An automation without a name (see /work)");
        for name in [unnamed, scheduled_name(Some("Daily blog"), long)] {
            assert!(!name.contains('…') && !name.contains("..."), "{name}");
        }
    }
}

#[cfg(test)]
mod format_tests {
    use super::*;

    #[test]
    fn test_format_number() {
        assert_eq!(format_number(0), "0");
        assert_eq!(format_number(999), "999");
        assert_eq!(format_number(1000), "1,000");
        assert_eq!(format_number(12450), "12,450");
        assert_eq!(format_number(1_000_000), "1,000,000");
    }
}