CommandSpec, Execution & Automation Patterns
1. CommandSpec Structure (crates/engine/src/commands.rs)
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement, e.g. `["Edit", "Transform"]`. Empty = not in menus.
pub menu: &'static [&'static str],
/// Default shortcut in egui-style notation (`Cmd+Shift+N`), mapped per platform by the UI.
pub shortcut: Option<&'static str>,
/// Human/agent-readable parameter description (JSON-ish).
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
/// Record in the session journal (false for queries).
pub journal: bool,
}2. Writing Informative Enabled Predicates
Instead of returning bool, Enabled returns Result<(), String> so both the egui frontend (e.g., disabled menu item hover tooltips) and AI agents (via MCP command_list) know why a command is unavailable:
fn has_active_selection(s: &Session) -> std::result::Result<(), String> {
let doc = s.active_doc().ok_or_else(|| "no open document".to_string())?;
if !doc.selection.is_empty() {
Ok(())
} else {
Err("nothing is selected".to_string())
}
}When command_list is queried, commands::list_entry exposes:
"enabled": bool"disabledReason": Option<String>"needsDocument": bool(distinguishes "open a document first" from domain preconditions like "nothing is selected")
3. Session Dispatch Lifecycle (precheck, admit, execute, edit)
When Session::execute(id, params) (or Session::start for background jobs in crates/engine/src/jobs.rs) runs:
Session::precheck(id, params): Validates that the command exists,paramsis a JSON object/null, strict parameter keys passparam_check::check, and any explicit target ID resolves to an existing entity.Session::admit(id, spec, params):- Evaluates the command's
enabledprecondition. - Rejects conflicting edits while a background job is running on the document (
job_conflict).
- Evaluates the command's
Session::edit(label, closure): Clones theArc<Document>(O(1) copy-on-write data), runs the mutation closure, computes change regions/damage (step_damage), coalesces history steps when"coalesce"matches the prior step, and bumpsDocState::revision.
4. Respecting Context Inside run
A command's run implementation should check:
- Parameter validity & strict key check: Parse and bounds-check numbers (
is_finite(), range limits) returningEngineError::BadParams. Commands listed inSTRICT(crates/engine/src/param_check.rs) automatically reject any parameter key not documented inCommandSpec::params(except universal keys like"coalesce"and"target"). - Target & Locks: Verify that the target entity is unlocked and editable before mutating.
- Coalescing Interactive
eguiEdits: Callers dragging anegui::Slider,egui::DragValue, or canvas handle pass"coalesce": "<gesture-id>"inparams;Session::executeextracts this key soSession::editmerges consecutive steps from the same drag gesture into a single undo entry.
5. Multi-Frontend Dispatch & egui Shell Interception
Because Session::execute(&mut self, id: &str, params: Value) -> Result<Value> is the single engine entry point:
- GUI (
ui-egui/src/menus.rs::invoke):- Checks
modal_allows(blocks background edits while modal dialogs or unsaved-changes prompts are open, except navigation commands). - Handles
SHELL_COMMANDS(view.zoomIn,window.toggle.*,window.workspace.*,window.theme.*) andTOOLS(tools.select.*). - Intercepts zero-arg menu invocations (e.g.,
file.neworitem.duplicatewith{}) to openeguidialogs or file pickers, then dispatches toapp.run(id, params)$\to$Session::execute.
- Checks
- Headless CLI (
apps/<app>-cli):<app>-cli commands [--json] [--filter <text>]lists and searches registered commands.<app>-cli run in.ext --cmd <id> --params '<json>' --out out.extruns without a display server.
- Headless JSON-Lines Server (
<app>-cli serve,crates/automation/src/rpc.rs): Persistent newline-delimited JSON-RPC over stdio or loopback TCP (--port <port>) without MCP framing (engine.execute,engine.commands,doc.open,doc.save,doc.inspect,batch). - TCP Control Server (
ui-egui/src/control.rs): Accepts authenticated JSON-lines requests (command.run,command.list,ui.inspect,ui.screenshot,ui.pointer,ui.key,ui.menu.invoke) to drive and visually verify a liveeguiinstance. - MCP Server (
crates/automation): WrapsSession(or bridges to a runningeguiGUI over TCP) with capability-restricted filesystem roots (cap-stdviaAuthorizedWorkspace), exposingcommand_list,command_run,command_batch, anddoc_inspect.