diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 98ccc9a24a..92ece2b943 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -86,6 +86,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) } @@ -186,7 +189,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)))), } } diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 90a5fde17b..131df72413 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -818,6 +818,23 @@ fn methods_lists_the_job_methods_and_every_listed_name_is_served() { 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(); diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index 0ac5c17a5f..e18df63c4a 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -311,6 +311,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; diff --git a/crates/engine/src/command_hints.rs b/crates/engine/src/command_hints.rs new file mode 100644 index 0000000000..6006f23257 --- /dev/null +++ b/crates/engine/src/command_hints.rs @@ -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 (`document.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) -> 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 = 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("document.undo"); + assert!(e.contains("did you mean `edit.undo`"), "{e}"); + assert!(unknown("document.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")); + } +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 635089f7a2..f879aa2319 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,8 +1,10 @@ +use crate::command_hints; use super::LayerId; #[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), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index baa596c707..b4a53a7d14 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -303,3 +303,5 @@ mod tests; #[cfg(test)] mod fx_mode_tests; + +pub mod command_hints; diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index 64a63a6850..9b9851f551 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -1,3 +1,4 @@ +use super::ScrollbarVisibility; use super::shortcuts::normalize_shortcut; use super::{ AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, DarkTheme, ExportLocation, ExportMetadata, FontPreview, diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 3e1741118c..8ea18aa4e0 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -127,7 +127,7 @@ impl Session { /// [`Self::disabled_reason`] for a call with `params`. pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - 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)) } diff --git a/crates/io/tests/it/color.rs b/crates/io/tests/it/color.rs index 44f85a7769..a9e0aa6f10 100644 --- a/crates/io/tests/it/color.rs +++ b/crates/io/tests/it/color.rs @@ -210,7 +210,7 @@ fn cmyk_merged_composite_reads_through_the_embedded_profile() { if depth == 8 { data.push(v as u8) } else { data.extend((v as u16).to_be_bytes()) } } } - f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data }; + f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data, ..Default::default() }; f.resources.push(ImageResource::new(1039, profile.to_bytes().to_vec())); let merged = merged_composite(&f).unwrap(); let mut seen_far = false; diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs index bc2afa63c8..31ddf7bf03 100644 --- a/crates/text/src/spell.rs +++ b/crates/text/src/spell.rs @@ -216,6 +216,13 @@ struct Rows { cur: Vec, } +/// 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 { + let (a, b): (Vec, Vec) = (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 { let (n, m) = (a.len(), b.len()); @@ -327,5 +334,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); } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index aed074b11e..e979d3d829 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -181,3 +181,34 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest #[cfg(test)] mod tests; + +pub(super) 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", +]; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index f775204599..b67dbef801 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -10,7 +10,7 @@ type Handler = fn(&mut PhotocraftApp, &egui::Context, &ControlRequest) -> Option pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { const HANDLERS: [Handler; 5] = [engine_methods, shell_methods, dialog_methods, input_methods, app_methods]; - HANDLERS.iter().find_map(|handler| handler(app, ctx, req)).unwrap_or_else(|| err(format!("unknown method `{}`", req.method))) + HANDLERS.iter().find_map(|handler| handler(app, ctx, req)).unwrap_or_else(|| err(photocraft_engine::command_hints::unknown_method(&req.method, METHODS))) } fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { @@ -68,6 +68,9 @@ fn context_choose(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Ou fn execute_command(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let Some(id) = str_param(p, "command").or(str_param(p, "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!({})); let wait = wait_param(p); // A control-channel menu click must respect the same modal gate as the native menu. diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index c6aa0a15e4..c52949b58f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -8,6 +8,35 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu } } +/// #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 shift_right_brush_does_not_open_presets_or_paint() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3ca1b8b0b7..c820b76bbd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -120,7 +120,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 (reply shape: [Command list replies](#command-list-replies)). Each row carries `enabled` (bool), `disabledReason` (`null` when enabled, otherwise the precondition that failed, such as `"no document open"`, `"no selection"` or `"the clipboard is empty"`) and `needsDocument` (true when the command is off because no document is open, so the first step is to create or open one; a command may still have its own precondition after that, such as an active text layer. False when enabled or off for another reason). With no document open, nearly every document command reports `enabled: false, needsDocument: true`; plan around `needsDocument` rather than reading `enabled` alone (#3664). 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 (reply shape: [Command list replies](#command-list-replies)). Each row carries `enabled` (bool), `disabledReason` (`null` when enabled, otherwise the precondition that failed, such as `"no document open"`, `"no selection"` or `"the clipboard is empty"`) and `needsDocument` (true when the command is off because no document is open, so the first step is to create or open one; a command may still have its own precondition after that, such as an active text layer. False when enabled or off for another reason). With no document open, nearly every document command reports `enabled: false, needsDocument: true`; plan around `needsDocument` rather than reading `enabled` alone (#3664). 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 | |---|---|