zeph-commands 0.22.4

Slash command registry, handler trait, and channel sink abstraction for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Session management command handlers: `/exit`, `/quit`, `/clear`, `/reset`, `/clear-queue`.

use std::future::Future;
use std::pin::Pin;

use crate::CommandHandler;
use crate::context::CommandContext;
use crate::{CommandError, CommandOutput, SlashCategory};

async fn handle_exit(ctx: &mut CommandContext<'_>) -> Result<CommandOutput, CommandError> {
    if ctx.session.supports_exit() {
        Ok(CommandOutput::Exit)
    } else {
        ctx.sink
            .send("/exit is not supported in this channel.")
            .await?;
        Ok(CommandOutput::Continue)
    }
}

/// Exit the agent loop.
///
/// `/exit` and `/quit` are treated as aliases; both map to this handler via the registry.
/// When the channel does not support exit (e.g., Telegram), the command is rejected with
/// a user-visible message.
pub struct ExitCommand;

impl CommandHandler<CommandContext<'_>> for ExitCommand {
    fn name(&self) -> &'static str {
        "/exit"
    }

    fn description(&self) -> &'static str {
        "Exit the agent (also: /quit)"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        false
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        _args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.exit.handle");
        Box::pin(async move { handle_exit(ctx).await }.instrument(span))
    }
}

/// Alias for `/exit`.
pub struct QuitCommand;

impl CommandHandler<CommandContext<'_>> for QuitCommand {
    fn name(&self) -> &'static str {
        "/quit"
    }

    fn description(&self) -> &'static str {
        "Exit the agent (alias for /exit)"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        false
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        _args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.quit.handle");
        Box::pin(async move { handle_exit(ctx).await }.instrument(span))
    }
}

/// Clear conversation history and tool caches without sending a confirmation message.
///
/// Clears the message history (keeping only the system prompt), tool caches,
/// pending images, and URL tracking.
pub struct ClearCommand;

impl CommandHandler<CommandContext<'_>> for ClearCommand {
    fn name(&self) -> &'static str {
        "/clear"
    }

    fn description(&self) -> &'static str {
        "Clear conversation history"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        true
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        _args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.clear.handle");
        Box::pin(
            async move {
                ctx.messages.clear_history();
                Ok(CommandOutput::Silent)
            }
            .instrument(span),
        )
    }
}

/// Reset conversation history (alias for `/clear`, replies with confirmation).
pub struct ResetCommand;

impl CommandHandler<CommandContext<'_>> for ResetCommand {
    fn name(&self) -> &'static str {
        "/reset"
    }

    fn description(&self) -> &'static str {
        "Reset conversation history (alias for /clear, replies with confirmation)"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        true
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        _args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.reset.handle");
        Box::pin(
            async move {
                ctx.messages.clear_history();
                Ok(CommandOutput::Message(
                    "Conversation history reset.".to_owned(),
                ))
            }
            .instrument(span),
        )
    }
}

/// Discard all messages currently queued for processing.
pub struct ClearQueueCommand;

impl CommandHandler<CommandContext<'_>> for ClearQueueCommand {
    fn name(&self) -> &'static str {
        "/clear-queue"
    }

    fn description(&self) -> &'static str {
        "Discard queued messages"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        true
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        _args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.clear_queue.handle");
        Box::pin(
            async move {
                let n = ctx.messages.drain_queue();
                if let Err(e) = ctx.sink.send_queue_count(0).await {
                    tracing::debug!(
                        "clear_queue: send_queue_count notification failed (best-effort): {e}"
                    );
                }
                Ok(CommandOutput::Message(format!(
                    "Cleared {n} queued messages."
                )))
            }
            .instrument(span),
        )
    }
}

/// Show conversation history (spec-068 §13.6).
///
/// `/history` (no argument): the last `[session.resume] expand_default_lines` messages,
/// sliced before formatting (INV-SP-6). `/history N`: the last `N` messages. `/history all`:
/// pages through the full history in `expand_default_lines`-sized chunks — never
/// materializes the full history before formatting — with an explicit "may take a moment"
/// notice before the first page. `/history next`: continues from the pagination cursor left
/// by a prior `/history all` or `/history next`.
///
/// Output is sent via [`crate::sink::ChannelSink::send_transcript`], not the `handle`
/// return value, so channels with a structured display buffer (TUI) can backfill per-entry
/// instead of flattening to one string.
pub struct HistoryCommand;

enum HistoryArgs {
    Bounded(usize),
    All,
    Next,
}

