eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! The slash commands, in one table.
//!
//! The plain REPL, the full-screen interface, `/help`, and Tab completion all read
//! [`COMMANDS`]. Before this the set lived in three places — the REPL's `match`, the
//! interface's `match`, and two hand-written `/help` strings — and they had already drifted:
//! the REPL's help named four commands and the interface's named seven.
//!
//! What the table does *not* hold is what a command does. Each front end keeps a plain
//! `match` on the canonical name, because the handlers need different things (the REPL prints,
//! the interface posts notes and asks its loop to open pickers, the server answers with events),
//! and a table of closures would need a shared context type that fits none of them. The drift
//! test in each front end closes the gap instead: every command the table says it serves must be
//! handled there.
//!
//! It lives here, in core, because there are three front ends now. The dashboard parses the same
//! lines (`#254`), and a table the server cannot read is a table the browser has to copy.

/// Which interface has a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Front {
    /// The plain line REPL (`--plain`, or any stdout that is not a terminal).
    Repl,
    /// The full-screen interface.
    Tui,
    /// The dashboard in a browser (`eclipse-web`).
    Web,
}

impl Front {
    /// The name this front goes by in a sentence — `/help` never says "Front::Tui".
    pub fn place(self) -> &'static str {
        match self {
            Front::Repl => "the plain REPL",
            Front::Tui => "the full-screen interface",
            Front::Web => "the dashboard",
        }
    }

    /// How to get to this front from another one: the half of the sentence a person can act on.
    pub fn enter(self) -> &'static str {
        match self {
            Front::Repl => "run eclipse --plain",
            Front::Tui => "run eclipse without --plain",
            Front::Web => "run eclipse-web",
        }
    }

    /// Whether a person is typing and watching. A `!` line means something only where this is
    /// true — see the `bang` module for what that promise costs.
    pub fn keyboard(self) -> bool {
        matches!(self, Front::Tui | Front::Repl)
    }
}

// The table reads better with the fronts as bare words: `&[Tui, Repl, Web]` is a sentence,
// `&[Front::Repl, Front::Tui, Front::Web]` is a type signature. Named, not globbed, so a new
// vocabulary word has to be added here on purpose.
use Front::{Repl, Tui, Web};

/// Whether a command takes an argument, and how `/help` spells it.
///
/// The two are not the same question. `/model 3` still switches a model, but the way in is the
/// picker, and `[number|name]` in the table taught the syntax first — a reader memorised a shape
/// they never need. So a command can take an argument without the table advertising one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Args {
    /// Takes none, and `parse` refuses a trailing word: `/new something` must not start a session
    /// called "something".
    None,
    /// Takes one, and the table spells the shape after the name: `/set <key> <value>`.
    Shown(&'static str),
    /// Takes one, but the table does not spell it: the interactive way in is the one to learn.
    Unshown,
}

