//! UI commands: commands the frontend runs itself (open the palette, //! toggle a tool window), registered with `ui.registerCommands` so the //! palette, the keymap and agents see them next to the engine's commands. //! //! The engine only lists them. Running one through [`crate::Engine::execute`] //! (control channel, later MCP) emits [`crate::Event::UiCommand`], which the //! frontend executes; that gives agents the same reach as the keyboard. use std::collections::BTreeMap; use serde::Deserialize; use serde_json::{Value, json}; use crate::cmd::params::parse; use crate::{Command, CommandInfo, CommandSpec, EngineError, Event, Outcome, State}; /// Most UI commands one registration may hold. pub const MAX_COMMANDS: usize = 1000; /// Longest command id, in bytes. pub const MAX_ID_LEN: usize = 128; /// Longest label key, menu path or shortcut, in bytes. pub const MAX_TEXT_LEN: usize = 256; /// Params documentation of every UI command. const UI_PARAMS: &str = "any; passed to the frontend in uiCommand"; /// A command the frontend registered. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UiCommand { /// Command id, `area.action` in camelCase, e.g. `palette.open`. pub id: String, /// Message-catalog key of the label. pub label_key: String, /// Menu path with `/` separators. #[serde(default)] pub menu_path: Option, /// Default shortcut in Lutra notation. #[serde(default)] pub default_shortcut: Option, } impl UiCommand { /// Describes the command for `listCommands`; UI commands are always /// enabled as far as the engine knows. pub fn info(&self) -> CommandInfo { CommandInfo { id: self.id.clone(), label: self.label_key.clone(), menu_path: self.menu_path.clone(), default_shortcut: self.default_shortcut.clone(), params: UI_PARAMS.to_string(), enabled: true, label_key: Some(self.label_key.clone()), ui: true, } } } /// Params of `ui.registerCommands`. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct RegisterParams { /// The frontend's UI commands; they replace any registered before. commands: Vec, } /// Whether an id has the `area.action` shape: dot-separated ASCII /// alphanumeric parts, at least two of them. /// /// # Parameters /// - `id`: the id to check. fn valid_id(id: &str) -> bool { id.len() <= MAX_ID_LEN && id.split('.').count() >= 2 && id .split('.') .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric())) } /// Checks one registered command. /// /// # Parameters /// - `command`: the command. /// - `state`: for the ids of the engine's own commands. /// /// # Errors /// [`EngineError::InvalidParams`] naming the problem. fn validate(command: &UiCommand, state: &State) -> Result<(), EngineError> { if !valid_id(&command.id) { return Err(EngineError::invalid_params( REGISTER, format!("invalid command id {:?}", command.id), )); } if state.engine_commands.contains(command.id.as_str()) { return Err(EngineError::invalid_params( REGISTER, format!("{} is an engine command", command.id), )); } if command.label_key.is_empty() || command.label_key.len() > MAX_TEXT_LEN { return Err(EngineError::invalid_params( REGISTER, format!("invalid labelKey for {}", command.id), )); } let too_long = |text: &Option| text.as_ref().is_some_and(|t| t.len() > MAX_TEXT_LEN); if too_long(&command.menu_path) || too_long(&command.default_shortcut) { return Err(EngineError::invalid_params( REGISTER, format!("menuPath or defaultShortcut of {} is too long", command.id), )); } Ok(()) } /// Id of the registration command. const REGISTER: &str = "ui.registerCommands"; /// `ui.registerCommands`: the frontend lists its UI commands, once after /// `engine_ready`. A new registration replaces the previous one (a page /// reload registers again). pub struct RegisterCommands; impl Command for RegisterCommands { fn spec(&self) -> &CommandSpec { &CommandSpec { id: REGISTER, label: "Register UI Commands", menu_path: None, default_shortcut: None, params: "{ commands: [{ id, labelKey, menuPath?, defaultShortcut? }] }; replaces the UI commands registered before; returns { registered }", } } fn run(&self, state: &mut State, params: Value) -> Result { let p: RegisterParams = parse(REGISTER, params)?; if p.commands.len() > MAX_COMMANDS { return Err(EngineError::invalid_params( REGISTER, format!("more than {MAX_COMMANDS} commands"), )); } let mut commands = BTreeMap::new(); for command in p.commands { validate(&command, state)?; if commands.contains_key(&command.id) { return Err(EngineError::invalid_params( REGISTER, format!("{} is listed twice", command.id), )); } commands.insert(command.id.clone(), command); } let registered = commands.len(); state.ui_commands = commands; Ok(Outcome::value(json!({ "registered": registered }))) } } /// Runs a registered UI command: queues [`Event::UiCommand`] for the /// frontend. /// /// # Parameters /// - `state`: the state with the registered commands. /// - `id`: the command id. /// - `params`: passed on unchanged. /// /// # Returns /// `None` if no UI command has that id. pub fn dispatch(state: &mut State, id: &str, params: Value) -> Option { if !state.ui_commands.contains_key(id) { return None; } state.emit(Event::UiCommand { id: id.to_string(), params, }); Some(Outcome::value(Value::Null)) } /// The ids of the commands this module registers, checked against the /// registry by the engine's listing test. Add a new command's id here. #[cfg(test)] pub(crate) const COMMAND_IDS: &[&str] = &["ui.registerCommands"]; #[cfg(test)] mod tests { use super::valid_id; #[test] fn ids_have_the_area_action_shape() { assert!(valid_id("palette.open")); assert!(valid_id("view.toggleProjectTree")); assert!(valid_id("a.b.c1")); assert!(!valid_id("palette")); assert!(!valid_id("palette.")); assert!(!valid_id(".open")); assert!(!valid_id("a..b")); assert!(!valid_id("a.b c")); assert!(!valid_id("a.รถ")); assert!(!valid_id(&format!("a.{}", "b".repeat(200)))); } }