fn parse_history_args(args: &str, default_lines: usize) -> HistoryArgs {
    match args.trim() {
        "" => HistoryArgs::Bounded(default_lines),
        "all" => HistoryArgs::All,
        "next" => HistoryArgs::Next,
        n => n
            .parse::<usize>()
            .map_or(HistoryArgs::Bounded(default_lines), HistoryArgs::Bounded),
    }
}

impl CommandHandler<CommandContext<'_>> for HistoryCommand {
    fn name(&self) -> &'static str {
        "/history"
    }

    fn description(&self) -> &'static str {
        "Show conversation history (N most recent messages, or 'all' to page through)"
    }

    fn args_hint(&self) -> &'static str {
        "[N|all|next]"
    }

    fn category(&self) -> SlashCategory {
        SlashCategory::Session
    }

    fn requires_auth(&self) -> bool {
        false
    }

    fn handle<'a>(
        &'a self,
        ctx: &'a mut CommandContext<'_>,
        args: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<CommandOutput, CommandError>> + Send + 'a>> {
        use tracing::Instrument as _;
        let span = tracing::info_span!("commands.history.handle");
        Box::pin(
            async move {
                let default_lines = ctx.session.history_expand_default_lines().max(1);
                let total = ctx.messages.transcript_len();
                if total == 0 {
                    ctx.sink.send("No conversation history yet.").await?;
                    return Ok(CommandOutput::Silent);
                }

                match parse_history_args(args, default_lines) {
                    HistoryArgs::Bounded(n) => {
                        let n = n.min(total);
                        let start = total.saturating_sub(n);
                        let entries = ctx.messages.transcript_page(start, n);
                        ctx.messages.set_history_cursor(0);
                        ctx.sink.send_transcript(&entries).await?;
                    }
                    HistoryArgs::All => {
                        ctx.sink
                            .send(&format!(
                                "Showing full history ({total} messages) — this may take a moment."
                            ))
                            .await?;
                        let count = default_lines.min(total);
                        let entries = ctx.messages.transcript_page(0, count);
                        ctx.messages.set_history_cursor(count);
                        ctx.sink.send_transcript(&entries).await?;
                        if count < total {
                            let total_pages = total.div_ceil(default_lines);
                            ctx.sink
                                .send(&format!(
                                    "Page 1/{total_pages} — use /history next to continue."
                                ))
                                .await?;
                        }
                    }
                    HistoryArgs::Next => {
                        let cursor = ctx.messages.history_cursor();
                        if cursor == 0 || cursor >= total {
                            ctx.sink
                                .send(
                                    "No more history to page through. Use /history all to start over.",
                                )
                                .await?;
                            return Ok(CommandOutput::Silent);
                        }
                        let count = default_lines.min(total - cursor);
                        let entries = ctx.messages.transcript_page(cursor, count);
                        let new_cursor = cursor + count;
                        ctx.messages.set_history_cursor(new_cursor);
                        ctx.sink.send_transcript(&entries).await?;
                        if new_cursor < total {
                            // `page` is already 1-based (cursor=20, default_lines=20 -> page 2)
                            // — do not add another `+ 1` (M2: previously printed "Page 3/3" for
                            // what was actually page 2 of 3).
                            let page = cursor / default_lines + 1;
                            let total_pages = total.div_ceil(default_lines);
                            ctx.sink
                                .send(&format!(
                                    "Page {page}/{total_pages} — use /history next to continue."
                                ))
                                .await?;
                        }
                    }
                }
                Ok(CommandOutput::Silent)
            }
            .instrument(span),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CommandRegistry;
    use crate::context::CommandContext;
    use crate::handlers::test_helpers::MockDebug;
    use crate::sink::ChannelSink;
    use crate::traits::messages::MessageAccess;
    use crate::traits::session::SessionAccess;
    use std::assert_matches;
    use std::future::Future;
    use std::pin::Pin;

    // --- Mock implementations ---

    struct MockSink {
        sent: Vec<String>,
    }

    impl ChannelSink for MockSink {
        fn send<'a>(
            &'a mut self,
            msg: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<(), CommandError>> + Send + 'a>> {
            self.sent.push(msg.to_owned());
            Box::pin(async { Ok(()) })
        }

        fn flush_chunks<'a>(
            &'a mut self,
        ) -> Pin<Box<dyn Future<Output = Result<(), CommandError>> + Send + 'a>> {
            Box::pin(async { Ok(()) })
        }

        fn send_queue_count<'a>(
            &'a mut self,
            _count: usize,
        ) -> Pin<Box<dyn Future<Output = Result<(), CommandError>> + Send + 'a>> {
            Box::pin(async { Ok(()) })
        }

        fn supports_exit(&self) -> bool {
            false
        }
    }

    struct MockMessages {
        pub cleared: bool,
        pub queue: usize,
        pub transcript: Vec<crate::transcript::TranscriptEntry>,
        pub cursor: usize,
    }

    impl MessageAccess for MockMessages {
        fn clear_history(&mut self) {
            self.cleared = true;
        }

        fn queue_len(&self) -> usize {
            self.queue
        }

        fn drain_queue(&mut self) -> usize {
            let n = self.queue;
            self.queue = 0;
            n
        }

        fn notify_queue_count<'a>(
            &'a mut self,
            _count: usize,
        ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
            Box::pin(async {})
        }

        fn transcript_len(&self) -> usize {
            self.transcript.len()
        }

        fn transcript_page(
            &self,
            start: usize,
            count: usize,
        ) -> Vec<crate::transcript::TranscriptEntry> {
            self.transcript
                .iter()
                .skip(start)
                .take(count)
                .cloned()
                .collect()
        }

        fn history_cursor(&self) -> usize {
            self.cursor
        }

        fn set_history_cursor(&mut self, pos: usize) {
            self.cursor = pos;
        }
    }

    struct MockSession {
        supports_exit: bool,
        expand_default_lines: usize,
    }

    impl SessionAccess for MockSession {
        fn supports_exit(&self) -> bool {
            self.supports_exit
        }

        fn history_expand_default_lines(&self) -> usize {
            self.expand_default_lines
        }
    }

    fn make_ctx<'a>(
        sink: &'a mut MockSink,
        debug: &'a mut MockDebug,
        messages: &'a mut MockMessages,
        session: &'a MockSession,
        agent: &'a mut crate::NullAgent,
    ) -> CommandContext<'a> {
        CommandContext {
            sink,
            debug,
            messages,
            session: session as &dyn SessionAccess,
            agent,
        }
    }

    // --- Tests ---

    #[tokio::test]
    async fn exit_returns_exit_when_supported() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: true,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);
        let out = ExitCommand.handle(&mut ctx, "").await.unwrap();
        assert_matches!(out, CommandOutput::Exit);
    }

    #[tokio::test]
    async fn exit_sends_message_when_not_supported() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);
        let out = ExitCommand.handle(&mut ctx, "").await.unwrap();
        assert_matches!(out, CommandOutput::Continue);
        assert!(!sink.sent.is_empty());
    }

    #[tokio::test]
    async fn clear_clears_history() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let out = {
            let mut agent = crate::NullAgent;
            let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);
            ClearCommand.handle(&mut ctx, "").await.unwrap()
        };
        assert_matches!(out, CommandOutput::Silent);
        assert!(messages.cleared);
    }

    #[tokio::test]
    async fn reset_clears_and_confirms() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let out = {
            let mut agent = crate::NullAgent;
            let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);
            ResetCommand.handle(&mut ctx, "").await.unwrap()
        };
        let CommandOutput::Message(msg) = out else {
            panic!("expected Message")
        };
        assert!(msg.contains("reset"));
        assert!(messages.cleared);
    }

    #[tokio::test]
    async fn clear_queue_drains_and_reports() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 3,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let out = {
            let mut agent = crate::NullAgent;
            let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);
            ClearQueueCommand.handle(&mut ctx, "").await.unwrap()
        };
        let CommandOutput::Message(msg) = out else {
            panic!("expected Message")
        };
        assert!(msg.contains('3'));
        assert_eq!(messages.queue, 0);
    }

    #[test]
    fn exit_requires_auth_false() {
        assert!(!ExitCommand.requires_auth());
    }

    #[test]
    fn quit_requires_auth_false() {
        assert!(!QuitCommand.requires_auth());
    }

    #[test]
    fn registry_finds_all_session_commands() {
        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ExitCommand);
        reg.register(QuitCommand);
        reg.register(ClearCommand);
        reg.register(ResetCommand);
        reg.register(ClearQueueCommand);

        assert!(reg.find_handler("/exit").is_some());
        assert!(reg.find_handler("/quit").is_some());
        assert!(reg.find_handler("/clear").is_some());
        assert!(reg.find_handler("/reset").is_some());
        assert!(reg.find_handler("/clear-queue").is_some());
    }

    #[tokio::test]
    async fn clear_dispatch_allowed_when_trusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ClearCommand);

        let result = reg.dispatch(&mut ctx, "/clear", true).await;
        assert!(result.unwrap().is_ok());
    }

    #[tokio::test]
    async fn clear_dispatch_rejected_when_untrusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ClearCommand);

        let result = reg.dispatch(&mut ctx, "/clear", false).await;
        let err = result.unwrap().unwrap_err();
        assert!(err.0.contains("trusted"));
    }

    #[tokio::test]
    async fn reset_dispatch_allowed_when_trusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ResetCommand);

        let result = reg.dispatch(&mut ctx, "/reset", true).await;
        assert!(result.unwrap().is_ok());
    }

    #[tokio::test]
    async fn reset_dispatch_rejected_when_untrusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ResetCommand);

        let result = reg.dispatch(&mut ctx, "/reset", false).await;
        let err = result.unwrap().unwrap_err();
        assert!(err.0.contains("trusted"));
    }

    #[tokio::test]
    async fn clear_queue_dispatch_allowed_when_trusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ClearQueueCommand);

        let result = reg.dispatch(&mut ctx, "/clear-queue", true).await;
        assert!(result.unwrap().is_ok());
    }

    #[tokio::test]
    async fn clear_queue_dispatch_rejected_when_untrusted() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let mut reg: CommandRegistry<CommandContext<'_>> = CommandRegistry::new();
        reg.register(ClearQueueCommand);

        let result = reg.dispatch(&mut ctx, "/clear-queue", false).await;
        let err = result.unwrap().unwrap_err();
        assert!(err.0.contains("trusted"));
    }

    // --- /history ---

    fn make_transcript(n: usize) -> Vec<crate::transcript::TranscriptEntry> {
        (0..n)
            .map(|i| crate::transcript::TranscriptEntry {
                role: crate::transcript::TranscriptRole::User,
                content: format!("message {i}"),
                tool_name: None,
            })
            .collect()
    }

    #[tokio::test]
    async fn history_no_history_yet() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: Vec::new(),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        let out = HistoryCommand.handle(&mut ctx, "").await.unwrap();
        assert_matches!(out, CommandOutput::Silent);
        assert!(sink.sent[0].contains("No conversation history"));
    }

    #[tokio::test]
    async fn history_default_bounds_to_expand_default_lines() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: make_transcript(500),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        HistoryCommand.handle(&mut ctx, "").await.unwrap();
        // Only the last 20 of 500 messages must ever reach the sink — never the full set
        // materialized then trimmed (INV-SP-6).
        assert_eq!(sink.sent.len(), 1);
        assert!(sink.sent[0].contains("message 480"));
        assert!(sink.sent[0].contains("message 499"));
        assert!(!sink.sent[0].contains("message 479"));
    }

    #[tokio::test]
    async fn history_numeric_argument_bounds_explicitly() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: make_transcript(10),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        HistoryCommand.handle(&mut ctx, "3").await.unwrap();
        assert_eq!(sink.sent.len(), 1);
        assert!(sink.sent[0].contains("message 7"));
        assert!(sink.sent[0].contains("message 9"));
        assert!(!sink.sent[0].contains("message 6"));
    }

    #[tokio::test]
    async fn history_all_shows_notice_then_paginates() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: make_transcript(50),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        HistoryCommand.handle(&mut ctx, "all").await.unwrap();
        assert!(sink.sent[0].contains("may take a moment"));
        assert!(sink.sent[1].contains("message 0"));
        assert!(!sink.sent[1].contains("message 20"));
        assert!(sink.sent[2].contains("Page 1/3"));
        assert_eq!(messages.history_cursor(), 20);
    }

    #[tokio::test]
    async fn history_next_continues_from_cursor() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: make_transcript(50),
            cursor: 20,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        HistoryCommand.handle(&mut ctx, "next").await.unwrap();
        assert!(sink.sent[0].contains("message 20"));
        assert!(sink.sent[0].contains("message 39"));
        assert!(!sink.sent[0].contains("message 40"));
        assert_eq!(messages.history_cursor(), 40);
        // M2 regression: cursor 20 -> 40 of 50 total is page 2 of 3, not "Page 3/3" (the
        // pre-fix off-by-one, which also contradicted its own "use /history next to continue"
        // text by claiming the last page still had more to show).
        assert_eq!(
            sink.sent[1], "Page 2/3 — use /history next to continue.",
            "page label must be 1-based without a stray extra +1"
        );
    }

    #[tokio::test]
    async fn history_next_without_prior_all_reports_nothing_to_page() {
        let mut sink = MockSink { sent: vec![] };
        let mut debug = MockDebug;
        let mut messages = MockMessages {
            cleared: false,
            queue: 0,
            transcript: make_transcript(50),
            cursor: 0,
        };
        let session = MockSession {
            supports_exit: false,
            expand_default_lines: 20,
        };
        let mut agent = crate::NullAgent;
        let mut ctx = make_ctx(&mut sink, &mut debug, &mut messages, &session, &mut agent);

        HistoryCommand.handle(&mut ctx, "next").await.unwrap();
        assert!(sink.sent[0].contains("No more history"));
    }

    #[test]
    fn history_requires_auth_false() {
        assert!(!HistoryCommand.requires_auth());
    }
}