Skip to main content

eclipse_core/
commands.rs

1//! The slash commands, in one table.
2//!
3//! The plain REPL, the full-screen interface, `/help`, and Tab completion all read
4//! [`COMMANDS`]. Before this the set lived in three places — the REPL's `match`, the
5//! interface's `match`, and two hand-written `/help` strings — and they had already drifted:
6//! the REPL's help named four commands and the interface's named seven.
7//!
8//! What the table does *not* hold is what a command does. Each front end keeps a plain
9//! `match` on the canonical name, because the handlers need different things (the REPL prints,
10//! the interface posts notes and asks its loop to open pickers, the server answers with events),
11//! and a table of closures would need a shared context type that fits none of them. The drift
12//! test in each front end closes the gap instead: every command the table says it serves must be
13//! handled there.
14//!
15//! It lives here, in core, because there are three front ends now. The dashboard parses the same
16//! lines (`#254`), and a table the server cannot read is a table the browser has to copy.
17
18/// Which interface has a command.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Front {
21    /// The plain line REPL (`--plain`, or any stdout that is not a terminal).
22    Repl,
23    /// The full-screen interface.
24    Tui,
25    /// The dashboard in a browser (`eclipse-web`).
26    Web,
27}
28
29impl Front {
30    /// The name this front goes by in a sentence — `/help` never says "Front::Tui".
31    pub fn place(self) -> &'static str {
32        match self {
33            Front::Repl => "the plain REPL",
34            Front::Tui => "the full-screen interface",
35            Front::Web => "the dashboard",
36        }
37    }
38
39    /// How to get to this front from another one: the half of the sentence a person can act on.
40    pub fn enter(self) -> &'static str {
41        match self {
42            Front::Repl => "run eclipse --plain",
43            Front::Tui => "run eclipse without --plain",
44            Front::Web => "run eclipse-web",
45        }
46    }
47
48    /// Whether a person is typing and watching. A `!` line means something only where this is
49    /// true — see the `bang` module for what that promise costs.
50    pub fn keyboard(self) -> bool {
51        matches!(self, Front::Tui | Front::Repl)
52    }
53}
54
55// The table reads better with the fronts as bare words: `&[Tui, Repl, Web]` is a sentence,
56// `&[Front::Repl, Front::Tui, Front::Web]` is a type signature. Named, not globbed, so a new
57// vocabulary word has to be added here on purpose.
58use Front::{Repl, Tui, Web};
59
60/// Whether a command takes an argument, and how `/help` spells it.
61///
62/// The two are not the same question. `/model 3` still switches a model, but the way in is the
63/// picker, and `[number|name]` in the table taught the syntax first — a reader memorised a shape
64/// they never need. So a command can take an argument without the table advertising one.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Args {
67    /// Takes none, and `parse` refuses a trailing word: `/new something` must not start a session
68    /// called "something".
69    None,
70    /// Takes one, and the table spells the shape after the name: `/set <key> <value>`.
71    Shown(&'static str),
72    /// Takes one, but the table does not spell it: the interactive way in is the one to learn.
73    Unshown,
74}
75
76impl Args {
77    /// Whether a trailing word is accepted at all. `Shown` and `Unshown` both say yes; they differ
78    /// only in whether `/help` teaches the shape.
79    pub fn takes(self) -> bool {
80        !matches!(self, Args::None)
81    }
82}
83
84#[derive(Debug, PartialEq, Eq)]
85pub struct Command {
86    /// The canonical word, with its slash: `/new`.
87    pub name: &'static str,
88    /// Other words that run the same command; `/resume` is also `/sessions`.
89    pub aliases: &'static [&'static str],
90    /// Whether an argument is accepted, and whether the table spells it. See [`Args`].
91    pub args: Args,
92    /// One line, no trailing full stop.
93    pub help: &'static str,
94    /// Every front end that has it, widest first. A list rather than a "both" shorthand: with three
95    /// fronts the shorthand would mean "not the web", which is a reading nobody would guess and a
96    /// bug waiting for the next front end. The order is only ever read by
97    /// [`Command::unavailable_in`]'s sentence — `/help` and completion walk [`COMMANDS`].
98    pub fronts: &'static [Front],
99}
100
101/// Every slash command, in the order `/help` and the menu list them.
102///
103/// `/clear`, `/resume` and `/model` are full-screen-only today: the plain REPL has no screen
104/// to clear and no picker to open. Giving it plain-text versions is a separate change.
105pub const COMMANDS: &[Command] = &[
106    Command {
107        name: "/new",
108        aliases: &[],
109        args: Args::None,
110        help: "start a new session",
111        fronts: &[Tui, Repl, Web],
112    },
113    Command {
114        name: "/resume",
115        aliases: &["/sessions"],
116        args: Args::None,
117        help: "open a stored session (↑↓, enter)",
118        fronts: &[Tui],
119    },
120    Command {
121        name: "/retry",
122        aliases: &[],
123        args: Args::None,
124        help: "run the last question again, without asking it twice",
125        fronts: &[Tui, Repl],
126    },
127    Command {
128        name: "/bg",
129        aliases: &[],
130        args: Args::Shown("<prompt>"),
131        help: "start it as a task that keeps running after this prompt returns",
132        fronts: &[Tui, Repl],
133    },
134    Command {
135        name: "/tasks",
136        aliases: &[],
137        args: Args::Unshown,
138        help: "the background runs: what each is doing, and how it ended",
139        fronts: &[Tui, Repl],
140    },
141    Command {
142        name: "/model",
143        aliases: &[],
144        args: Args::Unshown,
145        help: "pick a model (↑↓, enter)",
146        fronts: &[Tui, Web],
147    },
148    Command {
149        name: "/id",
150        aliases: &[],
151        args: Args::None,
152        help: "show the current session id",
153        fronts: &[Tui, Repl, Web],
154    },
155    Command {
156        name: "/profile",
157        aliases: &[],
158        args: Args::Unshown,
159        help: "which profile, from which file, under which home (`/profile list` for all)",
160        fronts: &[Tui, Repl],
161    },
162    Command {
163        name: "/gateway",
164        aliases: &["/platforms"],
165        args: Args::None,
166        help: "what the gateway is doing: its state, its age, its port and its jobs",
167        fronts: &[Tui, Repl],
168    },
169    Command {
170        name: "/goal",
171        aliases: &[],
172        args: Args::Shown("<text>"),
173        help: "a standing goal, worked on turn by turn until the judge says it is done",
174        // All three: a goal is a row in the session store, so whichever process is running the
175        // session can carry it — and the dashboard's gateway carries on with the tab closed.
176        fronts: &[Tui, Repl, Web],
177    },
178    Command {
179        name: "/loop",
180        aliases: &[],
181        args: Args::Shown("<interval> <prompt>"),
182        help: "send this prompt back into this session every interval (`status|pause|resume|stop`)",
183        // All three, and `Web` because the dashboard's gateway owns the timer there: a loop is the
184        // one command whose meaning depends on which process is holding it, and every front has a
185        // process. The line `/loop` answers with says which one.
186        fronts: &[Tui, Repl, Web],
187    },
188    Command {
189        name: "/cron",
190        aliases: &[],
191        args: Args::Unshown,
192        help: "the scheduled jobs: the table, `run <name>` and `logs <name> [n]`",
193        fronts: &[Tui, Repl, Web],
194    },
195    Command {
196        name: "/reasoning",
197        aliases: &[],
198        args: Args::Unshown,
199        help: "how much it thinks, and how much of it is drawn (`/reasoning high`)",
200        fronts: &[Tui, Repl, Web],
201    },
202    Command {
203        name: "/settings",
204        aliases: &[],
205        args: Args::None,
206        help: "the keys this build reads, and what each is set to",
207        fronts: &[Tui, Repl, Web],
208    },
209    Command {
210        name: "/set",
211        aliases: &[],
212        args: Args::Shown("<key> <value>"),
213        help: "write one setting; the next run uses it",
214        fronts: &[Tui, Repl, Web],
215    },
216    Command {
217        name: "/yolo",
218        aliases: &[],
219        args: Args::Unshown,
220        help: "stop asking before every tool call, until `/yolo off` (this session only)",
221        // The dashboard gets it too (#285), and only because it can now show it: a `yolo` word in
222        // the stats row, in the alert colour, painted from the server's state. The switch lived on
223        // the terminal's bar and nowhere else while the browser had no strip to put it on, and a
224        // verb that turns the cards off and says nothing is worse than one that says where it
225        // lives. `WebApprover` reads it per call and counts what it ran unasked.
226        fronts: &[Tui, Repl, Web],
227    },
228    Command {
229        name: "/status",
230        aliases: &[],
231        args: Args::None,
232        help: "tokens, cache, timings for this process",
233        fronts: &[Tui, Repl, Web],
234    },
235    Command {
236        name: "/compress",
237        aliases: &["/compact"],
238        args: Args::None,
239        help: "replace this session's older turns with the compiled handoff now",
240        fronts: &[Tui, Repl, Web],
241    },
242    Command {
243        name: "/archive",
244        aliases: &[],
245        args: Args::Unshown,
246        help: "file this session away — out of the list, still in the search (`list`, `off`)",
247        fronts: &[Tui, Repl, Web],
248    },
249    Command {
250        name: "/clear",
251        aliases: &[],
252        args: Args::None,
253        help: "clear the transcript",
254        fronts: &[Tui],
255    },
256    Command {
257        name: "/help",
258        aliases: &[],
259        args: Args::None,
260        help: "list the commands",
261        fronts: &[Tui, Repl, Web],
262    },
263    Command {
264        name: "/exit",
265        aliases: &["/quit"],
266        args: Args::None,
267        help: "quit",
268        fronts: &[Tui, Repl],
269    },
270];
271
272impl Command {
273    /// `/set <key> <value>`: the name and its argument, as `/help` and the menu show it. A command
274    /// whose arguments are `Unshown` is just its name — the table does not teach that syntax.
275    pub fn label(&self) -> String {
276        match self.args {
277            Args::Shown(args) => format!("{} {args}", self.name),
278            Args::None | Args::Unshown => self.name.to_string(),
279        }
280    }
281
282    /// The word to put in the line for someone who has typed `prefix`: the name, unless only
283    /// an alias starts with it — `/qu` completes to `/quit`, not to a command they did not type.
284    pub fn spelling(&self, prefix: &str) -> &'static str {
285        if self.name.starts_with(prefix) {
286            return self.name;
287        }
288        self.aliases
289            .iter()
290            .copied()
291            .find(|a| a.starts_with(prefix))
292            .unwrap_or(self.name)
293    }
294
295    /// What completing `prefix` to this command leaves in the line. A command that takes an
296    /// argument gets a space after it, so the next key is the argument.
297    pub fn fill(&self, prefix: &str) -> String {
298        let word = self.spelling(prefix);
299        if self.args.takes() {
300            format!("{word} ")
301        } else {
302            word.to_string()
303        }
304    }
305
306    /// Whether `viewer` has this command.
307    pub fn serves(&self, viewer: Front) -> bool {
308        self.fronts.contains(&viewer)
309    }
310
311    /// Why this command does nothing in `here`, for the front end that was asked for it.
312    ///
313    /// Names every front that *does* have it, because a command can live in two of the three and
314    /// naming one of them would send a person looking in the wrong place. The "how" half is the
315    /// nearest way in: what to type after they have read it.
316    pub fn unavailable_in(&self, here: Front) -> String {
317        let elsewhere: Vec<Front> = self.fronts.iter().copied().filter(|f| *f != here).collect();
318        let places: Vec<&str> = elsewhere.iter().map(|f| f.place()).collect();
319        let how = elsewhere
320            .iter()
321            .find(|f| f.keyboard())
322            .or_else(|| elsewhere.first())
323            .map_or("", |f| f.enter());
324        let list = match places.split_last() {
325            Some((last, [])) => (*last).to_string(),
326            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
327            None => "no interface".to_string(),
328        };
329        if how.is_empty() {
330            format!("{} is only in {list}", self.name)
331        } else {
332            format!("{} is only in {list} ({how})", self.name)
333        }
334    }
335}
336
337/// The command a word names, by canonical name or alias, exactly.
338pub fn lookup(word: &str) -> Option<&'static Command> {
339    COMMANDS
340        .iter()
341        .find(|c| c.name == word || c.aliases.contains(&word))
342}
343
344/// The commands whose name or an alias starts with `prefix`, in table order, that `front` has.
345pub fn matching(prefix: &str, front: Front) -> Vec<&'static Command> {
346    COMMANDS
347        .iter()
348        .filter(|c| c.serves(front))
349        .filter(|c| c.name.starts_with(prefix) || c.aliases.iter().any(|a| a.starts_with(prefix)))
350        .collect()
351}
352
353#[derive(Debug, PartialEq, Eq)]
354pub enum Completion {
355    Unique(&'static Command),
356    Several(Vec<&'static Command>),
357    None,
358}
359
360/// Whether `line` is a command word being typed: a leading `/` and no whitespace yet.
361///
362/// `complete` answers `None` for three different situations — prose, an argument, and a command
363/// word with no match — and the menu has to tell them apart: the first two close it for good, the
364/// third stays on screen saying so (#253).
365pub fn is_command_word(line: &str) -> bool {
366    line.starts_with('/') && !line.contains(char::is_whitespace)
367}
368
369/// What Tab does to `line`. Only while the command word is being typed: the line starts with
370/// `/` and has no whitespace yet. Anything else — prose, or an argument — is `None`, so Tab
371/// stays whatever the editor already made it.
372pub fn complete(line: &str, front: Front) -> Completion {
373    if !line.starts_with('/') || line.contains(char::is_whitespace) {
374        return Completion::None;
375    }
376    let mut found = matching(line, front);
377    match found.len() {
378        0 => Completion::None,
379        1 => Completion::Unique(found.remove(0)),
380        _ => Completion::Several(found),
381    }
382}
383
384/// A line that starts with `/`, resolved against what `front` has.
385#[derive(Debug, PartialEq, Eq)]
386pub enum Parsed<'a> {
387    /// A command this interface has, with the text after the word (trimmed, maybe empty).
388    Run(&'static Command, &'a str),
389    /// A real command that only the other interface has.
390    Elsewhere(&'static Command),
391    /// No such command, or an argument given to one that takes none. Carries the line.
392    Unknown(&'a str),
393}
394
395pub fn parse(line: &str, front: Front) -> Parsed<'_> {
396    let line = line.trim();
397    let (word, rest) = match line.split_once(char::is_whitespace) {
398        Some((word, rest)) => (word, rest.trim()),
399        None => (line, ""),
400    };
401    match lookup(word) {
402        None => Parsed::Unknown(line),
403        Some(c) if !c.serves(front) => Parsed::Elsewhere(c),
404        Some(c) if !rest.is_empty() && !c.args.takes() => Parsed::Unknown(line),
405        Some(c) => Parsed::Run(c, rest),
406    }
407}
408
409/// The `/help` body for `front`: one line per command, in table order.
410pub fn help(front: Front) -> String {
411    let shown: Vec<&Command> = COMMANDS.iter().filter(|c| c.serves(front)).collect();
412    let width = shown
413        .iter()
414        .map(|c| c.label().chars().count())
415        .max()
416        .unwrap_or(0)
417        .max("!command".len());
418    let mut lines: Vec<String> = shown
419        .iter()
420        .map(|c| {
421            let also = if c.aliases.is_empty() {
422                String::new()
423            } else {
424                format!(" (also {})", c.aliases.join(", "))
425            };
426            format!("{:<width$}  {}{also}", c.label(), c.help)
427        })
428        .collect();
429    // Not a slash command — it has no name to complete and no menu entry — so it is named here,
430    // where someone reads what the composer will accept. A leading bang changes what Enter does,
431    // and something that changes what Enter does is not discoverable enough on its own.
432    //
433    // Only where `!` means something: the dashboard has no bang (`#283`), so naming a leading bang
434    // there would teach a syntax that is prose.
435    if front.keyboard() {
436        lines.push(format!(
437            "{:<width$}  run a shell command here: no turn, no tokens, nothing added to the session",
438            "!command"
439        ));
440    }
441    lines.join("\n")
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    fn names(found: &[&Command]) -> Vec<&'static str> {
449        found.iter().map(|c| c.name).collect()
450    }
451
452    /// An argument a command accepts but the table does not advertise still parses.
453    ///
454    /// `/model 3` is kept because a name is not always easy to type; what changed is the *hint*,
455    /// so `/help` no longer teaches the positional form as the way to switch a model.
456    #[test]
457    fn an_unshown_argument_still_parses_but_is_not_in_the_table() {
458        let help = help(Front::Tui);
459        let model_row = help
460            .lines()
461            .find(|l| l.starts_with("/model"))
462            .unwrap_or_default();
463        assert!(
464            model_row.contains("pick a model (↑↓, enter)"),
465            "the row says what happens, in /resume's shape: {model_row:?}"
466        );
467        assert!(
468            !help.contains("[number|name]"),
469            "and no longer teaches the syntax the picker replaced:\n{help}"
470        );
471        assert!(
472            help.contains("/set <key> <value>"),
473            "a command whose arguments are the way in still spells them:\n{help}"
474        );
475
476        // Behaviour is untouched: a number or a name still resolves, and a command that takes no
477        // argument still refuses one.
478        match parse("/model 3", Front::Tui) {
479            Parsed::Run(c, rest) => {
480                assert_eq!(c.name, "/model");
481                assert_eq!(rest, "3");
482            }
483            other => panic!("/model 3 must still run: {other:?}"),
484        }
485        assert!(matches!(
486            parse("/new something", Front::Tui),
487            Parsed::Unknown(_)
488        ));
489        assert!(matches!(parse("/model", Front::Tui), Parsed::Run(..)));
490        // Completing it leaves a space, because the picker is not the only way in.
491        let model = lookup("/model").expect("in the table");
492        assert_eq!(model.fill("/mo"), "/model ");
493        assert_eq!(model.label(), "/model", "and the label is just its name");
494    }
495
496    /// The three `None`s are not the same `None` (#253).
497    #[test]
498    fn a_command_word_is_told_apart_from_prose_and_from_an_argument() {
499        assert!(is_command_word("/"));
500        assert!(is_command_word("/cr"));
501        assert!(
502            is_command_word("/zzz"),
503            "a word with no match is still a word"
504        );
505        assert!(!is_command_word(""));
506        assert!(!is_command_word("hello"));
507        assert!(!is_command_word("/cron brief"), "an argument is not a word");
508        assert!(!is_command_word("/cron "), "a trailing space ends the word");
509        // The menu's list for a word with no match is empty rather than `None`.
510        assert!(matching("/zzz", Front::Tui).is_empty());
511        let served = COMMANDS.iter().filter(|c| c.serves(Front::Tui)).count();
512        assert_eq!(matching("/", Front::Tui).len(), served);
513    }
514
515    #[test]
516    fn every_word_in_the_table_is_unique() {
517        let mut words: Vec<&str> = COMMANDS
518            .iter()
519            .flat_map(|c| std::iter::once(c.name).chain(c.aliases.iter().copied()))
520            .collect();
521        let all = words.len();
522        words.sort_unstable();
523        words.dedup();
524        assert_eq!(words.len(), all, "a name or alias is listed twice");
525        assert!(words.iter().all(|w| w.starts_with('/')));
526    }
527
528    #[test]
529    fn lookup_finds_a_name_or_an_alias_exactly() {
530        assert_eq!(lookup("/resume").map(|c| c.name), Some("/resume"));
531        assert_eq!(lookup("/sessions").map(|c| c.name), Some("/resume"));
532        assert_eq!(lookup("/quit").map(|c| c.name), Some("/exit"));
533        assert!(lookup("/re").is_none(), "a prefix is not a command");
534        assert!(lookup("/NEW").is_none());
535        assert!(lookup("new").is_none());
536    }
537
538    #[test]
539    fn matching_lists_names_and_aliases_in_table_order() {
540        assert_eq!(
541            names(&matching("/s", Front::Tui)),
542            ["/resume", "/settings", "/set", "/status"]
543        );
544        assert_eq!(names(&matching("/ses", Front::Tui)), ["/resume"]);
545        assert_eq!(names(&matching("/qu", Front::Tui)), ["/exit"]);
546        assert_eq!(
547            names(&matching("/", Front::Tui)),
548            [
549                "/new",
550                "/resume",
551                "/retry",
552                "/bg",
553                "/tasks",
554                "/model",
555                "/id",
556                "/profile",
557                "/gateway",
558                "/goal",
559                "/loop",
560                "/cron",
561                "/reasoning",
562                "/settings",
563                "/set",
564                "/yolo",
565                "/status",
566                "/compress",
567                "/archive",
568                "/clear",
569                "/help",
570                "/exit"
571            ]
572        );
573        assert!(matching("/zzz", Front::Tui).is_empty());
574    }
575
576    #[test]
577    fn matching_only_offers_what_the_front_end_has() {
578        assert_eq!(
579            names(&matching("/s", Front::Repl)),
580            ["/settings", "/set", "/status"]
581        );
582        assert_eq!(
583            names(&matching("/", Front::Repl)),
584            [
585                "/new",
586                "/retry",
587                "/bg",
588                "/tasks",
589                "/id",
590                "/profile",
591                "/gateway",
592                "/goal",
593                "/loop",
594                "/cron",
595                "/reasoning",
596                "/settings",
597                "/set",
598                "/yolo",
599                "/status",
600                "/compress",
601                "/archive",
602                "/help",
603                "/exit"
604            ]
605        );
606        assert!(matching("/cl", Front::Repl).is_empty());
607        assert_eq!(names(&matching("/cl", Front::Tui)), ["/clear"]);
608    }
609
610    #[test]
611    fn complete_is_unique_several_or_none_by_how_many_match() {
612        assert_eq!(
613            complete("/ne", Front::Repl),
614            Completion::Unique(&COMMANDS[0])
615        );
616        match complete("/s", Front::Tui) {
617            Completion::Several(found) => {
618                assert_eq!(names(&found), ["/resume", "/settings", "/set", "/status"])
619            }
620            other => panic!("expected several, got {other:?}"),
621        }
622        assert_eq!(complete("/zzz", Front::Tui), Completion::None);
623        assert!(matches!(complete("/", Front::Tui), Completion::Several(_)));
624    }
625
626    #[test]
627    fn complete_only_answers_while_the_command_word_is_being_typed() {
628        for line in [
629            "",
630            "hello",
631            "hello /ne",
632            " /ne",
633            "/new ",
634            "/model gem",
635            "/ne w",
636        ] {
637            assert_eq!(complete(line, Front::Tui), Completion::None, "{line:?}");
638        }
639    }
640
641    #[test]
642    fn an_alias_completes_to_the_alias_and_an_argument_command_gets_a_space() {
643        let resume = lookup("/resume").unwrap();
644        assert_eq!(resume.fill("/ses"), "/sessions");
645        assert_eq!(resume.fill("/re"), "/resume");
646        assert_eq!(resume.fill("/"), "/resume");
647        assert_eq!(lookup("/model").unwrap().fill("/mo"), "/model ");
648        assert_eq!(lookup("/exit").unwrap().fill("/qu"), "/quit");
649        assert_eq!(lookup("/new").unwrap().fill("/ne"), "/new");
650    }
651
652    #[test]
653    fn help_has_one_aligned_line_per_command_the_front_end_has() {
654        let tui = help(Front::Tui);
655        // One line per command, plus `!command`, which is not a command but does change what Enter
656        // does and so has to be named where the commands are named.
657        assert_eq!(tui.lines().count(), COMMANDS.len() + 1);
658        assert!(tui.contains("!command"), "{tui}");
659        assert!(
660            tui.lines().last().unwrap().starts_with("!command"),
661            "named last, where it is not mistaken for something completable: {tui}"
662        );
663        assert!(tui.contains("/resume"), "{tui}");
664        assert!(tui.contains("(also /sessions)"), "{tui}");
665        assert!(tui.contains("(also /quit)"), "{tui}");
666        // The help column starts at the same place on every line.
667        let col = |l: &str, needle: &str| l.find(needle);
668        assert_eq!(
669            col(tui.lines().nth(1).unwrap_or(""), "open a stored"),
670            col(tui.lines().nth(5).unwrap_or(""), "pick a model")
671        );
672        assert!(tui.lines().all(|l| l == l.trim_end()));
673
674        let repl = help(Front::Repl);
675        assert_eq!(
676            repl.lines()
677                .map(|l| l.split_whitespace().next().unwrap_or(""))
678                .collect::<Vec<_>>(),
679            [
680                "/new",
681                "/retry",
682                "/bg",
683                "/tasks",
684                "/id",
685                "/profile",
686                "/gateway",
687                "/goal",
688                "/loop",
689                "/cron",
690                "/reasoning",
691                "/settings",
692                "/set",
693                "/yolo",
694                "/status",
695                "/compress",
696                "/archive",
697                "/help",
698                "/exit",
699                // Not a command — the one accepted line here that does not start with a slash —
700                // but the REPL takes it, so it belongs where the accepted lines are listed.
701                "!command"
702            ]
703        );
704        for tui_only in ["/clear", "/resume", "/model"] {
705            assert!(!repl.contains(tui_only), "{repl}");
706        }
707    }
708
709    #[test]
710    fn parse_resolves_aliases_and_separates_the_other_front_ends_commands() {
711        assert_eq!(
712            parse("/sessions", Front::Tui),
713            Parsed::Run(lookup("/resume").unwrap(), "")
714        );
715        assert_eq!(
716            parse("  /model  gemma ", Front::Tui),
717            Parsed::Run(lookup("/model").unwrap(), "gemma")
718        );
719        assert_eq!(
720            parse("/clear", Front::Repl),
721            Parsed::Elsewhere(lookup("/clear").unwrap())
722        );
723        assert_eq!(parse("/nope", Front::Tui), Parsed::Unknown("/nope"));
724        assert_eq!(parse("/new now", Front::Tui), Parsed::Unknown("/new now"));
725        assert_eq!(parse("/", Front::Tui), Parsed::Unknown("/"));
726    }
727
728    /// Every row has to be reachable from somewhere, or it is a line in `/help` nobody can type.
729    #[test]
730    fn every_command_is_served_somewhere_and_listed_once() {
731        for c in COMMANDS {
732            assert!(
733                !c.fronts.is_empty(),
734                "{} is in the table with no front end to type it in",
735                c.name
736            );
737            let mut seen = c.fronts.to_vec();
738            seen.sort_by_key(|f| format!("{f:?}"));
739            let before = seen.len();
740            seen.dedup();
741            assert_eq!(before, seen.len(), "{} names a front twice", c.name);
742        }
743    }
744
745    /// `#254`: the dashboard reads this table too, and it may only ever be given what a terminal
746    /// already has. Strict, not equal — a verb that exists in the browser and nowhere else would
747    /// mean the table had grown a fourth opinion about what a command is.
748    #[test]
749    fn the_dashboards_verbs_are_a_strict_subset_of_the_terminals() {
750        let web: Vec<&str> = COMMANDS
751            .iter()
752            .filter(|c| c.serves(Front::Web))
753            .map(|c| c.name)
754            .collect();
755        let terminal: Vec<&str> = COMMANDS
756            .iter()
757            .filter(|c| c.serves(Front::Repl) || c.serves(Front::Tui))
758            .map(|c| c.name)
759            .collect();
760        assert!(
761            web.iter().all(|n| terminal.contains(n)),
762            "a command only the dashboard has: {web:?}"
763        );
764        assert!(
765            web.len() < terminal.len(),
766            "the web set is not a subset anyone has to think about: {web:?}"
767        );
768        // Named, so a verb cannot gain or lose the dashboard by accident: this is the list the
769        // composer gives words to. Two deliberate absences — `/resume`, because opening a stored
770        // session in the browser is the sidebar rather than a line to type, and `/yolo`, because
771        // approvals off has to be *visible* and this surface has nowhere to show it (#285).
772        assert_eq!(
773            web,
774            [
775                "/new",
776                "/model",
777                "/id",
778                "/goal",
779                "/loop",
780                "/cron",
781                "/reasoning",
782                "/settings",
783                "/set",
784                "/yolo",
785                "/status",
786                "/compress",
787                "/archive",
788                "/help"
789            ]
790        );
791        assert!(
792            !lookup("/resume").unwrap().serves(Front::Web),
793            "opening a stored session is the sidebar, not a line to type"
794        );
795        // `#285`: the dashboard has the switch now, because it has a word to show it with. The
796        // assertion that used to hold the absence is gone on purpose — it was there so a verb
797        // could not be added to the browser by accident before the page could say it was on.
798        assert!(lookup("/yolo").unwrap().serves(Front::Web));
799    }
800
801    #[test]
802    fn an_unavailable_command_says_where_it_is() {
803        let said = lookup("/clear").unwrap().unavailable_in(Front::Repl);
804        assert!(
805            said.contains("/clear") && said.contains("full-screen"),
806            "{said}"
807        );
808        // Two fronts have `/bg`, so both are named: a sentence that picked one would send the
809        // reader to the interface they may not be able to run.
810        let bg = lookup("/bg").unwrap().unavailable_in(Front::Web);
811        assert!(
812            bg.contains("only in the full-screen interface and the plain REPL"),
813            "{bg}"
814        );
815        assert!(bg.contains("run eclipse without --plain"), "{bg}");
816        // And the other way round: a terminal-only verb asked for from the dashboard says so in
817        // the dashboard's own words.
818        let resume = lookup("/resume").unwrap().unavailable_in(Front::Web);
819        assert!(
820            resume.contains("only in the full-screen interface"),
821            "{resume}"
822        );
823        assert!(resume.contains("run eclipse without --plain"), "{resume}");
824    }
825}