impl Args {
    /// Whether a trailing word is accepted at all. `Shown` and `Unshown` both say yes; they differ
    /// only in whether `/help` teaches the shape.
    pub fn takes(self) -> bool {
        !matches!(self, Args::None)
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Command {
    /// The canonical word, with its slash: `/new`.
    pub name: &'static str,
    /// Other words that run the same command; `/resume` is also `/sessions`.
    pub aliases: &'static [&'static str],
    /// Whether an argument is accepted, and whether the table spells it. See [`Args`].
    pub args: Args,
    /// One line, no trailing full stop.
    pub help: &'static str,
    /// Every front end that has it, widest first. A list rather than a "both" shorthand: with three
    /// fronts the shorthand would mean "not the web", which is a reading nobody would guess and a
    /// bug waiting for the next front end. The order is only ever read by
    /// [`Command::unavailable_in`]'s sentence — `/help` and completion walk [`COMMANDS`].
    pub fronts: &'static [Front],
}

/// Every slash command, in the order `/help` and the menu list them.
///
/// `/clear`, `/resume` and `/model` are full-screen-only today: the plain REPL has no screen
/// to clear and no picker to open. Giving it plain-text versions is a separate change.
pub const COMMANDS: &[Command] = &[
    Command {
        name: "/new",
        aliases: &[],
        args: Args::None,
        help: "start a new session",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/resume",
        aliases: &["/sessions"],
        args: Args::None,
        help: "open a stored session (↑↓, enter)",
        fronts: &[Tui],
    },
    Command {
        name: "/retry",
        aliases: &[],
        args: Args::None,
        help: "run the last question again, without asking it twice",
        fronts: &[Tui, Repl],
    },
    Command {
        name: "/bg",
        aliases: &[],
        args: Args::Shown("<prompt>"),
        help: "start it as a task that keeps running after this prompt returns",
        fronts: &[Tui, Repl],
    },
    Command {
        name: "/tasks",
        aliases: &[],
        args: Args::Unshown,
        help: "the background runs: what each is doing, and how it ended",
        fronts: &[Tui, Repl],
    },
    Command {
        name: "/model",
        aliases: &[],
        args: Args::Unshown,
        help: "pick a model (↑↓, enter)",
        fronts: &[Tui, Web],
    },
    Command {
        name: "/id",
        aliases: &[],
        args: Args::None,
        help: "show the current session id",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/profile",
        aliases: &[],
        args: Args::Unshown,
        help: "which profile, from which file, under which home (`/profile list` for all)",
        fronts: &[Tui, Repl],
    },
    Command {
        name: "/gateway",
        aliases: &["/platforms"],
        args: Args::None,
        help: "what the gateway is doing: its state, its age, its port and its jobs",
        fronts: &[Tui, Repl],
    },
    Command {
        name: "/goal",
        aliases: &[],
        args: Args::Shown("<text>"),
        help: "a standing goal, worked on turn by turn until the judge says it is done",
        // All three: a goal is a row in the session store, so whichever process is running the
        // session can carry it — and the dashboard's gateway carries on with the tab closed.
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/loop",
        aliases: &[],
        args: Args::Shown("<interval> <prompt>"),
        help: "send this prompt back into this session every interval (`status|pause|resume|stop`)",
        // All three, and `Web` because the dashboard's gateway owns the timer there: a loop is the
        // one command whose meaning depends on which process is holding it, and every front has a
        // process. The line `/loop` answers with says which one.
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/cron",
        aliases: &[],
        args: Args::Unshown,
        help: "the scheduled jobs: the table, `run <name>` and `logs <name> [n]`",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/reasoning",
        aliases: &[],
        args: Args::Unshown,
        help: "how much it thinks, and how much of it is drawn (`/reasoning high`)",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/settings",
        aliases: &[],
        args: Args::None,
        help: "the keys this build reads, and what each is set to",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/set",
        aliases: &[],
        args: Args::Shown("<key> <value>"),
        help: "write one setting; the next run uses it",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/yolo",
        aliases: &[],
        args: Args::Unshown,
        help: "stop asking before every tool call, until `/yolo off` (this session only)",
        // The dashboard gets it too (#285), and only because it can now show it: a `yolo` word in
        // the stats row, in the alert colour, painted from the server's state. The switch lived on
        // the terminal's bar and nowhere else while the browser had no strip to put it on, and a
        // verb that turns the cards off and says nothing is worse than one that says where it
        // lives. `WebApprover` reads it per call and counts what it ran unasked.
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/status",
        aliases: &[],
        args: Args::None,
        help: "tokens, cache, timings for this process",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/compress",
        aliases: &["/compact"],
        args: Args::None,
        help: "replace this session's older turns with the compiled handoff now",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/archive",
        aliases: &[],
        args: Args::Unshown,
        help: "file this session away — out of the list, still in the search (`list`, `off`)",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/clear",
        aliases: &[],
        args: Args::None,
        help: "clear the transcript",
        fronts: &[Tui],
    },
    Command {
        name: "/help",
        aliases: &[],
        args: Args::None,
        help: "list the commands",
        fronts: &[Tui, Repl, Web],
    },
    Command {
        name: "/exit",
        aliases: &["/quit"],
        args: Args::None,
        help: "quit",
        fronts: &[Tui, Repl],
    },
];

impl Command {
    /// `/set <key> <value>`: the name and its argument, as `/help` and the menu show it. A command
    /// whose arguments are `Unshown` is just its name — the table does not teach that syntax.
    pub fn label(&self) -> String {
        match self.args {
            Args::Shown(args) => format!("{} {args}", self.name),
            Args::None | Args::Unshown => self.name.to_string(),
        }
    }

    /// The word to put in the line for someone who has typed `prefix`: the name, unless only
    /// an alias starts with it — `/qu` completes to `/quit`, not to a command they did not type.
    pub fn spelling(&self, prefix: &str) -> &'static str {
        if self.name.starts_with(prefix) {
            return self.name;
        }
        self.aliases
            .iter()
            .copied()
            .find(|a| a.starts_with(prefix))
            .unwrap_or(self.name)
    }

