diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index b5cf5deb06..19158fb5fc 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -423,7 +423,7 @@ Dial action included, needs the CAD feature on (Preferences > Features, or `--ca holds them only when the feature is on at startup, as the main window makes the Design page only then, so turning it on takes a restart; with it off they are unknown commands, whose error says how a person turns it on, as `app_state`'s `cad_note` does. Turned off while OrcaSlicer runs, the tab stays until the restart, but the -Speed Dial has none of its actions. A call is refused (`-32002`) while the Design tab is busy: none runs while a +Speed Dial has none of its actions. A call is refused (`design_busy`) while the Design tab is busy: none runs while a rebuild owns the document, `change` and `sketch` commands do not run under an open feature card, the Text dialog, Constrain mode or a body Move, and a `change` one does not run under a sketch session, which `sketch` ones drive. `read` commands are refused only during a rebuild, and so are `confirm_tool` and `cancel_tool`, @@ -439,7 +439,7 @@ tab's while it is shown; `history: "design"` names the Design tab's from any tab Face and edge ids name faces and edges of the current model, and a rebuild renumbers them while a stale id still names a real face or edge, so the replies carry the model's `generation`: a call that -passes ids with the `generation` they were read at is refused (`-32010`) once the model has moved +passes ids with the `generation` they were read at is refused (`stale_ids`) once the model has moved on, rather than acting on another face or edge. The commands add features through the kernel calls the cards use, named as the cards name them, diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 564b78f57d..69d2731195 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -1837,11 +1837,14 @@ item's entry). It passes `cad_gate()` with `CadAccess::None`, whose only busy ru recipe is loaded and the call refused while the model is being rebuilt, and runs the item's handler in place (`DesignPanel::mcp_run_verb()`), as the menu item and the tab's keys do: an open card does not refuse it, since each tool decides what that means to it. Before the handler runs, `open_refusal()` refuses it in two cases -(`-32000`). An entry runs only in the mode its menu item belongs to, where the right-click menu offers it +(`wrong_mode`, `wrong_selection`). An entry runs only in the mode its menu item belongs to, where the right-click menu offers it (`offered_in_mode()`, by the menu's `sketch_map_applies()`, for which a sketch in Constrain mode is open too): a model tool such as Shell in an open sketch is refused with "This tool works on the model: finish or cancel the sketch first" (`mode: "model"`), a sketch tool outside a sketch with "This tool works in a sketch: open a -sketch first" (`mode: "sketch"`). No entry is offered in both modes, and the only keys read in both, the +sketch first" (`mode: "sketch"`); the person's message comes with a `hint` naming the commands that change the +mode: `sketch_create {plane}` and `sketch_edit {sketch}` (with their arguments, as `sketch_create {}` opens the plane +picker rather than a sketch), or `confirm_tool` and `cancel_tool`, which end a sketch or Constrain mode +alike, where the busy gate refuses `sketch_finish` and `sketch_cancel` in Constrain mode. No entry is offered in both modes, and the only keys read in both, the Ctrl+Shift ones, are no entry's handler. The tab's keys take the sketch's entries only in Sketch mode, so in Constrain mode they reach the model's while the menu offers the sketch's: there a command does what its menu item does, not what its key does. And a handler that only the right-click menu reaches (`btn:`, `fly:`), @@ -1876,18 +1879,23 @@ finds them among the commands with their input schemas, and `tool_search {tool}` `read_only`, description, input schema and examples. `tool_call {tool, args}` runs one, its arguments validated against its schema, and replies `{"result": ...}`, the tool's own reply; a replay step calls one by its name or through `tool_call`, and `orca_mcp.py`'s `call_command()` from Python. An unknown name is -answered as any unknown command is: with the closest key, or, for a Design command's name in a run started -with the CAD feature off, with how a person turns it on. +answered as any unknown command is: with the closest key (`invalid_argument`), or, for a Design command's name +in a run without the Design commands, why they are left out (`design_unavailable`): in the editor, the CAD feature +was off at startup, and how a person turns it on; in the G-code viewer, which has no Design tab whatever the +preference says, that a person opens the project in the editor (`CatalogOptions::editor`). A call runs its function on the UI thread: a person's pick in place, an automated call in one UI closure under the mutate guard, then `settle()`. Before the silent form, `cad_gate()` refuses a call by its cause, in this order. The MCP server is up before the main window, so first come `ui_plater()`'s "shutting down" and -"still starting" refusals, as for any tool. Then the G-code viewer, which has no Design tab (`-32001`); the -CAD feature off (Preferences > Features); and a Design panel that cannot be built (`-32001`: no page was made +"still starting" refusals, as for any tool. Then, each `design_unavailable`, the G-code viewer, which has no +Design tab; the CAD feature off (Preferences > Features); and a Design panel that cannot be built (no page was made at startup, the page is mid-build, or its build failed), whose message says to retry and then restart. The panel is otherwise built on the first call, since in a headless session nobody clicks the tab; -`app_state.design_tab` says whether this session has the page. Then come a busy Design tab (`-32002`), -and a `generation` that is not an unsigned integer (`-32602`) or not the model's (`-32010`). Before the +`app_state.design_tab` says whether this session has the page. Then come a busy Design tab (`design_busy`, whose +`hint` says that `confirm_tool` keeps what is open when its Confirm is on and `cancel_tool` discards it, and that a +rebuild ends by itself), and a `generation` that is not an integer of 0 or more (`invalid_argument`; +`cad_generation()` takes it stored signed too, as a script's Python integers arrive) or not the model's +(`stale_ids`). Before the generation is read, the project's recipe is loaded into an empty document (`DesignPanel::hydrate_from_model()`), as showing the tab would. @@ -1903,13 +1911,39 @@ session lets `sketch` commands through, since driving it is their point, and ref would not let the edit land there. `select_geometry` and `body_place` are `change` commands: a click in the view means something else under a card, a sketch, Constrain mode, a Move or the Text dialog. -A Design command that fails is an error (an `isError` result with `code` `-32000`, `OCCT: …` for a kernel -exception) and leaves the design as it was, so `replay_export` drops it and a replay never repeats a -call that did nothing. That holds for argument errors and for a rebuild the kernel rejects alike. +A Design command that fails is an error (an `isError` result). Its `code` is a word, as the other commands' +refusals have, that names the cause, so that an agent knows from the error alone whether to change the call or the +design: + +- `invalid_argument`: an argument is wrong in itself, names nothing, or names an object whose kind or geometry the + operation does not take (a face that is not planar, edges square to the sketch plane, a plane that misses the + body). The caller changes the arguments, or which object they name. +- `precondition`: the arguments are right, but the state of what they name, of the design or of the session is not + one the operation takes: no body yet, a body hidden or without a shape, a sketch open or none, a datum hidden, the + feature already first, a tool open, nothing to undo. The caller changes the design or the session first. +- `rebuild_failed`: a rebuild reported failure, with the call's change (taken back) or at the earlier state a call + reads (`body_describe {before}`); its message is the rebuild's reason, a kernel exception that + `CadDocument::recompute()` caught included. +- `kernel_failure`: a CAD kernel error reached the command's guard, wherever it was raised; its message starts with + `OCCT: `. +- `export_failed`: `export_step` could not transfer or write the STEP file. + +The line between the first two is between geometry and state. Geometry is what the named objects are and where +they lie, which the call chose, even where a modeling step could make it fit; state is what the Design tab tracks +apart from the geometry (whether an object exists, is shown or has a shape, a feature's place in the list, what is +open or selected), which a call cannot choose. The silent forms throw `CadPrecondition` for state, `CadKernelFailure` +where OCCT reports it could not compute, and plain exceptions for the arguments, which `run_guarded()` and +`add_feature()` tell apart; a refusal of their own (a `ToolFailure`) keeps its code, and one that names none reads as +a plain exception does. The `mcp_` entry points of `DesignPanel` that only these commands call (`mcp_select()`, +`mcp_place_body()`, `mcp_place_body_on_face()`) throw `CadPrecondition` themselves for their state refusals, as +`select_geometry` does for a body the view takes no pick on (`DesignSketchTool::body_takes_pick()`: no shape shown, +hidden, or another body the only one picked). Whatever the cause, the design is as it was, so `replay_export` drops the call and a replay never repeats +a call that did nothing. The exceptions are the silent forms whose block has `ok_false`, whose descriptions say so (`boolean`, `mirror`, `shell`, `draft`, `rib`, the surface tools, `delete_face`, `import_step`, `set_variable` and others): -they report a rejected rebuild in their reply, `{ok: false, error}`, after the same rollback, so such a call -is journaled and replays the same rejection. `extrude`, `revolve`, `sweep`, `loft`, `hole`, `thread`, `split`, +they report a rejected rebuild in their reply, `{ok: false, error}`, with no code, after the same rollback, so such +a call is journaled and replays the same rejection; their `ok: false` can mean more than that per command +(`sketch_finish` of a re-opened sketch that was not replaced). `extrude`, `revolve`, `sweep`, `loft`, `hole`, `thread`, `split`, `fillet`, `chamfer`, `thicken`, `pattern`, `align` and `sketch_draw` fail as errors, so none of them fails two ways depending on its arguments. The feature tools that fail as errors add through `add_feature()`: one checkpoint, a rebuild, and on failure `CadDocument::rollback()`, which restores the checkpoint without leaving @@ -2475,11 +2509,13 @@ sketch or switched the tab finds the actions of the app as it is then, and no lo Speed Dial's own picks run from the snapshot it was opened with. An unknown id returns up to three close ids, scored by edit distance against both the full id and its key, a key that contains the request (`delete_all` in the action id `obj_delete_all`) counting as closest, and says where to find an action or a -command (see Tool catalog); the id or key of a Design tab action that is not live says instead that the action -is there only while the Design tab is shown in its mode with the CAD feature on, and names the call that runs its -command from any tab, with a folded item's arguments (`tool_call {"tool": "sketch_pattern", "args": {"type": -"linear"}}`), or, in a run started with the feature off, that it was off then and how a person turns it on, as -`tool_call` does (`unknown_action()`). +command (see Tool catalog), with code `invalid_argument`; the id or key of a Design tab action that is not live +says instead why (`unknown_action()`): that the action is there only while the Design tab is shown in its mode +with the CAD feature on, naming the call that runs its command from any tab, with a folded item's arguments +(`tool_call {"tool": "sketch_pattern", "args": {"type": "linear"}}`), as `wrong_mode`; with the feature turned off +while the app runs, which drops every Design action though their commands stay in the catalog, that a person +enables it and restarts; and in a run without the Design commands, why they are left out, as `tool_call` does. +Those two are `design_unavailable`. A command's action takes no `args`, or exactly its own, and an action that collects a value takes that value alone (`action_args_error()`); a Design command's own action takes its command's arguments. To run a command diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index 2de7b793da..ad984970bc 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -388,15 +388,33 @@ lacks is refused in the same words by every command, which give the plates there ### How a failure shows - A call that is refused, or that fails, is an `isError` result: the English message, and a stable `code` - (`nothing_selected`, `slicing_in_progress`) where an operation refused it, with the names that help (the - closest names to an unknown one) under `similar` or `presets`. An operation refuses before it changes - anything; a command that can fail after it acted says what it left (`plugin_enable` names how the plugin - is left, `object_fix` keeps what it repaired before a cancel). + (`nothing_selected`, `slicing_in_progress`) where an operation refused it, or `invalid_argument` where its + arguments are what is wrong, by every route (`tools/call`, `tool_call`'s target, `action_run`, a script's or + plugin's `orca.host.tools`). That covers what the shared checks refuse: the schema (an unknown or misspelt name, + a wrong type, a missing one), a command, action or group name given as an argument that names none + (`tool_call`'s and `tool_search`'s `tool`, `tool_search`'s `group`, `action_run`'s `id`, a script's call), the + slicer commands' target indices and forms, `[x, y, z]` vectors and scale factors, a setting's value or key; and + what a Design command's own checks refuse. A name that is right but that this run cannot use is not + `invalid_argument`: a Design command or action left out of the run (the G-code viewer, the CAD feature off at + startup), or a Design action while the CAD feature is off, is `design_unavailable`; a Design tab action outside + the tab or mode that shows it is `wrong_mode`, and the `tool_call` its message names then says what keeps the + command from running, a Design panel that cannot be built included (`design_unavailable`). The other checks inside a slicer command's own + function carry no code (`replay_run`'s "give exactly one of path and replay", `object_transform`'s "give scale or + size, not both", the menu commands' file paths), nor does a direct `tools/call` of an unknown tool, a JSON-RPC + error, or a Python `TypeError` for arguments that are not a dict. The names that help (the closest names to an + unknown one, or every name there is) come under `similar`, `did_you_mean`, `groups` or `presets`. A refusal whose text, which a person reads too, + asks for a GUI step or a selection that a call can do instead (close a toolbar menu, deselect, select a part) + carries a `hint` with the commands that do it (`refusal_hint()`), as a Design menu item of the other mode and a + busy Design tab do; one whose step only a person takes (sign in, connect a printer) has none. An operation refuses + before it changes anything; a command that can fail after it acted says what it left (`plugin_enable` names how + the plugin is left, `object_fix` keeps what it repaired before a cancel). - A call that opens a modal dialog replies `{status: "blocked_by_dialog", job, dialogs}`, and the caller answers the dialog (`dialog_answer`), after which `app_wait {for: "job"}` returns the call's result. - A call whose work outlasts the reply budget (45 s) replies `{status: "running", job}`, and `app_wait {for: "job"}` returns its result; `job_cancel {job}` stops it. -- An unknown command is a JSON-RPC error that names the closest commands. +- A direct `tools/call` of an unknown command is a JSON-RPC error that names the closest commands; an unknown + command given as an argument (`tool_call`'s `tool`, a script's call) is an `isError` result with + `invalid_argument`, as above. - `replay_export` leaves out the calls that failed, at once or later as a job. ## When a call opens a dialog or a tool @@ -1047,8 +1065,14 @@ and a pattern's layout as `type` in the commands' words. A feature's type name ( #### How a failure shows -A command that fails is an error (`code` `-32000`) and leaves the design as it was, so `replay_export` leaves -it out. That holds for argument errors and for a rebuild the engine rejects alike. Twenty-one commands +A command that fails is an error whose `code` names the cause: `invalid_argument` (an argument is wrong, names +nothing, or names an object whose kind or geometry the operation does not take), `precondition` (the arguments are +right but the state is not: no body yet, a body hidden, no sketch open, a tool open), `rebuild_failed`, +`kernel_failure`, `export_failed`, or one of the gate's (`design_unavailable`, `design_busy`, `stale_ids`) and the +menu items' (`wrong_mode`, `wrong_selection`), and `no_silent_form` for an entry with no silent form called as one +(only by `run_cad_tool()` called directly); the server's design (mcp-server.md) draws the line between geometry and +state. It leaves the design as it was, so +`replay_export` leaves it out. That holds for argument errors and for a rebuild the engine rejects alike. Twenty-one commands instead report a rejected rebuild in their reply, `ok` false or `error` not empty, after the same rollback, so such a call is journaled and replays the same rejection: `body_transform`, `boolean`, `construct_axis`, `construct_coordinate_system`, `delete_face`, `draft`, `feature_set_expression`, `import_mesh`, diff --git a/src/slic3r/GUI/ActionRegistry.hpp b/src/slic3r/GUI/ActionRegistry.hpp index a4f99c4587..e7976a4742 100644 --- a/src/slic3r/GUI/ActionRegistry.hpp +++ b/src/slic3r/GUI/ActionRegistry.hpp @@ -42,8 +42,7 @@ struct AppActionRunResult // at its level all the same, and automation reports the run as failed. bool done = true; // For automation only: a JSON object saying what the command did that its message does not - // (the new object order, the object an Assemble made), or for a refusal what a call does instead - // in the commands' terms. An automated call's reply, or its error's details, has its fields + // (the new object order, the object an Assemble made). An automated call's reply has its fields // (NativeCommands::from_run_result()); the Speed Dial never shows it. std::string reply; // The operation's refusal that `message` words in the UI's language, when the command ran an diff --git a/src/slic3r/GUI/CAD/DesignPanel.cpp b/src/slic3r/GUI/CAD/DesignPanel.cpp index 1a09ef64ae..f6a76e74ea 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.cpp +++ b/src/slic3r/GUI/CAD/DesignPanel.cpp @@ -4994,11 +4994,12 @@ int DesignPanel::mcp_picked_plane() const { return m_plane_picked && m_ref_plane bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) { using Kind = DesignSelection::Kind; - if (m_viewport == nullptr || m_tree == nullptr || m_parts == nullptr) { why = "the Design view is not built"; return false; } + if (m_viewport == nullptr || m_tree == nullptr || m_parts == nullptr) throw Mcp::no_design_view(); const int bodies = int(m_doc.bodies.size()); DesignSketchTool& tool = m_viewport->mcp_sketch_tool(); // Everything the selecting below can refuse is tested here, by the tests it runs itself, so that a request that - // would fail there changes nothing. + // would fail there changes nothing. What the view cannot take now is the session's state, thrown as + // Mcp::CadPrecondition; what names nothing, or the wrong kind of thing, is the arguments', returned in `why`. const auto body_ok = [&] { if (s.body >= 0 && s.body < bodies) return true; why = "body " + std::to_string(s.body) + " is not a body of the model, which has " + std::to_string(bodies); @@ -5006,8 +5007,7 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) }; const auto handled = [&](bool set, const char* what) { if (set) return true; - why = std::string("the Design view takes no ") + what + " now"; - return false; + throw Mcp::CadPrecondition(std::string("the Design view takes no ") + what + " now"); }; using SolidSel = DesignSketchTool::SolidSel; const SolidSel solid = s.kind == Kind::Face ? SolidSel::Face : s.kind == Kind::Edges ? SolidSel::Edge : SolidSel::Vertex; @@ -5022,14 +5022,13 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) case Kind::Edges: case Kind::Vertex: { if (!body_ok()) return false; + // A body the view cannot take a pick on now (no shape shown, hidden, another the only one picked) is the + // session's state; can_select_solid() below checks the ids. + if (std::string state; !tool.body_takes_pick(s.body, &state)) + throw Mcp::CadPrecondition(state); if (s.kind == Kind::Vertex) { - std::vector vertices; - try { - vertices = Mcp::cad_body_vertices(m_doc, s.body); - } catch (const std::exception& e) { - why = e.what(); - return false; - } + // Its failures keep their kind (a body with no shape, a kernel error) for the call's error. + const std::vector vertices = Mcp::cad_body_vertices(m_doc, s.body); if (s.vertex < 0 || s.vertex >= int(vertices.size())) { why = "vertex " + std::to_string(s.vertex) + " is not one of body " + std::to_string(s.body) + ", which has " + std::to_string(vertices.size()); @@ -5044,11 +5043,10 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) case Kind::Plane: if (s.plane < 0 || s.plane > 2) { why = "plane is XY, XZ or YZ"; return false; } // Where update_reference_planes() puts the planes up for a click (no card is open here). - if (!m_show_origin && !m_choosing_sketch_plane) { - why = "no click can pick a plane now: one does while the Origin row shows the planes (view_set {\"tab\": " - "\"design\", \"origin\": true}) or while Sketch waits for its plane (sketch_create {})"; - return false; - } + if (!m_show_origin && !m_choosing_sketch_plane) + throw Mcp::CadPrecondition("no click can pick a plane now: one does while the Origin row shows the planes " + "(view_set {\"tab\": \"design\", \"origin\": true}) or while Sketch waits " + "for its plane (sketch_create {})"); if (!handled(bool(tool.on_datum_base_picked), "pick on a plane")) return false; break; case Kind::Loop: { @@ -5065,29 +5063,22 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) (loops.size() == 1 ? " closed loop" : " closed loops"); return false; } - if (!sketch.enabled) { - why = named + " is suppressed, so the view does not show it"; - return false; - } - if (const int by = sketch_extruded_by(s.sketch); by >= 0) { - why = named + " is not on show: " + m_doc.features[by].name + " takes it whole, so no click picks a loop of it"; - return false; - } + if (!sketch.enabled) + throw Mcp::CadPrecondition(named + " is suppressed, so the view does not show it"); + if (const int by = sketch_extruded_by(s.sketch); by >= 0) + throw Mcp::CadPrecondition(named + " is not on show: " + m_doc.features[by].name + + " takes it whole, so no click picks a loop of it"); const std::vector taken = loops_extruded_by(s.sketch); std::vector own; for (const int ei : loops[s.loop]) { - if (taken[ei] >= 0) { - why = "loop " + std::to_string(s.loop) + " of " + named + " is not on show: " + m_doc.features[taken[ei]].name + - " took it, so no click picks it"; - return false; - } + if (taken[ei] >= 0) + throw Mcp::CadPrecondition("loop " + std::to_string(s.loop) + " of " + named + " is not on show: " + + m_doc.features[taken[ei]].name + " took it, so no click picks it"); own.push_back(sketch.entities[ei]); } shown_loop = tool.display_region_of(s.sketch, own); - if (shown_loop < 0) { - why = "loop " + std::to_string(s.loop) + " of " + named + " is not on show, so no click picks it"; - return false; - } + if (shown_loop < 0) + throw Mcp::CadPrecondition("loop " + std::to_string(s.loop) + " of " + named + " is not on show, so no click picks it"); if (!handled(bool(tool.on_display_sketch_selected), "pick on a sketch")) return false; break; } @@ -5113,10 +5104,8 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why) case Kind::Face: case Kind::Edges: case Kind::Vertex: - if (!m_viewport->select_solid(solid, s.body, s.face, s.edges, vertex_pt)) { - why = "the Design view did not take the pick"; - return false; - } + if (!m_viewport->select_solid(solid, s.body, s.face, s.edges, vertex_pt)) + throw Mcp::CadPrecondition("the Design view did not take the pick"); break; case Kind::Plane: tool.on_datum_base_picked(s.plane); break; case Kind::Loop: @@ -12802,11 +12791,12 @@ bool DesignPanel::mcp_cancel_tool(std::string& was, std::string& why) bool DesignPanel::mcp_place_body(int body, const Vec3d& move, int axis, double angle_deg, std::string& why) { - if (body < 0 || body >= int(m_doc.bodies.size()) || body >= int(m_doc.display_body_meshes.size()) || - m_doc.display_body_meshes[body].empty()) { - why = "body " + std::to_string(body) + " has no shape shown to place"; + if (body < 0 || body >= int(m_doc.bodies.size())) { + why = "body " + std::to_string(body) + " is not a body of the model, which has " + std::to_string(m_doc.bodies.size()); return false; } + if (body >= int(m_doc.display_body_meshes.size()) || m_doc.display_body_meshes[body].empty()) + throw Mcp::CadPrecondition("body " + std::to_string(body) + " has no shape shown to place"); end_sketch_plane_choice(); // the body moves, as with Move; a sketch was not started sync_body_xform(); m_body_xform[body] = placed_by(m_body_xform[body], m_doc.display_body_meshes[body].bounding_box().center(), move, axis, @@ -12818,19 +12808,22 @@ bool DesignPanel::mcp_place_body(int body, const Vec3d& move, int axis, double a bool DesignPanel::mcp_place_body_on_face(int body, int face, std::string& why) { - if (body < 0 || body >= int(m_doc.bodies.size()) || body >= int(m_doc.display_body_meshes.size())) { - why = "body " + std::to_string(body) + " has no shape shown to place"; + if (body < 0 || body >= int(m_doc.bodies.size())) { + why = "body " + std::to_string(body) + " is not a body of the model, which has " + std::to_string(m_doc.bodies.size()); return false; } + if (body >= int(m_doc.display_body_meshes.size()) || m_doc.display_body_meshes[body].empty()) + throw Mcp::CadPrecondition("body " + std::to_string(body) + " has no shape shown to place"); if (GeometryEngine::face_by_index(m_doc.bodies[body].shape, face).IsNull()) { why = "face " + std::to_string(face) + " is not one of body " + std::to_string(body) + "'s " + std::to_string(GeometryEngine::face_count(m_doc.bodies[body].shape)) + " faces"; return false; } - if (!place_on_face(body, face)) { - why = "face " + std::to_string(face) + " has no normal to lay it on the bed by"; - return false; - } + // face_normal_world() gives every face a normal, so only the body's current placement can turn it into no + // direction to lay the face down by. + if (!place_on_face(body, face)) + throw Mcp::CadPrecondition("body " + std::to_string(body) + "'s placement cannot be read; body_place {body: " + + std::to_string(body) + ", reset: true} restores it"); return true; } diff --git a/src/slic3r/GUI/CAD/DesignPanel.hpp b/src/slic3r/GUI/CAD/DesignPanel.hpp index d41296818f..e6b7f992f7 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.hpp +++ b/src/slic3r/GUI/CAD/DesignPanel.hpp @@ -253,7 +253,9 @@ public: // select_geometry: select `s` as the click that selects it does, through the handlers that click runs. The whole // request is checked first, every id against the model and against what a click could pick now (a body shown, a // loop the view shows, a plane while the Origin row's planes are up or Sketch waits for its plane); one that fails - // returns false with the reason in `why` and changes nothing. Otherwise whatever is selected goes first, of every + // changes nothing: an id that names nothing, or the wrong kind of thing, returns false with the reason in `why`, + // and what the view cannot take now (a suppressed sketch, a loop not on show, no plane up for a click) throws + // Mcp::CadPrecondition, as a view not built throws Mcp::no_design_view(). Otherwise whatever is selected goes first, of every // kind (the solid and loop picks, the Feature list's and Bodies list's rows, the picked reference plane), so that // one form never leaves another's behind, and a feature's highlight is in place when this returns. For the model // at rest: cad_gate() refuses the call while a card or anything else a click would feed is open. @@ -290,10 +292,12 @@ public: // body_place: where body `body` stands for Commit to Plate and Export STEP, outside the history, as the Bodies row's // Move and Place on Face set it. Moved by `move` (world mm) and turned by `angle_deg` about world axis `axis` (0 x, // 1 y, 2 z; -1 for no turn) through its centre, added to where it stands, as the Move / Rotate card composes it. - // False, changing nothing, with the reason in `why`, for a body the model or its display does not have. + // False, changing nothing, with the reason in `why`, for a body the model does not have; throws + // Mcp::CadPrecondition, changing nothing, for one its display does not show. bool mcp_place_body(int body, const Vec3d& move, int axis, double angle_deg, std::string& why); - // Place on Face of body `body`'s face `face`; false, changing nothing, with `why` for a face the body does not have - // or one with no normal to lay it on the bed by. + // Place on Face of body `body`'s face `face`; false, changing nothing, with `why` for a body or face the model does + // not have; throws Mcp::CadPrecondition, changing nothing, for a body its display does not show or whose + // placement turns the face's normal into no direction. bool mcp_place_body_on_face(int body, int face, std::string& why); // Body `body` back where the model has it. void mcp_reset_body_placement(int body); diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.cpp b/src/slic3r/GUI/CAD/DesignSketchTool.cpp index 75a2bc8d80..b5bb9fac16 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.cpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.cpp @@ -3831,6 +3831,19 @@ void DesignSketchTool::select_body(int body) m_solid_sel = SolidSel::Whole; // the canvas fills just this body, render_solid_highlight outlines it } +bool DesignSketchTool::body_takes_pick(int body, std::string* why) const +{ + const auto refuse = [why](std::string reason) { + if (why != nullptr) *why = std::move(reason); + return false; + }; + if (body_shape(body) == nullptr) + return refuse("body " + std::to_string(body) + " has no shape in the view to pick from"); + if (!body_pickable(body)) + return refuse("body " + std::to_string(body) + " takes no click in the view: it is hidden, or another body is the only one picked"); + return true; +} + bool DesignSketchTool::can_select_solid(SolidSel kind, int body, int face, const std::vector& edges, std::string* why) const { @@ -3838,11 +3851,9 @@ bool DesignSketchTool::can_select_solid(SolidSel kind, int body, int face, const if (why != nullptr) *why = std::move(reason); return false; }; + if (!body_takes_pick(body, why)) + return false; const TopoDS_Shape* shape = body_shape(body); - if (shape == nullptr) - return refuse("body " + std::to_string(body) + " has no shape in the view to pick from"); - if (!body_pickable(body)) - return refuse("body " + std::to_string(body) + " takes no click in the view: it is hidden, or another body is the only one picked"); switch (kind) { case SolidSel::Face: { const int count = GeometryEngine::face_count(*shape); diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.hpp b/src/slic3r/GUI/CAD/DesignSketchTool.hpp index 4fc4cdbb92..5de1ce4676 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.hpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.hpp @@ -261,9 +261,13 @@ public: // as a click's pick is (body_xform_pt()). False, the selection as it was, where can_select_solid() is. bool select_solid(SolidSel kind, int body, int face, const std::vector& edges, const Vec3d& vertex_pt); + // Whether body `body` takes a pick in the view now, whatever the ids: false, with the reason in `why` when given, + // for a body with no shape in the view, or one that takes no click (hidden, or another body is the only one + // picked). It is the view's state, which select_geometry refuses apart from ids that name nothing. + bool body_takes_pick(int body, std::string* why = nullptr) const; // Whether select_solid() takes the pick: false, with the reason in `why` when given, for a body that is not - // pickable, an id its shape does not have, no edge or an edge listed twice. A caller checks a pick with it - // before it changes anything, and select_solid() runs the same tests. + // pickable (body_takes_pick()), an id its shape does not have, no edge or an edge listed twice. A caller checks a + // pick with it before it changes anything, and select_solid() runs the same tests. bool can_select_solid(SolidSel kind, int body, int face, const std::vector& edges, std::string* why = nullptr) const; // The picked vertex's point, in the view's frame (where the moved body draws it). diff --git a/src/slic3r/GUI/CommandCatalog.cpp b/src/slic3r/GUI/CommandCatalog.cpp index 4522d139b8..ba9d3a5939 100644 --- a/src/slic3r/GUI/CommandCatalog.cpp +++ b/src/slic3r/GUI/CommandCatalog.cpp @@ -35,11 +35,11 @@ void CommandCatalog::add_source(std::unique_ptr source) m_sources.push_back(std::move(source)); } -void CommandCatalog::leave_out(const std::string& key, std::string why) +void CommandCatalog::leave_out(const std::string& key, std::string why, std::string code) { if (m_sealed) throw std::logic_error("The command catalog is sealed; leaving out " + key + " comes too late"); - m_left_out[key] = std::move(why); + m_left_out[key] = {std::move(why), std::move(code)}; } void CommandCatalog::seal() { m_sealed = true; } @@ -87,7 +87,13 @@ std::vector CommandCatalog::similar(const std::string& key, std::si const std::string* CommandCatalog::left_out(const std::string& key) const { const auto it = m_left_out.find(key); - return it == m_left_out.end() ? nullptr : &it->second; + return it == m_left_out.end() ? nullptr : &it->second.why; +} + +std::string CommandCatalog::unknown_command_code(const std::string& key) const +{ + const auto it = m_left_out.find(key); + return it == m_left_out.end() ? "invalid_argument" : it->second.code; } std::string CommandCatalog::unknown_command(const std::string& key, bool suggest) const diff --git a/src/slic3r/GUI/CommandCatalog.hpp b/src/slic3r/GUI/CommandCatalog.hpp index c4b7b6224a..a32f7ecd0b 100644 --- a/src/slic3r/GUI/CommandCatalog.hpp +++ b/src/slic3r/GUI/CommandCatalog.hpp @@ -167,8 +167,9 @@ public: // added ones: lookup() finds an added command first. void add_source(std::unique_ptr source); // Before seal(); after it, throws std::logic_error. Records that this catalog leaves out `key`, a command - // a run of the app with other options holds, and `why`, which unknown_command() gives after the key. - void leave_out(const std::string& key, std::string why); + // a run of the app with other options holds, `why`, which unknown_command() gives after the key, and `code`, the + // code of an error naming it (unknown_command_code()), which says what keeps it from this run. + void leave_out(const std::string& key, std::string why, std::string code); void seal(); bool sealed() const { return m_sealed; } @@ -191,11 +192,20 @@ public: // The error for a key lookup() does not resolve: "Unknown tool: ", followed by why the catalog leaves // it out (leave_out()), or else with `suggest` by the closest key. std::string unknown_command(const std::string& key, bool suggest = false) const; + // The code of the error for a key lookup() does not resolve, given as a call's argument (tool_call's tool, + // tool_search's, a script's or plugin's call): leave_out()'s code for a key the catalog leaves out, whose name is + // right, else invalid_argument. + std::string unknown_command_code(const std::string& key) const; private: + struct LeftOut + { + std::string why; + std::string code; + }; std::vector m_commands; std::unordered_map m_index; // key -> position in m_commands - std::unordered_map m_left_out; // key -> why the catalog leaves it out + std::unordered_map m_left_out; // key -> why the catalog leaves it out, and the code std::vector> m_sources; bool m_sealed = false; }; diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index cca1664999..501bfa17f3 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -3366,7 +3366,7 @@ bool GUI_App::on_init_inner() // preference, or the command line's flag (--cad, --unrestricted-scripts). The CAD feature's is read here from the // config and the launch parameters, since is_enable_cad_feature() is in a CAD build only. const bool cad_in_force = app_config->get_bool("enable_cad_feature") || (init_params != nullptr && init_params->cad); - NativeCommands::build({is_editor() && cad_in_force}); + NativeCommands::build({is_editor() && cad_in_force, is_editor()}); Mcp::set_python_scripts_for_run(init_params != nullptr && init_params->unrestricted_scripts); Mcp::apply_python_scripts_setting(*app_config); diff --git a/src/slic3r/GUI/Mcp/McpArguments.cpp b/src/slic3r/GUI/Mcp/McpArguments.cpp index 1c6db0e6ba..a5aa634e85 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.cpp +++ b/src/slic3r/GUI/Mcp/McpArguments.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -45,8 +46,7 @@ bool type_matches(const json& value, const json& type) if (t == "number") return value.is_number(); if (t == "integer") - return value.is_number_integer() || value.is_number_unsigned() || - (value.is_number_float() && value.get() == double(int64_t(value.get()))); + return is_whole_number(value); return json_type_name(value) == t; } @@ -338,6 +338,16 @@ void normalize_arguments(const json& schema, json& args) std::string validate_arguments(const json& schema, const json& args) { return validate_value(schema, args, ""); } +bool is_whole_number(const json& v) +{ + if (v.is_number_integer()) + return true; + if (!v.is_number_float()) + return false; + const double d = v.get(); + return std::isfinite(d) && d == std::floor(d) && d >= -9223372036854775808.0 && d < 9223372036854775808.0; +} + bool person_form(const json& args) { return args.is_null() || (args.is_object() && args.empty()); } std::vector person_forms(const NativeCommand& command) diff --git a/src/slic3r/GUI/Mcp/McpArguments.hpp b/src/slic3r/GUI/Mcp/McpArguments.hpp index e68396b36e..f822d5c9d7 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.hpp +++ b/src/slic3r/GUI/Mcp/McpArguments.hpp @@ -1,11 +1,13 @@ #pragma once #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include #include #include +#include #include #include #include @@ -13,9 +15,12 @@ namespace Slic3r { namespace GUI { namespace Mcp { // For a call of tool_call ({tool, args}): replaces `command` and `args` with its target's, normalized and -// validated, so the call runs and is journaled as the target's own. Returns an error message, or "" (also -// for any other command, which it leaves as it is). -std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, nlohmann::json& args); +// validated, so the call runs and is journaled as the target's own. Returns the call's error, or nothing (also +// for any other command, which it leaves as it is): invalid_argument for a target that names no command, tool_call +// itself, or arguments the target refuses; for a target the catalog leaves out, the code it was left out with +// (CommandCatalog::unknown_command_code()). +std::optional resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, + nlohmann::json& args); // ---- arguments and name matching (McpArguments.cpp) ------------------------------------------ @@ -24,6 +29,11 @@ std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr def = m_catalog.lookup(tool); if (def == nullptr) - return ToolResult::error(m_catalog.unknown_command(tool)); + return ToolResult::error(m_catalog.unknown_command(tool), {{"code", m_catalog.unknown_command_code(tool)}}); nlohmann::json args = raw_args; if (std::string err = argument_error(*def, args); !err.empty()) - return ToolResult::error("Invalid arguments: " + err); - if (std::string err = resolve_call(m_catalog, def, args); !err.empty()) - return ToolResult::error(err); + return ToolResult::error("Invalid arguments: " + err, {{"code", "invalid_argument"}}); + if (const std::optional refused = resolve_call(m_catalog, def, args)) + return ToolResult::error(refused->what(), refused->details); return call_child(*def, args, parent_job, plugin); } diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp index afdc59934d..5a73681391 100644 --- a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -121,12 +122,13 @@ void install_plugin_tool_caller() const CommandCatalog& catalog = NativeCommands::instance(); std::shared_ptr def = catalog.lookup(tool); if (def == nullptr) - throw ToolCallError(catalog.unknown_command(tool), {{"did_you_mean", catalog.similar(tool)}}); + throw ToolCallError(catalog.unknown_command(tool), + {{"code", catalog.unknown_command_code(tool)}, {"did_you_mean", catalog.similar(tool)}}); json arguments = args; if (std::string err = argument_error(*def, arguments); !err.empty()) - throw ToolCallError("Invalid arguments: " + err, json()); - if (std::string err = resolve_call(catalog, def, arguments); !err.empty()) - throw ToolCallError(err, json()); + throw ToolCallError("Invalid arguments: " + err, json{{"code", "invalid_argument"}}); + if (const std::optional refused = resolve_call(catalog, def, arguments)) + throw ToolCallError(refused->what(), refused->details); const ToolResult r = runtime->core().call_plugin(*def, arguments, plugin); // The handlers raise no audit events, so this line is the record of what a plugin did; it is best diff --git a/src/slic3r/GUI/Mcp/McpProtocol.cpp b/src/slic3r/GUI/Mcp/McpProtocol.cpp index 4adf805560..f44d4035e7 100644 --- a/src/slic3r/GUI/Mcp/McpProtocol.cpp +++ b/src/slic3r/GUI/Mcp/McpProtocol.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -68,22 +69,22 @@ int base64_value(char c) // ---- tool_call ---------------------------------------------------------------- -std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, json& args) +std::optional resolve_call(const CommandCatalog& catalog, std::shared_ptr& command, json& args) { if (!command || command->key != "tool_call") - return {}; + return std::nullopt; const std::string target = args.value("tool", std::string()); std::shared_ptr inner = catalog.lookup(target); if (!inner) - return catalog.unknown_command(target, /*suggest=*/true); + return ToolFailure(catalog.unknown_command(target, /*suggest=*/true), {{"code", catalog.unknown_command_code(target)}}); if (inner->key == "tool_call") - return "tool_call calls another tool, not itself"; + return ToolFailure("tool_call calls another tool, not itself", {{"code", "invalid_argument"}}); json inner_args = args.contains("args") && args["args"].is_object() ? args["args"] : json::object(); if (std::string err = argument_error(*inner, inner_args); !err.empty()) - return "Invalid arguments for " + target + ": " + err; + return ToolFailure("Invalid arguments for " + target + ": " + err, {{"code", "invalid_argument"}}); command = std::move(inner); args = std::move(inner_args); - return {}; + return std::nullopt; } std::string decode_header_value(const std::string& value) @@ -170,11 +171,11 @@ json McpProtocol::call_tool(const json& params, bool& unknown_tool, std::string& } json args = params.contains("arguments") && !params["arguments"].is_null() ? params["arguments"] : json::object(); if (!args.is_object()) - return result_to_json(ToolResult::error("arguments must be an object")); + return result_to_json(ToolResult::error("arguments must be an object", {{"code", "invalid_argument"}})); if (std::string err = argument_error(*def, args); !err.empty()) - return result_to_json(ToolResult::error("Invalid arguments: " + err)); - if (std::string err = resolve_call(m_catalog, def, args); !err.empty()) - return result_to_json(ToolResult::error(err)); + return result_to_json(ToolResult::error("Invalid arguments: " + err, {{"code", "invalid_argument"}})); + if (const std::optional refused = resolve_call(m_catalog, def, args)) + return result_to_json(ToolResult::error(refused->what(), refused->details)); try { return result_to_json(m_caller.call(*def, args)); } catch (const ToolFailure& f) { @@ -210,6 +211,11 @@ PostReply McpProtocol::handle_post(const PostRequest& request) if (msg.contains("params") && !msg["params"].is_object()) return reply(200, error_body(id, kInvalidParams, "params must be an object")); const json params = msg.contains("params") ? msg["params"] : json::object(); + // The member a method reads as a string (the header check and the dispatch call value() on it, which throws for + // any other type) is refused here as a parameter error, rather than escaping as an internal one. + const char* const text_key = method == "resources/read" ? "uri" : method == "tools/call" || method == "prompts/get" ? "name" : nullptr; + if (text_key != nullptr && params.contains(text_key) && !params[text_key].is_string()) + return reply(200, error_body(id, kInvalidParams, std::string(text_key) + " must be a string")); try { if (params.contains("_meta") && params["_meta"].is_object() && params["_meta"].contains(kMetaVersion)) { diff --git a/src/slic3r/GUI/Mcp/McpTargets.cpp b/src/slic3r/GUI/Mcp/McpTargets.cpp index ddcc1ec3fc..50cff6d392 100644 --- a/src/slic3r/GUI/Mcp/McpTargets.cpp +++ b/src/slic3r/GUI/Mcp/McpTargets.cpp @@ -1,5 +1,6 @@ #include "McpTargets.hpp" +#include "McpArguments.hpp" #include "McpTools.hpp" #include "slic3r/GUI/3DScene.hpp" @@ -14,6 +15,7 @@ #include #include +#include #include #include #include @@ -46,38 +48,61 @@ std::string index_range(const char* noun, std::size_t count) return std::string(noun) + "s 0.." + std::to_string(count - 1); } -// The checks of a target's indices against the model, with the texts object_select gives. +// Index `v` among `count` things, or -1 where it is none of them. It is compared as the call gives it, so that neither +// an integer wider than an int (4294967296), nor an unsigned one past int64, nor a whole float (is_whole_number(), as +// the schema's integer type takes one) is narrowed into another index first. +std::int64_t index_among(const json& v, std::size_t count) +{ + if (v.is_number_unsigned()) + return v.get() < count ? std::int64_t(v.get()) : -1; + if (v.is_number_integer()) { + const std::int64_t i = v.get(); + return i >= 0 && std::uint64_t(i) < count ? i : -1; + } + if (!is_whole_number(v)) + return -1; + const double d = v.get(); + return d >= 0 && d < double(count) ? std::int64_t(d) : -1; +} + +// The checks of a target's indices against the model, with the texts object_select gives, each naming the index as +// the call gave it. struct IndexCheck { const Model& model; - const ModelObject& object(int index) const + // The index of the object `v` names. + int object(const json& v) const { - if (index < 0 || std::size_t(index) >= model.objects.size()) - throw ToolFailure("object index " + std::to_string(index) + " is out of range (the project has " + - index_range("object", model.objects.size()) + ")"); - return *model.objects[std::size_t(index)]; + const std::int64_t index = index_among(v, model.objects.size()); + if (index < 0) + throw ToolFailure("object index " + v.dump() + " is out of range (the project has " + + index_range("object", model.objects.size()) + ")", + {{"code", "invalid_argument"}}); + return int(index); } - // An instance, or with !instance a part, of object `owner`; the object is checked first. - void member(int owner, int index, bool instance) const + // The index of the instance, or with !instance the part, of object `owner` (checked) that `v` names. + int member(int owner, const json& v, bool instance) const { - const ModelObject& o = object(owner); + const ModelObject& o = *model.objects[std::size_t(owner)]; const std::size_t count = instance ? o.instances.size() : o.volumes.size(); - if (index < 0 || std::size_t(index) >= count) - throw ToolFailure("object " + std::to_string(owner) + " has no " + (instance ? "instance " : "part ") + std::to_string(index) + - " (it has " + index_range(instance ? "instance" : "part", count) + ")"); + const std::int64_t index = index_among(v, count); + if (index < 0) + throw ToolFailure("object " + std::to_string(owner) + " has no " + (instance ? "instance " : "part ") + v.dump() + + " (it has " + index_range(instance ? "instance" : "part", count) + ")", + {{"code", "invalid_argument"}}); + return int(index); } // [object, index] of a pair argument. std::pair pair(const json& entry, bool instance) const { - if (!entry.is_array() || entry.size() != 2 || !entry[0].is_number_integer() || !entry[1].is_number_integer()) + if (!entry.is_array() || entry.size() != 2 || !is_whole_number(entry[0]) || !is_whole_number(entry[1])) throw ToolFailure(std::string("an entry of ") + (instance ? "instances" : "parts") + " is [object, " + - (instance ? "instance" : "part") + "]"); - const std::pair out{entry[0].get(), entry[1].get()}; - member(out.first, out.second, instance); - return out; + (instance ? "instance" : "part") + "]", {{"code", "invalid_argument"}}); + const int owner = object(entry[0]); + return {owner, member(owner, entry[1], instance)}; } }; @@ -90,7 +115,7 @@ template void check_ids(const json& args, const char* list_key, return; const json& ids = args.at(ids_key); if (!ids.is_array() || ids.size() != entries) - throw ToolFailure(std::string(ids_key) + " takes one id per entry of " + list_key); + throw ToolFailure(std::string(ids_key) + " takes one id per entry of " + list_key, {{"code", "invalid_argument"}}); for (std::size_t k = 0; k < entries; ++k) expected(k, json{{id_key, ids[k]}}); } @@ -100,35 +125,33 @@ Targets named_targets(const Model& model, const json& args, unsigned kinds) using Forms = std::pair; for (const Forms& forms : {Forms{"object", "objects"}, Forms{"instance", "instances"}, Forms{"part", "parts"}}) if (args.contains(forms.first) && args.contains(forms.second)) - throw ToolFailure(std::string("Give ") + forms.first + " or " + forms.second + ", not both"); + throw ToolFailure(std::string("Give ") + forms.first + " or " + forms.second + ", not both", {{"code", "invalid_argument"}}); const IndexCheck check{model}; Targets out; // One target: the object, or an instance or a part of it. if (args.contains("object")) { - const int index = args.at("object").get(); - const ModelObject& object = check.object(index); + const int index = check.object(args.at("object")); + const ModelObject& object = *model.objects[std::size_t(index)]; check_expected_ids(object, nullptr, args); if ((kinds & kParts) && args.contains("part")) { - const int part = args.at("part").get(); - check.member(index, part, false); + const int part = check.member(index, args.at("part"), false); check_expected_ids(object, object.volumes[std::size_t(part)], args); out.parts.emplace_back(index, part); } else if ((kinds & kInstances) && args.contains("instance")) { - const int instance = args.at("instance").get(); - check.member(index, instance, true); + const int instance = check.member(index, args.at("instance"), true); out.instances.emplace_back(index, instance); } else if (kinds & kObjects) { if (args.contains("part_id")) - throw ToolFailure("part_id goes with part"); + throw ToolFailure("part_id goes with part", {{"code", "invalid_argument"}}); out.objects.push_back(index); } else { - throw ToolFailure(std::string("object names the object of a ") + (kinds & kParts ? "part: give part too" : "instance: give instance too")); + throw ToolFailure(std::string("object names the object of a ") + (kinds & kParts ? "part: give part too" : "instance: give instance too"), {{"code", "invalid_argument"}}); } } else { for (const char* key : {"instance", "part", "object_id", "part_id"}) if (args.contains(key)) - throw ToolFailure(std::string(key) + " goes with object"); + throw ToolFailure(std::string(key) + " goes with object", {{"code", "invalid_argument"}}); } // Several targets, each checked with its expected id before any is taken. @@ -138,10 +161,9 @@ Targets named_targets(const Model& model, const json& args, unsigned kinds) std::vector object_list; std::vector> instance_list, part_list; for (const json& entry : objects) { - if (!entry.is_number_integer()) - throw ToolFailure("an entry of objects is an object index"); - check.object(entry.get()); - object_list.push_back(entry.get()); + if (!is_whole_number(entry)) + throw ToolFailure("an entry of objects is an object index", {{"code", "invalid_argument"}}); + object_list.push_back(check.object(entry)); } for (const json& entry : instances) instance_list.push_back(check.pair(entry, true)); @@ -164,7 +186,7 @@ Targets named_targets(const Model& model, const json& args, unsigned kinds) for (const auto& part : part_list) add_once(out.parts, part); if (out.objects.empty() && out.instances.empty() && out.parts.empty()) - throw ToolFailure("The call names no target; give one, or none to act on the selection"); + throw ToolFailure("The call names no target; give one, or none to act on the selection", {{"code", "invalid_argument"}}); return out; } diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 82988f2d4f..a0666e6cec 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -195,11 +195,19 @@ Plater& ui_plater(); std::string no_such_plate(int plate, int count); // What a tool replies when an operation refuses: the refusal's English text, then `hint` when the tool -// has something to add for an agent, with the refusal's code as `code` and the names it carries under -// `names_key` when the tool gives one. +// has something to add for an agent, with the refusal's code as `code`, the names it carries under +// `names_key` when the tool gives one, and refusal_hint()'s as `hint`. ToolFailure refused(const Ops::Refusal& refusal, const std::string& hint = {}, const char* names_key = nullptr); -// Typed argument access with defaults; schema validation has already checked the types. +// What an agent's call does about `refusal` in the commands' terms, where the refusal's text, which a person reads too, +// asks for a GUI step or a selection that a call can do instead (close the toolbar menus, deselect, select a part); +// empty for the others, those whose step only a person takes (sign in, connect a printer) among them. Every route by +// which a refusal reaches an agent adds it to the error's details as `hint`: refused() and +// NativeCommands::from_run_result(). +std::string refusal_hint(const Ops::Refusal& refusal); + +// Typed argument access with defaults; schema validation has already checked the types. arg_int() refuses +// (ToolFailure, invalid_argument) a number that no int holds, rather than narrowing it into another value. std::string arg_string(const nlohmann::json& args, const char* key, const std::string& fallback = {}); int arg_int(const nlohmann::json& args, const char* key, int fallback); double arg_double(const nlohmann::json& args, const char* key, double fallback); @@ -236,11 +244,13 @@ std::string action_args_error(const AppAction& action, const nlohmann::json& arg // them, which takes its command's arguments and keeps the command's rewrite of them (Mcp::ActionContext). nlohmann::json action_journal_args(const AppAction& action, const nlohmann::json& args); -// What action_run answers for `id`, an action id or the name inside one, that no action of the app's state has: -// for a Design tab action's, when that action is there and the tool_call that runs it from any tab (its command, with -// the item's arguments for a folded item's action), or, when `catalog` leaves the action's command out -// (CommandCatalog::leave_out()), why; for any other, where an action or a command is found. -std::string unknown_action(const std::string& id, const CommandCatalog& catalog); +// What action_run answers for `id`, an action id or the name inside one, that no action of the app's state has, with +// a code that says why. For a Design tab action's: when `catalog` leaves the action's command out +// (CommandCatalog::leave_out()), why, with the code it was left out with; with the CAD feature off now (`cad_on` +// false), which drops every Design action, that a person enables it and restarts (design_unavailable); otherwise when +// that action is there and the tool_call that runs it from any tab (its command, with the item's arguments for a +// folded item's action), as wrong_mode. For any other, where an action or a command is found (invalid_argument). +ToolFailure unknown_action(const std::string& id, const CommandCatalog& catalog, bool cad_on); // A setting value from JSON in the serialized form set_deserialize accepts: "3", "0.2", "1"/"0" // for booleans, "a,b" for arrays. A list of strings (`key` names a coStrings option, such as diff --git a/src/slic3r/GUI/Mcp/McpToolsActions.cpp b/src/slic3r/GUI/Mcp/McpToolsActions.cpp index 7ccf1f1fb6..6dc67df9bf 100644 --- a/src/slic3r/GUI/Mcp/McpToolsActions.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsActions.cpp @@ -72,7 +72,14 @@ const AppAction& find_action(ActionRegistry& actions, std::string& id) json similar = json::array(); for (std::size_t i = 0; i < scored.size() && similar.size() < 3 && scored[i].first <= id.size() / 3 + 2; ++i) similar.push_back(scored[i].second); - throw ToolFailure(unknown_action(id, NativeCommands::instance()), {{"similar", similar}}); +#ifdef SLIC3R_CAD + const bool cad_on = wxGetApp().is_enable_cad_feature(); +#else + const bool cad_on = false; +#endif + ToolFailure refused = unknown_action(id, NativeCommands::instance(), cad_on); + refused.details["similar"] = std::move(similar); + throw refused; } } // namespace @@ -111,14 +118,20 @@ json action_journal_args(const AppAction& action, const json& args) return action.input.empty() ? action.preset : args; } -std::string unknown_action(const std::string& id, const CommandCatalog& catalog) +ToolFailure unknown_action(const std::string& id, const CommandCatalog& catalog, bool cad_on) { - // A Design tab action is in the registry only while it is live (ActionRegistry::materialize_design_actions()); its - // command is in the catalog, unless the catalog was built with the CAD feature off. + // A Design tab action is in the registry only while it is live (ActionRegistry::materialize_design_actions()), which + // none is while the CAD feature is off; its command is in the catalog, unless the catalog was built without the + // Design commands. Its id is right then, and the code says what keeps it from running. const std::string action_id = id.find(':') != std::string::npos ? id : AppAction::compose_id(kCommandPrefix, id, kOrcaSourceKey); if (is_design_action_id(action_id)) { - if (const std::string* why = catalog.left_out(short_id(action_id))) - return id + " is a Design tab action, and " + *why; + const std::string key = short_id(action_id); + if (const std::string* why = catalog.left_out(key)) + return ToolFailure(id + " is a Design tab action, and " + *why, {{"code", catalog.unknown_command_code(key)}}); + if (!cad_on) + return ToolFailure(id + " is a Design tab action, and the CAD feature is off: a person enables it in Preferences > " + "Features and restarts OrcaSlicer", + {{"code", "design_unavailable"}}); // A folded item's action is a call of the command it is folded into with the item's arguments, written as the // rest of the call is, a space after each colon and comma. const auto [command, folded] = find_command_action(catalog, short_id(action_id)); @@ -129,11 +142,13 @@ std::string unknown_action(const std::string& id, const CommandCatalog& catalog) args += (args.empty() ? "" : ", ") + json(name).dump() + ": " + value.dump(); call += ", \"args\": {" + args + "}"; } - return id + " is a Design tab action, there only while the Design tab is shown in its mode (a sketch's or the model's) " - "with the CAD feature on; tool_call " + call + "} runs its command from any tab"; + return ToolFailure(id + " is a Design tab action, there only while the Design tab is shown in its mode (a sketch's or " + "the model's) with the CAD feature on; tool_call " + call + "} runs its command from any tab", + {{"code", "wrong_mode"}}); } // The name may be a command's that has no action, which tool_call runs. - return "Unknown action id " + id + "; find an action with action_search, or a command with tool_search"; + return ToolFailure("Unknown action id " + id + "; find an action with action_search, or a command with tool_search", + {{"code", "invalid_argument"}}); } json rank_actions(const json& listed, const std::vector& words) @@ -250,7 +265,7 @@ void register_action_tools(CommandCatalog& catalog) ActionRegistry& actions = registry_or_fail(); const AppAction& action = find_action(actions, id); if (const std::string err = action_args_error(action, command_args); !err.empty()) - throw ToolFailure(err); + throw ToolFailure(err, {{"code", "invalid_argument"}}); key = action.command; action_args = action_journal_args(action, command_args); if (key.empty()) { @@ -272,7 +287,7 @@ void register_action_tools(CommandCatalog& catalog) if (command == nullptr) throw ToolFailure("Unknown command " + key); if (const std::string err = argument_error(*command, command_args); !err.empty()) - throw ToolFailure("Invalid arguments for " + key + ": " + err); + throw ToolFailure("Invalid arguments for " + key + ": " + err, {{"code", "invalid_argument"}}); ActionContext action_ctx(ctx, id, action_args); ToolResult reply = command->run(command_args, action_ctx); if (!reply.is_error && reply.data.is_object()) diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index 6fd92dc974..9d16a857d8 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -84,7 +84,7 @@ std::vector> search_inventory(const Command std::string names; for (const std::string& name : groups) names += (names.empty() ? "" : ", ") + name; - throw ToolFailure("Unknown group: " + group + "; the groups are " + names, {{"groups", groups}}); + throw ToolFailure("Unknown group: " + group + "; the groups are " + names, {{"code", "invalid_argument"}, {"groups", groups}}); } return out; } @@ -228,7 +228,8 @@ json search_commands(const CommandCatalog& catalog, const json& args) const std::string name = arg_string(args, "tool"); if (const std::shared_ptr def = catalog.lookup(name)) return describe_tool(*def); - throw ToolFailure(catalog.unknown_command(name), {{"did_you_mean", catalog.similar(name)}}); + throw ToolFailure(catalog.unknown_command(name), + {{"code", catalog.unknown_command_code(name)}, {"did_you_mean", catalog.similar(name)}}); } const std::vector> all = search_inventory(catalog, arg_string(args, "group")); const std::string query = arg_string(args, "query"); diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp index 648e2d71c7..291447dfea 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.cpp @@ -197,10 +197,25 @@ const char* const kCadOffNote = "tool_call runs no Design command now: they need "started, in Preferences > Features or with --cad. A person turns it on there if it is " "off and restarts OrcaSlicer, or starts it with --cad."; -// Why a catalog built with the CAD feature off leaves out the Design commands, after "Unknown tool: ; " -// or an action's " is a Design tab action, and " (unknown_action()). +// Why a catalog built without the Design commands leaves them out, after "Unknown tool: ; " or an action's +// " is a Design tab action, and " (unknown_action()): in the editor the CAD feature was off at startup; the +// G-code viewer has no Design tab whatever the preference says. const char* const kCadOffAtStartup = "the CAD feature was off when OrcaSlicer started: a person turns it on in " "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"; +const char* const kNoDesignInViewer = "the G-code viewer has no Design tab: a person opens the project in OrcaSlicer's editor"; +// cad_gate()'s refusal while the CAD feature is off in a run that started with it on. +const char* const kCadOffNow = "The CAD feature is off; enable it in Preferences > Features and restart OrcaSlicer"; + +// The details of a ToolFailure a silent form passes on, with invalid_argument as their code where they name no cause, +// as a plain exception a silent form throws reads (run_guarded(), add_feature()). +json with_code(json details) +{ + if (!details.is_object()) + details = json::object(); + if (!details.contains("code")) + details["code"] = "invalid_argument"; + return details; +} // What describe_design and select_geometry say is selected. The selection: what the right-click menu would be built // for, its kind (an OfferSel) and its id in the atlas, which the entries' accepts name. @@ -385,7 +400,9 @@ json plane_json(const SketchPlane& p, const Vec3d& modeling_origin) // `add` creates them and returns the index reported under `index_key`. A rebuild that fails, or an // `add` that throws, leaves the document as it was with nothing to redo, puts "Edit rejected" on // the status line as a refused GUI edit does, and fails the call with the kernel's reason, so the -// failed call can be left out of an exported replay. +// failed call can be left out of an exported replay. The error's code tells the causes apart, as +// run_guarded() does: rebuild_failed for a rebuild that reports failure, kernel_failure, precondition or +// invalid_argument, or the code of a ToolFailure `add` throws. // `slow` rebuilds as the cards do, off the UI thread behind the progress dialog (recompute_guarded), // for features whose helical pipes and skins can take seconds: the window keeps painting and // inspection calls keep answering meanwhile, while the rebuild refuses every Design call. @@ -395,20 +412,32 @@ json add_feature(DesignPanel* panel, const char* index_key, const std::function< doc.checkpoint(); int idx = -1; std::string why; + json details = {{"code", "rebuild_failed"}}; try { idx = add(); if (!(slow ? panel->recompute_guarded(_L("Rebuilding model…")) : doc.recompute())) why = doc.error.empty() ? "the model could not be rebuilt" : doc.error; - } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes first - why = std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"); + } catch (const ToolFailure& ex) { // a refusal with its own code, such as no_design_view() + why = ex.what(); + details = with_code(ex.details); + } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it + why = std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"); + details = {{"code", "kernel_failure"}}; + } catch (const CadKernelFailure& ex) { + why = std::string("OCCT: ") + ex.what(); + details = {{"code", "kernel_failure"}}; + } catch (const CadPrecondition& ex) { + why = ex.what(); + details = {{"code", "precondition"}}; } catch (const std::exception& ex) { - why = *ex.what() ? ex.what() : "the feature could not be added"; + why = *ex.what() ? ex.what() : "the feature could not be added"; + details = {{"code", "invalid_argument"}}; } if (!why.empty()) { doc.rollback(); doc.error = why; // the rollback's rebuild cleared it; the status line reads it panel->mcp_after_change(false); - throw ToolFailure(why, {{"code", -32000}}); + throw ToolFailure(why, std::move(details)); } panel->mcp_after_change(); return json{{"ok", true}, {index_key, idx}, {"bodies", int(doc.bodies.size())}}; @@ -463,7 +492,7 @@ const TopoDS_Shape& body_shape(const CadDocument& doc, const json& params) if (idx < 0 || idx >= int(doc.bodies.size())) throw std::runtime_error("body index out of range (have " + std::to_string(doc.bodies.size()) + ")"); if (doc.bodies[idx].shape.IsNull()) - throw std::runtime_error("body has no shape"); + throw CadPrecondition("body has no shape"); return doc.bodies[idx].shape; } @@ -475,7 +504,7 @@ json body_mass_properties(DesignPanel* panel, const json& params) { const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); auto mp = GeometryEngine::mass_properties(shape); - if (!mp.valid) throw std::runtime_error("mass properties could not be computed (null/empty shape)"); + if (!mp.valid) throw CadKernelFailure("mass properties could not be computed"); // A sheet body has no volume and no inertia. Report the area and say so, rather than // returning numbers a caller would reasonably treat as a material check. if (!mp.is_solid) @@ -546,7 +575,7 @@ json body_section(DesignPanel* panel, const json& params) sect.ComputePCurveOn1(false); sect.Approximation(true); sect.Build(); - if (!sect.IsDone()) throw std::runtime_error("section failed"); + if (!sect.IsDone()) throw CadKernelFailure("section failed"); std::vector> segs; for (TopExp_Explorer ex(sect.Shape(), TopAbs_EDGE); ex.More(); ex.Next()) { std::vector pts = GeometryEngine::sample_edge_world(TopoDS::Edge(ex.Current())); @@ -800,7 +829,7 @@ json action_shell(DesignPanel* panel, const json& params) if (thickness <= 0) throw std::runtime_error("thickness must be > 0"); const int face = params.value("face", -1); // face id to leave open (-1 = closed hollow) CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to shell"); + if (doc.bodies.empty()) throw CadPrecondition("no body to shell"); int bi = target_body_arg(params, doc); doc.checkpoint(); int s = doc.add_shell(thickness, face, bi, panel->mcp_feature_name(_L_CONTEXT("Shell", "Design"))); @@ -815,7 +844,7 @@ json action_rib(DesignPanel* panel, const json& params) if (!params.contains("sketch")) throw std::runtime_error("rib needs 'sketch' (feature index)"); if (!params.contains("entity")) throw std::runtime_error("rib needs 'entity' (entity index)"); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to rib"); + if (doc.bodies.empty()) throw CadPrecondition("no body to rib"); int sketch = params["sketch"].get(); int entity = params["entity"].get(); double thickness = params.value("thickness", 2.0); @@ -858,7 +887,7 @@ json action_surface_revolve(DesignPanel* panel, const json& params) json action_surface_offset(DesignPanel* panel, const json& params) { CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no sheet body to offset"); + if (doc.bodies.empty()) throw CadPrecondition("no sheet body to offset"); int bi = target_body_arg(params, doc); double offset = params.value("offset", 1.0); doc.checkpoint(); @@ -903,7 +932,7 @@ json action_draft(DesignPanel* panel, const json& params) if (!params.contains("face")) throw std::runtime_error("draft needs 'face' (id from body_describe)"); const double angle = params.value("angle", 5.0); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to draft"); + if (doc.bodies.empty()) throw CadPrecondition("no body to draft"); int bi = target_body_arg(params, doc); doc.checkpoint(); int d = doc.add_draft(angle, params["face"].get(), bi, panel->mcp_feature_name(_L("Draft"))); @@ -938,9 +967,9 @@ json action_draft(DesignPanel* panel, const json& params) DesignSketchTool& mcp_sketch(DesignPanel* panel) { DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw std::runtime_error("no viewport"); + if (vp == nullptr) throw no_design_view(); if (!vp->is_sketching()) - throw std::runtime_error("no sketch is open — call sketch_create first"); + throw CadPrecondition("no sketch is open — call sketch_create first"); return vp->mcp_sketch_tool(); } @@ -1676,7 +1705,7 @@ json action_feature_edit(DesignPanel* panel, const json& params) doc.rollback(); doc.error = why; panel->mcp_after_change(false); - throw ToolFailure(why, {{"code", -32000}}); + throw ToolFailure(why, {{"code", "rebuild_failed"}}); } panel->mcp_after_change(); return json{{"ok", true}, @@ -1730,8 +1759,8 @@ json sketch_report(const DesignSketchTool::LoopReport& rep) json action_sketch_create(DesignPanel* panel, const json& params) { DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw std::runtime_error("no viewport"); - if (vp->is_sketching()) throw std::runtime_error("a sketch is already open"); + if (vp == nullptr) throw no_design_view(); + if (vp->is_sketching()) throw CadPrecondition("a sketch is already open"); const CadDocument& doc = panel->mcp_doc(); const json pl = params.value("plane", json("XY")); const SketchPlane plane = cad_resolve_plane(pl, doc, false); @@ -1756,12 +1785,12 @@ json action_sketch_finish(DesignPanel* panel, const json& params) (void)params; DesignSketchTool& t = mcp_sketch(panel); const int edited = panel->mcp_edited_sketch(); - if (edited < 0 && t.entities().empty()) throw std::runtime_error("the sketch is empty; add entities or call sketch_cancel"); + if (edited < 0 && t.entities().empty()) throw CadPrecondition("the sketch is empty; add entities or call sketch_cancel"); const DesignPanel::SketchFinish done = panel->mcp_finish_sketch(); if (!done.committed && edited >= 0) return json{{"ok", false}, {"replaced", false}, {"sketch_index", edited}, {"error", "the sketch was not replaced: " + done.error}}; - if (!done.committed) throw std::runtime_error("the sketch was not committed"); + if (!done.committed) throw CadPrecondition("the sketch was not committed"); panel->mcp_after_change(); // Read back from the committed feature: solving its dimensions can move geometry, and extrude // takes `loop` against these entities. @@ -1777,7 +1806,8 @@ json action_sketch_cancel(DesignPanel* panel, const json& params) { (void)params; DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr || !vp->is_sketching()) throw std::runtime_error("no sketch is open"); + if (vp == nullptr) throw no_design_view(); + if (!vp->is_sketching()) throw CadPrecondition("no sketch is open"); panel->mcp_cancel_sketch(); return json{{"ok", true}}; } @@ -1788,7 +1818,11 @@ json action_sketch_edit(DesignPanel* panel, const json& params) { const json v = params.is_object() ? params.value("sketch", json()) : json(); if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_design's features[].index)"); - const int si = v.get(); + const int si = v.get(); + // The panel's own refusals of the view and an open sketch are the session's state; the others are the feature's. + const DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + if (vp->is_sketching()) throw CadPrecondition("a sketch is already open; finish or cancel it first"); std::string why; if (!panel->mcp_edit_sketch(si, why)) throw std::runtime_error(why); const DesignSketchTool& t = mcp_sketch(panel); @@ -1854,7 +1888,7 @@ json action_sketch_describe(DesignPanel* panel, const json& params) const json sketch = params.is_object() ? params.value("sketch", json()) : json(); if (!sketch.is_null()) { const DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw std::runtime_error("no viewport"); + if (vp == nullptr) throw no_design_view(); const CadDocument& doc = panel->mcp_doc(); return cad_sketch_describe(doc, vp->mcp_sketch_tool(), sketch_arg(sketch, doc)); } @@ -1924,7 +1958,7 @@ json action_sketch_set_value(DesignPanel* panel, const json& params) const double value = params["value"].get(); const DesignSketchTool::DimType kind = t.dimension_kind(); if (kind == DesignSketchTool::DimType::None) - throw std::runtime_error("the selection has no value to set — pick a line, an arc, a circle, or two entities"); + throw CadPrecondition("the selection has no value to set — pick a line, an arc, a circle, or two entities"); const char* kind_name = "none"; switch (kind) { @@ -1978,7 +2012,7 @@ json action_sketch_set_value(DesignPanel* panel, const json& params) void check_has_body(BooleanMode mode, const CadDocument& doc) { if (mode != BooleanMode::New && doc.bodies.empty()) - throw std::runtime_error("operation " + std::string(kOperations[int(mode)]) + " needs a body; add or import one first"); + throw CadPrecondition("operation " + std::string(kOperations[int(mode)]) + " needs a body; add or import one first"); } double distance_arg(const json& params) @@ -2122,7 +2156,7 @@ json action_extrude(DesignPanel* panel, const json& params) } if (!sketch.is_null()) { const DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw std::runtime_error("no viewport"); + if (vp == nullptr) throw no_design_view(); const auto add = cad_sketch_extrude(doc, vp->mcp_sketch_tool(), params); json r; try { @@ -2130,8 +2164,9 @@ json action_extrude(DesignPanel* panel, const json& params) [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); }); } catch (const ToolFailure& e) { // A whole sketch builds one region, with the loops inside it as holes. When the rebuild - // refused a sketch of several, name the way to take one. - if (!loop.is_null() || separate_regions(vp->mcp_sketch_tool(), doc.features[sketch.get()].entities) < 2) + // refused a sketch of several, name the way to take one; any other failure has another cause. + if (!loop.is_null() || e.details.value("code", std::string()) != "rebuild_failed" || + separate_regions(vp->mcp_sketch_tool(), doc.features[sketch.get()].entities) < 2) throw; throw ToolFailure(std::string(e.what()) + "; pass \"loop\" to extrude one of its regions (closed_loops of sketch_describe {sketch})", @@ -2214,7 +2249,7 @@ json action_mirror(DesignPanel* panel, const json& params) { const BooleanMode m = *operation_arg(params, "new_body", kMirrorOperations); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to mirror"); + if (doc.bodies.empty()) throw CadPrecondition("no body to mirror"); int bi = target_body_arg(params, doc); bool keep = params.value("keep_original", true); const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XZ")), doc, false); @@ -2231,7 +2266,7 @@ json action_mirror(DesignPanel* panel, const json& params) json action_transform(DesignPanel* panel, const json& params) { CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to transform"); + if (doc.bodies.empty()) throw CadPrecondition("no body to transform"); int bi = target_body_arg(params, doc); Vec3d translate(params.value("dx", 0.0), params.value("dy", 0.0), params.value("dz", 0.0)); Vec3d axis(params.value("axis_x", 0.0), params.value("axis_y", 0.0), params.value("axis_z", 1.0)); @@ -2286,7 +2321,7 @@ json action_sketch_project(DesignPanel* panel, const json& params) return r; } CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no source body to project from"); + if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); int source_body = params.value("source_body", -1); int face = params.value("face", -1); std::vector edges; @@ -2307,7 +2342,7 @@ json action_delete_face(DesignPanel* panel, const json& params) { if (!params.contains("faces")) throw std::runtime_error("delete_face needs 'faces' (array of face ids)"); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to delete faces from"); + if (doc.bodies.empty()) throw CadPrecondition("no body to delete faces from"); int bi = target_body_arg(params, doc); std::vector faces; if (params["faces"].is_array()) @@ -2562,8 +2597,8 @@ json undo_redo(DesignPanel* panel, bool redo) DesignCanvas* vp = panel->mcp_viewport(); const bool sketch = vp != nullptr && vp->is_sketching(); if (!panel->menu_can_undo_redo(redo)) { - if (sketch) throw std::runtime_error(redo ? "Nothing to redo in the open sketch" : "Nothing to undo in the open sketch"); - throw std::runtime_error(redo ? "Nothing to redo in the Design history (history \"project\" redoes the project's)" + if (sketch) throw CadPrecondition(redo ? "Nothing to redo in the open sketch" : "Nothing to undo in the open sketch"); + throw CadPrecondition(redo ? "Nothing to redo in the Design history (history \"project\" redoes the project's)" : "Nothing to undo in the Design history (history \"project\" undoes the project's)"); } panel->menu_undo_redo(redo); @@ -2582,7 +2617,7 @@ json undo_redo(DesignPanel* panel, bool redo) // kernel refuses one; the call then fails with the kernel's reason. [[noreturn]] void tree_edit_refused(const CadDocument& doc) { - throw ToolFailure(doc.error.empty() ? "the Design tab refused the edit" : doc.error, {{"code", -32000}}); + throw ToolFailure(doc.error.empty() ? "the Design tab refused the edit" : doc.error, {{"code", "rebuild_failed"}}); } json tree_edit_reply(const CadDocument& doc, json reply) @@ -2642,7 +2677,7 @@ json action_feature_move(DesignPanel* panel, const json& params) throw std::runtime_error("delta must be -1 (up) or 1 (down)"); const int to = fi + delta.get(); if (to < 0 || to >= int(doc.features.size())) - throw std::runtime_error("feature " + std::to_string(fi) + " is already " + (to < 0 ? "first" : "last")); + throw CadPrecondition("feature " + std::to_string(fi) + " is already " + (to < 0 ? "first" : "last")); if (!panel->move_feature(fi, delta.get())) tree_edit_refused(doc); return tree_edit_reply(doc, {{"feature", to}, {"from", fi}}); } @@ -2711,7 +2746,7 @@ json action_body_delete(DesignPanel* panel, const json& params) const int b = body_arg(params, doc); const int src = doc.bodies[b].source_feature; if (src < 0 || src >= int(doc.features.size())) - throw std::runtime_error("body " + std::to_string(b) + " has no feature to delete; use new_design to start over"); + throw CadPrecondition("body " + std::to_string(b) + " has no feature to delete; use new_design to start over"); const json deleted{{"index", src}, {"type", feature_type_name(doc.features[src].type)}, {"name", doc.features[src].name}}; const size_t before = doc.features.size(); if (!panel->delete_body(b)) tree_edit_refused(doc); @@ -2779,24 +2814,24 @@ json action_commit_to_plate(DesignPanel* panel, const json& params) Plater* plater = wxGetApp().plater(); ObjectList* obj_list = wxGetApp().obj_list(); - if (plater == nullptr || obj_list == nullptr) throw std::runtime_error("Prepare is not ready"); + if (plater == nullptr || obj_list == nullptr) throw CadPrecondition("Prepare is not ready"); Model& model = plater->model(); const std::vector replace = cad_commit_to_plate_replace(params.value("replace", json::array()), model); // The Delete key does not pull an object from under an open gizmo either. if (!replace.empty()) for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_assmeble_canvas3D()}) if (canvas != nullptr && canvas->get_gizmos_manager().get_current_type() != GLGizmosManager::Undefined) - throw std::runtime_error("close the " + Mcp::gizmo_name(canvas->get_gizmos_manager().get_current_type()) + + throw CadPrecondition("close the " + Mcp::gizmo_name(canvas->get_gizmos_manager().get_current_type()) + " gizmo first: replace deletes objects"); // commit_to_plate()'s own refusals, checked first so a refused call leaves no undo step. const CadDocument& doc = panel->mcp_doc(); if (doc.display_mesh.its.indices.empty()) - throw std::runtime_error("Nothing to commit: the design has no body; add a feature first"); + throw CadPrecondition("Nothing to commit: the design has no body; add a feature first"); bool any_shown = doc.display_body_meshes.size() <= 1; // a lone body is sent even when hidden for (size_t b = 0; !any_shown && b < doc.display_body_meshes.size(); ++b) any_shown = panel->mcp_body_shown(int(b)) && !doc.display_body_meshes[b].its.indices.empty(); - if (!any_shown) throw std::runtime_error("Every body is hidden; show one first with body_set {body, visible: true}"); + if (!any_shown) throw CadPrecondition("Every body is hidden; show one first with body_set {body, visible: true}"); json replaced = json::array(); for (int i : replace) replaced.push_back(json{{"index", i}, {"name", model.objects[i]->name}}); @@ -2807,7 +2842,7 @@ json action_commit_to_plate(DesignPanel* panel, const json& params) std::optional snapshot; if (!replace.empty()) snapshot.emplace(plater, _u8L("Commit to Plate")); for (size_t i : panel->commit_to_plate(mode, &sent)) made.push_back(model.objects[i]); - if (made.empty()) throw std::runtime_error("Commit to Plate sent nothing"); + if (made.empty()) throw CadPrecondition("Commit to Plate sent nothing"); std::vector items; for (int i : replace) items.emplace_back(itObject, i, -1); obj_list->delete_from_model_and_list(items); @@ -2846,7 +2881,7 @@ json action_new_design(DesignPanel* panel, const json& params) json action_export_step(DesignPanel* panel, const json& params) { const CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("Nothing to export: the design has no body; add a feature first"); + if (doc.bodies.empty()) throw CadPrecondition("Nothing to export: the design has no body; add a feature first"); const json path_arg = params.value("path", json()); const json overwrite = params.value("overwrite", json(false)); if (!path_arg.is_string()) throw std::runtime_error("export_step needs 'path', an absolute file path"); @@ -2855,7 +2890,7 @@ json action_export_step(DesignPanel* panel, const json& params) const auto path = Mcp::resolve_output_path(path_arg.get(), overwrite.get(), err); if (!path) throw std::runtime_error(err); const std::string path_utf8 = Mcp::path_to_utf8(*path); - if (!panel->export_step_to(path_utf8, err)) throw std::runtime_error("STEP export failed: " + err); + if (!panel->export_step_to(path_utf8, err)) throw ToolFailure("STEP export failed: " + err, {{"code", "export_failed"}}); boost::system::error_code ec; const auto bytes = boost::filesystem::file_size(*path, ec); @@ -2911,8 +2946,8 @@ std::vector entity_picks(const json& params, const DesignSketchTool& t) // would; the person finishes or drops those first. void check_sketch_idle(const DesignSketchTool& t) { - if (t.value_field_open()) throw std::runtime_error("a value field is open in the sketch; commit or cancel it (Enter or Esc) first"); - if (t.gesture_pending()) throw std::runtime_error("the armed sketch tool has a gesture in progress; finish it or press Esc first"); + if (t.value_field_open()) throw CadPrecondition("a value field is open in the sketch; commit or cancel it (Enter or Esc) first"); + if (t.gesture_pending()) throw CadPrecondition("the armed sketch tool has a gesture in progress; finish it or press Esc first"); } // How many of `cons` reference entity `e`. @@ -3217,7 +3252,7 @@ json sketch_draw(DesignSketchTool& t, const json& params) if (it.from >= int(ents.size())) throw std::runtime_error("arc_tangent entity " + std::to_string(it.from) + " does not exist; the sketch has " + std::to_string(ents.size()) + " entities with the items before it"); - if (ents.empty()) throw std::runtime_error("arc_tangent needs a line or an arc to leave, and the sketch has none"); + if (ents.empty()) throw CadPrecondition("arc_tangent needs a line or an arc to leave, and the sketch has none"); const int from = it.from >= 0 ? it.from : int(ents.size()) - 1; if (ents[from].type != SketchEntity::Type::Line && ents[from].type != SketchEntity::Type::Arc) throw std::runtime_error("arc_tangent leaves a line or an arc, and " + entity_label(ents, from) + " is neither"); @@ -3306,7 +3341,7 @@ json sketch_offset(DesignSketchTool& t, const json& params) const std::vector sources = copy_sources(params, t, listed); std::vector src; for (int i : sources) src.push_back(t.entities()[i]); - if (src.empty()) throw std::runtime_error("nothing to offset"); + if (src.empty()) throw CadPrecondition("nothing to offset"); const auto out = SketchEngine::offset_entities(src, d); if (out.empty()) throw std::runtime_error("offset produced nothing (ellipses and splines are not offset)"); const int base = int(t.entities().size()); @@ -3332,7 +3367,7 @@ json sketch_mirror(DesignSketchTool& t, const json& params) if (axis_v.is_null()) { const Vec2d a = params.contains("axis_a") ? point_arg(params, "axis_a") : Vec2d(0, 0); const Vec2d b = params.contains("axis_b") ? point_arg(params, "axis_b") : Vec2d(0, 1); - if (targets.empty()) throw std::runtime_error("nothing to mirror"); + if (targets.empty()) throw CadPrecondition("nothing to mirror"); std::vector src; for (int i : targets) src.push_back(ents[i]); const auto out = SketchEngine::mirror_entities(src, a, b); @@ -3359,7 +3394,7 @@ json sketch_mirror(DesignSketchTool& t, const json& params) if (listed) throw std::runtime_error("entity " + std::to_string(axis) + " is the axis; it is not mirrored about itself"); targets.erase(it); } - if (targets.empty()) throw std::runtime_error("nothing to mirror"); + if (targets.empty()) throw CadPrecondition("nothing to mirror"); check_sketch_idle(t); const int base = int(ents.size()); std::vector kept; @@ -3854,7 +3889,7 @@ json action_confirm_tool(DesignPanel* panel, const json&) { DesignPanel::ConfirmOutcome out; std::string why; - if (!panel->mcp_confirm_tool(out, why)) throw std::runtime_error(why); + if (!panel->mcp_confirm_tool(out, why)) throw CadPrecondition(why); return json{{"was", out.was}, {"ok", out.ok}, {"feature", out.feature >= 0 ? json(out.feature) : json()}, @@ -3866,7 +3901,7 @@ json action_confirm_tool(DesignPanel* panel, const json&) json action_cancel_tool(DesignPanel* panel, const json&) { std::string was, why; - if (!panel->mcp_cancel_tool(was, why)) throw std::runtime_error(why); + if (!panel->mcp_cancel_tool(was, why)) throw CadPrecondition(why); return json{{"was", was}, {"status", into_u8(panel->mcp_status())}}; } @@ -3963,6 +3998,65 @@ const std::pair kSilentForms[] = { }; const std::size_t kSilentFormCount = std::size(kSilentForms); +json run_guarded(const std::function& run) +{ + try { + return run(); + } catch (const ToolFailure& ex) { + // Its own refusal, code included; one that names no cause is read as a plain exception is. + if (ex.details.is_object() && ex.details.contains("code")) + throw; + throw ToolFailure(ex.what(), with_code(ex.details)); + } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it + throw ToolFailure(std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"), {{"code", "kernel_failure"}}); + } catch (const CadKernelFailure& ex) { + throw ToolFailure(std::string("OCCT: ") + ex.what(), {{"code", "kernel_failure"}}); + } catch (const CadPrecondition& ex) { + throw ToolFailure(ex.what(), {{"code", "precondition"}}); + } catch (const std::exception& ex) { + throw ToolFailure(ex.what(), {{"code", "invalid_argument"}}); + } +} + +ToolFailure no_design_tab() +{ + if (!wxGetApp().is_editor()) + return ToolFailure("The G-code viewer has no Design tab", {{"code", "design_unavailable"}}); + if (!wxGetApp().is_enable_cad_feature()) + return ToolFailure(kCadOffNow, {{"code", "design_unavailable"}}); + return ToolFailure("The Design tab isn't available in this window yet; retry, and if it stays unavailable restart " + "OrcaSlicer (turning the CAD feature on takes effect after a restart)", + {{"code", "design_unavailable"}}); +} + +ToolFailure no_design_view() +{ + return ToolFailure("The Design view is not built in this window; restart OrcaSlicer if it stays so", + {{"code", "design_unavailable"}}); +} + +ToolFailure design_busy(const std::string& why) +{ + return ToolFailure("Design tab busy: " + why, + {{"code", "design_busy"}, + {"hint", "confirm_tool keeps what is open when its Confirm is on (a card, the Text dialog, a body Move, " + "a sketch, Constrain mode) and cancel_tool discards it; a rebuild ends by itself, so call " + "again after it"}}); +} + +std::optional cad_generation(const json& args) +{ + if (!args.is_object() || !args.contains("generation")) + return std::nullopt; + // The numbers the schema's integer type takes (is_whole_number(): a whole float within int64 among them), not + // negative. + const json& g = args["generation"]; + if (!is_whole_number(g) || (!g.is_number_unsigned() && g.get() < 0)) + throw ToolFailure("generation must be an integer of 0 or more, as describe_design or body_describe gave it", + {{"code", "invalid_argument"}}); + return g.is_number_float() ? std::uint64_t(g.get()) : g.get(); +} + namespace { // The silent form of entry `id`, or nullptr. @@ -3973,21 +4067,6 @@ CadRun find_silent_form(const std::string& id) return nullptr; } -// Runs `run`, a silent form or undo and redo, with its failure as the call's error: its own refusal with its code, -// a kernel exception as "OCCT: ...", and any other as -32000. -json run_guarded(const std::function& run) -{ - try { - return run(); - } catch (const ToolFailure&) { - throw; // its own refusal, code included - } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes first - throw ToolFailure(std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"), {{"code", -32000}}); - } catch (const std::exception& ex) { - throw ToolFailure(ex.what(), {{"code", -32000}}); - } -} - // Why a menu-only entry (a btn: or fly: handler) is refused for a selection it does not accept. // TRN Refusal of a Design tab tool picked for a selection its right-click menu item is greyed for (Constrain // sketch with a face selected). @@ -4178,9 +4257,17 @@ std::vector design_actions(const CommandCatalog& catalog, bool ske std::optional open_refusal(const DesignTool& t, bool sketching, int kind, bool row_target) { + // The message is the person's; the hint names the commands that change the mode. if (!offered_in_mode(t, sketching)) return ToolFailure(t.sketch_mode ? kSketchTool : kModelTool, - {{"code", -32000}, {"mode", t.sketch_mode ? "sketch" : "model"}}); + {{"code", "wrong_mode"}, + {"mode", t.sketch_mode ? "sketch" : "model"}, + // A model tool's: Constrain mode is a sketch to the menu, and the busy gate refuses + // sketch_finish and sketch_cancel there, so the hint names the two that end either. + {"hint", t.sketch_mode ? "sketch_create {plane: \"XY\"} opens a sketch on a plane, sketch_edit " + "{sketch: i} a committed one" : + "confirm_tool keeps the open sketch, or ends Constrain mode, and " + "cancel_tool drops the sketch or leaves Constrain mode"}}); // The item's handler acts on the Feature list's selected row, and says itself what it cannot do with it. if (row_target && t.feature_row) return std::nullopt; @@ -4198,7 +4285,7 @@ std::optional open_refusal(const DesignTool& t, bool sketching, int for (int sel = 0; sel < int(OfferSel::Count); ++sel) if ((t.accepts & offer_bit(OfferSel(sel))) != 0) accepts.push_back(kDesignSelectionIds[sel]); - return ToolFailure(kDoesNotApply, {{"code", -32000}, + return ToolFailure(kDoesNotApply, {{"code", "wrong_selection"}, {"selection_kind", kind}, {"selection", kDesignSelectionIds[kind]}, {"accepts", std::move(accepts)}}); @@ -4208,18 +4295,14 @@ DesignPanel* cad_gate(CadAccess access, const json& args) { // The MCP server answers before the main window exists and while the app closes. ui_plater(); - if (!wxGetApp().is_editor()) - throw ToolFailure("The G-code viewer has no Design tab", {{"code", -32001}}); - if (!wxGetApp().is_enable_cad_feature()) - throw ToolFailure("The CAD feature is off; enable it in Preferences > Features and restart OrcaSlicer"); + if (!wxGetApp().is_editor() || !wxGetApp().is_enable_cad_feature()) + throw no_design_tab(); // The panel is built on first use, and in a headless session nobody clicks the tab that would // build it, so it is built here rather than refused. It is null when no page was made at startup // (the CAD feature was turned on later), while the page is mid-build, and after its build failed. DesignPanel* panel = DesignPanel::ensure(); if (panel == nullptr) - throw ToolFailure("The Design tab isn't available in this window yet; retry, and if it stays unavailable restart " - "OrcaSlicer (turning the CAD feature on takes effect after a restart)", - {{"code", -32001}}); + throw no_design_tab(); // Only Read commands, the opening of a tool and the Ui commands, which act on what is open, may run under a GUI // editor or a sketch session they do not own. None may run during a rebuild, not even these: the rebuild's busy @@ -4227,7 +4310,7 @@ DesignPanel* cad_gate(CadAccess access, const json& args) std::string why; const bool under_open = access == CadAccess::Read || access == CadAccess::None || access == CadAccess::Ui; if (panel->mcp_busy(under_open, access == CadAccess::Sketch, why)) - throw ToolFailure("Design tab busy: " + why, {{"code", -32002}}); + throw design_busy(why); // A project opened without ever showing the Design tab has its recipe only in the Model; // load it, as showing the tab would, before anything reads or writes the document. @@ -4248,20 +4331,18 @@ DesignPanel* cad_gate(CadAccess access, const json& args) // is not checked, and supplying it is what buys the guarantee. One check here rather than one // per command, so a command added later cannot forget it. // - // The type is checked first, as a caller that skips the schema (run_cad_tool() called directly) may - // pass any: a bare get() on `"generation": "x"` would surface as an internal error instead - // of a parameter error. - if (args.is_object() && args.contains("generation")) { - if (!args["generation"].is_number_unsigned()) - throw ToolFailure("generation must be an unsigned integer", {{"code", -32602}}); - const uint64_t want = args["generation"].get(); + // The type is checked first (cad_generation()), as a caller that skips the schema (run_cad_tool() called + // directly) may pass any: a bare get() on `"generation": "x"` would surface as an internal error + // instead of a parameter error. + if (const std::optional given = cad_generation(args)) { + const uint64_t want = *given; const uint64_t have = panel->mcp_doc().topo_generation; if (want != have) throw ToolFailure("stale face/edge ids: they were read at generation " + std::to_string(want) + " but the model is now at " + std::to_string(have) + ". Re-read body_describe and use the new ids — the old ones still name real " "edges, just not the ones you measured.", - {{"code", -32010}}); + {{"code", "stale_ids"}}); } return panel; } @@ -4271,7 +4352,7 @@ json run_cad_tool(const std::string& id, const json& args) const DesignTool* entry = find_design_tool(id); const CadRun run = find_silent_form(id); if (entry == nullptr || run == nullptr) - throw ToolFailure("No Design command runs silently as " + id, {{"code", -32601}}); + throw ToolFailure("No Design command runs silently as " + id, {{"code", "no_silent_form"}}); DesignPanel* panel = cad_gate(entry->access, args); return run_guarded([&] { return run(panel, args); }); } @@ -4370,12 +4451,12 @@ void register_cad_commands(CommandCatalog& catalog) catalog.add(design_command(t)); } -void leave_out_cad_commands(CommandCatalog& catalog) +void leave_out_cad_commands(CommandCatalog& catalog, bool editor) { // A folded item's id too, which is no command but names an action. for (const DesignTool& t : kDesignTools) if (t.action != nullptr || t.doc != nullptr) - catalog.leave_out(t.id, kCadOffAtStartup); + catalog.leave_out(t.id, editor ? kCadOffAtStartup : kNoDesignInViewer, "design_unavailable"); } std::vector sketch_target_indices(const json& params, const std::vector& selection, int entity_count, bool all_if_empty) @@ -4447,11 +4528,11 @@ SketchPlane cad_resolve_plane(const json& plane, const CadDocument& doc, bool dr throw std::runtime_error("feature " + std::to_string(fi) + " (" + feature_type_name(f.type) + ") is not a datum plane"); if (!f.enabled) - throw std::runtime_error("datum plane " + std::to_string(fi) + " is hidden; show it first"); + throw CadPrecondition("datum plane " + std::to_string(fi) + " is hidden; show it first"); const int ordinal = datum_ordinal(doc, fi); const auto datums = doc.resolve_datum_planes(); if (ordinal >= int(datums.size())) - throw std::runtime_error("datum plane " + std::to_string(fi) + " could not be resolved"); + throw CadPrecondition("datum plane " + std::to_string(fi) + " could not be resolved"); return datums[ordinal].second; } if (plane.is_object() && plane.size() == 2 && plane.contains("body") && plane.contains("face") && @@ -4616,8 +4697,9 @@ CadDocument cad_document_before(const CadDocument& doc, int feature) check_feature_index(feature, doc); CadDocument before = doc.history_before(feature); if (!before.recompute()) - throw std::runtime_error("the model before feature " + std::to_string(feature) + " (" + doc.features[size_t(feature)].name + - ") does not rebuild: " + (before.error.empty() ? std::string("no reason given") : before.error)); + throw ToolFailure("the model before feature " + std::to_string(feature) + " (" + doc.features[size_t(feature)].name + + ") does not rebuild: " + (before.error.empty() ? std::string("no reason given") : before.error), + {{"code", "rebuild_failed"}}); return before; } @@ -4731,7 +4813,7 @@ struct RefReader int target(int b) const { if (b >= 0) return b; - if (ids.bodies.empty()) throw std::runtime_error("there is no body " + where()); + if (ids.bodies.empty()) throw CadPrecondition("there is no body " + where()); return int(ids.bodies.size()) - 1; } @@ -4992,7 +5074,7 @@ std::vector cad_commit_to_plate_replace(const json& replace, const Model& m throw std::runtime_error("object " + std::to_string(i) + " is listed twice in replace"); // Deleting one opens the "part of a cut object" warning, which the person answers. if (model.objects[size_t(i)]->is_cut()) - throw std::runtime_error("object " + std::to_string(i) + + throw CadPrecondition("object " + std::to_string(i) + " is part of a cut object; delete it with object_select, then object_delete, which asks first"); out.push_back(int(i)); } @@ -5042,7 +5124,7 @@ json cad_sketch_call(DesignSketchTool& tool, const std::string& name, const json json cad_sketch_project(const CadDocument& doc, DesignSketchTool& tool, const json& params) { if (!param(params, "plane").is_null()) throw std::runtime_error("plane is the open sketch's: leave it out"); - if (doc.bodies.empty()) throw std::runtime_error("no source body to project from"); + if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); const json body = param(params, "source_body"); if (!body.is_null() && !body.is_number_integer()) throw std::runtime_error("source_body must be a body index, or -1 for the last body"); const int source = body.is_null() || body.get() == -1 ? int(doc.bodies.size()) - 1 : body.get(); @@ -5053,6 +5135,10 @@ json cad_sketch_project(const CadDocument& doc, DesignSketchTool& tool, const js } const json face = param(params, "face"); if (!face.is_null() && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe), or -1"); + // A body with no shape is the design's state; project_edges_on()'s other reasons are the call's edges, face and + // body index. + if (source >= 0 && source < int(doc.bodies.size()) && doc.bodies[size_t(source)].shape.IsNull()) + throw CadPrecondition("body " + std::to_string(source) + " has no shape"); std::string error; const std::vector ents = doc.project_edges_on(tool.plane(), source, edges, face.is_null() ? -1 : face.get(), error); if (ents.empty()) throw std::runtime_error(error); @@ -5208,7 +5294,7 @@ std::function cad_face_extrude(CadDocument& doc, c throw std::runtime_error(std::string(k) + " cannot be given with face: the face is the profile and fixes its plane"); const json fv = params.at("face"); if (!fv.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); - if (doc.bodies.empty()) throw std::runtime_error("a face push/pull needs a body"); + if (doc.bodies.empty()) throw CadPrecondition("a face push/pull needs a body"); const int asked = target_body_arg(params, doc); const int b = asked >= 0 ? asked : int(doc.bodies.size()) - 1; const int fi = fv.get(); @@ -5521,7 +5607,7 @@ json cad_measure(const CadDocument& doc, const json& params) } Vec3d ca, cb; const double d = GeometryEngine::min_distance(sa, sb, ca, cb); - if (d < 0) throw std::runtime_error("the minimum distance between the refs could not be computed"); + if (d < 0) throw CadKernelFailure("the minimum distance between the refs could not be computed"); r["min_distance"] = d; r["closest_a"] = vec3(ca); r["closest_b"] = vec3(cb); @@ -5533,7 +5619,7 @@ json cad_measure(const CadDocument& doc, const json& params) json cad_hole_placement(const CadDocument& doc, const json& params, SketchPlane& plane, int& target_body) { - if (doc.bodies.empty()) throw std::runtime_error("no body to drill"); + if (doc.bodies.empty()) throw CadPrecondition("no body to drill"); int face_body = -1; plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true, &face_body); const int body = target_body_arg(params, doc); @@ -5715,7 +5801,7 @@ std::function cad_thread(CadDocument& doc, const j const std::string kind = on_face ? "face" : "edge"; for (const char* k : {"plane", "x", "y", "at"}) if (given(k)) throw std::runtime_error(std::string(k) + " cannot be given with " + kind + ": the thread runs on its axis"); - if (doc.bodies.empty()) throw std::runtime_error("no body to thread"); + if (doc.bodies.empty()) throw CadPrecondition("no body to thread"); if (!params.at(kind).is_number_integer()) throw std::runtime_error(kind + " must be an id from body_describe"); target = target_body_arg(params, doc); if (target < 0) target = int(doc.bodies.size()) - 1; @@ -5745,7 +5831,7 @@ std::function cad_thread(CadDocument& doc, const j resolved = cad_hole_placement(doc, params, plane, target); // placed as a hole is } else { // A rod threaded from nothing: there is no body to place against. - if (internal) throw std::runtime_error("an internal thread needs a body to tap; add or import one first"); + if (internal) throw CadPrecondition("an internal thread needs a body to tap; add or import one first"); if (given("at")) throw std::runtime_error("at places a thread against a body, and there is none; give x and y"); plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true); resolved = {{"x", params.value("x", 0.0)}, {"y", params.value("y", 0.0)}}; @@ -5913,7 +5999,7 @@ std::function cad_thicken(CadDocument& doc, const throw std::runtime_error("type surface thickens a whole sheet body and takes no face; type face thickens a face"); if (!surface && face.is_null()) throw std::runtime_error("type face needs face, a face id (body_describe)"); if (!surface && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); - if (doc.bodies.empty()) throw std::runtime_error(surface ? "no sheet body to thicken" : "no body to thicken"); + if (doc.bodies.empty()) throw CadPrecondition(surface ? "no sheet body to thicken" : "no body to thicken"); const int body = target_body_arg(params, doc); const double thickness = params.value("thickness", 2.0); const bool flip = params.value("flip", false); @@ -5951,7 +6037,7 @@ std::function cad_pattern(CadDocument& doc, const : ", the guide curve's entity index within that sketch")); const int count = params.value("count", 3); if (count < 1) throw std::runtime_error("count must be >= 1"); - if (doc.bodies.empty()) throw std::runtime_error("no body to pattern"); + if (doc.bodies.empty()) throw CadPrecondition("no body to pattern"); const int body = target_body_arg(params, doc); if (curve) return [&doc, count, sketch = params.at("sketch").get(), entity = params.at("entity").get(), body](const std::string& name) { @@ -5995,7 +6081,7 @@ std::function cad_dressup(CadDocument& doc, const const char* key = chamfer ? "distance" : "radius"; const double size = params.value(key, 1.0); if (size <= 0) throw std::runtime_error(std::string(key) + " must be > 0"); - if (doc.bodies.empty()) throw std::runtime_error(std::string("no body to ") + verb); + if (doc.bodies.empty()) throw CadPrecondition(std::string("no body to ") + verb); const int body = target_body_arg(params, doc); return [&doc, chamfer, group, edges, size, body](const std::string& name) { const int i = group ? (chamfer ? doc.add_chamfer(size, *group, name) : doc.add_fillet(size, *group, name)) @@ -6017,7 +6103,7 @@ std::function cad_split(CadDocument& doc, const js if (by_plane && by_face) throw std::runtime_error("give plane or face, not both"); if (!by_plane && !by_face) throw std::runtime_error("split needs plane (\"XY\", \"XZ\", \"YZ\", {\"datum\": i} or {\"body\": b, \"face\": f}) or face (a face id to split along)"); - if (doc.bodies.empty()) throw std::runtime_error("no body to split"); + if (doc.bodies.empty()) throw CadPrecondition("no body to split"); const int body = target_body_arg(params, doc); const int t = body >= 0 ? body : int(doc.bodies.size()) - 1; const bool keep_upper = flag("keep_upper", true), keep_lower = flag("keep_lower", true); diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.hpp b/src/slic3r/GUI/Mcp/McpToolsCad.hpp index f8eead7c5e..a98ceec106 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.hpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.hpp @@ -7,11 +7,30 @@ // is in. A call with exactly the arguments that choose one of the command's items (opened_item()) does what that // right-click menu item does, in the mode the item belongs to (open_refusal()); any other call, or one with // silent: true, runs the entry's tool block's silent form. They run on the UI thread through the GUI's own -// CadDocument (no engine of their own), behind one gate (cad_gate()): every command is refused (-32002) during a +// CadDocument (no engine of their own), behind one gate (cad_gate()): every command is refused (design_busy) during a // rebuild, whose worker owns the document, and a silent form that changes the document also while the Design tab // is busy with it, an open feature card or a sketch session; face and edge ids read at another generation are -// refused (-32010). The catalog holds the commands only while the CAD feature is on +// refused (stale_ids). The catalog holds the commands only while the CAD feature is on // (NativeCommands::register_all_commands()). The unit tests call the cad_* helpers directly. +// +// A failed call's error names its cause in `code`, a word as the other commands' refusals have: +// - design_unavailable: no Design tab to act on (the G-code viewer, the CAD feature off, a panel or a view that is not +// built); +// - design_busy: a rebuild, an open card or tool or a sketch session holds the document; +// - stale_ids: face or edge ids read at another generation; +// - wrong_mode: a menu item of the other mode (a sketch tool with no sketch open, a model tool in a sketch); +// - wrong_selection: a menu item that does not take what is selected; +// - invalid_argument: an argument is wrong in itself, names nothing, or names an object whose kind or geometry the +// operation does not take; the caller changes the arguments, or which object they name; +// - precondition: the arguments are right, but the state of what they name, of the design or of the session is not +// one the operation takes (no body, a body hidden or without a shape, a sketch open or none, a tool open), as +// CadPrecondition says; the caller changes the design or the session first; +// - rebuild_failed: a rebuild of the model reported failure: with the call's change, which is taken back, or at the +// earlier state the call reads; +// - kernel_failure: a CAD kernel (OCCT) error reached the command's guard, wherever it was raised, its message after +// "OCCT: "; +// - export_failed: export_step could not transfer or write the STEP file; +// - no_silent_form: an entry with no silent form called as one (run_cad_tool() called directly). #include "libslic3r/Point.hpp" #include "slic3r/GUI/CAD/DesignOffer.hpp" @@ -21,8 +40,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -44,6 +65,51 @@ class DesignSketchTool; namespace Mcp { +// The refusal of a call whose arguments are right but whose design or session is in a state the operation does not +// take: no body to work on, the named body hidden or without a shape, no sketch open or one already open, nothing to +// undo, an open value field, tool or gizmo, the feature already first. State is what the Design tab tracks apart +// from the geometry, which a call cannot choose; what a named object is and where it lies (a face that is not planar, +// a plane that misses the body) is the call's choice, an argument error. Its error's code is precondition, where any +// other exception a silent form throws is invalid_argument (run_guarded()): the caller changes the design or the +// session, not the call. +struct CadPrecondition : std::runtime_error +{ + using std::runtime_error::runtime_error; +}; + +// The refusal of a call the CAD kernel could not compute though it threw nothing (a section or a distance it reports +// as not done): kernel_failure, as an OCCT exception is, its message after "OCCT: ". +struct CadKernelFailure : std::runtime_error +{ + using std::runtime_error::runtime_error; +}; + +// Runs `run`, a silent form or undo and redo, with its failure as the call's error: its own refusal (a ToolFailure) +// with its code (invalid_argument where it names none), a kernel exception or a CadKernelFailure as "OCCT: ..." +// (kernel_failure), a CadPrecondition as +// precondition, and any other exception as invalid_argument, since the silent forms check their arguments with +// plain exceptions. +nlohmann::json run_guarded(const std::function& run); + +// Why there is no Design panel to act on, as cad_gate() refuses it, each design_unavailable: the G-code viewer, which +// has no Design tab; the CAD feature off; else a panel that cannot be built (no page made at startup because the +// feature was turned on later, a page mid-build, or a build that failed), which a retry or a restart mends. UI thread. +ToolFailure no_design_tab(); + +// The refusal of a call that finds no Design view to act on (the panel's viewport, Feature list or parts list not +// built), which no change to the call mends: design_unavailable, as cad_gate() refuses a panel that cannot be built. +ToolFailure no_design_view(); + +// The refusal of a call the Design tab is too busy to take, `why` saying with what (DesignPanel::mcp_busy()): +// design_busy, with a hint naming the commands that close what is open. +ToolFailure design_busy(const std::string& why); + +// The `generation` a call's face and edge ids were read at, or nothing when `args` gives none: a number the schema's +// integer type takes (is_whole_number(): a JSON integer stored signed or unsigned, since a script's or plugin's Python +// integers reach the command as signed ones, or a whole float within int64) that is not negative. Anything else +// throws ToolFailure (invalid_argument). +std::optional cad_generation(const nlohmann::json& args); + // A Design command's silent form: what it does given its arguments, on the panel cad_gate() returned. using CadRun = nlohmann::json (*)(DesignPanel* panel, const nlohmann::json& params); @@ -76,10 +142,12 @@ NativeCommand cad_command(std::string key, std::string title, nlohmann::json sch // undo and redo are the shared commands of NativeCommands.cpp and not among them. void register_cad_commands(CommandCatalog& catalog); -// Records in `catalog`, built with the CAD feature off, that it leaves out the keys register_cad_commands() -// adds, and the ids of the items folded into them, which name actions, because the feature was off when OrcaSlicer -// started and how a person turns it on (CommandCatalog::leave_out()). -void leave_out_cad_commands(CommandCatalog& catalog); +// Records in `catalog`, built without the Design commands, that it leaves out the keys register_cad_commands() +// adds, and the ids of the items folded into them, which name actions, with code design_unavailable and why +// (CommandCatalog::leave_out()): in the editor (`editor`) the CAD feature was off when OrcaSlicer started, and how a +// person turns it on; in the G-code viewer, which has no Design tab whatever the preference, that a person opens the +// project in the editor. +void leave_out_cad_commands(CommandCatalog& catalog, bool editor); // What tool_search's description says of the Design commands, which tools/list does not show, so that an agent // learns without a search that they exist and are CAD: a lead saying what they cover, that one is looked up with @@ -105,12 +173,12 @@ std::vector sketch_target_indices(const nlohmann::json& params, const std:: nlohmann::json cad_input_schema(const nlohmann::json& block); // The checks every Design command passes before its function, in this order: the main window is up (not -// shutting down or still starting), the app is the editor and not the G-code viewer (-32001), the CAD -// feature is on, and the Design panel can be built (-32001); then the busy rules of `access` (-32002; with -// Read, None and Ui only a rebuild's), the project's recipe loaded into an empty document -// (DesignPanel::hydrate_from_model()), as showing the tab would, and a `generation` in `args` that is not an -// unsigned integer (-32602) or not the model's (-32010). Returns the panel. Throws ToolFailure, whose details -// carry the code. UI thread only. +// shutting down or still starting), the app is the editor and not the G-code viewer (design_unavailable), +// the CAD feature is on, and the Design panel can be built (design_unavailable for each); then the busy rules of +// `access` (design_busy, with a hint naming confirm_tool and cancel_tool; with Read, None and Ui only a rebuild's), the +// project's recipe loaded into an empty document (DesignPanel::hydrate_from_model()), as showing the tab would, and a +// `generation` in `args` that cad_generation() refuses (invalid_argument) or that is not the model's (stale_ids). +// Returns the panel. Throws ToolFailure, whose details carry the code. UI thread only. DesignPanel* cad_gate(CadAccess access, const nlohmann::json& args); // The Design table's entry `id`, or nullptr. @@ -156,18 +224,18 @@ std::vector design_actions(const CommandCatalog& catalog, bool ske // toolbar button does, and a key: handler runs whatever is selected, as its key does. With `row_target`, a call that // targets the Feature list's selected row (nothing picked in the view), an item whose handler acts on that row // (DesignTool::feature_row) is not refused for the selection: its handler says itself what it cannot do. The message -// is a msgid, the code -32000. +// is a msgid, the code wrong_mode, with a hint naming the commands that change the mode, or wrong_selection. std::optional open_refusal(const DesignTool& t, bool sketching, int kind, bool row_target = false); // Runs the silent form of Design command `id` with `args` past cad_gate() with its entry's access, and -// returns its result. One that fails is -32000, with "OCCT: " before a kernel exception's message; an id with -// no silent form is -32601. UI thread only. +// returns its result. One that fails has the code of its cause (the list at the top), with "OCCT: " before a +// kernel exception's message; an id with no silent form is no_silent_form. UI thread only. nlohmann::json run_cad_tool(const std::string& id, const nlohmann::json& args); // Edit > Undo, or Redo, in the Design tab, past cad_gate() with Sketch access: the Design history, or in a // sketch session the sketch's own, which takes off or puts back the last drawn shape. Returns {ok, scope} // with "sketch" and the sketch's entities, or "design" and the undo and redo depth, features, bodies and -// generation. Fails (-32000) when there is nothing to take back or put back. UI thread only. +// generation. Fails (precondition) when there is nothing to take back or put back. UI thread only. nlohmann::json cad_undo_redo(bool redo); // app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp index c2c3c16c54..6be4bafa11 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp @@ -21,10 +21,12 @@ #include #include +#include #include #include #include #include +#include #include #include #include @@ -220,13 +222,48 @@ ToolFailure refused(const Ops::Refusal& refusal, const std::string& hint, const json details{{"code", refusal.code}}; if (names_key != nullptr) details[names_key] = refusal.names; + if (std::string agent = refusal_hint(refusal); !agent.empty()) + details["hint"] = std::move(agent); return ToolFailure(refusal.english() + (hint.empty() ? "" : " " + hint), std::move(details)); } +std::string refusal_hint(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + // Two refusals share gizmo_open: Select All's, for the gizmo of the view shown (select_everything()), and the + // operations', for the Prepare view's (ObjectOps' gizmo_open()), so the hint tells them apart by the call. + if (code == "gizmo_open" || code == "gizmo_editing") + return "object_select {none: true} closes the open gizmo of the view shown, as Deselect All does. Select All is " + "refused for that view's gizmo, any other operation for the Prepare view's, so for those in the assemble view, " + "view_set {canvas: \"3d\"} comes first. Deselecting clears the selection: a call that acted on it names its " + "targets when it runs again."; + // Only Add Primitive's person's form ({shape} alone) asks for the selection to be clear. The Speed Dial's + // add_primitive actions take no arguments, so the call with a size or silent is the command's. + if (code == "object_selected") + return "object_select {none: true} first; or call object_add_primitive with size or silent: true, which adds the " + "shape whatever is selected; part_add adds it to the selected object"; + // The refusals that ask for a selection, where the call can name what it acts on. + if (code == "nothing_selected" || code == "one_object_only" || code == "wrong_selection" || code == "too_few_objects" || + code == "several_instances") + return "name the targets in the call (its objects, instances or parts, or object and part, as its schema takes them), " + "or select them with object_select"; + return {}; +} + int arg_int(const json& args, const char* key, int fallback) { auto it = args.find(key); - return it != args.end() && it->is_number() ? it->get() : fallback; + if (it == args.end() || !it->is_number()) + return fallback; + // Checked before it is narrowed: get() would turn 4294967296 into 0, another index or count the command then + // accepts, and a float past int's range into undefined behavior. + constexpr auto lo = std::numeric_limits::min(), hi = std::numeric_limits::max(); + const bool fits = it->is_number_unsigned() ? it->get() <= std::uint64_t(hi) : + it->is_number_integer() ? it->get() >= lo && it->get() <= hi : + std::isfinite(it->get()) && it->get() >= lo && it->get() <= hi; + if (!fits) + throw ToolFailure(std::string(key) + " " + it->dump() + " is out of range", {{"code", "invalid_argument"}}); + return it->get(); } double arg_double(const json& args, const char* key, double fallback) diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index 8815aba5e1..5941d951fa 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -205,7 +205,8 @@ ToolFailure invalid_value(const std::string& key, const std::string& text) takes = list ? "a list of " + kind + (range.empty() ? "" : ", each " + range) : kind + (range.empty() ? "" : (low && high ? " " : ", ") + range); } - return ToolFailure("Invalid value for " + key + ": \"" + text + "\"" + (takes.empty() ? std::string() : "; it takes " + takes)); + return ToolFailure("Invalid value for " + key + ": \"" + text + "\"" + (takes.empty() ? std::string() : "; it takes " + takes), + {{"code", "invalid_argument"}}); } // Option keys whose key or label contains `query`, for "did you mean". @@ -367,14 +368,17 @@ void add_unknown_keys(json& out, const json& unknown, const std::vector() throws on anything but a number. + if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) + throw ToolFailure(std::string(what) + " must be [x, y, z], three numbers", {{"code", "invalid_argument"}}); return {v[0].get(), v[1].get(), v[2].get()}; } diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index 11e717cd35..8f92bfa6ae 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -99,8 +99,9 @@ json vec3(const Vec3d& v) { return {v.x(), v.y(), v.z()}; } Vec3d to_vec3(const json& v, const char* what) { - if (!v.is_array() || v.size() != 3) - throw ToolFailure(std::string(what) + " must be [x, y, z]"); + // Each element too: a schema may give the array no items, and get() throws on anything but a number. + if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) + throw ToolFailure(std::string(what) + " must be [x, y, z], three numbers", {{"code", "invalid_argument"}}); return {v[0].get(), v[1].get(), v[2].get()}; } @@ -179,7 +180,7 @@ Vec3d scale_factors(const json& s) { const Vec3d f = s.is_number() ? Vec3d::Constant(s.get()) : to_vec3(s, "scale"); if (f.minCoeff() <= 0.) - throw ToolFailure("scale factors must be positive"); + throw ToolFailure("scale factors must be positive", {{"code", "invalid_argument"}}); return f; } @@ -1604,19 +1605,9 @@ AppActionRunResult add_primitive_command(const json& args) Plater& plater = ui_plater(); const Ops::Outcome added = Ops::add_primitive(op); - if (!added) { - const std::string code = added.refusal().code; + if (!added) // The size dialog cancelled told the person nothing more is to come. - if (op.ask && code == "not_added") - return quiet_refusal(added.refusal()); - AppActionRunResult refused = menu_refused(added.refusal()); - // The refusal words the person's menus; an agent's call has commands for each way out. - if (code == "object_selected") - refused.reply = json{{"hint", "object_select {none: true} first; or give size or silent: true, which adds the shape whatever is " - "selected; part_add adds it to the selected object"}} - .dump(); - return refused; - } + return op.ask && std::string(added.refusal().code) == "not_added" ? quiet_refusal(added.refusal()) : menu_refused(added.refusal()); const int index = added.value(); Targets made; made.objects = {index}; diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/McpToolsView.cpp index bcd0dc6a7b..89ce4befff 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsView.cpp @@ -31,6 +31,7 @@ #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" #ifdef SLIC3R_CAD +#include "McpToolsCad.hpp" #include "slic3r/GUI/CAD/DesignCanvas.hpp" #include "slic3r/GUI/CAD/DesignPanel.hpp" #endif @@ -274,6 +275,8 @@ std::optional point_camera(Plater& plater, const std::string& cam) #ifdef SLIC3R_CAD if (DesignPanel* design = wxGetApp().mainframe->shown_design_panel()) { DesignCanvas* view = design->mcp_viewport(); + if (view == nullptr) + throw Mcp::no_design_view(); if (cam == "fit_bed") return no_bed_in_design(); if (cam == "fit_objects") @@ -976,34 +979,39 @@ void register_view_tools(CommandCatalog& catalog) // Design view refuses (point_camera()), are refused here, before the tab or anything else // changes; a rebuild refuses the options, its worker holding the document the reference planes // are read from. + // With no Design panel to show or set, the refusal is cad_gate()'s (Mcp::no_design_tab()). DesignPanel* design = nullptr; if (arg_string(args, "tab") == "design" && frame->m_design_page != nullptr) design = DesignPanel::ensure(); + if (design != nullptr && design->mcp_viewport() == nullptr) + throw Mcp::no_design_view(); if (design_args) { if (design == nullptr) - throw ToolFailure(frame->m_design_page == nullptr ? "The Design tab is off; enable the CAD feature in Preferences and restart" - : "The Design tab isn't available in this window yet; retry"); + throw Mcp::no_design_tab(); std::string why; if (design->mcp_busy(true, false, why)) - throw ToolFailure("Design tab busy: " + why, {{"code", -32002}}); + throw Mcp::design_busy(why); if (arg_string(args, "camera") == "sketch_normal" && !design->mcp_viewport()->is_sketching()) - throw ToolFailure("No sketch is open in the Design tab"); + throw ToolFailure("No sketch is open in the Design tab", {{"code", "precondition"}}); } // The Design view the camera points once the tab is handled: the one asked for, or the one shown, which // a call with no tab, canvas or Preview field leaves shown. Its refusals (point_camera()) come here too. DesignPanel* aimed = design; if (aimed == nullptr && !args.contains("tab") && !args.contains("canvas") && !preview_args) aimed = frame->shown_design_panel(); + if (aimed != nullptr && aimed->mcp_viewport() == nullptr) + throw Mcp::no_design_view(); if (aimed != nullptr && arg_string(args, "camera") == "fit_bed") throw refused(no_bed_in_design()); if (aimed != nullptr && arg_string(args, "camera") == "fit_selection" && !aimed->mcp_viewport()->selection_box().defined) - throw ToolFailure("Nothing is selected in the Design tab"); + throw ToolFailure("Nothing is selected in the Design tab", {{"code", "precondition"}}); #endif if (args.contains("tab")) { const std::string tab = arg_string(args, "tab"); #ifdef SLIC3R_CAD - if (tab == "design" && frame->m_design_page == nullptr) - throw ToolFailure("The Design tab is off; enable the CAD feature in Preferences and restart"); + // A page whose panel cannot be built is refused too: showing it activates the panel. + if (tab == "design" && design == nullptr) + throw Mcp::no_design_tab(); #endif if (const std::optional refusal = show_tab(*frame, tab)) throw refused(*refusal); diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index a6cded5dc8..4f4bb554c6 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -1140,7 +1140,7 @@ void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unus if (options.cad) Mcp::register_cad_commands(catalog); else - Mcp::leave_out_cad_commands(catalog); + Mcp::leave_out_cad_commands(catalog, options.editor); #endif for (auto it = gui; it != placed.end(); ++it) catalog.add(std::move(*it)); @@ -1366,15 +1366,15 @@ ToolResult NativeCommands::from_run_result(const std::string& key, const AppActi // A command that did nothing (no selection, no objects) fails here, though the Speed Dial shows it as // information. if (result.level == AppActionRunResult::Level::Error || result.level == AppActionRunResult::Level::Busy || !result.done) { - json details = json::object(); + json details; if (result.refusal) { - details["code"] = result.refusal->code; + details = {{"code", result.refusal->code}}; if (!result.refusal->names.empty()) details["names"] = result.refusal->names; + // The message is the person's; the hint is what an agent's call does instead. + if (std::string hint = Mcp::refusal_hint(*result.refusal); !hint.empty()) + details["hint"] = std::move(hint); } - if (!result.reply.empty()) - if (json reply = json::parse(result.reply, nullptr, /*allow_exceptions=*/false); reply.is_object()) - details.update(reply); return ToolResult::error(message.empty() ? "The action failed" : message, std::move(details)); } json out{{"ran", key}, {"level", level_name(result.level)}}; diff --git a/src/slic3r/GUI/NativeCommands.hpp b/src/slic3r/GUI/NativeCommands.hpp index 8644375f00..053c99a647 100644 --- a/src/slic3r/GUI/NativeCommands.hpp +++ b/src/slic3r/GUI/NativeCommands.hpp @@ -20,10 +20,13 @@ struct Refusal; namespace NativeCommands { // Which optional families of commands the process catalog holds. cad: the Design tab is on in this run, so the -// catalog holds its commands (in a build with CAD; a build without it has none). +// catalog holds its commands (in a build with CAD; a build without it has none). editor: the run is the editor, not +// the G-code viewer, which has no Design tab whatever the preference says; it chooses why the catalog says it leaves +// the Design commands out. struct CatalogOptions { - bool cad = false; + bool cad = false; + bool editor = true; }; // Adds the built-in commands to `catalog`, family by family (Mcp::register_app_tools() and the others): the typed diff --git a/src/slic3r/plugin/host/PluginHostTools.cpp b/src/slic3r/plugin/host/PluginHostTools.cpp index 0fb7304ab9..dc58b920e7 100644 --- a/src/slic3r/plugin/host/PluginHostTools.cpp +++ b/src/slic3r/plugin/host/PluginHostTools.cpp @@ -204,6 +204,7 @@ void register_tools(py::module_& host) [tools](const std::string& name) mutable { json entry; std::string unknown; // the error for a name the catalog does not hold + std::string code; json close; { py::gil_scoped_release release; @@ -212,11 +213,12 @@ void register_tools(py::module_& host) entry = GUI::command_reference(*command); } else { unknown = catalog.unknown_command(name); + code = catalog.unknown_command_code(name); close = catalog.similar(name); } } if (!unknown.empty()) - raise_tool_error(tools, unknown, {{"did_you_mean", close}}); + raise_tool_error(tools, unknown, {{"code", code}, {"did_you_mean", close}}); return json_to_py(entry); }, py::arg("name"), diff --git a/tests/automation/test_mcp_protocol.cpp b/tests/automation/test_mcp_protocol.cpp index 660c1f4c90..594df72a8f 100644 --- a/tests/automation/test_mcp_protocol.cpp +++ b/tests/automation/test_mcp_protocol.cpp @@ -140,9 +140,14 @@ TEST_CASE("tool failures and invalid arguments are isError results", "[Mcp]") const std::string text = bad["content"][0]["text"]; CHECK(text.find("unknown argument txt") != std::string::npos); CHECK(text.find("\"text\"") != std::string::npos); + // Its code says it is the call's arguments, as a command's own argument checks say. + CHECK(text.find(R"({"code":"invalid_argument"})") != std::string::npos); const json missing = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", json::object()}}}}))["result"]; CHECK(missing["isError"] == true); CHECK(missing["content"][0]["text"].get().find("text is required") != std::string::npos); + CHECK(missing["content"][0]["text"].get().find(R"({"code":"invalid_argument"})") != std::string::npos); + // The tool's own failure is not about the arguments. + CHECK(failed["content"][0]["text"].get().find("invalid_argument") == std::string::npos); } TEST_CASE("an unknown tool is a JSON-RPC error with suggestions", "[Mcp]") @@ -303,6 +308,13 @@ TEST_CASE("argument validation covers types, enums, ranges and arrays", "[Mcp]") CHECK(validate_arguments(schema, {{"zoom", 0}}).find("zoom must be > 0") != std::string::npos); CHECK(validate_arguments(schema, {{"zoom", 0.5}}).empty()); CHECK(validate_arguments(schema, {{"n", 2.5}}).find("integer") != std::string::npos); + // A whole number written as a float is an integer, within the int64 range callers read it into; past it, and + // past what a double holds exactly, it is not one (checked without a cast, which there would be undefined). + CHECK(validate_arguments(schema, {{"n", 3.0}}).empty()); + const json wide = {{"type", "object"}, {"properties", {{"i", {{"type", "integer"}}}}}}; + CHECK(validate_arguments(wide, {{"i", 9.0e18}}).empty()); + CHECK(validate_arguments(wide, {{"i", 9.3e18}}).find("integer") != std::string::npos); + CHECK(validate_arguments(wide, {{"i", 1.0e300}}).find("integer") != std::string::npos); CHECK(validate_arguments(schema, {{"mode", "c"}}).find("one of") != std::string::npos); CHECK(validate_arguments(schema, {{"paths", {1}}}).find("paths[0]") != std::string::npos); CHECK(validate_arguments(schema, {{"paths", json::array()}}).empty()); @@ -528,11 +540,32 @@ TEST_CASE("an unknown tool is answered with the closest names", "[Mcp]") {"required", {"tool"}}}; api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; f.registry.add(api); - // tool_call's target names the closest command, and nothing else. + // tool_call's target names the closest command, and nothing else; the code says the call's `tool` is wrong. const json typo = body(f.post({{"jsonrpc", "2.0"}, {"id", 9}, {"method", "tools/call"}, {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; CHECK(typo["isError"] == true); - CHECK(typo["content"][0]["text"] == "Unknown tool: ech (did you mean echo?)"); + CHECK(typo["content"][0]["text"] == "Unknown tool: ech (did you mean echo?)\n" R"({"code":"invalid_argument"})"); + // A target the catalog leaves out is named right: its code is the one it was left out with, which says what keeps + // it from this run. + f.registry.leave_out("holes", "the feature was off", "feature_off"); + const json left_out = body(f.post({{"jsonrpc", "2.0"}, {"id", 10}, {"method", "tools/call"}, + {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "holes"}}}}}}))["result"]; + CHECK(left_out["isError"] == true); + CHECK(left_out["content"][0]["text"] == "Unknown tool: holes; the feature was off\n" R"({"code":"feature_off"})"); +} + +TEST_CASE("a tools/call whose name is not a string is a parameter error", "[Mcp]") +{ + Fixture f; + // Both dispatches read the name as a string, the modern one in its header check first. + const PostReply legacy = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", 5}}}}); + CHECK(legacy.status == 200); + CHECK(body(legacy)["error"]["code"] == -32602); + CHECK(body(legacy)["error"]["message"] == "name must be a string"); + const PostReply modern = f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/call"}, {"params", modern_params({{"name", 5}})}}, + "2026-07-28", "tools/call", "5"); + CHECK(modern.status == 200); + CHECK(body(modern)["error"]["code"] == -32602); } TEST_CASE("a call's arguments are normalized, then validated", "[Mcp]") @@ -574,10 +607,13 @@ TEST_CASE("tool_call runs and is journaled as the tool it names", "[Mcp]") const json invalid = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "echo"}, {"args", json::object()}}}}}}))["result"]; CHECK(invalid["isError"] == true); + CHECK(invalid["content"][0]["text"].get().find(R"({"code":"invalid_argument"})") != std::string::npos); + // tool_call's own argument names nothing: that is its arguments too. const json unknown = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; CHECK(unknown["isError"] == true); CHECK(unknown["content"][0]["text"].get().find("did you mean echo") != std::string::npos); + CHECK(unknown["content"][0]["text"].get().find(R"({"code":"invalid_argument"})") != std::string::npos); } // Holds the one operation a plugin offers while it is loaded. diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index 3eb1158b40..a9bb7f998d 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -12,6 +12,7 @@ #include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpPersonContext.hpp" #include "slic3r/GUI/Mcp/McpProtocol.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" @@ -932,7 +933,7 @@ TEST_CASE("a command the catalog leaves out is unknown with the reason", "[Comma { CommandCatalog catalog; catalog.add(command("hold")); - catalog.leave_out("holes", "the feature was off"); + catalog.leave_out("holes", "the feature was off", "feature_off"); catalog.seal(); REQUIRE(catalog.left_out("holes") != nullptr); CHECK(*catalog.left_out("holes") == "the feature was off"); @@ -940,19 +941,30 @@ TEST_CASE("a command the catalog leaves out is unknown with the reason", "[Comma // The reason, and no close key: the key names the command the caller meant. CHECK(catalog.unknown_command("holes", /*suggest=*/true) == "Unknown tool: holes; the feature was off"); CHECK(catalog.unknown_command("holx", /*suggest=*/true) == "Unknown tool: holx (did you mean hold?)"); - CHECK_THROWS_AS(catalog.leave_out("shell", "too late"), std::logic_error); + // A left-out key's name is right, so its error carries what keeps it from the run; any other is the call's to correct. + CHECK(catalog.unknown_command_code("holes") == "feature_off"); + CHECK(catalog.unknown_command_code("holx") == "invalid_argument"); + CHECK_THROWS_AS(catalog.leave_out("shell", "too late", "feature_off"), std::logic_error); // A run with the CAD feature off at startup leaves out the Design commands, and says how a person turns it - // on; a build without CAD has no Design commands to leave out. + // on; the G-code viewer leaves them out whatever the preference, and says to open the editor. A build without + // CAD has no Design commands to leave out. CommandCatalog no_cad; NativeCommands::register_all_commands(no_cad, {false}); no_cad.seal(); + CommandCatalog viewer; + NativeCommands::register_all_commands(viewer, {false, /*editor=*/false}); + viewer.seal(); #ifdef SLIC3R_CAD for (const std::string key : {"extrude", "hole", "describe_design"}) { INFO(key); CHECK(no_cad.unknown_command(key, /*suggest=*/true) == "Unknown tool: " + key + "; the CAD feature was off when OrcaSlicer started: a person turns it on in " "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"); + CHECK(no_cad.unknown_command_code(key) == "design_unavailable"); + CHECK(viewer.unknown_command(key, /*suggest=*/true) == + "Unknown tool: " + key + "; the G-code viewer has no Design tab: a person opens the project in OrcaSlicer's editor"); + CHECK(viewer.unknown_command_code(key) == "design_unavailable"); } #else CHECK(no_cad.left_out("extrude") == nullptr); @@ -1250,6 +1262,51 @@ TEST_CASE("a command's result reads as action_run's did", "[CommandCatalog]") CHECK(failed.is_error); CHECK(failed.message == "There are no objects."); CHECK(failed.data["code"] == "no_objects"); + CHECK_FALSE(failed.data.contains("hint")); + + // A refusal worded for the GUI keeps its text, which the person reads too, and tells an agent's call what to do + // in the commands' terms, by either route a refusal takes to it. + Ops::Refusal gizmo; + gizmo.code = "gizmo_open"; + gizmo.msgid = "Error: Please close all toolbar menus first"; + refused.refusal = std::make_shared(gizmo); + const ToolResult behind_gizmo = NativeCommands::from_run_result("k", refused); + CHECK(behind_gizmo.message == "Error: Please close all toolbar menus first"); + CHECK_THAT(behind_gizmo.data.value("hint", std::string()), ContainsSubstring("object_select {none: true}")); + const ToolFailure operation_refused = Mcp::refused(gizmo); + CHECK(std::string(operation_refused.what()) == "Error: Please close all toolbar menus first"); + CHECK(operation_refused.details.at("hint") == behind_gizmo.data.at("hint")); + // The two gizmo_open refusals are told apart by the call: Select All's is about the view shown, the others' about + // Prepare's, which the assemble view shows only after view_set. + CHECK_THAT(behind_gizmo.data.value("hint", std::string()), ContainsSubstring("view_set {canvas: \"3d\"}")); +} + +TEST_CASE("a refusal that asks for a GUI step or a selection names the calls that do it instead", "[CommandCatalog]") +{ + const auto hint_of = [](const char* code) { + Ops::Refusal refusal; + refusal.code = code; + refusal.msgid = "Refused."; + return Mcp::refusal_hint(refusal); + }; + // Add Primitive's person's form refuses while an object is selected; a size or silent adds it whatever is selected. + const std::string primitive = hint_of("object_selected"); + CHECK_THAT(primitive, ContainsSubstring("object_select {none: true}")); + // The Speed Dial's add_primitive actions take no arguments, so the hint names the command that takes them. + CHECK_THAT(primitive, ContainsSubstring("object_add_primitive with size or silent: true")); + CHECK_THAT(primitive, ContainsSubstring("size")); + CHECK_THAT(primitive, ContainsSubstring("silent: true")); + CHECK_THAT(primitive, ContainsSubstring("part_add")); + // The refusals that ask for a selection name the targets a call gives instead. + for (const char* code : {"nothing_selected", "one_object_only", "wrong_selection", "too_few_objects", "several_instances"}) { + INFO(code); + CHECK_THAT(hint_of(code), ContainsSubstring("name the targets in the call")); + } + // A step only a person takes has no command to name. + for (const char* code : {"not_signed_in", "no_printer", "no_printer_connected", "no_objects"}) { + INFO(code); + CHECK(hint_of(code).empty()); + } } #ifdef SLIC3R_CAD diff --git a/tests/slic3rutils/test_design_sketch_tool.cpp b/tests/slic3rutils/test_design_sketch_tool.cpp index 6191778552..505f8c8246 100644 --- a/tests/slic3rutils/test_design_sketch_tool.cpp +++ b/tests/slic3rutils/test_design_sketch_tool.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -390,14 +391,27 @@ TEST_CASE("A face, edges or a vertex is selected by id only where a click could refused(Sel::Edge, 0, -1, {1, 1}); refused(Sel::Edge, 0, -1, {999}); refused(Sel::Face, 2, 0, {}); - // A hidden body takes no click, nor does one a pick is held off (a card's focus on another body). + // An id the body does not have is the pick's; the body still takes picks, which select_geometry tells apart from the + // view's state. + CHECK(tool.body_takes_pick(0)); + CHECK(tool.body_takes_pick(1)); + // A hidden body takes no click, nor does one a pick is held off (a card's focus on another body): the view's state, + // whatever the ids. visible[1] = false; refused(Sel::Vertex, 1, -1, {}); + std::string state; + CHECK_FALSE(tool.body_takes_pick(1, &state)); + CHECK_THAT(state, Catch::Matchers::ContainsSubstring("takes no click")); + CHECK(tool.body_takes_pick(0)); visible[1] = true; tool.set_pick_only_body(0); refused(Sel::Face, 1, 0, {}); + CHECK_FALSE(tool.body_takes_pick(1)); tool.set_pick_only_body(-1); CHECK(tool.can_select_solid(Sel::Edge, 1, -1, {0, 1})); + // A body the pick shapes do not have has no shape in the view. + CHECK_FALSE(tool.body_takes_pick(2, &state)); + CHECK_THAT(state, Catch::Matchers::ContainsSubstring("has no shape in the view")); } TEST_CASE("Padding a box to frame gives every axis a small extent and leaves a long one alone", "[DesignSketchTool]") diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index c5e6c5dd19..11a2e163bf 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +66,7 @@ #include #include #include +#include #include #include #include @@ -133,6 +135,21 @@ template std::string failure(F&& call) return {}; } +// The code the error of a Design command's call carries when `call` fails inside it (GUI::Mcp::run_guarded()), or "" +// when it does not fail. +template std::string failure_code(F&& call) +{ + try { + GUI::Mcp::run_guarded([&]() -> json { + call(); + return json(); + }); + } catch (const GUI::ToolFailure& f) { + return f.details.value("code", std::string()); + } + return {}; +} + SketchEntity line(double x0, double y0, double x1, double y1) { SketchEntity e; @@ -751,7 +768,7 @@ TEST_CASE("a tool refused for the selection says it does not apply and what it t const std::optional refused = GUI::Mcp::open_refusal(delete_face, false, none); REQUIRE(refused.has_value()); CHECK(std::string(refused->what()) == "This tool does not apply to what is selected"); - CHECK(refused->details.at("code") == -32000); + CHECK(refused->details.at("code") == "wrong_selection"); CHECK(refused->details.at("selection_kind") == 0); CHECK(refused->details.at("selection") == "none"); CHECK(refused->details.at("accepts") == json::array({"face_planar", "face_cyl", "face_other"})); @@ -846,8 +863,19 @@ TEST_CASE("a Design tool opens only in the mode its menu item belongs to", "[Mcp const std::optional refused = GUI::Mcp::open_refusal(t, !t.sketch_mode, kind); REQUIRE(refused.has_value()); CHECK(std::string(refused->what()) == (t.sketch_mode ? in_sketch : on_model)); - CHECK(refused->details.at("code") == -32000); + CHECK(refused->details.at("code") == "wrong_mode"); CHECK(refused->details.at("mode") == (t.sketch_mode ? "sketch" : "model")); + // The person's message names no command; the hint names those that change the mode. A model tool's names + // the two that end a sketch and Constrain mode alike, where the busy gate refuses sketch_finish. + const std::string hint = refused->details.at("hint").get(); + if (t.sketch_mode) { + // With a plane, as sketch_create {} opens the plane picker instead of a sketch. + CHECK_THAT(hint, ContainsSubstring("sketch_create {plane: \"XY\"}")); + } else { + CHECK_THAT(hint, ContainsSubstring("confirm_tool")); + CHECK_THAT(hint, ContainsSubstring("cancel_tool")); + CHECK_THAT(hint, !ContainsSubstring("sketch_finish")); + } } ++(t.sketch_mode ? sketch_items : model_items); } @@ -1275,6 +1303,74 @@ TEST_CASE("a CAD command takes the names its function also reads", "[Mcp][CAD]") CHECK(unconstrain == json{{"index", 4}}); } +TEST_CASE("a CAD command's failure names its cause in its code", "[Mcp][CAD]") +{ + const auto code_of = [](const std::function& run) { + try { + GUI::Mcp::run_guarded(run); + } catch (const GUI::ToolFailure& failure) { + return failure.details.value("code", json()).get(); + } + return std::string("no failure"); + }; + // A silent form checks its arguments with plain exceptions, and the design's state with CadPrecondition. + CHECK(code_of([]() -> json { throw std::runtime_error("diameter must be > 0"); }) == "invalid_argument"); + CHECK(code_of([]() -> json { throw GUI::Mcp::CadPrecondition("no body to shell"); }) == "precondition"); + // The kernel's own exceptions are told apart from both, as is what it reports it could not compute. + CHECK(code_of([]() -> json { throw Standard_Failure("BRep_API: command not done"); }) == "kernel_failure"); + CHECK(code_of([]() -> json { throw GUI::Mcp::CadKernelFailure("section failed"); }) == "kernel_failure"); + try { + GUI::Mcp::run_guarded([]() -> json { throw GUI::Mcp::CadKernelFailure("section failed"); }); + } catch (const GUI::ToolFailure& failure) { + CHECK(std::string(failure.what()) == "OCCT: section failed"); + } + // A refusal of its own keeps its code: no Design view, a busy tab with the commands that close what is open. One + // that names no cause reads as a plain exception does. + CHECK(code_of([]() -> json { throw GUI::Mcp::no_design_view(); }) == "design_unavailable"); + CHECK(code_of([]() -> json { throw GUI::ToolFailure("no cause named"); }) == "invalid_argument"); + CHECK(code_of([]() -> json { throw GUI::ToolFailure("no cause named", {{"keys", json::array({"a"})}}); }) == "invalid_argument"); + const GUI::ToolFailure busy = GUI::Mcp::design_busy("a sketch is open in the Design tab"); + CHECK(std::string(busy.what()) == "Design tab busy: a sketch is open in the Design tab"); + CHECK(busy.details.at("code") == "design_busy"); + CHECK_THAT(busy.details.at("hint").get(), ContainsSubstring("confirm_tool")); + CHECK_THAT(busy.details.at("hint").get(), ContainsSubstring("cancel_tool")); + CHECK(code_of([]() -> json { return json::object(); }) == "no failure"); + + // The real checks: on a design with no body, the commands that work on one refuse for the design's state. + CadDocument empty; + SketchPlane frame; + CHECK(failure_code([&] { GUI::Mcp::cad_face_extrude(empty, {{"face", 0}}, frame); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_pattern(empty, {{"type", "circular"}, {"count", 4}}); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_dressup(empty, {{"edges", json::array({0})}}, false); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_thicken(empty, {{"type", "face"}, {"face", 0}}); }) == "precondition"); + // An argument wrong in itself is the call's, whatever the design holds. + CHECK(failure_code([&] { GUI::Mcp::cad_pattern(empty, {{"type", "circular"}, {"count", 0}}); }) == "invalid_argument"); + CHECK(failure_code([&] { GUI::Mcp::cad_face_extrude(empty, {{"face", "top"}}, frame); }) == "invalid_argument"); +} + +TEST_CASE("a CAD call's generation is any integer of 0 or more, signed or unsigned", "[Mcp][CAD]") +{ + // A script's or plugin's Python integers reach the command as signed JSON integers, which must read as the same + // generation a reply gave. + CHECK_FALSE(GUI::Mcp::cad_generation(json::object()).has_value()); + CHECK_FALSE(GUI::Mcp::cad_generation(json()).has_value()); + CHECK(GUI::Mcp::cad_generation({{"generation", std::uint64_t(7)}}) == std::optional(7)); + CHECK(GUI::Mcp::cad_generation({{"generation", std::int64_t(7)}}) == std::optional(7)); + CHECK(GUI::Mcp::cad_generation({{"generation", std::int64_t(0)}}) == std::optional(0)); + // A whole number written as a float passes the schema's integer type, so it counts too. + CHECK(GUI::Mcp::cad_generation({{"generation", 7.0}}) == std::optional(7)); + // The largest unsigned integer is a generation. A float is one where the schema's integer type takes it, below 2^63 + // (is_whole_number()), so the call and a caller that skips the schema read the same numbers. + CHECK(GUI::Mcp::cad_generation({{"generation", std::uint64_t(18446744073709551615ull)}}) == + std::optional(18446744073709551615ull)); + CHECK(GUI::Mcp::cad_generation({{"generation", 9.0e18}}) == std::optional(9000000000000000000ull)); + for (const json& bad : {json(std::int64_t(-1)), json(-1.0), json("7"), json(7.5), json(nullptr), json(9.3e18), + json(9223372036854775808.0), json(18446744073709551616.0), json(1.0e300)}) { + INFO(bad.dump()); + CHECK(failure_code([&] { GUI::Mcp::cad_generation({{"generation", bad}}); }) == "invalid_argument"); + } +} + TEST_CASE("a CAD command refuses a misspelt argument instead of using its default", "[Mcp][CAD]") { const GUI::CommandCatalog catalog = cad_catalog(); @@ -1826,7 +1922,7 @@ TEST_CASE("a CAD call is journaled without its generation and with its silent", // A failure is the call's error. const GUI::NativeCommand refused = GUI::Mcp::cad_command("hole", "Hole", json{{"type", "object"}, {"properties", json::object()}}, [](const json&, bool) -> json { - throw GUI::ToolFailure("removed no material", {{"code", -32000}}); + throw GUI::ToolFailure("removed no material", {{"code", "rebuild_failed"}}); }); CHECK_THROWS_AS(refused.run(json::object(), agent), GUI::ToolFailure); } @@ -2124,9 +2220,11 @@ TEST_CASE("plane refuses what is not a plane, naming why", "[Mcp][CAD]") CHECK_THAT(error_of({{"body", 4}, {"face", 0}}, doc), ContainsSubstring("out of range")); CHECK_THAT(error_of({{"body", 0}, {"face", 999}}, doc), ContainsSubstring("does not exist")); + CHECK(failure_code([&] { GUI::Mcp::cad_resolve_plane({{"datum", 0}}, doc, false); }) == "invalid_argument"); doc.features[datum].enabled = false; REQUIRE(doc.recompute()); CHECK_THAT(error_of({{"datum", datum}}, doc), ContainsSubstring("hidden")); + CHECK(failure_code([&] { GUI::Mcp::cad_resolve_plane({{"datum", datum}}, doc, false); }) == "precondition"); // A cylinder's side is not a plane, for sketching or for drilling. CadDocument cyl; @@ -2568,6 +2666,8 @@ TEST_CASE("commit_to_plate's replace takes distinct object indices that are not CHECK_THAT(refusal({0.5}), ContainsSubstring("not 0.5")); CHECK_THAT(refusal({"0"}), ContainsSubstring("object indices")); CHECK_THAT(refusal({0, 2}), ContainsSubstring("part of a cut object")); + CHECK(failure_code([&] { GUI::Mcp::cad_commit_to_plate_replace({0, 2}, model); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_commit_to_plate_replace({3}, model); }) == "invalid_argument"); } TEST_CASE("export_step's STEP file reads back with each body where the Move gizmo put it", "[Mcp][CAD]") @@ -3897,8 +3997,15 @@ TEST_CASE("a hole drills a face's body at a world point or on a round reference' GUI::Mcp::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", side}}}, {"at", {{"body", 0}, {"face", bore}}}}, pl, body); }), ContainsSubstring("is not square to the plane")); + // Where the named references lie, and what they are, is the call's choice; a design with no body is the state. + CHECK(failure_code([&] { + GUI::Mcp::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", side}}}, {"at", {{"body", 0}, {"face", bore}}}}, pl, body); + }) == "invalid_argument"); + CHECK(failure_code([&] { GUI::Mcp::cad_hole_placement(doc, {{"at", {{"body", 0}, {"face", top}}}}, pl, body); }) == + "invalid_argument"); CadDocument empty; CHECK_THAT(failure([&] { GUI::Mcp::cad_hole_placement(empty, json::object(), pl, body); }), ContainsSubstring("no body to drill")); + CHECK(failure_code([&] { GUI::Mcp::cad_hole_placement(empty, json::object(), pl, body); }) == "precondition"); } } @@ -4251,6 +4358,11 @@ TEST_CASE("thread refuses a target it cannot cut, before anything changes", "[Mc CHECK_THAT(failure([&] { GUI::Mcp::cad_thread(empty, {{"internal", true}, {"designation", "M5"}, {"length", 5}}, r); }), ContainsSubstring("needs a body to tap")); CHECK_THAT(failure([&] { GUI::Mcp::cad_thread(empty, {{"face", 0}}, r); }), ContainsSubstring("no body to thread")); + // No body is the design's state; a face of the wrong kind is the call's choice. + CHECK(failure_code([&] { GUI::Mcp::cad_thread(empty, {{"internal", true}, {"designation", "M5"}, {"length", 5}}, r); }) == + "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_thread(empty, {{"face", 0}}, r); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_thread(doc, {{"face", top}}, r); }) == "invalid_argument"); } TEST_CASE("a sweep along a helix keeps its profile at the same angle to the helix axis", "[Mcp][CAD]") @@ -4407,6 +4519,10 @@ TEST_CASE("split cuts a body with a plane and keeps either piece", "[Mcp][CAD]") CHECK(doc.features.size() == n); CadDocument empty; CHECK_THAT(failure([&] { GUI::Mcp::cad_split(empty, {{"plane", "XY"}}, r); }), ContainsSubstring("no body to split")); + // A plane that misses the body is where the call put it; no body is the design's state. + CHECK(failure_code([&] { GUI::Mcp::cad_split(doc, {{"plane", "XY"}, {"offset", 20}}, r); }) == "invalid_argument"); + CHECK(failure_code([&] { GUI::Mcp::cad_split(doc, {{"face", 99}}, r); }) == "invalid_argument"); + CHECK(failure_code([&] { GUI::Mcp::cad_split(empty, {{"plane", "XY"}}, r); }) == "precondition"); } } @@ -5837,6 +5953,19 @@ TEST_CASE("sketch_project adds a body's edges to the open sketch as construction CHECK_THAT(failure([&] { GUI::Mcp::cad_sketch_project(CadDocument(), tool, json::object()); }), ContainsSubstring("no source body")); CHECK_THAT(failure([&] { GUI::Mcp::cad_sketch_project(doc, tool, {{"source_body", 3}}); }), ContainsSubstring("body 3")); + CHECK(failure_code([&] { GUI::Mcp::cad_sketch_project(CadDocument(), tool, json::object()); }) == "precondition"); + CHECK(failure_code([&] { GUI::Mcp::cad_sketch_project(doc, tool, {{"source_body", 3}}); }) == "invalid_argument"); + // A vertical edge projects to a point on the XY sketch: the edge the call names is the wrong one. + int upright = -1; + for (int i = 0; i < GeometryEngine::edge_count(box) && upright < 0; ++i) { + const std::vector pts = GeometryEngine::sample_edge_world(GeometryEngine::edge_by_index(box, i)); + if (pts.size() >= 2 && (pts.front() - pts.back()).head<2>().norm() < 1e-9) upright = i; + } + REQUIRE(upright >= 0); + CHECK_THAT(failure([&] { GUI::Mcp::cad_sketch_project(doc, tool, {{"source_body", 0}, {"edges", {upright}}}); }), + ContainsSubstring("project to a point")); + CHECK(failure_code([&] { GUI::Mcp::cad_sketch_project(doc, tool, {{"source_body", 0}, {"edges", {upright}}}); }) == + "invalid_argument"); CHECK(tool.entities().size() == 9); // Construction only: the sketch has no closed loop to build from. diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index 8ac6aa99f5..4f1b9b3dd0 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include #include @@ -1295,6 +1296,42 @@ TEST_CASE("a command's targets are what its arguments name, else the selection", ContainsSubstring("object 0 has no instance 1 (it has instance 0 only)")); // Both forms of one target at once. CHECK_THROWS_AS(named_targets(model, {{"object", 1}, {"objects", json::array({0})}}, Mcp::kObjects), ToolFailure); + // An index wider than an int is out of range as given, not narrowed to another index (4294967296 to 0). + CHECK_THROWS_WITH(named_targets(model, {{"objects", json::array({std::int64_t(4294967296)})}}, Mcp::kObjects), + ContainsSubstring("object index 4294967296 is out of range")); + CHECK_THROWS_WITH(named_targets(model, {{"object", 1}, {"part", std::int64_t(4294967296)}}, kEveryKind, true), + ContainsSubstring("object 1 has no part 4294967296")); + CHECK_THROWS_WITH(named_targets(model, {{"instances", json::array({json::array({std::int64_t(4294967296), 0})})}}, Mcp::kInstances), + ContainsSubstring("object index 4294967296 is out of range")); + // An unsigned index past int64 is named as given, not as the negative number a narrowing makes of it. + CHECK_THROWS_WITH(named_targets(model, {{"objects", json::array({std::uint64_t(18446744073709551615ull)})}}, Mcp::kObjects), + ContainsSubstring("object index 18446744073709551615 is out of range")); + CHECK_THROWS_WITH(named_targets(model, {{"parts", json::array({json::array({1, std::uint64_t(18446744073709551615ull)})})}}, + Mcp::kParts), + ContainsSubstring("object 1 has no part 18446744073709551615")); + // A whole number written as a float is an index, as the schema's integer type takes it, in any form. + const auto as_floats = named_targets(model, {{"objects", json::array({0.0, 2.0})}}, Mcp::kObjects); + REQUIRE(as_floats); + CHECK(as_floats.value().objects == std::vector{0, 2}); + const auto float_part = named_targets(model, {{"parts", json::array({json::array({1.0, 1.0})})}}, Mcp::kParts); + REQUIRE(float_part); + CHECK(float_part.value().parts == std::vector>{{1, 1}}); + const auto float_object = named_targets(model, {{"object", 1.0}, {"instance", 1.0}}, kEveryKind, true); + REQUIRE(float_object); + CHECK(float_object.value().instances == std::vector>{{1, 1}}); + // A float past int64, which the schema's integer type does not take either (Mcp::is_whole_number()), is no index. + CHECK_THROWS_WITH(named_targets(model, {{"objects", json::array({9.3e18})}}, Mcp::kObjects), + ContainsSubstring("an entry of objects is an object index")); + // Each is the call's to correct, by whichever route it came. + for (const json& wrong : {json{{"objects", json::array({0, 3})}}, json{{"object", 1}, {"objects", json::array({0})}}}) { + INFO(wrong.dump()); + try { + named_targets(model, wrong, Mcp::kObjects); + FAIL("the targets were not refused"); + } catch (const ToolFailure& f) { + CHECK(f.details.value("code", std::string()) == "invalid_argument"); + } + } // With none named, the targets are the selection, and a null selection holds nothing. const auto none = named_targets(model, json::object(), kEveryKind); diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 37aac932f7..a5bc08cd24 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -42,7 +42,9 @@ #include #include +#include #include +#include #include #include #include @@ -90,6 +92,27 @@ public: } // namespace +TEST_CASE("an integer argument that no int holds is refused, not narrowed into another value", "[Mcp]") +{ + CHECK(arg_int({{"plate", 2}}, "plate", -1) == 2); + CHECK(arg_int({{"plate", 2.0}}, "plate", -1) == 2); + CHECK(arg_int(json::object(), "plate", -1) == -1); + CHECK(arg_int({{"plate", "2"}}, "plate", -1) == -1); + CHECK(arg_int({{"plate", std::numeric_limits::min()}}, "plate", 0) == std::numeric_limits::min()); + // get() would make plate 0, or instance 0, of these, which the command then accepts. + for (const json& wide : {json(std::int64_t(4294967296)), json(std::uint64_t(18446744073709551615ull)), json(-4294967297.0), + json(9.0e18), json(std::int64_t(std::numeric_limits::max()) + 1)}) { + INFO(wide.dump()); + try { + arg_int({{"instance", wide}}, "instance", 0); + FAIL("the argument was narrowed"); + } catch (const ToolFailure& f) { + CHECK_THAT(std::string(f.what()), Catch::Matchers::ContainsSubstring("instance " + wide.dump() + " is out of range")); + CHECK(f.details.value("code", std::string()) == "invalid_argument"); + } + } +} + TEST_CASE("setting values serialize the way their options read them back", "[Mcp]") { CHECK(to_config_string(json(3)) == "3"); @@ -481,24 +504,35 @@ TEST_CASE("project_export writes six formats, and project_import takes the entri TEST_CASE("action_run says where an action it cannot find is", "[Mcp][SpeedDial]") { - CHECK_THAT(unknown_action("obj_arange", NativeCommands::instance()), Catch::Matchers::ContainsSubstring("action_search")); + // The text and the code of action_run's refusal of `id`. + const auto refusal = [](const std::string& id, const CommandCatalog& catalog, bool cad_on) { + const ToolFailure refused = unknown_action(id, catalog, cad_on); + return std::make_pair(std::string(refused.what()), refused.details.value("code", std::string())); + }; + // An id no action has is the call's to correct. + const auto [typo, typo_code] = refusal("obj_arange", NativeCommands::instance(), true); + CHECK_THAT(typo, Catch::Matchers::ContainsSubstring("action_search")); + CHECK(typo_code == "invalid_argument"); #ifdef SLIC3R_CAD // A Design tab action, by its id or its key, while it is not shown: in a run with the CAD feature on at startup - // tool_call runs its command from any tab, and in one with it off there is no such command. + // tool_call runs its command from any tab (wrong_mode, the id being right), and in one with it off there is no such + // command (design_unavailable). for (const bool cad : {true, false}) { CommandCatalog catalog; NativeCommands::register_all_commands(catalog, {cad}); catalog.seal(); for (const std::string id : {"orca_command:shell:orca", "shell"}) { INFO(id << (cad ? ", the CAD feature on" : ", the CAD feature off")); - const std::string why = unknown_action(id, catalog); + const auto [why, code] = refusal(id, catalog, cad); if (cad) { CHECK_THAT(why, Catch::Matchers::ContainsSubstring("while the Design tab is shown")); CHECK_THAT(why, Catch::Matchers::ContainsSubstring("tool_call {\"tool\": \"shell\"}")); + CHECK(code == "wrong_mode"); } else { CHECK(why == id + " is a Design tab action, and the CAD feature was off when OrcaSlicer started: a person " "turns it on in Preferences > Features and restarts OrcaSlicer, or starts it with " "--cad"); + CHECK(code == "design_unavailable"); } } // A folded item's action names the call of its command that runs it; with the feature off at startup, there is @@ -506,15 +540,23 @@ TEST_CASE("action_run says where an action it cannot find is", "[Mcp][SpeedDial] const std::string folded = "orca_command:sk_array:orca"; INFO(folded << (cad ? ", the CAD feature on" : ", the CAD feature off")); if (cad) - CHECK_THAT(unknown_action(folded, catalog), + CHECK_THAT(refusal(folded, catalog, cad).first, Catch::Matchers::ContainsSubstring("tool_call {\"tool\": \"sketch_pattern\", \"args\": {\"type\": \"linear\"}}")); else - CHECK(unknown_action(folded, catalog) == folded + " is a Design tab action, and the CAD feature was off when OrcaSlicer " - "started: a person turns it on in Preferences > Features and restarts " - "OrcaSlicer, or starts it with --cad"); + CHECK(refusal(folded, catalog, cad).first == folded + " is a Design tab action, and the CAD feature was off when " + "OrcaSlicer started: a person turns it on in Preferences > " + "Features and restarts OrcaSlicer, or starts it with --cad"); // A Design command with no Speed Dial action is refused as any unknown action is. - CHECK_THAT(unknown_action("orca_command:describe_design:orca", catalog), Catch::Matchers::ContainsSubstring("action_search")); + CHECK_THAT(refusal("orca_command:describe_design:orca", catalog, cad).first, Catch::Matchers::ContainsSubstring("action_search")); } + // The CAD feature turned off while the app runs drops every Design action, though their commands stay in the + // catalog: the action is right, and a person turns the feature back on. + CommandCatalog with_cad; + NativeCommands::register_all_commands(with_cad, {true}); + with_cad.seal(); + const auto [off_now, off_now_code] = refusal("shell", with_cad, false); + CHECK_THAT(off_now, Catch::Matchers::ContainsSubstring("the CAD feature is off")); + CHECK(off_now_code == "design_unavailable"); #endif } @@ -807,7 +849,13 @@ TEST_CASE("tool_search reads one inventory", "[Mcp]") const json described = search_commands(catalog, {{"tool", "measure_action"}}); CHECK(described["listed"] == false); CHECK(described["input_schema"]["properties"].contains("a")); - CHECK_THROWS_AS(search_commands(catalog, {{"tool", "measure_nothing"}}), ToolFailure); + // A name no command has is the call's argument to correct. + try { + search_commands(catalog, {{"tool", "measure_nothing"}}); + FAIL("an unknown tool was not refused"); + } catch (const ToolFailure& f) { + CHECK(f.details.value("code", std::string()) == "invalid_argument"); + } // group narrows the names and the matches, in any case, a source's commands included. CHECK(search_commands(catalog, json::object())["names"] == json::array({"measure_bed", "measure_action", "plugin.fixture.measure"})); @@ -823,6 +871,7 @@ TEST_CASE("tool_search reads one inventory", "[Mcp]") } catch (const ToolFailure& f) { CHECK(std::string(f.what()).find("Unknown group: commands") != std::string::npos); CHECK(f.details["groups"] == json::array({"Plugins", "View"})); + CHECK(f.details.value("code", std::string()) == "invalid_argument"); } } diff --git a/tools/mcp/test-entries/design.md b/tools/mcp/test-entries/design.md index 75f4023461..e5638a873e 100644 --- a/tools/mcp/test-entries/design.md +++ b/tools/mcp/test-entries/design.md @@ -482,7 +482,7 @@ named after the rung, runs `recover()` and goes on to the next rung. `describe_design` error added; Scale artwork and Edit: undo depth +1 on Confirm, +0 on Cancel; `nothing_open` (no modal or modeless dialog, no sketch). - Edit cards: `feature_edit refs` sets the Fillet's `refs.edges` to the id `body_describe {before}` gave, in one - undo step, refuses stale ids with `-32010`, and undo restores it. The repick rungs click on the canvas through + undo step, refuses stale ids with `stale_ids`, and undo restores it. The repick rungs click on the canvas through the calibrated map, an edge 1 mm in on the top face it bounds, since seen from above the edge is the block's outline and a click on the line, rounded to a whole pixel, can land just outside the block. They require the exact edge or face id (`plane_face`, `plane_face_body`), the Hole's plane normal and origin to 1e-6 and @@ -493,8 +493,8 @@ named after the rung, runs `recover()` and goes on to the next rung. calls; `sketch_normal` looks along the XZ normal (cosine ≥ 0.999). - select, select_loops: `selection.id` for each kind (`body_solid`, `face_planar`, `edge_str`, `vertex`, `sk_loop`, `none`); vertex point to 1e-6; renames through the row editor show in `describe_design`; `feature_delete` and - its undo; `busy` texts for `feature_edit {}` and `sketch_constrain_selected`; refusals carrying `-32002` or - `-32010` with the selection kept; `applies` true for `fillet`, `delete_face` and `zoom_to_selection`; after + its undo; `busy` texts for `feature_edit {}` and `sketch_constrain_selected`; refusals carrying `design_busy` or + `stale_ids` with the selection kept; `applies` true for `fillet`, `delete_face` and `zoom_to_selection`; after `zoom_to_selection` the camera's `look_at` is loop 1's centre (1e-3); three canvas screenshots (face, edge, vertex selected) differ from the nothing-selected one and from each other. - confirm and cancel: `was` (`card`, `sketch`, `plane_pick`, `text`, `insert`), `ok`, `feature` index, `open`; diff --git a/tools/mcp/test_cad_commands.py b/tools/mcp/test_cad_commands.py index 8506d2ea8e..ee05a6daa1 100644 --- a/tools/mcp/test_cad_commands.py +++ b/tools/mcp/test_cad_commands.py @@ -45,7 +45,7 @@ surface_revolve_flip selects a sketch's loop with select_geometry, opens the Sur surface_revolve {}, ticks its Flip and confirms: the feature keeps the Flip. The refs rungs work on a block whose top edge is filleted and which is then shelled, renumbering its edges. feature_edit_refs re-points the Fillet with feature_edit's refs at an edge read with body_describe {before}: the Fillet -rounds it, in one undo step that undo takes back, and ids read at a generation the edit rebuilt are refused (-32010). +rounds it, in one undo step that undo takes back, and ids read at a generation the edit rebuilt are refused (stale_ids). text_edit changes a Text feature's words and height with feature_edit: two regions, 20 mm high, one undo step. edit_repick opens the Fillet's card from its row, picks another top edge in the view and confirms: the Fillet names that edge by its id in the model before it, and edit_repick_placed does so with the block placed off where the model @@ -1017,7 +1017,7 @@ def rung_select(): held = gui.cad("describe_design")["selection"] for args in ({"body": 0, "face": top, "generation": gen}, {}): why = refused("select_geometry", **args) - gui.check(f"select: {args} is refused as busy with the card", "-32002" in why and "a feature card is open" in why, + gui.check(f"select: {args} is refused as busy with the card", "design_busy" in why and "a feature card is open" in why, why) gui.check("select: the card's selection stays", gui.cad("describe_design")["selection"] == held, [held, gui.cad("describe_design")["selection"]]) @@ -1025,7 +1025,7 @@ def rung_select(): gui.cad("sketch_create", plane="XY") for args in ({"body": 0}, {}): why = refused("select_geometry", **args) - gui.check(f"select: {args} is refused as busy with the sketch", "-32002" in why and "a sketch is open" in why, why) + gui.check(f"select: {args} is refused as busy with the sketch", "design_busy" in why and "a sketch is open" in why, why) gui.cad("sketch_cancel") # A refused call changes nothing. @@ -1039,7 +1039,7 @@ def rung_select(): gui.check(f"select: {what} is refused", why != "", why) gui.check(f"select: {what}, refused, leaves the face selected", selected()[0] == "face_planar", selected()) why = refused("select_geometry", body=0, face=top, generation=gen + 1) - gui.check("select: a stale generation is refused", "-32010" in why, why) + gui.check("select: a stale generation is refused", "stale_ids" in why, why) # The menu items that take what is selected apply to it. select(body=0, edges=[edge], generation=gen) @@ -1174,7 +1174,7 @@ def rung_feature_edit_refs(): r.get("ok") is True and edges == [edge["id"]], [r, edges]) gui.check("feature_edit_refs: one undo step", undo_depth() == depth + 1, f"{depth} -> {undo_depth()}") why = refused("feature_edit", feature=fillet, refs={"edges": [rounded]}, generation=along_x["generation"]) - gui.check("feature_edit_refs: ids read before the edit rebuilt the model are refused as stale", "-32010" in why, why) + gui.check("feature_edit_refs: ids read before the edit rebuilt the model are refused as stale", "stale_ids" in why, why) gui.client.call_command("undo", history="design") edges = gui.cad("feature_describe", feature=fillet)["refs"]["edges"] gui.check("feature_edit_refs: one undo puts the Fillet back on its edge", edges == [rounded], edges) @@ -1691,7 +1691,7 @@ def rung_place(): gui.cad("sketch_create", plane="XY") why = refused("body_place", body=0, move=[1, 0, 0]) - gui.check("place: with a sketch open it is refused as busy", "-32002" in why and "a sketch is open" in why, why) + gui.check("place: with a sketch open it is refused as busy", "design_busy" in why and "a sketch is open" in why, why) gui.cad("sketch_cancel")