M1.8: command palette, global keymap, UI commands

- Engine: ui.registerCommands (validated, replaces the previous set),
  UI commands in listCommands with ui: true and labelKey, running one
  through the engine emits uiCommand {id, params}.
- Frontend: ui/src/commands/ (keymap by key code, fuzzy ranking, Pinia
  commands store with handlers, recents and error toasts), the command
  palette (Mod+Shift+P), UI commands palette.open, settings.open (Mod+,,
  disabled until M1.9b) and view.toggleProjectTree (Mod+1). The editor's
  shortcuts.ts moved into the global keymap.
- Tests: engine and control-channel tests for registration and
  uiCommand, Vitest for keymap, ranking, store, palette and App wiring.
- Docs: architecture, ui-parity, target-app-parity, gaps, roadmap,
  ROADMAP, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 16:59:43 +02:00
parent 2f8fef876b
commit 184b8a3468
33 changed files with 2282 additions and 233 deletions

View file

@ -8,6 +8,7 @@ mod project;
mod recovery;
mod settings;
pub mod theme;
pub mod ui;
use crate::{EngineError, Registry};
@ -37,5 +38,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(settings::Reset))?;
registry.register(Box::new(theme::List))?;
registry.register(Box::new(theme::SystemPreference))?;
registry.register(Box::new(ui::RegisterCommands))?;
Ok(())
}

202
crates/engine/src/cmd/ui.rs Normal file
View file

@ -0,0 +1,202 @@
//! 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<String>,
/// Default shortcut in Lutra notation.
#[serde(default)]
pub default_shortcut: Option<String>,
}
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<UiCommand>,
}
/// 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<String>| 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<Outcome, EngineError> {
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<Outcome> {
if !state.ui_commands.contains_key(id) {
return None;
}
state.emit(Event::UiCommand {
id: id.to_string(),
params,
});
Some(Outcome::value(Value::Null))
}
#[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))));
}
}

View file

@ -102,6 +102,13 @@ pub struct CommandInfo {
pub params: String,
/// Whether the command can run in the current state.
pub enabled: bool,
/// Message-catalog key of the label; set for UI commands, whose `label`
/// is the same key because the engine has no English text for them.
#[serde(skip_serializing_if = "Option::is_none")]
pub label_key: Option<String>,
/// Whether the frontend registered the command (`ui.registerCommands`)
/// and runs it; running it through the engine emits `uiCommand`.
pub ui: bool,
}
impl CommandInfo {
@ -114,6 +121,8 @@ impl CommandInfo {
default_shortcut: spec.default_shortcut.map(str::to_string),
params: spec.params.to_string(),
enabled,
label_key: None,
ui: false,
}
}
}

View file

@ -66,6 +66,7 @@ impl Engine {
pub fn new() -> Result<Self, EngineError> {
let mut engine = Self::empty();
cmd::register_builtins(&mut engine.registry)?;
engine.state.engine_commands = engine.registry.ids().collect();
Ok(engine)
}
@ -82,7 +83,10 @@ impl Engine {
/// # Errors
/// Returns [`EngineError::Internal`] if the id is already taken.
pub fn register(&mut self, command: Box<dyn Command>) -> Result<(), EngineError> {
self.registry.register(command)
let id = command.spec().id;
self.registry.register(command)?;
self.state.engine_commands.insert(id);
Ok(())
}
/// Runs a command inside the guard. On success the outcome carries every
@ -97,11 +101,18 @@ impl Engine {
/// [`EngineError::UnknownCommand`] for an unknown id,
/// [`EngineError::Disabled`] if the command is disabled, the command's own
/// error, or [`EngineError::Internal`] if it panicked.
///
/// A UI command registered with `ui.registerCommands` is not run here:
/// the engine queues `uiCommand` for the frontend and returns `null`.
pub fn execute(&mut self, id: &str, params: Value) -> Result<Outcome, EngineError> {
let Self { registry, state } = self;
let command = registry
.get(id)
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
let Some(command) = registry.get(id) else {
let mut outcome = cmd::ui::dispatch(state, id, params)
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
state.commands_run = state.commands_run.saturating_add(1);
outcome.events = state.take_events();
return Ok(outcome);
};
let result = guard::run(|| {
if !command.enabled(state) {
return Err(EngineError::Disabled(id.to_string()));
@ -180,16 +191,26 @@ impl Engine {
self.state.take_events()
}
/// Describes every command with its current enabled state. A command whose
/// `enabled` check panics is listed as disabled.
/// Describes every command with its current enabled state, the
/// engine's and the registered UI commands (`ui: true`), in id order.
/// A command whose `enabled` check panics is listed as disabled.
pub fn list_commands(&self) -> Vec<CommandInfo> {
self.registry
let mut list: Vec<CommandInfo> = self
.registry
.iter()
.map(|c| {
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
CommandInfo::new(c.spec(), enabled)
})
.collect()
.chain(
self.state
.ui_commands
.values()
.map(cmd::ui::UiCommand::info),
)
.collect();
list.sort_by(|a, b| a.id.cmp(&b.id));
list
}
/// Read access to the state.
@ -359,6 +380,7 @@ mod tests {
"test.disabled",
"theme.list",
"theme.systemPreference",
"ui.registerCommands",
]
);
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();

View file

@ -129,6 +129,14 @@ pub enum Event {
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<Map<String, Value>>,
},
/// A UI command registered with `ui.registerCommands` was run through
/// the engine (control channel, later MCP); the frontend executes it.
UiCommand {
/// Command id, e.g. `palette.open`.
id: String,
/// The params the command was run with, as given.
params: Value,
},
}
/// Severity of an [`Event::Notification`].
@ -208,4 +216,16 @@ mod tests {
json!({"kind": "themeChanged", "id": "lutra-light", "dark": false, "tokens": {"--lt-bg": "#f4f1ec"}})
);
}
#[test]
fn ui_command_shape() {
let e = Event::UiCommand {
id: "palette.open".into(),
params: json!({}),
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "uiCommand", "id": "palette.open", "params": {}})
);
}
}

View file

@ -33,6 +33,11 @@ impl Registry {
self.commands.get(id).map(Box::as_ref)
}
/// The ids of every command.
pub fn ids(&self) -> impl Iterator<Item = &'static str> + '_ {
self.commands.keys().copied()
}
/// Iterates over the commands in id order.
pub fn iter(&self) -> impl Iterator<Item = &dyn Command> {
self.commands.values().map(Box::as_ref)

View file

@ -1,8 +1,11 @@
//! Workspace state that commands read and change.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Map, Value};
use crate::buffers::Buffers;
use crate::cmd::ui::UiCommand;
use crate::journal::Journal;
use crate::settings::Settings;
use crate::workspace::Workspace;
@ -28,6 +31,10 @@ pub struct State {
/// The crash-recovery journal of the open project; `None` without a
/// project or without persistence.
pub journal: Option<Journal>,
/// Ids of the engine's own commands, which UI commands may not take.
pub engine_commands: BTreeSet<&'static str>,
/// UI commands the frontend registered (`ui.registerCommands`), by id.
pub ui_commands: BTreeMap<String, UiCommand>,
/// Number of notifications emitted, for their ids.
notifications: u64,
/// Events queued for the host, oldest first.