    /// What completing `prefix` to this command leaves in the line. A command that takes an
    /// argument gets a space after it, so the next key is the argument.
    pub fn fill(&self, prefix: &str) -> String {
        let word = self.spelling(prefix);
        if self.args.takes() {
            format!("{word} ")
        } else {
            word.to_string()
        }
    }

    /// Whether `viewer` has this command.
    pub fn serves(&self, viewer: Front) -> bool {
        self.fronts.contains(&viewer)
    }

    /// Why this command does nothing in `here`, for the front end that was asked for it.
    ///
    /// Names every front that *does* have it, because a command can live in two of the three and
    /// naming one of them would send a person looking in the wrong place. The "how" half is the
    /// nearest way in: what to type after they have read it.
    pub fn unavailable_in(&self, here: Front) -> String {
        let elsewhere: Vec<Front> = self.fronts.iter().copied().filter(|f| *f != here).collect();
        let places: Vec<&str> = elsewhere.iter().map(|f| f.place()).collect();
        let how = elsewhere
            .iter()
            .find(|f| f.keyboard())
            .or_else(|| elsewhere.first())
            .map_or("", |f| f.enter());
        let list = match places.split_last() {
            Some((last, [])) => (*last).to_string(),
            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
            None => "no interface".to_string(),
        };
        if how.is_empty() {
            format!("{} is only in {list}", self.name)
        } else {
            format!("{} is only in {list} ({how})", self.name)
        }
    }
}

/// The command a word names, by canonical name or alias, exactly.
pub fn lookup(word: &str) -> Option<&'static Command> {
    COMMANDS
        .iter()
        .find(|c| c.name == word || c.aliases.contains(&word))
}

/// The commands whose name or an alias starts with `prefix`, in table order, that `front` has.
pub fn matching(prefix: &str, front: Front) -> Vec<&'static Command> {
    COMMANDS
        .iter()
        .filter(|c| c.serves(front))
        .filter(|c| c.name.starts_with(prefix) || c.aliases.iter().any(|a| a.starts_with(prefix)))
        .collect()
}

#[derive(Debug, PartialEq, Eq)]
pub enum Completion {
    Unique(&'static Command),
    Several(Vec<&'static Command>),
    None,
}

/// Whether `line` is a command word being typed: a leading `/` and no whitespace yet.
///
/// `complete` answers `None` for three different situations — prose, an argument, and a command
/// word with no match — and the menu has to tell them apart: the first two close it for good, the
/// third stays on screen saying so (#253).
pub fn is_command_word(line: &str) -> bool {
    line.starts_with('/') && !line.contains(char::is_whitespace)
}

/// What Tab does to `line`. Only while the command word is being typed: the line starts with
/// `/` and has no whitespace yet. Anything else — prose, or an argument — is `None`, so Tab
/// stays whatever the editor already made it.
pub fn complete(line: &str, front: Front) -> Completion {
    if !line.starts_with('/') || line.contains(char::is_whitespace) {
        return Completion::None;
    }
    let mut found = matching(line, front);
    match found.len() {
        0 => Completion::None,
        1 => Completion::Unique(found.remove(0)),
        _ => Completion::Several(found),
    }
}

/// A line that starts with `/`, resolved against what `front` has.
#[derive(Debug, PartialEq, Eq)]
pub enum Parsed<'a> {
    /// A command this interface has, with the text after the word (trimmed, maybe empty).
    Run(&'static Command, &'a str),
    /// A real command that only the other interface has.
    Elsewhere(&'static Command),
    /// No such command, or an argument given to one that takes none. Carries the line.
    Unknown(&'a str),
}

pub fn parse(line: &str, front: Front) -> Parsed<'_> {
    let line = line.trim();
    let (word, rest) = match line.split_once(char::is_whitespace) {
        Some((word, rest)) => (word, rest.trim()),
        None => (line, ""),
    };
    match lookup(word) {
        None => Parsed::Unknown(line),
        Some(c) if !c.serves(front) => Parsed::Elsewhere(c),
        Some(c) if !rest.is_empty() && !c.args.takes() => Parsed::Unknown(line),
        Some(c) => Parsed::Run(c, rest),
    }
}

/// The `/help` body for `front`: one line per command, in table order.
pub fn help(front: Front) -> String {
    let shown: Vec<&Command> = COMMANDS.iter().filter(|c| c.serves(front)).collect();
    let width = shown
        .iter()
        .map(|c| c.label().chars().count())
        .max()
        .unwrap_or(0)
        .max("!command".len());
    let mut lines: Vec<String> = shown
        .iter()
        .map(|c| {
            let also = if c.aliases.is_empty() {
                String::new()
            } else {
                format!(" (also {})", c.aliases.join(", "))
            };
            format!("{:<width$}  {}{also}", c.label(), c.help)
        })
        .collect();
    // Not a slash command — it has no name to complete and no menu entry — so it is named here,
    // where someone reads what the composer will accept. A leading bang changes what Enter does,
    // and something that changes what Enter does is not discoverable enough on its own.
    //
    // Only where `!` means something: the dashboard has no bang (`#283`), so naming a leading bang
    // there would teach a syntax that is prose.
    if front.keyboard() {
        lines.push(format!(
            "{:<width$}  run a shell command here: no turn, no tokens, nothing added to the session",
            "!command"
        ));
    }
    lines.join("\n")
}

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

    fn names(found: &[&Command]) -> Vec<&'static str> {
        found.iter().map(|c| c.name).collect()
    }

