Skip to main content

kitchen_shell/
command.rs

1//! What an app can do, declared once: each [`CommandSpec`] has an id, a title, an icon, a line
2//! saying what it does, a group, a key, the JSON Schema of its arguments, when it is enabled (and
3//! why not), and the function that runs it. The [`Registry`] turns that one list into the menus
4//! ([`Registry::menu_button`]), the search rows ([`crate::search`]), the key bindings
5//! ([`Registry::bind_keys`]) and an agent's tools (`kitchen-chat`), so none drifts from the
6//! others: a command is in the search because it is in the list, greyed with its reason
7//! wherever it cannot run.
8
9use std::cell::RefCell;
10use std::rc::Rc;
11
12use gpui_kit::assets::IconName;
13use gpui_kit::component::button::{Button, ButtonVariants as _};
14use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu, PopupMenuItem};
15use gpui_kit::component::{Icon, Sizable as _, v_flex};
16use gpui_kit::{
17    Action, App, Context, IntoElement, KeyBinding, ParentElement as _, SharedString, Styled as _, Window, div,
18};
19use kitchen_ui::theme::color;
20use schemars::JsonSchema;
21use serde::de::DeserializeOwned;
22use serde_json::Value;
23
24/// Runs a command with its arguments (`null` when it takes none); its result is JSON (`null`
25/// for a plain action), and an error says why it did not run.
26pub type RunFn = Rc<dyn Fn(Value, &mut Window, &mut App) -> Result<Value, String>>;
27/// Whether a command can run now; `Err` says why not (shown greyed in menus and search).
28pub type EnabledFn = Rc<dyn Fn(&App) -> Result<(), String>>;
29/// Whether a toggle command is on (a check mark in menus).
30pub type CheckedFn = Rc<dyn Fn(&App) -> bool>;
31/// Makes a menu's entries when it opens, from what the app holds then (its images, recent
32/// files, the models that fit): see [`Registry::provide`] and [`MenuItem::Provided`].
33pub type MenuProvider = Rc<dyn Fn(&App) -> Vec<MenuItem>>;
34
35/// The action every command key and menu item dispatches: run the command `id` (no arguments).
36#[derive(Clone, Debug, PartialEq, Action)]
37#[action(namespace = kitchen, no_json)]
38pub struct RunCommand {
39    /// The command's id.
40    pub id: SharedString,
41}
42
43/// One thing an app can do.
44#[derive(Clone)]
45pub struct CommandSpec {
46    /// Unique, dotted by area: `file.open`, `hist.find_cells`, `pipeline.add_op`.
47    pub id: SharedString,
48    /// What menus and search show: "Open image…".
49    pub title: SharedString,
50    /// Its icon, in menus and search.
51    pub icon: IconName,
52    /// One line saying what it does (search, tooltips, the agent's tool description).
53    pub hint: SharedString,
54    /// The group it is listed under in search ("File", "Process").
55    pub group: SharedString,
56    /// Its key in GPUI's notation (`secondary-o`: Cmd on macOS, Ctrl elsewhere), if any.
57    pub key: Option<SharedString>,
58    /// The JSON Schema of its arguments, when an agent can pass some ([`CommandSpec::with_args`]).
59    pub args: Option<Value>,
60    /// Whether it only reads (an agent may run it without asking).
61    pub read_only: bool,
62    /// Whether it can run now, and why not.
63    pub enabled: EnabledFn,
64    /// For a toggle: whether it is on.
65    pub checked: Option<CheckedFn>,
66    /// What it does.
67    pub run: RunFn,
68}
69
70impl CommandSpec {
71    /// A plain command: no arguments, no result.
72    pub fn new(
73        id: impl Into<SharedString>,
74        title: impl Into<SharedString>,
75        icon: IconName,
76        run: impl Fn(&mut Window, &mut App) + 'static,
77    ) -> Self {
78        Self::raw(
79            id,
80            title,
81            icon,
82            None,
83            Rc::new(move |_, window, cx| {
84                run(window, cx);
85                Ok(Value::Null)
86            }),
87        )
88    }
89
90    /// A command taking arguments `A` (their JSON Schema comes from `A`, and a call whose
91    /// arguments do not read as `A` is refused with the reason) and returning JSON.
92    pub fn with_args<A: DeserializeOwned + JsonSchema + 'static>(
93        id: impl Into<SharedString>,
94        title: impl Into<SharedString>,
95        icon: IconName,
96        run: impl Fn(A, &mut Window, &mut App) -> Result<Value, String> + 'static,
97    ) -> Self {
98        let schema = serde_json::to_value(schemars::schema_for!(A)).ok();
99        Self::raw(
100            id,
101            title,
102            icon,
103            schema,
104            Rc::new(move |args, window, cx| {
105                // A command whose arguments are all optional also runs with none
106                let args = if args.is_null() { Value::Object(Default::default()) } else { args };
107                let a: A = serde_json::from_value(args).map_err(|e| format!("arguments: {e}"))?;
108                run(a, window, cx)
109            }),
110        )
111    }
112
113    /// A command from its parts: `args` is its JSON Schema (or `None`), `run` gets the raw JSON.
114    pub fn raw(
115        id: impl Into<SharedString>,
116        title: impl Into<SharedString>,
117        icon: IconName,
118        args: Option<Value>,
119        run: RunFn,
120    ) -> Self {
121        Self {
122            id: id.into(),
123            title: title.into(),
124            icon,
125            hint: SharedString::default(),
126            group: "Commands".into(),
127            key: None,
128            args,
129            read_only: false,
130            enabled: Rc::new(|_| Ok(())),
131            checked: None,
132            run,
133        }
134    }
135
136    /// Sets the line saying what it does.
137    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
138        self.hint = hint.into();
139        self
140    }
141
142    /// Sets the group it is listed under.
143    pub fn group(mut self, group: impl Into<SharedString>) -> Self {
144        self.group = group.into();
145        self
146    }
147
148    /// Sets its key (`secondary-o`, `f3`, `secondary-shift-s`).
149    pub fn key(mut self, key: impl Into<SharedString>) -> Self {
150        self.key = Some(key.into());
151        self
152    }
153
154    /// Marks it as only reading (an agent may run it without asking).
155    pub fn read_only(mut self) -> Self {
156        self.read_only = true;
157        self
158    }
159
160    /// Sets when it can run (`Err(why)` otherwise).
161    pub fn enabled(mut self, enabled: impl Fn(&App) -> Result<(), String> + 'static) -> Self {
162        self.enabled = Rc::new(enabled);
163        self
164    }
165
166    /// Makes it a toggle, on when `checked` says so.
167    pub fn checked(mut self, checked: impl Fn(&App) -> bool + 'static) -> Self {
168        self.checked = Some(Rc::new(checked));
169        self
170    }
171
172    /// Its key as people read it ("Ctrl+Shift+S", "⌘⇧S" on macOS).
173    pub fn key_label(&self) -> Option<String> {
174        self.key.as_deref().map(key_label)
175    }
176}
177
178/// An entry of a menu.
179#[derive(Clone, Debug, PartialEq)]
180pub enum MenuItem {
181    /// A registered command, by id.
182    Command(SharedString),
183    /// A registered command run with arguments, under its own title: one entry per image, per
184    /// recent file, per model. Greyed with the command's reason when it cannot run.
185    Run {
186        /// What the entry says.
187        title: SharedString,
188        /// Its icon (the command's when `None`).
189        icon: Option<IconName>,
190        /// The command's id.
191        command: SharedString,
192        /// Its arguments.
193        args: Value,
194        /// A check mark (the entry is the current choice).
195        checked: bool,
196    },
197    /// The entries the provider `id` makes when the menu opens ([`Registry::provide`]).
198    Provided(SharedString),
199    /// A line between groups.
200    Separator,
201    /// A heading (not clickable).
202    Label(SharedString),
203    /// A menu inside the menu.
204    Submenu {
205        /// What the entry says.
206        title: SharedString,
207        /// Its icon.
208        icon: Option<IconName>,
209        /// What it holds.
210        items: Vec<MenuItem>,
211    },
212}
213
214impl MenuItem {
215    /// The command `id`.
216    pub fn command(id: impl Into<SharedString>) -> Self {
217        MenuItem::Command(id.into())
218    }
219
220    /// A submenu `title` holding `items`.
221    pub fn submenu(title: impl Into<SharedString>, items: Vec<MenuItem>) -> Self {
222        MenuItem::Submenu { title: title.into(), icon: None, items }
223    }
224
225    /// A submenu `title` with `icon`, holding `items`.
226    pub fn submenu_with_icon(title: impl Into<SharedString>, icon: IconName, items: Vec<MenuItem>) -> Self {
227        MenuItem::Submenu { title: title.into(), icon: Some(icon), items }
228    }
229
230    /// The command `command` run with `args`, titled `title`.
231    pub fn run(title: impl Into<SharedString>, command: impl Into<SharedString>, args: Value) -> Self {
232        MenuItem::Run { title: title.into(), icon: None, command: command.into(), args, checked: false }
233    }
234
235    /// The entries of the provider `id`.
236    pub fn provided(id: impl Into<SharedString>) -> Self {
237        MenuItem::Provided(id.into())
238    }
239
240    /// A heading.
241    pub fn label(text: impl Into<SharedString>) -> Self {
242        MenuItem::Label(text.into())
243    }
244
245    /// Sets the icon of a [`MenuItem::Run`] or a submenu (other entries are unchanged).
246    pub fn icon(mut self, with: IconName) -> Self {
247        match &mut self {
248            MenuItem::Run { icon, .. } | MenuItem::Submenu { icon, .. } => *icon = Some(with),
249            _ => {}
250        }
251        self
252    }
253
254    /// Sets the check mark of a [`MenuItem::Run`] (other entries are unchanged).
255    pub fn checked(mut self, on: bool) -> Self {
256        if let MenuItem::Run { checked, .. } = &mut self {
257            *checked = on;
258        }
259        self
260    }
261}
262
263/// A menu of a menu row or title bar: its title and its entries.
264#[derive(Clone, Debug, PartialEq)]
265pub struct MenuSpec {
266    /// What the button says ("File", "Process").
267    pub title: SharedString,
268    /// The tooltip of its button.
269    pub hint: SharedString,
270    /// Its entries.
271    pub items: Vec<MenuItem>,
272}
273
274impl MenuSpec {
275    /// A menu `title` with `items`.
276    pub fn new(title: impl Into<SharedString>, items: Vec<MenuItem>) -> Self {
277        Self { title: title.into(), hint: SharedString::default(), items }
278    }
279
280    /// Sets the tooltip of its button.
281    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
282        self.hint = hint.into();
283        self
284    }
285
286    /// The ids of the commands it holds, submenus included, in order.
287    pub fn command_ids(&self) -> Vec<SharedString> {
288        fn walk(items: &[MenuItem], out: &mut Vec<SharedString>) {
289            for i in items {
290                match i {
291                    MenuItem::Command(id) | MenuItem::Run { command: id, .. } => out.push(id.clone()),
292                    MenuItem::Submenu { items, .. } => walk(items, out),
293                    _ => {}
294                }
295            }
296        }
297        let mut out = Vec::new();
298        walk(&self.items, &mut out);
299        out
300    }
301}
302
303/// Every command of an app, shared by its menus, search, keys and agent (a cheap handle: clones
304/// share the same list).
305#[derive(Clone, Default)]
306pub struct Registry {
307    commands: Rc<RefCell<Vec<CommandSpec>>>,
308    providers: Rc<RefCell<Vec<(SharedString, MenuProvider)>>>,
309}
310
311impl Registry {
312    /// A registry holding `commands`.
313    pub fn new(commands: Vec<CommandSpec>) -> Self {
314        let r = Self::default();
315        r.extend(commands);
316        r
317    }
318
319    /// Adds a command, replacing one with the same id.
320    pub fn add(&self, command: CommandSpec) {
321        let mut list = self.commands.borrow_mut();
322        match list.iter_mut().find(|c| c.id == command.id) {
323            Some(c) => *c = command,
324            None => list.push(command),
325        }
326    }
327
328    /// Adds several commands ([`Registry::add`] each).
329    pub fn extend(&self, commands: impl IntoIterator<Item = CommandSpec>) {
330        for c in commands {
331            self.add(c);
332        }
333    }
334
335    /// Removes the command `id`; whether it was there.
336    pub fn remove(&self, id: &str) -> bool {
337        let mut list = self.commands.borrow_mut();
338        let n = list.len();
339        list.retain(|c| c.id != id);
340        list.len() != n
341    }
342
343    /// The command `id`.
344    pub fn get(&self, id: &str) -> Option<CommandSpec> {
345        self.commands.borrow().iter().find(|c| c.id == id).cloned()
346    }
347
348    /// Every command, in the order added.
349    pub fn all(&self) -> Vec<CommandSpec> {
350        self.commands.borrow().clone()
351    }
352
353    /// How many commands it holds.
354    pub fn len(&self) -> usize {
355        self.commands.borrow().len()
356    }
357
358    /// Whether it holds none.
359    pub fn is_empty(&self) -> bool {
360        self.commands.borrow().is_empty()
361    }
362
363    /// Registers the menu provider `id` (replacing one with the same id): a
364    /// [`MenuItem::Provided`] naming it shows the entries it makes when the menu opens.
365    pub fn provide(&self, id: impl Into<SharedString>, provider: impl Fn(&App) -> Vec<MenuItem> + 'static) {
366        let id = id.into();
367        let mut list = self.providers.borrow_mut();
368        list.retain(|(p, _)| *p != id);
369        list.push((id, Rc::new(provider)));
370    }
371
372    /// The entries the provider `id` makes now (none when there is no such provider).
373    pub fn provided(&self, id: &str, cx: &App) -> Vec<MenuItem> {
374        let provider = self.providers.borrow().iter().find(|(p, _)| p == id).map(|(_, f)| f.clone());
375        provider.map(|f| f(cx)).unwrap_or_default()
376    }
377
378    /// Whether `id` can run now (`Err` says why not, or that there is no such command).
379    pub fn check(&self, id: &str, cx: &App) -> Result<(), String> {
380        let c = self.get(id).ok_or_else(|| format!("no command {id:?}"))?;
381        (c.enabled)(cx)
382    }
383
384    /// Runs `id` with `args` (`null` for none), when it can run now, as the person did.
385    pub fn run(&self, id: &str, args: Value, window: &mut Window, cx: &mut App) -> Result<Value, String> {
386        self.run_as(crate::activity::Actor::Person, "app", id, args, window, cx)
387    }
388
389    /// Runs `id` with `args` for `actor`, started from `via` (menu, key, search, title bar, agent),
390    /// and records it in the activity log ([`crate::activity`]), refused or not.
391    pub fn run_as(
392        &self,
393        actor: crate::activity::Actor,
394        via: &str,
395        id: &str,
396        args: Value,
397        window: &mut Window,
398        cx: &mut App,
399    ) -> Result<Value, String> {
400        let Some(c) = self.get(id) else { return Err(format!("no command {id:?}")) };
401        let result = (c.enabled)(cx).and_then(|_| (c.run)(args.clone(), window, cx));
402        crate::activity::command(actor, id, &c.title, &c.group, via, &args, &result);
403        result
404    }
405
406    /// Binds every command's key to [`RunCommand`] (globally; `context` limits them to a part of
407    /// the window, as GPUI's key contexts do). A key that does not parse is skipped and named
408    /// in the result.
409    pub fn bind_keys(&self, context: Option<&str>, cx: &mut App) -> Vec<String> {
410        let mut bindings = Vec::new();
411        let mut bad = Vec::new();
412        let context = match context.map(gpui_kit::KeyBindingContextPredicate::parse).transpose() {
413            Ok(c) => c.map(Rc::new),
414            Err(e) => return vec![format!("context {context:?}: {e}")],
415        };
416        for c in self.all() {
417            let Some(key) = c.key.clone() else { continue };
418            match KeyBinding::load(&key, Box::new(RunCommand { id: c.id.clone() }), context.clone(), false, None, cx) {
419                Ok(b) => bindings.push(b),
420                Err(e) => bad.push(format!("{}: {key}: {e:?}", c.id)),
421            }
422        }
423        cx.bind_keys(bindings);
424        bad
425    }
426
427    /// A ghost button titled as `menu`, opening its entries: each command with its icon, key
428    /// and check mark; a command that cannot run now is greyed with its reason under it.
429    pub fn menu_button(&self, id: impl Into<SharedString>, menu: &MenuSpec) -> gpui_kit::AnyElement {
430        let registry = self.clone();
431        let items = Rc::new(menu.items.clone());
432        let mut button = Button::new(id.into()).ghost().small().label(menu.title.clone());
433        if !menu.hint.is_empty() {
434            button = button.tooltip(menu.hint.clone());
435        }
436        // Long menus (an entry per image or channel) scroll
437        button
438            .dropdown_menu(move |m, window, cx| {
439                registry.fill_menu(
440                    m.min_w(gpui_kit::px(240.)).scrollable(true).max_h(gpui_kit::px(560.)),
441                    &items,
442                    window,
443                    cx,
444                )
445            })
446            .into_any_element()
447    }
448
449    /// Adds `items` to `menu` (as [`Registry::menu_button`] does).
450    pub fn fill_menu(
451        &self,
452        mut menu: PopupMenu,
453        items: &[MenuItem],
454        window: &mut Window,
455        cx: &mut Context<PopupMenu>,
456    ) -> PopupMenu {
457        for item in items {
458            menu = match item {
459                MenuItem::Separator => menu.separator(),
460                MenuItem::Label(text) => menu.label(text.clone()),
461                MenuItem::Submenu { title, icon, items } => {
462                    let (registry, items) = (self.clone(), items.clone());
463                    menu.submenu_with_icon(icon.map(Icon::new), title.clone(), window, cx, move |m, window, cx| {
464                        registry.fill_menu(m, &items, window, cx)
465                    })
466                }
467                MenuItem::Command(id) => match self.get(id) {
468                    Some(c) => menu.item(self.menu_item(&c, cx)),
469                    // A menu naming a command the app did not register shows it, greyed
470                    None => menu.item(PopupMenuItem::new(format!("{id} (not registered)")).disabled(true)),
471                },
472                MenuItem::Run { title, icon, command, args, checked } => match self.get(command) {
473                    Some(c) => menu.item(self.run_item(&c, title, icon.unwrap_or(c.icon), args, *checked, cx)),
474                    None => menu.item(PopupMenuItem::new(format!("{title} ({command} not registered)")).disabled(true)),
475                },
476                MenuItem::Provided(id) => {
477                    let items = self.provided(id, cx);
478                    self.fill_menu(menu, &items, window, cx)
479                }
480            };
481        }
482        menu
483    }
484
485    /// An entry running `c` with `args` under `title`.
486    fn run_item(
487        &self,
488        c: &CommandSpec,
489        title: &SharedString,
490        icon: IconName,
491        args: &Value,
492        checked: bool,
493        cx: &App,
494    ) -> PopupMenuItem {
495        match (c.enabled)(cx) {
496            Ok(()) => {
497                let (registry, id, args) = (self.clone(), c.id.clone(), args.clone());
498                PopupMenuItem::new(title.clone()).icon(Icon::new(icon)).checked(checked).on_click(
499                    move |_, window, cx| {
500                        if let Err(e) =
501                            registry.run_as(crate::activity::Actor::Person, "menu", &id, args.clone(), window, cx)
502                        {
503                            eprintln!("{id}: {e}");
504                        }
505                    },
506                )
507            }
508            Err(why) => {
509                let title = title.clone();
510                PopupMenuItem::element(move |_, _| {
511                    v_flex()
512                        .child(div().text_color(color::text_disabled()).child(title.clone()))
513                        .child(div().text_xs().text_color(color::text_muted()).child(why.clone()))
514                })
515                .icon(Icon::new(icon))
516                .disabled(true)
517            }
518        }
519    }
520
521    fn menu_item(&self, c: &CommandSpec, cx: &App) -> PopupMenuItem {
522        let action = Box::new(RunCommand { id: c.id.clone() });
523        match (c.enabled)(cx) {
524            Ok(()) => {
525                let (registry, id) = (self.clone(), c.id.clone());
526                let checked = c.checked.as_ref().is_some_and(|f| f(cx));
527                // The action shows the key; the handler runs the command (it wins over the action)
528                PopupMenuItem::new(c.title.clone()).icon(Icon::new(c.icon)).checked(checked).action(action).on_click(
529                    move |_, window, cx| {
530                        if let Err(e) =
531                            registry.run_as(crate::activity::Actor::Person, "menu", &id, Value::Null, window, cx)
532                        {
533                            eprintln!("{id}: {e}");
534                        }
535                    },
536                )
537            }
538            Err(why) => {
539                let title = c.title.clone();
540                PopupMenuItem::element(move |_, _| {
541                    v_flex()
542                        .child(div().text_color(color::text_disabled()).child(title.clone()))
543                        .child(div().text_xs().text_color(color::text_muted()).child(why.clone()))
544                })
545                .icon(Icon::new(c.icon))
546                .disabled(true)
547            }
548        }
549    }
550}
551
552/// A key in GPUI's notation as people read it: `secondary-shift-s` is "Ctrl+Shift+S" (and
553/// "⌘⇧S" on macOS), `f3` is "F3".
554pub fn key_label(key: &str) -> String {
555    // A sequence of keystrokes is separated by spaces
556    key.split_whitespace().map(stroke_label).collect::<Vec<_>>().join(" ")
557}
558
559fn stroke_label(stroke: &str) -> String {
560    let mac = cfg!(target_os = "macos");
561    let parts: Vec<&str> = stroke.split('-').collect();
562    // `ctrl--` (the minus key) splits into an empty last part
563    let (mods, key) = match parts.as_slice() {
564        [mods @ .., "", ""] => (mods, "-"),
565        [mods @ .., key] => (mods, *key),
566        [] => (&[][..], ""),
567    };
568    let mut out: Vec<String> = mods
569        .iter()
570        .map(|m| match (*m, mac) {
571            ("secondary" | "cmd", true) => "⌘".into(),
572            ("secondary" | "ctrl", false) => "Ctrl".into(),
573            ("ctrl", true) => "⌃".into(),
574            ("cmd", false) => "Super".into(),
575            ("shift", true) => "⇧".into(),
576            ("shift", false) => "Shift".into(),
577            ("alt", true) => "⌥".into(),
578            ("alt", false) => "Alt".into(),
579            (other, _) => other.to_string(),
580        })
581        .collect();
582    let key = match key {
583        k if k.len() == 1 => k.to_uppercase(),
584        k if k.starts_with('f') && k[1..].parse::<u8>().is_ok() => k.to_uppercase(),
585        "escape" => "Esc".into(),
586        k => {
587            let mut c = k.chars();
588            c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
589        }
590    };
591    out.push(key);
592    if mac { out.concat() } else { out.join("+") }
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598
599    #[test]
600    fn keys_read_as_people_write_them() {
601        if cfg!(target_os = "macos") {
602            assert_eq!(key_label("secondary-shift-s"), "⌘⇧S");
603        } else {
604            assert_eq!(key_label("secondary-shift-s"), "Ctrl+Shift+S");
605            assert_eq!(key_label("secondary-,"), "Ctrl+,");
606            assert_eq!(key_label("ctrl--"), "Ctrl+-");
607            assert_eq!(key_label("secondary-k secondary-s"), "Ctrl+K Ctrl+S");
608        }
609        assert_eq!(key_label("f3"), "F3");
610        assert_eq!(key_label("escape"), "Esc");
611    }
612
613    #[test]
614    fn menus_list_their_commands() {
615        let m = MenuSpec::new(
616            "File",
617            vec![
618                MenuItem::command("file.open"),
619                MenuItem::Separator,
620                MenuItem::submenu("Recent", vec![MenuItem::command("file.recent.1")]),
621            ],
622        );
623        assert_eq!(m.command_ids(), vec![SharedString::from("file.open"), SharedString::from("file.recent.1")]);
624    }
625
626    #[test]
627    fn a_registry_replaces_a_command_with_the_same_id() {
628        let r = Registry::new(vec![
629            CommandSpec::new("a", "A", IconName::Plus, |_, _| {}),
630            CommandSpec::new("b", "B", IconName::Plus, |_, _| {}),
631        ]);
632        r.add(CommandSpec::new("a", "A again", IconName::Plus, |_, _| {}));
633        assert_eq!(r.len(), 2);
634        assert_eq!(r.get("a").unwrap().title.as_ref(), "A again");
635        assert!(r.remove("b") && !r.remove("b"));
636    }
637
638    #[derive(serde::Deserialize, JsonSchema)]
639    #[allow(dead_code)]
640    struct Threshold {
641        /// The level, 0–1.
642        level: f64,
643    }
644
645    #[test]
646    fn typed_commands_publish_their_schema() {
647        let c = CommandSpec::with_args::<Threshold>("t", "Threshold", IconName::Plus, |a, _, _| {
648            Ok(serde_json::json!(a.level))
649        });
650        let schema = c.args.unwrap();
651        assert_eq!(schema["properties"]["level"]["type"], "number");
652        assert_eq!(schema["required"][0], "level");
653    }
654}