control: suggest near matches for unknown command ids and methods

An unknown id passed to engine.execute (or any path that ends in
EngineError::UnknownCommand) now lists up to three registered ids
close to it: typos, case, a truncated id, the same last segment in
another namespace (history.undo -> edit.undo), plus the documented
engine.commands -> command.list mapping. The headless server and the
desktop control server also say when a protocol method is sent through
engine.execute, or an engine command id is sent as a method, and
suggest near method names. Reuses the spell checker's edit distance.

Fixes #3674

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabio LussiandClaude Opus 5.5 committed 2026-10-11 22:48:57 +02:00
1 parent 56b192453e
commit c3fc37234c
7 files changed
+248 -5

No files matched your search

+21 -1
View File
@@ -67,6 +67,9 @@ impl Headless {
match method {
"engine.execute" => {
let id = str_of(&p, "command").ok_or_else(|| bad("engine.execute needs `command`"))?;
if METHODS.contains(&id) && photocraft_engine::commands::find(id).is_none() {
return Err(bad(photocraft_engine::command_hints::protocol_method_as_command(id)));
}
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true);
self.command_start(id, p.get("params").cloned().unwrap_or(Value::Null), wait)
}
@@ -135,7 +138,7 @@ impl Headless {
"doc.close" => self.close(index_of(&p)),
"batch" => self.batch(&p),
"methods" => Ok(json!(METHODS)),
other => Err(bad(format!("unknown method `{other}` (try `methods`)"))),
other => Err(bad(format!("{} (try `methods`)", photocraft_engine::command_hints::unknown_method(other, METHODS)))),
}
}
@@ -597,6 +600,23 @@ mod tests {
assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method"));
}
/// #3674: a guessed name gets a pointer to the right one, in both directions.
#[test]
fn unknown_names_suggest_the_right_method_or_command() {
let mut h = Headless::new();
let err = |h: &mut Headless, m: &str, p: Value| h.handle(m, p).unwrap_err().to_string();
let e = err(&mut h, "engine.execute", json!({"command": "engine.commands"}));
assert!(e.contains("did you mean `command.list`") && e.contains("protocol method"), "{e}");
let e = err(&mut h, "engine.execute", json!({"command": "doc.inspect"}));
assert!(e.contains("`doc.inspect` is a protocol method"), "{e}");
let e = err(&mut h, "engine.execute", json!({"command": "edit.undoo"}));
assert!(e.contains("did you mean `edit.undo`"), "{e}");
let e = err(&mut h, "doc.inspct", Value::Null);
assert!(e.contains("did you mean `doc.inspect`") && e.contains("(try `methods`)"), "{e}");
let e = err(&mut h, "edit.undo", Value::Null);
assert!(e.contains("engine.execute {\"command\": \"edit.undo\"}"), "{e}");
}
#[test]
fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() {
let mut h = Headless::new();
+4
View File
@@ -296,6 +296,10 @@ async fn errors_are_tool_errors_not_crashes() {
let r = call(&client, "command_run", json!({"id": "no.such.command"})).await;
assert_eq!(r.is_error, Some(true));
assert!(text(&r).contains("unknown command"));
// #3674: the error names the nearest registered id.
let r = call(&client, "command_run", json!({"id": "engine.commands"})).await;
assert_eq!(r.is_error, Some(true));
assert!(text(&r).contains("did you mean `command.list`"), "{}", text(&r));
let r = call(&client, "doc_inspect", json!({"index": 0})).await;
assert_eq!(r.is_error, Some(true));
let r = call(&client, "doc_open", json!({"path": "/definitely/missing.png"})).await;
+144
View File
@@ -0,0 +1,144 @@
//! "Did you mean …?" hints for unknown command ids and protocol method names (#3674), so an agent
//! that guesses a name gets something to correct from instead of re-listing the whole registry.
//! Only computed on the error path; the registry is small enough to scan.
use crate::commands;
/// Names that are documented elsewhere and can't be found by spelling alone: a protocol method
/// mistaken for the engine command that does the same thing.
const ALIASES: &[(&str, &str)] = &[("engine.commands", "command.list")];
/// At most this many suggestions per error.
const MAX_SUGGESTIONS: usize = 3;
/// Up to [`MAX_SUGGESTIONS`] `candidates` close to `name`, best first: a different case or a few
/// typos (edit distance), then names that `name` is the start of (`filter.blur.gaussian`), the
/// same last segment in another namespace (`history.undo` → `edit.undo`), and the same namespace
/// with a longer last segment (`image.size` → `image.imageSize`). Deterministic: within a tier
/// the closest spelling wins, then the name.
pub fn near_matches<'a>(name: &str, candidates: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
let lower = name.to_lowercase();
let max = (lower.chars().count() / 4).clamp(1, 4);
let dotted = lower.split_once('.');
let tail = |s: &str| s.rsplit('.').next().map(str::to_owned).unwrap_or_default();
let name_tail = tail(&lower);
let long_tail = name_tail.chars().count() >= 3;
let mut scored: Vec<(usize, usize, &'a str)> = candidates
.into_iter()
.filter(|c| *c != name)
.filter_map(|c| {
let cl = c.to_lowercase();
if let Some(d) = photocraft_text::spell::edit_distance(&lower, &cl, max) {
return Some((0, d, c));
}
let (namespace, _) = dotted?;
let cl_tail = tail(&cl);
let tier = if cl.starts_with(&lower) {
1
} else if long_tail && cl_tail == name_tail {
2
} else if long_tail && cl.split_once('.').is_some_and(|(ns, _)| ns == namespace) && cl_tail.contains(&name_tail) {
3
} else {
return None;
};
Some((tier, photocraft_text::spell::edit_distance(&lower, &cl, 64).unwrap_or(usize::MAX), c))
})
.collect();
scored.sort_unstable();
scored.dedup();
scored.into_iter().take(MAX_SUGGESTIONS).map(|(.., c)| c).collect()
}
/// `"; did you mean `a`?"` / `"; did you mean `a`, `b` or `c`?"`, or `""` for no suggestions.
pub fn did_you_mean(names: &[&str]) -> String {
let quoted: Vec<String> = names.iter().map(|n| format!("`{n}`")).collect();
match quoted.split_last() {
None => String::new(),
Some((last, [])) => format!("; did you mean {last}?"),
Some((last, rest)) => format!("; did you mean {} or {last}?", rest.join(", ")),
}
}
/// The hint appended to "unknown command `id`": registered ids close to `id`, or `""`.
pub fn unknown_command_hint(id: &str) -> String {
let mut names: Vec<&str> = ALIASES.iter().filter(|(from, _)| *from == id).map(|(_, to)| *to).collect();
for n in near_matches(id, commands::command_specs().iter().map(|s| s.id)) {
if names.len() < MAX_SUGGESTIONS && !names.contains(&n) {
names.push(n);
}
}
did_you_mean(&names)
}
/// The error for `engine.execute` given `id`, a control-protocol method rather than an engine
/// command (shared by the headless server and the desktop control server).
pub fn protocol_method_as_command(id: &str) -> String {
format!("{}; `{id}` is a protocol method: send it as the request's method, not through engine.execute", crate::EngineError::UnknownCommand(id.into()))
}
/// The error for an unknown protocol request `method`, given the server's `methods`: an engine
/// command id points at `engine.execute`, anything else gets the nearest method names.
pub fn unknown_method(method: &str, methods: &[&str]) -> String {
if commands::find(method).is_some() {
return format!("unknown method `{method}`; `{method}` is an engine command: run it with engine.execute {{\"command\": \"{method}\"}}");
}
format!("unknown method `{method}`{}", did_you_mean(&near_matches(method, methods.iter().copied())))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::{EngineError, Session};
fn unknown(id: &str) -> String {
EngineError::UnknownCommand(id.into()).to_string()
}
#[test]
fn protocol_listing_method_points_at_command_list() {
assert_eq!(unknown("engine.commands"), "unknown command `engine.commands`; did you mean `command.list`?");
let mut s = Session::new();
let e = s.execute("engine.commands", json!({})).unwrap_err().to_string();
assert!(e.contains("did you mean `command.list`"), "{e}");
assert!(s.disabled_reason("engine.commands").unwrap().contains("`command.list`"));
}
#[test]
fn near_misses_suggest_registered_ids() {
// Typo, case, and the same verb in another namespace.
assert!(unknown("edit.undoo").contains("did you mean `edit.undo`"), "{}", unknown("edit.undoo"));
assert!(unknown("Edit.Undo").contains("did you mean `edit.undo`"), "{}", unknown("Edit.Undo"));
let e = unknown("history.undo");
assert!(e.contains("did you mean `edit.undo`"), "{e}");
assert!(unknown("history.redo").contains("did you mean `edit.redo`"));
// A namespace prefix, a truncated id, a shorter last segment.
assert!(unknown("layer.new").contains("`layer.new.layer`"), "{}", unknown("layer.new"));
assert!(unknown("filter.blur.gaussian").contains("did you mean `filter.blur.gaussianBlur`"));
assert!(unknown("image.size").contains("did you mean `image.imageSize`"), "{}", unknown("image.size"));
assert!(e.len() < 200, "a few suggestions, not a listing: {e}");
// Nothing close: the plain error.
assert_eq!(unknown("zzzz.qqqq"), "unknown command `zzzz.qqqq`");
assert_eq!(unknown(""), "unknown command ``");
}
#[test]
fn suggestions_are_capped_and_ordered() {
let c = ["a.bc", "a.bd", "a.be", "a.bf", "x.y"];
assert_eq!(near_matches("a.bb", c), ["a.bc", "a.bd", "a.be"]);
assert_eq!(did_you_mean(&[]), "");
assert_eq!(did_you_mean(&["a"]), "; did you mean `a`?");
assert_eq!(did_you_mean(&["a", "b", "c"]), "; did you mean `a`, `b` or `c`?");
}
#[test]
fn protocol_method_hints() {
let methods = ["engine.execute", "doc.inspect", "doc.open", "methods"];
assert_eq!(unknown_method("doc.inspct", &methods), "unknown method `doc.inspct`; did you mean `doc.inspect`?");
assert!(unknown_method("edit.undo", &methods).contains("engine.execute {\"command\": \"edit.undo\"}"));
assert_eq!(unknown_method("zzzz", &methods), "unknown method `zzzz`");
assert!(protocol_method_as_command("doc.inspect").contains("`doc.inspect` is a protocol method"));
}
}
+4 -2
View File
@@ -25,6 +25,7 @@ mod channel_clip;
pub mod channel_cmds;
pub mod color_cmds;
pub mod color_to_alpha_cmds;
pub mod command_hints;
pub mod commands;
pub mod comps_cmds;
pub mod cutout_cmds;
@@ -133,7 +134,8 @@ pub use photocraft_paint::BrushSettings;
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("unknown command `{0}`")]
/// Displays with the nearest registered ids, if any ([`command_hints`], #3674).
#[error("unknown command `{id}`{hint}", id = .0, hint = command_hints::unknown_command_hint(.0))]
UnknownCommand(String),
#[error("command `{0}` is not available right now: {1}")]
Disabled(String, String),
@@ -556,7 +558,7 @@ impl Session {
/// [`Self::disabled_reason`] for a call with `params`.
pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option<String> {
let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) };
let Some(s) = commands::find(id) else { return Some(EngineError::UnknownCommand(id.into()).to_string()) };
self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal))
}
+9
View File
@@ -216,6 +216,13 @@ struct Rows {
cur: Vec<usize>,
}
/// Damerau–Levenshtein (optimal string alignment) distance between `a` and `b` in chars, or None
/// when above `max`. Exposed for "did you mean" hints elsewhere (engine command ids, #3674).
pub fn edit_distance(a: &str, b: &str, max: usize) -> Option<usize> {
let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
distance(&a, &b, max, &mut Rows::default())
}
/// Damerau–Levenshtein (optimal string alignment) distance, or None when above `max`.
fn distance(a: &[char], b: &[char], max: usize, rows: &mut Rows) -> Option<usize> {
let (n, m) = (a.len(), b.len());
@@ -318,5 +325,7 @@ mod tests {
assert_eq!(distance(&c("teh"), &c("the"), 2, &mut r), Some(1));
assert_eq!(distance(&c("teh"), &c("toe"), 2, &mut r), Some(2));
assert_eq!(distance(&c("teh"), &c("banana"), 2, &mut r), None);
assert_eq!(edit_distance("edit.undoo", "edit.undo", 2), Some(1));
assert_eq!(edit_distance("teh", "banana", 2), None);
}
}
+65 -1
View File
@@ -312,6 +312,38 @@ fn modifiers_from(p: &Value) -> egui::Modifiers {
/// The `dialog` id of the shell's own dialog (`workspace_ui`) in `ui.inspect` and `ui.dialog.*`.
const SHELL_DIALOG: &str = "shell";
/// The request methods [`handle`] serves, for "did you mean" hints on unknown names (#3674).
const METHODS: &[&str] = &[
"app.open",
"app.quit",
"app.save",
"engine.commands",
"engine.execute",
"jobs.cancel",
"jobs.list",
"ui.click",
"ui.context.choose",
"ui.dialog.apply",
"ui.dialog.cancel",
"ui.dialog.confirm",
"ui.dialog.open",
"ui.dialog.set",
"ui.focus",
"ui.gpu.simulateLoss",
"ui.inspect",
"ui.key",
"ui.menu.invoke",
"ui.menu.list",
"ui.move",
"ui.pointer",
"ui.resize",
"ui.screenshot",
"ui.set",
"ui.type",
"ui.window.close",
"ui.window.open",
];
pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let saved = app.session.authorize;
if let Some(gate) = app.services.automation_authorize {
@@ -346,6 +378,9 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
}
"engine.execute" | "ui.menu.invoke" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
if req.method == "engine.execute" && METHODS.contains(&id) && photocraft_engine::commands::find(id).is_none() {
return err(photocraft_engine::command_hints::protocol_method_as_command(id));
}
let params = p.get("params").cloned().unwrap_or(json!({}));
// A control-channel menu click must respect the same modal gate as the native menu.
// Camera Raw's documented `ui` requests operate its already-open dialog rather
@@ -1154,7 +1189,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
ok(Value::Null)
}
other => err(format!("unknown method `{other}`")),
other => err(photocraft_engine::command_hints::unknown_method(other, METHODS)),
}
}
@@ -1273,6 +1308,35 @@ mod tests {
}
}
/// #3674: a guessed name gets a pointer to the right one, in both directions; and every
/// method listed for those hints is served.
#[test]
fn unknown_names_suggest_the_right_method_or_command() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
let mut error = |method: &str, params: Value| {
let reply = call(&mut app, &ctx, method, params);
assert_eq!(reply["ok"], false, "{reply}");
reply["error"].as_str().unwrap_or_default().to_owned()
};
let e = error("engine.execute", json!({"command": "engine.commands"}));
assert!(e.contains("did you mean `command.list`") && e.contains("protocol method"), "{e}");
let e = error("engine.execute", json!({"command": "ui.inspect"}));
assert!(e.contains("`ui.inspect` is a protocol method"), "{e}");
let e = error("engine.execute", json!({"command": "edit.undoo"}));
assert!(e.contains("did you mean `edit.undo`"), "{e}");
let e = error("ui.inspct", json!({}));
assert!(e.contains("did you mean `ui.inspect`"), "{e}");
let e = error("edit.undo", json!({}));
assert!(e.contains("engine.execute {\"command\": \"edit.undo\"}"), "{e}");
for m in METHODS {
let (req, _rx) = ControlRequest::new(*m, json!({}));
if let Outcome::Done(v) = handle(&mut app, &ctx, &req) {
assert!(!v.to_string().contains("unknown method"), "{m} is listed but not served: {v}");
}
}
}
#[test]
fn camera_raw_control_updates_and_commits_or_cancels_an_open_raw() {
use photocraft_raw::testgen::{DngSpec, mosaic, scene};
+1 -1
View File
@@ -86,7 +86,7 @@ Change the UI language without restarting with `prefs.set`:
are documented in [UI localisation](localization.md). `prefs.get` and the existing preference
store expose and persist the same setting; scripts keep using canonical command IDs.
`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled. Examples:
`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled. An unknown command id or method name fails with up to three near matches, for example ``unknown command `engine.commands`; did you mean `command.list`?``; a protocol method sent through `engine.execute`, or an engine command id sent as a method, says which of the two it is. Examples:
| Command | Params |
|---|---|