    /// An argument a command accepts but the table does not advertise still parses.
    ///
    /// `/model 3` is kept because a name is not always easy to type; what changed is the *hint*,
    /// so `/help` no longer teaches the positional form as the way to switch a model.
    #[test]
    fn an_unshown_argument_still_parses_but_is_not_in_the_table() {
        let help = help(Front::Tui);
        let model_row = help
            .lines()
            .find(|l| l.starts_with("/model"))
            .unwrap_or_default();
        assert!(
            model_row.contains("pick a model (↑↓, enter)"),
            "the row says what happens, in /resume's shape: {model_row:?}"
        );
        assert!(
            !help.contains("[number|name]"),
            "and no longer teaches the syntax the picker replaced:\n{help}"
        );
        assert!(
            help.contains("/set <key> <value>"),
            "a command whose arguments are the way in still spells them:\n{help}"
        );

        // Behaviour is untouched: a number or a name still resolves, and a command that takes no
        // argument still refuses one.
        match parse("/model 3", Front::Tui) {
            Parsed::Run(c, rest) => {
                assert_eq!(c.name, "/model");
                assert_eq!(rest, "3");
            }
            other => panic!("/model 3 must still run: {other:?}"),
        }
        assert!(matches!(
            parse("/new something", Front::Tui),
            Parsed::Unknown(_)
        ));
        assert!(matches!(parse("/model", Front::Tui), Parsed::Run(..)));
        // Completing it leaves a space, because the picker is not the only way in.
        let model = lookup("/model").expect("in the table");
        assert_eq!(model.fill("/mo"), "/model ");
        assert_eq!(model.label(), "/model", "and the label is just its name");
    }

    /// The three `None`s are not the same `None` (#253).
    #[test]
    fn a_command_word_is_told_apart_from_prose_and_from_an_argument() {
        assert!(is_command_word("/"));
        assert!(is_command_word("/cr"));
        assert!(
            is_command_word("/zzz"),
            "a word with no match is still a word"
        );
        assert!(!is_command_word(""));
        assert!(!is_command_word("hello"));
        assert!(!is_command_word("/cron brief"), "an argument is not a word");
        assert!(!is_command_word("/cron "), "a trailing space ends the word");
        // The menu's list for a word with no match is empty rather than `None`.
        assert!(matching("/zzz", Front::Tui).is_empty());
        let served = COMMANDS.iter().filter(|c| c.serves(Front::Tui)).count();
        assert_eq!(matching("/", Front::Tui).len(), served);
    }

    #[test]
    fn every_word_in_the_table_is_unique() {
        let mut words: Vec<&str> = COMMANDS
            .iter()
            .flat_map(|c| std::iter::once(c.name).chain(c.aliases.iter().copied()))
            .collect();
        let all = words.len();
        words.sort_unstable();
        words.dedup();
        assert_eq!(words.len(), all, "a name or alias is listed twice");
        assert!(words.iter().all(|w| w.starts_with('/')));
    }

    #[test]
    fn lookup_finds_a_name_or_an_alias_exactly() {
        assert_eq!(lookup("/resume").map(|c| c.name), Some("/resume"));
        assert_eq!(lookup("/sessions").map(|c| c.name), Some("/resume"));
        assert_eq!(lookup("/quit").map(|c| c.name), Some("/exit"));
        assert!(lookup("/re").is_none(), "a prefix is not a command");
        assert!(lookup("/NEW").is_none());
        assert!(lookup("new").is_none());
    }

    #[test]
    fn matching_lists_names_and_aliases_in_table_order() {
        assert_eq!(
            names(&matching("/s", Front::Tui)),
            ["/resume", "/settings", "/set", "/status"]
        );
        assert_eq!(names(&matching("/ses", Front::Tui)), ["/resume"]);
        assert_eq!(names(&matching("/qu", Front::Tui)), ["/exit"]);
        assert_eq!(
            names(&matching("/", Front::Tui)),
            [
                "/new",
                "/resume",
                "/retry",
                "/bg",
                "/tasks",
                "/model",
                "/id",
                "/profile",
                "/gateway",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/clear",
                "/help",
                "/exit"
            ]
        );
        assert!(matching("/zzz", Front::Tui).is_empty());
    }

    #[test]
    fn matching_only_offers_what_the_front_end_has() {
        assert_eq!(
            names(&matching("/s", Front::Repl)),
            ["/settings", "/set", "/status"]
        );
        assert_eq!(
            names(&matching("/", Front::Repl)),
            [
                "/new",
                "/retry",
                "/bg",
                "/tasks",
                "/id",
                "/profile",
                "/gateway",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/help",
                "/exit"
            ]
        );
        assert!(matching("/cl", Front::Repl).is_empty());
        assert_eq!(names(&matching("/cl", Front::Tui)), ["/clear"]);
    }

    #[test]
    fn complete_is_unique_several_or_none_by_how_many_match() {
        assert_eq!(
            complete("/ne", Front::Repl),
            Completion::Unique(&COMMANDS[0])
        );
        match complete("/s", Front::Tui) {
            Completion::Several(found) => {
                assert_eq!(names(&found), ["/resume", "/settings", "/set", "/status"])
            }
            other => panic!("expected several, got {other:?}"),
        }
        assert_eq!(complete("/zzz", Front::Tui), Completion::None);
        assert!(matches!(complete("/", Front::Tui), Completion::Several(_)));
    }

    #[test]
    fn complete_only_answers_while_the_command_word_is_being_typed() {
        for line in [
            "",
            "hello",
            "hello /ne",
            " /ne",
            "/new ",
            "/model gem",
            "/ne w",
        ] {
            assert_eq!(complete(line, Front::Tui), Completion::None, "{line:?}");
        }
    }

    #[test]
    fn an_alias_completes_to_the_alias_and_an_argument_command_gets_a_space() {
        let resume = lookup("/resume").unwrap();
        assert_eq!(resume.fill("/ses"), "/sessions");
        assert_eq!(resume.fill("/re"), "/resume");
        assert_eq!(resume.fill("/"), "/resume");
        assert_eq!(lookup("/model").unwrap().fill("/mo"), "/model ");
        assert_eq!(lookup("/exit").unwrap().fill("/qu"), "/quit");
        assert_eq!(lookup("/new").unwrap().fill("/ne"), "/new");
    }

    #[test]
    fn help_has_one_aligned_line_per_command_the_front_end_has() {
        let tui = help(Front::Tui);
        // One line per command, plus `!command`, which is not a command but does change what Enter
        // does and so has to be named where the commands are named.
        assert_eq!(tui.lines().count(), COMMANDS.len() + 1);
        assert!(tui.contains("!command"), "{tui}");
        assert!(
            tui.lines().last().unwrap().starts_with("!command"),
            "named last, where it is not mistaken for something completable: {tui}"
        );
        assert!(tui.contains("/resume"), "{tui}");
        assert!(tui.contains("(also /sessions)"), "{tui}");
        assert!(tui.contains("(also /quit)"), "{tui}");
        // The help column starts at the same place on every line.
        let col = |l: &str, needle: &str| l.find(needle);
        assert_eq!(
            col(tui.lines().nth(1).unwrap_or(""), "open a stored"),
            col(tui.lines().nth(5).unwrap_or(""), "pick a model")
        );
        assert!(tui.lines().all(|l| l == l.trim_end()));

        let repl = help(Front::Repl);
        assert_eq!(
            repl.lines()
                .map(|l| l.split_whitespace().next().unwrap_or(""))
                .collect::<Vec<_>>(),
            [
                "/new",
                "/retry",
                "/bg",
                "/tasks",
                "/id",
                "/profile",
                "/gateway",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/help",
                "/exit",
                // Not a command — the one accepted line here that does not start with a slash —
                // but the REPL takes it, so it belongs where the accepted lines are listed.
                "!command"
            ]
        );
        for tui_only in ["/clear", "/resume", "/model"] {
            assert!(!repl.contains(tui_only), "{repl}");
        }
    }

    #[test]
    fn parse_resolves_aliases_and_separates_the_other_front_ends_commands() {
        assert_eq!(
            parse("/sessions", Front::Tui),
            Parsed::Run(lookup("/resume").unwrap(), "")
        );
        assert_eq!(
            parse("  /model  gemma ", Front::Tui),
            Parsed::Run(lookup("/model").unwrap(), "gemma")
        );
        assert_eq!(
            parse("/clear", Front::Repl),
            Parsed::Elsewhere(lookup("/clear").unwrap())
        );
        assert_eq!(parse("/nope", Front::Tui), Parsed::Unknown("/nope"));
        assert_eq!(parse("/new now", Front::Tui), Parsed::Unknown("/new now"));
        assert_eq!(parse("/", Front::Tui), Parsed::Unknown("/"));
    }

    /// Every row has to be reachable from somewhere, or it is a line in `/help` nobody can type.
    #[test]
    fn every_command_is_served_somewhere_and_listed_once() {
        for c in COMMANDS {
            assert!(
                !c.fronts.is_empty(),
                "{} is in the table with no front end to type it in",
                c.name
            );
            let mut seen = c.fronts.to_vec();
            seen.sort_by_key(|f| format!("{f:?}"));
            let before = seen.len();
            seen.dedup();
            assert_eq!(before, seen.len(), "{} names a front twice", c.name);
        }
    }

    /// `#254`: the dashboard reads this table too, and it may only ever be given what a terminal
    /// already has. Strict, not equal — a verb that exists in the browser and nowhere else would
    /// mean the table had grown a fourth opinion about what a command is.
    #[test]
    fn the_dashboards_verbs_are_a_strict_subset_of_the_terminals() {
        let web: Vec<&str> = COMMANDS
            .iter()
            .filter(|c| c.serves(Front::Web))
            .map(|c| c.name)
            .collect();
        let terminal: Vec<&str> = COMMANDS
            .iter()
            .filter(|c| c.serves(Front::Repl) || c.serves(Front::Tui))
            .map(|c| c.name)
            .collect();
        assert!(
            web.iter().all(|n| terminal.contains(n)),
            "a command only the dashboard has: {web:?}"
        );
        assert!(
            web.len() < terminal.len(),
            "the web set is not a subset anyone has to think about: {web:?}"
        );
        // Named, so a verb cannot gain or lose the dashboard by accident: this is the list the
        // composer gives words to. Two deliberate absences — `/resume`, because opening a stored
        // session in the browser is the sidebar rather than a line to type, and `/yolo`, because
        // approvals off has to be *visible* and this surface has nowhere to show it (#285).
        assert_eq!(
            web,
            [
                "/new",
                "/model",
                "/id",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/help"
            ]
        );
        assert!(
            !lookup("/resume").unwrap().serves(Front::Web),
            "opening a stored session is the sidebar, not a line to type"
        );
        // `#285`: the dashboard has the switch now, because it has a word to show it with. The
        // assertion that used to hold the absence is gone on purpose — it was there so a verb
        // could not be added to the browser by accident before the page could say it was on.
        assert!(lookup("/yolo").unwrap().serves(Front::Web));
    }

    #[test]
    fn an_unavailable_command_says_where_it_is() {
        let said = lookup("/clear").unwrap().unavailable_in(Front::Repl);
        assert!(
            said.contains("/clear") && said.contains("full-screen"),
            "{said}"
        );
        // Two fronts have `/bg`, so both are named: a sentence that picked one would send the
        // reader to the interface they may not be able to run.
        let bg = lookup("/bg").unwrap().unavailable_in(Front::Web);
        assert!(
            bg.contains("only in the full-screen interface and the plain REPL"),
            "{bg}"
        );
        assert!(bg.contains("run eclipse without --plain"), "{bg}");
        // And the other way round: a terminal-only verb asked for from the dashboard says so in
        // the dashboard's own words.
        let resume = lookup("/resume").unwrap().unavailable_in(Front::Web);
        assert!(
            resume.contains("only in the full-screen interface"),
            "{resume}"
        );
        assert!(resume.contains("run eclipse without --plain"), "{resume}");
    }
}