From fece418ae0c4ef41fdf56480c81cdbb5eec47155 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Sat, 14 Nov 2026 22:55:47 +0800 Subject: [PATCH] Make the automation runtime its own subsystem, with MCP as one front end Everything that drives OrcaSlicer by command (the dispatch of the command catalog, jobs, the journal, replays, Python scripts, recordings) lived inside the MCP server's service class. So Action Replay, the Run Script panel, a plugin's tool call, a person's recording and a run from the command line each had to start "the MCP service", with all of its GUI hooks, although none of them needs a server or an agent. The automation runtime is now a subsystem of its own. It starts the first time a front end asks for it and knows none of them. The MCP endpoint (HTTP, the protocol, the token, the discovery file, the takeover of a port another window holds) is one front end beside the others, opened and closed without stopping what the others run. The widget inspector, menu capture and ImGui item recording are turned on only by a front end that drives the GUI, so a person's recording or long command does not carry them. The part of the runtime that needs no GUI is the library libslic3r_automation, built without wxWidgets and tested by its own suite, automation_tests. A wx dependency in it fails to build, and its tests no longer link the GUI library or the embedded Python. The command line has one option set for this: --run FILE runs a replay or a Python script once the GUI is ready, with --outputdir for its files, and --unrestricted-scripts and --cad turn their settings on for one run without saving them. --mcp-run, --mcp-run-out and --mcp-token are gone; the scripts setting is python_scripts_unrestricted and a session's output folder is /automation/out. get_app_state reports ready and version at the top level, and its mcp block describes the endpoint only. No change to slicing output. --- docs/HLSD/design-tab.md | 4 +- docs/HLSD/mcp-server.md | 463 +++-- docs/HLSD/plugin-permissions.md | 9 +- localization/i18n/OrcaSlicer.pot | 51 +- .../web/dialog/ActionReplay/action_replay.js | 6 +- resources/web/dialog/RunScript/run_script.js | 2 +- scripts/flatpak/com.orcaslicer.OrcaSlicer.yml | 2 +- src/CMakeLists.txt | 2 + src/OrcaSlicer.cpp | 30 +- src/libslic3r/PrintConfig.cpp | 38 +- src/libslic3r_automation/CMakeLists.txt | 69 + src/slic3r/CMakeLists.txt | 42 +- src/slic3r/GUI/ActionIds.hpp | 15 + src/slic3r/GUI/ActionRegistry.cpp | 1 + src/slic3r/GUI/ActionRegistry.hpp | 8 - src/slic3r/GUI/ActionReplayDialog.cpp | 52 +- src/slic3r/GUI/ActionReplayDialog.hpp | 8 +- src/slic3r/GUI/AuiMgr.cpp | 2 +- src/slic3r/GUI/BindDialog.cpp | 2 +- src/slic3r/GUI/CommandCatalog.cpp | 11 +- src/slic3r/GUI/CommandCatalog.hpp | 12 +- src/slic3r/GUI/CommandTypes.hpp | 138 ++ src/slic3r/GUI/ConnectPrinter.cpp | 2 +- src/slic3r/GUI/GUI_App.cpp | 197 +- src/slic3r/GUI/GUI_App.hpp | 62 +- src/slic3r/GUI/GUI_Init.cpp | 9 +- src/slic3r/GUI/GUI_Init.hpp | 3 + src/slic3r/GUI/ImGuiWrapper.hpp | 12 +- src/slic3r/GUI/InstanceCheck.cpp | 4 +- src/slic3r/GUI/InstanceCheck.hpp | 3 +- src/slic3r/GUI/MainFrame.cpp | 17 +- src/slic3r/GUI/Mcp/AutomationRuntime.cpp | 581 ++++++ src/slic3r/GUI/Mcp/AutomationRuntime.hpp | 227 +++ src/slic3r/GUI/Mcp/AutomationRuntimePtr.hpp | 19 + src/slic3r/GUI/Mcp/FollowedThreads.cpp | 88 + src/slic3r/GUI/Mcp/FollowedThreads.hpp | 52 + src/slic3r/GUI/Mcp/JobRegistry.cpp | 34 +- src/slic3r/GUI/Mcp/JobRegistry.hpp | 24 +- src/slic3r/GUI/Mcp/LaunchRun.cpp | 138 ++ src/slic3r/GUI/Mcp/LaunchRun.hpp | 16 + src/slic3r/GUI/Mcp/McpArguments.cpp | 4 +- src/slic3r/GUI/Mcp/McpArguments.hpp | 76 + src/slic3r/GUI/Mcp/McpCore.cpp | 36 +- src/slic3r/GUI/Mcp/McpCore.hpp | 32 +- src/slic3r/GUI/Mcp/McpEndpoint.cpp | 244 +++ src/slic3r/GUI/Mcp/McpEndpoint.hpp | 90 + src/slic3r/GUI/Mcp/McpJournal.cpp | 4 +- src/slic3r/GUI/Mcp/McpJournal.hpp | 3 +- src/slic3r/GUI/Mcp/McpOptions.hpp | 16 +- src/slic3r/GUI/Mcp/McpPaths.cpp | 24 +- src/slic3r/GUI/Mcp/McpPaths.hpp | 6 +- src/slic3r/GUI/Mcp/McpPersonContext.cpp | 24 +- src/slic3r/GUI/Mcp/McpPersonContext.hpp | 28 +- src/slic3r/GUI/Mcp/McpPersonRun.cpp | 74 +- src/slic3r/GUI/Mcp/McpPersonRun.hpp | 44 +- src/slic3r/GUI/Mcp/McpPluginCaller.cpp | 46 +- src/slic3r/GUI/Mcp/McpPluginCaller.hpp | 10 + src/slic3r/GUI/Mcp/McpProtocol.cpp | 3 +- src/slic3r/GUI/Mcp/McpProtocol.hpp | 6 +- src/slic3r/GUI/Mcp/McpRecorder.cpp | 74 +- src/slic3r/GUI/Mcp/McpRecorder.hpp | 25 +- src/slic3r/GUI/Mcp/McpReplay.cpp | 2 +- src/slic3r/GUI/Mcp/McpReplay.hpp | 2 +- src/slic3r/GUI/Mcp/McpReplaySummary.cpp | 28 +- src/slic3r/GUI/Mcp/McpReplaySummary.hpp | 15 +- src/slic3r/GUI/Mcp/McpServerInfo.cpp | 70 + src/slic3r/GUI/Mcp/McpService.cpp | 1028 ---------- src/slic3r/GUI/Mcp/McpService.hpp | 298 --- src/slic3r/GUI/Mcp/McpServicePtr.hpp | 19 - src/slic3r/GUI/Mcp/McpStdioBridge.cpp | 18 +- src/slic3r/GUI/Mcp/McpStdioBridge.hpp | 12 +- src/slic3r/GUI/Mcp/McpTools.hpp | 31 +- src/slic3r/GUI/Mcp/McpToolsActions.cpp | 4 +- src/slic3r/GUI/Mcp/McpToolsApi.cpp | 3 +- src/slic3r/GUI/Mcp/McpToolsApp.cpp | 51 +- src/slic3r/GUI/Mcp/McpToolsCad.cpp | 19 +- src/slic3r/GUI/Mcp/McpToolsCad.hpp | 2 +- src/slic3r/GUI/Mcp/McpToolsCommon.cpp | 2 +- src/slic3r/GUI/Mcp/McpToolsConfig.cpp | 3 +- src/slic3r/GUI/Mcp/McpToolsLayers.cpp | 2 +- src/slic3r/GUI/Mcp/McpToolsProject.cpp | 17 +- src/slic3r/GUI/Mcp/McpToolsPython.cpp | 127 +- src/slic3r/GUI/Mcp/McpToolsRecord.cpp | 44 +- src/slic3r/GUI/Mcp/McpToolsReplay.cpp | 37 +- src/slic3r/GUI/Mcp/McpToolsScene.cpp | 21 +- src/slic3r/GUI/Mcp/McpToolsUi.cpp | 331 +-- src/slic3r/GUI/Mcp/McpToolsView.cpp | 22 +- src/slic3r/GUI/Mcp/McpTypes.hpp | 212 -- src/slic3r/GUI/Mcp/ModalTracker.cpp | 3 +- src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp | 37 +- src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp | 17 +- src/slic3r/GUI/Mcp/ScreenCapture.cpp | 2 +- src/slic3r/GUI/Mcp/UiInspector.cpp | 44 +- src/slic3r/GUI/Mcp/UiInspector.hpp | 13 +- src/slic3r/GUI/Mcp/UiInvoker.cpp | 2 +- src/slic3r/GUI/Mcp/UiInvoker.hpp | 2 +- src/slic3r/GUI/Mcp/UiRefs.cpp | 2 +- src/slic3r/GUI/Mcp/VideoOverlay.cpp | 4 +- src/slic3r/GUI/Mcp/WebPages.cpp | 3 +- src/slic3r/GUI/Mcp/WebPages.hpp | 9 +- src/slic3r/GUI/Mcp/WindowNames.hpp | 18 + src/slic3r/GUI/NativeCommands.cpp | 83 +- src/slic3r/GUI/NativeCommands.hpp | 4 +- src/slic3r/GUI/Preferences.cpp | 79 +- src/slic3r/GUI/ReleaseNote.cpp | 2 +- src/slic3r/GUI/RunScriptPanel.cpp | 49 +- src/slic3r/GUI/RunScriptPanel.hpp | 12 +- src/slic3r/GUI/SyntheticInput.hpp | 4 +- src/slic3r/plugin/PluginAuditManager.hpp | 2 +- src/slic3r/plugin/PythonScriptRunner.hpp | 2 +- tests/AGENTS.md | 4 +- tests/CMakeLists.txt | 1 + tests/automation/CMakeLists.txt | 26 + tests/automation/automation_test_utils.hpp | 199 ++ tests/automation/automation_tests.cpp | 1 + tests/automation/test_command_catalog.cpp | 175 ++ tests/automation/test_mcp_core.cpp | 1815 +++++++++++++++++ .../test_mcp_http.cpp | 0 tests/automation/test_mcp_paths.cpp | 45 + tests/automation/test_mcp_protocol.cpp | 576 ++++++ .../test_mcp_replay.cpp | 4 +- .../test_mcp_replay_summary.cpp | 55 +- .../test_mcp_setup.cpp | 0 .../test_mcp_token.cpp | 0 tests/data/command_catalog.json | 2 +- tests/libslic3r/test_config.cpp | 13 + tests/slic3rutils/CMakeLists.txt | 5 - tests/slic3rutils/test_command_catalog.cpp | 235 +-- tests/slic3rutils/test_mcp_cad.cpp | 19 +- tests/slic3rutils/test_mcp_config.cpp | 45 +- tests/slic3rutils/test_mcp_core.cpp | 1730 +--------------- tests/slic3rutils/test_mcp_protocol.cpp | 591 +----- tests/slic3rutils/test_mcp_recording.cpp | 3 +- tests/slic3rutils/test_mcp_results.cpp | 14 +- tests/slic3rutils/test_mcp_scene.cpp | 98 +- tests/slic3rutils/test_mcp_tools.cpp | 7 +- tests/slic3rutils/test_mcp_ui.cpp | 12 +- tests/slic3rutils/test_mcp_web.cpp | 3 +- tests/slic3rutils/test_operations.cpp | 1 - tools/mcp/README.md | 48 +- tools/mcp/orca_mcp.py | 32 +- tools/mcp/smoke_test.json | 2 +- tools/mcp/test_command_line.py | 473 +++++ tools/mcp/test_orca_mcp_attach.py | 9 +- tools/mcp/test_plugin_tools.py | 8 +- tools/mcp/test_runtime_lifecycle.py | 471 +++++ tools/mcp/tests/replay_basic.json | 4 +- 147 files changed, 7575 insertions(+), 5288 deletions(-) create mode 100644 src/libslic3r_automation/CMakeLists.txt create mode 100644 src/slic3r/GUI/ActionIds.hpp create mode 100644 src/slic3r/GUI/CommandTypes.hpp create mode 100644 src/slic3r/GUI/Mcp/AutomationRuntime.cpp create mode 100644 src/slic3r/GUI/Mcp/AutomationRuntime.hpp create mode 100644 src/slic3r/GUI/Mcp/AutomationRuntimePtr.hpp create mode 100644 src/slic3r/GUI/Mcp/FollowedThreads.cpp create mode 100644 src/slic3r/GUI/Mcp/FollowedThreads.hpp create mode 100644 src/slic3r/GUI/Mcp/LaunchRun.cpp create mode 100644 src/slic3r/GUI/Mcp/LaunchRun.hpp create mode 100644 src/slic3r/GUI/Mcp/McpArguments.hpp create mode 100644 src/slic3r/GUI/Mcp/McpEndpoint.cpp create mode 100644 src/slic3r/GUI/Mcp/McpEndpoint.hpp create mode 100644 src/slic3r/GUI/Mcp/McpPluginCaller.hpp create mode 100644 src/slic3r/GUI/Mcp/McpServerInfo.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpService.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpService.hpp delete mode 100644 src/slic3r/GUI/Mcp/McpServicePtr.hpp delete mode 100644 src/slic3r/GUI/Mcp/McpTypes.hpp create mode 100644 src/slic3r/GUI/Mcp/WindowNames.hpp create mode 100644 tests/automation/CMakeLists.txt create mode 100644 tests/automation/automation_test_utils.hpp create mode 100644 tests/automation/automation_tests.cpp create mode 100644 tests/automation/test_command_catalog.cpp create mode 100644 tests/automation/test_mcp_core.cpp rename tests/{slic3rutils => automation}/test_mcp_http.cpp (100%) create mode 100644 tests/automation/test_mcp_paths.cpp create mode 100644 tests/automation/test_mcp_protocol.cpp rename tests/{slic3rutils => automation}/test_mcp_replay.cpp (99%) rename tests/{slic3rutils => automation}/test_mcp_replay_summary.cpp (89%) rename tests/{slic3rutils => automation}/test_mcp_setup.cpp (100%) rename tests/{slic3rutils => automation}/test_mcp_token.cpp (100%) create mode 100644 tools/mcp/test_command_line.py create mode 100644 tools/mcp/test_runtime_lifecycle.py diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 9d2a4eaea3..316deb570d 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -403,8 +403,8 @@ its work is split into a function both callers share, and the command calls that arguments instead of driving the widgets. An agent's call needs the MCP server on (`--mcp`, or Preferences), and every command, a person's tile -included, needs the CAD feature on (Preferences > Features). The catalog 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; +included, needs the CAD feature on (Preferences > Features, or `--cad` for one run). The catalog 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 `get_app_state`'s `cad_note` does. Turned off while OrcaSlicer runs, the tab stays until the restart, but the Speed Dial has no tile of it. A diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 3a7e3cd689..93217cc767 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -8,12 +8,13 @@ files, picks presets, changes settings, clicks through the GUI and slices. It al screenshots before and after a fix and replays the steps from a replay file. A user can drive OrcaSlicer from Claude Code, Codex, Cursor or Claude Desktop. -The server runs inside the GUI process, because most of what an agent reproduces is GUI -behaviour, and reuses the Speed Dial catalog, so a feature added to the palette reaches agents, -replays and scripts too. It is off by default; until it is first turned on, `McpService` does not exist, so -there is no thread, socket, modal-dialog hook, ImGui item recording or synthetic input state. The code is in -`src/slic3r/GUI/Mcp/`; the protocol, transport, threading core, replay runner and operation logic -don't use wx, so they can be unit-tested. +The server runs inside the GUI process, because most of what an agent reproduces is GUI behaviour, and +reuses the Speed Dial catalog, so a feature added to the palette reaches agents, replays and scripts +too. It is off by default. The code is in `src/slic3r/GUI/Mcp/`. The core, which uses no wx (the command +catalog's type, the dispatch core, the hand-off to the UI thread, the job registry, the followed threads, the +journal, the paths, argument checking, the protocol and HTTP transport, what the server says of itself, the +replay model, Action Replay's summary of a replay, the setup a client copies, the stdio bridge and the token), +is the library `libslic3r_automation`, so it is unit-tested without the GUI (see Testing). ``` MCP client ──POST /mcp──▶ McpHttpServer ──▶ McpProtocol ──▶ McpCore ──▶ UiInvoker ──▶ UI thread @@ -21,9 +22,17 @@ stdio client ──▶ orca-slicer --mcp-stdio ──┘ │ JobRegistry, Journal ``` -`McpService`, owned by `GUI_App`, owns all of it except the bridge, plus the `ModalTracker`. The -commands it serves are the process's command catalog (`NativeCommands::instance()`, see Tool catalog), -which startup builds without a service. +Two classes, both owned by `GUI_App`, hold all of it except the bridge. `AutomationRuntime` runs +commands for every front end: the MCP endpoint, Action Replay, the Run Script panel, plugins, a person's +commands from the Speed Dial and the command line's run. It owns the dispatch core (`McpCore`), the +jobs, the journal, the UI invoker, the `ModalTracker`, the recorder and the scopes a run, a plugin or a +client leaves state in. `McpEndpoint` is the MCP server and nothing else: the HTTP server, the protocol, +the request gate, the token, the discovery file and the takeover of a port another window holds. It +holds the runtime by reference and reaches its core through the protocol; the runtime does not know it. +Neither exists until something needs it: the runtime until a front end first asks for it, the endpoint +until the server is first turned on. Until then there is no thread, socket, modal-dialog hook, ImGui +item recording or synthetic input state. The commands the runtime runs are the process's command catalog +(`NativeCommands::instance()`, see Tool catalog), which startup builds without either. ## Transport @@ -107,10 +116,10 @@ load. The bearer token is 32 random bytes as 64 hex characters in `/mcp/token`: directory 0700 and file created 0600 with `O_CREAT|O_EXCL` on POSIX, the per-user ACL of `%APPDATA%` on Windows. -It stays out of AppConfig, whose writes and backups use default permissions. `ORCA_MCP_TOKEN` -(preferred, as it stays out of the process list) or `--mcp-token` overrides it for one run; -`get_app_state.mcp.token_source` says which is in force. Every start of the endpoint reads the file, so -deleting it and turning the server off and on in Preferences issues a new token. While +It stays out of AppConfig, whose writes and backups use default permissions. `ORCA_MCP_TOKEN` overrides +it for one run, and stays out of the process list; `get_app_state.mcp.token_source` (`file` or +`ORCA_MCP_TOKEN`) says which is in force. Every start of the endpoint reads the file, so deleting it and +turning the server off and on in Preferences issues a new token. While serving, `/mcp/server.json` holds `{url, port, pid, version, token}` with the token in use, so the stdio bridge and the harness connect without the launch environment. It is written owner-only via an exclusive temporary file and a rename (`write_private_file()`), and removed on @@ -119,72 +128,105 @@ file, and one that stops must not hide another's server from the stdio bridge. ## Lifecycle -`GUI_App::on_init_inner()` starts the service once AppConfig is loaded. That is before the first -startup dialog, such as the TLS prompt or the setup wizard, so an agent can answer those dialogs. -`--mcp` or the `mcp_enabled` preference opens the endpoint, while `--mcp-run` alone, or opening -Action Replay or the Run Script panel, only builds the catalog. `get_app_state.ready` stays false until `post_init()` calls `mark_ready()`, the Prepare -canvas has loaded OpenGL and the main window has built its tab pages, and tools that need the main -window fail with "still starting". Starting on Home, the canvas loads OpenGL at idle after -`post_init()` (MainFrame's GL prebuild), and before that a 3MF save would draw its thumbnail with no -GL functions loaded. The same idle queue builds the tab pages (`MainFrame::prebuild_pending()`); a -page's web view registers its `wx` script message handler with a script it waits for in a nested -loop, and on GTK calls that came in meanwhile have left that wait unfinished for good, so that no web -view made afterwards gets `window.wx` and a dialog page's own buttons do nothing. So `mark_ready()` -polls every 100 ms until both are done. A hidden canvas that can't get a GL context loads OpenGL on -its first draw instead, and the pages build only while no input arrives, so after 10 s ready no -longer waits for either. Becoming ready also starts the `--mcp-run` file. Notifications don't depend on this: one pushed or updated before the first -ImGui frame has built the font waits for its first render to measure its text. +`GUI_App::on_init_inner()` opens the endpoint once AppConfig is loaded when `--mcp`, `--mcp-port` or the +`mcp_enabled` preference asks for it (`GUI_App::open_mcp_endpoint()`, which starts the runtime first). That is +before the first startup dialog, such as the TLS prompt or the setup wizard, so an agent can answer those +dialogs. `--run` alone starts the runtime without the endpoint, and so do Action Replay, the Run +Script panel, a plugin's tool call and a person's recording or long command when the server is off. Each +front end gets the runtime from `GUI_App::automation()`, which starts it on first use and returns +nullptr while OrcaSlicer closes or the runtime stops; `automation_if_started()` returns it, stopping or +not, and never starts it. `get_app_state.ready` stays false until `post_init()` calls `mark_ready()`, +the Prepare canvas has loaded OpenGL and the main window has built its tab pages, and tools that need +the main window fail with "still starting". Starting on Home, the canvas loads OpenGL at idle after +`post_init()` (MainFrame's GL prebuild), and before that a 3MF save would draw its thumbnail with no GL +functions loaded. The same idle queue builds the tab pages (`MainFrame::prebuild_pending()`); a page's +web view registers its `wx` script message handler with a script it waits for in a nested loop, and on +GTK calls that came in meanwhile have left that wait unfinished for good, so that no web view made +afterwards gets `window.wx` and a dialog page's own buttons do nothing. So `mark_ready()` polls every +100 ms until both are done. A hidden canvas that can't get a GL context loads OpenGL on its first draw +instead, and the pages build only while no input arrives, so after 10 s ready no longer waits for +either. Becoming ready also starts the `--run` file, which `start_launch_run()` registers with +`on_ready()`. Notifications don't depend on this: one pushed or updated before the first ImGui frame has +built the font waits for its first render to measure its text. -The service stops, idempotently, at the start of `MainFrame::shutdown()` when the app closes -(before panels are destroyed) and on `wxEVT_END_SESSION` (after which macOS calls `exit()`). -`McpService::stop()` wakes every waiting call with "shutting down" (`UiInvoker::shutdown()`, -`JobRegistry::wake_all()`), refuses new calls, closes the endpoint and removes the discovery file, -drops every auto-answer rule, clears `SyntheticInput`, removes the menu capture and turns ImGui -recording off. It frees -nothing: a call may still be on the UI thread's stack inside a nested event loop, using the -inspector and the modal tracker, and job and request threads may still be returning. -A stopped service never starts again. `GUI_App` holds the service in an `McpServicePtr`, whose -deleter (`McpServiceDeleter`) is the only way to destroy one: the destructor is private. The -deleter stops the service, waits with `McpService::drain()` until no request, call or job thread -is inside it, and frees it; a call that never returns would make freeing a crash, so after 10 s the -service is left in place instead. `GUI_App::destroy_mcp_service()` runs it from `OnExit()`, and -from `CleanUp()` after a failed initialization, outside any event loop, so no closure can be -running. HTTP request threads reach the protocol through a shared `RequestGate`, which `drain()` -closes, so a late request gets 503 rather than a freed object. `McpCore`'s own destructor waits for -every call and job thread to leave, however long that takes; its owner drains first, so it returns -at once. +A front end asks for what it uses. `AutomationRuntime::start()` brings up the dispatch core, the jobs, +the UI invoker, the modal tracker, the recorder and the list of presses held on web pages: all that a +person's recording or a long command a person picked from the Speed Dial needs, the recorder drawing the +modal dialogs from the tracker's stack. The GUI instruments are the UI inspector behind `list_widgets` +and the input tools, the menu capture, ImGui item recording and, on Wayland, the window-state hooks +(`track_window_states()`). `enable_gui_instruments()` turns them on, once, for the front ends that drive +the GUI: `McpEndpoint::open()` when it opens, Action Replay as it opens, the Run Script panel on its +page's `init`, the command line's run (`start_launch_run()`) and a plugin's call as the UI thread admits +it. A person's pick from the Speed Dial (`PersonContext`) does not. The log reads `Automation runtime +started` as the runtime starts and `Automation GUI instruments on` when they go on, so a session that +began with a person's recording shows the second line only once something drives the GUI. ImGui items +are recorded as a frame draws them, so turning the instruments on asks the shown 3D view for a frame. +`AutomationRuntime::inspector()` turns them on itself if no front end has, so a command never finds the +inspector missing. + +Both stop, idempotently, at the start of `MainFrame::shutdown()` when the app closes (before panels are +destroyed) and on `wxEVT_END_SESSION` (after which macOS calls `exit()`): `GUI_App::stop_automation()` +closes the endpoint, then stops the runtime, and does nothing for one that was never made. +`McpEndpoint::close()` closes the socket, stops the takeover retries, removes the discovery file and +closes the runtime's client scope; requests in flight run on. `AutomationRuntime::stop()` wakes every +waiting call with "shutting down" (`UiInvoker::shutdown()`, `JobRegistry::wake_all()`), refuses new +calls, joins the threads of the followed calls (Threading), drops every auto-answer rule, clears +`SyntheticInput` and, when the GUI instruments are on, removes the menu capture and turns ImGui +recording off; nothing turns them on again. Neither frees anything: a call may still be on the UI +thread's stack inside a nested event loop, using the inspector and the modal tracker, and job and +request threads may still be returning. A stopped runtime never starts again. + +`GUI_App` holds the runtime in an `AutomationRuntimePtr`, whose deleter (`AutomationRuntimeDeleter`) is +the only way to destroy one: the destructor is private. The deleter stops the runtime, waits with +`AutomationRuntime::drain()` until no lease is held and no call or job thread is inside the core, and +frees it; a call that never returns would make freeing a crash, so after 10 s the runtime is left in +place instead, and the log says "Automation runtime: a call did not return; leaving it in place". The +endpoint is held in a `std::unique_ptr` declared after the runtime, so it is destroyed first whichever +way `GUI_App` goes. `GUI_App::destroy_automation()` runs from `OnExit()`, and from `CleanUp()` after a +failed initialization, outside any event loop, so no closure can be running: it drops the Run Script +panel, calls `stop_automation()`, then waits up to 10 s with `McpEndpoint::drain()` for the request +threads to leave the protocol. HTTP request threads reach the protocol through a shared `RequestGate`, +which `drain()` closes, so a late request gets 503 rather than a freed object. When a request is still +inside after 10 s, both are left in place, since the protocol reaches the runtime's core, and the log +says so; otherwise the endpoint is freed, then the runtime goes through its deleter. `McpCore`'s own +destructor waits for every call and job thread to leave, however long that takes; its owner drains +first, so it returns at once. A language change runs `MainFrame::shutdown()` from `recreate_GUI()`, which only suspends the -service: the transport stays up, the UI generation is bumped so every GUI ref goes stale, UI calls +runtime: the endpoint stays open, the UI generation is bumped so every GUI ref goes stale, UI calls fail with a request to retry, and `ready` is false until `recreate_GUI()` resumes it. A UI closure posted before the rebuild refuses to run after it ("not run, safe to retry"). Several OrcaSlicer windows may run at once, and those that share a configuration folder share the -`mcp_enabled` preference and the port. The bind is exclusive (`SO_REUSEADDR` stays off on -Windows, and POSIX refuses a second listener), so the first window to start serves and agents, -over HTTP or stdio, reach it. A later window that wants to serve finds the port taken by the -process the discovery file names (`discovery_held_by_other()`): it reports no error, Preferences -says another window is serving agents, and `GUI_App` tries the port every 3 s, so when the serving -window closes, one of the others takes over and writes the discovery file. A window that cannot -bind for any other reason reports it and stops trying. Windows meant to serve side by side need -their own configuration folders (`--datadir`) or `--mcp-port`; agents then pick one by its URL, or -the stdio bridge by `--datadir`. The server makes no attempt to route between windows. +`mcp_enabled` preference and the port. The bind is exclusive (`SO_REUSEADDR` stays off on Windows, and +POSIX refuses a second listener), so the first window to start serves and agents, over HTTP or stdio, +reach it. A later window that wants to serve finds the port taken by the process the discovery file +names (`discovery_held_by_other()`): it reports no error, Preferences says another window is serving +agents, and the endpoint tries the port every 3 s, so when the serving window closes, one of the others +takes over and writes the discovery file. A window that cannot bind for any other reason reports it and +stops trying: a retry that fails otherwise is shown as a notification, through the function `GUI_App` +builds the endpoint with. Windows meant to serve side by side need their own configuration folders +(`--datadir`) or `--mcp-port`; agents then pick one by its URL, or the stdio bridge by `--datadir`. The +server makes no attempt to route between windows. -Preferences turns the server on with `GUI_App::start_mcp_service()` and off with -`GUI_App::stop_mcp_endpoint()`, which stops the takeover retries and calls -`McpService::stop_serving()` to close only the endpoint and remove the discovery file. The -catalog, running jobs and a launch run carry on, because the call that opened Preferences may -itself be an MCP call still on the stack. The port field shows the port in use, `--mcp-port`'s -included, and only an edit of it is saved and reopens the endpoint, through -`GUI_App::restart_mcp_endpoint()`: the field also commits when focus merely passes through it. A -port set in Preferences replaces `--mcp-port` for the rest of the session, also while the server is -off. Closing the endpoint drops the session's auto-answer rules, and a client's rules -that a call still running registers afterwards are refused, so a person using the app afterwards -never has a prompt answered for them. Closing doesn't wait for in-flight requests, which -may be waiting on the UI thread that closes it; their replies are dropped. A bind failure is -logged, shown as a notification and in Preferences, and a start from Preferences never reruns a -`--mcp-run` file. The modal tracker is created with the service and picks up modal dialogs that -are already open, such as Preferences when the server is turned on from there. +Preferences turns the server on with `GUI_App::open_mcp_endpoint()` and off with +`GUI_App::close_mcp_endpoint()`, which closes only the endpoint. The runtime, running jobs and a launch +run carry on, because the call that opened Preferences may itself be an MCP call still on the stack, and +turning the server on again opens the same endpoint, with the protocol it had, on the same port. +Preferences reads the endpoint through `GUI_App::mcp_endpoint()`, and `get_app_state.mcp` is the +endpoint's `describe()`: whether it serves and, while it does, its port, URL, token source, token file +and discovery file; in a session that never opened it, `{serving: false}`. The port field shows the port +in use, `--mcp-port`'s included, and only an edit of it is saved and reopens the endpoint, through +`GUI_App::restart_mcp_endpoint()`: the field also commits when focus merely passes through it. A port +set in Preferences replaces `--mcp-port` for the rest of the session, also while the server is off. +Closing the endpoint closes the runtime's client scope (`close_client_scope()`): a client's auto-answer +rules, recording and held presses end, and a client's rules that a call still running registers +afterwards are refused (`client_scope_open()`), so a person using the app afterwards never has a prompt +answered for them. Closing doesn't wait for in-flight requests, which may be waiting on the UI thread +that closes it; their replies are dropped. A bind failure is logged, shown as a notification and in +Preferences, and opening the endpoint from Preferences never reruns a `--run` file. The modal +tracker is created with the runtime and picks up modal dialogs that are already open, such as +Preferences when the server is turned on from there. ## Threading @@ -221,7 +263,7 @@ window isn't being drawn when it isn't. | `Mutate` | everything else | no | The closure checks the guards on the UI thread, since the app can change between posting and -running. A closing app or a stopped service fails the call with "shutting down". A frame being +running. A closing app or a stopped runtime fails the call with "shutting down". A frame being recreated fails it with "retry". A mutate call is refused while a modal dialog is open, and the refusal lists the dialogs. It is also refused when it would run inside another UI call's nested event loop: a modal, `ProgressDialog::Update` or `wxYield`. The GUI input tools (`click`, @@ -268,6 +310,26 @@ first takes one of 32 slots. Without one, a job call returns its `running` envel inline call returns `{status: "pending"}`, so at most 32 request threads ever block, well under the 64-connection cap. +**Followed calls.** A run a person starts (Action Replay, the Run Script panel, `--run`) and the encode +of a person's recording once it ends outlive any reply, so the runtime follows each on a thread of its own: +`AutomationRuntime::follow()` takes a `FollowedCall`, calls its command and waits past a `running` or +`blocked_by_dialog` reply for the job's result. Its `ready` runs first on that thread and may complete the +arguments: the encode waits there for the recording's file, and `--run` reads its file there, off the UI +thread. `ended` gets the result; while the runtime stops, that is an error ("OrcaSlicer is shutting down") when +the call was refused or cut short within its reply budget, and nothing when the runtime stopped while the call's +job was being waited for. `stop` lets `stop_followed()` end +the call early; `suspend()` and `stop()` call it first, while the main window the runs act on is still the +current one. The threads are a `FollowedThreads`: a start joins the threads whose work has returned, and +`stop()` joins the rest once it has woken their waits. `follow()` may be called from any thread. A start and +the join take one lock, and the join refuses every start after it, so a call followed while the runtime stops +is refused or joined, never left running. + +**The person mark.** A job a person's run makes is created with the person mark (`McpCore::call_person()`, +and `McpCore::submit()` for a long command a person picks), and the mark counts while the job is unfinished: +`JobRegistry::person_in()` finds it in a call's lineage, so a script under the run runs as the person's +(Identity, under Python scripts). An agent's call never has it, a call made right after a person's run +included. + ### Operations Slicing and G-code export finish in the background process. Their handlers call @@ -548,7 +610,7 @@ feature reachable). By area, the tools are: The tools are commands of the process's command catalog (`CommandCatalog`, `NativeCommands::instance()`; see Speed Dial catalog), beside the Speed Dial's: a tool is a `NativeCommand` with `listed` set, which -`tools/list` shows in the order the tools were added. Startup builds the catalog, with no MCP service: +`tools/list` shows in the order the tools were added. Startup builds the catalog, with no automation runtime: `register_all_commands()` adds the Speed Dial's commands, then each tool family in a fixed order of calls (app, api, project, config, scene, layer, view, replay, python, record, action, ui), each through its `register_*_tools(catalog)`, and between record and action the Design tab's commands, which no listing shows, @@ -556,8 +618,8 @@ in a CAD build with the CAD feature on (`register_cad_commands()`; see Design ta with the app's state, the search and the generic call, and ends with the tools that drive the GUI. A tool is made with `inspect_tool()`, `mutate_tool()`, `record_tool()` or `recover_input_tool()`, which take its group first and build it through `long_command()` with its function unchanged, so it runs where its call does. A -function reaches the service through its call's context, `ToolContext::service()`: the core gives the service -that owns it (`McpCore::set_service()`), a person's pick starts the runtime without its endpoint, and a core +function reaches the automation runtime through its call's context, `ToolContext::runtime()`: the core gives the +runtime that owns it (`McpCore::set_runtime()`), a person's pick starts the runtime without the endpoint, and a core built on its own, as in a unit test, refuses, which ends the call in an error. Every key is unique across the catalog, tools and Speed Dial commands together. @@ -1271,12 +1333,13 @@ plate are commands of the catalog (`Mcp/McpToolsCad.cpp`) in the group `Design`, never open the Design tab pay nothing for them in `tools/list`. Those that open a tool are in the palette, whose tiles for them the Speed Dial has while the Design tab is shown (see Speed Dial catalog). `register_all_commands()` adds them through `register_cad_commands()` only when the catalog is built with -the CAD feature on (`CatalogOptions::cad`, which startup takes from `enable_cad_feature` in the editor). With +the CAD feature on (`CatalogOptions::cad`, which startup takes in the editor from the value in force: the +`enable_cad_feature` preference, or `--cad` for the run). With it off the catalog holds none, and records that it leaves them out (`leave_out_cad_commands()`): `call_tool {tool: "hole"}` is an unknown command whose error says the feature was off when OrcaSlicer started and how a person turns it on, and `get_app_state` carries `cad_note`, how a person turns the feature on (`cad_note()`, in the editor while the catalog holds no Design -command or the preference is off). The catalog is sealed at startup and the main window makes the Design +command or the feature is off). The catalog is sealed at startup and the main window makes the Design page only then, so turning the feature on or off takes effect after a restart, but for the Speed Dial's Design tiles, which go as soon as it is turned off (see Speed Dial catalog); a window rebuilt for a language change in between makes the page by the new preference, while the catalog keeps the commands it @@ -1659,10 +1722,10 @@ calibration dialogs (pointing at `generate_calibration_test`), camera views and `CommandAction` copies them, the schema and the command's key into the `AppAction`. The commands live in one `CommandCatalog` (`CommandCatalog.hpp`, which includes no wx), built once at startup -by `NativeCommands::build()` before the MCP service starts, and sealed: from then on it never changes and any +by `NativeCommands::build()` before the automation runtime starts, and sealed: from then on it never changes and any thread reads it (`NativeCommands::instance()`, `find()`). A process that never calls `build()`, such as the unit tests and the stdio bridge, gets it built on first use; nothing in the GUI process reads it -before startup builds it, the MCP service included, which `GUI_App` starts after `build()`. +before startup builds it, the automation runtime included, which `GUI_App` starts after `build()`. `register_all_commands()` adds the Speed Dial's commands, then the typed tools (see Tool catalog). Those with `in_palette` have a tile, and `ActionRegistry` makes an action of each of them (`palette_commands()`) and of nothing else in the catalog: no typed tool has one, but the four that are also a Speed Dial command. The @@ -1699,10 +1762,14 @@ Design tab's model, a sketch, and every other tab); reading the stored list cuts A command has one function, `run(args, context)`, which the palette, a menu and every automated caller call. Its arguments are a JSON object that matches its `input_schema`, and every caller checks them first with `Mcp::argument_error(command, args)`, which normalizes them as a tool's (`normalize_arguments()`) and -validates them. The context is a `Mcp::ToolContext`: the MCP core's for a call, or a `Mcp::PersonContext` -(`McpPersonContext.hpp`) for a person's pick, whose `person()` is true. A person's context runs UI -closures in place, has no job, no journal entry and no operation to hold, and reads as cancelled once -OrcaSlicer is closing; it needs no MCP service, so every tile runs with the server off. +validates them. The context is a `ToolContext`, declared beside the catalog with the other types a command +is written in (`CommandTypes.hpp`: `ToolResult`, `ToolFailure`, `GuardClass`). It is the MCP core's for a +call, or a `Mcp::PersonContext` (`McpPersonContext.hpp`) for a person's pick, whose `person()` is true. A +person's pick runs in place on the UI thread, outside the runtime's dispatch core: it has no job, no journal +entry and no operation to hold, and its context reads as cancelled once OrcaSlicer is closing. It needs no MCP +endpoint, so every tile runs with the server off. A pick starts the automation runtime only when its command +needs it: through its context (`runtime()`, `submit()`), as a long command does, or through +`GUI_App::automation()`, as a person's recording and the Action Replay and Run Script windows do. Two helpers wrap the function a command's author writes and place it on the thread it needs: @@ -1717,10 +1784,10 @@ Two helpers wrap the function a command's author writes and place it on the thre - `long_command(key, title, group, schema, fn, inline_call)`: `fn(args, ctx)` runs where its call does, on the job's thread for an automated call. Picked by a person it is started as a job and returns at once (`ctx.submit()`), since it must not hold the UI thread; a command with `inline_call` runs in place - instead. A person's context submits it with `McpCore::submit()` on the service's core, started without - its endpoint when the server is off: the job runs as a client's call does, under the same guards and - operation admission, is not journaled, and is marked as a person's run (`McpService::as_person()`), so a - script it runs runs as the person's. The pick replies at once with the notice "Started:" and the + instead. A person's context submits it with `McpCore::submit()` on the runtime's core, started without + the endpoint when the server is off: the job runs as a client's call does, under the same guards and + operation admission, is not journaled, and its job carries the person mark (`JobRegistry::person_in()`), so + a script it runs runs as the person's. The pick replies at once with the notice "Started:" and the command's title, or an Error when no job started (another operation holds the project, the app is closing); the job's result shows as a notification when it ends. @@ -1948,6 +2015,10 @@ setting). An option of a selector Orca builds of buttons (`RadioGroup`, `TabCtrl is a button that reads checked while it is the selected one (`selector_option()`), so `set_widget_value true` selects it, and a `SwitchButton` with a label at each end has the one it is on as its value. +The inspector, the menu capture, ImGui item recording and, on Wayland, the window-state hooks are the +GUI instruments, which exist once a front end that drives the GUI has turned them on (see Lifecycle). +The inspector is built from the modal tracker and the UI generation alone, not from the runtime. + Input tools take a `target`: a ref (also read written as `{ref: "w12"}`), or a locator, which is stable across runs and is what the journal stores. A locator is one of: @@ -2008,7 +2079,7 @@ the shortcut modifier (Command on macOS) in both, and `rawctrl` the macOS Contro keys are released however the gesture ends; a `mouse_gesture` `down` keeps its button held, and a `move` drags with it, until an `up`, another gesture (one that fails included; a request the server rejects for its arguments never runs and changes nothing), the end of the replay or script that pressed it, -the closing of the endpoint for a client's press, or the service's stop. A client's gesture that +the closing of the endpoint for a client's press, or the runtime's stop. A client's gesture that reaches the UI thread after its endpoint closed is refused. Keys without a target go to the focused window inside the topmost modal, else that modal, else the focused window, else the 3D view shown. @@ -2139,8 +2210,8 @@ compositor-private interfaces do (KWin's scripting, sway's IPC), and GNOME has n `position` is refused there, naming `GDK_BACKEND=x11`, under which the app runs through XWayland and every field works. `list_windows`, `set_window` and `get_app_state.window` leave positions out. Size, maximize and normal work. GTK never reports a minimized window, but the compositor's `suspended` state -(xdg-shell 6) reaches it as a fully obscured visibility notify, which emission hooks installed when the -service starts record on the window (`track_window_states()`). Hidden is not minimized: KWin hides a +(xdg-shell 6) reaches it as a fully obscured visibility notify, which emission hooks installed with the +GUI instruments record on the window (`track_window_states()`). Hidden is not minimized: KWin hides a minimized window at once, but also one on another virtual desktop and every window while the screens are off, and Mutter hides any window it has not shown for 3 s. So a window reads minimized while it is hidden and a minimize from `set_window` stands, which ends once the window shows, takes the focus or closes. A @@ -2158,7 +2229,7 @@ that the person restores the window from the taskbar, and a refused `raise` repl ### Menus Every popup and context menu goes through `popup_menu()` (`SyntheticInput.hpp`), which is -`wxWindow::PopupMenu()` unless the MCP server has installed a capture +`wxWindow::PopupMenu()` unless the GUI instruments are on, which install a capture (`SyntheticInput::set_menu_capture()`). The capture is there because a native menu loop holds the UI thread until a person closes the menu: on macOS it pauses wx's pending events, and with them every `run_ui()` closure. So MCP never shows a menu. `UiInspector::on_menu()` takes a menu that opens in a call's window: from the start of each of @@ -2300,8 +2371,8 @@ menu, and either is captured as any other menu (Menus above). The 3D canvases draw their panels with ImGui, which has no widgets to walk. ImGui's test-engine hooks (`IMGUI_ENABLE_TEST_ENGINE`) report every item a frame adds while -`ImGuiContext::TestEngineHookItems` is set, which `ImGuiWrapper` does only while the service runs; -otherwise ImGui skips each hook with one branch. `ImGuiWrapper` keeps the items of each canvas's +`ImGuiContext::TestEngineHookItems` is set, which `ImGuiWrapper` does only while the GUI instruments +are on; otherwise ImGui skips each hook with one branch. `ImGuiWrapper` keeps the items of each canvas's last frame: id, label, window, rectangle and status flags, and whether the item lies outside the visible part of its window. The hooks reach the recorder through `ImGuiContext::TestEngine`, so they work without the app. Orca's copy of ImGui adds two hooks upstream lacks: `ItemValue`, through which @@ -2720,7 +2791,7 @@ not run it. The releases are asked all at once and get one second together, so a answer holds up none of the others, and the call still names the dialog it works in before the soft budget, past which an open dialog would read as what it waits on. Like the widgets' held press, a page's belongs to the client, replay or script that made it: a replay's or script's ends with it, -a client's when the endpoint closes, every one when the service stops, and a client's down sent +a client's when the endpoint closes, every one when the runtime stops, and a client's down sent after the endpoint closed is refused. These releases, and an auto-answer rule's before it presses a button, are made on the UI thread without waiting (`release_web_presses()`) and with no deadline, so a page busy then releases once free: a page's own confirmed release drops its record, and a @@ -2914,7 +2985,8 @@ there, so Windows leaves out one that DWM cloaks or that a window above it cover application's, a window of ours that is not a popup, or a popup over another window or left out. Only a popup over the same window that is drawn itself, and a layered window at constant alpha 0, do not count. AppKit draws macOS's menus and tooltips in windows of its own, which only the window server shows, so drawing -views leaves them out. The full-size PNG goes to `save_path` or `/mcp/out/OrcaSlicer-screenshot-.png`. The image +views leaves them out. The full-size PNG goes to `save_path` or `OrcaSlicer-screenshot-.png` in the output +folder (`output_dir()`: the `--outputdir` of a `--run` launch, else `/automation/out`). The image block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–2000). `include_image: false` returns only the path. @@ -2926,6 +2998,12 @@ since it runs while the app works: frames are kept as JPEG in a Matroska file (M encode, which costs far more, comes after it. There is no audio. `McpRecorder` holds at most one recording; `get_app_state.recording` shows it while it runs. +The recorder starts with the runtime and needs none of the GUI instruments. It is built from the modal +tracker, whose stack it draws, the UI generation its kept canvas frames belong to, whether the main window is +being rebuilt, and a way to queue a function on the UI thread, not from the runtime. So a person's Start +Recording with the server off starts the runtime without the instruments: its captions, pointer and dialogs +are recorded all the same, and the person's own menus show as they do without automation. + **Capture.** The UI thread captures a frame per tick of a one-shot `wxTimer`, which fires inside modal loops too. `start_recording` takes the first frame in its own UI closure: it fixes the video's size (fit to `max_dim`, rounded down to even numbers for 4:2:0), and a failure fails the call before @@ -2995,12 +3073,12 @@ it, so the last call's effect is in the video even if the timer has not ticked s `stop_recording`, after `max_seconds`, at 4 GiB, on a write error, when the replay or script that started it ends (`run_replay_job()`, which names a file still being written after 30 s as the result's `unfinished_recording`), when the endpoint closes for a client's -(`stop_serving()`; a run's carries on), and at exit. Ending from any thread sets a flag the next tick +(`close_client_scope()`; a run's carries on), and at exit. Ending from any thread sets a flag the next tick reads, tells the sink to finish, and posts the timer and input filter's cleanup to the UI thread; the sink drains its queue, writes the last frame again at the end time so the video lasts until then, closes the file and calls back, on its own thread. So ending never needs a UI round trip: a run's -end waits for the file without deadlocking against `McpService::stop()`, which joins run threads on -the UI thread, and a step after the replay sees a closed file. At exit `stop()` waits 5 s for the +end waits for the file without deadlocking against `AutomationRuntime::stop()`, which joins the followed calls' +threads on the UI thread, and a step after the replay sees a closed file. At exit `stop()` waits 5 s for the file, then drops what is still queued and leaves the sink to its threads, which own its state. A recording counts as active until its file is closed, for the one-at-a-time rule and for encodes. @@ -3008,7 +3086,7 @@ recording counts as active until its file is closed, for the one-at-a-time rule `encode_preset`, `codec`, `crf`, `speed`, `profile`), checked by `apply_recording_overrides()` with its defaults, the Balanced preset, and refuses `encode` without an ffmpeg before anything records. The recording keeps `encode_recording`'s arguments (`RecordingOptions::encode`), and the `stop_recording` -that reports it, once its file is closed, starts the encode with `McpService::start_encode()`: a job of +that reports it, once its file is closed, starts the encode with `start_encode()` (`McpToolsRecord.cpp`): a job of its own, outside the journal (a replayed `start_recording` asks for it again), whose envelope the report carries as `encode`, so the agent waits for the MP4 by that job's id. A recording that ended on its own is encoded when the next `stop_recording` reports it; one nothing reports, a client's that ended with @@ -3026,11 +3104,12 @@ person turns them on. Encode to MP4 holds whether ffmpeg encodes it once it ends codec, CRF, speed and profile; it is off and disabled when no ffmpeg is found, and says how to get one. A rail joins the two stages and shows whether the second runs. The dialog remembers what it starts with in AppConfig's `recording` section (`RecordingSettings`). The encode is -`encode_recording` itself, run by `McpService::encode_when_closed()` as an unjournaled job once the -recording's file is closed (`McpRecorder::wait_closed()`), so it can be cancelled like any encode. No reply +`encode_recording` itself, run by `McpRecorder::encode_when_closed()` as an unjournaled job that the runtime +follows (`follow()`) once the recording's file is closed (`McpRecorder::wait_closed()`, in the call's `ready`), so +it can be cancelled like any encode. No reply names the job, which only exists once the file is closed: an agent finds it in `get_app_state.jobs` and waits for it by its id, as the command's description says. -Start Recording starts the service without its endpoint when the server is off, as Action Replay and the +Start Recording starts the runtime without the endpoint when the server is off, as Action Replay and the Run Script panel do. The person's recording has its own owner (`kPersonOwner`), so neither a run's end nor the endpoint closing ends it. Whatever ends it tells the person where it went, in a notification whose button opens the folder: Stop Recording itself, which stops any recording, an agent's too, ending it as @@ -3096,7 +3175,7 @@ falls to almost nothing while the window is still and rises for the motion, wher spend it evenly; the video's length in the reply is the MP4's movie header's (`mp4_duration()`); an ffmpeg without the encoder is refused, naming what is needed. It runs without a console window, polled every 100 ms and terminated when the call is cancelled -(`NativeCommand::cancellable`: `cancel_job {job}` stops it through `McpService::request_stop()`). On Windows it is +(`NativeCommand::cancellable`: `cancel_job {job}` stops it through `JobRegistry::request_stop()`). On Windows it is ended with `TerminateProcess()` on its handle and waited for on that handle, since `TerminateProcess()` returns before the process is gone and boost's `terminate()` closes the handle right after it; a child not gone within 5 s keeps its files, which the error names, and its source and destination stay reserved for @@ -3230,25 +3309,34 @@ step's `reason` says why in parts a host can word: `cancelled`, `timeout {second op, expected, actual, exists}`, `expect_invalid`, `placeholder {text}`, `missing_job {name, saved_by}` (the step that saves that job, when one does) or `tool` (the tool's own error). A replay file's `out_dir` defaults to `.out` beside it. An inline replay's defaults to -`/mcp/out/replay-`, which is also its `${replay_dir}`. +`replay-` in the output folder (`output_dir()`), which is also its `${replay_dir}`. The engine (`McpReplay.cpp`, wx-free) and the job around it (`run_replay_job()` in -`McpToolsReplay.cpp`) are shared by `run_replay`, `--mcp-run` and Action Replay. A run -stops before its next step, and stops waiting on a step's job, once the service stops or a stop was -asked for any job in its lineage (`McpService::request_stop()`), so a nested `run_replay` stops with +`McpToolsReplay.cpp`) are shared by `run_replay`, `--run` and Action Replay. A run +stops before its next step, and stops waiting on a step's job, once the runtime stops or a stop was +asked for any job in its lineage (`JobRegistry::request_stop()`), so a nested `run_replay` stops with the run that holds it. Stop requests last the session, and `JobRegistry` records each job's ancestor chain when it is created, so a descendant still reaches its root after finished ancestors are forgotten. A step during which the stop came is failed as `cancelled` whatever it returned (a cancelled slice still reports its plates) and ends the run, `optional` or not. The engine reports each step as it starts and ends, and can run a single step with the jobs earlier runs saved. -`orca-slicer --mcp-run FILE [--mcp-run-out DIR]` runs a replay (`.json`) or a Python script (`.py`) once -the GUI is ready. It doesn't open the endpoint unless `--mcp` is also given. A replay writes `result.json` -and screenshots to the output directory, which defaults to `.out` next to the replay. Then -it closes the app without prompting and exits 0 if the replay passed or the script finished, 1 if a step -failed or the script did not finish, and 2 if the file is invalid or can't be read. `OrcaSlicer.cpp` -resolves both paths against the original working directory, since the GUI changes it. wx ignores -`OnExit()`'s return value, so `GUI_Run()` returns `McpService::run_exit_code()` after `wxEntry()`. +`orca-slicer --run FILE [--outputdir DIR]` runs a replay (`.json`) or a Python script (`.py`) once the GUI +is ready. `--run` itself asks only for the runtime: the endpoint opens with it when `--mcp` or `--mcp-port` is +also given or the saved `mcp_enabled` preference is on. `--outputdir` names the +session's output folder: `start_launch_run()` hands it to `set_run_output_dir()`, so `output_dir()` returns +it and files a call saves without a path go there, and a replay writes `result.json` and its screenshots +there. Without it a replay writes to `.out` next to the replay, and `output_dir()` is +`/automation/out`. Then the run closes the app without prompting and exits 0 if the replay passed +or the script finished, 1 if a step failed or the script did not finish, and 2 if the file is invalid, +can't be read or is neither a `.json` nor a `.py` file. A `--run` launch keeps a window of its own: +`GUI_Run()` calls `instance_check()` with `never_send`, so the launch is never handed to a running +instance, whatever the `single_instance` preference says, and its exit code is its own. The call still +sets the instance hash, which `post_init()` reads. Where no GUI starts, beside a slicing action or +`--downward-check`, `CLI::run()` refuses `--run` with `CLI_INVALID_PARAMS` and a line on stderr that names +it, rather than leave the file unrun. `OrcaSlicer.cpp` resolves both paths against the original working +directory, since the GUI changes it. wx ignores `OnExit()`'s return value, so `GUI_Run()` returns +`launch_exit_code()` (`LaunchRun.hpp`) after `wxEntry()`. ### Action Replay @@ -3267,14 +3355,14 @@ nothing while a replay runs, as Open is unavailable then. The browser's own keys don't reload the page back to its draft. The page's editor starts from a commented draft and suggests the replay's keys, tool names, a tool's arguments and their allowed values, and `${…}` placeholders; the tool part comes from the command catalog's listed tools (`editor_tool_catalog()`), -which the dialog sends once the service is ready, so the suggestions match the build. Save writes the text +which the dialog sends once the runtime is ready, so the suggestions match the build. Save writes the text back to the file it was opened from, or asks where to put a new replay file and offers the replay's name as the file name. A replay saved somewhere new is that file's from then on: `${replay_dir}` and its output folder follow the file, as for an opened one. Closing the window, or opening another replay, with unsaved edits asks first. The page reports every edit to the host, which parses, runs and saves that one copy of the text, so the host can -ask and save even when the window's close box starts the close. Opening the window starts the service -without the endpoint, as `--mcp-run` does, so a person replays files with the server off. +ask and save even when the window's close box starts the close. Opening the window starts the runtime +without the endpoint, as `--run` does, so a person replays files with the server off. **The editor.** Action Replay and the Run Script panel edit in Ace (`ace-builds` 1.45.2, BSD-3-Clause), vendored unmodified in `resources/web/include/ace/` (its `src-min-noconflict` core, the JSON and Python @@ -3291,15 +3379,15 @@ message keys, and `code_editor.js` hands them to `ace.config.setMessages()`. Eac chords its editor binds (`editor_keys`), which the main frame's menu rule reads (Keys, under Run Script panel). Action Replay's language is a JSON mode of its own (`orca_replay`, `replay_editor.js`). -`McpService::start_replay_run()` runs the replay as a job of `run_replay`'s kind but outside the -session journal, since a person's run is not an agent's call. A thread the service owns follows the -job past a `running` or `blocked_by_dialog` reply to its result, posts it once, and is joined by -`stop()`. Step reports and the result reach the dialog through the service's dispatcher as +`start_replay_run()` (`McpPersonRun.cpp`) runs the replay as a job of `run_replay`'s kind but outside the +session journal, since a person's run is not an agent's call, with the person mark. The runtime follows the +job (`follow()`) past a `running` or `blocked_by_dialog` reply to its result, which it posts once. Step reports +and the result reach the dialog through the runtime's dispatcher as `PersonRun` events, which the dialog drops once it is gone. `PersonRun::stop()` latches, so a stop asked before the job exists still counts, requests the stop for the job (`JobRegistry::request_stop()`) and cancels its operation as `cancel_job` does. Every call the run and its nested replays make -then sees `ToolContext::cancelled()`, so a step that waits, such as `wait`, returns at once. `suspend()` and `stop()` stop every run first, while the main -window they run in is still the current one. +then sees `ToolContext::cancelled()`, so a step that waits, such as `wait`, returns at once. `suspend()` and `stop()` +stop every run first (`stop_followed()`), while the main window they run in is still the current one. Before a run the dialog describes each step with `describe_step()` (`McpReplaySummary.cpp`, wx-free): what it acts on, and flags for effects beyond the open project (writes a file outside the output @@ -3312,8 +3400,9 @@ replacing step either checks unsaved changes itself (`new_project`, `open_files` `generate_calibration_test`) or goes through the app's own save question (`close_with_confirm()`). When the project has unsaved changes and the steps to run hold a step of the first kind, or one of the second kind with a step that can answer a dialog, the dialog asks whether to save first. Yes saves; No lets the -run's replacing tools treat the run as `discard_changes: true` (`McpService::discard_authorized()`, -read from the job lineage when the tool checks), so changes are dropped only when a step really +run's replacing tools treat the run as `discard_changes: true`: the run's handler marks its job as it starts +(`JobRegistry::allow_discard()`), the mark counts while the job is unfinished, and a tool reads it from its +call's lineage when it checks (`discard_allowed_in()`), so changes are dropped only when a step really replaces the project. The runner never answers the app's own question. The window is named `kHiddenFromAutomation`: `list_widgets` and locators skip it, `list_windows` lists @@ -3368,7 +3457,7 @@ be satisfied. Only the call's own job counts as its job: a A Python script is a `.py` file or a code string that runs on the plugin interpreter as an embedded macro: the main program of a run inside OrcaSlicer, with the whole plugin API (`orca.host`), without being packaged as a -plugin. A person runs one in the Run Script panel or with `--mcp-run file.py`; an agent sends one with +plugin. A person runs one in the Run Script panel or with `--run file.py`; an agent sends one with `run_script {code, args, timeout_s, filename}`; a plugin's code may call `run_script` too. A script that runs under `python file.py` runs the same way here, and code written for a plugin's `execute()` (windows, progress, presets, storage) runs from a script unchanged. A script is not a plugin: it gets no permission prompt and no @@ -3381,7 +3470,7 @@ Script panel, below). The code is text, compiled as Python compiles any code string, so a coding line in it changes nothing; a file's bytes are decoded first as Python reads a source file, by its BOM or its PEP 263 declaration, else as UTF-8 (`decode_python_source()`). It runs as the main program, in a `types.ModuleType("__main__")` of its own, with `args` bound and `orca` importable. A run is a *file -run* when `filename` names an existing file (a saved script's in the panel and `--mcp-run`'s do): `__file__` and +run* when `filename` names an existing file (a saved script's in the panel and `--run`'s do): `__file__` and `sys.argv` (`[path]`) name it, its folder serves its imports, and its PEP 723 dependencies are installed first. Any other name (the default ``, a bare traceback name) is code sent as text, which gets none of that; `filename` still names it in tracebacks. The value left in `result` is read once when the body returns; in code @@ -3504,9 +3593,10 @@ script's and a plugin's never write the folder at once. An install that fails ma code. The install isn't covered by the watcher; uv's 120 s timeout bounds it. **Identity.** A person's script runs under the audit identity `script`, an agent's under `mcp` -(`kScriptIdentityPerson`, `kScriptIdentityAgent`); `McpService::person_run()` tells them apart by the run's -lineage, since the panel's, `--mcp-run`'s and a person's pick of a long command's jobs are marked as a person's -(`as_person()`). The plugin audit +(`kScriptIdentityPerson`, `kScriptIdentityAgent`); `JobRegistry::person_in()` tells them apart by the run's +lineage, since the jobs of Action Replay, the panel, `--run` and a person's pick of a long command carry the +person mark while they are unfinished (Threading). So a `run_script` that the panel's session calls through +`orca.host.tools` runs as the person's too. The plugin audit ([plugin-permissions.md](plugin-permissions.md)) judges a script under its identity as it judges a plugin, with one difference: a script has no install state to hold a grant, so it is never asked, and what the implicit rules don't allow is denied with a `PermissionError` that names the setting. The threads, pool tasks and window @@ -3516,21 +3606,26 @@ reserved: a plugin whose key equals one is refused before any of its code runs, a script. A plugin's `run_script` runs under the plugin's own identity and grants instead, with the same main-program environment, but its windows, callbacks and storage stay the plugin's. -**The setting.** One switch, `mcp_python_unrestricted`, off by default, decides how a person's scripts and an -agent's `run_script` are judged (a plugin's `run_script` is the plugin's and ignores it). Off, a script is +**The setting.** One switch, `python_scripts_unrestricted`, off by default, decides how a person's scripts and an +agent's `run_script` are judged (a plugin's `run_script` is the plugin's and ignores it), and the command line's +`--unrestricted-scripts` turns it on for one run without writing it. Off, a script is restricted: its Python code reads and writes OrcaSlicer's data folder, reads the resources folder, the standard library and, in a file run, the folder of its file (`PythonRunScope::allow_folder_reads()`, a scoped root on each of the run's threads, so its imports work), and is denied every other audited access: files elsewhere, programs, threads and the network. On, every audited access is allowed to it (`PluginAuditManager::set_scripts_unrestricted()`, which `apply_python_scripts_setting()` sets at startup and -on a change, and the audit reads on whichever thread raises the event). The categorical denies every plugin has +on a change to the value in force, and the audit reads on whichever thread raises the event). The categorical denies every plugin has (`is_denied_path()`) hold either way. The audit is a Python audit hook, not a sandbox: the tools a script calls through `orca.host.tools` and the rest of `orca.host` run OrcaSlicer's own code and are not judged, so a restricted script still does what an agent's tool calls do. The setting is changed only in `PythonScriptsDialog`, opened from Preferences › AI features › Python scripts, which is named `kHiddenFromAutomation`: the UI tools never -see it and `ModalTracker` leaves it off the stack, so no dialog tool or auto-answer rule reaches it. No tool -writes the key, and `get_app_state.python.scripts_unrestricted` reads it, so an agent learns what its script may -do before it plans a run rather than from a refusal. +see it and `ModalTracker` leaves it off the stack, so no dialog tool or auto-answer rule reaches it. No tool and no +command line option writes the key. Two functions keep the saved setting apart from the value in force: +`python_scripts_setting()` is the key, which the dialog and the Preferences row show and the dialog writes, and +`python_scripts_unrestricted()` is the key or the run's flag (`set_python_scripts_for_run()`, called once at +startup), which the audit gets and `get_app_state.python.scripts_unrestricted` reads, so an agent learns what its +script may do before it plans a run rather than from a refusal. While the flag is on, the row adds "(on for this +run by the command line)" and the dialog says the flag is on under its checkbox. **The host surface and the bridge.** A script reaches the whole `orca.host`, as a plugin does: reads, `orca.host.ui` (message boxes, progress dialogs, HTML windows, dock panels, notifications), the staged preset update, bundle @@ -3623,9 +3718,9 @@ dependencies as its first work starts. `run_python_code()` is a session with one with streaming, quoting, Cell events and cell results off and a stop closing every window of the run, which is how it keeps the run described above. -**The session job.** `McpService::start_python_session()` hosts the panel's session as an unjournaled person's -`run_script` job (`run_python_session_job()`) on a thread the service owns, which `stop()` joins and -`stop_person_runs()` stops. The job is idle for `wait {for: "idle"}` as any `run_script` job is, so agents' and +**The session job.** `start_python_session()` (`McpToolsPython.cpp`) hosts the panel's session as an unjournaled +person's `run_script` job (`run_python_session_job()`), which the runtime follows (`follow()`) on a thread that +`stop()` joins and `stop_followed()` stops. The job is idle for `wait {for: "idle"}` as any `run_script` job is, so agents' and plugins' runs overlap with it, sharing no state, tracebacks included. It owns what its calls leave behind for the whole session, as a run does (`begin_run_scope()`): auto-answer rules, recordings, held presses. Between works its rule layer is paused (`ModalTracker::set_paused()`; the rules listing shows it as paused), so a rule a cell @@ -3709,9 +3804,9 @@ A plugin's call waits for the UI thread, so it comes only from a thread nothing worker, a Python thread one starts (the thread shim carries the mark) or MCP's own thread running a plugin operation (`ScopedToolCallerThread`). A call from the UI thread, a slicing hook or another plugin callback is refused before anything waits. `install_plugin_tool_caller()` routes a plugin's calls. The UI -thread, which owns the service and runs the plugin's unload, admits each one: the plugin must still be -loaded and its scope not ended, and the service is started without its endpoint when MCP is off; the -call then holds a lease the service's drain waits for. A caller that stops waiting because the app closes +thread, which owns the runtime and runs the plugin's unload, admits each one: the plugin must still be +loaded and its scope not ended, and the runtime is started without the endpoint when MCP is off; the +call then holds a lease the runtime's drain waits for. A caller that stops waiting because the app closes marks its admission abandoned, so no lease is taken that nobody releases. The call runs as `McpCore::call_plugin()`: a top-level job owned by the plugin (`JobRegistry::owner()`), never journaled, whose children inherit the plugin @@ -3793,8 +3888,8 @@ built there on first use, since the bridge never starts the GUI that builds it), server would get: the handshake, `ping`, `tools/list`, `server/discover`, notifications and unknown methods get exactly the reply this build's server gives. That holds because these methods read only the catalog and the server's details, and the server keeps no session. The catalog needs no -service: registering a command only describes it (a schema built from constants and compile-time -options), and its function runs only when the command is called, reaching the service through its +runtime: registering a command only describes it (a schema built from constants and compile-time +options), and its function runs only when the command is called, reaching the runtime through its call's context, so building it needs neither wx nor a window. A command's registration must stay that way, never reading app state; a unit test builds the catalog without the app. @@ -3826,9 +3921,20 @@ A line that is valid JSON but not one message object, such as a batch, gets an e ## Configuration -The CLI options are in `CLIMiscConfigDef`, so the GUI still starts: `--mcp`, `--mcp-port N`, -`--mcp-token T`, `--mcp-run FILE`, `--mcp-run-out DIR` and `--mcp-stdio`. The AppConfig `app` -section holds `mcp_enabled` (false) and `mcp_port` (13619). Preferences › General › AI features +The CLI options are in `CLIMiscConfigDef`, so the GUI still starts: `--mcp`, `--mcp-port N`, `--mcp-stdio`, +`--run FILE` (with `--outputdir DIR`, see Replays), `--unrestricted-scripts` and `--cad`. `--mcp-port` opens the +endpoint as `--mcp` does, whatever its value, and 0 takes the preference's port: every option has a value after +`CLI::setup()`, so `OrcaSlicer.cpp` reads whether it was given from `m_given_option_keys`. `--mcp`, +`--unrestricted-scripts` and `--cad` each turn their setting on for the run, and the flag never writes the +configuration; without the flag the setting decides. `--mcp` opens the endpoint at startup, and Preferences' +server switch still closes and opens it during the run, saving `mcp_enabled`, as it does without the flag. With +`--unrestricted-scripts` or `--cad` the setting is on until OrcaSlicer closes, whatever Preferences saves +meanwhile. `GUI_InitParams` holds these two flags. +Each of the two settings has two readers: the saved setting (`python_scripts_setting()`, +`GUI_App::cad_feature_setting()`), which Preferences shows with "(on for this run by the command line)" beside +it while the flag is on, and the value in force (`python_scripts_unrestricted()`, +`GUI_App::is_enable_cad_feature()`), which the rest of the app reads, `get_app_state` included. The AppConfig +`app` section holds `mcp_enabled` (false) and `mcp_port` (13619). Preferences › General › AI features opens with a line on what agents can do and who can connect, then has five rows: - **"MCP server"**: checked while the server runs. A dot and a line beside it give the state: @@ -3868,23 +3974,49 @@ that can't connect over HTTP; its setup names this executable, so it breaks when ## Testing -Unit tests are Catch2 cases tagged `[Mcp]` in `tests/slic3rutils/test_mcp_*.cpp`, run with -`slic3rutils_tests "[Mcp]"`. `test_mcp_protocol` covers both eras, the order of `tools/list`, argument -validation, the names and values read in place of a tool's own, and the error for an unknown tool, which names -the closest; -`test_mcp_http` the endpoint rules and a live server (deadlines, eviction, stop); `test_mcp_token` +Unit tests are Catch2 cases in two suites. The automation core is the library +`libslic3r_automation`: sixteen units of `src/slic3r/GUI` (the command catalog's type, the dispatch core, the +hand-off to the UI thread, the job registry, the followed threads, the journal, the paths, argument checking, +the protocol and HTTP transport, what the server says of itself, the replay model, Action Replay's summary of a +replay, the setup a client copies, the stdio bridge and the token), which `libslic3r_gui` links. +Its tests are in `tests/automation/`, run with `automation_tests` +(the `test_mcp_*` cases are tagged `[Mcp]`, `test_command_catalog`'s `[CommandCatalog]`); that suite links the +library and libslic3r and nothing of `libslic3r_gui`, so it builds without wx and the embedded Python. What +needs the GUI library (the runtime, the endpoint, the tool families, the process catalog `NativeCommands` +builds) is tested in `tests/slic3rutils/`: the `test_mcp_*.cpp` cases are tagged `[Mcp]`, and the other files +named below carry tags of their own (`test_command_catalog` `[CommandCatalog]`, `test_operations` +`[Operations]`, `test_imgui_wrapper` `[ImGuiWrapper]`), so +`slic3rutils_tests "[Mcp],[CommandCatalog],[Operations],[ImGuiWrapper]"` runs them all. The build keeps wx out +of the core: `src/CMakeLists.txt` adds the library +before it finds wxWidgets. On Linux, wx's include paths and definitions apply at directory scope only from the +point after which the library is added. On Windows and macOS, wx's setup header and definitions come only with +the wx targets, which the library does not link. So a wx include in a core unit fails to compile, and a call +from a core unit into the GUI library fails to link `automation_tests`. + +In `tests/automation/`, `test_mcp_protocol` covers both eras, argument validation, the names and values read +in place of a tool's own, and the error for an unknown tool, which names the closest; +`test_mcp_http` the endpoint rules and a live server (deadlines, eviction, stop); `test_mcp_paths` the output +folder, the run's or `/automation/out`; `test_mcp_token` who owns the discovery file and when a port counts as held by another window; `test_mcp_core` `UiInvoker`, `McpCore` and `JobRegistry` on a hand-stepped dispatcher (guards, abandoned calls, -jobs, blocked_by_dialog, admission, slots, idle, journal and the id arguments it leaves out, a context -with no service, a submitted call); -`test_command_catalog` (tagged `[CommandCatalog]`) the catalog itself: unique keys, the palette's -commands, which are listed, the merged commands' schemas and forms, a tool list built without a -service, a Speed Dial command found by the one lookup, each command's `id_args` against its schema, the -history `undo` and `redo` take, and the command reference (tagged `[Reference]`): the checked-in file against -the catalog, and that its entries hold what `tools/list` tells a client and both forms of a two-form command; -`test_operations` (tagged `[Operations]`) +jobs, blocked_by_dialog, admission, slots, idle, journal and the id arguments it leaves out, a submitted +call, a job's person and discard marks) and the followed threads (`FollowedThreads`: a returned work's thread +joined by the next start, a stop that reaches only the works still running, no start after the join); +`test_command_catalog` (tagged `[CommandCatalog]`) the catalog's own rules (keys, sealing, order, +sources, a Design command's title context, the schema of a two-form command) and a command's reference entry; +`test_mcp_replay` parsing, substitution, matchers and await; `test_mcp_replay_summary` how Action Replay +describes and flags a replay's steps; `test_mcp_setup` the HTTP and stdio setups a client copies. + +In `tests/slic3rutils/`, the files of the same name hold the cases that need the GUI library: +`test_mcp_core` a context with no runtime and a tile's journal update; `test_mcp_protocol` the order of the +process catalog's `tools/list` and the tool families the stdio bridge lists; `test_command_catalog` the +process catalog itself: unique keys, the palette's commands, which are listed, the merged commands' schemas +and forms, a tool list built without a runtime, a Speed Dial command found by the one lookup, each command's +`id_args` against its schema, the history `undo` and `redo` take, and the command reference (tagged +`[Reference]`): the checked-in file against the catalog, and that its entries hold what `tools/list` tells a +client and both forms of a two-form command. The others there: `test_operations` (tagged `[Operations]`) the slice and export outcomes, an operation's `Outcome` and `Refusal`, and the catalogs' operation -names and exception lists; `test_mcp_replay` parsing, substitution, matchers and await; `test_mcp_ui` labels, +names and exception lists; `test_mcp_ui` labels, snapshot text, ref liveness, synthetic key state, a key's way through the hooks of its target's parents (with a display), how ImGui items are labelled and named, value matching and the model-target projection and surface check (`CanvasTarget`); `test_mcp_results` @@ -3912,14 +4044,15 @@ effective values, the names and places `save_preset` accepts, enum labels and de per-variant entries and their writes, preset comparison, `changed`, which unsaved changes a call discarded, which presets `delete_preset` refuses or deletes with a custom printer, the project scope's slot colours, flushing multipliers and matrix, and the plate scope's filament orders and layer ranges and -`list_plates`' layer numbers and layer G-codes, the preferences scope's keys, and `generate_calibration_test`'s arguments, +`list_plates`' layer numbers and layer G-codes, the preferences scope's keys, the scripts setting's saved value and value in +force, and `generate_calibration_test`'s arguments, defaults, the dialogs' shared rules, VFA's auto-adjust and the parameters the journal records. End to end, `tools/mcp/orca_mcp.py` launches the app on Linux on the XWayland of a private headless compositor (KWin, else mutter, which is not tested yet), which gives it the GPU's OpenGL and a window manager, or, on a machine without a desktop, on a private Xvfb display (with `-noreset`, and the pointer parked in a corner so no tooltip lands in a screenshot); on macOS and Windows it opens the app on the desktop. It runs `tools/mcp/smoke_test.json`. `tools/mcp/tests/replay_basic.json` -checks `--mcp-run` headless, `tools/mcp/tests/gizmos.json` every gizmo through the GUI tools, +checks `--run` headless, `tools/mcp/tests/gizmos.json` every gizmo through the GUI tools, `tools/mcp/tests/multicolor.json` object and part filaments and the project scope, `tools/mcp/tests/presets.json` saving, reading and comparing presets, explaining settings, per-variant entries, `changed`, reverting keys, answering the unsaved-changes prompts of a preset switch and a new project, deleting presets, exporting and importing @@ -3956,6 +4089,10 @@ and `get_app_state.camera`, and a fit after the window was sized while no 3D vie `tools/mcp/test_export_running_job.py` an export during and after a job that outlived its reply, `tools/mcp/test_send_gcode.py` `send_gcode` and `get_app_state.uploads` against a stub print host that answers 200 or 500, +`tools/mcp/test_command_line.py` the command line's options (the refused ones, `--run`'s exit codes, folders and +refusals, `--mcp-port`, the two run flags, and a run beside a window already open), +`tools/mcp/test_runtime_lifecycle.py` the app's exit with a job, a recording or a call no stop interrupts still +running and with the endpoint never opened, and the server switched off and on during a call, `tools/mcp/test_stdio_bridge.py` the stdio bridge, and `tools/mcp/test_recovery_under_load.py` answering a dialog while stalled clients hold every connection. See `tools/mcp/README.md`. diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index 7b72007e17..a1f611d4a1 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -120,16 +120,17 @@ nested events of the same operation are not asked again. ### Python scripts -A Python script run from the Run Script panel, with `--mcp-run` or by an agent's `run_script` +A Python script run from the Run Script panel, with `--run` or by an agent's `run_script` is not a plugin, but its events are judged here under a reserved identity, `script` or `mcp` (see "Python scripts" in [mcp-server.md](mcp-server.md)). A script has no sidecar, so it holds no grant and is never asked: steps 1 to 3 apply to it, and any other event is denied with a `PermissionError` that names the setting below. A file run also reads the folder of its file, through a per-call scoped root. -The "Run Python scripts unrestricted" setting (Preferences, AI features, Python scripts; off by -default) lifts this for every script: while it is on, a script's event is allowed right after -step 1, so only the denied paths stay blocked. No plugin key may equal a script identity; such a +The "Run Python scripts unrestricted" setting (`python_scripts_unrestricted`: Preferences, AI features, +Python scripts; off by default) lifts this for every script, and so does the command line's +`--unrestricted-scripts` for one run, without writing the setting: while either is on, a script's event +is allowed right after step 1, so only the denied paths stay blocked. No plugin key may equal a script identity; such a plugin is refused at load. ## Permission prompts diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index 951aa72f09..ddb282ed00 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -7914,12 +7914,16 @@ msgstr "" msgid "Python scripts" msgstr "" -msgid "Python scripts are subject to the same permission checks as plugins: the scripts you run in the Run Script panel or with --mcp-run, and the ones AI agents send through the MCP server. When this option is on, they bypass the permission checks, which is useful for fully automated workflows." +msgid "Python scripts are subject to the same permission checks as plugins: the scripts you run in the Run Script panel or with --run, and the ones AI agents send through the MCP server. When this option is on, they bypass the permission checks, which is useful for fully automated workflows." msgstr "" msgid "Run Python scripts unrestricted" msgstr "" +#. TRN Python scripts window. --unrestricted-scripts is a command line option: keep it as it is. +msgid "OrcaSlicer was started with --unrestricted-scripts, so scripts run unrestricted until it closes, whatever this setting says." +msgstr "" + msgid "Small file" msgstr "" @@ -11169,6 +11173,11 @@ msgstr "" msgid "Copied" msgstr "" +#. TRN Preferences, after a setting that a command line option turned on until OrcaSlicer closes. The row +#. shows the saved setting, which the option does not change. +msgid "(on for this run by the command line)" +msgstr "" + msgid "Unrestricted" msgstr "" @@ -20966,25 +20975,7 @@ msgstr "" msgid "MCP server port" msgstr "" -msgid "Port of the MCP server. Defaults to the preference, or 13619." -msgstr "" - -msgid "MCP server token" -msgstr "" - -msgid "Bearer token the MCP server requires for this run. The ORCA_MCP_TOKEN environment variable takes precedence and does not show up in the process list." -msgstr "" - -msgid "Run a replay or script" -msgstr "" - -msgid "Run a replay (.json) or a Python script (.py) once the GUI is ready, then exit: 0 when it passed or finished, 1 when a step failed or the script did not finish, 2 when the file is invalid or cannot be read." -msgstr "" - -msgid "Replay output directory" -msgstr "" - -msgid "Where --mcp-run writes a replay's result.json and screenshots. Defaults to .out next to the replay." +msgid "Start the MCP server for this run on this port, as --mcp does. 0 takes the port from the preference, or 13619." msgstr "" msgid "MCP stdio bridge" @@ -20993,10 +20984,28 @@ msgstr "" msgid "Act as an MCP server on standard input and output for clients that cannot use HTTP, forwarding to the running OrcaSlicer (started with --mcp when none answers)." msgstr "" +msgid "Run a replay or script" +msgstr "" + +msgid "Run a replay (.json) or a Python script (.py) once the GUI is ready, then exit: 0 when it passed or finished, 1 when a step failed or the script did not finish, 2 when the file is invalid or cannot be read." +msgstr "" + +msgid "Unrestricted Python scripts" +msgstr "" + +msgid "Let Python scripts bypass the permission checks for this run, whatever the preference says." +msgstr "" + +msgid "Design tab" +msgstr "" + +msgid "Show the Design tab and offer its commands for this run, whatever the CAD feature preference says." +msgstr "" + msgid "Output directory" msgstr "" -msgid "This is the output directory for exported files." +msgid "This is the output directory for exported files. With --run, it is where the run's files go: a replay's result.json and screenshots, and the files saved without a path." msgstr "" msgid "Export statistics" diff --git a/resources/web/dialog/ActionReplay/action_replay.js b/resources/web/dialog/ActionReplay/action_replay.js index 340958495a..792bc79b6c 100644 --- a/resources/web/dialog/ActionReplay/action_replay.js +++ b/resources/web/dialog/ActionReplay/action_replay.js @@ -61,7 +61,7 @@ function scheduleParse(delay) { const seq = ++state.parseSeq; state.stale = true; state.parseTimer = setTimeout(() => { - // Asked again once the service is ready (HandleStudio's "service"). + // Asked again once the automation runtime is ready (HandleStudio's "runtime"). if (!state.ready) return; if (!sourceText().trim()) { onParsed({ seq, ok: false, empty: true }); @@ -517,11 +517,11 @@ function renderFooter() { function HandleStudio(msg) { switch (msg.command) { - case "service": { + case "runtime": { const was = state.ready; state.ready = !!msg.ready; if (msg.tools) setEditorTools(msg.tools); - // A replay parsed while the service was starting got only "still starting" back. + // A replay parsed while the automation runtime was starting got only "still starting" back. if (state.ready && !was && !busy()) scheduleParse(0); render(); break; diff --git a/resources/web/dialog/RunScript/run_script.js b/resources/web/dialog/RunScript/run_script.js index 80099a7ff0..59950be173 100644 --- a/resources/web/dialog/RunScript/run_script.js +++ b/resources/web/dialog/RunScript/run_script.js @@ -922,7 +922,7 @@ function HandleStudio(msg) { applyScript(msg.script || { none: true }); renderRecent(); break; - case "service": + case "runtime": S.ready = !!msg.ready; render(); break; diff --git a/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml b/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml index 46ed319244..d48a14aa94 100644 --- a/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml +++ b/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml @@ -414,7 +414,7 @@ modules: # this build uses the default Makefile generator, so it is not available here.) - cmake --build build_flatpak -j"${FLATPAK_BUILDER_N_JOBS:-$(nproc)}" --target libslic3r_tests fff_print_tests sla_print_tests libnest2d_tests slic3rutils_tests - filament_group_tests + automation_tests filament_group_tests cleanup: - /include diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c8d882f291..455806afe4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,6 +14,8 @@ find_package(libnoise REQUIRED) add_subdirectory(libslic3r) if (SLIC3R_GUI) + # Before wxWidgets is found, so the automation core builds without wx (see its CMakeLists.txt). + add_subdirectory(libslic3r_automation) add_subdirectory(glad) # imgui, imguizmo, and hidapi are now included from deps_src add_subdirectory(libvgcode) diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 32cc1140fa..001df2f137 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -168,8 +168,10 @@ using json = nlohmann::json; #endif #ifdef SLIC3R_GUI + #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/GUI_Init.hpp" #include "slic3r/GUI/Mcp/McpStdioBridge.hpp" + #include "slic3r/GUI/NativeCommands.hpp" // BBLPrinterAgent::from_orca_filament_id(); the map and its lookups live in libslic3r_gui, // which only a SLIC3R_GUI build links (see target_link_libraries(OrcaSlicer libslic3r_gui) // in CMakeLists). @@ -1223,7 +1225,9 @@ int CLI::run(int argc, char **argv) // The stdio bridge is a plain pipe to a running GUI instance; it needs none of the setup below. for (int i = 1; i < argc; ++i) if (std::strcmp(argv[i], "--mcp-stdio") == 0) - return Slic3r::GUI::Mcp::run_stdio_bridge(argc, argv); + return Slic3r::GUI::Mcp::run_stdio_bridge(argc, argv, []() -> const Slic3r::GUI::CommandCatalog& { + return Slic3r::GUI::NativeCommands::instance(); + }); #endif #ifdef __WXGTK__ @@ -1490,6 +1494,14 @@ int CLI::run(int argc, char **argv) } bool start_gui = m_actions.empty() && !downward_check; + // --run runs its file in the GUI, so it is refused where no GUI starts rather than left unrun. + if (!start_gui && m_given_option_keys.count("run") > 0) { + std::string flag = m_actions.empty() ? std::string("downward_check") : m_actions.front(); + std::replace(flag.begin(), flag.end(), '_', '-'); + boost::nowide::cerr << "--run cannot be combined with --" << flag << std::endl; + record_exit_reson(outfile_dir, CLI_INVALID_PARAMS, 0, cli_errors[CLI_INVALID_PARAMS], sliced_info); + flush_and_exit(CLI_INVALID_PARAMS); + } if (start_gui) { BOOST_LOG_TRIVIAL(info) << "no action, start gui directly" << std::endl; #ifdef SLIC3R_GUI @@ -1534,17 +1546,21 @@ int CLI::run(int argc, char **argv) //BBS: remove GCodeViewer as separate APP logic //params.start_as_gcodeviewer = start_as_gcodeviewer; + // --mcp-port opens the endpoint as --mcp does, whatever its value. Every option has a value after setup(), + // so whether it was given is read from the options the command line named. if (const auto *opt = m_config.opt("mcp")) params.mcp.enable = opt->value; + if (m_given_option_keys.count("mcp_port") > 0) + params.mcp.enable = true; if (const auto *opt = m_config.opt("mcp_port")) params.mcp.port = opt->value; - if (const auto *opt = m_config.opt("mcp_token")) - params.mcp.token = opt->value; // Resolved now: the GUI moves the working directory to /log before the replay or script runs. - if (const auto *opt = m_config.opt("mcp_run")) - params.mcp.run_file = resolve_cli_input_path(opt->value); - if (const auto *opt = m_config.opt("mcp_run_out")) - params.mcp.run_out = resolve_cli_input_path(opt->value); + if (m_given_option_keys.count("run") > 0) { + params.mcp.run_file = resolve_cli_input_path(m_config.opt_string("run")); + params.mcp.run_out = resolve_cli_input_path(m_config.opt_string("outputdir")); + } + params.unrestricted_scripts = m_config.opt_bool("unrestricted_scripts"); + params.cad = m_config.opt_bool("cad"); BOOST_LOG_TRIVIAL(info) << "begin to launch OrcaSlicer GUI soon"; return Slic3r::GUI::GUI_Run(params); diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 6556f4b2af..939d8c5707 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13153,38 +13153,36 @@ CLIMiscConfigDef::CLIMiscConfigDef() def = this->add("mcp_port", coInt); def->label = L("MCP server port"); - def->tooltip = L("Port of the MCP server. Defaults to the preference, or 13619."); + def->tooltip = L("Start the MCP server for this run on this port, as --mcp does. 0 takes the port from the preference, or 13619."); def->cli_params = "port"; def->min = 0; def->max = 65535; def->set_default_value(new ConfigOptionInt(0)); - def = this->add("mcp_token", coString); - def->label = L("MCP server token"); - def->tooltip = L("Bearer token the MCP server requires for this run. The ORCA_MCP_TOKEN environment variable takes precedence and does not show up in the process list."); - def->cli_params = "token"; - def->set_default_value(new ConfigOptionString()); - - def = this->add("mcp_run", coString); - def->label = L("Run a replay or script"); - def->tooltip = L("Run a replay (.json) or a Python script (.py) once the GUI is ready, then exit: 0 when it passed or finished, 1 when a step failed or the script did not finish, 2 when the file is invalid or cannot be read."); - def->cli_params = "file"; - def->set_default_value(new ConfigOptionString()); - - def = this->add("mcp_run_out", coString); - def->label = L("Replay output directory"); - def->tooltip = L("Where --mcp-run writes a replay's result.json and screenshots. Defaults to .out next to the replay."); - def->cli_params = "dir"; - def->set_default_value(new ConfigOptionString()); - def = this->add("mcp_stdio", coBool); def->label = L("MCP stdio bridge"); def->tooltip = L("Act as an MCP server on standard input and output for clients that cannot use HTTP, forwarding to the running OrcaSlicer (started with --mcp when none answers)."); def->set_default_value(new ConfigOptionBool(false)); + def = this->add("run", coString); + def->label = L("Run a replay or script"); + def->tooltip = L("Run a replay (.json) or a Python script (.py) once the GUI is ready, then exit: 0 when it passed or finished, 1 when a step failed or the script did not finish, 2 when the file is invalid or cannot be read."); + def->cli_params = "file"; + def->set_default_value(new ConfigOptionString()); + + def = this->add("unrestricted_scripts", coBool); + def->label = L("Unrestricted Python scripts"); + def->tooltip = L("Let Python scripts bypass the permission checks for this run, whatever the preference says."); + def->set_default_value(new ConfigOptionBool(false)); + + def = this->add("cad", coBool); + def->label = L("Design tab"); + def->tooltip = L("Show the Design tab and offer its commands for this run, whatever the CAD feature preference says."); + def->set_default_value(new ConfigOptionBool(false)); + def = this->add("outputdir", coString); def->label = L("Output directory"); - def->tooltip = L("This is the output directory for exported files."); + def->tooltip = L("This is the output directory for exported files. With --run, it is where the run's files go: a replay's result.json and screenshots, and the files saved without a path."); def->cli_params = "dir"; def->set_default_value(new ConfigOptionString()); diff --git a/src/libslic3r_automation/CMakeLists.txt b/src/libslic3r_automation/CMakeLists.txt new file mode 100644 index 0000000000..393829d0d0 --- /dev/null +++ b/src/libslic3r_automation/CMakeLists.txt @@ -0,0 +1,69 @@ +cmake_minimum_required(VERSION 3.13) +project(libslic3r_automation) + +# The automation core: the command catalog's type, the dispatch core, the hand-off to the UI thread, the job +# registry, the followed threads, the journal, the paths, argument checking, the protocol and HTTP transport, +# what the server says of itself, the replay model, Action Replay's summary of a replay, the setup a client +# copies, the stdio bridge and the token. +# It uses no wxWidgets and nothing of libslic3r_gui, which builds the automation runtime, the MCP +# endpoint and the tool families on top of it. +# +# The sources stay beside the GUI code that uses them, under src/slic3r/GUI. The build keeps wx out: +# src/CMakeLists.txt adds this directory before it finds wxWidgets. On Linux, wx's include paths and +# definitions apply at directory scope only from the point after which this library is added. On Windows +# and macOS, wx's setup header and definitions come only with the wx targets, which this library does not +# link. So a wx include in a core unit fails to compile. The core's tests (tests/automation) link this +# library and not libslic3r_gui, so a call from a core unit into the GUI library fails to link there. +set(SLIC3R_AUTOMATION_SOURCES + ActionIds.hpp + CommandCatalog.cpp + CommandCatalog.hpp + CommandTypes.hpp + Mcp/FollowedThreads.cpp + Mcp/FollowedThreads.hpp + Mcp/JobRegistry.cpp + Mcp/JobRegistry.hpp + Mcp/McpArguments.cpp + Mcp/McpArguments.hpp + Mcp/McpCore.cpp + Mcp/McpCore.hpp + Mcp/McpHttpServer.cpp + Mcp/McpHttpServer.hpp + Mcp/McpJournal.cpp + Mcp/McpJournal.hpp + Mcp/McpOptions.hpp + Mcp/McpPaths.cpp + Mcp/McpPaths.hpp + Mcp/McpProtocol.cpp + Mcp/McpProtocol.hpp + Mcp/McpReplay.cpp + Mcp/McpReplay.hpp + Mcp/McpReplaySummary.cpp + Mcp/McpReplaySummary.hpp + Mcp/McpServerInfo.cpp + Mcp/McpSetup.cpp + Mcp/McpSetup.hpp + Mcp/McpStdioBridge.cpp + Mcp/McpStdioBridge.hpp + Mcp/McpToken.cpp + Mcp/McpToken.hpp + Mcp/UiInvoker.cpp + Mcp/UiInvoker.hpp + Mcp/WindowNames.hpp +) + +get_filename_component(_gui_dir ${CMAKE_CURRENT_SOURCE_DIR}/../slic3r/GUI ABSOLUTE) +list(TRANSFORM SLIC3R_AUTOMATION_SOURCES PREPEND ${_gui_dir}/) + +add_library(libslic3r_automation STATIC ${SLIC3R_AUTOMATION_SOURCES}) +source_group(TREE ${_gui_dir} FILES ${SLIC3R_AUTOMATION_SOURCES}) + +encoding_check(libslic3r_automation) + +target_link_libraries(libslic3r_automation PUBLIC libslic3r) + +# McpPaths.cpp calls CoreFoundation on macOS. +if (APPLE) + find_library(CORE_FOUNDATION CoreFoundation REQUIRED) + target_link_libraries(libslic3r_automation PRIVATE ${CORE_FOUNDATION}) +endif () diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 0ca804887c..18195c8a0e 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -145,8 +145,6 @@ set(SLIC3R_GUI_SOURCES GUI/ActionRegistry.hpp GUI/ActionReplayDialog.cpp GUI/ActionReplayDialog.hpp - GUI/CommandCatalog.cpp - GUI/CommandCatalog.hpp GUI/NativeCommands.cpp GUI/NativeCommands.hpp GUI/Operations/ExportOps.cpp @@ -163,43 +161,24 @@ set(SLIC3R_GUI_SOURCES GUI/Operations/RunStatus.hpp GUI/SyntheticInput.cpp GUI/SyntheticInput.hpp + GUI/Mcp/AutomationRuntime.cpp + GUI/Mcp/AutomationRuntime.hpp + GUI/Mcp/AutomationRuntimePtr.hpp GUI/Mcp/CanvasTarget.cpp GUI/Mcp/CanvasTarget.hpp - GUI/Mcp/JobRegistry.cpp - GUI/Mcp/JobRegistry.hpp - GUI/Mcp/McpArguments.cpp - GUI/Mcp/McpCore.cpp - GUI/Mcp/McpCore.hpp - GUI/Mcp/McpHttpServer.cpp - GUI/Mcp/McpHttpServer.hpp - GUI/Mcp/McpJournal.cpp - GUI/Mcp/McpJournal.hpp + GUI/Mcp/LaunchRun.cpp + GUI/Mcp/LaunchRun.hpp + GUI/Mcp/McpEndpoint.cpp + GUI/Mcp/McpEndpoint.hpp GUI/Mcp/McpPersonContext.cpp GUI/Mcp/McpPersonContext.hpp GUI/Mcp/McpPersonRun.cpp GUI/Mcp/McpPersonRun.hpp - GUI/Mcp/McpProtocol.cpp - GUI/Mcp/McpProtocol.hpp GUI/Mcp/McpRecorder.cpp GUI/Mcp/McpRecorder.hpp - GUI/Mcp/McpOptions.hpp - GUI/Mcp/McpReplay.cpp - GUI/Mcp/McpReplay.hpp - GUI/Mcp/McpReplaySummary.cpp - GUI/Mcp/McpReplaySummary.hpp - GUI/Mcp/McpService.cpp - GUI/Mcp/McpService.hpp - GUI/Mcp/McpServicePtr.hpp - GUI/Mcp/McpSetup.cpp - GUI/Mcp/McpSetup.hpp - GUI/Mcp/McpStdioBridge.cpp - GUI/Mcp/McpStdioBridge.hpp - GUI/Mcp/McpToken.cpp - GUI/Mcp/McpToken.hpp GUI/Mcp/McpTools.hpp - GUI/Mcp/McpPaths.cpp - GUI/Mcp/McpPaths.hpp GUI/Mcp/McpPluginCaller.cpp + GUI/Mcp/McpPluginCaller.hpp GUI/Mcp/McpToolsActions.cpp GUI/Mcp/McpToolsApi.cpp GUI/Mcp/McpToolsApp.cpp @@ -215,7 +194,6 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpToolsView.cpp GUI/Mcp/ScreenCapture.cpp GUI/Mcp/ScreenCapture.hpp - GUI/Mcp/McpTypes.hpp GUI/Mcp/PythonScriptsDialog.cpp GUI/Mcp/PythonScriptsDialog.hpp GUI/Mcp/MkvWriter.cpp @@ -228,8 +206,6 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/RecordingSink.hpp GUI/Mcp/UiInspector.cpp GUI/Mcp/UiInspector.hpp - GUI/Mcp/UiInvoker.cpp - GUI/Mcp/UiInvoker.hpp GUI/Mcp/UiRefs.cpp GUI/Mcp/UiRefs.hpp GUI/Mcp/VideoEncode.cpp @@ -1089,7 +1065,7 @@ else() set(_opengl_link_lib OpenGL::GL) endif() -target_link_libraries(libslic3r_gui libslic3r cereal::cereal imgui imguizmo minilzo libvgcode md4c-html glad ${_opengl_link_lib} hidapi mdns ${wxWidgets_LIBRARIES} glfw libcurl OpenSSL::SSL OpenSSL::Crypto LibDataChannel::LibDataChannel noise::noise pybind11::embed) +target_link_libraries(libslic3r_gui libslic3r libslic3r_automation cereal::cereal imgui imguizmo minilzo libvgcode md4c-html glad ${_opengl_link_lib} hidapi mdns ${wxWidgets_LIBRARIES} glfw libcurl OpenSSL::SSL OpenSSL::Crypto LibDataChannel::LibDataChannel noise::noise pybind11::embed) # MCP recordings encode their frames with libjpeg directly. libslic3r links it privately, and imported # targets are scoped to the directory that found them. diff --git a/src/slic3r/GUI/ActionIds.hpp b/src/slic3r/GUI/ActionIds.hpp new file mode 100644 index 0000000000..8071b6eca8 --- /dev/null +++ b/src/slic3r/GUI/ActionIds.hpp @@ -0,0 +1,15 @@ +#pragma once + +// The built-in action source's key and name, and the prefix of a command's tile id. No wx here: this header is part +// of the library libslic3r_automation, which is built without wx. +namespace Slic3r { namespace GUI { + +// Stable identity/display name of the built-in ("OrcaSlicer") action source. Shared by the native +// command catalog and the dynamically materialised setting/plate/recent actions so every built-in +// action re-keys together. +inline constexpr const char* kOrcaSourceKey = "orca"; +inline constexpr const char* kOrcaSourceName = "OrcaSlicer"; +// The prefix of a catalog command's tile id, "orca_command::orca" (NativeCommands::make_action()). +inline constexpr const char* kCommandPrefix = "orca_command"; + +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/ActionRegistry.cpp b/src/slic3r/GUI/ActionRegistry.cpp index 5b7aa57ecd..226130f549 100644 --- a/src/slic3r/GUI/ActionRegistry.cpp +++ b/src/slic3r/GUI/ActionRegistry.cpp @@ -1,5 +1,6 @@ #include "ActionRegistry.hpp" +#include "ActionIds.hpp" #include "CommandCatalog.hpp" #include "GUI.hpp" #include "GUI_App.hpp" diff --git a/src/slic3r/GUI/ActionRegistry.hpp b/src/slic3r/GUI/ActionRegistry.hpp index f7a2eee3d4..626d8d67d8 100644 --- a/src/slic3r/GUI/ActionRegistry.hpp +++ b/src/slic3r/GUI/ActionRegistry.hpp @@ -153,14 +153,6 @@ private: std::string m_source_name; // display name of the action's source }; -// Stable identity/display name of the built-in ("OrcaSlicer") action source. Shared by the native -// command catalog and the dynamically materialised setting/plate/recent actions so every built-in -// action re-keys together. -inline constexpr const char* kOrcaSourceKey = "orca"; -inline constexpr const char* kOrcaSourceName = "OrcaSlicer"; -// The prefix of a catalog command's tile id, "orca_command::orca" (NativeCommands::make_action()). -inline constexpr const char* kCommandPrefix = "orca_command"; - // True when a setting at `setting_mode` cannot be edited in `current_mode` and the UI must switch // first. Developer settings are handled as a separate prompt by the Speed Dial. inline bool requires_mode_switch(ConfigOptionMode setting_mode, ConfigOptionMode current_mode) diff --git a/src/slic3r/GUI/ActionReplayDialog.cpp b/src/slic3r/GUI/ActionReplayDialog.cpp index 5b907d470c..41459cb5d2 100644 --- a/src/slic3r/GUI/ActionReplayDialog.cpp +++ b/src/slic3r/GUI/ActionReplayDialog.cpp @@ -15,9 +15,9 @@ #include "Mcp/McpReplay.hpp" #include "Mcp/McpPersonRun.hpp" #include "Mcp/McpReplaySummary.hpp" -#include "Mcp/McpService.hpp" +#include "Mcp/AutomationRuntime.hpp" #include "Mcp/McpTools.hpp" -#include "Mcp/McpTypes.hpp" +#include "Mcp/WindowNames.hpp" #include "Widgets/WebViewHostDialog.hpp" #include "libslic3r/Utils.hpp" #ifdef __APPLE__ @@ -68,12 +68,6 @@ namespace fs = boost::filesystem; namespace { -Mcp::McpService* service() -{ - Mcp::McpService* s = wxGetApp().mcp_service(); - return s != nullptr && s->started() && !s->stopping() ? s : nullptr; -} - std::string timestamp() { const std::time_t t = std::time(nullptr); @@ -261,15 +255,16 @@ ActionReplayDialog::ActionReplayDialog(wxWindow* parent) : WebViewHostDialog(par { // Replays drive the main window through the MCP tools; the dialog keeps out of their sight. SetName(Mcp::kHiddenFromAutomation); - // Replaying needs the MCP service's tools and jobs, never its network endpoint. - if (service() == nullptr) - wxGetApp().start_mcp_service(false); + // Replaying needs the runtime's tools and jobs, started here without the network endpoint, and its steps drive + // the GUI. + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation()) + runtime->enable_gui_instruments(); m_ready_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); if (s == nullptr || s->ready()) m_ready_timer.Stop(); - send_service_state(); + send_runtime_state(); }); Bind(wxEVT_CLOSE_WINDOW, &ActionReplayDialog::on_close, this); static const char page[] = "web/dialog/ActionReplay/index.html"; @@ -388,7 +383,7 @@ void ActionReplayDialog::handle(const nlohmann::json& payload) const std::string command = payload.value("command", ""); try { if (command == "init") - send_service_state(); + send_runtime_state(); else if (command == "open_file") open_file(); else if (command == "edit") { @@ -421,15 +416,15 @@ void ActionReplayDialog::handle(const nlohmann::json& payload) } } -void ActionReplayDialog::send_service_state() +void ActionReplayDialog::send_runtime_state() { - Mcp::McpService* s = service(); - const bool ready = s != nullptr && s->ready(); - if (!ready && s != nullptr && !m_ready_timer.IsRunning()) + Mcp::AutomationRuntime* runtime = wxGetApp().automation(); + const bool ready = runtime != nullptr && runtime->ready(); + if (!ready && runtime != nullptr && !m_ready_timer.IsRunning()) m_ready_timer.Start(500); - json msg{{"command", "service"}, {"ready", ready}}; + json msg{{"command", "runtime"}, {"ready", ready}}; if (ready) - msg["tools"] = Mcp::editor_tool_catalog(s->catalog()); + msg["tools"] = Mcp::editor_tool_catalog(NativeCommands::instance()); call_web_handler(msg); } @@ -611,7 +606,6 @@ Mcp::ReplayContext ActionReplayDialog::context() const json ActionReplayDialog::describe(const Mcp::Replay& replay) const { - Mcp::McpService* s = service(); // ${jobs.NAME} stays as written: a full run starts from no saved jobs and a single step uses the // ones saved when it runs, so a job id resolved now would be one neither of them uses. Mcp::ReplayContext ctx = context(); @@ -619,8 +613,8 @@ json ActionReplayDialog::describe(const Mcp::Replay& replay) const json steps = json::array(); for (std::size_t i = 0; i < replay.steps.size(); ++i) { const Mcp::ReplayStep& step = replay.steps[i]; - const Mcp::StepDescription d = Mcp::describe_step(step, replay, ctx); - const NativeCommand* def = s != nullptr ? s->catalog().find(step.tool) : nullptr; + const Mcp::StepDescription d = Mcp::describe_step(NativeCommands::instance(), step, replay, ctx); + const NativeCommand* def = NativeCommands::instance().find(step.tool); json flags = json::array(); for (Mcp::StepFlag f : d.flags) flags.push_back(Mcp::flag_id(f)); @@ -647,7 +641,7 @@ void ActionReplayDialog::parse(const nlohmann::json& payload) { json reply{{"command", "parsed"}, {"seq", payload.value("seq", 0)}, {"ok", false}}; try { - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); std::string err; const auto replay = Mcp::parse_replay(m_text, err); if (s == nullptr) @@ -656,7 +650,7 @@ void ActionReplayDialog::parse(const nlohmann::json& payload) reply["error"] = err; else { for (std::size_t i = 0; i < replay->steps.size() && !reply.contains("error"); ++i) - if (s->catalog().lookup(replay->steps[i].tool) == nullptr) + if (NativeCommands::instance().lookup(replay->steps[i].tool) == nullptr) // TRN %1% is a step number, %2% the name of the tool the replay asks for. reply["error"] = format(_u8L("Step %1% uses a tool this version of OrcaSlicer doesn't have: %2%"), i + 1, replay->steps[i].tool); @@ -683,7 +677,7 @@ void ActionReplayDialog::run(const nlohmann::json& payload) { if (running()) return; - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); if (s == nullptr || !s->ready()) { refuse(_u8L("Replays can't run while OrcaSlicer is starting or closing.")); return; @@ -711,7 +705,7 @@ void ActionReplayDialog::run(const nlohmann::json& payload) // check them themselves), or ones the replay may answer the app's own question for. bool checked = false, app_asked = false, answers = false; for (std::size_t i = only ? *only - 1 : 0; i < (only ? *only : replay->steps.size()); ++i) { - const Mcp::StepDescription d = Mcp::describe_step(replay->steps[i], *replay, ctx); + const Mcp::StepDescription d = Mcp::describe_step(NativeCommands::instance(), replay->steps[i], *replay, ctx); checked = checked || d.replace == "checked"; app_asked = app_asked || d.replace == "app_asked"; answers = answers || d.answers_dialogs; @@ -775,7 +769,7 @@ void ActionReplayDialog::run(const nlohmann::json& payload) m_single = only; m_total = replay->steps.size(); m_started = std::chrono::steady_clock::now(); - m_run = s->start_replay_run(std::move(*replay), ctx, only, discard, std::move(events)); + m_run = Mcp::start_replay_run(*s, std::move(*replay), ctx, only, discard, std::move(events)); if (!m_run) { refuse(_u8L("Replays can't run while OrcaSlicer is starting or closing.")); return; @@ -786,7 +780,7 @@ void ActionReplayDialog::run(const nlohmann::json& payload) if (MainFrame* frame = wxGetApp().mainframe) keep_window_above(GetHandle(), frame->GetHandle(), true); #endif - // Reaches the page before any report of this run: those come through the service's dispatcher + // Reaches the page before any report of this run: those come through the runtime's dispatcher // and then call_web_handler(), two CallAfter()s on the app's queue, after this one. json started{{"command", "run_started"}, {"total", m_total}}; if (only) diff --git a/src/slic3r/GUI/ActionReplayDialog.hpp b/src/slic3r/GUI/ActionReplayDialog.hpp index 762cfc66a0..f52e6725c2 100644 --- a/src/slic3r/GUI/ActionReplayDialog.hpp +++ b/src/slic3r/GUI/ActionReplayDialog.hpp @@ -33,9 +33,9 @@ struct ReplayContext; // The Action Replay window: a person opens or writes a replay file (an orca_replay, the JSON list of tool calls an // agent session exports), saves it, reads its steps and replays it, whole or one step at a time, watching each step's // outcome. The page (resources/web/dialog/ActionReplay) shows; this host parses, describes, words and runs, through the -// MCP service's replay runner without opening its endpoint. A Python script opened or dropped here is offered to the Run -// Script panel instead. Modeless, one at a time (MainFrame::show_action_replay), and invisible to the MCP GUI tools, so -// a replay can't act on it. +// automation runtime's replay runner without opening the MCP endpoint. A Python script opened or dropped here is +// offered to the Run Script panel instead. Modeless, one at a time (MainFrame::show_action_replay), and invisible to +// the MCP GUI tools, so a replay can't act on it. class ActionReplayDialog : public WebViewHostDialog, public CodeEditorWindow { public: @@ -57,7 +57,7 @@ private: nlohmann::json localized_strings() const override; void handle(const nlohmann::json& payload); - void send_service_state(); + void send_runtime_state(); void open_file(); void on_navigating(wxWebViewEvent& event); void dropped(const boost::filesystem::path& path); diff --git a/src/slic3r/GUI/AuiMgr.cpp b/src/slic3r/GUI/AuiMgr.cpp index e27cbc339b..cceb7d0010 100644 --- a/src/slic3r/GUI/AuiMgr.cpp +++ b/src/slic3r/GUI/AuiMgr.cpp @@ -1,7 +1,7 @@ #include "AuiMgr.hpp" #include "GUI_App.hpp" -#include "Mcp/McpTypes.hpp" +#include "Mcp/WindowNames.hpp" #ifdef __WXGTK__ #include "LinuxDisplayBackend.hpp" #endif diff --git a/src/slic3r/GUI/BindDialog.cpp b/src/slic3r/GUI/BindDialog.cpp index 61a333e8e0..f5de676681 100644 --- a/src/slic3r/GUI/BindDialog.cpp +++ b/src/slic3r/GUI/BindDialog.cpp @@ -10,7 +10,7 @@ #include "slic3r/GUI/Widgets/Label.hpp" #include "slic3r/GUI/Widgets/HyperLink.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include #include #include diff --git a/src/slic3r/GUI/CommandCatalog.cpp b/src/slic3r/GUI/CommandCatalog.cpp index 41a38a2d94..8f0a1a4c0c 100644 --- a/src/slic3r/GUI/CommandCatalog.cpp +++ b/src/slic3r/GUI/CommandCatalog.cpp @@ -1,6 +1,7 @@ #include "CommandCatalog.hpp" -#include "Mcp/McpTypes.hpp" +#include "CommandTypes.hpp" +#include "Mcp/McpArguments.hpp" #include @@ -102,12 +103,12 @@ std::string CommandCatalog::unknown_command(const std::string& key, bool suggest namespace { -const char* guard_name(Mcp::GuardClass guard) +const char* guard_name(GuardClass guard) { switch (guard) { - case Mcp::GuardClass::Inspect: return "inspect"; - case Mcp::GuardClass::Recover: return "recover"; - case Mcp::GuardClass::Mutate: return "mutate"; + case GuardClass::Inspect: return "inspect"; + case GuardClass::Recover: return "recover"; + case GuardClass::Mutate: return "mutate"; } return "mutate"; } diff --git a/src/slic3r/GUI/CommandCatalog.hpp b/src/slic3r/GUI/CommandCatalog.hpp index 627f6e4246..4b409f7ed5 100644 --- a/src/slic3r/GUI/CommandCatalog.hpp +++ b/src/slic3r/GUI/CommandCatalog.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Mcp/McpTypes.hpp" +#include "CommandTypes.hpp" #include @@ -11,8 +11,8 @@ #include #include -// The command type and the catalog that holds every command. No wx here, so that the wx-free units of -// the MCP server can include it. +// The command type and the catalog that holds every command. No wx here: this header is part of the library +// libslic3r_automation, which is built without wx. namespace Slic3r { namespace GUI { // The group of the Design tab's commands (Mcp::register_cad_commands()), an untranslated msgid as every @@ -25,7 +25,7 @@ enum class CommandCompletion { None, Export }; // A command's function: the arguments match `input_schema`; the context is the call's, a person's pick // (ToolContext::person()) or an automated call. -using CommandFn = std::function; +using CommandFn = std::function; // One command of the app: identity, what a person sees of it, what an agent reads about it and how to // run it. NativeCommands::make_action() wraps one as a thin AppAction for the Speed Dial, so the catalog @@ -64,8 +64,8 @@ struct NativeCommand // tools, run_action, call_tool, run_replay, run_script), though what it runs may be. The client sees both in // the arguments, and the label would ask on every call. open_world: it can reach outside OrcaSlicer (a // printer, the cloud account, the network, or anything the computer allows), including through what it runs. - bool read_only = false, destructive = false, idempotent = false, open_world = false; - Mcp::GuardClass guard = Mcp::GuardClass::Mutate; + bool read_only = false, destructive = false, idempotent = false, open_world = false; + GuardClass guard = GuardClass::Mutate; // inline_call: pure observation, which runs on the request thread and is never a job; everything that can // activate UI runs as a job instead, because activating UI can open a modal that blocks the call. journal: // recorded by the session journal for export_replay; observation commands turn it off, except wait and diff --git a/src/slic3r/GUI/CommandTypes.hpp b/src/slic3r/GUI/CommandTypes.hpp new file mode 100644 index 0000000000..5222c3932b --- /dev/null +++ b/src/slic3r/GUI/CommandTypes.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// The types a command of the catalog (CommandCatalog.hpp) is called with and answers in, whichever front end +// calls it: a Speed Dial tile, an MCP tool or a plugin. No wx here: this header is part of the library +// libslic3r_automation, which is built without wx. +namespace Slic3r { namespace GUI { + +// Defined in ActionRegistry.hpp, which brings in wx: a ToolResult only holds one through a shared_ptr, which +// the code that makes one (NativeCommands.cpp) completes. +struct AppActionRunResult; +// Defined in CommandCatalog.hpp, which includes this header. +struct NativeCommand; + +namespace Mcp { +class AutomationRuntime; +} + +// What a tool may do while the app is inside another call's nested event loop or behind a modal +// dialog. Inspect tools only read; Recover tools act on the topmost modal dialog to unblock the +// app; everything else is Mutate and is refused in both situations. +enum class GuardClass { Inspect, Recover, Mutate }; + +// A tool's outcome in protocol-neutral form. `data` is the JSON the model receives as text (and a +// script evaluates `expect` against); `content` carries extra MCP content blocks such as images. +struct ToolResult +{ + nlohmann::json data = nlohmann::json::object(); + std::vector content; + bool is_error = false; + std::string message; + // What a person's pick of the command shows, in the UI's language (NativeCommands::notify_result()); + // null for a result that shows nothing. + std::shared_ptr notice; + + static ToolResult ok(nlohmann::json data = nlohmann::json::object()) + { + ToolResult r; + r.data = std::move(data); + return r; + } + static ToolResult error(std::string message, nlohmann::json details = nlohmann::json()) + { + ToolResult r; + r.is_error = true; + r.message = std::move(message); + r.data = std::move(details); + return r; + } +}; + +// Thrown by handlers (or by ToolContext on their behalf) to end a call with an isError result. +struct ToolFailure : std::runtime_error +{ + nlohmann::json details; + explicit ToolFailure(const std::string& message, nlohmann::json details = nlohmann::json()) + : std::runtime_error(message), details(std::move(details)) + {} +}; + +// The services a handler gets for one call. A client's call, a replay's and a script's run on a request or +// job thread, never on the UI thread, and everything that touches wx goes through run_ui(); a person's pick +// runs on the UI thread (person()). +class ToolContext +{ +public: + virtual ~ToolContext() = default; + // True for a person's pick from the Speed Dial or a menu: the call is on the UI thread and has no job. + virtual bool person() const { return false; } + // The automation runtime the call runs under: what a command reads the jobs, the journal, recordings and the UI + // inspector from, so that the catalog is built without a runtime. + // Throws when the call has none: std::logic_error here, ToolFailure where one cannot be started. + virtual Mcp::AutomationRuntime& runtime() { throw std::logic_error("This call runs without the automation runtime"); } + // Starts command `key` with `args` as a job and returns at once, as the reply to a long command that a + // person picks. Throws ToolFailure where this call cannot start a job. + virtual ToolResult submit(const std::string& key, const nlohmann::json& /*args*/) + { + throw ToolFailure("This call cannot start " + key + " as a job"); + } + // Runs `fn` on the UI thread under the tool's guard class and returns its value. Throws + // ToolFailure when a guard refuses the call, the UI does not pick it up in time, or the app is + // closing. + virtual nlohmann::json run_ui(const std::function& fn) = 0; + // Runs `fn` on the UI thread under the inspect guard, whatever the tool's class: for watching + // an operation the call has started, which a dialog or another call's nested loop must not stop. + virtual nlohmann::json observe_ui(const std::function& fn) = 0; + // Id of the job this call runs as; empty for inline (inspect/recover) calls. + virtual const std::string& job_id() const = 0; + // True once the runtime is stopping, or a stop was asked for this call's job or one of its + // ancestors (a replay or script the user stopped); long-running handlers poll it between steps. + virtual bool cancelled() const = 0; + // Calls another tool as a child of this call (replay steps and a script's calls). Returns what a client would get: + // the result, or a job envelope when the child outlives its reply budget. + virtual ToolResult call_child(const std::string& tool, const nlohmann::json& args) = 0; + // This call's job and its ancestors, which `wait {for:"idle"}` must not wait for. + virtual std::set lineage() const = 0; + // Replaces the arguments the session journal records for this call (refs become locators). + virtual void set_journal_args(nlohmann::json args) = 0; + // Marks this job as a slice/export operation: until it finishes, other mutate calls are refused + // so nothing changes the project under it. Call it on the UI thread before starting the work, at + // the latest in the closure that starts it; throws ToolFailure when another operation already runs. + // No-op for inline calls. + virtual void begin_operation() = 0; + // Says the call works in the open modal dialog whose serial is `dialog` (ModalTracker::serial()): + // while that dialog is the topmost, a call outliving its soft budget is still running, not + // blocked on a dialog. The web page paths of the GUI input tools say it once their page is in the + // topmost dialog, since a page can take longer than a widget to answer. Any thread; no-op for + // inline calls. + virtual void works_in_dialog(std::uint64_t /*dialog*/) {} + // The plugin whose code made this call, directly or through a call it made (a step of its script); + // empty for a client's call, a replay, and a person's or an agent's script. + virtual const std::string& caller_plugin() const + { + static const std::string none; + return none; + } +}; + +// Executes a command for the protocol layer: the runtime's core adds jobs, budgets, guards and the +// journal; tests call the command's function directly. +class ToolCaller +{ +public: + virtual ~ToolCaller() = default; + virtual ToolResult call(const NativeCommand& command, const nlohmann::json& args) = 0; +}; + +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/ConnectPrinter.cpp b/src/slic3r/GUI/ConnectPrinter.cpp index 7d587277f1..50625e2c18 100644 --- a/src/slic3r/GUI/ConnectPrinter.cpp +++ b/src/slic3r/GUI/ConnectPrinter.cpp @@ -11,7 +11,7 @@ #include #include #include "slic3r/GUI/Widgets/TextInput.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include #include #include "slic3r/GUI/wxExtensions.hpp" diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 435f67e628..bb104afc65 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -255,9 +255,12 @@ #include "slic3r/GUI/ConfigWizardTypes.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/HttpServer.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/LaunchRun.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" #include "slic3r/GUI/Mcp/McpOptions.hpp" +#include "slic3r/GUI/Mcp/McpPluginCaller.hpp" #include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/plugin/PluginOperations.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" @@ -1228,8 +1231,8 @@ void GUI_App::post_init() if (m_startup_cloud_report) std::exchange(m_startup_cloud_report, nullptr)(); - if (m_mcp) - m_mcp->mark_ready(); + if (m_automation) + m_automation->mark_ready(); BOOST_LOG_TRIVIAL(info) << "finished post_init"; //BBS: remove the single instance currently @@ -2922,7 +2925,7 @@ bool GUI_App::OnInit() int GUI_App::OnExit() { - destroy_mcp_service(); + destroy_automation(); stop_http_server(); stop_sync_user_preset(); if (m_startup_cloud_plugin_fetch_thread.joinable()) @@ -2985,9 +2988,9 @@ void GUI_App::CleanUp() stop_orca_health_check(m_agent); if (m_startup_cloud_plugin_fetch_thread.joinable()) m_startup_cloud_plugin_fetch_thread.join(); - // Same reason: the MCP server started before the first startup dialog, so an initialization that - // failed after it never reaches OnExit(). - destroy_mcp_service(); + // Same reason: the automation runtime and the MCP endpoint start before the first startup dialog, so an + // initialization that failed after them never reaches OnExit(). + destroy_automation(); wxApp::CleanUp(); } @@ -3096,13 +3099,12 @@ void GUI_App::init_plugin_gui_wiring() plugin_mgr.subscribe_on_unload_callback(PluginHostUi::close_windows_for_plugin); Mcp::install_plugin_tool_caller(); - Mcp::apply_python_scripts_setting(*app_config); // A plugin loaded again may make tool calls again. plugin_mgr.subscribe_on_load_callback([](const std::string& plugin_key) { if (wxTheApp != nullptr) wxGetApp().CallAfter([plugin_key] { - if (Mcp::McpService* service = wxGetApp().mcp_service(); service != nullptr && service->started()) - service->plugin_loaded(plugin_key); + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->plugin_loaded(plugin_key); }); }); plugin_mgr.subscribe_on_unload_callback([](const std::string& plugin_key) { @@ -3110,8 +3112,8 @@ void GUI_App::init_plugin_gui_wiring() // What the plugin's tool calls left behind (rules, a recording, a held press) ends with it. if (wxTheApp != nullptr) wxGetApp().CallAfter([plugin_key] { - if (Mcp::McpService* service = wxGetApp().mcp_service(); service != nullptr && service->started()) - service->end_plugin_scope(plugin_key); + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->end_plugin_scope(plugin_key); }); }); plugin_mgr.subscribe_on_load_callback([refresh_plugins_dialog](const std::string&) { refresh_plugins_dialog(); }); @@ -3291,7 +3293,7 @@ bool GUI_App::on_init_inner() // Stop the Orca Cloud health check as OnExit() does, so no request is in flight while exit() tears down. wxGetApp().Bind(wxEVT_END_SESSION, [this](wxCloseEvent &e) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "received wxEVT_END_SESSION"; - stop_mcp_service(); + stop_automation(); stop_sync_user_preset(); stop_orca_health_check(m_agent); // Before the plugin manager and network module go away. @@ -3356,18 +3358,25 @@ bool GUI_App::on_init_inner() // wxSystemOptions::SetOption("msw.notebook.themed-background", 0); // Slic3r::debugf "wxWidgets version %s, Wx version %s\n", wxVERSION_STRING, wxVERSION; - // The command catalog, before anything that runs or lists a command: the MCP service below and the - // Speed Dial's action registry. The preference is read from the config, since is_enable_cad_feature() is in - // a CAD build only. - NativeCommands::build({is_editor() && app_config->get_bool("enable_cad_feature")}); + // The command catalog, before anything that runs or lists a command: the automation runtime below and the + // Speed Dial's action registry. Then the Python scripts setting's value in force, before the endpoint opens and + // the command line's run starts, so that get_app_state and the first script read it. Each value in force is the + // 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}); + Mcp::set_python_scripts_for_run(init_params != nullptr && init_params->unrestricted_scripts); + Mcp::apply_python_scripts_setting(*app_config); - // The MCP server starts before the first startup dialog (the TLS prompt below, the setup wizard) + // The MCP endpoint opens before the first startup dialog (the TLS prompt below, the setup wizard) // so an agent can see and answer it; tools that need the main window report not-ready until - // post_init() has run. + // post_init() has run. A --run alone starts the runtime without the endpoint. if (init_params != nullptr) { - const bool serve = init_params->mcp.enable || app_config->get_bool("mcp_enabled"); - if (serve || !init_params->mcp.run_file.empty()) - start_mcp_service(serve); + if (init_params->mcp.enable || app_config->get_bool("mcp_enabled")) + open_mcp_endpoint(); + if (!init_params->mcp.run_file.empty()) + if (Mcp::AutomationRuntime* runtime = automation()) + Mcp::start_launch_run(*runtime, init_params->mcp); } if (is_editor()) { std::string msg = Slic3r::Http::tls_global_init(); @@ -5106,8 +5115,8 @@ void GUI_App::recreate_GUI(const wxString &msg_name) update_publish_status(); m_is_recreating_gui = false; - if (m_mcp) - m_mcp->resume(); + if (m_automation) + m_automation->resume(); if (m_run_script_panel) m_run_script_panel->main_window_rebuilt(); @@ -8498,78 +8507,101 @@ void GUI_App::stop_http_server() m_http_server->stop(); } -bool GUI_App::start_mcp_service(bool serve, std::string* error) +namespace { + +// What the MCP endpoint could not open for, as an error notification once the main window has a plater. +void show_mcp_endpoint_error(const std::string& err) { - // Only the launch options from the command line carry a file to run (--mcp-run); a later start from Preferences - // must not run it again. - Mcp::McpLaunchOptions options; - if (init_params != nullptr && !m_post_initialized) - options = init_params->mcp; - else if (init_params != nullptr) { - options.port = init_params->mcp.port; - options.token = init_params->mcp.token; - } - if (!m_mcp) - m_mcp.reset(new Mcp::McpService()); - if (serve) - m_mcp_wanted = true; + if (Plater* plater = wxGetApp().plater()) + plater->get_notification_manager()->push_notification(NotificationType::CustomNotification, + NotificationManager::NotificationLevel::ErrorNotificationLevel, err); +} + +} // namespace + +Mcp::AutomationRuntime* GUI_App::automation() +{ + if (is_closing()) + return nullptr; + // A runtime that has stopped is kept, and refuses to start again. + if (!m_automation) + m_automation.reset(new Mcp::AutomationRuntime()); std::string err; - const bool ok = m_mcp->start(options, serve, err); - if (!ok && serve && m_mcp->port_held_by_other_window()) { - // Another window that shares the configuration folder serves agents. Not an error: try the - // port every few seconds, so agents keep a server once that window closes. - if (!m_mcp_takeover_timer) { - m_mcp_takeover_timer = std::make_unique(); - m_mcp_takeover_timer->Bind(wxEVT_TIMER, [this](wxTimerEvent&) { - if (m_mcp_wanted && m_mcp && !m_mcp->serving() && !is_closing()) - start_mcp_service(true); - else - m_mcp_takeover_timer->Stop(); - }); - } - if (!m_mcp_takeover_timer->IsRunning()) - m_mcp_takeover_timer->Start(3000); - } else { - if (m_mcp_takeover_timer) - m_mcp_takeover_timer->Stop(); - if (!ok && plater() != nullptr) - plater()->get_notification_manager()->push_notification(NotificationType::CustomNotification, - NotificationManager::NotificationLevel::ErrorNotificationLevel, - err); - } + if (!m_automation->start(err)) + return nullptr; if (m_post_initialized) - m_mcp->mark_ready(); + m_automation->mark_ready(); + return m_automation.get(); +} + +Mcp::AutomationRuntime* GUI_App::automation_if_started() { return m_automation.get(); } + +Mcp::McpEndpoint* GUI_App::mcp_endpoint() { return m_mcp_endpoint.get(); } + +bool GUI_App::open_mcp_endpoint(std::string* error) +{ + std::string err; + bool ok = false; + if (Mcp::AutomationRuntime* runtime = automation()) { + if (!m_mcp_endpoint) + // A retry that fails for another reason than the port being held is shown as a first open's failure is. + m_mcp_endpoint = std::make_unique(*runtime, show_mcp_endpoint_error); + // The command line's port, if any. + const int option_port = init_params != nullptr ? init_params->mcp.port : 0; + ok = m_mcp_endpoint->open(Mcp::endpoint_port(option_port, app_config != nullptr ? app_config->get("mcp_port") : std::string()), + err); + // Another window that shares the configuration folder serves agents: not an error, and the endpoint takes + // the port over when that window closes. + if (!ok && !m_mcp_endpoint->port_held_by_other_window()) + show_mcp_endpoint_error(err); + } else + err = "OrcaSlicer is closing"; if (error != nullptr) *error = err; return ok; } -void GUI_App::stop_mcp_endpoint() +void GUI_App::close_mcp_endpoint() { - m_mcp_wanted = false; - if (m_mcp_takeover_timer) - m_mcp_takeover_timer->Stop(); - if (m_mcp) - m_mcp->stop_serving(); + if (m_mcp_endpoint) + m_mcp_endpoint->close(); } bool GUI_App::restart_mcp_endpoint(std::string* error) { if (init_params != nullptr) init_params->mcp.port = 0; - if (!m_mcp || !m_mcp->serving()) + // Serving, or waiting for the port another window holds: either goes to the new port. + if (!m_mcp_endpoint || !(m_mcp_endpoint->serving() || m_mcp_endpoint->port_held_by_other_window())) return true; - m_mcp->stop_serving(); - return start_mcp_service(true, error); + m_mcp_endpoint->close(); + return open_mcp_endpoint(error); } -void GUI_App::stop_mcp_service() +void GUI_App::stop_automation() { - m_mcp_wanted = false; - if (m_mcp_takeover_timer) - m_mcp_takeover_timer->Stop(); - if (m_mcp) - m_mcp->stop(); + if (m_mcp_endpoint) + m_mcp_endpoint->close(); + if (m_automation) + m_automation->stop(); +} + +void GUI_App::destroy_automation() +{ + // The Run Script panel's session is a job of the runtime: it goes first. + m_run_script_panel.reset(); + stop_automation(); + // Outside any event loop, so nothing the waits hold up can be running. A request thread still inside the + // protocol reaches the runtime's core through it: then neither is freed. + if (m_mcp_endpoint && !m_mcp_endpoint->drain(std::chrono::seconds(10))) { + BOOST_LOG_TRIVIAL(error) << "MCP server: a request did not return; leaving the endpoint and the automation runtime in place"; + (void) m_mcp_endpoint.release(); + (void) m_automation.release(); + return; + } + m_mcp_endpoint.reset(); + // Its deleter waits for running calls, and leaves in place a runtime whose calls never return. + m_automation.reset(); } RunScriptPanel& GUI_App::run_script_panel() @@ -8579,17 +8611,6 @@ RunScriptPanel& GUI_App::run_script_panel() return *m_run_script_panel; } -void GUI_App::destroy_mcp_service() -{ - // The Run Script panel's session is a job of the service: it goes first. - m_run_script_panel.reset(); - // Before wxApp::CleanUp(): a timer must not outlive the toolkit. - m_mcp_takeover_timer.reset(); - // Outside any event loop: the deleter waits for running calls, and leaks a service whose calls - // never return. - m_mcp.reset(); -} - #ifdef __linux__ static const wxLanguageInfo* linux_get_existing_locale_language(const wxLanguageInfo* language, const wxLanguageInfo* system_language) diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index 261c86037a..71c2144ac5 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -23,7 +23,8 @@ #include "libslic3r/PresetBundle.hpp" #include "libslic3r_version.h" #include "slic3r/GUI/UserNotification.hpp" -#include "slic3r/GUI/Mcp/McpServicePtr.hpp" +#include "slic3r/GUI/GUI_Init.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntimePtr.hpp" #include "slic3r/Utils/CloudDeleteQueue.hpp" #include "slic3r/Utils/CloudProvider.hpp" #include "libslic3r/Point.hpp" @@ -56,7 +57,6 @@ class wxMenuItem; class wxMenuBar; -class wxTimer; class wxTopLevelWindow; class wxDataViewCtrl; class wxBookCtrlBase; @@ -120,6 +120,9 @@ class HttpServer; class ImGuiWrapper; class OpenGLManager; class UpgradeNetworkJob; +namespace Mcp { +class McpEndpoint; +} typedef std::function InstallProgressFn; @@ -386,10 +389,11 @@ private: bool m_show_error_msgdlg{false}; wxString m_info_dialog_content; std::unique_ptr m_http_server; - Mcp::McpServicePtr m_mcp; + Mcp::AutomationRuntimePtr m_automation; + // After the runtime, so it is destroyed first: it holds the runtime by reference. Null in a session that never + // opened it. + std::unique_ptr m_mcp_endpoint; std::unique_ptr m_run_script_panel; - bool m_mcp_wanted = false; // the endpoint should be open: --mcp, the preference, or Preferences - std::unique_ptr m_mcp_takeover_timer; // retries the port another window holds; created on first need bool m_show_gcode_window{true}; boost::thread m_check_network_thread; public: @@ -403,7 +407,11 @@ public: bool initialized() const { return m_initialized; } inline bool is_enable_multi_machine() { return this->app_config&& this->app_config->get("enable_multi_machine") == "true"; } #ifdef SLIC3R_CAD - inline bool is_enable_cad_feature() { return this->app_config && this->app_config->get_bool("enable_cad_feature"); } + // the saved preference + bool cad_feature_setting() const { return this->app_config && this->app_config->get_bool("enable_cad_feature"); } + // in force: the preference, or --cad for this run + bool is_enable_cad_feature() const { return cad_feature_setting() || cad_feature_set_for_run(); } + bool cad_feature_set_for_run() const { return this->init_params != nullptr && this->init_params->cad; } inline bool is_auto_close_sketch_loops() { return !this->app_config || this->app_config->get_bool("auto_close_sketch_loops"); } #endif @@ -668,24 +676,30 @@ public: void start_http_server(int port, const std::string& provider = ORCA_CLOUD_PROVIDER); void stop_http_server(); - // MCP server for AI agents, from Preferences or --mcp/--mcp-run. `serve` opens the HTTP - // endpoint; a --mcp-run alone needs only the tool catalog. While another window that shares - // the configuration folder holds the port, this one keeps trying and takes it over when that - // window closes. UI thread. - bool start_mcp_service(bool serve, std::string* error = nullptr); - // Closes the endpoint until the next start, as turning the server off in Preferences does; the - // service lives on, since an MCP call may have opened Preferences. - void stop_mcp_endpoint(); - // Stops the MCP service but keeps it: a call may still be on the stack (a nested event loop). - void stop_mcp_service(); - // Stops it and frees it once no call runs in it. Outside any event loop only (OnExit, CleanUp). - void destroy_mcp_service(); - // Moves the MCP endpoint to the port set in Preferences, which replaces one given on the command - // line for the rest of the session: a serving endpoint reopens on it, and a later start opens on it. - bool restart_mcp_endpoint(std::string* error = nullptr); - Mcp::McpService* mcp_service() { return m_mcp.get(); } - // The Run Script panel's controller, built on first use and kept until the MCP service, whose job hosts its session, - // goes away. + // The automation runtime, ready for use: started, by this call if need be and without the MCP endpoint, and not + // stopping. nullptr while OrcaSlicer closes or the runtime stops. UI thread. + Mcp::AutomationRuntime* automation(); + // The runtime if something has started it, stopping or not. Never starts it. UI thread. + Mcp::AutomationRuntime* automation_if_started(); + // The MCP endpoint, or nullptr before the first open. UI thread. + Mcp::McpEndpoint* mcp_endpoint(); + // Opens the endpoint on the port of the command line, else of the preference, starting the runtime first. + // Shows a notification when it cannot open and no other window holds the port. While OrcaSlicer closes it + // opens nothing and only returns the error. + bool open_mcp_endpoint(std::string* error = nullptr); + // Closes the endpoint until the next open, as turning the server off in Preferences does. The runtime carries + // on, since an MCP call may have opened Preferences. UI thread. + void close_mcp_endpoint(); + // Moves the endpoint to the port set in Preferences, which replaces one given on the command line for the rest + // of the session: an endpoint that serves, or waits for a port another window holds, reopens on it, and a later + // open opens on it. UI thread. + bool restart_mcp_endpoint(std::string* error = nullptr); + // Closes the endpoint, then stops the runtime; both are kept, since a call may still be on the stack. + void stop_automation(); + // Stops both and frees them once no thread is inside. Outside any event loop only (OnExit, CleanUp). + void destroy_automation(); + // The Run Script panel's controller, built on first use and kept until the automation runtime, whose job hosts + // its session, goes away. RunScriptPanel& run_script_panel(); RunScriptPanel* run_script_panel_if_built() { return m_run_script_panel.get(); } diff --git a/src/slic3r/GUI/GUI_Init.cpp b/src/slic3r/GUI/GUI_Init.cpp index 43d0a4b9d1..abee9b372e 100644 --- a/src/slic3r/GUI/GUI_Init.cpp +++ b/src/slic3r/GUI/GUI_Init.cpp @@ -4,7 +4,7 @@ #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/InstanceCheck.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" +#include "slic3r/GUI/Mcp/LaunchRun.hpp" #ifdef __APPLE__ #include "slic3r/GUI/DeepLinkHandlerMac.h" #endif @@ -55,7 +55,8 @@ int GUI_Run(GUI_InitParams ¶ms) //if (gui->get_app_mode() != GUI::GUI_App::EAppMode::GCodeViewer) { // G-code viewer is currently not performing instance check, a new G-code viewer is started every time. bool gui_single_instance_setting = gui->app_config->get("app", "single_instance") == "true"; - if (Slic3r::instance_check(params.argc, params.argv, gui_single_instance_setting)) { + // A command line's run reports its own exit code, so it keeps a window of its own. + if (Slic3r::instance_check(params.argc, params.argv, gui_single_instance_setting, !params.mcp.run_file.empty())) { //TODO: do we have delete gui and other stuff? return -1; } @@ -79,8 +80,8 @@ int GUI_Run(GUI_InitParams ¶ms) } else { result = wxEntry(params.argc, params.argv); } - // A --mcp-run file reports its outcome as the process exit code. - if (const int run_code = Mcp::McpService::run_exit_code(); run_code >= 0) + // A --run file reports its outcome as the process exit code. + if (const int run_code = Mcp::launch_exit_code(); run_code >= 0) return run_code; return result; } catch (const Slic3r::Exception &ex) { diff --git a/src/slic3r/GUI/GUI_Init.hpp b/src/slic3r/GUI/GUI_Init.hpp index ed110c50b9..ab89cb2e35 100644 --- a/src/slic3r/GUI/GUI_Init.hpp +++ b/src/slic3r/GUI/GUI_Init.hpp @@ -38,6 +38,9 @@ struct GUI_InitParams bool input_gcode { false }; Mcp::McpLaunchOptions mcp; + // On for this run only: the command line never writes these settings. + bool unrestricted_scripts = false; // --unrestricted-scripts + bool cad = false; // --cad }; int GUI_Run(GUI_InitParams ¶ms); diff --git a/src/slic3r/GUI/ImGuiWrapper.hpp b/src/slic3r/GUI/ImGuiWrapper.hpp index 78c49e6054..b5d522d75d 100644 --- a/src/slic3r/GUI/ImGuiWrapper.hpp +++ b/src/slic3r/GUI/ImGuiWrapper.hpp @@ -58,12 +58,12 @@ bool menu_item_with_icon(const char *label, const char *shortcut, ImVec2 icon_si class ImGuiWrapper { public: - // Automation (the MCP server) lists and clicks ImGui items, which have no window handles. While - // recording is on, every item a frame adds is recorded with its id, label, window and rectangle - // (in ImGui coordinates), along with the values fields show and the text the frame draws, per - // canvas: the canvas calls set_frame_owner() before new_frame(), and end_frame() publishes the - // frame's items as that owner's latest. Off unless the MCP server runs; ImGui then skips the - // hooks with one branch per item. + // Automation lists and clicks ImGui items, which have no window handles. While recording is on, + // every item a frame adds is recorded with its id, label, window and rectangle (in ImGui + // coordinates), along with the values fields show and the text the frame draws, per canvas: the + // canvas calls set_frame_owner() before new_frame(), and end_frame() publishes the frame's items as + // that owner's latest. Off unless the GUI instruments are on (`enable_gui_instruments()`); ImGui + // then skips the hooks with one branch per item. struct RecordedItem { unsigned id = 0; diff --git a/src/slic3r/GUI/InstanceCheck.cpp b/src/slic3r/GUI/InstanceCheck.cpp index d8365be97e..f6a2d0f9f7 100644 --- a/src/slic3r/GUI/InstanceCheck.cpp +++ b/src/slic3r/GUI/InstanceCheck.cpp @@ -314,7 +314,7 @@ namespace instance_check_internal #endif //__APPLE__/__linux__ } //namespace instance_check_internal -bool instance_check(int argc, char** argv, bool app_config_single_instance) +bool instance_check(int argc, char** argv, bool app_config_single_instance, bool never_send) { std::size_t hashed_path; #ifdef _WIN32 @@ -358,6 +358,8 @@ bool instance_check(int argc, char** argv, bool app_config_single_instance) instance_check_internal::CommandLineAnalysis cla = instance_check_internal::process_command_line(argc, argv); if (! cla.should_send.has_value()) cla.should_send = app_config_single_instance; + if (never_send) + cla.should_send = false; #ifdef _WIN32 GUI::wxGetApp().init_single_instance_checker(lock_name + ".lock", data_dir() + "\\cache\\"); if (cla.should_send.value() && GUI::wxGetApp().single_instance_checker()->IsAnotherRunning()) { diff --git a/src/slic3r/GUI/InstanceCheck.hpp b/src/slic3r/GUI/InstanceCheck.hpp index 635004e2eb..f5290bf8cc 100644 --- a/src/slic3r/GUI/InstanceCheck.hpp +++ b/src/slic3r/GUI/InstanceCheck.hpp @@ -27,7 +27,8 @@ namespace Slic3r { // checks for other running instances and sends them argv, // if there is --single-instance argument or AppConfig is set to single_instance=1 // returns true if this instance should terminate -bool instance_check(int argc, char** argv, bool app_config_single_instance); +// `never_send`: this launch is not handed to a running instance, whatever the setting says. +bool instance_check(int argc, char** argv, bool app_config_single_instance, bool never_send = false); #if __APPLE__ // apple implementation of inner functions of instance_check diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index ec40703570..f1c4dff7c1 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -117,7 +117,7 @@ #include "../Utils/PrintHost.hpp" #include "GUI_App.hpp" -#include "Mcp/McpService.hpp" +#include "Mcp/AutomationRuntime.hpp" #include "ImGuiWrapper.hpp" #include "OpenGLManager.hpp" #include "Shortcuts.hpp" @@ -1363,14 +1363,13 @@ void MainFrame::update_edge_panels() void MainFrame::shutdown() { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "MainFrame::shutdown enter"; - // MCP calls must not reach panels that are about to go away. A language change rebuilds the - // frame, so the server only pauses until GUI_App::recreate_GUI() resumes it. - if (Mcp::McpService* mcp = wxGetApp().mcp_service()) { - if (wxGetApp().is_recreating_gui()) - mcp->suspend(); - else - wxGetApp().stop_mcp_service(); - } + // Automation calls must not reach panels that are about to go away. A language change rebuilds the + // frame, so the runtime only pauses until GUI_App::recreate_GUI() resumes it, and the MCP endpoint stays open. + if (wxGetApp().is_recreating_gui()) { + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->suspend(); + } else + wxGetApp().stop_automation(); m_idle.stop(); if (ProjectPanel* project = ProjectPanel::if_built()) project->shutdown(); diff --git a/src/slic3r/GUI/Mcp/AutomationRuntime.cpp b/src/slic3r/GUI/Mcp/AutomationRuntime.cpp new file mode 100644 index 0000000000..206ad6c908 --- /dev/null +++ b/src/slic3r/GUI/Mcp/AutomationRuntime.cpp @@ -0,0 +1,581 @@ +#include "AutomationRuntime.hpp" + +#include "AutomationRuntimePtr.hpp" +#include "FollowedThreads.hpp" +#include "JobRegistry.hpp" +#include "McpCore.hpp" +#include "McpRecorder.hpp" +#include "ModalTracker.hpp" +#include "UiInspector.hpp" +#include "UiInvoker.hpp" +#include "WebPages.hpp" +#include "WindowControl.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" +#include "slic3r/plugin/PluginManager.hpp" + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +class WxDispatcher final : public UiDispatcher +{ +public: + void post(std::function fn) override + { + // CallAfter queues a thread-safe event; without an app the closure never runs and its + // caller gives up after the queue timeout. + if (wxTheApp == nullptr) + return; + wxTheApp->CallAfter(std::move(fn)); +#ifdef __WXMSW__ + // CallAfter wakes only wx's own loop. In a native modal loop, a menu's or a system dialog's, wx runs + // queued events from a message hook when the loop takes a message off the thread's queue, so give it one + // rather than wait for an unrelated message. + wxWakeUpMainThread(); +#endif + } +}; + +// Whether the Prepare canvas has loaded OpenGL: its functions, shaders and the ImGui font. +bool canvas_gl_ready() +{ + Plater* plater = wxGetApp().plater(); + GLCanvas3D* canvas = plater != nullptr ? plater->canvas3D() : nullptr; + return canvas == nullptr || canvas->is_initialized(); +} + +// Whether the main window has tab pages still to build at idle. +bool pages_pending() +{ + const MainFrame* frame = wxGetApp().mainframe; + return frame != nullptr && frame->prebuild_pending(); +} + +// The Plater's UI job worker, as McpCore watches it for jobs that calls start. +WorkerHooks ui_job_worker_hooks() +{ + WorkerHooks hooks; + hooks.busy = [] { + Plater* plater = wxGetApp().plater(); + return plater != nullptr && !plater->get_ui_job_worker().is_idle(); + }; + hooks.cancel = [] { + if (Plater* plater = wxGetApp().plater()) + plater->get_ui_job_worker().cancel(); + }; + return hooks; +} + +// The scope key of a plugin's calls, which no job id ("j") can equal. +std::string plugin_scope_key(const std::string& plugin_key) { return "plugin:" + plugin_key; } + +} // namespace + +void AutomationRuntimeDeleter::operator()(AutomationRuntime* runtime) const +{ + runtime->stop(); + if (runtime->drain(std::chrono::seconds(10))) + delete runtime; + else + BOOST_LOG_TRIVIAL(error) << "Automation runtime: a call did not return; leaving it in place"; +} + +AutomationRuntime::AutomationRuntime() = default; + +// Reached only through AutomationRuntimeDeleter, after stop() joined the followed calls' threads and drain() saw +// every thread leave. +AutomationRuntime::~AutomationRuntime() = default; + +GuardState AutomationRuntime::guards_on_ui() const +{ + GuardState g; + g.closing = m_stopping || wxTheApp == nullptr || wxGetApp().is_closing(); + g.suspended = m_suspended; + if (m_modals) { + g.dialogs = m_modals->snapshot(); + g.modal = !g.dialogs.empty(); + g.top_dialog = m_modals->serial(m_modals->top()); + } + return g; +} + +bool AutomationRuntime::start(std::string& err) +{ + if (m_stopping) { + err = "The automation runtime has stopped for exit"; + return false; + } + if (m_core == nullptr) { + m_dispatcher = std::make_unique(); + m_modals = std::make_unique(); + m_recorder = std::make_unique(*m_modals, [this] { return m_generation.load(); }, [this] { return m_suspended.load(); }, + [this](std::function fn) { post_ui(std::move(fn)); }); + // A call's window for taking menus is the inspector's: none while the GUI instruments are off. + m_invoker = std::make_unique(*m_dispatcher, [this] { return guards_on_ui(); }, [this] { return m_generation.load(); }, + [this] { return m_modals->snapshot(); }, + [this](const std::string& tool, bool running) { + if (m_inspector) + m_inspector->ui_activity(tool, running); + }); + // A plugin's calls are refused from the moment it unloads, before end_plugin_scope() comes. + m_jobs.set_owner_liveness([](const std::string& plugin) { return PluginManager::instance().is_plugin_loaded(plugin); }); + m_core = std::make_unique(NativeCommands::instance(), *m_invoker, m_jobs, &m_journal, CoreTiming{}, + ui_job_worker_hooks(), m_recorder.get()); + // A command reaches the runtime through its call's context (ToolContext::runtime()). + m_core->set_runtime(this); + m_web_presses = std::make_shared(); + m_modals->set_before_press([this] { release_web_presses(m_web_presses, nullptr); }); + BOOST_LOG_TRIVIAL(info) << "Automation runtime started"; + } + return true; +} + +void AutomationRuntime::enable_gui_instruments() +{ + // The inspector is built on the modal tracker, so nothing comes before start(). + if (m_inspector != nullptr || m_modals == nullptr) + return; + m_inspector = std::make_unique(*m_modals, [this] { return m_generation.load(); }); + // Once stop() has taken the instruments down, a call still on the UI thread's stack gets an inspector with + // nothing installed. + if (m_stopping) + return; + track_window_states(); + m_inspector->capture_menus(true); + if (ImGuiWrapper* imgui = wxGetApp().imgui()) + imgui->set_item_recording(true); + // ImGui items are recorded as a frame draws them, and a view already shown draws none until it changes. + if (GLCanvas3D* canvas = shown_canvas()) { + canvas->set_as_dirty(); + wxWakeUpIdle(); + } + BOOST_LOG_TRIVIAL(info) << "Automation GUI instruments on"; +} + +UiInspector& AutomationRuntime::inspector() +{ + // Only a command reaches it, so the runtime is started and the inspector is made here if need be. + if (m_inspector == nullptr) + enable_gui_instruments(); + return *m_inspector; +} + +void AutomationRuntime::stop() +{ + // Before the stop flag: a run's stop does nothing once the runtime is stopping, and it must cancel + // the run's slice while the main window is still there. + if (m_core != nullptr && !m_stopping) + stop_followed(); + if (m_core == nullptr || m_stopping.exchange(true)) + return; + BOOST_LOG_TRIVIAL(info) << "Automation runtime stopping"; + // Its file is finished on the recorder's own threads; this waits a little for them, not for the UI. + m_recorder->shutdown(std::chrono::seconds(5)); + if (m_ready_timer) + m_ready_timer->Stop(); + // Wake everything that waits, so running calls return. + m_invoker->shutdown(); + m_jobs.wake_all(); + m_core->shutdown(); + // What a client left behind ends with the stop, also when no endpoint closed its scope first. + close_client_scope(); + // The waits above are woken, so the followed calls return; one followed from here on is refused. + m_followed.join_all(); + { + // Run rules too: no run survives the stop. + std::lock_guard lock(m_rules_mutex); + for (const auto& [job, layers] : m_run_rule_layers) + for (int layer : layers) + m_modals->pop_rules(layer); + m_run_rule_layers.clear(); + } + release_web_presses(m_web_presses, nullptr); + // The GUI instruments, when they were turned on. + if (m_inspector) { + m_inspector->release_held(nullptr); + m_inspector->capture_menus(false); + } + SyntheticInput::clear(); + if (m_inspector && wxTheApp != nullptr) + if (ImGuiWrapper* imgui = wxGetApp().imgui()) + imgui->set_item_recording(false); +} + +bool AutomationRuntime::acquire_lease() +{ + if (m_stopping) + return false; + ++m_leases; + // A stop that came meanwhile may already be draining: give the lease back rather than race it. + if (m_stopping) { + --m_leases; + return false; + } + return true; +} + +void AutomationRuntime::release_lease() { --m_leases; } + +bool AutomationRuntime::drain(std::chrono::milliseconds timeout) +{ + const auto deadline = std::chrono::steady_clock::now() + timeout; + // A lease's holder finds the core stopped and returns at once. + while (m_leases.load() > 0) { + if (std::chrono::steady_clock::now() >= deadline) + return false; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + if (m_core == nullptr) + return true; + const auto left = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); + return m_core->drain(std::max(left, std::chrono::milliseconds(0))); +} + +AutoAnswerSet AutomationRuntime::set_auto_answer(std::vector rules, const std::vector& ancestry) +{ + // A plugin's call is owned by its plugin's scope when no run in its chain is nearer. + const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); + std::lock_guard lock(m_rules_mutex); + // The nearest running replay or script in the caller's job chain owns the rules. + for (const std::string& job : ancestry) + if (auto it = m_run_rule_layers.find(job); it != m_run_rule_layers.end()) { + const bool paused = m_paused_scopes.count(job) != 0; + if (rules.empty()) + return {"run", 0, paused}; + it->second.push_back(m_modals->push_rules(std::move(rules), paused)); + return {"run", it->second.back(), paused}; + } + if (!plugin.empty()) { + if (auto it = m_run_rule_layers.find(plugin_scope_key(plugin)); it != m_run_rule_layers.end()) { + if (rules.empty()) + return {"plugin", 0, false}; + it->second.push_back(m_modals->push_rules(std::move(rules))); + return {"plugin", it->second.back(), false}; + } + if (m_unloaded_plugins.count(plugin) != 0) + throw ToolFailure("The plugin that made this call has been unloaded; its rules were not applied"); + } + // A call that was running when the client scope closed must not bring its client's rules back. + if (!m_client_scope_open) + throw ToolFailure("The MCP server was turned off while the rules were being set; they were not applied"); + if (m_session_rule_layer != 0) + m_modals->pop_rules(m_session_rule_layer); + m_session_rule_layer = rules.empty() ? 0 : m_modals->push_rules(std::move(rules)); + return {"session", m_session_rule_layer, false}; +} + +void AutomationRuntime::begin_run_scope(const std::string& job) +{ + std::lock_guard lock(m_rules_mutex); + m_run_rule_layers.emplace(job, std::vector{}); +} + +void AutomationRuntime::end_run_scope(const std::string& job, bool wait_recording) +{ + // Noted before the scope goes: from then on a call of this run finds no live scope, and must not be + // taken for a client's. + if (m_recorder) + m_recorder->owner_ended(job); + { + std::lock_guard lock(m_rules_mutex); + auto it = m_run_rule_layers.find(job); + if (it == m_run_rule_layers.end()) + return; + if (m_modals) + for (int layer : it->second) + m_modals->pop_rules(layer); + m_run_rule_layers.erase(it); + m_paused_scopes.erase(job); + } + // A recording the run started ends with it, its file closed before the run's call returns. + if (m_recorder) + m_recorder->end_owned_by(job, "run_ended", wait_recording); + release_run_presses(job); +} + +void AutomationRuntime::set_run_scope_paused(const std::string& job, bool paused) +{ + std::lock_guard lock(m_rules_mutex); + auto it = m_run_rule_layers.find(job); + if (it == m_run_rule_layers.end()) + return; + if (paused) + m_paused_scopes.insert(job); + else + m_paused_scopes.erase(job); + if (m_modals) + for (int layer : it->second) + m_modals->set_paused(layer, paused); +} + +void AutomationRuntime::release_run_presses(const std::string& job) +{ + // Found again on the UI thread: the runtime may be gone by the time the closure runs. + if (m_dispatcher && !m_stopping) + m_dispatcher->post([job] { + if (AutomationRuntime* runtime = wxGetApp().automation_if_started(); runtime != nullptr) { + if (runtime->m_inspector) + runtime->m_inspector->release_held(&job); + release_web_presses(runtime->m_web_presses, &job); + } + }); +} + +void AutomationRuntime::cancel_operations_of(const std::string& job) +{ + for (const std::string& op : m_jobs.running_operations()) + if (m_jobs.lineage(op).count(job) != 0 && !m_core->cancel_worker(op)) + if (Plater* plater = wxGetApp().plater()) + plater->cancel_slicing(); +} + +std::string AutomationRuntime::run_owner(const std::vector& ancestry) const +{ + const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); + std::lock_guard lock(m_rules_mutex); + for (const std::string& job : ancestry) + if (m_run_rule_layers.count(job) != 0) + return job; + if (!plugin.empty() && m_run_rule_layers.count(plugin_scope_key(plugin)) != 0) + return plugin_scope_key(plugin); + // A call of an unloaded plugin must not leave anything nothing would end. + if (!plugin.empty() && m_unloaded_plugins.count(plugin) != 0) + throw ToolFailure("The plugin that made this call has been unloaded"); + return {}; +} + +bool AutomationRuntime::begin_plugin_scope(const std::string& plugin_key) +{ + std::lock_guard lock(m_rules_mutex); + if (m_unloaded_plugins.count(plugin_key) != 0) + return false; + m_run_rule_layers.emplace(plugin_scope_key(plugin_key), std::vector{}); + return true; +} + +void AutomationRuntime::end_plugin_scope(const std::string& plugin_key) +{ + { + std::lock_guard lock(m_rules_mutex); + m_unloaded_plugins.insert(plugin_key); + } + // No call of the plugin starts from now on, one it was admitted for included, and the ones running stop, + // as a stopped replay's steps do. + m_jobs.block_owner(plugin_key); + for (const std::string& job : m_jobs.running_owned_by(plugin_key)) + m_jobs.request_stop(job); + // Not waited for: an unloading plugin's recording is closed by the recorder's own threads. + end_run_scope(plugin_scope_key(plugin_key), false); +} + +void AutomationRuntime::plugin_loaded(const std::string& plugin_key) +{ + { + std::lock_guard lock(m_rules_mutex); + m_unloaded_plugins.erase(plugin_key); + } + m_jobs.unblock_owner(plugin_key); +} + +void AutomationRuntime::open_client_scope() +{ + std::lock_guard lock(m_rules_mutex); + m_client_scope_open = true; +} + +bool AutomationRuntime::client_scope_open() const +{ + std::lock_guard lock(m_rules_mutex); + return m_client_scope_open; +} + +void AutomationRuntime::close_client_scope() +{ + // A client's recording ends with its scope; a run's carries on until the run ends. + if (m_recorder) + m_recorder->end_owned_by({}, "endpoint_closed", false); + // So does a press a client's mouse_gesture left held, on a widget or a page. + if (m_web_presses) { + const std::string client; + if (m_inspector) + m_inspector->release_held(&client); + release_web_presses(m_web_presses, &client); + } + { + // A client's rules end with its scope; a person using the app afterwards must not have + // dialogs answered for them. + std::lock_guard lock(m_rules_mutex); + m_client_scope_open = false; + if (m_session_rule_layer != 0) + m_modals->pop_rules(m_session_rule_layer); + m_session_rule_layer = 0; + } +} + +void AutomationRuntime::suspend() +{ + // The main window is about to be rebuilt; runs stop while its plater is still the current one. + stop_followed(); + if (m_recorder) + m_recorder->suspend(); + m_suspended = true; + ++m_generation; +} + +void AutomationRuntime::resume() +{ + ++m_generation; + m_suspended = false; + if (m_recorder) + m_recorder->resume(); +} + +void AutomationRuntime::mark_ready() +{ + if (m_ready || m_ready_timer) + return; + // Starting on Home, the Prepare canvas loads OpenGL at idle after post_init(), and until then a + // 3MF save draws its thumbnail with no GL functions loaded. The main window builds its tab pages + // at idle then too, and a page's web view registers its "wx" handler with a script it waits for in + // a nested loop; on GTK, calls that came in meanwhile have left that wait unfinished for good, + // and with it every later web view's window.wx, a dialog page's own buttons included. So ready + // waits for the canvas and the pages. When the hidden canvas can't get a GL context, the first + // draw of Prepare loads it instead, and the pages build only while no input comes, so ready stops + // waiting after 10 s. + const auto settled = [] { return canvas_gl_ready() && !pages_pending(); }; + if (settled()) { + set_ready(); + return; + } + const auto since = std::chrono::steady_clock::now(); + m_ready_timer = std::make_unique(); + m_ready_timer->Bind(wxEVT_TIMER, [this, since, settled](wxTimerEvent&) { + if (m_stopping || (!settled() && std::chrono::steady_clock::now() - since < std::chrono::seconds(10))) + return; + m_ready_timer->Stop(); + if (!canvas_gl_ready()) + BOOST_LOG_TRIVIAL(warning) << "Automation runtime ready before the 3D view loaded OpenGL"; + if (pages_pending()) + BOOST_LOG_TRIVIAL(warning) << "Automation runtime ready before the main window built its tab pages"; + set_ready(); + }); + m_ready_timer->Start(100); +} + +void AutomationRuntime::set_ready() +{ + m_ready = true; + for (std::function& fn : std::exchange(m_on_ready, {})) + fn(); +} + +void AutomationRuntime::on_ready(std::function fn) +{ + if (m_ready) + fn(); + else + m_on_ready.push_back(std::move(fn)); +} + +void AutomationRuntime::post_ui(std::function fn) +{ + if (m_dispatcher) + m_dispatcher->post(std::move(fn)); +} + +bool AutomationRuntime::follow(FollowedCall call) +{ + if (m_core == nullptr || m_stopping) + return false; + std::function stop = call.stop; + // An exception that leaves a thread's function ends the process, so none leaves this one: a `ready` that throws + // gives the call up, what the call throws is its error result, and what `ended` throws is logged. + return m_followed.start( + [this, call = std::move(call)]() mutable { + const auto failed = [&call](const char* what) { + BOOST_LOG_TRIVIAL(error) << "Automation runtime: following " << call.command.key << " failed: " << what; + }; + try { + if (call.ready && !call.ready(call.args)) + return; + } catch (const std::exception& e) { + failed(e.what()); + return; + } catch (...) { + failed("unknown exception"); + return; + } + std::optional r; + try { + r = call_to_end(call.command, call.args, call.person); + } catch (const std::exception& e) { + r = ToolResult::error(std::string("Internal error: ") + e.what()); + } catch (...) { + r = ToolResult::error("Internal error"); + } + if (!call.ended) + return; + try { + call.ended(r); + } catch (const std::exception& e) { + failed(e.what()); + } catch (...) { + failed("unknown exception"); + } + }, + std::move(stop)); +} + +void AutomationRuntime::stop_followed() { m_followed.stop_all(); } + +std::optional AutomationRuntime::call_to_end(const NativeCommand& def, const json& args, bool person) +{ + ToolResult r = person ? m_core->call_person(def, args) : m_core->call(def, args); + const std::string status = r.is_error ? std::string() : r.data.value("status", ""); + if ((status != "running" && status != "blocked_by_dialog") || !r.data.contains("job")) + return r; + const std::string job = r.data["job"].get(); + std::optional done; + while (!done && !m_stopping) { + try { + done = m_jobs.wait(job, std::chrono::seconds(1)); + } catch (const ToolFailure& f) { + done = ToolResult::error(f.what()); // the job's result was lost + } + } + return done; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/AutomationRuntime.hpp b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp new file mode 100644 index 0000000000..cf45614ce6 --- /dev/null +++ b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp @@ -0,0 +1,227 @@ +#pragma once + +#include "AutomationRuntimePtr.hpp" +#include "FollowedThreads.hpp" +#include "JobRegistry.hpp" +#include "McpCore.hpp" +#include "McpJournal.hpp" +#include "UiInvoker.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class wxTimer; + +namespace Slic3r { namespace GUI { namespace Mcp { + +class McpRecorder; +class ModalTracker; +class UiInspector; +class WebPresses; +struct AutoAnswerRule; + +// Whose an auto_answer_dialogs call's rules are ("run", "plugin" or "session"), the tracker layer they went into (0 for +// none), and whether they start paused: a Run Script session's rules registered between its works answer nothing, an open +// dialog included, until its next work. +struct AutoAnswerSet +{ + std::string scope; + int layer = 0; + bool paused = false; +}; + +// A call the runtime follows to its end on a thread of its own (AutomationRuntime::follow()): a run a person started +// from a window or the command line, or the encode of a person's recording once it ends. +struct FollowedCall +{ + NativeCommand command; + nlohmann::json args = nlohmann::json::object(); + // The job is a person's run (JobRegistry::person_in). + bool person = false; + // Runs first on the following thread and may complete `args`; false gives the call up, and `ended` is not + // called. One that throws gives the call up as false does. Optional. + std::function ready; + // The call's result once its job has ended, past a running or blocked_by_dialog reply. While the runtime stops it + // is an error ("OrcaSlicer is shutting down") when the call was refused or cut short within its reply budget, and + // nullopt when the runtime stopped while the call's job was being waited for. When the call itself threw, it is + // an "Internal error: ..." error. On the following thread. + std::function&)> ended; + // Asks the call to end early. stop_followed() calls it while the call has not ended. Optional. + std::function stop; +}; + +// What runs commands for every front end: the MCP endpoint, Action Replay, the Run Script panel, plugins, a person's +// commands from the Speed Dial and the command line's run. Owns the dispatch core, the UI invoker, the jobs, the +// session journal, the modal-dialog tracker, the recorder and the scopes, runs the process's command catalog +// (NativeCommands::instance()), and follows the calls its front ends start to their end (follow()). It knows none of +// its front ends: they hold it and call in. Created by GUI_App when a front end first asks for it; started, +// suspended and stopped on the UI thread. +// +// Until something asks for it, none of this exists. Held in an AutomationRuntimePtr, whose deleter is the only way +// to destroy one. +class AutomationRuntime +{ +public: + AutomationRuntime(); + AutomationRuntime(const AutomationRuntime&) = delete; + AutomationRuntime& operator=(const AutomationRuntime&) = delete; + + // Starts the jobs, the core, the UI invoker, the modal tracker and the recorder, once; a later call returns at + // once. The GUI instruments are left to the front ends that drive the GUI (enable_gui_instruments()). + bool start(std::string& err); // false only once it has stopped for exit + // Turns on what a front end that drives the GUI needs: the UI inspector, menu capture, ImGui item recording + // and window tracking, and asks the shown 3D view for a frame so its ImGui items are recorded. Idempotent. + // UI thread. + void enable_gui_instruments(); + // Stops everything; idempotent, and final: start() refuses afterwards. Wakes every waiting call, refuses new + // ones, closes the client scope and joins the threads of the followed calls, but frees nothing: a call may + // still be on the UI thread's stack inside a nested event loop, and job threads, and the request threads of a + // front end, may still be returning. + void stop(); + // After stop(): waits until no lease is held and no call or job thread is inside the core. False when one + // is still running after `timeout`; the runtime must then be kept alive (leaked) rather than + // destroyed under it. + bool drain(std::chrono::milliseconds timeout); + // The endpoint opened or closed: a client's rules, recording and held presses end with close. + void open_client_scope(); + void close_client_scope(); + // Whether a client's call may leave rules, a recording or a held press behind: from open_client_scope() + // until close_client_scope(). A client's call still running after the close must not leave behind what the + // close ended. Any thread. + bool client_scope_open() const; + + // Main frame recreation (language change): refs become stale and UI calls fail with "retry" + // until resume(). + void suspend(); + void resume(); + bool suspended() const { return m_suspended; } + + // The main frame finished starting up (end of GUI_App::post_init). Ready follows once the Prepare + // canvas has loaded OpenGL, at once when it already has. + void mark_ready(); + bool ready() const { return m_ready && !m_suspended; } + // Runs `fn` on the UI thread once the runtime is ready, at once when it already is. UI thread. + void on_ready(std::function fn); + + // Monotonic counter bumped by suspend(); refs carry it to detect a rebuilt UI. + uint64_t ui_generation() const { return m_generation; } + + JobRegistry& jobs() { return m_jobs; } + Journal& journal() { return m_journal; } + UiInvoker& ui() { return *m_invoker; } + McpCore& core() { return *m_core; } + ModalTracker& modals() { return *m_modals; } + // Refs from list_widgets live here. Turns the GUI instruments on if no front end has. UI thread only. + UiInspector& inspector(); + // The presses mouse_gesture downs left on pages, the web counterpart of the inspector's held press. + // Any thread. + WebPresses& web_presses() { return *m_web_presses; } + // start_recording and its kin; also told about every call, for the captions. + McpRecorder& recorder() { return *m_recorder; } + + // Auto-answer rules from auto_answer_dialogs. Rules registered from inside a run (the nearest + // running replay or script in `ancestry`, the caller's job chain, nearest first) last until that run + // ends; a client's rules replace the ones it registered before, and end when the client scope + // closes: with the scope closed (the server turned off meanwhile), a client's rules are refused. + // A run scope that is paused (set_run_scope_paused()) gets them paused. Any thread. + AutoAnswerSet set_auto_answer(std::vector rules, const std::vector& ancestry); + // run_replay and run_script bracket their runs with these. A mouse press the run left held is released + // when it ends, and so is a recording it started; `wait_recording` waits for that recording's file, + // unless the run already did. + void begin_run_scope(const std::string& job); + void end_run_scope(const std::string& job, bool wait_recording = true); + // Pauses or resumes every rule layer of `job`'s scope (ModalTracker::set_paused); a layer the scope adds while it + // is paused starts paused. Any thread. + void set_run_scope_paused(const std::string& job, bool paused); + // Releases the mouse presses `job`'s calls left held, on widgets and pages, as the end of its scope does. Any + // thread. + void release_run_presses(const std::string& job); + // Cancels the operations whose lineage holds `job`, as cancel_job does: a background job through the worker, + // a slice or an export through the plater. UI thread. + void cancel_operations_of(const std::string& job); + // The job of the nearest running replay or script in `ancestry`, else the scope of the plugin whose call it is, + // or "" for a client's own call. Any thread. + std::string run_owner(const std::vector& ancestry) const; + // Keeps the runtime from being destroyed while a caller outside the core uses it: a plugin's call holds + // a lease from the moment the UI thread hands it the runtime until the call returns, and drain() waits + // for every lease. False once the runtime is stopping. Any thread. + bool acquire_lease(); + void release_lease(); + // A plugin's calls own what they leave behind (auto-answer rules, a recording, a held press) as a + // run's do, until the plugin unloads: begin is called before each of its calls (idempotent), end when + // it unloads. Any thread. + // begin returns false for a plugin whose scope ended (it unloaded) until plugin_loaded() is called for + // it again; end also stops the plugin's running calls, and a call of its that would leave something + // behind after that is refused (run_owner, set_auto_answer throw). + bool begin_plugin_scope(const std::string& plugin_key); + void end_plugin_scope(const std::string& plugin_key); + void plugin_loaded(const std::string& plugin_key); + + // Calls a command on a thread the runtime owns, which stop() joins. False, with nothing started, when the + // runtime is not started or is stopping, or when the system cannot start a thread. Any thread. + bool follow(FollowedCall call); + // Stops every followed call that has a stop, while the main window is still the one they run in. UI thread. + void stop_followed(); + bool stopping() const { return m_stopping; } + // Queues `fn` on the UI thread; nothing runs once the app is gone. Any thread. + void post_ui(std::function fn); + +private: + friend struct AutomationRuntimeDeleter; + ~AutomationRuntime(); + + // Calls `command`, as a person's call with `person`, and follows the job it starts to its end; nullopt when + // the runtime stops first. A thread follow() starts calls it. + std::optional call_to_end(const NativeCommand& command, const nlohmann::json& args, bool person); + void set_ready(); + GuardState guards_on_ui() const; + + std::unique_ptr m_dispatcher; + JobRegistry m_jobs; + Journal m_journal; + // Before the invoker, so it outlives the invoker's callbacks, which read it. + std::unique_ptr m_modals; + // Before the core, which reports its calls to it. + std::unique_ptr m_recorder; + std::unique_ptr m_invoker; + std::unique_ptr m_core; + // Null until enable_gui_instruments(). UI thread. + std::unique_ptr m_inspector; + // Made by start(). Shared with the page calls that release its presses, whose replies may come after the runtime. + std::shared_ptr m_web_presses; + + mutable std::mutex m_rules_mutex; + std::map> m_run_rule_layers; // running replay's or script's job -> layers + std::set m_paused_scopes; // jobs whose layers are paused + int m_session_rule_layer = 0; + bool m_client_scope_open = false; + + std::atomic m_ready{false}; + // Polls for the Prepare canvas's OpenGL between mark_ready() and ready. UI thread. + std::unique_ptr m_ready_timer; + std::atomic m_suspended{false}; + std::atomic m_stopping{false}; + std::atomic m_leases{0}; + std::atomic m_generation{1}; + std::vector> m_on_ready; // UI thread + + std::set m_unloaded_plugins; // under m_rules_mutex + // Last, so its threads, which use everything above, are gone first. + FollowedThreads m_followed; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/AutomationRuntimePtr.hpp b/src/slic3r/GUI/Mcp/AutomationRuntimePtr.hpp new file mode 100644 index 0000000000..78cb2bae56 --- /dev/null +++ b/src/slic3r/GUI/Mcp/AutomationRuntimePtr.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +class AutomationRuntime; + +// The only way a runtime is destroyed: stops it, then frees it once no lease is held and no call or job thread is +// inside its core. A runtime whose calls have not returned 10 s after its stop is leaked instead, as they hold +// references into it. Kept apart from AutomationRuntime.hpp so GUI_App.hpp can hold the pointer. +struct AutomationRuntimeDeleter +{ + void operator()(AutomationRuntime* runtime) const; +}; + +using AutomationRuntimePtr = std::unique_ptr; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/FollowedThreads.cpp b/src/slic3r/GUI/Mcp/FollowedThreads.cpp new file mode 100644 index 0000000000..a943ab8071 --- /dev/null +++ b/src/slic3r/GUI/Mcp/FollowedThreads.cpp @@ -0,0 +1,88 @@ +#include "FollowedThreads.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +FollowedThreads::~FollowedThreads() { join_all(); } + +bool FollowedThreads::start(std::function work, std::function stop) +{ + std::lock_guard lock(m_mutex); + // Under the lock join_all() closes with: a start either comes before the join takes the threads, and is + // joined with them, or is refused. + if (m_closed) + return false; + // A returned work's thread has only to release what the work held and end, and neither takes this lock. + for (auto it = m_threads.begin(); it != m_threads.end();) { + if (!*it->returned) { + ++it; + continue; + } + if (it->thread.joinable()) + it->thread.join(); + it = m_threads.erase(it); + } + auto returned = std::make_shared>(false); + std::thread thread; + try { + // What the work holds goes as the thread ends, after it counts as returned. + thread = std::thread([work = std::move(work), returned] { + work(); + *returned = true; + }); + } catch (const std::system_error&) { + // The system cannot start a thread: nothing is added to the list, and neither the work nor `stop` is kept. + return false; + } + m_threads.push_back({std::move(thread), std::move(returned), std::move(stop)}); + return true; +} + +void FollowedThreads::stop_all() +{ + std::vector> stops; + { + std::lock_guard lock(m_mutex); + for (const Followed& followed : m_threads) + if (followed.stop && !*followed.returned) + stops.push_back(followed.stop); + } + // Outside the lock: a stop runs its run's own code, which may call these threads too. + for (const std::function& stop : stops) + stop(); +} + +void FollowedThreads::join_all() +{ + std::list joining; + { + std::lock_guard lock(m_mutex); + m_closed = true; + joining.splice(joining.end(), m_threads); + m_joining += joining.size(); + } + // Outside the lock: a start or size() from a work that is returning is answered, not kept waiting for the join. + for (Followed& followed : joining) + if (followed.thread.joinable()) + followed.thread.join(); + std::lock_guard lock(m_mutex); + m_joining -= joining.size(); +} + +std::size_t FollowedThreads::size() const +{ + std::lock_guard lock(m_mutex); + return m_threads.size() + m_joining; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/FollowedThreads.hpp b/src/slic3r/GUI/Mcp/FollowedThreads.hpp new file mode 100644 index 0000000000..d6a1bf783f --- /dev/null +++ b/src/slic3r/GUI/Mcp/FollowedThreads.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// The threads the automation runtime owns to follow calls to their end (AutomationRuntime::follow()), each with what +// stops its work early. A work has returned once its function has returned; what it holds is released after +// that, on its own thread. Thread-safe. +class FollowedThreads +{ +public: + FollowedThreads() = default; + FollowedThreads(const FollowedThreads&) = delete; + FollowedThreads& operator=(const FollowedThreads&) = delete; + // Joins what is left, as join_all() does. + ~FollowedThreads(); + + // Joins the threads whose work has returned, then runs `work` on a new one. `stop`, when given, is what + // stop_all() calls while the work has not returned. False, with nothing started and neither `work` nor `stop` + // kept, after join_all() or when the system cannot start a thread. `work` must not throw: an exception that + // leaves it ends the process. + bool start(std::function work, std::function stop = {}); + // Calls `stop` of every work that has not returned, outside the lock. + void stop_all(); + // Refuses later starts, then joins every thread. The owner has made the works return. + void join_all(); + // Threads not yet joined. + std::size_t size() const; + +private: + struct Followed + { + std::thread thread; + std::shared_ptr> returned; + std::function stop; + }; + + mutable std::mutex m_mutex; + std::list m_threads; + // Taken out of m_threads by join_all(), which joins them outside the lock. + std::size_t m_joining = 0; + bool m_closed = false; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index c014941f8f..fdc43b7e1a 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -1,5 +1,5 @@ #include "JobRegistry.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include #include @@ -31,9 +31,9 @@ bool JobRegistry::unloaded(const std::string& parent, const std::string& owner) return m_owner_loaded && !m_owner_loaded(plugin); } -std::string JobRegistry::create(const std::string& tool, const std::string& parent, const std::string& owner) +std::string JobRegistry::create(const std::string& tool, const std::string& parent, const std::string& owner, bool person) { - const std::string id = register_job(tool, parent, owner); + const std::string id = register_job(tool, parent, owner, person); if (unloaded(id, {})) { // Never started: nothing waits for it, and a stop the unload asked for it meanwhile goes with it. std::lock_guard lock(m_mutex); @@ -44,7 +44,7 @@ std::string JobRegistry::create(const std::string& tool, const std::string& pare return id; } -std::string JobRegistry::register_job(const std::string& tool, const std::string& parent, const std::string& owner) +std::string JobRegistry::register_job(const std::string& tool, const std::string& parent, const std::string& owner, bool person) { std::lock_guard lock(m_mutex); const std::size_t running = std::count_if(m_jobs.begin(), m_jobs.end(), [](const auto& kv) { return !kv.second.finished; }); @@ -55,6 +55,7 @@ std::string JobRegistry::register_job(const std::string& tool, const std::string job.tool = tool; job.parent = parent; job.owner = owner; + job.person = person; job.created = std::chrono::steady_clock::now(); if (!parent.empty()) { job.ancestors.push_back(parent); @@ -198,6 +199,31 @@ std::optional JobRegistry::wait(const std::string& id, std::chrono:: } } +bool JobRegistry::person_in(const std::set& lineage) const +{ + std::lock_guard lock(m_mutex); + return std::any_of(lineage.begin(), lineage.end(), [this](const std::string& id) { + const auto it = m_jobs.find(id); + return it != m_jobs.end() && !it->second.finished && it->second.person; + }); +} + +void JobRegistry::allow_discard(const std::string& id) +{ + std::lock_guard lock(m_mutex); + if (auto it = m_jobs.find(id); it != m_jobs.end() && !it->second.finished) + it->second.discard = true; +} + +bool JobRegistry::discard_allowed_in(const std::set& lineage) const +{ + std::lock_guard lock(m_mutex); + return std::any_of(lineage.begin(), lineage.end(), [this](const std::string& id) { + const auto it = m_jobs.find(id); + return it != m_jobs.end() && !it->second.finished && it->second.discard; + }); +} + void JobRegistry::request_stop(const std::string& id) { std::lock_guard lock(m_mutex); diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index 7bfab957f7..af66e2b9a7 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -1,6 +1,6 @@ #pragma once -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include @@ -35,11 +35,18 @@ public: static constexpr std::size_t kKeepFinishedMax = 1024; // Registers a running job. `owner` is the plugin whose call it is ("" for anyone else's); - // a child job takes its parent's. Throws ToolFailure when kMaxRunning jobs are already running, and - // kPluginUnloaded when its plugin is unloaded(), which is asked once the job is registered: a plugin - // found loaded then was loaded while the job was there for its unload to find, so every job of the - // plugin is either refused or one the unload finds running. - std::string create(const std::string& tool, const std::string& parent, const std::string& owner = {}); + // a child job takes its parent's. `person` marks a run a person started (Action Replay, the Run Script + // panel, the command line's run, a long command a person picked). Throws ToolFailure when kMaxRunning + // jobs are already running, and kPluginUnloaded when its plugin is unloaded(), which is asked once the + // job is registered: a plugin found loaded then was loaded while the job was there for its unload to + // find, so every job of the plugin is either refused or one the unload finds running. + std::string create(const std::string& tool, const std::string& parent, const std::string& owner = {}, bool person = false); + // True when an unfinished job in `lineage` carries the person mark: a run_script there runs as the person's. + bool person_in(const std::set& lineage) const; + // Lets the unfinished job `id`, and the calls under it, drop the project's unsaved changes: the user chose + // not to save before a run that replaces the project. Does nothing for an unknown or finished job. + void allow_discard(const std::string& id); + bool discard_allowed_in(const std::set& lineage) const; // Whether the call's plugin (`owner`, else the owner of the job `parent`) is blocked or, by the liveness // hook, no longer loaded. False for a call that is not a plugin's. bool unloaded(const std::string& parent, const std::string& owner) const; @@ -95,7 +102,7 @@ public: private: // create() without the liveness check. - std::string register_job(const std::string& tool, const std::string& parent, const std::string& owner); + std::string register_job(const std::string& tool, const std::string& parent, const std::string& owner, bool person); struct Job { @@ -108,6 +115,9 @@ private: bool finished = false; bool operation = false; bool idle = false; + // The marks count only while the job is unfinished. + bool person = false; + bool discard = false; ToolResult result; std::chrono::steady_clock::time_point created; }; diff --git a/src/slic3r/GUI/Mcp/LaunchRun.cpp b/src/slic3r/GUI/Mcp/LaunchRun.cpp new file mode 100644 index 0000000000..3254e8ce7a --- /dev/null +++ b/src/slic3r/GUI/Mcp/LaunchRun.cpp @@ -0,0 +1,138 @@ +#include "LaunchRun.hpp" + +#include "McpOptions.hpp" +#include "McpPaths.hpp" +#include "AutomationRuntime.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/plugin/PythonScriptRunner.hpp" + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +std::atomic g_run_exit_code{-1}; + +void set_launch_exit_code(int code) { g_run_exit_code = code; } + +// The run's end: its exit code, then the main window's close, which ends the event loop. +void end_launch_run(AutomationRuntime& runtime, int code) +{ + set_launch_exit_code(code); + BOOST_LOG_TRIVIAL(info) << "--run finished with exit code " << code; + if (runtime.stopping() || wxTheApp == nullptr) + return; + // Close without the unsaved-project prompt: the run owns this session. + runtime.post_ui([] { + if (wxTheApp != nullptr && wxGetApp().mainframe != nullptr) + wxGetApp().mainframe->Close(true); + }); +} + +// The exit code of the run's result: 0 passed, 1 failed, 2 invalid (the replay's result says so). An error built +// without details carries no object to read, and is a failed run. +int launch_run_code(const ToolResult& r, bool python) +{ + if (r.is_error) + BOOST_LOG_TRIVIAL(error) << "--run: " << r.message; + const bool fields = r.data.is_object(); + if (python) { + const bool finished = !r.is_error && fields && r.data.value("status", "") == "finished"; + if (!r.is_error && !finished) + BOOST_LOG_TRIVIAL(error) << "--run: " << (fields ? r.data.value("message", std::string()) : std::string()) << "\n" + << (fields ? r.data.value("traceback", std::string()) : std::string()); + return finished ? 0 : 1; + } + if (r.is_error) + return fields && r.data.value("invalid", false) ? 2 : 1; + return fields && r.data.value("passed", false) ? 0 : 1; +} + +} // namespace + +int launch_exit_code() { return g_run_exit_code.load(); } + +void start_launch_run(AutomationRuntime& runtime, const McpLaunchOptions& options) +{ + const std::string file = options.run_file; + const std::string extension = path_to_utf8(path_from_utf8(file).extension()); + const bool python = boost::algorithm::iequals(extension, ".py"); + const bool replay = boost::algorithm::iequals(extension, ".json"); + // A replay's steps and a script's tools drive the GUI. + runtime.enable_gui_instruments(); + if (!options.run_out.empty()) + set_run_output_dir(path_from_utf8(options.run_out)); + + FollowedCall call; + call.command = *NativeCommands::instance().find(python ? "run_script" : "run_replay"); + call.person = true; + // The file is read off the UI thread. + call.ready = [&runtime, file, out = options.run_out, python, replay](json& args) { + try { + if (!python && !replay) + throw std::runtime_error(file + " is neither a replay (.json) nor a Python script (.py)"); + if (python) { + boost::nowide::ifstream in(file.c_str(), std::ios::binary); + if (!in) + throw std::runtime_error("Cannot read " + file); + std::ostringstream raw; + raw << in.rdbuf(); + std::string text, encoding, error; + if (!decode_python_source(raw.str(), text, encoding, error)) + throw std::runtime_error("Cannot read " + file + " as Python source: " + error); + args = {{"code", text}, {"filename", file}}; + } else { + args = {{"path", file}}; + if (!out.empty()) + args["out_dir"] = out; + } + return true; + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "--run: " << e.what(); + end_launch_run(runtime, 2); + return false; + } + }; + call.ended = [&runtime, python](const std::optional& r) { + // The runtime stopped before the run ended: it did not pass. + int code = 1; + try { + if (r) + code = launch_run_code(*r, python); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "--run: " << e.what(); + code = 2; + } + end_launch_run(runtime, code); + }; + runtime.on_ready([&runtime, call = std::move(call)]() mutable { + // Refused while the runtime stops, or when the system cannot start a thread: the run never began. + if (!runtime.follow(std::move(call))) + end_launch_run(runtime, 1); + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/LaunchRun.hpp b/src/slic3r/GUI/Mcp/LaunchRun.hpp new file mode 100644 index 0000000000..e337b9984b --- /dev/null +++ b/src/slic3r/GUI/Mcp/LaunchRun.hpp @@ -0,0 +1,16 @@ +#pragma once + +// The command line's run: the replay or Python script that --run gives. +namespace Slic3r { namespace GUI { namespace Mcp { + +class AutomationRuntime; +struct McpLaunchOptions; + +// Exit code of the command line's run (0 passed, 1 failed, 2 invalid), -1 when none ran. Read by GUI_Run after +// the event loop ends; wx ignores OnExit()'s return value. +int launch_exit_code(); +// Registers the run of `options.run_file` for when the runtime is ready, and makes `options.run_out`, when given, +// the session's output folder (set_run_output_dir). UI thread. +void start_launch_run(AutomationRuntime& runtime, const McpLaunchOptions& options); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpArguments.cpp b/src/slic3r/GUI/Mcp/McpArguments.cpp index d68b097c39..167b143113 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.cpp +++ b/src/slic3r/GUI/Mcp/McpArguments.cpp @@ -1,9 +1,9 @@ // Argument checking and name matching for the command catalog: the schema validator, the normalizer that // reads what agents send in place of a schema's form, what tells a command's person's form from its silent // one, the words and scores of the searches, and the edit distance every "did you mean" ranks with. It -// includes no wx header, so the wx-free units, such as the protocol layer, and their tests can use it. +// includes no wx header: it is a unit of the library libslic3r_automation, which is built without wx. -#include "McpTypes.hpp" +#include "McpArguments.hpp" #include "slic3r/GUI/CommandCatalog.hpp" diff --git a/src/slic3r/GUI/Mcp/McpArguments.hpp b/src/slic3r/GUI/Mcp/McpArguments.hpp new file mode 100644 index 0000000000..3c586133f7 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpArguments.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include "slic3r/GUI/CommandCatalog.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// For a call of call_tool ({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); + +// ---- arguments and name matching (McpArguments.cpp) ------------------------------------------ + +// Validates `args` against the subset of JSON Schema the tool catalog uses (object properties with +// type, enum, minimum/maximum, required, additionalProperties:false, array items, and the +// "if": {"minProperties": 1}, "then": {"required": [...]} of with_silent()). Returns an empty string when +// valid, else a message naming the offending property. +std::string validate_arguments(const nlohmann::json& schema, const nlohmann::json& args); + +// Whether `args` asks for a command's person's form: an object with no members, or null. A command that has +// a person's form and a silent one does the person's then (it asks, as a person's pick does), and the +// silent one when it is given any argument. +bool person_form(const nlohmann::json& args); +// `args` without `silent`, which only chooses the silent form. +nlohmann::json silent_args(nlohmann::json args); +// The schema of a two-form command from its silent form's `schema`: it gains the property `silent`, which +// takes only true and asks for the silent form with its defaults, and a top-level `required` list moves to +// "if": {"minProperties": 1}, "then": {"required": [...]}, since the call with no arguments, the person's +// form, needs none of them. +nlohmann::json with_silent(nlohmann::json schema); + +// Readies a call's arguments for `command`, as every caller of a command does: normalizes `args` in place +// (normalize_arguments()) and returns why validate_arguments() refuses them; empty when they are valid. +std::string argument_error(const NativeCommand& command, nlohmann::json& args); + +// Rewrites, before validation, what agents often send in place of what the schema asks for: an +// argument under a name the tool does not take but that stands for one it does, which the call leaves +// out and the value fits (ref for target, key for keys, text for value, action for id or button, object for objects, +// plate for plates, filter for query, settings for values, path for save_path, index for feature, params or +// values for fields), a value written in +// another JSON form (a number, boolean, array or object as a string, a single item for an array), +// a value outside its argument's enum that only one omitted argument's enum takes (set_view's canvas +// "front" as camera), and the x and y, or width and height, that list_windows reports, both given, as +// the position or size array of a tool that takes that array, of integers, and neither part. Anything +// that still does not fit is left for validate_arguments to report. +void normalize_arguments(const nlohmann::json& schema, nlohmann::json& args); + +// The Levenshtein distance between `a` and `b`: the fewest insertions, deletions and substitutions of one +// character that turn one into the other. A "did you mean" ranks the names a mistyped one may stand for by it, +// each lookup with its own threshold. +std::size_t edit_distance(const std::string& a, const std::string& b); + +// The words of a search query: lower case, split at anything but a letter or a digit. "to" or "of" +// starts a word of most help texts, so words of fewer than three letters are left out when the query +// has longer ones. +std::vector query_words(const std::string& query); + +// How well an entry matches the words of query_words(): {words found in `name` or `text`, of them those +// found in `name`}, {0, 0} when none is. A word is found where a word of the text starts with it, so +// "retract" finds "retraction"; the text's words are split at underscores, dots and the like and also +// at a capital in a CamelCase name, so "mesh" finds TriangleMesh. +std::pair match_score(const std::vector& words, const std::string& name, const std::string& text); + +// The first sentence of `text` on one line, for a listing: up to the first full stop followed by a space +// or the end, "e.g." and "i.e." aside; the whole text when it has none. +std::string first_sentence(const std::string& text); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 657a6534af..af0fed96f6 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -1,13 +1,12 @@ #include "McpCore.hpp" #include "JobRegistry.hpp" +#include "McpArguments.hpp" #include "McpJournal.hpp" -#include "McpProtocol.hpp" -#include "McpService.hpp" -#include "McpTypes.hpp" #include "UiInvoker.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include #include @@ -108,12 +107,12 @@ public: }); } const std::string& job_id() const override { return m_job; } - // The service that owns the core; a core built on its own has none, and the base refuses. - McpService& service() override + // The runtime that owns the core; a core built on its own has none, and the base refuses. + AutomationRuntime& runtime() override { - if (McpService* service = m_core.service()) - return *service; - return ToolContext::service(); + if (AutomationRuntime* runtime = m_core.runtime()) + return *runtime; + return ToolContext::runtime(); } // A plugin's call reads as cancelled the moment the plugin unloads, before the unload's stop request comes; // a handler that waits or polls then ends, one that does neither runs to its end. @@ -229,12 +228,14 @@ bool McpCore::shutting_down() return m_stopping || m_ui.is_shutdown(); } -ToolResult McpCore::call(const NativeCommand& command, const nlohmann::json& args) { return run(command, args, {}, {}); } +ToolResult McpCore::call(const NativeCommand& command, const nlohmann::json& args) { return run(command, args, {}, {}, false); } + +ToolResult McpCore::call_person(const NativeCommand& command, const nlohmann::json& args) { return run(command, args, {}, {}, true); } ToolResult McpCore::call_child(const NativeCommand& command, const nlohmann::json& args, const std::string& parent_job, const std::string& plugin) { - return run(command, args, parent_job, plugin); + return run(command, args, parent_job, plugin, false); } ToolResult McpCore::call_child_named(const std::string& tool, const nlohmann::json& raw_args, const std::string& parent_job, @@ -253,7 +254,7 @@ ToolResult McpCore::call_child_named(const std::string& tool, const nlohmann::js ToolResult McpCore::call_plugin(const NativeCommand& command, const nlohmann::json& args, const std::string& plugin_key) { - return run(command, args, {}, plugin_key); + return run(command, args, {}, plugin_key, false); } std::string McpCore::submit(const NativeCommand& command, const nlohmann::json& args, std::function done) @@ -263,8 +264,7 @@ std::string McpCore::submit(const NativeCommand& command, const nlohmann::json& struct Leave { McpCore* core; ~Leave() { core->leave(); } } leave_on_return{this}; ToolResult refused; // A person's pick: its job, and a script it runs, are the person's, as a run the person starts is. - const std::string job = start_job(m_service != nullptr ? m_service->as_person(command) : command, args, {}, {}, 0, m_next_call++, - done, refused); + const std::string job = start_job(command, args, {}, {}, true, 0, m_next_call++, done, refused); // A refusal at shutdown is no answer to give: the caller is told nothing, as a call it never made. if (job.empty() && !shutting_down()) deliver(done, refused); @@ -272,7 +272,8 @@ std::string McpCore::submit(const NativeCommand& command, const nlohmann::json& } std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin, - uint64_t seq, uint64_t call, const std::function& done, ToolResult& refused) + bool person, uint64_t seq, uint64_t call, const std::function& done, + ToolResult& refused) { // Operation admission: an MCP operation holds the project until it finishes; only recovery // input and the commands that may run during an operation (cancel_job) get through. @@ -284,7 +285,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a std::string job; try { - job = m_jobs.create(def.key, parent, plugin); + job = m_jobs.create(def.key, parent, plugin, person); } catch (const ToolFailure& f) { refused = ToolResult::error(f.what()); return {}; @@ -335,7 +336,8 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a return job; } -ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin) +ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin, + bool person) { if (m_ui.is_shutdown() || !enter()) return ToolResult::error("OrcaSlicer is shutting down"); @@ -373,7 +375,7 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co } ToolResult refused; - const std::string job = start_job(def, args, parent, plugin, seq, call, {}, refused); + const std::string job = start_job(def, args, parent, plugin, person, seq, call, {}, refused); if (job.empty()) return finish(std::move(refused)); diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp index fb0bfbd0a3..57c8aee8f2 100644 --- a/src/slic3r/GUI/Mcp/McpCore.hpp +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -1,10 +1,10 @@ #pragma once #include "JobRegistry.hpp" -#include "McpTypes.hpp" #include "UiInvoker.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include @@ -22,7 +22,7 @@ namespace Slic3r { namespace GUI { namespace Mcp { class Journal; -class McpService; +class AutomationRuntime; struct CoreTiming { @@ -79,6 +79,8 @@ public: // A call from a client. Mutate commands become top-level jobs. ToolResult call(const NativeCommand& command, const nlohmann::json& args) override; + // As call(), with the job marked a person's. + ToolResult call_person(const NativeCommand& command, const nlohmann::json& args); // A call made by a running job (a replay step or a script's call). The new job's parent is `parent_job`, so a // `wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out. ToolResult call_child(const NativeCommand& command, const nlohmann::json& args, const std::string& parent_job, @@ -92,12 +94,11 @@ public: // is the agent's session. ToolResult call_plugin(const NativeCommand& command, const nlohmann::json& args, const std::string& plugin_key); // Starts `command` as a client's call starts a job, under the same guards and operation admission, whatever - // its inline_call, and returns the job's id without waiting; not journaled. It is a person's pick, so with a - // service set the job runs as a person's run (McpService::as_person()). `done` gets the job's result on - // the job's thread as it ends. A call refused before a job starts (another job's operation holds the - // project, too many jobs) returns an empty id and gets its refusal through `done` at once, on the calling - // thread. Once the core is shutting down it returns an empty id and never calls `done`. What `done` throws - // is dropped. Any thread. + // its inline_call, and returns the job's id without waiting; not journaled. It is a person's pick, so its job + // is marked a person's (JobRegistry::person_in()). `done` gets the job's result on the job's thread as it + // ends. A call refused before a job starts (another job's operation holds the project, too many jobs) returns + // an empty id and gets its refusal through `done` at once, on the calling thread. Once the core is shutting + // down it returns an empty id and never calls `done`. What `done` throws is dropped. Any thread. std::string submit(const NativeCommand& command, const nlohmann::json& args, std::function done); // Refuses new calls. The owner wakes UiInvoker and JobRegistry, which makes running calls return. @@ -109,10 +110,10 @@ public: const CommandCatalog& catalog() const { return m_catalog; } UiInvoker& ui() { return m_ui; } JobRegistry& jobs() { return m_jobs; } - // The service that owns the core, which ToolContext::service() of its calls returns; nullptr for a core + // The runtime that owns the core, which ToolContext::runtime() of its calls returns; nullptr for a core // built on its own, as a unit test builds one. Set once, before any call. - void set_service(McpService* service) { m_service = service; } - McpService* service() const { return m_service; } + void set_runtime(AutomationRuntime* runtime) { m_runtime = runtime; } + AutomationRuntime* runtime() const { return m_runtime; } // Operation admission for a change made by `job` ("" for a call that holds nothing), on the UI // thread: throws ToolFailure while another job's operation holds the project, or while the UI job @@ -132,12 +133,15 @@ public: private: std::uint64_t dialog_of(const std::string& job) const; - ToolResult run(const NativeCommand& command, const nlohmann::json& args, const std::string& parent, const std::string& plugin); + // `person` marks the call's job a person's (JobRegistry::create()); an inline call has no job to mark. + ToolResult run(const NativeCommand& command, const nlohmann::json& args, const std::string& parent, const std::string& plugin, + bool person); // Starts `command` as a job on a thread of its own, under operation admission: returns the job's id, or "" // with `refused` set when no job started. The job's journal entry is `seq` (0 for none); `done`, when // given, gets the job's result on its thread as it ends, before a wait on the job sees it. std::string start_job(const NativeCommand& command, const nlohmann::json& args, const std::string& parent, const std::string& plugin, - uint64_t seq, uint64_t call, const std::function& done, ToolResult& refused); + bool person, uint64_t seq, uint64_t call, const std::function& done, + ToolResult& refused); // Whether the core refuses new calls. bool shutting_down(); // On `job`'s thread once its handler returned: when it holds the UI job worker, waits until the @@ -152,7 +156,7 @@ private: CoreTiming m_timing; WorkerHooks m_worker; CallObserver* m_observer; - McpService* m_service = nullptr; + AutomationRuntime* m_runtime = nullptr; std::atomic m_next_call{1}; // The job whose call started the worker's current job, and whether a cancel was asked for it. diff --git a/src/slic3r/GUI/Mcp/McpEndpoint.cpp b/src/slic3r/GUI/Mcp/McpEndpoint.cpp new file mode 100644 index 0000000000..f334431dca --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpEndpoint.cpp @@ -0,0 +1,244 @@ +#include "McpEndpoint.hpp" + +#include "AutomationRuntime.hpp" +#include "McpHttpServer.hpp" +#include "McpOptions.hpp" +#include "McpPaths.hpp" +#include "McpProtocol.hpp" +#include "McpToken.hpp" + +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/NativeCommands.hpp" + +#include "libslic3r/Utils.hpp" +#include "libslic3r_version.h" + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#define getpid _getpid +#else +#include +#endif + +namespace Slic3r { namespace GUI { namespace Mcp { + +// HTTP request threads can outlive the server they came from; they reach the protocol through this gate, which +// drain() closes before the endpoint goes away. +struct RequestGate +{ + std::mutex mutex; + std::condition_variable cv; + McpProtocol* protocol = nullptr; + int active = 0; +}; + +using nlohmann::json; + +namespace { + +std::string shutting_down_reply() +{ + return json{{"jsonrpc", "2.0"}, {"id", nullptr}, {"error", {{"code", -32603}, {"message", "OrcaSlicer is shutting down"}}}}.dump(); +} + +} // namespace + +int endpoint_port(int option_port, const std::string& setting) +{ + int port = option_port; + if (port <= 0) { + try { + port = std::stoi(setting); + } catch (const std::exception&) { + port = 0; + } + } + return port > 0 && port <= 65535 ? port : kDefaultPort; +} + +McpEndpoint::McpEndpoint(AutomationRuntime& runtime, std::function retry_failed) + : m_runtime(runtime), m_retry_failed(std::move(retry_failed)) +{} + +McpEndpoint::~McpEndpoint() { close(); } + +bool McpEndpoint::serving() const { return m_http != nullptr && m_http->running(); } + +uint16_t McpEndpoint::port() const { return m_http ? m_http->port() : 0; } + +bool McpEndpoint::open(int port, std::string& err) +{ + m_wanted = true; + m_wanted_port = port; + const bool ok = listen(port, err); + if (!ok && m_port_held_by_other) { + // Another window that shares the configuration folder serves agents. Not an error: try the port every few + // seconds, so agents keep a server once that window closes. + if (!m_retry_timer) { + m_retry_timer = std::make_unique(); + m_retry_timer->Bind(wxEVT_TIMER, [this](wxTimerEvent&) { retry(); }); + } + if (!m_retry_timer->IsRunning()) + m_retry_timer->Start(3000); + } else if (m_retry_timer) + m_retry_timer->Stop(); + return ok; +} + +void McpEndpoint::retry() +{ + if (!m_wanted || serving() || m_runtime.stopping() || wxGetApp().is_closing()) { + m_retry_timer->Stop(); + return; + } + std::string err; + // A failure other than the port being held has stopped the retries; the owner shows it. + if (!open(m_wanted_port, err) && !m_port_held_by_other && m_retry_failed) + m_retry_failed(err); +} + +bool McpEndpoint::listen(int port, std::string& err) +{ + if (serving()) + return true; + + std::string token; + if (const char* env = boost::nowide::getenv("ORCA_MCP_TOKEN"); env != nullptr && *env != '\0') { + token = env; + m_token_source = "ORCA_MCP_TOKEN"; + } else { + token = load_or_create_token(path_from_utf8(data_dir()), err); + m_token_source = "file"; + } + if (token.empty()) { + err = "MCP server: no token (" + err + ")"; + // Not the port: the retries of a takeover stop on this, and the owner shows it. + m_port_held_by_other = false; + return false; + } + m_token = token; + + // Request threads of an endpoint closed earlier may still be using the protocol object. + if (!m_protocol) { + m_protocol = std::make_unique(NativeCommands::instance(), m_runtime.core(), server_info()); + m_gate = std::make_shared(); + m_gate->protocol = m_protocol.get(); + } + m_http = std::make_unique(token, [gate = m_gate](const PostRequest& r) -> PostReply { + McpProtocol* protocol = nullptr; + { + std::lock_guard lock(gate->mutex); + protocol = gate->protocol; + if (protocol == nullptr) + return {503, shutting_down_reply()}; + ++gate->active; + } + struct Leave + { + RequestGate& gate; + ~Leave() + { + { + std::lock_guard lock(gate.mutex); + --gate.active; + } + gate.cv.notify_all(); + } + } leave{*gate}; + return protocol->handle_post(r); + }); + // The client scope opens before the port does: a request that arrives at once must find it open. + m_runtime.open_client_scope(); + if (!m_http->start(uint16_t(port), err)) { + err = "MCP server: cannot listen on 127.0.0.1:" + std::to_string(port) + " (" + err + ")"; + m_http.reset(); + // No client was served, so nothing of a client's is there to end; this takes the scope back. + m_runtime.close_client_scope(); + // Expected with several windows on one configuration folder, and retried until that window + // closes, so logged once rather than as an error. + const bool held_before = m_port_held_by_other; + m_port_held_by_other = discovery_held_by_other(path_from_utf8(data_dir()), port); + if (!m_port_held_by_other) + BOOST_LOG_TRIVIAL(error) << err; + else if (!held_before) + BOOST_LOG_TRIVIAL(info) << "MCP server: another OrcaSlicer window serves on port " << port; + return false; + } + m_port_held_by_other = false; + // Agents drive the GUI through the endpoint. + m_runtime.enable_gui_instruments(); + + m_discovery_error.clear(); + if (!write_discovery(path_from_utf8(data_dir()), + {{"url", "http://127.0.0.1:" + std::to_string(m_http->port()) + "/mcp"}, + {"port", m_http->port()}, + {"pid", int(getpid())}, + {"version", SLIC3R_VERSION}, + {"token", token}}, + m_discovery_error)) + // Serving anyway: clients configured with the URL and token still connect; the stdio + // bridge and the harness, which need the file, see the reason in get_app_state. + BOOST_LOG_TRIVIAL(warning) << "MCP server: " << m_discovery_error; + BOOST_LOG_TRIVIAL(info) << "MCP server listening on http://127.0.0.1:" << m_http->port() << "/mcp"; + return true; +} + +void McpEndpoint::close() +{ + m_wanted = false; + m_retry_timer.reset(); + m_port_held_by_other = false; + // A client's recording, held presses and rules end with its endpoint; a run's carry on until the run ends. + m_runtime.close_client_scope(); + if (!m_http) + return; + // Requests in flight may be waiting on the UI thread, which is running this; drain() waits for + // them before the endpoint goes away. + m_http->stop(false); + m_http.reset(); + remove_discovery(path_from_utf8(data_dir())); + BOOST_LOG_TRIVIAL(info) << "MCP server endpoint closed"; +} + +bool McpEndpoint::drain(std::chrono::milliseconds timeout) +{ + if (!m_gate) + return true; + std::unique_lock lock(m_gate->mutex); + // A request that comes after this gets 503 rather than the protocol. + m_gate->protocol = nullptr; + return m_gate->cv.wait_for(lock, timeout, [this] { return m_gate->active == 0; }); +} + +json McpEndpoint::describe() const +{ + json out{{"serving", serving()}}; + if (serving()) { + out["port"] = port(); + out["url"] = "http://127.0.0.1:" + std::to_string(port()) + "/mcp"; + out["token_source"] = m_token_source; + out["token_file"] = path_to_utf8(mcp_dir(path_from_utf8(data_dir())) / "token"); + out["discovery_file"] = path_to_utf8(discovery_path(path_from_utf8(data_dir()))); + if (!m_discovery_error.empty()) + out["discovery_error"] = m_discovery_error; + } + return out; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpEndpoint.hpp b/src/slic3r/GUI/Mcp/McpEndpoint.hpp new file mode 100644 index 0000000000..64374bb692 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpEndpoint.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +class wxTimer; + +namespace Slic3r { namespace GUI { namespace Mcp { + +class AutomationRuntime; +class McpHttpServer; +class McpProtocol; +struct RequestGate; + +// The port the endpoint listens on: `option_port` when it is above 0, else `setting` when it parses; the result when +// it is 1 to 65535, else kDefaultPort. +int endpoint_port(int option_port, const std::string& setting); + +// The MCP server, one of the automation runtime's front ends: HTTP on the loopback, the protocol, the request gate, +// the token, the discovery file, and the takeover of a port that another window holds. It reaches the runtime's core +// through the protocol and holds the runtime by reference; the runtime does not know it. GUI_App owns it, opens it +// once the runtime has started, closes it before the runtime stops and destroys it first. +class McpEndpoint +{ +public: + // `retry_failed` is called on the UI thread with the error when a retry of open() fails for another reason + // than the port being held by another window; the retries then stop. It must not close the endpoint: it runs + // inside the retry timer's handler, and close() deletes that timer. + explicit McpEndpoint(AutomationRuntime& runtime, std::function retry_failed = {}); + McpEndpoint(const McpEndpoint&) = delete; + McpEndpoint& operator=(const McpEndpoint&) = delete; + // Closes it. The owner drains first. + ~McpEndpoint(); + + // Opens HTTP on 127.0.0.1:`port`, turns the runtime's GUI instruments on and opens its client scope. + // False with `err` set when it cannot listen; while another window that shares the configuration folder + // holds the port it retries every 3 s until it opens, a retry fails otherwise, or close(). UI thread. + bool open(int port, std::string& err); + // Closes the socket, stops the retries, removes the discovery file and closes the runtime's client + // scope. The request gate stays for requests in flight. UI thread. + void close(); + // After close(): waits until no request thread is inside the protocol; false when one still is after + // `timeout`, and the endpoint and the runtime must then be leaked. An endpoint that has been drained does not + // serve again: a later request gets 503. + bool drain(std::chrono::milliseconds timeout); + + bool serving() const; + uint16_t port() const; + const std::string& token() const { return m_token; } + // Where the token in use comes from: "file" or "ORCA_MCP_TOKEN". + const std::string& token_source() const { return m_token_source; } + // The last open() could not listen because another OrcaSlicer window that shares the configuration folder + // serves on the port. Cleared when the endpoint opens or close() runs. + bool port_held_by_other_window() const { return m_port_held_by_other; } + // {serving} and, while serving, {port, url, token_source, token_file, discovery_file, discovery_error?}. + nlohmann::json describe() const; + +private: + // open() without the retries: listens on `port` with the token in force. UI thread. + bool listen(int port, std::string& err); + // The retry timer's tick: open() again on what the last open() asked for, while that is still wanted. UI thread. + void retry(); + + AutomationRuntime& m_runtime; + std::function m_retry_failed; + + std::string m_token; + std::string m_token_source; + std::string m_discovery_error; + bool m_port_held_by_other = false; + // What the last open() asked for, which the retries ask for again: from open() until close(). + bool m_wanted = false; + int m_wanted_port = 0; + + // Made by the first open() and kept across close(): request threads of an endpoint closed earlier may still be + // inside the protocol, which they reach through the gate. + std::unique_ptr m_protocol; + std::shared_ptr m_gate; + std::unique_ptr m_http; + // Tries the port again every 3 s while another window holds it. Made on first need, and gone with close(), so an + // endpoint left in place at exit holds no timer past the toolkit. + std::unique_ptr m_retry_timer; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp index ca49b59b66..4dcf79f407 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.cpp +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -1,9 +1,9 @@ #include "McpJournal.hpp" #include "McpPaths.hpp" -#include "McpTypes.hpp" -#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/ActionIds.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp index f698eb2840..8af577d002 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.hpp +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -1,8 +1,7 @@ #pragma once -#include "McpTypes.hpp" - #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include diff --git a/src/slic3r/GUI/Mcp/McpOptions.hpp b/src/slic3r/GUI/Mcp/McpOptions.hpp index 149fff4113..727f602a97 100644 --- a/src/slic3r/GUI/Mcp/McpOptions.hpp +++ b/src/slic3r/GUI/Mcp/McpOptions.hpp @@ -8,19 +8,19 @@ namespace Slic3r { namespace GUI { namespace Mcp { inline constexpr int kDefaultPort = 13619; // The app config key of the unrestricted Python scripts setting: one switch, off unless true. While it is on, -// the scripts a person runs (the Run Script panel, --mcp-run) and agents send (run_script) skip the plugin -// permission checks. Only the window show_python_scripts_dialog() opens writes it; no tool does. -inline constexpr char kPythonUnrestrictedKey[] = "mcp_python_unrestricted"; +// or the command line's --unrestricted-scripts is, the scripts a person runs (the Run Script panel, --run) and +// agents send (run_script) skip the plugin permission checks. Only the window show_python_scripts_dialog() opens +// writes it; no tool and no command line option does. +inline constexpr char kPythonUnrestrictedKey[] = "python_scripts_unrestricted"; -// MCP settings from the command line. Paths are absolute: OrcaSlicer.cpp resolves them +// The endpoint's and the run's settings from the command line. Paths are absolute: OrcaSlicer.cpp resolves them // against the original working directory before the GUI changes it. struct McpLaunchOptions { - bool enable = false; // --mcp + bool enable = false; // --mcp, or --mcp-port given int port = 0; // --mcp-port; 0 = the preference - std::string token; // --mcp-token; ORCA_MCP_TOKEN takes precedence - std::string run_file; // --mcp-run: a replay (.json) or a Python script (.py) - std::string run_out; // --mcp-run-out + std::string run_file; // --run: a replay (.json) or a Python script (.py) + std::string run_out; // --outputdir, when --run is given }; }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpPaths.cpp b/src/slic3r/GUI/Mcp/McpPaths.cpp index 6212c833a7..b5fee416e8 100644 --- a/src/slic3r/GUI/Mcp/McpPaths.cpp +++ b/src/slic3r/GUI/Mcp/McpPaths.cpp @@ -1,5 +1,4 @@ #include "McpPaths.hpp" -#include "McpToken.hpp" #include "libslic3r/Utils.hpp" @@ -11,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -154,14 +154,34 @@ std::optional resolve_output_dir(const std::string& path, std::string& return p; } +namespace { + +// Set on the UI thread at startup, read by the threads that save files. +std::mutex g_run_output_mutex; +fs::path g_run_output_dir; + +} // namespace + fs::path output_dir() { - const fs::path dir = mcp_dir(path_from_utf8(data_dir())) / "out"; + fs::path dir; + { + std::lock_guard lock(g_run_output_mutex); + dir = g_run_output_dir; + } + if (dir.empty()) + dir = path_from_utf8(data_dir()) / "automation" / "out"; boost::system::error_code ec; fs::create_directories(dir, ec); return dir; } +void set_run_output_dir(const fs::path& dir) +{ + std::lock_guard lock(g_run_output_mutex); + g_run_output_dir = dir; +} + fs::path timestamped_path(const fs::path& dir, const std::string& kind, const std::string& extension, const std::vector& companions, std::time_t when) { diff --git a/src/slic3r/GUI/Mcp/McpPaths.hpp b/src/slic3r/GUI/Mcp/McpPaths.hpp index 1d4396bac7..b122b8dbe3 100644 --- a/src/slic3r/GUI/Mcp/McpPaths.hpp +++ b/src/slic3r/GUI/Mcp/McpPaths.hpp @@ -30,9 +30,11 @@ std::optional resolve_output_path(const std::string& pa // An existing directory (multi-file exports). std::optional resolve_output_dir(const std::string& path, std::string& err); -// Where screenshots, recordings and replay outputs go when no path is given: /mcp/out, created -// when missing. +// The folder files are saved to when a call names none: the run's folder when the command line gave one +// (set_run_output_dir), else /automation/out. Created on first use. boost::filesystem::path output_dir(); +// An empty path takes the run's folder back. +void set_run_output_dir(const boost::filesystem::path& dir); // A path in `dir` for a new file named "OrcaSlicer--YYYYMMDD-HHMMSS" for the local time // `when`, so files of one kind sort by when they were made and say where they came from. A name taken by a diff --git a/src/slic3r/GUI/Mcp/McpPersonContext.cpp b/src/slic3r/GUI/Mcp/McpPersonContext.cpp index 3a273a9693..5c7c53be48 100644 --- a/src/slic3r/GUI/Mcp/McpPersonContext.cpp +++ b/src/slic3r/GUI/Mcp/McpPersonContext.cpp @@ -1,10 +1,10 @@ #include "McpPersonContext.hpp" #include "McpCore.hpp" -#include "McpService.hpp" -#include "McpTypes.hpp" +#include "AutomationRuntime.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" @@ -57,15 +57,13 @@ ToolResult PersonContext::call_child(const std::string& tool, const nlohmann::js throw ToolFailure("A person's pick does not call " + tool); } -McpService& PersonContext::service() +AutomationRuntime& PersonContext::runtime() { auto* app = dynamic_cast(wxTheApp); if (app == nullptr || app->is_closing()) throw ToolFailure("OrcaSlicer is closing"); - if (McpService* s = app->mcp_service(); s == nullptr || !s->started()) - app->start_mcp_service(false); - McpService* s = app->mcp_service(); - if (s == nullptr || !s->started() || s->stopping()) + AutomationRuntime* s = app->automation(); + if (s == nullptr) throw ToolFailure("The automation runtime could not start"); return *s; } @@ -75,13 +73,13 @@ ToolResult PersonContext::submit(const std::string& key, const nlohmann::json& a const std::shared_ptr command = NativeCommands::instance().lookup(key); if (command == nullptr) throw ToolFailure("Unknown command " + key); - McpService* const owner = &service(); - const std::thread::id caller = std::this_thread::get_id(); - auto refusal = std::make_shared>(); - const std::string title = into_u8(NativeCommands::tile_title(*command)); - const std::string job = owner->core().submit(*command, args, [owner, caller, refusal, title](const ToolResult& r) { + AutomationRuntime* const owner = &runtime(); + const std::thread::id caller = std::this_thread::get_id(); + auto refusal = std::make_shared>(); + const std::string title = into_u8(NativeCommands::tile_title(*command)); + const std::string job = owner->core().submit(*command, args, [owner, caller, refusal, title](const ToolResult& r) { // A refusal comes at once, on this thread: it is the reply. A job's result comes on the job's thread, - // while the service still runs it, and is shown on the UI thread. + // while the runtime still runs it, and is shown on the UI thread. if (std::this_thread::get_id() == caller) { *refusal = r; return; diff --git a/src/slic3r/GUI/Mcp/McpPersonContext.hpp b/src/slic3r/GUI/Mcp/McpPersonContext.hpp index 8b875bc481..fd43f2e5e1 100644 --- a/src/slic3r/GUI/Mcp/McpPersonContext.hpp +++ b/src/slic3r/GUI/Mcp/McpPersonContext.hpp @@ -1,6 +1,6 @@ #pragma once -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include @@ -11,19 +11,21 @@ #include // The contexts a command runs with besides the MCP core's own: a person's pick, and a Speed Dial tile that -// run_action runs. No wx here, so that the core's tests can include it. +// run_action runs. No wx here, so that unit tests can include it (the slic3rutils tile case does). namespace Slic3r { namespace GUI { namespace Mcp { -// A person's pick from the Speed Dial or a menu, on the UI thread, which no MCP service needs to run: UI -// closures run in place, and there is no job, no journal entry and no operation to hold. +// A person's pick from the Speed Dial or a menu, on the UI thread and outside the automation runtime's dispatch +// core: UI closures run in place, and there is no job, no journal entry and no operation to hold. It needs no MCP +// endpoint, and the runtime starts only when the pick's command needs it: through this context (runtime(), +// submit()) or through GUI_App::automation(). class PersonContext final : public ToolContext { public: bool person() const override { return true; } - // The MCP service, started without its endpoint when the server is off, as the Run Script panel starts - // it. Throws ToolFailure when it cannot start: OrcaSlicer is closing, or no app runs (a unit test). - McpService& service() override; - // Starts command `key` as a job on the service's core (McpCore::submit()), under the admission a client's + // The automation runtime, started without the MCP endpoint when the server is off, as the Run Script panel + // starts it. Throws ToolFailure when it cannot start: OrcaSlicer is closing, or no app runs (a unit test). + AutomationRuntime& runtime() override; + // Starts command `key` as a job on the runtime's core (McpCore::submit()), under the admission a client's // call has, and returns at once: an Info notice "Started: ", or an Error when no job started. The // job's result is shown as a notification once it ends. ToolResult submit(const std::string& key, const nlohmann::json& args) override; @@ -47,11 +49,11 @@ class TileContext final : public ToolContext public: TileContext(ToolContext& call, std::string action_id) : m_call(call), m_id(std::move(action_id)) {} - bool person() const override { return m_call.person(); } - McpService& service() override { return m_call.service(); } - ToolResult submit(const std::string& key, const nlohmann::json& args) override { return m_call.submit(key, args); } - nlohmann::json run_ui(const std::function<nlohmann::json()>& fn) override { return m_call.run_ui(fn); } - nlohmann::json observe_ui(const std::function<nlohmann::json()>& fn) override { return m_call.observe_ui(fn); } + bool person() const override { return m_call.person(); } + AutomationRuntime& runtime() override { return m_call.runtime(); } + ToolResult submit(const std::string& key, const nlohmann::json& args) override { return m_call.submit(key, args); } + nlohmann::json run_ui(const std::function<nlohmann::json()>& fn) override { return m_call.run_ui(fn); } + nlohmann::json observe_ui(const std::function<nlohmann::json()>& fn) override { return m_call.observe_ui(fn); } const std::string& job_id() const override { return m_call.job_id(); } bool cancelled() const override { return m_call.cancelled(); } ToolResult call_child(const std::string& tool, const nlohmann::json& args) override { return m_call.call_child(tool, args); } diff --git a/src/slic3r/GUI/Mcp/McpPersonRun.cpp b/src/slic3r/GUI/Mcp/McpPersonRun.cpp index 48a32e3a64..2dfa915c43 100644 --- a/src/slic3r/GUI/Mcp/McpPersonRun.cpp +++ b/src/slic3r/GUI/Mcp/McpPersonRun.cpp @@ -1,15 +1,28 @@ #include "McpPersonRun.hpp" -#include "McpService.hpp" + +#include "JobRegistry.hpp" +#include "McpReplay.hpp" +#include "AutomationRuntime.hpp" +#include "McpTools.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/CommandTypes.hpp" + +#include <nlohmann/json.hpp> #include <cstddef> #include <memory> #include <mutex> +#include <optional> #include <string> #include <utility> namespace Slic3r { namespace GUI { namespace Mcp { -PersonRun::PersonRun(McpService& service, Events events) : m_service(service), m_events(std::move(events)) {} +using nlohmann::json; + +PersonRun::PersonRun(AutomationRuntime& runtime, Events events) : m_runtime(runtime), m_events(std::move(events)) {} std::string PersonRun::job() const { @@ -26,7 +39,7 @@ void PersonRun::set_job(const std::string& job) stop = m_stop; } if (stop) - m_service.request_stop(job); + m_runtime.jobs().request_stop(job); } void PersonRun::stop() @@ -37,18 +50,18 @@ void PersonRun::stop() m_stop = true; job = m_job; } - if (job.empty() || m_service.stopping()) + if (job.empty() || m_runtime.stopping()) return; - m_service.request_stop(job); + m_runtime.jobs().request_stop(job); // The step's own operation stops too, as cancel_job stops it. - m_service.cancel_operations_of(job); + m_runtime.cancel_operations_of(job); } void PersonRun::detach() { m_detached = true; } void PersonRun::post_step_started(std::size_t index) { - m_service.post_ui([self = shared_from_this(), index] { + m_runtime.post_ui([self = shared_from_this(), index] { if (!self->m_detached && self->m_events.step_started) self->m_events.step_started(index); }); @@ -56,7 +69,7 @@ void PersonRun::post_step_started(std::size_t index) void PersonRun::post_step_finished(nlohmann::json entry) { - m_service.post_ui([self = shared_from_this(), entry = std::move(entry)] { + m_runtime.post_ui([self = shared_from_this(), entry = std::move(entry)] { if (!self->m_detached && self->m_events.step_finished) self->m_events.step_finished(entry); }); @@ -64,10 +77,53 @@ void PersonRun::post_step_finished(nlohmann::json entry) void PersonRun::post_finished(nlohmann::json result, nlohmann::json jobs) { - m_service.post_ui([self = shared_from_this(), result = std::move(result), jobs = std::move(jobs)] { + m_runtime.post_ui([self = shared_from_this(), result = std::move(result), jobs = std::move(jobs)] { if (!self->m_detached && self->m_events.finished) self->m_events.finished(result, jobs); }); } +std::shared_ptr<PersonRun> start_replay_run(AutomationRuntime& runtime, Replay replay, ReplayContext sctx, + std::optional<std::size_t> only_step, bool discard_authorized, PersonRun::Events events) +{ + const NativeCommand* run_replay_def = NativeCommands::instance().find("run_replay"); + if (run_replay_def == nullptr || runtime.stopping()) + return nullptr; + + auto run = std::make_shared<PersonRun>(runtime, std::move(events)); + auto shared = std::make_shared<Replay>(std::move(replay)); + auto ctx_held = std::make_shared<ReplayContext>(std::move(sctx)); + // run_replay's properties, outside the session journal: a person's run is not an agent's call. + NativeCommand def = *run_replay_def; + def.journal = false; + def.run = [&runtime, run, shared, ctx_held, only_step, discard_authorized](const json&, ToolContext& ctx) { + const std::string job = ctx.job_id(); + run->set_job(job); + if (discard_authorized) + runtime.jobs().allow_discard(job); + ReplayRunOptions options; + options.only_step = only_step; + options.write_result = !only_step; + options.step_started = [run](std::size_t index) { run->post_step_started(index); }; + options.step_finished = [run](const json& entry) { run->post_step_finished(entry); }; + return ToolResult::ok(run_replay_job(runtime, ctx, *shared, *ctx_held, options)); + }; + + FollowedCall call; + call.command = std::move(def); + call.person = true; + call.ended = [&runtime, run, ctx_held](const std::optional<ToolResult>& r) { + run->mark_ended(); + if (!r || runtime.stopping()) + return; + // The handler has returned, so the jobs it saved are settled. A run refused before its handler started + // (another operation holds the project) saved none and replaces none. + run->post_finished(r->is_error ? json{{"error", r->message}} : r->data, run->job().empty() ? json() : ctx_held->jobs); + }; + call.stop = [run] { run->stop(); }; + if (!runtime.follow(std::move(call))) + return nullptr; + return run; +} + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpPersonRun.hpp b/src/slic3r/GUI/Mcp/McpPersonRun.hpp index 667a0cd62c..e0dafa075e 100644 --- a/src/slic3r/GUI/Mcp/McpPersonRun.hpp +++ b/src/slic3r/GUI/Mcp/McpPersonRun.hpp @@ -1,5 +1,7 @@ #pragma once +#include "McpReplay.hpp" + #include <nlohmann/json.hpp> #include <atomic> @@ -7,16 +9,17 @@ #include <functional> #include <memory> #include <mutex> +#include <optional> #include <string> namespace Slic3r { namespace GUI { namespace Mcp { -class McpService; +class AutomationRuntime; -// A run a person started from a window: a replay Action Replay starts through McpService::start_replay_run(), -// or a Run Script panel session through start_python_session(). An unjournaled job whose steps report as -// they start and end. The service owns the thread that follows it; the window holds it to stop it and drops -// its events when it closes. +// A run a person started from a window: a replay Action Replay starts through start_replay_run(), or a Run +// Script panel session through start_python_session(). An unjournaled job whose steps report as they start and +// end. The runtime follows it on a thread it owns (AutomationRuntime::follow()); the window holds it to stop it and +// drops its events when it closes. class PersonRun : public std::enable_shared_from_this<PersonRun> { public: @@ -31,11 +34,11 @@ public: std::function<void(const nlohmann::json& result, const nlohmann::json& jobs)> finished; }; - PersonRun(McpService& service, Events events); + PersonRun(AutomationRuntime& runtime, Events events); - // UI thread. Latches the stop, so one asked before the job exists still counts, asks the service to - // stop the job's lineage once it is known, and cancels the run's operation (a slice, an export, a - // background job) as cancel_job does. Does nothing once the service is stopping. + // UI thread. Latches the stop, so one asked before the job exists still counts, stops the job's lineage + // once it is known (JobRegistry::request_stop), and cancels the run's operation (a slice, an export, a + // background job) as cancel_job does. Does nothing once the runtime is stopping. void stop(); // UI thread: the events are dropped from now on; the run carries on to its end. void detach(); @@ -43,7 +46,7 @@ public: // A copy: the job thread sets it. "" until the job has started. std::string job() const; - // Service side. The handler calls set_job() before any step runs; it applies a latched stop. + // Runtime side. The handler calls set_job() before any step runs; it applies a latched stop. void set_job(const std::string& job); void post_step_started(std::size_t index); void post_step_finished(nlohmann::json entry); @@ -51,13 +54,22 @@ public: void mark_ended() { m_running = false; } private: - McpService& m_service; - Events m_events; // UI thread - bool m_detached = false; // UI thread + AutomationRuntime& m_runtime; + Events m_events; // UI thread + bool m_detached = false; // UI thread mutable std::mutex m_mutex; - std::string m_job; - bool m_stop = false; - std::atomic<bool> m_running{true}; + std::string m_job; + bool m_stop = false; + std::atomic<bool> m_running{true}; }; +// Runs a replay for the Action Replay window: an unjournaled mutate job, as run_replay runs one, whose steps +// report through `events`. `runtime` follows the job to its end, past a running or blocked_by_dialog reply, and +// posts `finished`. `only_step` runs one step (no result.json). `discard_authorized`: the user chose not to save +// before a run that replaces the project, so the replacing tools may drop unsaved changes while it runs. nullptr +// when the runtime is not started or is stopping, or when the system cannot start a thread. UI thread. +std::shared_ptr<PersonRun> start_replay_run(AutomationRuntime& runtime, Replay replay, ReplayContext sctx, + std::optional<std::size_t> only_step, bool discard_authorized, + PersonRun::Events events); + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp index 81e9d86b28..afdc59934d 100644 --- a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp @@ -1,10 +1,14 @@ // How a plugin's orca.host.tools calls reach the MCP tools. +#include "McpPluginCaller.hpp" + +#include "McpArguments.hpp" #include "McpProtocol.hpp" -#include "McpService.hpp" -#include "McpTypes.hpp" +#include "AutomationRuntime.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/host/PluginHostTools.hpp" @@ -26,23 +30,23 @@ using nlohmann::json; namespace { -// The UI thread's answer to a plugin's call: the service with a lease the caller releases, or why not. +// The UI thread's answer to a plugin's call: the runtime with a lease the caller releases, or why not. struct Admission { std::mutex mutex; std::condition_variable cv; bool answered = false; bool abandoned = false; // the caller stopped waiting: take no lease - McpService* service = nullptr; + AutomationRuntime* runtime = nullptr; std::string refusal; }; -// Admits a plugin's call on the UI thread, which owns the service and runs the plugin's unload: the plugin -// must still be loaded and its scope not ended, and the service is started without its endpoint when MCP is -// off, as Action Replay starts it. Returns the service with a lease taken, +// Admits a plugin's call on the UI thread, which owns the runtime and runs the plugin's unload: the plugin +// must still be loaded and its scope not ended, and the runtime is started without its endpoint when MCP is +// off, with the GUI instruments on, as Action Replay starts it. Returns the runtime with a lease taken, // or throws. A caller that stops waiting because the app closes marks the admission abandoned, under the // lock the UI thread answers it under, so no lease is taken that nobody releases. -McpService* admit_plugin_call(const std::string& plugin) +AutomationRuntime* admit_plugin_call(const std::string& plugin) { auto admission = std::make_shared<Admission>(); wxGetApp().CallAfter([admission, plugin] { @@ -59,14 +63,14 @@ McpService* admit_plugin_call(const std::string& plugin) admission->refusal = "This plugin is not loaded"; return; } - if (wxGetApp().mcp_service() == nullptr || !wxGetApp().mcp_service()->started()) - wxGetApp().start_mcp_service(false); - McpService* service = wxGetApp().mcp_service(); - if (service == nullptr || !service->started() || !service->begin_plugin_scope(plugin) || !service->acquire_lease()) { + AutomationRuntime* runtime = wxGetApp().automation(); + if (runtime == nullptr || !runtime->begin_plugin_scope(plugin) || !runtime->acquire_lease()) { admission->refusal = "OrcaSlicer can't run the call now"; return; } - admission->service = service; + // A plugin's tools drive the GUI as an agent's do. + runtime->enable_gui_instruments(); + admission->runtime = runtime; }); std::unique_lock<std::mutex> lock(admission->mutex); while (!admission->cv.wait_for(lock, std::chrono::milliseconds(200), [&] { return admission->answered; })) @@ -77,9 +81,9 @@ McpService* admit_plugin_call(const std::string& plugin) admission->abandoned = true; throw std::runtime_error("OrcaSlicer is closing"); } - if (admission->service == nullptr) + if (admission->runtime == nullptr) throw std::runtime_error(admission->refusal); - return admission->service; + return admission->runtime; } // The paths a call's arguments name, as the log records them: the values of the arguments whose name @@ -108,13 +112,13 @@ std::string named_paths(const json& args) void install_plugin_tool_caller() { set_plugin_tool_caller([](const std::string& plugin, const std::string& tool, const json& args) -> json { - McpService* service = admit_plugin_call(plugin); + AutomationRuntime* runtime = admit_plugin_call(plugin); struct Lease { - McpService* service; - ~Lease() { service->release_lease(); } - } lease{service}; - const CommandCatalog& catalog = service->catalog(); + AutomationRuntime* runtime; + ~Lease() { runtime->release_lease(); } + } lease{runtime}; + const CommandCatalog& catalog = NativeCommands::instance(); std::shared_ptr<const NativeCommand> def = catalog.lookup(tool); if (def == nullptr) throw ToolCallError(catalog.unknown_command(tool), {{"did_you_mean", catalog.similar(tool)}}); @@ -124,7 +128,7 @@ void install_plugin_tool_caller() if (std::string err = resolve_call(catalog, def, arguments); !err.empty()) throw ToolCallError(err, json()); - const ToolResult r = service->core().call_plugin(*def, arguments, plugin); + 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 // effort, since plugin code may write the log folder. const std::string outcome = r.is_error ? "error: " + r.message : r.data.is_object() ? r.data.value("status", "ok") : "ok"; diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.hpp b/src/slic3r/GUI/Mcp/McpPluginCaller.hpp new file mode 100644 index 0000000000..423258bfc1 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.hpp @@ -0,0 +1,10 @@ +#pragma once + +namespace Slic3r { namespace GUI { namespace Mcp { + +// Lets plugins call the tools through orca.host.tools: a call from a plugin's Script worker runs as +// McpCore::call_plugin(), starting the automation runtime without the MCP endpoint when the server is off, and is +// logged. Called once by GUI_App as it sets up plugins. +void install_plugin_tool_caller(); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpProtocol.cpp b/src/slic3r/GUI/Mcp/McpProtocol.cpp index c5f69fa45b..e4f7b62d07 100644 --- a/src/slic3r/GUI/Mcp/McpProtocol.cpp +++ b/src/slic3r/GUI/Mcp/McpProtocol.cpp @@ -1,7 +1,8 @@ #include "McpProtocol.hpp" -#include "McpTypes.hpp" +#include "McpArguments.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <algorithm> #include <cstddef> diff --git a/src/slic3r/GUI/Mcp/McpProtocol.hpp b/src/slic3r/GUI/Mcp/McpProtocol.hpp index 29d44baf27..46dbae54ce 100644 --- a/src/slic3r/GUI/Mcp/McpProtocol.hpp +++ b/src/slic3r/GUI/Mcp/McpProtocol.hpp @@ -1,8 +1,7 @@ #pragma once -#include "McpTypes.hpp" - #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <nlohmann/json.hpp> @@ -28,6 +27,9 @@ struct ServerInfo std::string instructions; }; +// What initialize and server/discover report: the server's name, version and instructions (McpServerInfo.cpp). +ServerInfo server_info(); + // One POSTed message and the transport headers the protocol checks. Header values are empty when // the header was absent. struct PostRequest diff --git a/src/slic3r/GUI/Mcp/McpRecorder.cpp b/src/slic3r/GUI/Mcp/McpRecorder.cpp index 90fff7914a..bafbfc6c22 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.cpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.cpp @@ -1,8 +1,7 @@ #include "McpRecorder.hpp" #include "McpPaths.hpp" -#include "McpService.hpp" -#include "McpTypes.hpp" +#include "AutomationRuntime.hpp" #include "MkvWriter.hpp" #include "ModalTracker.hpp" #include "RecordingSink.hpp" @@ -11,6 +10,8 @@ #include "VideoEncode.hpp" #include "VideoOverlay.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -47,10 +48,12 @@ #include <atomic> #include <chrono> #include <cmath> +#include <cstddef> #include <cstdint> #include <cstring> #include <deque> #include <exception> +#include <functional> #include <map> #include <memory> #include <mutex> @@ -235,8 +238,16 @@ private: McpRecorder& m_recorder; }; -McpRecorder::McpRecorder(McpService& service) - : m_service(service), m_filter(std::make_unique<InputFilter>(*this)), m_input(std::make_unique<Input>()) +McpRecorder::McpRecorder(ModalTracker& modals, + std::function<uint64_t()> ui_generation, + std::function<bool()> suspended, + std::function<void(std::function<void()>)> post_ui) + : m_modals(modals) + , m_ui_generation(std::move(ui_generation)) + , m_suspended(std::move(suspended)) + , m_post_ui(std::move(post_ui)) + , m_filter(std::make_unique<InputFilter>(*this)) + , m_input(std::make_unique<Input>()) {} McpRecorder::~McpRecorder() @@ -256,11 +267,13 @@ McpRecorder::~McpRecorder() namespace { -// The captured area: the main window with the modal dialogs on it, or the 3D view shown. Sets where it -// is on the screen, for the pointer, and `note` to what the capture approximated. UI thread. -bool capture_area(McpService& service, Recording& rec, const CaptureOptions& options, wxImage& out, std::string& note, std::string& err) +// The captured area: the main window with the modal dialogs of `modals` on it, or the 3D view shown. Sets +// where it is on the screen, for the pointer, and `note` to what the capture approximated. Fails while +// `suspended`, the main window being rebuilt. UI thread. +bool capture_area(ModalTracker& modals, bool suspended, Recording& rec, const CaptureOptions& options, wxImage& out, + std::string& note, std::string& err) { - if (service.suspended()) { + if (suspended) { err = "OrcaSlicer is rebuilding its window"; return false; } @@ -311,7 +324,7 @@ bool capture_area(McpService& service, Recording& rec, const CaptureOptions& opt }; // The modal dialogs, outermost first, which is how they stack. std::vector<wxTopLevelWindow*> drawn{frame}; - for (wxDialog* dialog : service.modals().stack()) { + for (wxDialog* dialog : modals.stack()) { if (dialog == nullptr || is_native_dialog(dialog) || hidden_from_automation(dialog) || !dialog->IsShownOnScreen()) continue; std::string dialog_err; @@ -408,7 +421,7 @@ bool McpRecorder::canvas_frame(Recording& rec, GLCanvas3D& canvas, wxImage& out, { // The frame on screen is the last one the canvas presented: kept until it presents another. Recording::CanvasFrame& kept = rec.canvases[&canvas]; - const uint64_t generation = m_service.ui_generation(); + const uint64_t generation = m_ui_generation(); const wxSize size = canvas.get_wxglcanvas()->GetClientSize(); if (kept.image.IsOk() && kept.generation == generation && kept.size == size && kept.presented == canvas.presented_frames()) { out = kept.image; @@ -464,7 +477,7 @@ json McpRecorder::start(const RecordingOptions& options, uint64_t files_owner) }; wxImage first; std::string note, err; - if (!capture_area(m_service, *rec, capture_options, first, note, err)) + if (!capture_area(m_modals, m_suspended(), *rec, capture_options, first, note, err)) throw ToolFailure("Cannot record: " + err); rec->note = note; // no other thread has it yet std::tie(rec->video_w, rec->video_h) = video_size(first.GetWidth(), first.GetHeight(), options.max_dim); @@ -569,7 +582,7 @@ void McpRecorder::capture_frame(Recording& rec, Clock::time_point now, const wxI options.canvas_frame = [this, &rec](GLCanvas3D& canvas, wxImage& out, std::string& err) { return canvas_frame(rec, canvas, out, err); }; options.sessions = rec.windows.get(); std::string note, err; - if (!capture_area(m_service, rec, options, image, note, err)) { + if (!capture_area(m_modals, m_suspended(), rec, options, image, note, err)) { ++rec.skipped; return; } @@ -662,10 +675,10 @@ void McpRecorder::end_recording(const std::shared_ptr<Recording>& rec, const std if (wxThread::IsMain()) ended(*this); else - // Found again on the UI thread: the service may be gone by then. - m_service.post_ui([ended] { - if (McpService* service = wxGetApp().mcp_service(); service != nullptr) - ended(service->recorder()); + // Found again on the UI thread: the runtime may be gone by then. + m_post_ui([ended] { + if (AutomationRuntime* runtime = wxGetApp().automation_if_started(); runtime != nullptr) + ended(runtime->recorder()); }); } @@ -813,6 +826,31 @@ bool McpRecorder::wait_closed(const fs::path& path, std::chrono::milliseconds ti return !rec || rec->options.path != path || rec->sink->wait_finalized(timeout); } +bool McpRecorder::encode_when_closed(AutomationRuntime& runtime, json args, std::function<void(const ToolResult&)> done) +{ + const NativeCommand* encode = NativeCommands::instance().find("encode_recording"); + if (encode == nullptr || runtime.stopping()) + return false; + FollowedCall call; + // A person's encode, outside the session journal like Action Replay's runs. + call.command = *encode; + call.command.journal = false; + call.args = std::move(args); + // The sink's threads close the file soon after the recording ends. + call.ready = [this, &runtime](json& encode_args) { + const fs::path source = path_from_utf8(encode_args.value("path", std::string())); + while (!runtime.stopping() && !wait_closed(source, std::chrono::seconds(1))) { + } + return !runtime.stopping(); + }; + call.ended = [&runtime, done = std::move(done)](const std::optional<ToolResult>& r) { + if (!r || runtime.stopping()) + return; + runtime.post_ui([done, result = *r] { done(result); }); + }; + return runtime.follow(std::move(call)); +} + void McpRecorder::suspend() { std::shared_ptr<Recording> rec; @@ -834,7 +872,7 @@ bool McpRecorder::running() const void McpRecorder::update_indicator() const { - if (wxGetApp().is_closing() || m_service.suspended()) + if (wxGetApp().is_closing() || m_suspended()) return; if (MainFrame* frame = wxGetApp().mainframe; frame != nullptr) frame->show_recording_indicator(running()); @@ -933,7 +971,7 @@ bool McpRecorder::shows(const Recording& rec, wxWindow* window) const if (top == wxGetApp().mainframe) return true; } - const auto& stack = m_service.modals().stack(); + const auto& stack = m_modals.stack(); return std::find(stack.begin(), stack.end(), top) != stack.end(); } diff --git a/src/slic3r/GUI/Mcp/McpRecorder.hpp b/src/slic3r/GUI/Mcp/McpRecorder.hpp index 4c609a2335..5b582e079c 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.hpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.hpp @@ -1,11 +1,11 @@ #pragma once #include "McpCore.hpp" -#include "McpTypes.hpp" #include "VideoEncode.hpp" #include "VideoOverlay.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <boost/filesystem/path.hpp> #include <nlohmann/json.hpp> @@ -33,7 +33,8 @@ class GLCanvas3D; namespace Mcp { -class McpService; +class AutomationRuntime; +class ModalTracker; struct Recording; // `font` resized so that a memory DC, which caption text is drawn in, draws a line of it `line_height` @@ -74,11 +75,13 @@ inline constexpr const char* kPersonOwner = "person"; // recording ends when stopped, at its time limit, when the replay or script that started it ends, when the // endpoint closes for a client's, on a write error and at exit; the sink then finalizes the file on its // own threads, so ending it needs no UI round trip. Created and destroyed on the UI thread with the -// service; the CallObserver methods come from call threads. +// runtime; the CallObserver methods come from call threads. class McpRecorder : public CallObserver { public: - explicit McpRecorder(McpService& service); + // `post_ui` queues a function on the UI thread; nothing runs once the app is gone. + McpRecorder(ModalTracker& modals, std::function<uint64_t()> ui_generation, std::function<bool()> suspended, + std::function<void(std::function<void()>)> post_ui); ~McpRecorder() override; McpRecorder(const McpRecorder&) = delete; McpRecorder& operator=(const McpRecorder&) = delete; @@ -112,6 +115,11 @@ public: // Any thread. Waits up to `timeout` for the recording at `path` to have its file closed; true once it has, // or when that recording is not the latest, since another starts only after it is closed. bool wait_closed(const boost::filesystem::path& path, std::chrono::milliseconds timeout) const; + // Any thread. Encodes a recording once its file is closed: encode_recording with `args` as an unjournaled job, + // which `runtime` follows to its end before posting `done` its result on the UI thread. The job is cancelled + // like any encode (cancel_job {job}, the runtime's stop), and `done` is not called once the runtime stops. + // False when the runtime is not started or is stopping, or when the system cannot start a thread. + bool encode_when_closed(AutomationRuntime& runtime, nlohmann::json args, std::function<void(const ToolResult&)> done); // The files recordings and encodes use; shared with the sinks' finalizers. const std::shared_ptr<RecordingFiles>& files() const { return m_files; } @@ -153,8 +161,13 @@ private: void update_indicator() const; nlohmann::json report(Recording& rec) const; - McpService& m_service; - std::shared_ptr<RecordingFiles> m_files = std::make_shared<RecordingFiles>(); + // The modal dialogs a capture draws over the main window. + ModalTracker& m_modals; + // The UI generation a kept canvas frame belongs to, and whether the main window is being rebuilt. + std::function<uint64_t()> m_ui_generation; + std::function<bool()> m_suspended; + std::function<void(std::function<void()>)> m_post_ui; + std::shared_ptr<RecordingFiles> m_files = std::make_shared<RecordingFiles>(); mutable std::mutex m_mutex; std::shared_ptr<Recording> m_rec; // the latest recording, running, ending or finished diff --git a/src/slic3r/GUI/Mcp/McpReplay.cpp b/src/slic3r/GUI/Mcp/McpReplay.cpp index e2bc132498..1921c108c3 100644 --- a/src/slic3r/GUI/Mcp/McpReplay.cpp +++ b/src/slic3r/GUI/Mcp/McpReplay.cpp @@ -1,6 +1,6 @@ #include "McpReplay.hpp" #include "McpPaths.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <algorithm> #include <chrono> diff --git a/src/slic3r/GUI/Mcp/McpReplay.hpp b/src/slic3r/GUI/Mcp/McpReplay.hpp index 713f99b1f9..c3dae66887 100644 --- a/src/slic3r/GUI/Mcp/McpReplay.hpp +++ b/src/slic3r/GUI/Mcp/McpReplay.hpp @@ -1,6 +1,6 @@ #pragma once -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <boost/filesystem/path.hpp> #include <nlohmann/json.hpp> diff --git a/src/slic3r/GUI/Mcp/McpReplaySummary.cpp b/src/slic3r/GUI/Mcp/McpReplaySummary.cpp index 13404992b4..5a66c109e9 100644 --- a/src/slic3r/GUI/Mcp/McpReplaySummary.cpp +++ b/src/slic3r/GUI/Mcp/McpReplaySummary.cpp @@ -1,11 +1,10 @@ #include "McpReplaySummary.hpp" +#include "McpArguments.hpp" #include "McpPaths.hpp" #include "McpReplay.hpp" -#include "McpTypes.hpp" -#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/ActionIds.hpp" #include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/NativeCommands.hpp" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem/path.hpp> @@ -180,11 +179,11 @@ void describe_action(Builder& b, const json& args) } } -// A command that has a tile and no typed tool's place in the tool list (load_project, export_stl): called by -// its key, it does what run_action of its tile does. -bool tile_command(const std::string& tool) +// A command of `catalog` that has a tile and no typed tool's place in the tool list (load_project, export_stl): +// called by its key, it does what run_action of its tile does. +bool tile_command(const CommandCatalog& catalog, const std::string& tool) { - const NativeCommand* command = NativeCommands::find(tool); + const NativeCommand* command = catalog.find(tool); return command != nullptr && command->in_palette && !command->listed; } @@ -199,7 +198,7 @@ std::optional<std::string> read_text(const fs::path& path) } // A run_replay step: the nested replay, read in the context its run will have. -void describe_nested(Builder& b, const json& args, const ReplayContext& outer, int depth) +void describe_nested(Builder& b, const CommandCatalog& catalog, const json& args, const ReplayContext& outer, int depth) { std::optional<Replay> nested; ReplayContext ctx; @@ -239,7 +238,7 @@ void describe_nested(Builder& b, const json& args, const ReplayContext& outer, i return; } for (const ReplayStep& step : nested->steps) - b.join(describe_step(step, *nested, ctx, depth + 1)); + b.join(describe_step(catalog, step, *nested, ctx, depth + 1)); } // The first scalar argument as "key: value", for tools without a more telling description. @@ -287,14 +286,14 @@ json describe_what(const std::string& tool, const json& args) } // namespace -json describe_call(const std::string& tool, const json& args) +json describe_call(const CommandCatalog& catalog, const std::string& tool, const json& args) { if (tool == "run_action") { Builder b; describe_action(b, args); return b.d.what; } - if (tile_command(tool)) { + if (tile_command(catalog, tool)) { Builder b; describe_command(b, tool, args); return b.d.what; @@ -316,7 +315,8 @@ const char* flag_id(StepFlag flag) return ""; } -StepDescription describe_step(const ReplayStep& step, const Replay& replay, const ReplayContext& ctx, int depth) +StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& step, const Replay& replay, const ReplayContext& ctx, + int depth) { const json args = substitute_lenient(step.args, replay, ctx); const std::string tool = step.tool; @@ -328,10 +328,10 @@ StepDescription describe_step(const ReplayStep& step, const Replay& replay, cons return b.done(); } if (tool == "run_replay") { - describe_nested(b, args, ctx, depth); + describe_nested(b, catalog, args, ctx, depth); return b.done(); } - if (tile_command(tool)) { + if (tile_command(catalog, tool)) { describe_command(b, tool, args); return b.done(); } diff --git a/src/slic3r/GUI/Mcp/McpReplaySummary.hpp b/src/slic3r/GUI/Mcp/McpReplaySummary.hpp index 9a67cebe02..d2c6472b7a 100644 --- a/src/slic3r/GUI/Mcp/McpReplaySummary.hpp +++ b/src/slic3r/GUI/Mcp/McpReplaySummary.hpp @@ -2,6 +2,8 @@ #include "McpReplay.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" + #include <nlohmann/json.hpp> #include <string> @@ -39,18 +41,19 @@ struct StepDescription // Describes `step` of `replay`, substituting its arguments leniently over `ctx`; a file counts as // written inside the output folder when it is inside ctx.out_dir. A step that calls a Speed Dial command -// by its key (one with a tile and no place in the tool list) is described as run_action of its tile is. -// A run_replay step is described by +// by its key (one of `catalog` with a tile and no place in the tool list) is described as run_action of +// its tile is. A run_replay step is described by // the steps of its inline replay, or of its file when `path` reads and parses, each in the nested // run's own context (its vars merged with the step's `vars`, its own replay and output folders); // past `depth` 4, or when the file doesn't read or parse, it gets every flag, "checked" and // answers_dialogs. -StepDescription describe_step(const ReplayStep& step, const Replay& replay, const ReplayContext& ctx, int depth = 0); +StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& step, const Replay& replay, + const ReplayContext& ctx, int depth = 0); -// What a call of `tool` with `args` acts on, as describe_step()'s `what` says it, Speed Dial ids -// included, but from the arguments as they are and without reading files: a run_replay call is named +// What a call of `tool` with `args` acts on, as describe_step()'s `what` says it over `catalog`, Speed Dial +// ids included, but from the arguments as they are and without reading files: a run_replay call is named // by its replay file. For recording captions. -nlohmann::json describe_call(const std::string& tool, const nlohmann::json& args); +nlohmann::json describe_call(const CommandCatalog& catalog, const std::string& tool, const nlohmann::json& args); // What a finished step returned, from the tools' real replies: {"kind":"objects","count":n} // | {"kind":"plates","ok":n,"other":m} | {"kind":"file","name":n} diff --git a/src/slic3r/GUI/Mcp/McpServerInfo.cpp b/src/slic3r/GUI/Mcp/McpServerInfo.cpp new file mode 100644 index 0000000000..b6e7cec393 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpServerInfo.cpp @@ -0,0 +1,70 @@ +// What the server says of itself in initialize and server/discover (server_info()): its name, version and the +// instructions text, which lives here. + +#include "McpProtocol.hpp" + +#include "libslic3r_version.h" + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// Server instructions shown to the model; clients truncate them at 4096 characters. +const char* kInstructions = + "OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n" + "Workflow: get_app_state (is it ready? which presets, plates, dialogs?) -> act -> check it with the reading " + "tools (list_objects, list_plates, get_settings, slice's reply, get_slice_stats); screenshot only to see what they " + "do not report.\n" + "Running the session, dialogs, replays and scripts:\n" + "- A call that takes long or opens a dialog returns {status:\"running\"|\"blocked_by_dialog\", job}. It keeps " + "running: never retry it. Answer dialogs with answer_dialog (see get_app_state.dialogs), then wait {for:\"job\"}. " + "A native message box (native: true) is answered with answer_dialog by one of the buttons listed for it; a file or " + "folder picker, or a native dialog whose buttons list is empty (any on macOS), can't be: register auto_answer_dialogs " + "before the step that opens one.\n" + "- While an operation (slice, export, arrange or another background job) runs, other changes are refused; use wait " + "or cancel_job.\n" + "- export_replay saves this session's calls as a replay that run_replay runs.\n" + "- run_script runs Python against orca.host, the plugin API (search_python_api searches it), computing over meshes and " + "settings and calling tools through orca.host.tools; its own file, program, thread and network use is restricted " + "unless get_app_state.python.scripts_unrestricted.\n" + "- Not sure what does something? search_tools {query} searches every catalog at once: the commands, with those the " + "tool list does not show (Speed Dial commands, the Design tab's, and operations plugins offer as " + "plugin.<plugin>.<name>; call_tool runs them), the Speed Dial's other actions, settings and the Python API, each " + "match with how to use it.\n" + "Acting on project data by index and name, JSON in and out; prefer these:\n" + "- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n" + "- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words, and no " + "scope, which looks through the process, filament and printer settings; each item names its scope, the one " + "set_settings needs (its default is the process), and its meta has its description and where (its settings page and " + "group).\n" + "- Objects, parts and plates are 0-based indices, as list_objects and list_plates give " + "them; filament slots and Preview layers are 1-based.\n" + "- Lists come in pages: {items, offset, total}, with next_offset while more remain; call again with that offset to " + "read on. list_objects has plates and outside in place of items.\n" + "- Paths are absolute. Outputs never overwrite a file unless overwrite is true.\n" + "Driving the GUI itself, for what those do not reach or to see what a person sees:\n" + "- run_action runs every Speed Dial command (search_actions finds them): prefer it to GUI clicks.\n" + "- list_widgets lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; click " + "/ set_widget_value / press_keys / mouse_gesture act on refs from the latest list_widgets call, or on locators, which " + "its description lists.\n" + "- list_windows lists the open windows, modal or not, with refs: a window's ref as screenshot's target captures " + "that window, as list_widgets's target lists it alone, and as set_window's target sizes, moves or raises it.\n" + "- Gizmos (Cut, Text, SVG, the painting tools...): click {target: {gizmo: \"Cut\"}} opens one; its panel's " + "fields and buttons are ImGui items for set_widget_value / click, and painting is a mouse_gesture drag starting on the " + "object. Move the camera with set_view, never a drag: what a drag does follows the user's mouse settings. pick_gizmo_file only stands in for a file picker inside an open gizmo.\n" + "- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" + "- start_recording / stop_recording record a video (MJPEG .mkv), optionally with the tool calls as captions and the " + "pointer highlighted; with encode, stop_recording then encodes it to MP4 with the system ffmpeg as a job to wait " + "for, and encode_recording encodes any recording later."; + +} // namespace + +ServerInfo server_info() +{ + ServerInfo info; + info.version = SLIC3R_VERSION; + info.instructions = kInstructions; + return info; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp deleted file mode 100644 index ce11dd7487..0000000000 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ /dev/null @@ -1,1028 +0,0 @@ -#include "McpCore.hpp" -#include "McpOptions.hpp" -#include "McpService.hpp" - -#include "McpHttpServer.hpp" -#include "McpProtocol.hpp" -#include "McpRecorder.hpp" -#include "McpServicePtr.hpp" -#include "McpToken.hpp" -#include "McpTools.hpp" -#include "McpTypes.hpp" -#include "ModalTracker.hpp" -#include "UiInspector.hpp" -#include "WebPages.hpp" -#include "WindowControl.hpp" -#include "McpPaths.hpp" -#include "McpReplay.hpp" -#include "McpPersonRun.hpp" -#include "JobRegistry.hpp" -#include "slic3r/GUI/SyntheticInput.hpp" -#include "slic3r/GUI/GLCanvas3D.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/ImGuiWrapper.hpp" -#include "slic3r/GUI/Jobs/Worker.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/MainFrame.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Plater.hpp" -#include "slic3r/plugin/PluginManager.hpp" -#include "slic3r/plugin/PythonScriptRunner.hpp" -#include "slic3r/plugin/PythonSession.hpp" - -#include "libslic3r/AppConfig.hpp" -#include "libslic3r/Utils.hpp" -#include "libslic3r_version.h" -#include "UiInvoker.hpp" - -#include <boost/algorithm/string/predicate.hpp> -#include <boost/filesystem/operations.hpp> -#include <boost/filesystem/path.hpp> -#include <boost/log/trivial.hpp> -#include <boost/nowide/cstdlib.hpp> -#include <boost/nowide/fstream.hpp> - -#include <wx/app.h> -#include <wx/event.h> -#include <wx/thread.h> -#include <wx/timer.h> - -#include <algorithm> -#include <atomic> -#include <chrono> -#include <condition_variable> -#include <cstddef> -#include <cstdint> -#include <exception> -#include <functional> -#include <ios> -#include <memory> -#include <mutex> -#include <optional> -#include <set> -#include <sstream> -#include <stdexcept> -#include <string> -#include <thread> -#include <utility> -#include <vector> - -#ifdef _WIN32 -#include <process.h> -#define getpid _getpid -#else -#include <unistd.h> -#endif - -namespace Slic3r { namespace GUI { namespace Mcp { - -// HTTP request threads can outlive the endpoint they came from; they reach the protocol through -// this gate, which drain() closes before the service goes away. -struct RequestGate -{ - std::mutex mutex; - std::condition_variable cv; - McpProtocol* protocol = nullptr; - int active = 0; -}; - -using nlohmann::json; -namespace fs = boost::filesystem; - -namespace { - -std::atomic<int> g_run_exit_code{-1}; - -std::string shutting_down_reply() -{ - return json{{"jsonrpc", "2.0"}, {"id", nullptr}, {"error", {{"code", -32603}, {"message", "OrcaSlicer is shutting down"}}}}.dump(); -} - -class WxDispatcher final : public UiDispatcher -{ -public: - void post(std::function<void()> fn) override - { - // CallAfter queues a thread-safe event; without an app the closure never runs and its - // caller gives up after the queue timeout. - if (wxTheApp == nullptr) - return; - wxTheApp->CallAfter(std::move(fn)); -#ifdef __WXMSW__ - // CallAfter wakes only wx's own loop. In a native modal loop, a menu's or a system dialog's, wx runs - // queued events from a message hook when the loop takes a message off the thread's queue, so give it one - // rather than wait for an unrelated message. - wxWakeUpMainThread(); -#endif - } -}; - -// Whether the Prepare canvas has loaded OpenGL: its functions, shaders and the ImGui font. -bool canvas_gl_ready() -{ - Plater* plater = wxGetApp().plater(); - GLCanvas3D* canvas = plater != nullptr ? plater->canvas3D() : nullptr; - return canvas == nullptr || canvas->is_initialized(); -} - -// Whether the main window has tab pages still to build at idle. -bool pages_pending() -{ - const MainFrame* frame = wxGetApp().mainframe; - return frame != nullptr && frame->prebuild_pending(); -} - -// The Plater's UI job worker, as McpCore watches it for jobs that calls start. -WorkerHooks ui_job_worker_hooks() -{ - WorkerHooks hooks; - hooks.busy = [] { - Plater* plater = wxGetApp().plater(); - return plater != nullptr && !plater->get_ui_job_worker().is_idle(); - }; - hooks.cancel = [] { - if (Plater* plater = wxGetApp().plater()) - plater->get_ui_job_worker().cancel(); - }; - return hooks; -} - -// The scope key of a plugin's calls, which no job id ("j<n>") can equal. -std::string plugin_scope_key(const std::string& plugin_key) { return "plugin:" + plugin_key; } - -// Server instructions shown to the model; clients truncate them at 4096 characters. -const char* kInstructions = - "OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n" - "Workflow: get_app_state (is it ready? which presets, plates, dialogs?) -> act -> check it with the reading " - "tools (list_objects, list_plates, get_settings, slice's reply, get_slice_stats); screenshot only to see what they " - "do not report.\n" - "Running the session, dialogs, replays and scripts:\n" - "- A call that takes long or opens a dialog returns {status:\"running\"|\"blocked_by_dialog\", job}. It keeps " - "running: never retry it. Answer dialogs with answer_dialog (see get_app_state.dialogs), then wait {for:\"job\"}. " - "A native message box (native: true) is answered with answer_dialog by one of the buttons listed for it; a file or " - "folder picker, or a native dialog whose buttons list is empty (any on macOS), can't be: register auto_answer_dialogs " - "before the step that opens one.\n" - "- While an operation (slice, export, arrange or another background job) runs, other changes are refused; use wait " - "or cancel_job.\n" - "- export_replay saves this session's calls as a replay that run_replay runs.\n" - "- run_script runs Python against orca.host, the plugin API (search_python_api searches it), computing over meshes and " - "settings and calling tools through orca.host.tools; its own file, program, thread and network use is restricted " - "unless get_app_state.python.scripts_unrestricted.\n" - "- Not sure what does something? search_tools {query} searches every catalog at once: the commands, with those the " - "tool list does not show (Speed Dial commands, the Design tab's, and operations plugins offer as " - "plugin.<plugin>.<name>; call_tool runs them), the Speed Dial's other actions, settings and the Python API, each " - "match with how to use it.\n" - "Acting on project data by index and name, JSON in and out; prefer these:\n" - "- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n" - "- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words, and no " - "scope, which looks through the process, filament and printer settings; each item names its scope, the one " - "set_settings needs (its default is the process), and its meta has its description and where (its settings page and " - "group).\n" - "- Objects, parts and plates are 0-based indices, as list_objects and list_plates give " - "them; filament slots and Preview layers are 1-based.\n" - "- Lists come in pages: {items, offset, total}, with next_offset while more remain; call again with that offset to " - "read on. list_objects has plates and outside in place of items.\n" - "- Paths are absolute. Outputs never overwrite a file unless overwrite is true.\n" - "Driving the GUI itself, for what those do not reach or to see what a person sees:\n" - "- run_action runs every Speed Dial command (search_actions finds them): prefer it to GUI clicks.\n" - "- list_widgets lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; click " - "/ set_widget_value / press_keys / mouse_gesture act on refs from the latest list_widgets call, or on locators, which " - "its description lists.\n" - "- list_windows lists the open windows, modal or not, with refs: a window's ref as screenshot's target captures " - "that window, as list_widgets's target lists it alone, and as set_window's target sizes, moves or raises it.\n" - "- Gizmos (Cut, Text, SVG, the painting tools...): click {target: {gizmo: \"Cut\"}} opens one; its panel's " - "fields and buttons are ImGui items for set_widget_value / click, and painting is a mouse_gesture drag starting on the " - "object. Move the camera with set_view, never a drag: what a drag does follows the user's mouse settings. pick_gizmo_file only stands in for a file picker inside an open gizmo.\n" - "- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" - "- start_recording / stop_recording record a video (MJPEG .mkv), optionally with the tool calls as captions and the " - "pointer highlighted; with encode, stop_recording then encodes it to MP4 with the system ffmpeg as a job to wait " - "for, and encode_recording encodes any recording later."; - -} // namespace - -void McpServiceDeleter::operator()(McpService* service) const -{ - service->stop(); - if (service->drain(std::chrono::seconds(10))) - delete service; - else - BOOST_LOG_TRIVIAL(error) << "MCP server: a call did not return; leaving the service in place"; -} - -McpService::McpService() = default; - -const CommandCatalog& McpService::catalog() const { return NativeCommands::instance(); } - -ServerInfo McpService::server_info() -{ - ServerInfo info; - info.version = SLIC3R_VERSION; - info.instructions = kInstructions; - return info; -} - -// Reached only through McpServiceDeleter, after stop() joined the launch thread and drain() saw -// every thread leave. -McpService::~McpService() = default; - -int McpService::run_exit_code() { return g_run_exit_code.load(); } - -bool McpService::serving() const { return m_http != nullptr && m_http->running(); } - -uint16_t McpService::port() const { return m_http ? m_http->port() : 0; } - -GuardState McpService::guards_on_ui() const -{ - GuardState g; - g.closing = m_stopping || wxTheApp == nullptr || wxGetApp().is_closing(); - g.suspended = m_suspended; - if (m_modals) { - g.dialogs = m_modals->snapshot(); - g.modal = !g.dialogs.empty(); - g.top_dialog = m_modals->serial(m_modals->top()); - } - return g; -} - -bool McpService::start(const McpLaunchOptions& options, bool serve, std::string& err) -{ - if (m_stopping) { - err = "MCP server: stopped for exit"; - return false; - } - if (m_core == nullptr) { - m_options = options; - m_dispatcher = std::make_unique<WxDispatcher>(); - m_modals = std::make_unique<ModalTracker>(); - m_inspector = std::make_unique<UiInspector>(*this); - m_recorder = std::make_unique<McpRecorder>(*this); - m_invoker = std::make_unique<UiInvoker>(*m_dispatcher, [this] { return guards_on_ui(); }, [this] { return m_generation.load(); }, - [this] { return m_modals->snapshot(); }, - [this](const std::string& tool, bool running) { m_inspector->ui_activity(tool, running); }); - // A plugin's calls are refused from the moment it unloads, before end_plugin_scope() comes. - m_jobs.set_owner_liveness([](const std::string& plugin) { return PluginManager::instance().is_plugin_loaded(plugin); }); - m_core = std::make_unique<McpCore>(catalog(), *m_invoker, m_jobs, &m_journal, CoreTiming{}, ui_job_worker_hooks(), - m_recorder.get()); - // A command reaches the service through its call's context (ToolContext::service()). - m_core->set_service(this); - m_web_presses = std::make_shared<WebPresses>(); - m_modals->set_before_press([this] { release_web_presses(m_web_presses, nullptr); }); - track_window_states(); - m_inspector->capture_menus(true); - if (ImGuiWrapper* imgui = wxGetApp().imgui()) - imgui->set_item_recording(true); - } - if (!serve || serving()) - return true; - - AppConfig* config = wxGetApp().app_config; - int port = options.port; - if (port <= 0 && config != nullptr) { - try { - port = std::stoi(config->get("mcp_port")); - } catch (const std::exception&) { - port = 0; - } - } - if (port <= 0 || port > 65535) - port = kDefaultPort; - - std::string token; - if (const char* env = boost::nowide::getenv("ORCA_MCP_TOKEN"); env != nullptr && *env != '\0') { - token = env; - m_token_source = "ORCA_MCP_TOKEN"; - } else if (!options.token.empty()) { - token = options.token; - m_token_source = "--mcp-token"; - } else { - token = load_or_create_token(path_from_utf8(data_dir()), err); - m_token_source = "file"; - } - if (token.empty()) { - err = "MCP server: no token (" + err + ")"; - return false; - } - m_token = token; - - // Request threads of an endpoint closed earlier may still be using the protocol object. - if (!m_protocol) { - m_protocol = std::make_unique<McpProtocol>(catalog(), *m_core, server_info()); - m_gate = std::make_shared<RequestGate>(); - m_gate->protocol = m_protocol.get(); - } - m_http = std::make_unique<McpHttpServer>(token, [gate = m_gate](const PostRequest& r) -> PostReply { - McpProtocol* protocol = nullptr; - { - std::lock_guard<std::mutex> lock(gate->mutex); - protocol = gate->protocol; - if (protocol == nullptr) - return {503, shutting_down_reply()}; - ++gate->active; - } - struct Leave - { - RequestGate& gate; - ~Leave() - { - { - std::lock_guard<std::mutex> lock(gate.mutex); - --gate.active; - } - gate.cv.notify_all(); - } - } leave{*gate}; - return protocol->handle_post(r); - }); - if (!m_http->start(uint16_t(port), err)) { - err = "MCP server: cannot listen on 127.0.0.1:" + std::to_string(port) + " (" + err + ")"; - m_http.reset(); - // Expected with several windows on one configuration folder, and retried until that window - // closes, so logged once rather than as an error. - const bool held_before = m_port_held_by_other; - m_port_held_by_other = discovery_held_by_other(path_from_utf8(data_dir()), port); - if (!m_port_held_by_other) - BOOST_LOG_TRIVIAL(error) << err; - else if (!held_before) - BOOST_LOG_TRIVIAL(info) << "MCP server: another OrcaSlicer window serves on port " << port; - return false; - } - m_port_held_by_other = false; - { - std::lock_guard<std::mutex> lock(m_rules_mutex); - m_endpoint_open = true; - } - - m_discovery_error.clear(); - if (!write_discovery(path_from_utf8(data_dir()), - {{"url", "http://127.0.0.1:" + std::to_string(m_http->port()) + "/mcp"}, - {"port", m_http->port()}, - {"pid", int(getpid())}, - {"version", SLIC3R_VERSION}, - {"token", token}}, - m_discovery_error)) - // Serving anyway: clients configured with the URL and token still connect; the stdio - // bridge and the harness, which need the file, see the reason in get_app_state. - BOOST_LOG_TRIVIAL(warning) << "MCP server: " << m_discovery_error; - BOOST_LOG_TRIVIAL(info) << "MCP server listening on http://127.0.0.1:" << m_http->port() << "/mcp"; - return true; -} - -void McpService::stop() -{ - // Before the stop flag: a run's stop does nothing once the service is stopping, and it must cancel - // the run's slice while the main window is still there. - if (m_core != nullptr && !m_stopping) - stop_person_runs(); - if (m_core == nullptr || m_stopping.exchange(true)) - return; - BOOST_LOG_TRIVIAL(info) << "MCP server stopping"; - // Its file is finished on the recorder's own threads; this waits a little for them, not for the UI. - m_recorder->shutdown(std::chrono::seconds(5)); - if (m_ready_timer) - m_ready_timer->Stop(); - // Wake everything that waits, so running calls return. - m_invoker->shutdown(); - m_jobs.wake_all(); - m_core->shutdown(); - stop_serving(); - if (m_launch_thread.joinable()) - m_launch_thread.join(); - { - std::lock_guard<std::mutex> lock(m_runs_mutex); - for (RunThread& r : m_run_threads) - if (r.thread.joinable()) - r.thread.join(); - m_run_threads.clear(); - for (EncodeThread& e : m_encode_threads) - if (e.thread.joinable()) - e.thread.join(); - m_encode_threads.clear(); - } - { - // Run rules too: no run survives the stop. - std::lock_guard<std::mutex> lock(m_rules_mutex); - for (const auto& [job, layers] : m_run_rule_layers) - for (int layer : layers) - m_modals->pop_rules(layer); - m_run_rule_layers.clear(); - } - if (m_inspector) { - m_inspector->release_held(nullptr); - release_web_presses(m_web_presses, nullptr); - m_inspector->capture_menus(false); - } - SyntheticInput::clear(); - if (wxTheApp != nullptr) - if (ImGuiWrapper* imgui = wxGetApp().imgui()) - imgui->set_item_recording(false); -} - -bool McpService::acquire_lease() -{ - if (m_stopping) - return false; - ++m_leases; - // A stop that came meanwhile may already be draining: give the lease back rather than race it. - if (m_stopping) { - --m_leases; - return false; - } - return true; -} - -void McpService::release_lease() { --m_leases; } - -bool McpService::drain(std::chrono::milliseconds timeout) -{ - const auto deadline = std::chrono::steady_clock::now() + timeout; - // A lease's holder finds the core stopped and returns at once. - while (m_leases.load() > 0) { - if (std::chrono::steady_clock::now() >= deadline) - return false; - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - if (m_core == nullptr) - return true; - if (m_gate) { - std::unique_lock<std::mutex> lock(m_gate->mutex); - m_gate->protocol = nullptr; - if (!m_gate->cv.wait_until(lock, deadline, [this] { return m_gate->active == 0; })) - return false; - } - const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()); - return m_core->drain(std::max(left, std::chrono::milliseconds(0))); -} - -AutoAnswerSet McpService::set_auto_answer(std::vector<AutoAnswerRule> rules, const std::vector<std::string>& ancestry) -{ - // A plugin's call is owned by its plugin's scope when no run in its chain is nearer. - const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); - std::lock_guard<std::mutex> lock(m_rules_mutex); - // The nearest running replay or script in the caller's job chain owns the rules. - for (const std::string& job : ancestry) - if (auto it = m_run_rule_layers.find(job); it != m_run_rule_layers.end()) { - const bool paused = m_paused_scopes.count(job) != 0; - if (rules.empty()) - return {"run", 0, paused}; - it->second.push_back(m_modals->push_rules(std::move(rules), paused)); - return {"run", it->second.back(), paused}; - } - if (!plugin.empty()) { - if (auto it = m_run_rule_layers.find(plugin_scope_key(plugin)); it != m_run_rule_layers.end()) { - if (rules.empty()) - return {"plugin", 0, false}; - it->second.push_back(m_modals->push_rules(std::move(rules))); - return {"plugin", it->second.back(), false}; - } - if (m_unloaded_plugins.count(plugin) != 0) - throw ToolFailure("The plugin that made this call has been unloaded; its rules were not applied"); - } - // A call that was running when the endpoint closed must not bring its client's rules back. - if (!m_endpoint_open) - throw ToolFailure("The MCP server was turned off while the rules were being set; they were not applied"); - if (m_session_rule_layer != 0) - m_modals->pop_rules(m_session_rule_layer); - m_session_rule_layer = rules.empty() ? 0 : m_modals->push_rules(std::move(rules)); - return {"session", m_session_rule_layer, false}; -} - -void McpService::begin_run_scope(const std::string& job) -{ - std::lock_guard<std::mutex> lock(m_rules_mutex); - m_run_rule_layers.emplace(job, std::vector<int>{}); -} - -void McpService::end_run_scope(const std::string& job, bool wait_recording) -{ - // Noted before the scope goes: from then on a call of this run finds no live scope, and must not be - // taken for a client's. - if (m_recorder) - m_recorder->owner_ended(job); - { - std::lock_guard<std::mutex> lock(m_rules_mutex); - auto it = m_run_rule_layers.find(job); - if (it == m_run_rule_layers.end()) - return; - if (m_modals) - for (int layer : it->second) - m_modals->pop_rules(layer); - m_run_rule_layers.erase(it); - m_paused_scopes.erase(job); - } - // A recording the run started ends with it, its file closed before the run's call returns. - if (m_recorder) - m_recorder->end_owned_by(job, "run_ended", wait_recording); - release_run_presses(job); -} - -void McpService::set_run_scope_paused(const std::string& job, bool paused) -{ - std::lock_guard<std::mutex> lock(m_rules_mutex); - auto it = m_run_rule_layers.find(job); - if (it == m_run_rule_layers.end()) - return; - if (paused) - m_paused_scopes.insert(job); - else - m_paused_scopes.erase(job); - if (m_modals) - for (int layer : it->second) - m_modals->set_paused(layer, paused); -} - -void McpService::release_run_presses(const std::string& job) -{ - // Found again on the UI thread: the service may be gone by the time the closure runs. - if (m_dispatcher && !m_stopping) - m_dispatcher->post([job] { - if (McpService* service = wxGetApp().mcp_service(); service != nullptr && service->m_inspector) { - service->m_inspector->release_held(&job); - release_web_presses(service->m_web_presses, &job); - } - }); -} - -void McpService::cancel_operations_of(const std::string& job) -{ - for (const std::string& op : m_jobs.running_operations()) - if (m_jobs.lineage(op).count(job) != 0 && !m_core->cancel_worker(op)) - if (Plater* plater = wxGetApp().plater()) - plater->cancel_slicing(); -} - -std::string McpService::run_owner(const std::vector<std::string>& ancestry) const -{ - const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); - std::lock_guard<std::mutex> lock(m_rules_mutex); - for (const std::string& job : ancestry) - if (m_run_rule_layers.count(job) != 0) - return job; - if (!plugin.empty() && m_run_rule_layers.count(plugin_scope_key(plugin)) != 0) - return plugin_scope_key(plugin); - // A call of an unloaded plugin must not leave anything nothing would end. - if (!plugin.empty() && m_unloaded_plugins.count(plugin) != 0) - throw ToolFailure("The plugin that made this call has been unloaded"); - return {}; -} - -bool McpService::begin_plugin_scope(const std::string& plugin_key) -{ - std::lock_guard<std::mutex> lock(m_rules_mutex); - if (m_unloaded_plugins.count(plugin_key) != 0) - return false; - m_run_rule_layers.emplace(plugin_scope_key(plugin_key), std::vector<int>{}); - return true; -} - -void McpService::end_plugin_scope(const std::string& plugin_key) -{ - { - std::lock_guard<std::mutex> lock(m_rules_mutex); - m_unloaded_plugins.insert(plugin_key); - } - // No call of the plugin starts from now on, one it was admitted for included, and the ones running stop, - // as a stopped replay's steps do. - m_jobs.block_owner(plugin_key); - for (const std::string& job : m_jobs.running_owned_by(plugin_key)) - m_jobs.request_stop(job); - // Not waited for: an unloading plugin's recording is closed by the recorder's own threads. - end_run_scope(plugin_scope_key(plugin_key), false); -} - -void McpService::plugin_loaded(const std::string& plugin_key) -{ - { - std::lock_guard<std::mutex> lock(m_rules_mutex); - m_unloaded_plugins.erase(plugin_key); - } - m_jobs.unblock_owner(plugin_key); -} - -bool McpService::endpoint_open() const -{ - std::lock_guard<std::mutex> lock(m_rules_mutex); - return m_endpoint_open; -} - -void McpService::stop_serving() -{ - m_port_held_by_other = false; - // A client's recording ends with its endpoint; a run's carries on until the run ends. - if (m_recorder) - m_recorder->end_owned_by({}, "endpoint_closed", false); - // So does a press a client's mouse_gesture left held, on a widget or a page. - if (m_inspector) { - const std::string client; - m_inspector->release_held(&client); - release_web_presses(m_web_presses, &client); - } - { - // A client's rules end with its endpoint; a person using the app afterwards must not have - // dialogs answered for them. - std::lock_guard<std::mutex> lock(m_rules_mutex); - m_endpoint_open = false; - if (m_session_rule_layer != 0) - m_modals->pop_rules(m_session_rule_layer); - m_session_rule_layer = 0; - } - if (!m_http) - return; - // Requests in flight may be waiting on the UI thread, which is running this; drain() waits for - // them before the service goes away. - m_http->stop(false); - m_http.reset(); - remove_discovery(path_from_utf8(data_dir())); - BOOST_LOG_TRIVIAL(info) << "MCP server endpoint closed"; -} - -void McpService::suspend() -{ - // The main window is about to be rebuilt; runs stop while its plater is still the current one. - stop_person_runs(); - if (m_recorder) - m_recorder->suspend(); - m_suspended = true; - ++m_generation; -} - -void McpService::resume() -{ - ++m_generation; - m_suspended = false; - if (m_recorder) - m_recorder->resume(); -} - -void McpService::mark_ready() -{ - if (m_ready || m_ready_timer) - return; - // Starting on Home, the Prepare canvas loads OpenGL at idle after post_init(), and until then a - // 3MF save draws its thumbnail with no GL functions loaded. The main window builds its tab pages - // at idle then too, and a page's web view registers its "wx" handler with a script it waits for in - // a nested loop; on GTK, calls that came in meanwhile have left that wait unfinished for good, - // and with it every later web view's window.wx, a dialog page's own buttons included. So ready - // waits for the canvas and the pages. When the hidden canvas can't get a GL context, the first - // draw of Prepare loads it instead, and the pages build only while no input comes, so ready stops - // waiting after 10 s. - const auto settled = [] { return canvas_gl_ready() && !pages_pending(); }; - if (settled()) { - set_ready(); - return; - } - const auto since = std::chrono::steady_clock::now(); - m_ready_timer = std::make_unique<wxTimer>(); - m_ready_timer->Bind(wxEVT_TIMER, [this, since, settled](wxTimerEvent&) { - if (m_stopping || (!settled() && std::chrono::steady_clock::now() - since < std::chrono::seconds(10))) - return; - m_ready_timer->Stop(); - if (!canvas_gl_ready()) - BOOST_LOG_TRIVIAL(warning) << "MCP ready before the 3D view loaded OpenGL"; - if (pages_pending()) - BOOST_LOG_TRIVIAL(warning) << "MCP ready before the main window built its tab pages"; - set_ready(); - }); - m_ready_timer->Start(100); -} - -void McpService::set_ready() -{ - m_ready = true; - if (!m_options.run_file.empty()) - run_launch_file(); -} - -json McpService::describe() const -{ - json out{{"serving", serving()}, {"ready", ready()}, {"version", SLIC3R_VERSION}}; - if (serving()) { - out["port"] = port(); - out["url"] = "http://127.0.0.1:" + std::to_string(port()) + "/mcp"; - out["token_source"] = m_token_source; - out["token_file"] = path_to_utf8(mcp_dir(path_from_utf8(data_dir())) / "token"); - out["discovery_file"] = path_to_utf8(discovery_path(path_from_utf8(data_dir()))); - if (!m_discovery_error.empty()) - out["discovery_error"] = m_discovery_error; - } - return out; -} - -NativeCommand McpService::as_person(const NativeCommand& command) -{ - NativeCommand person = command; - person.run = [this, handler = command.run](const json& args, ToolContext& ctx) { - const std::string job = ctx.job_id(); - { - std::lock_guard<std::mutex> lock(m_run_state_mutex); - m_person_jobs.insert(job); - } - struct Forget - { - McpService& service; - std::string job; - ~Forget() - { - std::lock_guard<std::mutex> lock(service.m_run_state_mutex); - service.m_person_jobs.erase(job); - } - } forget{*this, job}; - return handler(args, ctx); - }; - return person; -} - -bool McpService::person_run(const std::set<std::string>& lineage) const -{ - std::lock_guard<std::mutex> lock(m_run_state_mutex); - for (const std::string& job : lineage) - if (m_person_jobs.count(job) != 0) - return true; - return false; -} - -void McpService::run_launch_file() -{ - m_launch_thread = std::thread([this] { - int code = 2; - try { - const fs::path file = path_from_utf8(m_options.run_file); - const bool python = boost::algorithm::iequals(path_to_utf8(file.extension()), ".py"); - json args; - if (python) { - boost::nowide::ifstream in(m_options.run_file.c_str(), std::ios::binary); - if (!in) - throw std::runtime_error("Cannot read " + m_options.run_file); - std::ostringstream raw; - raw << in.rdbuf(); - std::string text, encoding, error; - if (!decode_python_source(raw.str(), text, encoding, error)) - throw std::runtime_error("Cannot read " + m_options.run_file + " as Python source: " + error); - args = {{"code", text}, {"filename", m_options.run_file}}; - } else { - args = {{"path", m_options.run_file}}; - if (!m_options.run_out.empty()) - args["out_dir"] = m_options.run_out; - } - const NativeCommand def = as_person(*catalog().find(python ? "run_script" : "run_replay")); - ToolResult r = m_core->call(def, args); - // A replay or script that opened a dialog and answers it itself replies blocked_by_dialog first. - const std::string status = r.is_error ? std::string() : r.data.value("status", ""); - if ((status == "running" || status == "blocked_by_dialog") && r.data.contains("job")) { - std::optional<ToolResult> done; - while (!done && !m_stopping) - done = m_jobs.wait(r.data["job"].get<std::string>(), std::chrono::seconds(5)); - if (done) - r = *done; - } - if (r.is_error) - BOOST_LOG_TRIVIAL(error) << "--mcp-run: " << r.message; - if (python) { - if (!r.is_error && r.data.value("status", "") != "finished") - BOOST_LOG_TRIVIAL(error) << "--mcp-run: " << r.data.value("message", std::string()) << "\n" - << r.data.value("traceback", std::string()); - code = !r.is_error && r.data.value("status", "") == "finished" ? 0 : 1; - } else - code = r.is_error ? (r.data.value("invalid", false) ? 2 : 1) : (r.data.value("passed", false) ? 0 : 1); - } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(error) << "--mcp-run: " << e.what(); - } - g_run_exit_code = code; - BOOST_LOG_TRIVIAL(info) << "--mcp-run finished with exit code " << code; - if (m_stopping || wxTheApp == nullptr) - return; - // Close without the unsaved-project prompt: the run owns this session. - m_dispatcher->post([] { - if (wxTheApp != nullptr && wxGetApp().mainframe != nullptr) - wxGetApp().mainframe->Close(true); - }); - }); -} - -void McpService::post_ui(std::function<void()> fn) -{ - if (m_dispatcher) - m_dispatcher->post(std::move(fn)); -} - -void McpService::request_stop(const std::string& job) { m_jobs.request_stop(job); } - -std::optional<ToolResult> McpService::call_to_end(const NativeCommand& def, const json& args) -{ - ToolResult r = m_core->call(def, args); - const std::string status = r.is_error ? std::string() : r.data.value("status", ""); - if ((status != "running" && status != "blocked_by_dialog") || !r.data.contains("job")) - return r; - const std::string job = r.data["job"].get<std::string>(); - std::optional<ToolResult> done; - while (!done && !m_stopping) { - try { - done = m_jobs.wait(job, std::chrono::seconds(1)); - } catch (const ToolFailure& f) { - done = ToolResult::error(f.what()); // the job's result was lost - } - } - return done; -} - -bool McpService::encode_when_closed(json args, std::function<void(const ToolResult&)> done) -{ - const NativeCommand* encode = started() ? catalog().find("encode_recording") : nullptr; - if (encode == nullptr || m_stopping) - return false; - // A person's encode, outside the session journal like Action Replay's runs. - NativeCommand def = *encode; - def.journal = false; - std::lock_guard<std::mutex> lock(m_runs_mutex); - // Threads that have set their flag are done or about to be; joining them keeps the list short. - for (auto it = m_encode_threads.begin(); it != m_encode_threads.end();) { - if (!*it->finished) { - ++it; - continue; - } - if (it->thread.joinable()) - it->thread.join(); - it = m_encode_threads.erase(it); - } - auto finished = std::make_shared<std::atomic<bool>>(false); - m_encode_threads.push_back({std::thread([this, def, args = std::move(args), done = std::move(done), finished] { - struct Finished - { - std::atomic<bool>& flag; - ~Finished() { flag = true; } - } mark{*finished}; - // The sink's threads close the file soon after the recording ends. - const fs::path source = path_from_utf8(args.value("path", std::string())); - while (!m_stopping && !m_recorder->wait_closed(source, std::chrono::seconds(1))) { - } - if (m_stopping) - return; - std::optional<ToolResult> r = call_to_end(def, args); - if (!r || m_stopping) - return; - post_ui([done, result = std::move(*r)] { done(result); }); - }), - finished}); - return true; -} - -ToolResult McpService::start_encode(const json& args) -{ - const NativeCommand* encode = started() ? catalog().find("encode_recording") : nullptr; - if (encode == nullptr || m_stopping) - return ToolResult::error("OrcaSlicer is shutting down"); - NativeCommand def = *encode; - def.journal = false; - def.budget_ms = 0; // the envelope at once; the result comes from wait - return m_core->call(def, args); -} - -bool McpService::discard_authorized(const std::set<std::string>& lineage) const -{ - std::lock_guard<std::mutex> lock(m_run_state_mutex); - for (const std::string& job : lineage) - if (m_discard_jobs.count(job) != 0) - return true; - return false; -} - -void McpService::stop_person_runs() -{ - std::vector<std::shared_ptr<PersonRun>> runs; - { - std::lock_guard<std::mutex> lock(m_runs_mutex); - for (const RunThread& r : m_run_threads) - if (r.run->running()) - runs.push_back(r.run); - } - for (const auto& run : runs) - run->stop(); -} - -std::shared_ptr<PersonRun> McpService::start_replay_run(Replay replay, ReplayContext sctx, std::optional<std::size_t> only_step, - bool discard_authorized, PersonRun::Events events) -{ - const NativeCommand* run_replay_def = started() ? catalog().find("run_replay") : nullptr; - if (run_replay_def == nullptr || m_stopping) - return nullptr; - { - // Threads whose run has ended are done or about to be; joining them keeps the list short. - std::lock_guard<std::mutex> lock(m_runs_mutex); - for (auto it = m_run_threads.begin(); it != m_run_threads.end();) { - if (it->run->running()) { - ++it; - continue; - } - if (it->thread.joinable()) - it->thread.join(); - it = m_run_threads.erase(it); - } - } - - auto run = std::make_shared<PersonRun>(*this, std::move(events)); - auto shared = std::make_shared<Replay>(std::move(replay)); - auto ctx_held = std::make_shared<ReplayContext>(std::move(sctx)); - // run_replay's properties, outside the session journal: a person's run is not an agent's call. - NativeCommand def = *run_replay_def; - def.journal = false; - def.run = [this, run, shared, ctx_held, only_step, discard_authorized](const json&, ToolContext& ctx) { - const std::string job = ctx.job_id(); - run->set_job(job); - struct Authorization - { - McpService& service; - std::string job; - bool held; - ~Authorization() - { - if (held) { - std::lock_guard<std::mutex> lock(service.m_run_state_mutex); - service.m_discard_jobs.erase(job); - } - } - } authorization{*this, job, discard_authorized}; - if (discard_authorized) { - std::lock_guard<std::mutex> lock(m_run_state_mutex); - m_discard_jobs.insert(job); - } - ReplayRunOptions options; - options.only_step = only_step; - options.write_result = !only_step; - options.step_started = [run](std::size_t index) { run->post_step_started(index); }; - options.step_finished = [run](const json& entry) { run->post_step_finished(entry); }; - return ToolResult::ok(run_replay_job(*this, ctx, *shared, *ctx_held, options)); - }; - def = as_person(def); - - std::lock_guard<std::mutex> lock(m_runs_mutex); - m_run_threads.push_back({std::thread([this, run, def, ctx_held] { - const std::optional<ToolResult> r = call_to_end(def, json::object()); - run->mark_ended(); - if (!r || m_stopping) - return; - // The handler has returned, so the jobs it saved are settled. A run refused - // before its handler started (another operation holds the project) saved none - // and replaces none. - run->post_finished(r->is_error ? json{{"error", r->message}} : r->data, - run->job().empty() ? json() : ctx_held->jobs); - }), - run}); - return run; -} - -std::shared_ptr<PersonRun> McpService::start_python_session(std::shared_ptr<PythonSession> session, const fs::path& file, - PersonRun::Events events) -{ - const NativeCommand* run_script = started() ? catalog().find("run_script") : nullptr; - if (run_script == nullptr || m_stopping || !session) - return nullptr; - { - // Threads whose run has ended are done or about to be; joining them keeps the list short. - std::lock_guard<std::mutex> lock(m_runs_mutex); - for (auto it = m_run_threads.begin(); it != m_run_threads.end();) { - if (it->run->running()) { - ++it; - continue; - } - if (it->thread.joinable()) - it->thread.join(); - it = m_run_threads.erase(it); - } - } - auto run = std::make_shared<PersonRun>(*this, std::move(events)); - auto hosted = std::make_shared<std::atomic<bool>>(false); - auto filename = file.empty() ? std::string("<run_script>") : path_to_utf8(file); - // run_script's properties, outside the session journal, as a person's run. - NativeCommand def = as_person(*run_script); - def.journal = false; - def.run = [this, run, session, hosted, filename](const json&, ToolContext& ctx) { - run->set_job(ctx.job_id()); - hosted->store(true); - // A handler that refuses never hosts the session: it ends here all the same. - struct Ended - { - PythonSession& session; - ~Ended() - { - if (!session.ended()) - session.host_returned(); - } - } ended{*session}; - return run_python_session_job(*this, ctx, *session, filename); - }; - - std::lock_guard<std::mutex> lock(m_runs_mutex); - m_run_threads.push_back({std::thread([this, run, def, session, hosted] { - const std::optional<ToolResult> r = call_to_end(def, json::object()); - run->mark_ended(); - // Refused before its handler ran: the session was never hosted. - if (r && !hosted->load()) - session->host_returned(); - if (!r || m_stopping || !r->is_error) - return; - run->post_finished(json{{"error", r->message}}, json()); - }), - run}); - return run; -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp deleted file mode 100644 index 6686e94ec3..0000000000 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ /dev/null @@ -1,298 +0,0 @@ -#pragma once - -#include "JobRegistry.hpp" -#include "McpCore.hpp" -#include "McpJournal.hpp" -#include "McpOptions.hpp" -#include "McpProtocol.hpp" -#include "McpReplay.hpp" -#include "McpPersonRun.hpp" -#include "McpServicePtr.hpp" -#include "McpTypes.hpp" -#include "UiInvoker.hpp" - -#include "slic3r/GUI/CommandCatalog.hpp" - -#include <boost/filesystem/path.hpp> -#include <nlohmann/json.hpp> - -#include <atomic> -#include <chrono> -#include <cstddef> -#include <cstdint> -#include <functional> -#include <map> -#include <memory> -#include <mutex> -#include <optional> -#include <set> -#include <string> -#include <thread> -#include <vector> - -class wxTimer; - -namespace Slic3r { -class PythonSession; -} - -namespace Slic3r { namespace GUI { namespace Mcp { - -class McpHttpServer; -class McpProtocol; -class McpRecorder; -class ModalTracker; -class UiInspector; -class WebPresses; -struct AutoAnswerRule; -struct RequestGate; - -// Whose an auto_answer_dialogs call's rules are ("run", "plugin" or "session"), the tracker layer they went into (0 for -// none), and whether they start paused: a Run Script session's rules registered between its works answer nothing, an open -// dialog included, until its next work. -struct AutoAnswerSet -{ - std::string scope; - int layer = 0; - bool paused = false; -}; - -// The MCP server inside the running app: owns the UI invoker, jobs, the session journal, the -// modal-dialog tracker and the HTTP endpoint, serves the process's command catalog -// (NativeCommands::instance()), and runs a --mcp-run once the app is ready. Created by GUI_App; started, -// suspended and stopped on the UI thread. -// -// Off unless the preference or --mcp/--mcp-run asks for it; when off, none of this exists. -// Held in an McpServicePtr, whose deleter is the only way to destroy one. -class McpService -{ -public: - McpService(); - McpService(const McpService&) = delete; - McpService& operator=(const McpService&) = delete; - - // What initialize and server/discover report: the server's name, version and instructions. - static ServerInfo server_info(); - - // Starts the automation runtime (jobs, the core, the UI invoker) and, when `serve` is true, opens the HTTP - // endpoint. A replay or script from `options` runs after mark_ready(). Returns false with `err` set when - // the endpoint can't start; the runtime stays usable either way. - bool start(const McpLaunchOptions& options, bool serve, std::string& err); - // Stops everything; idempotent, and final: start() refuses afterwards. Wakes every waiting call - // and closes the endpoint, but frees nothing: a call may still be on the UI thread's stack inside - // a nested event loop, and job and request threads may still be returning. - void stop(); - // After stop(): waits until no request, call or job thread is inside the service. False when one - // is still running after `timeout`; the service must then be kept alive (leaked) rather than - // destroyed under it. - bool drain(std::chrono::milliseconds timeout); - // Closes the HTTP endpoint and removes the discovery file; the catalog, running jobs and a - // launch run carry on, and start() with `serve` opens the endpoint again. This is what - // turning the server off in Preferences does: a running call may have opened that very dialog, - // so the service itself must outlive it. - void stop_serving(); - bool started() const { return m_core != nullptr; } - bool serving() const; - // The last start() could not open the endpoint because another OrcaSlicer window that shares the - // configuration folder serves on the port. Cleared when the endpoint opens or stop_serving() runs. - bool port_held_by_other_window() const { return m_port_held_by_other; } - uint16_t port() const; - const std::string& token() const { return m_token; } - - // Main frame recreation (language change): refs become stale and UI calls fail with "retry" - // until resume(). - void suspend(); - void resume(); - bool suspended() const { return m_suspended; } - - // The main frame finished starting up (end of GUI_App::post_init). Ready follows once the Prepare - // canvas has loaded OpenGL, at once when it already has. - void mark_ready(); - bool ready() const { return m_ready && !m_suspended; } - - // Monotonic counter bumped by suspend(); refs carry it to detect a rebuilt UI. - uint64_t ui_generation() const { return m_generation; } - - // The process's command catalog, which the service serves; the same for every service. Any thread, once - // startup has built it (NativeCommands::build()). - const CommandCatalog& catalog() const; - JobRegistry& jobs() { return m_jobs; } - Journal& journal() { return m_journal; } - UiInvoker& ui() { return *m_invoker; } - McpCore& core() { return *m_core; } - ModalTracker& modals() { return *m_modals; } - // Refs from list_widgets live here, so they survive between calls. UI thread only. - UiInspector& inspector() { return *m_inspector; } - // The presses mouse_gesture downs left on pages, the web counterpart of the inspector's held press. - // Any thread. - WebPresses& web_presses() { return *m_web_presses; } - // start_recording and its kin; also told about every call, for the captions. - McpRecorder& recorder() { return *m_recorder; } - - // Auto-answer rules from auto_answer_dialogs. Rules registered from inside a run (the nearest - // running replay or script in `ancestry`, the caller's job chain, nearest first) last until that run - // ends; a client's rules replace the ones it registered before, and end when the endpoint - // closes: with no endpoint open (the server turned off meanwhile), a client's rules are refused. - // A run scope that is paused (set_run_scope_paused()) gets them paused. Any thread. - AutoAnswerSet set_auto_answer(std::vector<AutoAnswerRule> rules, const std::vector<std::string>& ancestry); - // run_replay and run_script bracket their runs with these. A mouse press the run left held is released - // when it ends, and so is a recording it started; `wait_recording` waits for that recording's file, - // unless the run already did. - void begin_run_scope(const std::string& job); - void end_run_scope(const std::string& job, bool wait_recording = true); - // Pauses or resumes every rule layer of `job`'s scope (ModalTracker::set_paused); a layer the scope adds while it - // is paused starts paused. Any thread. - void set_run_scope_paused(const std::string& job, bool paused); - // Releases the mouse presses `job`'s calls left held, on widgets and pages, as the end of its scope does. Any - // thread. - void release_run_presses(const std::string& job); - // Cancels the operations whose lineage holds `job`, as cancel_job does: a background job through the worker, - // a slice or an export through the plater. UI thread. - void cancel_operations_of(const std::string& job); - // The job of the nearest running replay or script in `ancestry`, else the scope of the plugin whose call it is, - // or "" for a client's own call. Any thread. - std::string run_owner(const std::vector<std::string>& ancestry) const; - // Keeps the service from being destroyed while a caller outside the core uses it: a plugin's call holds - // a lease from the moment the UI thread hands it the service until the call returns, and drain() waits - // for every lease. False once the service is stopping. Any thread. - bool acquire_lease(); - void release_lease(); - // A plugin's calls own what they leave behind (auto-answer rules, a recording, a held press) as a - // run's do, until the plugin unloads: begin is called before each of its calls (idempotent), end when - // it unloads. Any thread. - // begin returns false for a plugin whose scope ended (it unloaded) until plugin_loaded() is called for - // it again; end also stops the plugin's running calls, and a call of its that would leave something - // behind after that is refused (run_owner, set_auto_answer throw). - bool begin_plugin_scope(const std::string& plugin_key); - void end_plugin_scope(const std::string& plugin_key); - void plugin_loaded(const std::string& plugin_key); - // Whether clients can reach the server: false from stop_serving() until the endpoint opens again. - // A client's call still running then must not leave state behind that the closing ended. Any thread. - bool endpoint_open() const; - - // {serving, ready, version, port, url, token_file, token_source, discovery_file, - // discovery_error} for Preferences and get_app_state. - nlohmann::json describe() const; - // Where the token in use comes from: "file", "ORCA_MCP_TOKEN" or "--mcp-token". - const std::string& token_source() const { return m_token_source; } - - // Exit code of a --mcp-run run (0 passed, 1 failed, 2 invalid), -1 when none ran. Read by - // GUI_Run after the event loop ends; wx ignores OnExit()'s return value. - static int run_exit_code(); - - // Runs a replay for the Action Replay window: an unjournaled mutate job, as run_replay runs one, - // whose steps report through `events`. A thread the service owns follows the job to its end, past a - // running or blocked_by_dialog reply, and posts `finished`; stop() joins it. `only_step` runs one - // step (no result.json). `discard_authorized`: the user chose not to save before a run that - // replaces the project, so the replacing tools may drop unsaved changes while it runs. nullptr when - // the service is not started or is stopping. UI thread. - std::shared_ptr<PersonRun> start_replay_run(Replay replay, ReplayContext sctx, std::optional<std::size_t> only_step, - bool discard_authorized, PersonRun::Events events); - // Hosts the Run Script panel's `session` as an unjournaled person's run_script job (run_python_session_job()) on a - // thread the service owns, which stop() joins and stop_person_runs() stops. `file` is the session's file; empty - // for an unsaved script. `events.finished` is posted only for a job refused before its handler ran or a handler - // that refused (Python scripts off), as {"error": message}; the session's end is PythonSession::ended(), which a - // refused job sets too. nullptr when the service is not started or is stopping. UI thread. - std::shared_ptr<PersonRun> start_python_session(std::shared_ptr<PythonSession> session, const boost::filesystem::path& file, - PersonRun::Events events); - // True when a run a person started (Action Replay, the Run Script panel, --mcp-run, a long command a person - // picked) is in `lineage`: a run_script there runs as the person's script, not an agent's. Any thread. - bool person_run(const std::set<std::string>& lineage) const; - // `command` with a function that marks its job as a person's run while it runs (person_run()). - NativeCommand as_person(const NativeCommand& command); - // Stops `job` and what it runs: every call it and its descendants make sees itself cancelled - // (JobRegistry::request_stop). Any thread. - void request_stop(const std::string& job); - // True while a run in `lineage` that the user let drop unsaved changes is running. Any thread. - bool discard_authorized(const std::set<std::string>& lineage) const; - // Stops every run start_replay_run() started, while the main window is still the one they run in. - // suspend() and stop() call it first. UI thread. - void stop_person_runs(); - bool stopping() const { return m_stopping; } - // Queues `fn` on the UI thread; nothing runs once the app is gone. Any thread. - void post_ui(std::function<void()> fn); - // Encodes a recording once its file is closed: encode_recording with `args` as an unjournaled job, which - // a thread the service owns follows to its end before posting `done` its result on the UI thread. The job - // is cancelled like any encode (cancel_job {job}, stop()), and `done` is not called once the service stops. - // False when the service is not started or is stopping. Any thread. - bool encode_when_closed(nlohmann::json args, std::function<void(const ToolResult&)> done); - // Starts encode_recording with `args` as an unjournaled job of its own and returns at once: the job's - // envelope, or the error that refused it. For a recording's encode that stop_recording starts, which a - // replay of the recording asks for again. Any thread. - ToolResult start_encode(const nlohmann::json& args); - -private: - friend struct McpServiceDeleter; - ~McpService(); - - // Calls `command` and follows the job it starts to its end; nullopt when the service stops first. A thread - // the service owns calls it. - std::optional<ToolResult> call_to_end(const NativeCommand& command, const nlohmann::json& args); - void set_ready(); - void run_launch_file(); - GuardState guards_on_ui() const; - - McpLaunchOptions m_options; - std::string m_token; - std::string m_token_source; - std::string m_discovery_error; - bool m_port_held_by_other = false; - - std::unique_ptr<UiDispatcher> m_dispatcher; - JobRegistry m_jobs; - Journal m_journal; - // Before the invoker, so it outlives the invoker's callbacks, which read it. - std::unique_ptr<ModalTracker> m_modals; - // Before the core, which reports its calls to it. - std::unique_ptr<McpRecorder> m_recorder; - std::unique_ptr<UiInvoker> m_invoker; - std::unique_ptr<McpCore> m_core; - std::unique_ptr<McpProtocol> m_protocol; - std::unique_ptr<McpHttpServer> m_http; - std::shared_ptr<RequestGate> m_gate; - std::unique_ptr<UiInspector> m_inspector; - // Shared with the page calls that release its presses, whose replies may come after the service. - std::shared_ptr<WebPresses> m_web_presses; - - mutable std::mutex m_rules_mutex; - std::map<std::string, std::vector<int>> m_run_rule_layers; // running replay's or script's job -> layers - std::set<std::string> m_paused_scopes; // jobs whose layers are paused - int m_session_rule_layer = 0; - bool m_endpoint_open = false; - - std::atomic<bool> m_ready{false}; - // Polls for the Prepare canvas's OpenGL between mark_ready() and ready. UI thread. - std::unique_ptr<wxTimer> m_ready_timer; - std::atomic<bool> m_suspended{false}; - std::atomic<bool> m_stopping{false}; - std::atomic<int> m_leases{0}; - std::atomic<uint64_t> m_generation{1}; - std::thread m_launch_thread; - - // Runs a person started (Action Replay, the Run Script panel), each with the thread that follows its job. - struct RunThread - { - std::thread thread; - std::shared_ptr<PersonRun> run; - }; - std::mutex m_runs_mutex; - std::vector<RunThread> m_run_threads; - // Threads following encode_when_closed()'s jobs, each with the flag it sets on leaving. - struct EncodeThread - { - std::thread thread; - std::shared_ptr<std::atomic<bool>> finished; - }; - std::vector<EncodeThread> m_encode_threads; // under m_runs_mutex - mutable std::mutex m_run_state_mutex; - std::set<std::string> m_discard_jobs; - std::set<std::string> m_person_jobs; - std::set<std::string> m_unloaded_plugins; // under m_rules_mutex -}; - -// Lets plugins call the tools through orca.host.tools: a call from a plugin's Script worker runs as -// McpCore::call_plugin(), starting the service without its endpoint when MCP is off, and is logged. -// Called once by GUI_App as it sets up plugins. -void install_plugin_tool_caller(); - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpServicePtr.hpp b/src/slic3r/GUI/Mcp/McpServicePtr.hpp deleted file mode 100644 index 3e46de992a..0000000000 --- a/src/slic3r/GUI/Mcp/McpServicePtr.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include <memory> - -namespace Slic3r { namespace GUI { namespace Mcp { - -class McpService; - -// The only way a service is destroyed: stops it, then frees it once no request, call or job thread -// is inside it. A service whose calls do not return within a few seconds is leaked instead, as they -// hold references into it. Kept apart from McpService.hpp so GUI_App.hpp can hold the pointer. -struct McpServiceDeleter -{ - void operator()(McpService* service) const; -}; - -using McpServicePtr = std::unique_ptr<McpService, McpServiceDeleter>; - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpStdioBridge.cpp b/src/slic3r/GUI/Mcp/McpStdioBridge.cpp index 1b93bf87a1..9bf7d530cd 100644 --- a/src/slic3r/GUI/Mcp/McpStdioBridge.cpp +++ b/src/slic3r/GUI/Mcp/McpStdioBridge.cpp @@ -3,11 +3,9 @@ #include "McpOptions.hpp" #include "McpProtocol.hpp" -#include "McpService.hpp" -#include "McpTypes.hpp" #include "libslic3r/Utils.hpp" #include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "libslic3r_version.h" #include <boost/asio/connect.hpp> @@ -30,9 +28,11 @@ #include <boost/nowide/iostream.hpp> #include <chrono> +#include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> +#include <functional> #include <map> #include <utility> #include <vector> @@ -304,7 +304,8 @@ std::string string_member(const json& obj, const char* key) // The reply this build's server would give to `line`, for any request but tools/call: the other // methods only read the tool catalog and the server's details, and the server keeps no session, so // the reply is the same whether or not OrcaSlicer runs. -PostReply answer_offline(const std::string& line, const std::map<std::string, std::string>& headers) +PostReply answer_offline(const std::string& line, const std::map<std::string, std::string>& headers, + const std::function<const CommandCatalog&()>& catalog) { // A tool needs the app, so the bridge never brings a tools/call here. struct NoApp final : ToolCaller @@ -312,8 +313,9 @@ PostReply answer_offline(const std::string& line, const std::map<std::string, st ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("OrcaSlicer is not running."); } }; static NoApp caller; - // The process catalog, built here on first use: this process never starts the GUI that builds it. - static McpProtocol protocol(NativeCommands::instance(), caller, McpService::server_info()); + // Made on the first request answered here, the only time `catalog` is called: this process never starts + // the GUI, so the catalog may be built on that call. + static McpProtocol protocol(catalog(), caller, server_info()); auto header = [&headers](const char* name) { const auto it = headers.find(name); return it == headers.end() ? std::string() : it->second; @@ -356,7 +358,7 @@ std::map<std::string, std::string> bridge_headers(const json& message, const std return h; } -int run_stdio_bridge(int argc, char** argv) +int run_stdio_bridge(int argc, char** argv, const std::function<const CommandCatalog&()>& catalog) { #ifdef _WIN32 _setmode(_fileno(stdin), _O_BINARY); @@ -463,7 +465,7 @@ int run_stdio_bridge(int argc, char** argv) } if (!endpoint) { if (!needs_app) { - const PostReply offline = answer_offline(line, headers); + const PostReply offline = answer_offline(line, headers, catalog); reply = std::make_pair(offline.status, offline.body); } else if (connect()) reply = post(*endpoint, line, headers, &sent); diff --git a/src/slic3r/GUI/Mcp/McpStdioBridge.hpp b/src/slic3r/GUI/Mcp/McpStdioBridge.hpp index 466589863d..a8dac77f7b 100644 --- a/src/slic3r/GUI/Mcp/McpStdioBridge.hpp +++ b/src/slic3r/GUI/Mcp/McpStdioBridge.hpp @@ -1,7 +1,10 @@ #pragma once +#include "slic3r/GUI/CommandCatalog.hpp" + #include <nlohmann/json.hpp> +#include <functional> #include <map> #include <string> @@ -10,10 +13,11 @@ namespace Slic3r { namespace GUI { namespace Mcp { // `orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]`: an MCP server on stdin/stdout for // clients that only speak stdio (Claude Desktop, for one). Each newline-delimited JSON-RPC message // is POSTed to the running OrcaSlicer's endpoint found through <datadir>/mcp/server.json. While none -// answers, every request but tools/call gets the reply this build's server would give, from its own -// catalog (NativeCommands::instance()), and a tools/call starts OrcaSlicer with --mcp, giving it -// up to 60 s: an agent session that never calls a tool never opens the app. Runs before any GUI setup. -int run_stdio_bridge(int argc, char** argv); +// answers, every request but tools/call gets the reply this build's server would give, from the +// catalog `catalog` returns, and a tools/call starts OrcaSlicer with --mcp, giving it up to 60 s: an +// agent session that never calls a tool never opens the app. Runs before any GUI setup. `catalog` is +// called at most once, on the first request answered without the app. +int run_stdio_bridge(int argc, char** argv, const std::function<const CommandCatalog&()>& catalog); // The HTTP headers a Streamable HTTP client derives from a message: MCP-Protocol-Version (the // message's _meta version, else the version `initialize` negotiated), Mcp-Method and, for diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index f695e8cbaf..602e5e9894 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -1,9 +1,10 @@ #pragma once -#include "McpTypes.hpp" +#include "McpPersonRun.hpp" #include "libslic3r/CustomGCode.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/Slicing.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" @@ -52,13 +53,13 @@ struct Refusal; namespace Mcp { -class McpService; +class AutomationRuntime; struct Replay; struct ReplayContext; // Each tool family adds its commands to the catalog (NativeCommands::register_all_commands()), and so do the -// Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function reaches the MCP service through -// its call's context (ToolContext::service()), so the catalog is built without one. +// Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function reaches the automation runtime +// through its call's context (ToolContext::runtime()), so the catalog is built without one. void register_app_tools(CommandCatalog& catalog); void register_action_tools(CommandCatalog& catalog); void register_project_tools(CommandCatalog& catalog); @@ -84,9 +85,9 @@ struct ReplayRunOptions // Runs a parsed replay as the calling job, as run_replay does: steps are child calls, dialog rules // the replay registers end with it, and result.json goes to sctx.out_dir (created if missing). It // stops before the next step, and stops waiting on a step's job, once the call is cancelled: the -// service stops, or a stop was asked for any job in the call's lineage (McpService::request_stop), so +// runtime stops, or a stop was asked for any job in the call's lineage (JobRegistry::request_stop), so // a nested run_replay stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file). -nlohmann::json run_replay_job(McpService& service, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, +nlohmann::json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options); // ---- schema helpers -------------------------------------------------------------------------- @@ -211,12 +212,28 @@ bool python_has_numpy(); // recording, a held press) until the session ends, with its rules paused between works and its presses released as each // work ends. The calls hang under a lineage node of the job, which a stop cancels, inline calls included, and which the // next work replaces. Hosts `session` (host_python_session()) under `filename` until it ends; a job cancel ends it. -ToolResult run_python_session_job(McpService& service, ToolContext& ctx, PythonSession& session, const std::string& filename); +ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename); + +// Hosts the Run Script panel's `session` as an unjournaled person's run_script job (run_python_session_job()), which +// `runtime` follows on a thread of its own that its stop() joins and stop_followed() stops. `file` is the session's +// file; empty for an unsaved script. `events.finished` is posted only for a job refused before its handler ran or a +// handler that refused (Python scripts off), as {"error": message}; the session's end is PythonSession::ended(), +// which a refused job sets too. nullptr when the runtime is not started or is stopping, or when the system cannot +// start a thread. UI thread. +std::shared_ptr<PersonRun> start_python_session(AutomationRuntime& runtime, std::shared_ptr<PythonSession> session, + const boost::filesystem::path& file, PersonRun::Events events); // What an editor suggests for each listed command: [{name, title (translated), args: {name: {type?, enum?}}}]. The // argument descriptions are written for agents, in English, and stay out. nlohmann::json editor_tool_catalog(const CommandCatalog& catalog); +// ---- recording (McpToolsRecord.cpp) ---------------------------------------------------------- + +// Starts encode_recording with `args` as an unjournaled job of its own and returns at once: the job's envelope, or +// the error that refused it. For a recording's encode that stop_recording starts, which a replay of the recording +// asks for again. Any thread. +ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args); + // ---- settings scopes (McpToolsConfig.cpp) ---------------------------------------------------- // The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered` diff --git a/src/slic3r/GUI/Mcp/McpToolsActions.cpp b/src/slic3r/GUI/Mcp/McpToolsActions.cpp index 87238f6a4a..d6bafe6fd6 100644 --- a/src/slic3r/GUI/Mcp/McpToolsActions.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsActions.cpp @@ -2,11 +2,13 @@ // plugin scripts and pages, and (on request) settings - is reachable through these two tools. #include "slic3r/GUI/I18N.hpp" +#include "McpArguments.hpp" #include "McpPersonContext.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/ActionIds.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/ExportOps.hpp" diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index bf4c7e9cdb..1c9e845330 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -3,11 +3,12 @@ // search_tools's search also reaches the other catalogs an agent calls into: the Speed Dial's other actions, // settings and the Python API. +#include "McpArguments.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI.hpp" diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index eeca0366b5..c81e8a1236 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -2,17 +2,18 @@ #include "JobRegistry.hpp" #include "slic3r/GUI/I18N.hpp" +#include "McpEndpoint.hpp" #include "McpPaths.hpp" #include "McpRecorder.hpp" #include "libslic3r/Config.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "ModalTracker.hpp" #include "PythonScriptsDialog.hpp" #include "ScreenCapture.hpp" #include "UiInspector.hpp" #include "WindowControl.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" @@ -28,6 +29,7 @@ #include "slic3r/plugin/PythonInterpreter.hpp" #ifdef SLIC3R_CAD #include "McpToolsCad.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #endif #if defined(__WXGTK__) #include "slic3r/GUI/LinuxDisplayBackend.hpp" @@ -103,21 +105,23 @@ const char* mode_name(ConfigOptionMode mode) } // The app as an agent sees it. UI thread. -json app_state(McpService& service) +json app_state(AutomationRuntime& runtime) { + // A session that never opened the MCP endpoint has none. + const McpEndpoint* endpoint = wxGetApp().mcp_endpoint(); json state{{"version", SLIC3R_VERSION}, {"platform", platform_name()}, {"display_backend", display_backend()}, - {"ready", service.ready()}, - {"dialogs", service.modals().snapshot()}, - {"closed_menus", service.inspector().closed_menus()}, - {"auto_answer_rules", service.modals().rules_json()}, - {"mcp", service.describe()}, + {"ready", runtime.ready()}, + {"dialogs", runtime.modals().snapshot()}, + {"closed_menus", runtime.inspector().closed_menus()}, + {"auto_answer_rules", runtime.modals().rules_json()}, + {"mcp", endpoint != nullptr ? endpoint->describe() : json{{"serving", false}}}, {"python", {{"available", PythonInterpreter::instance().is_initialized()}, {"scripts_unrestricted", python_scripts_unrestricted(*wxGetApp().app_config)}}}, - {"jobs", service.jobs().list()}}; - if (json recording = service.recorder().state(); !recording.is_null()) + {"jobs", runtime.jobs().list()}}; + if (json recording = runtime.recorder().state(); !recording.is_null()) state["recording"] = std::move(recording); // Each display's work area, where set_window can place a window. json displays = json::array(); @@ -151,7 +155,7 @@ json app_state(McpService& service) // The page exists only when the CAD preference was on at startup. #ifdef SLIC3R_CAD state["design_tab"] = frame->m_design_page != nullptr; - if (json note = cad_note(service.catalog()); !note.is_null()) + if (json note = cad_note(NativeCommands::instance()); !note.is_null()) state["cad_note"] = std::move(note); #else state["design_tab"] = false; @@ -219,16 +223,16 @@ json app_state(McpService& service) } // Whether `condition` holds now. UI thread. -bool condition_holds(McpService& service, const std::string& condition, const std::set<std::string>& own_jobs) +bool condition_holds(AutomationRuntime& runtime, const std::string& condition, const std::set<std::string>& own_jobs) { if (condition == "ready") - return service.ready(); + return runtime.ready(); if (condition == "dialog") - return service.modals().any_open(); + return runtime.modals().any_open(); if (condition == "no_dialog") - return !service.modals().any_open(); + return !runtime.modals().any_open(); if (condition == "idle") { - if (service.modals().any_open() || service.jobs().any_running_except(own_jobs)) + if (runtime.modals().any_open() || runtime.jobs().any_running_except(own_jobs)) return false; Plater* plater = wxGetApp().plater(); if (plater == nullptr) @@ -253,7 +257,8 @@ void register_app_tools(CommandCatalog& catalog) "height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python " "(available: Python runs " "in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to " - "OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts), design_tab " + "OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run " + "with --unrestricted-scripts), design_tab " "(the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, " "cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, " "selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the " @@ -270,8 +275,8 @@ void register_app_tools(CommandCatalog& catalog) "notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running " "recording.", object_schema({}), [](const json&, ToolContext& ctx) { - McpService& service = ctx.service(); - return ToolResult::ok(ctx.run_ui([&service] { return app_state(service); })); + AutomationRuntime& runtime = ctx.runtime(); + return ToolResult::ok(ctx.run_ui([&runtime] { return app_state(runtime); })); })); NativeCommand wait = inspect_tool( @@ -285,7 +290,7 @@ void register_app_tools(CommandCatalog& catalog) {"job", prop("string", "Job id, for \"job\".")}, {"timeout_s", {{"type", "number"}, {"minimum", 0}, {"maximum", 50}, {"description", "Default 30."}}}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); const std::string what = arg_string(args, "for", args.contains("job") ? "job" : "idle"); const auto timeout = std::chrono::milliseconds(int(arg_double(args, "timeout_s", 30) * 1000)); const auto start = std::chrono::steady_clock::now(); @@ -293,14 +298,14 @@ void register_app_tools(CommandCatalog& catalog) const std::string job = arg_string(args, "job"); if (job.empty()) throw ToolFailure("job is required for \"job\""); - require_own_job(ctx, service.jobs(), job, "waits for"); - if (auto r = service.jobs().wait(job, timeout, [&ctx] { return ctx.cancelled(); })) + require_own_job(ctx, runtime.jobs(), job, "waits for"); + if (auto r = runtime.jobs().wait(job, timeout, [&ctx] { return ctx.cancelled(); })) return *r; return ToolResult::ok({{"status", "running"}, {"job", job}, {"note", "Still running; wait again."}}); } const std::set<std::string> own = ctx.lineage(); for (;;) { - const bool holds = ctx.run_ui([&] { return json(condition_holds(service, what, own)); }).get<bool>(); + const bool holds = ctx.run_ui([&] { return json(condition_holds(runtime, what, own)); }).get<bool>(); const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start); if (holds) return ToolResult::ok({{"satisfied", true}, {"waited_ms", waited.count()}}); diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp index 9539ae8614..f1f5937fd4 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.cpp @@ -14,6 +14,7 @@ #include <exception> #include <cstdint> +#include <cstddef> #include <cstdlib> #include <cstring> #include <string> @@ -43,8 +44,9 @@ #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "McpArguments.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "McpPaths.hpp" #include "UiInspector.hpp" // gizmo_name: the name get_app_state reports #include "slic3r/GUI/CAD/DesignPanel.hpp" @@ -176,17 +178,18 @@ const char* mode_note(const DesignTool& t) "constrains a sketch, its Confirm or Cancel button ends that)."; } -// cad_note()'s text, given while the preference is off and while it is on but was off at startup. The -// catalog holds the Design commands only when the feature was on at startup, and the main window creates -// the Design page only then too (its panel is built on first use), so turning the feature on takes a restart. -const char* const kCadOffNote = "call_tool runs no Design command now: they need the CAD feature on in Preferences > " - "Features, and on when OrcaSlicer started. A person turns it on there if it is off, and " - "restarts OrcaSlicer."; +// cad_note()'s text, given while the feature is off and while it is on but was off at startup. The +// catalog holds the Design commands only when the feature was on at startup (the preference, or the command +// line's --cad), and the main window creates the Design page only then too (its panel is built on first use), +// so turning the feature on takes a restart. +const char* const kCadOffNote = "call_tool runs no Design command now: they need the CAD feature on when OrcaSlicer " + "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: <key>; " // or a tile's "<key> is a Design tab tile, and " (unknown_action()). const char* const kCadOffAtStartup = "the CAD feature was off when OrcaSlicer started: a person turns it on in " - "Preferences > Features and restarts OrcaSlicer"; + "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"; json describe_scene(DesignPanel* panel) { diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.hpp b/src/slic3r/GUI/Mcp/McpToolsCad.hpp index 4072107de6..7b5e5b7057 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.hpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.hpp @@ -15,7 +15,7 @@ #include "slic3r/GUI/CAD/DesignOffer.hpp" #include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <nlohmann/json.hpp> diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp index 7f6906fc3d..b4034869fe 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp @@ -2,9 +2,9 @@ #include "libslic3r/Model.hpp" -#include "McpTypes.hpp" #include "UiInspector.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index efa3a75c66..6c1b949a3d 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -6,8 +6,9 @@ // dialog, whose handlers carry their effects. #include "slic3r/GUI/I18N.hpp" +#include "McpArguments.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/CreatePresetsDialog.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" diff --git a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp index d7dda85ddf..325668958b 100644 --- a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp @@ -5,7 +5,7 @@ #include "slic3r/GUI/I18N.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" diff --git a/src/slic3r/GUI/Mcp/McpToolsProject.cpp b/src/slic3r/GUI/Mcp/McpToolsProject.cpp index d73af2d34a..5fd8df3dc2 100644 --- a/src/slic3r/GUI/Mcp/McpToolsProject.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsProject.cpp @@ -2,12 +2,13 @@ // Calibration menu's tests, which start a new project. #include "slic3r/GUI/I18N.hpp" +#include "JobRegistry.hpp" #include "McpPaths.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/MainFrame.hpp" @@ -404,7 +405,7 @@ void register_project_tools(CommandCatalog& catalog) "replaces it.")}}, {"paths"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); std::vector<fs::path> paths; for (const json& p : args["paths"]) { std::string err; @@ -417,7 +418,7 @@ void register_project_tools(CommandCatalog& catalog) throw ToolFailure("paths is empty"); const std::string as = arg_string(args, "as", "auto"); // A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes. - const bool discard = arg_bool(args, "discard_changes", false) || service.discard_authorized(ctx.lineage()); + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); json out = ctx.run_ui([&]() -> json { Plater& plater = ui_plater(); if (paths.size() == 1 && has_extension(paths[0], {".gcode", ".bgcode"})) { @@ -463,8 +464,8 @@ void register_project_tools(CommandCatalog& catalog) {"preset_changes", enum_prop({"keep", "discard"}, "The presets' unsaved changes, not the project's: keep " "them for the new project (default) or drop them.")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - const bool discard = arg_bool(args, "discard_changes", false) || service.discard_authorized(ctx.lineage()); + AutomationRuntime& runtime = ctx.runtime(); + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); const bool discard_presets = arg_string(args, "preset_changes", "keep") == "discard"; json out = ctx.run_ui([&] { ui_plater(); @@ -533,9 +534,9 @@ void register_project_tools(CommandCatalog& catalog) "test or drop them first. Required when presets are modified.")}}, {"test"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); json recorded = args; - const bool discard = arg_bool(args, "discard_changes", false) || service.discard_authorized(ctx.lineage()); + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); json out = ctx.run_ui([&]() -> json { Plater& plater = ui_plater(); if (plater.printer_technology() != ptFFF) diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 4809c917d5..fc38011336 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -2,11 +2,16 @@ // reference. #include "JobRegistry.hpp" +#include "McpArguments.hpp" #include "McpCore.hpp" -#include "McpService.hpp" +#include "McpPaths.hpp" +#include "McpPersonRun.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/plugin/PluginAuditManager.hpp" @@ -15,6 +20,8 @@ #include "slic3r/plugin/PythonSession.hpp" #include "slic3r/plugin/host/PluginHostTools.hpp" +#include <boost/filesystem/path.hpp> + #include <pybind11/eval.h> #include <pybind11/gil.h> #include <pybind11/pybind11.h> @@ -24,6 +31,8 @@ #include <atomic> #include <chrono> #include <cstddef> +#include <memory> +#include <optional> #include <string> #include <utility> #include <vector> @@ -59,12 +68,12 @@ private: class SessionBridge final : public ToolBridge { public: - SessionBridge(McpService& service, const std::string& session_job) - : m_service(service), m_node(service.jobs(), "run_script", session_job) + SessionBridge(AutomationRuntime& runtime, const std::string& session_job) + : m_runtime(runtime), m_node(runtime.jobs(), "run_script", session_job) {} json call(const std::string& tool, const json& args) override { - ToolResult r = m_service.core().call_child_named(tool, args, m_node.id()); + ToolResult r = m_runtime.core().call_child_named(tool, args, m_node.id()); if (r.is_error) throw ToolCallError(r.message, r.data); return r.data; @@ -75,11 +84,11 @@ public: { const std::string node = m_node.id(); m_stopped = true; - m_service.request_stop(node); - // Found again on the UI thread: the service may be gone by the time the closure runs. - m_service.post_ui([node] { - if (McpService* service = wxGetApp().mcp_service()) - service->cancel_operations_of(node); + m_runtime.jobs().request_stop(node); + // Found again on the UI thread: the runtime may be gone by the time the closure runs. + m_runtime.post_ui([node] { + if (AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->cancel_operations_of(node); }); } // As a work starts: after a stop its calls get a node no stop was asked for. @@ -90,9 +99,9 @@ public: } private: - McpService& m_service; - LineageNode m_node; - std::atomic<bool> m_stopped{false}; + AutomationRuntime& m_runtime; + LineageNode m_node; + std::atomic<bool> m_stopped{false}; }; // python_api_reference()'s walk over the orca package. @@ -245,40 +254,86 @@ bool python_has_numpy() } } -ToolResult run_python_session_job(McpService& service, ToolContext& ctx, PythonSession& session, const std::string& filename) +ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename) { const std::string job = ctx.job_id(); // The session waits for the person between works: `wait {for: "idle"}` counts only the calls it makes. - service.jobs().set_idle(job); + runtime.jobs().set_idle(job); // What its calls leave behind is the session's, as a run's is; its rules act only while a work runs. - service.begin_run_scope(job); - service.set_run_scope_paused(job, true); + runtime.begin_run_scope(job); + runtime.set_run_scope_paused(job, true); struct ScopeEnd { - McpService& service; + AutomationRuntime& runtime; std::string job; - ~ScopeEnd() { service.end_run_scope(job); } - } scope_end{service, job}; + ~ScopeEnd() { runtime.end_run_scope(job); } + } scope_end{runtime, job}; - SessionBridge bridge(service, job); + SessionBridge bridge(runtime, job); ScopedToolBridge bound(bridge); PythonSessionRequest request; request.identity = kScriptIdentityPerson; request.filename = filename; request.cancelled = [&ctx] { return ctx.cancelled(); }; request.stop_calls = [&bridge] { bridge.stop_calls(); }; - request.work_started = [&service, &bridge, job] { + request.work_started = [&runtime, &bridge, job] { bridge.renew_after_stop(); - service.set_run_scope_paused(job, false); + runtime.set_run_scope_paused(job, false); }; - request.work_ended = [&service, job] { - service.set_run_scope_paused(job, true); - service.release_run_presses(job); + request.work_ended = [&runtime, job] { + runtime.set_run_scope_paused(job, true); + runtime.release_run_presses(job); }; host_python_session(request, session); return ToolResult::ok({{"status", "ended"}}); } +std::shared_ptr<PersonRun> start_python_session(AutomationRuntime& runtime, std::shared_ptr<PythonSession> session, + const boost::filesystem::path& file, PersonRun::Events events) +{ + const NativeCommand* run_script = NativeCommands::instance().find("run_script"); + if (run_script == nullptr || runtime.stopping() || !session) + return nullptr; + auto run = std::make_shared<PersonRun>(runtime, std::move(events)); + auto hosted = std::make_shared<std::atomic<bool>>(false); + auto filename = file.empty() ? std::string("<run_script>") : path_to_utf8(file); + // run_script's properties, outside the session journal, as a person's run. + NativeCommand def = *run_script; + def.journal = false; + def.run = [&runtime, run, session, hosted, filename](const json&, ToolContext& ctx) { + run->set_job(ctx.job_id()); + hosted->store(true); + // A handler that refuses never hosts the session: it ends here all the same. + struct Ended + { + PythonSession& session; + ~Ended() + { + if (!session.ended()) + session.host_returned(); + } + } ended{*session}; + return run_python_session_job(runtime, ctx, *session, filename); + }; + + FollowedCall call; + call.command = std::move(def); + call.person = true; + call.ended = [&runtime, run, session, hosted](const std::optional<ToolResult>& r) { + run->mark_ended(); + // Refused before its handler ran: the session was never hosted. + if (r && !hosted->load()) + session->host_returned(); + if (!r || runtime.stopping() || !r->is_error) + return; + run->post_finished(json{{"error", r->message}}, json()); + }; + call.stop = [run] { run->stop(); }; + if (!runtime.follow(std::move(call))) + return nullptr; + return run; +} + void register_python_tools(CommandCatalog& catalog) { NativeCommand run = mutate_tool( @@ -306,25 +361,25 @@ void register_python_tools(CommandCatalog& catalog) "from its folder and its PEP 723 dependencies; any other name only names it.")}}, {"code"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); // A plugin's script is the plugin's own code: its identity and grants. const std::string& plugin = ctx.caller_plugin(); - const std::string identity = !plugin.empty() ? plugin : - service.person_run(ctx.lineage()) ? kScriptIdentityPerson : - kScriptIdentityAgent; + const std::string identity = !plugin.empty() ? plugin : + runtime.jobs().person_in(ctx.lineage()) ? kScriptIdentityPerson : + kScriptIdentityAgent; // A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON // script does: it all ends with the run. const std::string job = ctx.job_id(); // A run may wait for a person in its window: `wait {for: "idle"}` counts only the calls it makes. - service.jobs().set_idle(job); - service.begin_run_scope(job); + runtime.jobs().set_idle(job); + runtime.begin_run_scope(job); struct ScopeEnd { - McpService& service; + AutomationRuntime& runtime; std::string job; - ~ScopeEnd() { service.end_run_scope(job); } - } scope_end{service, job}; + ~ScopeEnd() { runtime.end_run_scope(job); } + } scope_end{runtime, job}; RunBridge bridge(ctx); ScopedToolBridge bound(bridge); @@ -338,7 +393,7 @@ void register_python_tools(CommandCatalog& catalog) request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300)); request.cancelled = [&ctx] { return ctx.cancelled(); }; // A stop or time-out cancels the run's tool calls in flight too, so one that waits returns at once. - request.stop_calls = [&service, job] { service.request_stop(job); }; + request.stop_calls = [&runtime, job] { runtime.jobs().request_stop(job); }; const PythonRunOutcome out = run_python_code(request); if (out.status == "unavailable") throw ToolFailure(out.message); diff --git a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp index 3aca5775ed..905a218807 100644 --- a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp @@ -1,14 +1,15 @@ // start_recording, stop_recording and encode_recording: a video of what OrcaSlicer shows, optionally captioned // with the current tool call and its pointer highlighted, and its encode to MP4. +#include "McpCore.hpp" #include "McpPaths.hpp" #include "McpRecorder.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "RecordingSettings.hpp" #include "VideoEncode.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/NativeCommands.hpp" @@ -96,6 +97,17 @@ std::vector<std::string> encode_preset_keys() } // namespace +ToolResult start_encode(AutomationRuntime& runtime, const json& args) +{ + const NativeCommand* encode = NativeCommands::instance().find("encode_recording"); + if (encode == nullptr || runtime.stopping()) + return ToolResult::error("OrcaSlicer is shutting down"); + NativeCommand def = *encode; + def.journal = false; + def.budget_ms = 0; // the envelope at once; the result comes from wait + return runtime.core().call(def, args); +} + void register_record_tools(CommandCatalog& catalog) { // The Speed Dial's Start Recording too: with no arguments it opens the tile's dialog. @@ -131,7 +143,7 @@ void register_record_tools(CommandCatalog& catalog) {"save_path", prop("string", "Absolute .mkv path; default the session's output folder.")}, {"overwrite", prop("boolean", "Replace an existing save_path, and with encode its MP4.")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); RecordingOptions o; o.target = arg_string(args, "target", "main"); o.fps = arg_int(args, "fps", 10); @@ -164,14 +176,14 @@ void register_record_tools(CommandCatalog& catalog) o.encode["overwrite"] = true; } // Like auto-answer rules: a run's recording ends with the run, a client's with the endpoint. - const std::vector<std::string> ancestry = service.jobs().ancestry(ctx.job_id()); - o.owner = service.run_owner(ancestry); + const std::vector<std::string> ancestry = runtime.jobs().ancestry(ctx.job_id()); + o.owner = runtime.run_owner(ancestry); // A call of a run that has ended (its scope gone before this ran): not a client's call. - if (o.owner.empty() && service.recorder().owner_ended_in(ancestry)) + if (o.owner.empty() && runtime.recorder().owner_ended_in(ancestry)) throw ToolFailure("The replay or script that started the recording has ended"); // Reserved here, off the UI thread: comparing paths may touch the disk. start() keeps the // reservation for the recording or releases it. - const std::shared_ptr<RecordingFiles>& files = service.recorder().files(); + const std::shared_ptr<RecordingFiles>& files = runtime.recorder().files(); const uint64_t owner = files->new_owner(); if (const std::string why = files->reserve(owner, {{o.path, RecordingFiles::Use::Recording}}); !why.empty()) throw ToolFailure("Cannot record there: " + why); @@ -189,12 +201,12 @@ void register_record_tools(CommandCatalog& catalog) } release{*files, owner, handed_over}; json out = ctx.run_ui([&] { ui_plater(); // refuses while OrcaSlicer starts or closes - // On the UI thread, as stop_serving() runs: a client's start queued while the endpoint + // On the UI thread, as close_client_scope() runs: a client's start queued while the endpoint // closed must not begin a recording nothing would end. - if (o.owner.empty() && !service.endpoint_open()) + if (o.owner.empty() && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off; the recording was not started"); handed_over = true; // start() owns the reservation from here, success or not - return service.recorder().start(o, owner); + return runtime.recorder().start(o, owner); }); if (settings.encode) out["encode"] = {{"codec", settings.codec}, @@ -225,22 +237,22 @@ void register_record_tools(CommandCatalog& catalog) "file, it shows the person a notification naming it and replies with its path; the next " "stop_recording with silent: true reports it as ended stopped_in_app.", object_schema({}), [](const json&, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); // The last state too, even if the timer has not ticked since the last call. Without the // UI thread (a native dialog holds it), the recording ends with its last frame. try { ctx.run_ui([&] { - service.recorder().capture_now(); + runtime.recorder().capture_now(); return json(); }); } catch (const ToolFailure&) { } json encode; - json report = service.recorder().stop_and_report(std::chrono::seconds(60), encode); + json report = runtime.recorder().stop_and_report(std::chrono::seconds(60), encode); if (report.is_null()) throw ToolFailure("No recording is running"); if (!encode.is_null()) { - const ToolResult r = service.start_encode(encode); + const ToolResult r = start_encode(runtime, encode); report["encode"] = r.is_error ? json{{"error", r.message}} : r.data; } return ToolResult::ok(report); @@ -265,8 +277,8 @@ void register_record_tools(CommandCatalog& catalog) "encoder's (high, main).")}, {"delete_source", prop("boolean", "Delete the .mkv once encoded (a recording this session made).")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - const std::shared_ptr<RecordingFiles>& files = service.recorder().files(); + AutomationRuntime& runtime = ctx.runtime(); + const std::shared_ptr<RecordingFiles>& files = runtime.recorder().files(); std::string err; fs::path source; if (args.contains("path")) { diff --git a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp b/src/slic3r/GUI/Mcp/McpToolsReplay.cpp index bd7052c438..80261c1490 100644 --- a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsReplay.cpp @@ -1,14 +1,15 @@ // run_replay and export_replay: deterministic replays of tool calls, and turning a session into one. #include "JobRegistry.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "McpJournal.hpp" #include "McpPaths.hpp" #include "McpRecorder.hpp" #include "McpReplay.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> @@ -57,12 +58,12 @@ std::string timestamp() return buf; } -// An invalid replay is a tool error flagged `invalid`, which --mcp-run turns into exit code 2. +// An invalid replay is a tool error flagged `invalid`, which --run turns into exit code 2. ToolResult invalid(const std::string& message) { return ToolResult::error("Invalid replay: " + message, {{"invalid", true}}); } } // namespace -json run_replay_job(McpService& service, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options) +json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options) { boost::system::error_code ec; fs::create_directories(sctx.out_dir, ec); @@ -70,31 +71,31 @@ json run_replay_job(McpService& service, ToolContext& ctx, const Replay& replay, throw ToolFailure("Cannot create " + path_to_utf8(sctx.out_dir) + ": " + ec.message()); const std::string job = ctx.job_id(); - service.begin_run_scope(job); + runtime.begin_run_scope(job); struct ScopeEnd { - McpService& service; + AutomationRuntime& runtime; std::string job; bool recording_waited = false; // the run below waited for the replay's recording already - ~ScopeEnd() { service.end_run_scope(job, !recording_waited); } - } scope_end{service, job}; + ~ScopeEnd() { runtime.end_run_scope(job, !recording_waited); } + } scope_end{runtime, job}; const auto stopped = [&ctx] { return ctx.cancelled(); }; ReplayHost host; host.call = [&ctx](const std::string& tool, const json& a) { return ctx.call_child(tool, a); }; - host.wait_job = [&service, &stopped](const std::string& id, int timeout_s) { - return service.jobs().wait(id, std::chrono::seconds(timeout_s), stopped); + host.wait_job = [&runtime, &stopped](const std::string& id, int timeout_s) { + return runtime.jobs().wait(id, std::chrono::seconds(timeout_s), stopped); }; host.cancelled = stopped; host.step_started = options.step_started; host.step_finished = options.step_finished; - host.open_dialogs = [&service] { return service.ui().open_dialogs(); }; + host.open_dialogs = [&runtime] { return runtime.ui().open_dialogs(); }; json result = run_replay(replay, sctx, host, options.only_step); // A recording the replay started ends with it, its file closed before the result is written; one still // being written after the wait is named, since an encode of it would fail. - std::optional<std::string> unfinished = service.recorder().end_owned_by(job, "run_ended", true); + std::optional<std::string> unfinished = runtime.recorder().end_owned_by(job, "run_ended", true); scope_end.recording_waited = true; if (unfinished) result["unfinished_recording"] = *unfinished; @@ -124,7 +125,7 @@ void register_replay_tools(CommandCatalog& catalog) {"out_dir", prop("string", "Absolute directory for result.json and screenshots; created if missing.")}, {"vars", {{"type", "object"}, {"description", "Values that override the replay's vars."}}}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); const bool has_path = args.contains("path"), has_replay = args.contains("replay"); if (has_path == has_replay) return invalid("give exactly one of path and replay"); @@ -154,7 +155,7 @@ void register_replay_tools(CommandCatalog& catalog) if (!replay) return invalid(err); for (const ReplayStep& step : replay->steps) - if (service.catalog().lookup(step.tool) == nullptr) + if (NativeCommands::instance().lookup(step.tool) == nullptr) return invalid("unknown tool " + step.tool); if (args.contains("vars")) for (const auto& [key, value] : args["vars"].items()) @@ -165,7 +166,7 @@ void register_replay_tools(CommandCatalog& catalog) return invalid("out_dir must be an absolute path"); if (!has_path) sctx.replay_dir = sctx.out_dir; - json result = run_replay_job(service, ctx, *replay, sctx, ReplayRunOptions{}); + json result = run_replay_job(runtime, ctx, *replay, sctx, ReplayRunOptions{}); return ToolResult::ok(std::move(result)); }); // Its steps call any tool, run_script included. @@ -184,11 +185,11 @@ void register_replay_tools(CommandCatalog& catalog) {"overwrite", prop("boolean", "Replace an existing file.")}, {"clear", prop("boolean", "Forget the calls recorded so far once exported.")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); if (!ctx.caller_plugin().empty()) throw ToolFailure("export_replay exports the agent's session, which a plugin's calls are not part of"); json running; - json replay = service.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running); + json replay = runtime.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running); json out{{"steps", replay["steps"].size()}}; if (!running.empty()) out["left_out_running"] = std::move(running); @@ -201,7 +202,7 @@ void register_replay_tools(CommandCatalog& catalog) out["path"] = path_to_utf8(*path); } if (arg_bool(args, "clear", false)) - service.journal().clear(); + runtime.journal().clear(); out["replay"] = std::move(replay); return ToolResult::ok(std::move(out)); }); diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index f1841ef07d..936f5a51f1 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -9,12 +9,12 @@ #include "libslic3r/Config.hpp" #include "libslic3r/Point.hpp" #include "McpPaths.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "UiInspector.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -23,6 +23,7 @@ #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/NotificationManager.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" @@ -1194,7 +1195,7 @@ void register_scene_tools(CommandCatalog& catalog) {"fill_with", enum_prop({"instances", "copies"}, "Default instances.")}, {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 1800}, {"description", "Cancel it after this long (default 300)."}}}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); ArrangeStart start; ctx.run_ui([&] { start = start_arrange(ui_plater(), args); @@ -1219,7 +1220,7 @@ void register_scene_tools(CommandCatalog& catalog) if (ctx.cancelled()) throw; // McpCore keeps the call's admission until the cancelled job has really stopped. - ctx.observe_ui([&] { return json(service.core().cancel_worker(ctx.job_id())); }); + ctx.observe_ui([&] { return json(runtime.core().cancel_worker(ctx.job_id())); }); throw ToolFailure("The arrangement did not finish within " + std::to_string(timeout.count()) + " s, so it was cancelled"); } }))); @@ -1357,28 +1358,28 @@ void register_scene_tools(CommandCatalog& catalog) "operation, a run_script run or an encode_recording. Allowed while an operation holds the project.", object_schema({{"job", prop("string", "The operation's job to cancel, e.g. \"j12\".")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - const auto ops = service.jobs().running_operations(); + AutomationRuntime& runtime = ctx.runtime(); + const auto ops = runtime.jobs().running_operations(); // A plugin stops only what its own calls started, so it names the job. if (!ctx.caller_plugin().empty() && !args.contains("job")) throw ToolFailure("A plugin cancels only the jobs of its own calls: give the job"); if (args.contains("job")) - require_own_job(ctx, service.jobs(), arg_string(args, "job"), "cancels"); + require_own_job(ctx, runtime.jobs(), arg_string(args, "job"), "cancels"); if (args.contains("job")) { const std::string job = arg_string(args, "job"); if (std::find(ops.begin(), ops.end(), job) == ops.end()) { // A call that is no operation but can be stopped: its handler watches for the stop. - const NativeCommand* def = service.catalog().find(service.jobs().running_tool(job)); + const NativeCommand* def = NativeCommands::instance().find(runtime.jobs().running_tool(job)); if (def == nullptr || !def->cancellable) throw ToolFailure("Job " + job + " is not a running operation", {{"running", ops}}); - service.request_stop(job); + runtime.jobs().request_stop(job); return ToolResult::ok({{"was_running", true}, {"job", job}}); } } json out = ctx.run_ui([&]() -> json { // Only a job an MCP call started: a person's (Text typing) is theirs to stop. for (const std::string& op : ops) - if ((!args.contains("job") || op == arg_string(args, "job")) && service.core().cancel_worker(op)) + if ((!args.contains("job") || op == arg_string(args, "job")) && runtime.core().cancel_worker(op)) return {{"was_running", true}, {"job", op}}; Plater& plater = ui_plater(); // A slice operation still waiting to request its slice counts: the cancel keeps it from starting. diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index 619978d410..c30d78a5a7 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -5,15 +5,16 @@ #include "slic3r/GUI/I18N.hpp" #include "McpCore.hpp" #include "McpPaths.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "WindowNames.hpp" #include "ModalTracker.hpp" #include "ScreenCapture.hpp" #include "UiInspector.hpp" #include "WebPages.hpp" #include "WindowControl.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" @@ -83,21 +84,21 @@ const json kModifiersSchema = {{"type", "array"}, {"description", "Modifier keys held during the click, as in press_keys: ctrl and cmd are both Command on macOS " "and Ctrl elsewhere; rawctrl is the macOS Control key."}}; -bool in_top_dialog(McpService& service, wxWindow* window) +bool in_top_dialog(AutomationRuntime& runtime, wxWindow* window) { - wxDialog* top = service.modals().top(); + wxDialog* top = runtime.modals().top(); return top != nullptr && window != nullptr && owning_window(window) == top; } // GUI input tools run under the recover guard so they can work in the topmost modal dialog; a // target anywhere else gets the checks a mutate call would: no other call's nested loop, no open // modal, and operation admission (no MCP operation holding the project, no busy UI job worker). -void guard_target(McpService& service, wxWindow* window) +void guard_target(AutomationRuntime& runtime, wxWindow* window) { - if (in_top_dialog(service, window)) + if (in_top_dialog(runtime, window)) return; - service.ui().require_mutate(); - service.core().admit({}); + runtime.ui().require_mutate(); + runtime.core().admit({}); } // The window a target is in: a widget's own, a row's list. @@ -133,7 +134,7 @@ const json kPopupItemSchema = prop("string", "Run this item of the menu the inpu // input queued have run. A call that fails before reading it drops it. struct InputMenu { - McpService& service; + AutomationRuntime& runtime; ToolContext& ctx; std::string item; int token = 0; @@ -145,7 +146,7 @@ struct InputMenu // which runs it too). std::shared_ptr<bool> marked; - InputMenu(McpService& service, ToolContext& ctx, std::string item) : service(service), ctx(ctx), item(std::move(item)) {} + InputMenu(AutomationRuntime& runtime, ToolContext& ctx, std::string item) : runtime(runtime), ctx(ctx), item(std::move(item)) {} InputMenu(const InputMenu&) = delete; InputMenu& operator=(const InputMenu&) = delete; ~InputMenu() @@ -154,7 +155,7 @@ struct InputMenu return; try { ctx.observe_ui([this] { - service.inspector().drop_menu(token); + runtime.inspector().drop_menu(token); return json(); }); } catch (const ToolFailure&) { @@ -162,7 +163,7 @@ struct InputMenu } // UI thread, in the input's closure, before the input. - void arm() { token = service.inspector().arm_menu(item); } + void arm() { token = runtime.inspector().arm_menu(item); } // UI thread, after an input to a 3D view, on the handler the input posted its work to. void mark(wxEvtHandler* queue) { @@ -180,9 +181,9 @@ struct InputMenu settle(ctx); const int t = std::exchange(token, 0); return ctx.observe_ui([&] { - json out = service.inspector().disarm_menu(t); - if ((dialogs || out.contains("ran")) && service.modals().any_open()) - out["dialogs"] = service.modals().snapshot(); + json out = runtime.inspector().disarm_menu(t); + if ((dialogs || out.contains("ran")) && runtime.modals().any_open()) + out["dialogs"] = runtime.modals().snapshot(); return out; }); } @@ -214,11 +215,11 @@ std::vector<wxWebView*> visible_webviews() // The web view a script without a target runs in: the one in the topmost modal dialog while one is // open, else the only one shown. -wxWebView* default_webview(McpService& service) +wxWebView* default_webview(AutomationRuntime& runtime) { std::vector<wxWebView*> webs = visible_webviews(); std::string where; - if (wxDialog* top = service.modals().top()) { + if (wxDialog* top = runtime.modals().top()) { std::vector<wxWebView*> in_top; for (wxWebView* w : webs) if (owning_window(w) == top) @@ -242,16 +243,16 @@ wxWebView* default_webview(McpService& service) // A web view in a dialog under the topmost modal one is refused, one in the topmost takes input as // that dialog's widgets do (and the call works in that dialog), and any other gets the checks a // mutate call would. -void guard_page(McpService& service, ToolContext& ctx, wxWebView* web) +void guard_page(AutomationRuntime& runtime, ToolContext& ctx, wxWebView* web) { - const std::vector<wxDialog*>& stack = service.modals().stack(); + const std::vector<wxDialog*>& stack = runtime.modals().stack(); const auto in = std::find(stack.begin(), stack.end(), owning_window(web)); if (in != stack.end() && *in != stack.back()) throw ToolFailure("\"" + into_u8((*in)->GetTitle()) + "\" is under \"" + into_u8(stack.back()->GetTitle()) + "\"; answer the topmost dialog first"); if (in != stack.end()) - ctx.works_in_dialog(service.modals().serial(stack.back())); - guard_target(service, web); + ctx.works_in_dialog(runtime.modals().serial(stack.back())); + guard_target(runtime, web); } // ---- web pages ---------------------------------------------------------------------------------- @@ -271,16 +272,16 @@ bool is_web_target(const json& target) // A widget target that is a web view itself (its `w` ref, or a {class: "webview"} locator), whose page // wx events never reach: its handle, `within` and locator, or 0 for any other target. -WebHandle web_view_target(McpService& service, ToolContext& ctx, const json& target, std::string& within, json* locator = nullptr) +WebHandle web_view_target(AutomationRuntime& runtime, ToolContext& ctx, const json& target, std::string& within, json* locator = nullptr) { WebHandle out = 0; ctx.run_ui([&]() -> json { - const UiTarget t = service.inspector().resolve(target); + const UiTarget t = runtime.inspector().resolve(target); if (auto* web = dynamic_cast<wxWebView*>(target_window(t))) { out = web_handle(web); within = within_of(web); if (locator != nullptr) - *locator = service.inspector().locator_for(t); + *locator = runtime.inspector().locator_for(t); } return json(); }); @@ -288,10 +289,10 @@ WebHandle web_view_target(McpService& service, ToolContext& ctx, const json& tar } // click and set_widget_value on a web view: the page's elements are the targets. -void refuse_web_view(McpService& service, ToolContext& ctx, const json& target) +void refuse_web_view(AutomationRuntime& runtime, ToolContext& ctx, const json& target) { std::string within; - if (web_view_target(service, ctx, target, within) != 0) + if (web_view_target(runtime, ctx, target, within) != 0) throw ToolFailure("That is a web view, whose page wx events don't reach; target one of its page elements: a d ref from " "list_widgets, or a {web} / {css} locator"); } @@ -447,10 +448,10 @@ void check_page_reply(const PageReply& r, std::chrono::seconds timeout, bool act // The pages a locator looks in: the shown ones within `within`, in snapshot order. Without `within` // while the topmost modal dialog shows a page, only that dialog's pages, the ones list_widgets reads // and the only ones input can reach, so a page behind it never makes a label ambiguous. -std::vector<wxWebView*> locator_pages(McpService& service, const std::string& within) +std::vector<wxWebView*> locator_pages(AutomationRuntime& runtime, const std::string& within) { - std::vector<wxWebView*> webs = service.inspector().web_views(within); - if (wxDialog* top = within.empty() ? service.modals().top() : nullptr) { + std::vector<wxWebView*> webs = runtime.inspector().web_views(within); + if (wxDialog* top = within.empty() ? runtime.modals().top() : nullptr) { std::vector<wxWebView*> in_top; for (wxWebView* w : webs) if (owning_window(w) == top) @@ -462,12 +463,12 @@ std::vector<wxWebView*> locator_pages(McpService& service, const std::string& wi } // Finds a page element by ref or locator; `index` picks among the matches of all locator_pages(). -WebTarget resolve_web(McpService& service, ToolContext& ctx, const json& target, std::chrono::seconds timeout) +WebTarget resolve_web(AutomationRuntime& runtime, ToolContext& ctx, const json& target, std::chrono::seconds timeout) { WebTarget out; if (!is_web_locator(target)) { ctx.run_ui([&]() -> json { - const UiTarget t = service.inspector().resolve(target); + const UiTarget t = runtime.inspector().resolve(target); if (t.kind != UiTarget::Kind::WebElement) throw ToolFailure("The ref is not a page element"); auto* web = dynamic_cast<wxWebView*>(t.window.get()); @@ -511,14 +512,14 @@ WebTarget resolve_web(McpService& service, ToolContext& ctx, const json& target, webs.clear(); withins.clear(); ctx.run_ui([&]() -> json { - const std::vector<wxWebView*> pages = locator_pages(service, within); + const std::vector<wxWebView*> pages = locator_pages(runtime, within); for (wxWebView* w : pages) { webs.push_back(web_handle(w)); withins.push_back(within_of(w)); } - if (wxDialog* top = service.modals().top(); top != nullptr && !pages.empty() && + if (wxDialog* top = runtime.modals().top(); top != nullptr && !pages.empty() && std::all_of(pages.begin(), pages.end(), [top](wxWebView* w) { return owning_window(w) == top; })) - ctx.works_in_dialog(service.modals().serial(top)); + ctx.works_in_dialog(runtime.modals().serial(top)); return json(); }); matches.clear(); @@ -599,7 +600,7 @@ WebTarget resolve_web(McpService& service, ToolContext& ctx, const json& target, // The locator the journal records for the element an action reached: the page's own, with `within`, // and `index` among the matches of every page a locator looks in. -json web_locator(McpService& service, ToolContext& ctx, const WebTarget& t, const json& reply, std::chrono::seconds timeout) +json web_locator(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& t, const json& reply, std::chrono::seconds timeout) { if (!reply.contains("loc") || !reply["loc"].is_object()) return json(); @@ -608,7 +609,7 @@ json web_locator(McpService& service, ToolContext& ctx, const WebTarget& t, cons loc["within"] = t.within; std::vector<WebHandle> webs; ctx.observe_ui([&]() -> json { - for (wxWebView* w : locator_pages(service, t.within)) + for (wxWebView* w : locator_pages(runtime, t.within)) webs.push_back(web_handle(w)); return json(); }); @@ -632,10 +633,10 @@ std::string refused_button(const std::string& button, DialogPress refused) // `closed: true`, with the dialogs still open under the one that closed (the filament picker under the // colour picker it opened), whose answer is still to give. Any thread. -json closed_reply(McpService& service) +json closed_reply(AutomationRuntime& runtime) { json out{{"closed", true}}; - if (json open = service.modals().snapshot(); !open.empty()) + if (json open = runtime.modals().snapshot(); !open.empty()) out["dialogs"] = std::move(open); return out; } @@ -669,7 +670,7 @@ std::string watch_id() // when a configuration frame could not be compared (then changed only when a line was found), and how // many messages the page itself sent OrcaSlicer during the action (posted). A change after that is the // next snapshot's to show. -json observe_page(McpService& service, ToolContext& ctx, const WebTarget& t, const PageBefore& before, const json& reply) +json observe_page(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& t, const PageBefore& before, const json& reply) { const std::string href = reply.value("href", std::string()); const bool moved_hash = reply.contains("href0") && reply.value("href0", std::string()) != href; @@ -689,11 +690,11 @@ json observe_page(McpService& service, ToolContext& ctx, const WebTarget& t, con try { change = ctx.observe_ui([&]() -> json { wxWebView* web = web_view_of(t.web); - const auto& stack = service.modals().stack(); - if (web == nullptr || (before.modal != 0 && !service.modals().is_open(before.modal))) - return closed_reply(service); + const auto& stack = runtime.modals().stack(); + if (web == nullptr || (before.modal != 0 && !runtime.modals().is_open(before.modal))) + return closed_reply(runtime); if (stack.size() > before.stack) - return {{"dialogs", service.modals().snapshot()}}; + return {{"dialogs", runtime.modals().snapshot()}}; // The page's own URL is the new one when it moved; the web view's may lag behind it. if (moved_hash) return navigated(href); @@ -703,7 +704,7 @@ json observe_page(McpService& service, ToolContext& ctx, const WebTarget& t, con }); } catch (const ToolFailure&) { // A native dialog the action opened can hold the UI thread's queue (macOS). - return service.modals().any_open() ? json{{"dialogs", service.modals().snapshot()}} : json::object(); + return runtime.modals().any_open() ? json{{"dialogs", runtime.modals().snapshot()}} : json::object(); } if (!change.is_null()) return change; @@ -714,7 +715,7 @@ json observe_page(McpService& service, ToolContext& ctx, const WebTarget& t, con if (!doc.empty()) { const PageReply now = ask_page(ctx, t.web, {{"op", "doc"}}, std::chrono::steady_clock::now() + 1s); if (now.state == PageReply::State::Destroyed) - return closed_reply(service); + return closed_reply(runtime); if (now.state == PageReply::State::Answered && now.value.contains("doc") && now.value.value("doc", std::string()) != doc) return navigated(now.value.value("href", std::string())); } @@ -725,7 +726,7 @@ json observe_page(McpService& service, ToolContext& ctx, const WebTarget& t, con // it is not past its deadline when a busy page answers the rounds before it slowly. const PageReply c = ask_page(ctx, t.web, {{"op", "changes"}, {"watch", before.watch}}, std::chrono::steady_clock::now() + 3s); if (c.state == PageReply::State::Destroyed) - return closed_reply(service); + return closed_reply(runtime); // A page that lost the outline (one past its minute) or failed to compare says nothing. if (c.state != PageReply::State::Answered || !c.value.contains("added") || c.value.contains("error")) return json::object(); @@ -764,8 +765,8 @@ struct DownPress }; // Runs `action` on a page element, waiting up to `timeout` for the page. -WebActed web_act(McpService& service, ToolContext& ctx, const WebTarget& t, const std::string& action, json args, std::chrono::seconds timeout, - const DownPress& down = {}) +WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& t, const std::string& action, json args, + std::chrono::seconds timeout, const DownPress& down = {}) { const auto deadline = std::chrono::steady_clock::now() + timeout; PageBefore before; @@ -774,29 +775,29 @@ WebActed web_act(McpService& service, ToolContext& ctx, const WebTarget& t, cons PageCalls calls; ctx.run_ui([&]() -> json { // A client's down sent after the endpoint closed would leave a press no one releases. - if (down.client && !service.endpoint_open()) + if (down.client && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); wxWebView* web = web_view_of(t.web); if (web == nullptr || !web->IsShownOnScreen()) throw ToolFailure("The page's web view is gone or hidden; call list_widgets again"); - guard_page(service, ctx, web); - if (in_top_dialog(service, web)) - before.modal = service.modals().serial(service.modals().top()); - before.stack = service.modals().stack().size(); + guard_page(runtime, ctx, web); + if (in_top_dialog(runtime, web)) + before.modal = runtime.modals().serial(runtime.modals().top()); + before.stack = runtime.modals().stack().size(); before.url = into_u8(web->GetCurrentURL()); args["scale"] = web->GetContentScaleFactor(); request["args"] = args; calls.start(web, request); // From here on a release sent to the page runs after the down. if (down.id != 0) - service.web_presses().sent(down.id); + runtime.web_presses().sent(down.id); return json(); }); calls.wait(ctx, deadline); WebActed out; PageReply r = calls.reply(0); if (r.state == PageReply::State::Destroyed) { - out.after = closed_reply(service); + out.after = closed_reply(runtime); return out; } check_page_reply(r, timeout, true, ctx); @@ -805,7 +806,7 @@ WebActed web_act(McpService& service, ToolContext& ctx, const WebTarget& t, cons // An element of a plugin configuration frame: its page forwarded the action to the frame. const PageReply p = follow_relays(ctx, {t.web}, {value["relay"]}, deadline).front(); if (p.state == PageReply::State::Destroyed) { - out.after = closed_reply(service); + out.after = closed_reply(runtime); return out; } check_page_reply(p, timeout, true, ctx); @@ -819,8 +820,8 @@ WebActed web_act(McpService& service, ToolContext& ctx, const WebTarget& t, cons } } out.reply = value; - out.locator = web_locator(service, ctx, t, value, std::min(timeout, std::chrono::seconds(3))); - out.after = observe_page(service, ctx, t, before, value); + out.locator = web_locator(runtime, ctx, t, value, std::min(timeout, std::chrono::seconds(3))); + out.after = observe_page(runtime, ctx, t, before, value); return out; } @@ -865,9 +866,9 @@ PressAgent agent_of(const WebTarget& t) { return press_agent(t.web, t.doc, t.key // deadline and not run. A gone web view or frame holds nothing. The releases get one second, so a // call waits on them for less than the soft budget and still names the dialog it works in (which its // target's lookup does next) before an open dialog would read as what the call waits on. -void end_web_press(McpService& service, ToolContext& ctx, const std::optional<PressAgent>& keep = std::nullopt) +void end_web_press(AutomationRuntime& runtime, ToolContext& ctx, const std::optional<PressAgent>& keep = std::nullopt) { - WebPresses& presses = service.web_presses(); + WebPresses& presses = runtime.web_presses(); const std::vector<WebPresses::Press> held = presses.releasable(keep); if (held.empty()) return; @@ -899,19 +900,19 @@ void end_web_press(McpService& service, ToolContext& ctx, const std::optional<Pr presses.drop(held[i].id); } -ToolResult web_click(McpService& service, ToolContext& ctx, const json& args) +ToolResult web_click(AutomationRuntime& runtime, ToolContext& ctx, const json& args) { if (args.contains("popup_item")) throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after " "the click"); const auto timeout = web_timeout(args); - WebTarget t = resolve_web(service, ctx, args["target"], timeout); + WebTarget t = resolve_web(runtime, ctx, args["target"], timeout); json a{{"button", arg_string(args, "button", "left")}, {"double", arg_bool(args, "double", false)}, {"modifiers", web_modifiers(args)}}; if (args.contains("x") || args.contains("y")) { a["x"] = arg_int(args, "x", 0); a["y"] = arg_int(args, "y", 0); } - WebActed acted = web_act(service, ctx, t, "click", a, timeout); + WebActed acted = web_act(runtime, ctx, t, "click", a, timeout); journal_web(ctx, args, acted.locator); // A text line is clicked through its block, whose own kind and name the page replies with; the // reply names what was listed. @@ -923,11 +924,11 @@ ToolResult web_click(McpService& service, ToolContext& ctx, const json& args) return ToolResult::ok(out); } -ToolResult web_input(McpService& service, ToolContext& ctx, const json& args) +ToolResult web_input(AutomationRuntime& runtime, ToolContext& ctx, const json& args) { const auto timeout = web_timeout(args); - WebTarget t = resolve_web(service, ctx, args["target"], timeout); - WebActed acted = web_act(service, ctx, t, "input", {{"value", args["value"]}, {"submit", arg_bool(args, "submit", true)}}, timeout); + WebTarget t = resolve_web(runtime, ctx, args["target"], timeout); + WebActed acted = web_act(runtime, ctx, t, "input", {{"value", args["value"]}, {"submit", arg_bool(args, "submit", true)}}, timeout); journal_web(ctx, args, acted.locator); json out{{"label", acted.reply.value("label", t.label)}}; const json state = acted.reply.value("state", json::object()); @@ -940,7 +941,7 @@ ToolResult web_input(McpService& service, ToolContext& ctx, const json& args) } // Keys for a page: its element `t`, or with a null key the page's focused element. -ToolResult web_keys(McpService& service, ToolContext& ctx, const json& args, WebTarget t) +ToolResult web_keys(AutomationRuntime& runtime, ToolContext& ctx, const json& args, WebTarget t) { if (args.contains("popup_item")) throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after " @@ -952,20 +953,20 @@ ToolResult web_keys(McpService& service, ToolContext& ctx, const json& args, Web a["key"] = key["key"]; a["mods"] = key["mods"]; } - WebActed acted = web_act(service, ctx, t, "key", a, web_timeout(args)); + WebActed acted = web_act(runtime, ctx, t, "key", a, web_timeout(args)); journal_web(ctx, args, acted.locator); json out{{"sent", keys.empty() ? json() : json(keys)}, {"typed", text}, {"to", acted.reply.value("to", std::string("page"))}}; out.update(acted.after); return ToolResult::ok(out); } -ToolResult web_mouse(McpService& service, ToolContext& ctx, const json& args) +ToolResult web_mouse(AutomationRuntime& runtime, ToolContext& ctx, const json& args) { // A move or an up finds its target first, to know whether it belongs to a press held there. const std::string action = arg_string(args, "action", "click"); const bool joins = action == "move" || action == "up"; if (!joins) - end_web_press(service, ctx); + end_web_press(runtime, ctx); if (args.contains("at") || args.contains("canvas")) throw ToolFailure("A page element's gesture takes x/y from its top left, not at or canvas"); if (args.contains("popup_item")) @@ -975,14 +976,14 @@ ToolResult web_mouse(McpService& service, ToolContext& ctx, const json& args) if (joins) { // One whose target can't be found ends the presses held, as any other gesture does. try { - t = resolve_web(service, ctx, args["target"], timeout); + t = resolve_web(runtime, ctx, args["target"], timeout); } catch (...) { - end_web_press(service, ctx); + end_web_press(runtime, ctx); throw; } - end_web_press(service, ctx, agent_of(t)); + end_web_press(runtime, ctx, agent_of(t)); } else - t = resolve_web(service, ctx, args["target"], timeout); + t = resolve_web(runtime, ctx, args["target"], timeout); json a{{"action", action}, {"button", arg_string(args, "button", "left")}, {"double", arg_bool(args, "double", false)}, {"modifiers", web_modifiers(args)}, {"steps", arg_int(args, "steps", 10)}, {"delta", arg_int(args, "delta", 0)}}; @@ -1006,9 +1007,9 @@ ToolResult web_mouse(McpService& service, ToolContext& ctx, const json& args) // ends. An up ends the presses its agent held when it was sent, not one a later down made. One // that failed or timed out ends none: past its deadline the page does not run it, so the press may // still be held, and a release of one that is not only answers. - WebPresses& presses = service.web_presses(); + WebPresses& presses = runtime.web_presses(); const PressAgent agent = agent_of(t); - const std::string owner = service.run_owner(service.jobs().ancestry(ctx.job_id())); + const std::string owner = runtime.run_owner(runtime.jobs().ancestry(ctx.job_id())); const std::uint64_t pressed = action == "down" ? presses.hold(agent, owner) : 0; const std::vector<std::uint64_t> ended = action == "up" ? presses.of(agent) : std::vector<std::uint64_t>(); // The page keeps the press's id, so a release ends that press and no later one. @@ -1016,7 +1017,7 @@ ToolResult web_mouse(McpService& service, ToolContext& ctx, const json& args) a["press"] = pressed; WebActed acted; try { - acted = web_act(service, ctx, t, "mouse", a, timeout, {pressed, owner.empty()}); + acted = web_act(runtime, ctx, t, "mouse", a, timeout, {pressed, owner.empty()}); } catch (...) { // A down refused before it was sent is released as one that was: its release only answers. if (pressed != 0) @@ -1033,13 +1034,13 @@ ToolResult web_mouse(McpService& service, ToolContext& ctx, const json& args) // The page keys without a target go to: the focused web view, or the topmost dialog's only web view // when the focus is on none of the dialog's own widgets. Null when the keys are a widget's. UI thread. -wxWebView* key_page(McpService& service) +wxWebView* key_page(AutomationRuntime& runtime) { - wxWindow* target = service.inspector().key_target(nullptr); + wxWindow* target = runtime.inspector().key_target(nullptr); if (auto* web = dynamic_cast<wxWebView*>(target)) return web; auto* dialog = dynamic_cast<wxDialog*>(target); - if (dialog == nullptr || dialog != service.modals().top()) + if (dialog == nullptr || dialog != runtime.modals().top()) return nullptr; std::vector<wxWebView*> webs; for (wxWebView* w : visible_webviews()) @@ -1053,7 +1054,7 @@ wxWebView* key_page(McpService& service) // The window set_window's target names: the main window, the topmost modal dialog, or the window a ref or // locator is in. Refuses one no tool may size or move. `locator` gets what the journal records for a // ref. UI thread. -wxTopLevelWindow& window_target(McpService& service, const json& target, json& locator) +wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, json& locator) { wxWindow* window = nullptr; if (target == "main") { @@ -1061,20 +1062,20 @@ wxTopLevelWindow& window_target(McpService& service, const json& target, json& l if (window == nullptr) throw ToolFailure("The main window is not up yet"); } else if (target == "dialog") { - window = service.modals().top(); + window = runtime.modals().top(); if (window == nullptr) - throw ToolFailure(no_modal_dialog(service)); + throw ToolFailure(no_modal_dialog(runtime.modals())); } else { UiTarget t; try { - t = service.inspector().resolve(target); + t = runtime.inspector().resolve(target); } catch (const ToolFailure& e) { // A window's ref goes stale once the window is destroyed, and list_windows gives the open ones'. if (!target.is_string()) throw; throw ToolFailure(std::string(e.what()) + ", or list_windows for the open windows", e.details); } - locator = service.inspector().locator_for(t); + locator = runtime.inspector().locator_for(t); window = t.window.get() != nullptr ? wxGetTopLevelParent(t.window.get()) : nullptr; } if (dynamic_cast<wxPopupWindow*>(window) != nullptr) @@ -1108,7 +1109,7 @@ wxTopLevelWindow* live_window(wxTopLevelWindow* window) // waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to // the restore sizes the window again, and wx would size it by the maximized window's decorations. A window // brought back from the minimized state is finished restoring once it is back (finish_restore(), macOS). -ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) +ToolResult set_window(AutomationRuntime& runtime, ToolContext& ctx, const json& args) { const json target = args.value("target", json("main")); json locator; @@ -1140,7 +1141,7 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) raise_window(w); }; ctx.run_ui([&] { - wxTopLevelWindow& w = window_target(service, target, locator); + wxTopLevelWindow& w = window_target(runtime, target, locator); auto* dlg = dynamic_cast<wxDialog*>(&w); main = &w == wxGetApp().mainframe; modal = dlg != nullptr && dlg->IsModal(); @@ -1224,7 +1225,7 @@ ToolResult set_window(McpService& service, ToolContext& ctx, const json& args) if (w == nullptr) throw ToolFailure(closed); // list_windows's own entry, so the two report a window alike. - const json entry = service.inspector().window_entry(*w, modal); + const json entry = runtime.inspector().window_entry(*w, modal); json reply{{"title", entry["title"]}, {"kind", entry["kind"]}, {"ref", entry["ref"]}, {"size", {entry["width"], entry["height"]}}}; if (entry.contains("x")) reply["position"] = {entry["x"], entry["y"]}; @@ -1346,8 +1347,8 @@ void register_ui_tools(CommandCatalog& catalog) object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 100."}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - return ToolResult::ok(page(ctx.run_ui([&] { return service.inspector().windows(); }), args)); + AutomationRuntime& runtime = ctx.runtime(); + return ToolResult::ok(page(ctx.run_ui([&] { return runtime.inspector().windows(); }), args)); })); { @@ -1373,7 +1374,7 @@ void register_ui_tools(CommandCatalog& catalog) "or position.")}, {"raise", prop("boolean", "Bring the window in front of the app's other windows; active in the reply says " "whether it became the active one.")}}), - [](const json& args, ToolContext& ctx) { return set_window(ctx.service(), ctx, args); }); + [](const json& args, ToolContext& ctx) { return set_window(ctx.runtime(), ctx, args); }); def.allowed_during_operation = true; catalog.add(def); } @@ -1412,7 +1413,7 @@ void register_ui_tools(CommandCatalog& catalog) {"max_web_nodes", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5000}, {"description", "Page elements, apart from max_nodes; default 300."}}}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); SnapshotOptions o; o.root = arg_string(args, "target", "all"); o.query = arg_string(args, "query"); @@ -1427,7 +1428,7 @@ void register_ui_tools(CommandCatalog& catalog) for (int i = 0; i < 20; ++i) { const bool busy = ctx.run_ui([&] { std::vector<wxWebView*> later; - const std::vector<wxWebView*> read = service.inspector().snapshot_pages(o, &later); + const std::vector<wxWebView*> read = runtime.inspector().snapshot_pages(o, &later); pages.clear(); behind.clear(); std::transform(read.begin(), read.end(), std::back_inserter(pages), web_handle); @@ -1456,7 +1457,7 @@ void register_ui_tools(CommandCatalog& catalog) for (WebHandle h : behind) if (const wxWebView* web = web_view_of(h)) o.pages[web] = {{"note", "behind a modal dialog"}}; - return service.inspector().snapshot(o); + return runtime.inspector().snapshot(o); }); ToolResult r = ToolResult::ok(); const std::string tree = snap["tree"].get<std::string>(); @@ -1496,11 +1497,11 @@ void register_ui_tools(CommandCatalog& catalog) {"timeout_s", kPageTimeoutSchema}}, {"target"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - end_web_press(service, ctx); // a click ends a press held on a page, even one refused here + AutomationRuntime& runtime = ctx.runtime(); + end_web_press(runtime, ctx); // a click ends a press held on a page, even one refused here if (is_web_target(args["target"])) - return web_click(service, ctx, args); - refuse_web_view(service, ctx, args["target"]); + return web_click(runtime, ctx, args); + refuse_web_view(runtime, ctx, args["target"]); ClickOptions o; o.button = arg_string(args, "button", "left"); o.double_click = arg_bool(args, "double", false); @@ -1511,15 +1512,15 @@ void register_ui_tools(CommandCatalog& catalog) json locator; GLCanvas3D* canvas = nullptr; int gizmo = -1; - InputMenu menu(service, ctx, arg_string(args, "popup_item")); + InputMenu menu(runtime, ctx, arg_string(args, "popup_item")); // A list's rows get their places a frame after they change (on GTK; a dialog's tree rebuilt // by a preset choice), so a row is scrolled to first and given up to 1 s to take its place. bool placed = false; for (int i = 0; i < 20; ++i) { placed = ctx.run_ui([&] { - UiTarget t = service.inspector().resolve(args["target"]); - guard_target(service, target_window(t)); - return json(service.inspector().place_row(t)); + UiTarget t = runtime.inspector().resolve(args["target"]); + guard_target(runtime, target_window(t)); + return json(runtime.inspector().place_row(t)); }) .get<bool>(); if (placed) @@ -1531,16 +1532,16 @@ void register_ui_tools(CommandCatalog& catalog) if (const std::string undrawn = undrawn_window(ctx); !undrawn.empty()) throw ToolFailure("The row can't be scrolled into the list's view: " + undrawn); json out = ctx.run_ui([&] { - UiTarget t = service.inspector().resolve(args["target"]); - locator = service.inspector().locator_for(t); - guard_target(service, target_window(t)); + UiTarget t = runtime.inspector().resolve(args["target"]); + locator = runtime.inspector().locator_for(t); + guard_target(runtime, target_window(t)); canvas = t.canvas; gizmo = t.gizmo; menu.arm(); - json clicked = service.inspector().click(t, o); + json clicked = runtime.inspector().click(t, o); // A 3D view posts a click's work to itself; a plate icon posts its dialogs to the plater. const bool plate_icon = t.kind == UiTarget::Kind::PlateIcon; - GLCanvas3D* view = service.inspector().canvas_of(&t); + GLCanvas3D* view = runtime.inspector().canvas_of(&t); if (plate_icon && o.button == "left") menu.mark(&ui_plater()); else if (view != nullptr) @@ -1596,16 +1597,16 @@ void register_ui_tools(CommandCatalog& catalog) {"timeout_s", kPageTimeoutSchema}}, {"target", "value"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); if (is_web_target(args["target"])) - return web_input(service, ctx, args); - refuse_web_view(service, ctx, args["target"]); + return web_input(runtime, ctx, args); + refuse_web_view(runtime, ctx, args["target"]); json locator; json out = ctx.run_ui([&] { - UiTarget t = service.inspector().resolve(args["target"]); - locator = service.inspector().locator_for(t); - guard_target(service, target_window(t)); - return service.inspector().input(t, args["value"], arg_bool(args, "submit", true)); + UiTarget t = runtime.inspector().resolve(args["target"]); + locator = runtime.inspector().locator_for(t); + guard_target(runtime, target_window(t)); + return runtime.inspector().input(t, args["value"], arg_bool(args, "submit", true)); }); journal_with_locator(ctx, args, locator); settle(ctx); @@ -1628,42 +1629,42 @@ void register_ui_tools(CommandCatalog& catalog) {"popup_item", kPopupItemSchema}, {"timeout_s", kPageTimeoutSchema}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); const std::string keys = arg_string(args, "keys"), text = arg_string(args, "text"); if (keys.empty() && text.empty()) throw ToolFailure("Give keys, text or both"); if (args.contains("target") && is_web_target(args["target"])) - return web_keys(service, ctx, args, resolve_web(service, ctx, args["target"], web_timeout(args))); + return web_keys(runtime, ctx, args, resolve_web(runtime, ctx, args["target"], web_timeout(args))); // Keys for a web view itself, or for none while a page has the focus, go to that page's // focused element. WebTarget page; json view_locator; if (args.contains("target")) - page.web = web_view_target(service, ctx, args["target"], page.within, &view_locator); + page.web = web_view_target(runtime, ctx, args["target"], page.within, &view_locator); else ctx.run_ui([&] { - if (wxWebView* web = key_page(service)) { + if (wxWebView* web = key_page(runtime)) { page.web = web_handle(web); page.within = within_of(web); } return json(); }); if (page.web != 0) { - ToolResult r = web_keys(service, ctx, args, page); + ToolResult r = web_keys(runtime, ctx, args, page); journal_with_locator(ctx, args, view_locator); return r; } json locator; - InputMenu menu(service, ctx, arg_string(args, "popup_item")); + InputMenu menu(runtime, ctx, arg_string(args, "popup_item")); json out = ctx.run_ui([&] { std::optional<UiTarget> t; if (args.contains("target")) { - t = service.inspector().resolve(args["target"]); - locator = service.inspector().locator_for(*t); + t = runtime.inspector().resolve(args["target"]); + locator = runtime.inspector().locator_for(*t); } - guard_target(service, service.inspector().key_target(t ? &*t : nullptr)); + guard_target(runtime, runtime.inspector().key_target(t ? &*t : nullptr)); menu.arm(); - return service.inspector().key(t ? &*t : nullptr, keys, text); + return runtime.inspector().key(t ? &*t : nullptr, keys, text); }); journal_with_locator(ctx, args, locator); out.update(menu.read()); @@ -1726,24 +1727,24 @@ void register_ui_tools(CommandCatalog& catalog) {"description", "A web page's element (its ref or a {web}/{css} locator) to gesture on instead of a 3D canvas."}}}, {"timeout_s", kPageTimeoutSchema}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); if (args.contains("target") && is_web_target(args["target"])) - return web_mouse(service, ctx, args); - end_web_press(service, ctx); // a gesture elsewhere ends a press held on a page, even one refused here + return web_mouse(runtime, ctx, args); + end_web_press(runtime, ctx); // a gesture elsewhere ends a press held on a page, even one refused here if (args.contains("target")) throw ToolFailure("mouse_gesture's target is a web page's element; a 3D canvas is chosen with canvas"); const std::string action = arg_string(args, "action", "click"); if (args.contains("popup_item") && action != "click" && action != "up") throw ToolFailure("popup_item goes with action click or up, which open a right click's menu"); - const std::string owner = service.run_owner(service.jobs().ancestry(ctx.job_id())); - InputMenu menu(service, ctx, arg_string(args, "popup_item")); + const std::string owner = runtime.run_owner(runtime.jobs().ancestry(ctx.job_id())); + InputMenu menu(runtime, ctx, arg_string(args, "popup_item")); json out = ctx.run_ui([&] { // A client's press that runs after the endpoint closed would stay held, with no one left // to release it. - if (owner.empty() && !service.endpoint_open()) + if (owner.empty() && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); // The canvases are in the main window, which takes no input while a dialog is open. - guard_target(service, wxGetApp().mainframe); + guard_target(runtime, wxGetApp().mainframe); try { ui_plater(); // refuses while OrcaSlicer starts or closes const std::string name = arg_string(args, "canvas", "current"); @@ -1760,14 +1761,14 @@ void register_ui_tools(CommandCatalog& catalog) const Transform3d view = camera.get_view_matrix(); const double zoom = camera.get_zoom(); menu.arm(); - json done = service.inspector().mouse(*canvas, args, owner); + json done = runtime.inspector().mouse(*canvas, args, owner); menu.mark(canvas->get_wxglcanvas()); if (canvas != design_canvas() && (!camera.get_view_matrix().isApprox(view) || camera.get_zoom() != zoom)) done["camera_moved"] = true; return done; } catch (...) { // A gesture that fails ends a press held from before it, as any other gesture would. - service.inspector().release_held(nullptr); + runtime.inspector().release_held(nullptr); throw; } }); @@ -1844,15 +1845,15 @@ void register_ui_tools(CommandCatalog& catalog) {"description", "Which dialog; default the topmost."}}}}, {"button"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); - end_web_press(service, ctx); // pressing a button ends a press held on a page, even one refused here + AutomationRuntime& runtime = ctx.runtime(); + end_web_press(runtime, ctx); // pressing a button ends a press held on a page, even one refused here const std::string button = arg_string(args, "button"); const std::string title = args.contains("dialog") ? args["dialog"].value("title", "") : std::string(); // The dialog to answer, found again on the UI thread for each step. auto find_dialog = [&]() -> wxDialog* { - const auto& stack = service.modals().stack(); + const auto& stack = runtime.modals().stack(); if (stack.empty()) - throw ToolFailure(no_modal_dialog(service)); + throw ToolFailure(no_modal_dialog(runtime.modals())); wxDialog* dialog = stack.back(); if (!title.empty()) { auto contains = [&](wxDialog* d) { @@ -1866,7 +1867,7 @@ void register_ui_tools(CommandCatalog& catalog) if (contains(d)) throw ToolFailure("\"" + into_u8(d->GetTitle()) + "\" is under \"" + into_u8(dialog->GetTitle()) + "\"; answer the topmost dialog first"); - throw ToolFailure("No open dialog's title contains \"" + title + "\"", {{"dialogs", service.modals().snapshot()}}); + throw ToolFailure("No open dialog's title contains \"" + title + "\"", {{"dialogs", runtime.modals().snapshot()}}); } } if (is_native_dialog(dialog) && message_box_buttons(dialog).empty()) @@ -1883,7 +1884,7 @@ void register_ui_tools(CommandCatalog& catalog) json out = ctx.run_ui([&]() -> json { wxDialog* dialog = find_dialog(); dialog_title = into_u8(dialog->GetTitle()); - serial = service.modals().serial(dialog); + serial = runtime.modals().serial(dialog); int id = dialog_button_by_label(dialog, button); if (id == wxID_NONE) { if (wxWebView* web = web_view_in(dialog)) { @@ -1910,14 +1911,14 @@ void register_ui_tools(CommandCatalog& catalog) settle(ctx); // A message box closes once its own loop runs again, which a press always makes it do; // that loop may run after the UI thread has served other calls. - auto open = [&] { return ctx.observe_ui([&] { return json(service.modals().is_open(serial)); }).get<bool>(); }; + auto open = [&] { return ctx.observe_ui([&] { return json(runtime.modals().is_open(serial)); }).get<bool>(); }; bool still_open = open(); for (const auto end = std::chrono::steady_clock::now() + 1s; native && still_open && std::chrono::steady_clock::now() < end;) { std::this_thread::sleep_for(20ms); still_open = open(); } if (!still_open) - out.update(closed_reply(service)); + out.update(closed_reply(runtime)); return ToolResult::ok(out); } // A web dialog: its page's button by that label, which may take up to 3 s to show. Every ask @@ -1937,8 +1938,8 @@ void register_ui_tools(CommandCatalog& catalog) wxWebView* web = web_view_of(page.web); if (dialog != web_dialog || web == nullptr) throw ToolFailure("The dialog changed while its page was being asked; call list_widgets again"); - before.modal = service.modals().serial(dialog); - before.stack = service.modals().stack().size(); + before.modal = runtime.modals().serial(dialog); + before.stack = runtime.modals().stack().size(); before.url = into_u8(web->GetCurrentURL()); calls.start(web, request); return json(); @@ -1948,7 +1949,7 @@ void register_ui_tools(CommandCatalog& catalog) if (r.state == PageReply::State::Destroyed) { json gone{{"dialog", dialog_title}, {"button", button}, {"web", true}}; - gone.update(closed_reply(service)); + gone.update(closed_reply(runtime)); return ToolResult::ok(gone); } // A page that can't be asked (busy, or its agent failing) leaves cancel and close to the @@ -1962,7 +1963,7 @@ void register_ui_tools(CommandCatalog& catalog) } if (r.value.contains("pressed") && r.value["pressed"].is_string()) { out = {{"dialog", dialog_title}, {"button", r.value["pressed"]}, {"pressed", true}, {"web", true}}; - out.update(observe_page(service, ctx, page, before, r.value)); + out.update(observe_page(runtime, ctx, page, before, r.value)); return ToolResult::ok(out); } page_buttons = r.value.value("buttons", json::array()); @@ -1988,11 +1989,11 @@ void register_ui_tools(CommandCatalog& catalog) }); settle(ctx); const bool gone = ctx.observe_ui([&]() -> json { - const auto& stack = service.modals().stack(); + const auto& stack = runtime.modals().stack(); return std::find(stack.begin(), stack.end(), web_dialog) == stack.end(); }).get<bool>(); if (gone) - out.update(closed_reply(service)); + out.update(closed_reply(runtime)); return ToolResult::ok(out); })); @@ -2020,17 +2021,17 @@ void register_ui_tools(CommandCatalog& catalog) "Rules, first match wins.")}}, {"rules"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); std::vector<AutoAnswerRule> rules; for (const json& r : args["rules"]) rules.push_back(make_rule(r["match"].get<std::string>(), r["button"].get<std::string>(), r.value("path", std::string()), r.value("overwrite", false))); const std::vector<AutoAnswerRule> registered = rules; - const AutoAnswerSet set = service.set_auto_answer(std::move(rules), service.jobs().ancestry(ctx.job_id())); - json out{{"scope", set.scope}, {"rules", service.modals().rules_json()}}; + const AutoAnswerSet set = runtime.set_auto_answer(std::move(rules), runtime.jobs().ancestry(ctx.job_id())); + json out{{"scope", set.scope}, {"rules", runtime.modals().rules_json()}}; // Paused rules leave the dialog that is open now to the person, as they leave the ones that open later. json answered = set.paused ? json() : ctx.run_ui([&]() -> json { - wxDialog* top = service.modals().top(); + wxDialog* top = runtime.modals().top(); // A message box is pressed as answer_dialog presses it; a picker can't be. const bool native = top != nullptr && is_native_dialog(top); if (top == nullptr || (native && message_box_buttons(top).empty())) @@ -2041,12 +2042,12 @@ void register_ui_tools(CommandCatalog& catalog) // A path rule answers a picker only as it opens. if (rule.path.empty() && rule_matches(rule, info["title"].get<std::string>(), info["message"].get<std::string>(), text)) { // The rule may have been paused (a Run Script work ended) or replaced since it was registered. - if (!service.modals().rule_in_force(set.layer, rule.pattern, rule.button)) + if (!runtime.modals().rule_in_force(set.layer, rule.pattern, rule.button)) return json(); // A web dialog is answered on its page, as ModalTracker::Enter() does. if (info.value("web", false) && native_dialog_button(top, rule.button) == wxID_NONE) { const int standard = standard_dialog_button(rule.button); - start_web_answer(service.modals(), top, set.layer, rule.pattern, rule.button, + start_web_answer(runtime.modals(), top, set.layer, rule.pattern, rule.button, standard == wxID_CANCEL || standard == wxID_CLOSE ? standard : int(wxID_NONE)); return {{"dialog", info["title"]}, {"button", rule.button}, {"web", "answering on its page"}}; } @@ -2058,9 +2059,9 @@ void register_ui_tools(CommandCatalog& catalog) if (const std::optional<DialogPress> refused = refused_press(top, id)) return {{"dialog", info["title"]}, {"button", rule.button}, {*refused == DialogPress::Hidden ? "hidden" : "disabled", true}}; // As before any other press, the presses mouse_gesture downs left on pages end first. - service.modals().before_press(); + runtime.modals().before_press(); if (press_dialog_button(top, id) != DialogPress::Failed) { - service.modals().count_use(set.layer, rule.pattern, rule.button); + runtime.modals().count_use(set.layer, rule.pattern, rule.button); return {{"dialog", info["title"]}, {"button", rule.button}}; } } @@ -2069,7 +2070,7 @@ void register_ui_tools(CommandCatalog& catalog) if (!answered.is_null()) { out["answered_open_dialog"] = std::move(answered); settle(ctx); - out["rules"] = service.modals().rules_json(); + out["rules"] = runtime.modals().rules_json(); } return ToolResult::ok(std::move(out)); }); @@ -2092,11 +2093,11 @@ void register_ui_tools(CommandCatalog& catalog) {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 120}, {"description", "Seconds the code gets (default 10)."}}}}, {"code"}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); const std::string code = arg_string(args, "code"); const auto timeout = std::chrono::seconds(std::clamp(arg_int(args, "timeout_s", 10), 1, 120)); const bool element = args.contains("target") && is_web_target(args["target"]); - WebTarget page = element ? resolve_web(service, ctx, args["target"], timeout) : WebTarget(); + WebTarget page = element ? resolve_web(runtime, ctx, args["target"], timeout) : WebTarget(); const auto deadline = std::chrono::steady_clock::now() + timeout; json request{{"op", "eval"}, {"script", code}, {"expires", page_expiry(deadline)}}; if (element) { @@ -2111,19 +2112,19 @@ void register_ui_tools(CommandCatalog& catalog) if (element) web = web_view_of(page.web); else if (args.contains("target")) { - UiTarget t = service.inspector().resolve(args["target"]); - locator = service.inspector().locator_for(t); + UiTarget t = runtime.inspector().resolve(args["target"]); + locator = runtime.inspector().locator_for(t); web = dynamic_cast<wxWebView*>(target_window(t)); if (web == nullptr) throw ToolFailure("The target is not a web view (list_widgets lists them as kind webview)"); } else - web = default_webview(service); + web = default_webview(runtime); if (web == nullptr) throw ToolFailure("The page's web view is gone; call list_widgets again"); - guard_page(service, ctx, web); + guard_page(runtime, ctx, web); page.web = web_handle(web); - before.modal = in_top_dialog(service, web) ? service.modals().serial(service.modals().top()) : 0; - before.stack = service.modals().stack().size(); + before.modal = in_top_dialog(runtime, web) ? runtime.modals().serial(runtime.modals().top()) : 0; + before.stack = runtime.modals().stack().size(); before.url = into_u8(web->GetCurrentURL()); calls.start(web, request); return json(); @@ -2153,7 +2154,7 @@ void register_ui_tools(CommandCatalog& catalog) json value = json::parse(text, nullptr, false); out["result"] = value.is_discarded() ? json(text) : value; // What followed, the page's new url with navigated, overrides the one from before. - out.update(observe_page(service, ctx, page, before, r.value)); + out.update(observe_page(runtime, ctx, page, before, r.value)); return ToolResult::ok(out); }); // Its script runs with the page's own reach: the device page and Home talk to printers and the cloud. diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/McpToolsView.cpp index 578e38cd0e..25f370d3dc 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsView.cpp @@ -6,13 +6,13 @@ #include "libvgcode/include/Types.hpp" #include "libvgcode/include/Viewer.hpp" #include "McpPaths.hpp" -#include "McpService.hpp" +#include "AutomationRuntime.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" #include "ModalTracker.hpp" #include "ScreenCapture.hpp" #include "UiInspector.hpp" #include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" @@ -436,7 +436,7 @@ void register_view_tools(CommandCatalog& catalog) {"overwrite", prop("boolean", "Replace an existing save_path.")}, {"include_image", prop("boolean", "Return the image itself (default true); false returns only the path.")}}), [](const json& args, ToolContext& ctx) { - McpService& service = ctx.service(); + AutomationRuntime& runtime = ctx.runtime(); const json target_arg = args.value("target", json("main")); const std::string target = target_arg.is_string() ? target_arg.get<std::string>() : std::string(); json locator; @@ -456,8 +456,8 @@ void register_view_tools(CommandCatalog& catalog) if (target != "main" && target != "canvas" && target != "dialog") // Scrolled into view first, and painted before the capture below runs. ctx.run_ui([&] { - UiTarget t = service.inspector().resolve(target_arg); - service.inspector().reveal(t); + UiTarget t = runtime.inspector().resolve(target_arg); + runtime.inspector().reveal(t); return json(); }); // A canvas that comes back blank has not drawn yet; it does within moments. @@ -473,14 +473,14 @@ void register_view_tools(CommandCatalog& catalog) throw ToolFailure("No 3D view is shown; switch to one with set_view tab"); cap = capture_canvas(*canvas, err); } else if (target == "dialog") { - wxDialog* top = service.modals().top(); + wxDialog* top = runtime.modals().top(); if (top == nullptr) - throw ToolFailure(no_modal_dialog(service)); + throw ToolFailure(no_modal_dialog(runtime.modals())); cap = capture_window(*top, err); } else if (target != "main") { // A widget: its top-level window, cropped to the widget unless it is that window. - const UiTarget t = service.inspector().resolve(target_arg); - locator = service.inspector().locator_for(t); + const UiTarget t = runtime.inspector().resolve(target_arg); + locator = runtime.inspector().locator_for(t); // A page element is captured as its web view. wxWindow* w = t.window.get(); if ((t.kind != UiTarget::Kind::Window && t.kind != UiTarget::Kind::WebElement) || w == nullptr) @@ -494,7 +494,7 @@ void register_view_tools(CommandCatalog& catalog) view.locator = {{"class", "webview"}}; if (const std::string within = within_of(w); !within.empty()) view.locator["within"] = within; - locator = service.inspector().locator_for(view); + locator = runtime.inspector().locator_for(view); } if (t.page >= 0) { // A tab: its page, which only the selected tab shows. @@ -505,7 +505,7 @@ void register_view_tools(CommandCatalog& catalog) throw ToolFailure("The tab's page is not shown; click the tab (click) first"); w = book->GetPage(size_t(t.page)); } - if (GLCanvas3D* canvas = service.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { + if (GLCanvas3D* canvas = runtime.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { cap = capture_canvas(*canvas, err); } else { wxWindow* top = wxGetTopLevelParent(w); diff --git a/src/slic3r/GUI/Mcp/McpTypes.hpp b/src/slic3r/GUI/Mcp/McpTypes.hpp deleted file mode 100644 index c04422e656..0000000000 --- a/src/slic3r/GUI/Mcp/McpTypes.hpp +++ /dev/null @@ -1,212 +0,0 @@ -#pragma once - -#include <nlohmann/json.hpp> - -#include <chrono> -#include <cstddef> -#include <cstdint> -#include <functional> -#include <map> -#include <memory> -#include <set> -#include <stdexcept> -#include <string> -#include <utility> -#include <vector> - -namespace Slic3r { namespace GUI { - -// Defined in ActionRegistry.hpp, which brings in wx: a ToolResult only holds one through a shared_ptr, which -// the code that makes one (NativeCommands.cpp) completes. -struct AppActionRunResult; -// Defined in CommandCatalog.hpp, which includes this header. -struct NativeCommand; -class CommandCatalog; - -namespace Mcp { - -class McpService; - -// The name of a top-level window the MCP GUI tools never see: list_widgets and locators skip it, -// run_javascript never picks its web views, keys sent without a target never go to it, window screenshots leave it -// out, and as a modal dialog it is not tracked, so the dialog tools and auto-answer rules never reach -// it. Action Replay carries it, so a replay it runs can't act on it, and so does the window that -// changes the Python scripts setting, so no agent, replay or script can turn it on. -inline constexpr char kHiddenFromAutomation[] = "OrcaHiddenFromMcp"; - -// The name of a text field that holds a secret its dialog shows in plain text, such as a printer's -// access code: a modal dialog's description writes its value as [******] (describe_dialog()). A field -// with password style, or a setting field for a password or key, needs no name. -inline constexpr char kSecretField[] = "OrcaSecretForMcp"; - -// What a tool may do while the app is inside another call's nested event loop or behind a modal -// dialog. Inspect tools only read; Recover tools act on the topmost modal dialog to unblock the -// app; everything else is Mutate and is refused in both situations. -enum class GuardClass { Inspect, Recover, Mutate }; - -// A tool's outcome in protocol-neutral form. `data` is the JSON the model receives as text (and a -// script evaluates `expect` against); `content` carries extra MCP content blocks such as images. -struct ToolResult -{ - nlohmann::json data = nlohmann::json::object(); - std::vector<nlohmann::json> content; - bool is_error = false; - std::string message; - // What a person's pick of the command shows, in the UI's language (NativeCommands::notify_result()); - // null for a result that shows nothing. - std::shared_ptr<const AppActionRunResult> notice; - - static ToolResult ok(nlohmann::json data = nlohmann::json::object()) - { - ToolResult r; - r.data = std::move(data); - return r; - } - static ToolResult error(std::string message, nlohmann::json details = nlohmann::json()) - { - ToolResult r; - r.is_error = true; - r.message = std::move(message); - r.data = std::move(details); - return r; - } -}; - -// Thrown by handlers (or by ToolContext on their behalf) to end a call with an isError result. -struct ToolFailure : std::runtime_error -{ - nlohmann::json details; - explicit ToolFailure(const std::string& message, nlohmann::json details = nlohmann::json()) - : std::runtime_error(message), details(std::move(details)) - {} -}; - -// The services a handler gets for one call. A client's call, a replay's and a script's run on a request or -// job thread, never on the UI thread, and everything that touches wx goes through run_ui(); a person's pick -// runs on the UI thread (person()). -class ToolContext -{ -public: - virtual ~ToolContext() = default; - // True for a person's pick from the Speed Dial or a menu: the call is on the UI thread and has no job. - virtual bool person() const { return false; } - // The MCP service the call runs under: what a command that reaches the automation runtime (jobs, the - // journal, recordings, the UI inspector) reads it from, so that the catalog is built without a service. - // Throws when the call has none: std::logic_error here, ToolFailure where one cannot be started. - virtual McpService& service() { throw std::logic_error("This call runs without an MCP service"); } - // Starts command `key` with `args` as a job and returns at once, as the reply to a long command that a - // person picks. Throws ToolFailure where this call cannot start a job. - virtual ToolResult submit(const std::string& key, const nlohmann::json& /*args*/) - { - throw ToolFailure("This call cannot start " + key + " as a job"); - } - // Runs `fn` on the UI thread under the tool's guard class and returns its value. Throws - // ToolFailure when a guard refuses the call, the UI does not pick it up in time, or the app is - // closing. - virtual nlohmann::json run_ui(const std::function<nlohmann::json()>& fn) = 0; - // Runs `fn` on the UI thread under the inspect guard, whatever the tool's class: for watching - // an operation the call has started, which a dialog or another call's nested loop must not stop. - virtual nlohmann::json observe_ui(const std::function<nlohmann::json()>& fn) = 0; - // Id of the job this call runs as; empty for inline (inspect/recover) calls. - virtual const std::string& job_id() const = 0; - // True once the service is stopping, or a stop was asked for this call's job or one of its - // ancestors (a replay or script the user stopped); long-running handlers poll it between steps. - virtual bool cancelled() const = 0; - // Calls another tool as a child of this call (replay steps and a script's calls). Returns what a client would get: - // the result, or a job envelope when the child outlives its reply budget. - virtual ToolResult call_child(const std::string& tool, const nlohmann::json& args) = 0; - // This call's job and its ancestors, which `wait {for:"idle"}` must not wait for. - virtual std::set<std::string> lineage() const = 0; - // Replaces the arguments the session journal records for this call (refs become locators). - virtual void set_journal_args(nlohmann::json args) = 0; - // Marks this job as a slice/export operation: until it finishes, other mutate calls are refused - // so nothing changes the project under it. Call it on the UI thread before starting the work, at - // the latest in the closure that starts it; throws ToolFailure when another operation already runs. - // No-op for inline calls. - virtual void begin_operation() = 0; - // Says the call works in the open modal dialog whose serial is `dialog` (ModalTracker::serial()): - // while that dialog is the topmost, a call outliving its soft budget is still running, not - // blocked on a dialog. The web page paths of the GUI input tools say it once their page is in the - // topmost dialog, since a page can take longer than a widget to answer. Any thread; no-op for - // inline calls. - virtual void works_in_dialog(std::uint64_t /*dialog*/) {} - // The plugin whose code made this call, directly or through a call it made (a step of its script); - // empty for a client's call, a replay, and a person's or an agent's script. - virtual const std::string& caller_plugin() const - { - static const std::string none; - return none; - } -}; - -// For a call of call_tool ({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<const NativeCommand>& command, nlohmann::json& args); - -// Executes a command for the protocol layer: the service implementation adds jobs, budgets, guards -// and the journal; tests call the command's function directly. -class ToolCaller -{ -public: - virtual ~ToolCaller() = default; - virtual ToolResult call(const NativeCommand& command, const nlohmann::json& args) = 0; -}; - -// ---- arguments and name matching (McpArguments.cpp) ------------------------------------------ - -// Validates `args` against the subset of JSON Schema the tool catalog uses (object properties with -// type, enum, minimum/maximum, required, additionalProperties:false, array items, and the -// "if": {"minProperties": 1}, "then": {"required": [...]} of with_silent()). Returns an empty string when -// valid, else a message naming the offending property. -std::string validate_arguments(const nlohmann::json& schema, const nlohmann::json& args); - -// Whether `args` asks for a command's person's form: an object with no members, or null. A command that has -// a person's form and a silent one does the person's then (it asks, as a person's pick does), and the -// silent one when it is given any argument. -bool person_form(const nlohmann::json& args); -// `args` without `silent`, which only chooses the silent form. -nlohmann::json silent_args(nlohmann::json args); -// The schema of a two-form command from its silent form's `schema`: it gains the property `silent`, which -// takes only true and asks for the silent form with its defaults, and a top-level `required` list moves to -// "if": {"minProperties": 1}, "then": {"required": [...]}, since the call with no arguments, the person's -// form, needs none of them. -nlohmann::json with_silent(nlohmann::json schema); - -// Readies a call's arguments for `command`, as every caller of a command does: normalizes `args` in place -// (normalize_arguments()) and returns why validate_arguments() refuses them; empty when they are valid. -std::string argument_error(const NativeCommand& command, nlohmann::json& args); - -// Rewrites, before validation, what agents often send in place of what the schema asks for: an -// argument under a name the tool does not take but that stands for one it does, which the call leaves -// out and the value fits (ref for target, key for keys, text for value, action for id or button, object for objects, -// plate for plates, filter for query, settings for values, path for save_path, index for feature, params or -// values for fields), a value written in -// another JSON form (a number, boolean, array or object as a string, a single item for an array), -// a value outside its argument's enum that only one omitted argument's enum takes (set_view's canvas -// "front" as camera), and the x and y, or width and height, that list_windows reports, both given, as -// the position or size array of a tool that takes that array, of integers, and neither part. Anything -// that still does not fit is left for validate_arguments to report. -void normalize_arguments(const nlohmann::json& schema, nlohmann::json& args); - -// The Levenshtein distance between `a` and `b`: the fewest insertions, deletions and substitutions of one -// character that turn one into the other. A "did you mean" ranks the names a mistyped one may stand for by it, -// each lookup with its own threshold. -std::size_t edit_distance(const std::string& a, const std::string& b); - -// The words of a search query: lower case, split at anything but a letter or a digit. "to" or "of" -// starts a word of most help texts, so words of fewer than three letters are left out when the query -// has longer ones. -std::vector<std::string> query_words(const std::string& query); - -// How well an entry matches the words of query_words(): {words found in `name` or `text`, of them those -// found in `name`}, {0, 0} when none is. A word is found where a word of the text starts with it, so -// "retract" finds "retraction"; the text's words are split at underscores, dots and the like and also -// at a capital in a CamelCase name, so "mesh" finds TriangleMesh. -std::pair<int, int> match_score(const std::vector<std::string>& words, const std::string& name, const std::string& text); - -// The first sentence of `text` on one line, for a listing: up to the first full stop followed by a space -// or the end, "e.g." and "i.e." aside; the whole text when it has none. -std::string first_sentence(const std::string& text); - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 932cc2c60b..7487d3f30c 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -1,9 +1,10 @@ #include "ModalTracker.hpp" #include "McpPaths.hpp" -#include "McpTypes.hpp" +#include "WindowNames.hpp" #include "UiInspector.hpp" #include "WebPages.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Widgets/Button.hpp" diff --git a/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp b/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp index 3588e81b26..5c6a0b0e17 100644 --- a/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp +++ b/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp @@ -1,7 +1,7 @@ #include "PythonScriptsDialog.hpp" #include "McpOptions.hpp" -#include "McpTypes.hpp" +#include "WindowNames.hpp" #include "libslic3r/AppConfig.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -20,6 +20,8 @@ #include <wx/toplevel.h> #include <wx/window.h> +#include <atomic> + namespace Slic3r { namespace GUI { namespace Mcp { namespace { @@ -40,7 +42,7 @@ public: m_about = new Label(this, Label::Body_13, _L("Python scripts are subject to the same permission checks as plugins: the scripts you run in " - "the Run Script panel or with --mcp-run, and the ones AI agents send through the MCP server. " + "the Run Script panel or with --run, and the ones AI agents send through the MCP server. " "When this option is on, they bypass the permission checks, which is useful for fully " "automated workflows.")); m_about->Wrap(FromDIP(kTextWidth)); @@ -48,12 +50,22 @@ public: auto* row = new wxBoxSizer(wxHORIZONTAL); m_allow = new ::CheckBox(this); - m_allow->SetValue(python_scripts_unrestricted(*wxGetApp().app_config)); + m_allow->SetValue(python_scripts_setting(*wxGetApp().app_config)); auto* text = new Label(this, _L("Run Python scripts unrestricted")); row->Add(m_allow, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(6)); row->Add(text, 0, wxALIGN_CENTER_VERTICAL); sizer->Add(row, 0, wxALL, FromDIP(16)); + // The checkbox is the saved setting, which the command line's flag does not change. + if (python_scripts_set_for_run()) { + // TRN Python scripts window. --unrestricted-scripts is a command line option: keep it as it is. + const wxString note = _L("OrcaSlicer was started with --unrestricted-scripts, so scripts run unrestricted until " + "it closes, whatever this setting says."); + m_run_note = new Label(this, Label::Body_13, note); + m_run_note->Wrap(FromDIP(kTextWidth)); + sizer->Add(m_run_note, 0, wxLEFT | wxRIGHT | wxBOTTOM, FromDIP(16)); + } + auto* buttons = new DialogButtons(this, {"OK", "Cancel"}); buttons->GetOK()->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { EndModal(wxID_OK); }); buttons->GetCANCEL()->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { EndModal(wxID_CANCEL); }); @@ -71,18 +83,29 @@ protected: { m_allow->Rescale(); m_about->Wrap(FromDIP(kTextWidth)); + if (m_run_note != nullptr) + m_run_note->Wrap(FromDIP(kTextWidth)); GetSizer()->SetSizeHints(this); Refresh(); } private: - Label* m_about = nullptr; - ::CheckBox* m_allow = nullptr; + Label* m_about = nullptr; + Label* m_run_note = nullptr; + ::CheckBox* m_allow = nullptr; }; +std::atomic<bool> g_scripts_unrestricted_for_run{false}; + } // namespace -bool python_scripts_unrestricted(const AppConfig& config) { return config.get_bool(kPythonUnrestrictedKey); } +bool python_scripts_setting(const AppConfig& config) { return config.get_bool(kPythonUnrestrictedKey); } + +bool python_scripts_unrestricted(const AppConfig& config) { return python_scripts_set_for_run() || python_scripts_setting(config); } + +void set_python_scripts_for_run(bool unrestricted) { g_scripts_unrestricted_for_run = unrestricted; } + +bool python_scripts_set_for_run() { return g_scripts_unrestricted_for_run; } void apply_python_scripts_setting(const AppConfig& config) { @@ -96,7 +119,7 @@ bool show_python_scripts_dialog(wxWindow* parent) return false; AppConfig& config = *wxGetApp().app_config; const bool allow = dialog.allow(); - if (allow == python_scripts_unrestricted(config)) + if (allow == python_scripts_setting(config)) return false; config.set_bool(kPythonUnrestrictedKey, allow); apply_python_scripts_setting(config); diff --git a/src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp b/src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp index 9c98d8ccf3..90995499f6 100644 --- a/src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp +++ b/src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp @@ -8,16 +8,21 @@ class AppConfig; namespace GUI { namespace Mcp { -// Whether the unrestricted Python scripts setting is on in `config`. +// The saved setting. +bool python_scripts_setting(const AppConfig& config); +// The value in force: the setting, or the command line's --unrestricted-scripts for this run. bool python_scripts_unrestricted(const AppConfig& config); +// Called once at startup with the command line's flag. +void set_python_scripts_for_run(bool unrestricted); +bool python_scripts_set_for_run(); -// Passes the setting in `config` on to the plugin audit, which judges a script's accesses by it. Called once -// the app config is loaded, and by the setting's window on a change. +// Passes the value in force on to the plugin audit, which judges a script's accesses by it. Called once the app +// config is loaded, and by the setting's window on a change. void apply_python_scripts_setting(const AppConfig& config); -// Opens the window that lets Python scripts run unrestricted or not, modal on `parent`. The window is hidden -// from automation (kHiddenFromAutomation), so no MCP tool, script or plugin can find, operate or answer it: -// only a person changes the setting. Returns whether it changed. UI thread. +// Opens the window that lets Python scripts run unrestricted or not, modal on `parent`. It shows and writes the +// saved setting. The window is hidden from automation (kHiddenFromAutomation), so no MCP tool, script or plugin +// can find, operate or answer it: only a person changes the setting. Returns whether it changed. UI thread. bool show_python_scripts_dialog(wxWindow* parent); }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/ScreenCapture.cpp b/src/slic3r/GUI/Mcp/ScreenCapture.cpp index 27d6898018..80b465c626 100644 --- a/src/slic3r/GUI/Mcp/ScreenCapture.cpp +++ b/src/slic3r/GUI/Mcp/ScreenCapture.cpp @@ -1,6 +1,6 @@ #include "ScreenCapture.hpp" -#include "McpTypes.hpp" +#include "WindowNames.hpp" #include "UiInspector.hpp" #include "slic3r/GUI/LinuxDisplayBackend.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index 2963aae48d..86b9b05e46 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -2,15 +2,15 @@ #include "UiInspector.hpp" #include "CanvasTarget.hpp" -#include "McpService.hpp" #include "McpTools.hpp" -#include "McpTypes.hpp" +#include "WindowNames.hpp" #include "ModalTracker.hpp" #include "ScreenCapture.hpp" #include "WindowControl.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/BBLTopbar.hpp" #include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/ExtraRenderers.hpp" #include "slic3r/GUI/GLToolbar.hpp" @@ -486,21 +486,21 @@ wxPoint client_pos_in_tlw(wxWindow* w) // Shown top-level windows: the main frame first, then the others (modal dialogs last, in the // order they opened). -std::vector<wxTopLevelWindow*> top_level_windows(McpService& service) +std::vector<wxTopLevelWindow*> top_level_windows(ModalTracker& modals) { std::vector<wxTopLevelWindow*> out; if (wxGetApp().mainframe != nullptr && wxGetApp().mainframe->IsShown()) out.push_back(wxGetApp().mainframe); - const auto& modals = service.modals().stack(); + const auto& stack = modals.stack(); for (wxWindow* w : wxTopLevelWindows) { auto* tlw = dynamic_cast<wxTopLevelWindow*>(w); if (tlw == nullptr || !tlw->IsShown() || tlw == wxGetApp().mainframe || tlw->GetName() == kHiddenFromAutomation) continue; - if (std::find(modals.begin(), modals.end(), tlw) != modals.end()) + if (std::find(stack.begin(), stack.end(), tlw) != stack.end()) continue; out.push_back(tlw); } - for (wxDialog* d : modals) + for (wxDialog* d : stack) if (d->IsShown()) out.push_back(d); return out; @@ -636,10 +636,10 @@ bool is_native_control(wxWindow* w) } // namespace -std::string no_modal_dialog(McpService& service) +std::string no_modal_dialog(ModalTracker& modals) { std::string open; - for (wxTopLevelWindow* tlw : top_level_windows(service)) + for (wxTopLevelWindow* tlw : top_level_windows(modals)) if (tlw != wxGetApp().mainframe && dynamic_cast<wxDialog*>(tlw) != nullptr) open += (open.empty() ? "\"" : ", \"") + label_of(tlw) + "\""; if (open.empty()) @@ -2023,7 +2023,7 @@ bool UiInspector::push(UiNode node, UiTarget target, std::vector<UiNode>& nodes, std::string UiInspector::add_ref(UiTarget target) { - const uint64_t generation = m_service.ui_generation(); + const uint64_t generation = m_ui_generation(); std::function<bool()> alive; char kind = 'w'; switch (target.kind) { @@ -2526,20 +2526,20 @@ std::vector<wxWindow*> UiInspector::snapshot_roots(const SnapshotOptions& o) roots.push_back(popup); }; if (o.root == "dialog") { - if (wxDialog* d = m_service.modals().top()) + if (wxDialog* d = m_modals.top()) with_popups(d); else - throw ToolFailure(no_modal_dialog(m_service)); + throw ToolFailure(no_modal_dialog(m_modals)); } else if (o.root == "main") { if (wxGetApp().mainframe == nullptr) throw ToolFailure("The main window is not up yet"); with_popups(wxGetApp().mainframe); } else if (o.root == "popup") { - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) for (wxWindow* popup : popups_of(tlw)) roots.push_back(popup); } else if (o.root == "all" || o.root.empty()) { - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) with_popups(tlw); } else { const UiTarget t = resolve(json(o.root)); @@ -2553,7 +2553,7 @@ std::vector<wxWindow*> UiInspector::snapshot_roots(const SnapshotOptions& o) std::vector<wxWebView*> UiInspector::snapshot_pages(const SnapshotOptions& o, std::vector<wxWebView*>* behind) { std::vector<wxWebView*> out; - wxDialog* top = m_service.modals().top(); + wxDialog* top = m_modals.top(); std::function<void(wxWindow*)> visit = [&](wxWindow* w) { if (!w->IsShownOnScreen() || hidden_from_automation(w)) return; @@ -2589,7 +2589,7 @@ std::vector<wxWebView*> UiInspector::web_views(const std::string& within) if (dynamic_cast<wxTopLevelWindow*>(child) == nullptr && !skipped_by_walks(child)) visit(child); }; - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) if (within.empty() || label_of(tlw) == within) visit(tlw); return out; @@ -2605,7 +2605,7 @@ json UiInspector::snapshot(const SnapshotOptions& o) json out{{"tree", format_snapshot(nodes, omitted)}, {"nodes", nodes.size()}}; if (omitted > 0) out["omitted"] = omitted; - json dialogs = m_service.modals().snapshot(); + json dialogs = m_modals.snapshot(); if (!dialogs.empty()) out["dialogs"] = std::move(dialogs); return out; @@ -2667,7 +2667,7 @@ json UiInspector::window_entry(wxTopLevelWindow& tlw, bool modal) json UiInspector::windows() { - const std::vector<wxDialog*>& modals = m_service.modals().stack(); + const std::vector<wxDialog*>& modals = m_modals.stack(); json out = json::array(); if (wxGetApp().mainframe != nullptr && wxGetApp().mainframe->IsShown()) out.push_back(window_entry(*wxGetApp().mainframe, false)); @@ -2692,7 +2692,7 @@ UiTarget UiInspector::resolve(const json& target) { if (target.is_string()) { std::string err; - const UiTarget* t = m_refs.resolve(target.get<std::string>(), m_service.ui_generation(), err); + const UiTarget* t = m_refs.resolve(target.get<std::string>(), m_ui_generation(), err); if (t == nullptr) throw ToolFailure(err); UiTarget out = *t; @@ -2888,7 +2888,7 @@ std::vector<wxWindow*> UiInspector::match_windows(const json& locator) if (dynamic_cast<wxTopLevelWindow*>(child) == nullptr && !skipped_by_walks(child)) visit(child); }; - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) if (within.empty() || label_of(tlw) == within) visit(tlw); if (matches.size() > 1 && !locator.contains("class")) { @@ -2938,7 +2938,7 @@ std::vector<std::pair<wxWindow*, ListRow>> UiInspector::match_rows(const json& l { const std::string within = locator.value("within", ""); std::vector<wxWindow*> roots; - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) if (within.empty() || label_of(tlw) == within) roots.push_back(tlw); const json& row = locator["row"]; @@ -2961,7 +2961,7 @@ std::vector<std::pair<wxBookCtrlBase*, int>> UiInspector::match_tabs(const json& if (dynamic_cast<wxTopLevelWindow*>(child) == nullptr && !skipped_by_walks(child)) visit(child); }; - for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxTopLevelWindow* tlw : top_level_windows(m_modals)) if (within.empty() || label_of(tlw) == within) visit(tlw); return out; @@ -3514,7 +3514,7 @@ wxWindow* UiInspector::key_target(const UiTarget* t) const // Focus left in a window the tools don't see (the Action Replay window) is no target for keys. if (focus != nullptr && hidden_from_automation(focus)) focus = nullptr; - if (wxDialog* top = m_service.modals().top()) + if (wxDialog* top = m_modals.top()) return focus != nullptr && owning_window(focus) == top ? focus : top; if (focus != nullptr) return focus; diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index 116d98cc5e..9b1e85570d 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -14,6 +14,7 @@ #include <chrono> #include <cstddef> +#include <cstdint> #include <deque> #include <functional> #include <limits> @@ -44,7 +45,7 @@ class GLToolbarItem; namespace Mcp { -class McpService; +class ModalTracker; // What a ref or locator points at. struct UiTarget @@ -129,7 +130,9 @@ struct ClickOptions class UiInspector { public: - explicit UiInspector(McpService& service) : m_service(service) {} + UiInspector(ModalTracker& modals, std::function<uint64_t()> ui_generation) + : m_modals(modals), m_ui_generation(std::move(ui_generation)) + {} ~UiInspector() { capture_menus(false); } UiInspector(const UiInspector&) = delete; UiInspector& operator=(const UiInspector&) = delete; @@ -241,7 +244,9 @@ private: std::string owner; }; - McpService& m_service; + ModalTracker& m_modals; + // The UI generation refs carry, so that a ref into a rebuilt main window reads stale. + std::function<uint64_t()> m_ui_generation; RefTable<UiTarget> m_refs; std::optional<HeldGesture> m_held; @@ -294,7 +299,7 @@ bool hidden_from_automation(const wxWindow* w); bool skipped_by_walks(const wxWindow* w); // "No modal dialog is open", naming the shown windows that don't block (the Plugins dialog) and how // to reach them, since an agent sees them as dialogs too. UI thread only. -std::string no_modal_dialog(McpService& service); +std::string no_modal_dialog(ModalTracker& modals); // What a locator's `within` names `w`'s window by: its top-level window's title, empty for the main // window, whose title follows the project name. std::string within_of(wxWindow* w); diff --git a/src/slic3r/GUI/Mcp/UiInvoker.cpp b/src/slic3r/GUI/Mcp/UiInvoker.cpp index a14212ab9e..fe51baec74 100644 --- a/src/slic3r/GUI/Mcp/UiInvoker.cpp +++ b/src/slic3r/GUI/Mcp/UiInvoker.cpp @@ -1,4 +1,4 @@ -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "UiInvoker.hpp" #include <algorithm> diff --git a/src/slic3r/GUI/Mcp/UiInvoker.hpp b/src/slic3r/GUI/Mcp/UiInvoker.hpp index 33dd582080..2f2d07652d 100644 --- a/src/slic3r/GUI/Mcp/UiInvoker.hpp +++ b/src/slic3r/GUI/Mcp/UiInvoker.hpp @@ -1,6 +1,6 @@ #pragma once -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <nlohmann/json.hpp> diff --git a/src/slic3r/GUI/Mcp/UiRefs.cpp b/src/slic3r/GUI/Mcp/UiRefs.cpp index 82729ba1c7..4ea4c7739c 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.cpp +++ b/src/slic3r/GUI/Mcp/UiRefs.cpp @@ -1,6 +1,6 @@ #include "UiRefs.hpp" -#include "McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include <nlohmann/json.hpp> diff --git a/src/slic3r/GUI/Mcp/VideoOverlay.cpp b/src/slic3r/GUI/Mcp/VideoOverlay.cpp index 765cce0ab2..eb063e1338 100644 --- a/src/slic3r/GUI/Mcp/VideoOverlay.cpp +++ b/src/slic3r/GUI/Mcp/VideoOverlay.cpp @@ -2,6 +2,8 @@ #include "McpReplaySummary.hpp" +#include "slic3r/GUI/NativeCommands.hpp" + #include <algorithm> #include <array> #include <cctype> @@ -672,7 +674,7 @@ std::string caption_detail(const std::string& tool, const json& args) pairs.push_back(key + " = " + (is_sensitive_key(key) ? std::string("\xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2") : scalar_text(value))); return join(pairs); } - const json what = describe_call(tool, args); + const json what = describe_call(NativeCommands::instance(), tool, args); if (!what.is_object()) return {}; const std::string kind = str(what, "kind"); diff --git a/src/slic3r/GUI/Mcp/WebPages.cpp b/src/slic3r/GUI/Mcp/WebPages.cpp index 3329eb61b4..6c7411bfab 100644 --- a/src/slic3r/GUI/Mcp/WebPages.cpp +++ b/src/slic3r/GUI/Mcp/WebPages.cpp @@ -1,9 +1,9 @@ #include "WebPages.hpp" -#include "McpTypes.hpp" #include "ModalTracker.hpp" #include "UiInspector.hpp" #include "UiRefs.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/KeyChord.hpp" #include "slic3r/GUI/Widgets/WebView.hpp" @@ -31,6 +31,7 @@ #include <chrono> #include <cmath> #include <condition_variable> +#include <cstddef> #include <cstdint> #include <cstdio> #include <functional> diff --git a/src/slic3r/GUI/Mcp/WebPages.hpp b/src/slic3r/GUI/Mcp/WebPages.hpp index 90d1d80fe9..f3127bec12 100644 --- a/src/slic3r/GUI/Mcp/WebPages.hpp +++ b/src/slic3r/GUI/Mcp/WebPages.hpp @@ -19,10 +19,13 @@ class wxDialog; class wxWebView; class wxWindow; -namespace Slic3r { namespace GUI { namespace Mcp { +namespace Slic3r { namespace GUI { + +class ToolContext; + +namespace Mcp { class ModalTracker; -class ToolContext; // Web pages as the GUI tools see them. Every wxWebView of OrcaSlicer - its dialogs and tabs, sign-in // pages, plugin dialogs, windows, pages and dock panels - is read and driven through the page agent @@ -181,7 +184,7 @@ private: }; // Asks the agents of the presses `owner` made (every one when null) to release them, without -// waiting, where no call is there to wait: as a run ends, the endpoint closes, the service stops +// waiting, where no call is there to wait: as a run ends, the endpoint closes, the runtime stops // or an auto-answer rule presses a button. Each release names its press, which the page ends only if // it still holds it, so it carries no deadline: a page busy now releases once free. A press its page // confirms is dropped. A frame's release, which its page forwards, reaches the frame before any diff --git a/src/slic3r/GUI/Mcp/WindowNames.hpp b/src/slic3r/GUI/Mcp/WindowNames.hpp new file mode 100644 index 0000000000..f8fa7335be --- /dev/null +++ b/src/slic3r/GUI/Mcp/WindowNames.hpp @@ -0,0 +1,18 @@ +#pragma once + +// The window names the MCP tools read. A header of their own, so that a window that sets one includes nothing more. +namespace Slic3r { namespace GUI { namespace Mcp { + +// The name of a top-level window the MCP GUI tools never see: list_widgets and locators skip it, +// run_javascript never picks its web views, keys sent without a target never go to it, window screenshots leave it +// out, and as a modal dialog it is not tracked, so the dialog tools and auto-answer rules never reach +// it. Action Replay carries it, so a replay it runs can't act on it, and so does the window that +// changes the Python scripts setting, so no agent, replay or script can turn it on. +inline constexpr char kHiddenFromAutomation[] = "OrcaHiddenFromMcp"; + +// The name of a text field that holds a secret its dialog shows in plain text, such as a printer's +// access code: a modal dialog's description writes its value as [******] (describe_dialog()). A field +// with password style, or a setting field for a password or key, needs no name. +inline constexpr char kSecretField[] = "OrcaSecretForMcp"; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index 5844b711fa..91f923e498 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -1,8 +1,10 @@ #include "NativeCommands.hpp" +#include "ActionIds.hpp" #include "calib_dlg.hpp" #include "Camera.hpp" #include "CommandCatalog.hpp" +#include "CommandTypes.hpp" #include "CreatePresetsDialog.hpp" #include "DailyTips.hpp" #include "GLCanvas3D.hpp" @@ -35,16 +37,16 @@ #include "SceneBenchmark.hpp" #include "format.hpp" #include "DeviceCore/DevManager.h" +#include "Mcp/McpArguments.hpp" #include "Mcp/McpPaths.hpp" #include "Mcp/McpPersonContext.hpp" #include "Mcp/McpRecorder.hpp" -#include "Mcp/McpService.hpp" +#include "Mcp/AutomationRuntime.hpp" #include "Mcp/McpTools.hpp" #ifdef SLIC3R_CAD #include "CAD/DesignPanel.hpp" #include "Mcp/McpToolsCad.hpp" #endif -#include "Mcp/McpTypes.hpp" #include "Mcp/RecordingSettings.hpp" #include "Mcp/ScreenCapture.hpp" #include "Mcp/UiInvoker.hpp" @@ -200,15 +202,14 @@ AppActionRunResult project_undo_redo(bool redo, bool agent) if (plater != nullptr) redo ? plater->redo() : plater->undo(); if (agent && (plater == nullptr || project_history_items(*plater) == before)) - throw Mcp::ToolFailure(redo ? "Nothing was redone in the project's history (nothing to put back, or a background job is running)" - : "Nothing was undone in the project's history (nothing to take back, or a background job is running)"); + throw ToolFailure(redo ? "Nothing was redone in the project's history (nothing to put back, or a background job is running)" + : "Nothing was undone in the project's history (nothing to take back, or a background job is running)"); return {AppActionRunResult::Level::Success, {}, true, json{{"history", "project"}}.dump()}; } // An automated call of Undo, or Redo, on the history args.history names: "design", the Design tab's, or // "project". Without it the history is the shown tab's, as the Edit menu's Undo and Redo choose it. The reply says -// which history it was and, for the Design tab's, what Mcp::cad_undo_redo() replies. A refusal is thrown as -// Mcp::ToolFailure. +// which history it was and, for the Design tab's, what Mcp::cad_undo_redo() replies. A refusal is thrown as ToolFailure. AppActionRunResult undo_redo(const json& args, bool redo) { std::string history = args.value("history", std::string()); @@ -224,7 +225,7 @@ AppActionRunResult undo_redo(const json& args, bool redo) json reply{{"history", "design"}, {"result", Mcp::cad_undo_redo(redo)}}; return {AppActionRunResult::Level::Success, {}, true, reply.dump()}; #else - throw Mcp::ToolFailure("The CAD feature is off: this build of OrcaSlicer has no Design tab"); + throw ToolFailure("The CAD feature is off: this build of OrcaSlicer has no Design tab"); #endif } return project_undo_redo(redo, /*agent=*/true); @@ -402,31 +403,21 @@ void notify_error(const wxString& text) NotificationManager::NotificationLevel::ErrorNotificationLevel, into_u8(text)); } -// Recordings are the MCP service's: the one a person's pick reaches (Mcp::PersonContext::service()), which with the -// server off is started without its endpoint. nullptr when it cannot start, as while OrcaSlicer closes. -Mcp::McpService* recording_service() -{ - try { - return &Mcp::PersonContext().service(); - } catch (const Mcp::ToolFailure&) { - return nullptr; - } -} - // Encodes the recording at `path` to an MP4 beside it once its file is closed, and tells the person how that -// went. False when it cannot start: OrcaSlicer is closing. +// went. False when it cannot start: OrcaSlicer is closing, or the system cannot start a thread. bool encode_when_closed(const boost::filesystem::path& path, const Mcp::RecordingSettings& settings) { - Mcp::McpService* service = wxGetApp().mcp_service(); - if (service == nullptr || wxGetApp().is_closing()) + Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started(); + if (runtime == nullptr || wxGetApp().is_closing()) return false; - return service->encode_when_closed(Mcp::encode_arguments(settings, Mcp::path_to_utf8(path)), [](const Mcp::ToolResult& r) { + const auto done = [](const ToolResult& r) { if (r.is_error) // TRN %1% is why, in English. notify_error(format_wxstr(_L("The recording was saved, but could not be encoded: %1%"), r.message)); else notify_saved(_L("Recording encoded"), Mcp::path_from_utf8(r.data.value("path", std::string()))); - }); + }; + return runtime->recorder().encode_when_closed(*runtime, Mcp::encode_arguments(settings, Mcp::path_to_utf8(path)), done); } } // namespace @@ -450,12 +441,14 @@ AppActionRunResult NativeCommands::start_person_recording() Mcp::save_recording_settings(config, settings); config.save(); - Mcp::McpService* service = recording_service(); - if (service == nullptr) + // Recordings are the automation runtime's, which with the server off starts without its endpoint. None while + // OrcaSlicer closes. + Mcp::AutomationRuntime* runtime = wxGetApp().automation(); + if (runtime == nullptr) return {}; // The switch is remembered as the person left it; without an ffmpeg this recording is not encoded. settings.encode = settings.encode && has_ffmpeg; - Mcp::McpRecorder& recorder = service->recorder(); + Mcp::McpRecorder& recorder = runtime->recorder(); Mcp::RecordingOptions options; options.quality = settings.quality; options.captions = settings.captions; @@ -490,17 +483,17 @@ AppActionRunResult NativeCommands::start_person_recording() AppActionRunResult NativeCommands::stop_recording_in_app() { - Mcp::McpService* service = wxGetApp().mcp_service(); - const nlohmann::json state = service != nullptr && service->started() ? service->recorder().state() : nlohmann::json(); + Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started(); + const nlohmann::json state = runtime != nullptr ? runtime->recorder().state() : nlohmann::json(); if (state.is_null() || state.value("ending", false)) return AppActionRunResult{AppActionRunResult::Level::Info, _L("No recording is running."), false}; // What the window shows now, even if the timer has not ticked since, before the notification shows. - service->recorder().capture_now(); + runtime->recorder().capture_now(); // The recording may be an agent's, a replay's or a script's; the person stopped it all the same, so they are told // where it went. Before it ends: a person's recording that is to be encoded says so instead, as it ends. const boost::filesystem::path path = Mcp::path_from_utf8(state["path"].get<std::string>()); notify_saved(_L("Recording saved"), path); - service->recorder().end(kStoppedInApp); + runtime->recorder().end(kStoppedInApp); return AppActionRunResult{AppActionRunResult::Level::Success, {}, true, path_reply(path)}; } @@ -887,7 +880,7 @@ void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unus const CommandFn picked = ui_command(command.key, command.title, command.group, command.input_schema, [redo](const json& args) { return picked_undo_redo(args, redo); }) .run; - command.run = [picked, automated = std::move(command.run)](const json& args, Mcp::ToolContext& ctx) { + command.run = [picked, automated = std::move(command.run)](const json& args, ToolContext& ctx) { return ctx.person() ? picked(args, ctx) : automated(args, ctx); }; }; @@ -1840,10 +1833,10 @@ NativeCommand NativeCommands::ui_command(std::string key, std::string title, std c.group = std::move(group); c.input_schema = std::move(schema); c.completion = completion; - c.run = [key = c.key, fn = std::move(fn), completion](const json& args, Mcp::ToolContext& ctx) { + c.run = [key = c.key, fn = std::move(fn), completion](const json& args, ToolContext& ctx) { if (ctx.person()) { AppActionRunResult shown = fn(args); - Mcp::ToolResult reply = from_run_result(key, shown); + ToolResult reply = from_run_result(key, shown); reply.notice = std::make_shared<const AppActionRunResult>(std::move(shown)); return reply; } @@ -1867,7 +1860,7 @@ NativeCommand NativeCommands::ui_command(std::string key, std::string title, std } return json(); }); - Mcp::ToolResult reply = from_run_result(key, result); + ToolResult reply = from_run_result(key, result); if (!exports) { Mcp::settle(ctx); return reply; @@ -1875,7 +1868,7 @@ NativeCommand NativeCommands::ui_command(std::string key, std::string title, std if (reply.is_error) return reply; if (ticket.seq_after == ticket.seq_before) - return Mcp::ToolResult::error(result.message.empty() ? "The export did not start." : into_u8(result.message)); + return ToolResult::error(result.message.empty() ? "The export did not start." : into_u8(result.message)); return Mcp::await_gcode_export(ctx, ticket); }; return c; @@ -1889,7 +1882,7 @@ NativeCommand NativeCommands::long_command(std::string key, std::string title, s c.group = std::move(group); c.input_schema = std::move(schema); c.inline_call = inline_call; - c.run = [key = c.key, fn = std::move(fn), inline_call](const json& args, Mcp::ToolContext& ctx) { + c.run = [key = c.key, fn = std::move(fn), inline_call](const json& args, ToolContext& ctx) { // A person's pick is on the UI thread, which a long function must not hold. if (ctx.person() && !inline_call) return ctx.submit(key, args); @@ -1904,13 +1897,13 @@ NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::string t // The person's form runs as a ui_command() function does: in place for a person's pick, in one UI closure // for an automated call, whose reply then says what the pick showed. const CommandFn asks = ui_command(tool.key, title, group, Mcp::object_schema({}), [person](const json&) { return person(); }).run; - const bool checked = !person_form_behind_dialogs && tool.guard != Mcp::GuardClass::Mutate; + const bool checked = !person_form_behind_dialogs && tool.guard != GuardClass::Mutate; tool.title = std::move(title); tool.group = std::move(group); tool.icon = std::move(icon); tool.in_palette = true; tool.input_schema = Mcp::with_silent(std::move(tool.input_schema)); - tool.run = [key = tool.key, person = std::move(person), asks, checked, silent = std::move(tool.run)](const json& args, Mcp::ToolContext& ctx) { + tool.run = [key = tool.key, person = std::move(person), asks, checked, silent = std::move(tool.run)](const json& args, ToolContext& ctx) { if (!Mcp::person_form(args)) return silent(args, ctx); if (!checked || ctx.person()) @@ -1918,7 +1911,7 @@ NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::string t // An agent's call of a tool whose guard lets it run behind dialogs: the person's form opens what a pick // opens, so it is refused while a modal dialog is open or another call's nested loop runs, in the UI // closure that runs it. - Mcp::UiInvoker& ui = ctx.service().ui(); + Mcp::UiInvoker& ui = ctx.runtime().ui(); return ui_command(key, {}, {}, Mcp::object_schema({}), [&person, &ui](const json&) { ui.require_mutate(); return person(); @@ -1927,7 +1920,7 @@ NativeCommand NativeCommands::with_person_form(NativeCommand tool, std::string t return tool; } -Mcp::ToolResult NativeCommands::from_run_result(const std::string& key, const AppActionRunResult& result) +ToolResult NativeCommands::from_run_result(const std::string& key, const AppActionRunResult& result) { // An operation's refusal is worded once, in English here as in a tool's reply. const std::string message = result.refusal ? result.refusal->english() : into_u8(result.message); @@ -1940,7 +1933,7 @@ Mcp::ToolResult NativeCommands::from_run_result(const std::string& key, const Ap if (!result.refusal->names.empty()) details["names"] = result.refusal->names; } - return Mcp::ToolResult::error(message.empty() ? "The action failed" : message, std::move(details)); + return ToolResult::error(message.empty() ? "The action failed" : message, std::move(details)); } json out{{"ran", key}, {"level", level_name(result.level)}}; if (!message.empty()) @@ -1948,7 +1941,7 @@ Mcp::ToolResult NativeCommands::from_run_result(const std::string& key, const Ap if (!result.reply.empty()) if (json reply = json::parse(result.reply, nullptr, /*allow_exceptions=*/false); reply.is_object()) out.update(reply); - return Mcp::ToolResult::ok(std::move(out)); + return ToolResult::ok(std::move(out)); } AppActionRunResult NativeCommands::run(const std::string& key, const json& args) @@ -1964,7 +1957,7 @@ AppActionRunResult NativeCommands::run(const std::string& key, const json& args) return failed(err); Mcp::PersonContext person; try { - const Mcp::ToolResult reply = command->run(checked, person); + const ToolResult reply = command->run(checked, person); if (reply.notice) return *reply.notice; if (reply.is_error) @@ -1988,8 +1981,8 @@ void NativeCommands::notify_result(const AppActionRunResult& result) bool NativeCommands::recording_active() { - Mcp::McpService* service = wxGetApp().mcp_service(); - return service != nullptr && service->started() && service->recorder().active(); + Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started(); + return runtime != nullptr && runtime->recorder().active(); } }} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/NativeCommands.hpp b/src/slic3r/GUI/NativeCommands.hpp index 1025d8c195..33cf8399f8 100644 --- a/src/slic3r/GUI/NativeCommands.hpp +++ b/src/slic3r/GUI/NativeCommands.hpp @@ -2,7 +2,7 @@ #include "ActionRegistry.hpp" // for AppAction / AppActionRunResult #include "CommandCatalog.hpp" -#include "Mcp/McpTypes.hpp" +#include "CommandTypes.hpp" #include <nlohmann/json.hpp> #include <wx/string.h> @@ -84,7 +84,7 @@ AppActionRunResult stop_recording_in_app(); // What a command's result replies to an automated call: {"ran": key, "level", "message"?} with the fields // of its `reply`. It is an error for a Busy or Error level and for a command that did nothing; an operation's // refusal is worded in English, with {"code", "names"?} as the error's details. -Mcp::ToolResult from_run_result(const std::string& key, const AppActionRunResult& result); +ToolResult from_run_result(const std::string& key, const AppActionRunResult& result); // Runs command `key` as a person's pick: checks `args` (Mcp::argument_error()), then runs the command with a // Mcp::PersonContext. Returns what the pick shows, the reply's notice, or an Error holding the message when diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index d8deb84f80..5b18743cd4 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -50,14 +50,14 @@ #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/Mcp/McpOptions.hpp" #include "slic3r/GUI/Mcp/McpPaths.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" #include "slic3r/GUI/Mcp/McpSetup.hpp" #include "slic3r/GUI/Mcp/McpToken.hpp" #include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" -#include <exception> #include <wx/clipbrd.h> #include <wx/sizer.h> #include <wx/stdpaths.h> +#include <wx/window.h> #include <wx/timer.h> #include <wx/unichar.h> #include <wx/chartype.h> @@ -1402,26 +1402,20 @@ static constexpr int MCP_HINT_WIDTH = 270; // The setup row's Copy button, in DIP: ButtonType::Parameter's height, narrower to leave the picker room. static const wxSize MCP_COPY_BUTTON_SIZE(100, 26); -// The running server's port, otherwise the one turning it on here opens, which McpService::start() -// reads the same way: --mcp-port until a port is set in Preferences, then the saved one. -static int mcp_port(const Mcp::McpService *mcp, AppConfig *config) +// The running server's port, otherwise the one turning it on here opens (GUI_App::open_mcp_endpoint()): +// --mcp-port until a port is set in Preferences, then the saved one. +static int mcp_port(const Mcp::McpEndpoint *endpoint, AppConfig *config) { - if (mcp != nullptr && mcp->serving()) - return mcp->port(); + if (endpoint != nullptr && endpoint->serving()) + return endpoint->port(); const GUI_InitParams *params = wxGetApp().init_params; - int port = params != nullptr ? params->mcp.port : 0; - if (port <= 0) { - try { - port = std::stoi(config->get("mcp_port")); - } catch (const std::exception &) {} - } - return port > 0 && port <= 65535 ? port : Mcp::kDefaultPort; + return Mcp::endpoint_port(params != nullptr ? params->mcp.port : 0, config->get("mcp_port")); } // Where agents connect over HTTP. -static std::string mcp_url(const Mcp::McpService *mcp, AppConfig *config) +static std::string mcp_url(const Mcp::McpEndpoint *endpoint, AppConfig *config) { - return "http://127.0.0.1:" + std::to_string(mcp_port(mcp, config)) + "/mcp"; + return "http://127.0.0.1:" + std::to_string(mcp_port(endpoint, config)) + "/mcp"; } // The program a stdio setup runs. Inside an AppImage the executable path is a temporary mount. @@ -1466,9 +1460,9 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_server(wxString title, wxString t wxBoxSizer *m_sizer = create_item_label(title, tooltip); // Checked while the server runs, also when --mcp started it for this session only. - const Mcp::McpService *mcp = wxGetApp().mcp_service(); + const Mcp::McpEndpoint *endpoint = wxGetApp().mcp_endpoint(); auto checkbox = new ::CheckBox(m_parent); - checkbox->SetValue(app_config->get_bool("mcp_enabled") || (mcp != nullptr && mcp->serving())); + checkbox->SetValue(app_config->get_bool("mcp_enabled") || (endpoint != nullptr && endpoint->serving())); checkbox->SetToolTip(tooltip); checkbox->SetName("mcp_enabled"); @@ -1486,9 +1480,9 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_server(wxString title, wxString t app_config->save(); std::string err; if (on) - wxGetApp().start_mcp_service(true, &err); + wxGetApp().open_mcp_endpoint(&err); else - wxGetApp().stop_mcp_endpoint(); + wxGetApp().close_mcp_endpoint(); update_mcp_status(err); }); m_mcp_status_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent &) { update_mcp_status(); }); @@ -1517,13 +1511,13 @@ void PreferencesDialog::update_mcp_status(const std::string ¬e) { if (m_mcp_status == nullptr) return; - const Mcp::McpService *mcp = wxGetApp().mcp_service(); - const bool serving = mcp != nullptr && mcp->serving(); - const bool enabled = app_config->get_bool("mcp_enabled"); - // Another window that shares the configuration folder holds the port, and GUI_App takes it over + const Mcp::McpEndpoint *endpoint = wxGetApp().mcp_endpoint(); + const bool serving = endpoint != nullptr && endpoint->serving(); + const bool enabled = app_config->get_bool("mcp_enabled"); + // Another window that shares the configuration folder holds the port, and the endpoint takes it over // when that window closes. Not a fault, so neither its bind error nor the warning colour shows, // and the timer refreshes the status for the takeover. - const bool held = !serving && mcp != nullptr && mcp->port_held_by_other_window(); + const bool held = !serving && endpoint != nullptr && endpoint->port_held_by_other_window(); const std::string shown_note = held ? std::string() : note; wxString text; if (serving) { @@ -1553,7 +1547,7 @@ void PreferencesDialog::update_mcp_status(const std::string ¬e) m_mcp_status->Wrap(FromDIP(MCP_STATUS_WIDTH)); // While the server is off, the address it will listen on, dimmed. m_mcp_address->SetForegroundColour(serving ? primary : secondary); - m_mcp_address->SetLabel(from_u8(mcp_url(mcp, app_config))); + m_mcp_address->SetLabel(from_u8(mcp_url(endpoint, app_config))); m_mcp_status_dot->Refresh(); m_mcp_status->Refresh(); m_mcp_address->Refresh(); @@ -1569,7 +1563,7 @@ void PreferencesDialog::update_mcp_status(const std::string ¬e) wxBoxSizer *PreferencesDialog::create_item_mcp_port(wxString title, wxString tooltip) { wxBoxSizer *m_sizer = create_item_label(title, tooltip); - auto shown = std::make_shared<long>(mcp_port(wxGetApp().mcp_service(), app_config)); + auto shown = std::make_shared<long>(mcp_port(wxGetApp().mcp_endpoint(), app_config)); auto input = new ::TextInput(m_parent, wxEmptyString, wxEmptyString, wxEmptyString, wxDefaultPosition, DESIGN_INPUT_SIZE, wxTE_PROCESS_ENTER); StateColor input_bg(std::pair<wxColour, int>(wxColour("#F0F0F1"), StateColor::Disabled), @@ -1696,22 +1690,23 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_connect(wxString title, wxString }); copy_button->Bind(wxEVT_BUTTON, [this, picker, confirm = confirm_on_button(copy_button, _L("Copied"))](wxCommandEvent &) { - const Mcp::Agent agent = Mcp::Agent(picker->GetSelection()); - const Mcp::Transport transport = Mcp::Transport(m_mcp_transport->GetSelection()); - const Mcp::McpService *mcp = wxGetApp().mcp_service(); + const Mcp::Agent agent = Mcp::Agent(picker->GetSelection()); + const Mcp::Transport transport = Mcp::Transport(m_mcp_transport->GetSelection()); + const Mcp::McpEndpoint *endpoint = wxGetApp().mcp_endpoint(); // The token the server uses: its own while it runs, otherwise the token file's, which turning it // on reads. A stdio setup holds none: --mcp-stdio reads it from the discovery file. std::string token; if (transport == Mcp::Transport::Http) { std::string err; - token = mcp != nullptr && mcp->serving() ? mcp->token() : Mcp::load_or_create_token(Mcp::path_from_utf8(data_dir()), err); + token = endpoint != nullptr && endpoint->serving() ? endpoint->token() : + Mcp::load_or_create_token(Mcp::path_from_utf8(data_dir()), err); if (token.empty()) { update_mcp_status(err); return; } } if (wxTheClipboard->Open()) { - const std::string setup = Mcp::agent_setup(agent, transport, mcp_url(mcp, app_config), token, mcp_executable()); + const std::string setup = Mcp::agent_setup(agent, transport, mcp_url(endpoint, app_config), token, mcp_executable()); wxTheClipboard->SetData(new wxTextDataObject(from_u8(setup))); wxTheClipboard->Close(); confirm(); @@ -1723,15 +1718,26 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_connect(wxString title, wxString return with_mcp_hint(m_sizer, m_mcp_agent_hint); } +// Added to a row that shows a saved setting which a command line flag turned on for this run. +static wxStaticText *run_override_label(wxWindow *parent) +{ + // TRN Preferences, after a setting that a command line option turned on until OrcaSlicer closes. The row + // shows the saved setting, which the option does not change. + auto label = new wxStaticText(parent, wxID_ANY, _L("(on for this run by the command line)")); + label->SetForegroundColour(DESIGN_GRAY900_COLOR); + label->SetFont(::Label::Body_14); + return label; +} + // The setting itself is changed only in its own window, which automation can't reach: this page is -// reachable by the UI tools, so a switch here could be turned on by an agent. +// reachable by the UI tools, so a switch here could be turned on by an agent. The row shows the saved setting. wxBoxSizer *PreferencesDialog::create_item_mcp_python(wxString title, wxString tooltip) { wxBoxSizer *m_sizer = create_item_label(title, tooltip); auto state = new ::Label(m_parent, wxEmptyString); auto show_state = [this, state] { - state->SetLabel(Mcp::python_scripts_unrestricted(*app_config) ? _L("Unrestricted") : _L("Restricted")); + state->SetLabel(Mcp::python_scripts_setting(*app_config) ? _L("Unrestricted") : _L("Restricted")); }; show_state(); @@ -1745,6 +1751,8 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_python(wxString title, wxString t m_sizer->Add(state, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(10)); m_sizer->Add(button, 0, wxALIGN_CENTER_VERTICAL); + if (Mcp::python_scripts_set_for_run()) + m_sizer->Add(run_override_label(m_parent), 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(10)); return m_sizer; } @@ -2206,6 +2214,9 @@ void PreferencesDialog::create_items() _L("With this option enabled, the Design tab is shown, where models can be built and edited " "parametrically. This feature is experimental and still under development."), "enable_cad_feature", _L("(Requires restart)")); + // The checkbox is the saved preference; --cad turns the feature on for this run without changing it. + if (wxGetApp().cad_feature_set_for_run()) + item_cad_feature->Add(run_override_label(m_parent), 0, wxALIGN_CENTER | wxLEFT, FromDIP(5)); g_sizer->Add(item_cad_feature); #endif diff --git a/src/slic3r/GUI/ReleaseNote.cpp b/src/slic3r/GUI/ReleaseNote.cpp index d8dfa1c049..0ab4ba489e 100644 --- a/src/slic3r/GUI/ReleaseNote.cpp +++ b/src/slic3r/GUI/ReleaseNote.cpp @@ -19,7 +19,7 @@ #include "slic3r/GUI/Widgets/Label.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include <boost/nowide/fstream.hpp> #include "slic3r/GUI/Printer/PrinterFileSystem.h" #include <exception> diff --git a/src/slic3r/GUI/RunScriptPanel.cpp b/src/slic3r/GUI/RunScriptPanel.cpp index 09794e3b4a..3c3ce600f8 100644 --- a/src/slic3r/GUI/RunScriptPanel.cpp +++ b/src/slic3r/GUI/RunScriptPanel.cpp @@ -7,14 +7,16 @@ #include "KeyChord.hpp" #include "MainFrame.hpp" #include "MsgDialog.hpp" +#include "NativeCommands.hpp" #include "Plater.hpp" #include "Shortcuts.hpp" #include "format.hpp" +#include "Mcp/AutomationRuntime.hpp" +#include "Mcp/McpArguments.hpp" #include "Mcp/McpPaths.hpp" #include "Mcp/McpPersonRun.hpp" -#include "Mcp/McpService.hpp" #include "Mcp/McpTools.hpp" -#include "Mcp/McpTypes.hpp" +#include "Mcp/WindowNames.hpp" #include "Widgets/WebView.hpp" #include "Widgets/WebViewHostDialog.hpp" #include "libslic3r/AppConfig.hpp" @@ -72,12 +74,6 @@ constexpr std::size_t kOutputPerTick = 256 * 1024; // A toggle the page asks for this soon after one the main frame dispatched is the same key press, delivered twice. constexpr auto kToggleEcho = std::chrono::milliseconds(150); -Mcp::McpService* service() -{ - Mcp::McpService* s = wxGetApp().mcp_service(); - return s != nullptr && s->started() && !s->stopping() ? s : nullptr; -} - #ifdef __APPLE__ const char* const kEnter = "Return"; #else @@ -347,10 +343,10 @@ RunScriptPanel::RunScriptPanel() : m_alive(std::make_shared<std::atomic<bool>>(t { m_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { tick(); }); m_ready_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); if (s == nullptr || s->ready()) m_ready_timer.Stop(); - send_service_state(); + send_runtime_state(); }); // The pane comes back after a rebuild once the old main window is gone: a WebView2 created while the window it // replaces still exists shows a blank page. recreate_GUI() Destroy()s that window, which wx deletes in its idle pass @@ -371,7 +367,7 @@ RunScriptPanel::~RunScriptPanel() m_alive->store(false); m_timer.Stop(); m_ready_timer.Stop(); - // The service, which hosts the session on a thread of its own, joins that thread as it stops. + // The runtime, which hosts the session on a thread of its own, joins that thread as it stops. if (m_session) { m_session->end(); m_session->stop(); @@ -494,11 +490,12 @@ void RunScriptPanel::handle(const json& payload) const std::string command = payload.value("command", ""); try { if (command == "init") { - // The panel needs the service's tools and jobs, never its network endpoint. - if (wxGetApp().mcp_service() == nullptr) - wxGetApp().start_mcp_service(false); + // The panel needs the runtime's tools and jobs, started here without the network endpoint, and its + // scripts drive the GUI. + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation()) + runtime->enable_gui_instruments(); send(state()); - send_service_state(); + send_runtime_state(); read_api(); } else if (command == "editor_keys") { m_editor_keys.clear(); @@ -566,7 +563,7 @@ void RunScriptPanel::handle(const json& payload) json RunScriptPanel::state() const { - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); json script = script_message(); script.erase("command"); return {{"command", "state"}, @@ -639,15 +636,15 @@ void RunScriptPanel::send_session_state() send({{"command", "session"}, {"state", now}}); } -void RunScriptPanel::send_service_state() +void RunScriptPanel::send_runtime_state() { - Mcp::McpService* s = service(); - const bool ready = s != nullptr && s->ready(); - if (!ready && s != nullptr && !m_ready_timer.IsRunning()) + Mcp::AutomationRuntime* runtime = wxGetApp().automation(); + const bool ready = runtime != nullptr && runtime->ready(); + if (!ready && runtime != nullptr && !m_ready_timer.IsRunning()) m_ready_timer.Start(500); - send({{"command", "service"}, {"ready", ready}}); + send({{"command", "runtime"}, {"ready", ready}}); if (ready) - send({{"command", "catalog"}, {"tools", Mcp::editor_tool_catalog(s->catalog())}}); + send({{"command", "catalog"}, {"tools", Mcp::editor_tool_catalog(NativeCommands::instance())}}); } // The orca.host API's entries, read once per app run on a thread of the panel's, which it joins. @@ -835,7 +832,7 @@ void RunScriptPanel::run(const json& payload) { if (m_running || m_waiting) return; - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); if (s == nullptr || !s->ready()) { refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); return; @@ -881,7 +878,7 @@ void RunScriptPanel::run(const json& payload) bool RunScriptPanel::start_session() { - Mcp::McpService* s = service(); + Mcp::AutomationRuntime* s = wxGetApp().automation(); if (s == nullptr) { refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); return false; @@ -895,7 +892,7 @@ bool RunScriptPanel::start_session() m_running = false; send({{"command", "run_finished"}, {"status", "refused"}, {"message", result.value("error", std::string())}}); }; - m_session_run = s->start_python_session(session, m_file, std::move(events)); + m_session_run = Mcp::start_python_session(*s, session, m_file, std::move(events)); if (!m_session_run) { refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); return false; @@ -997,7 +994,7 @@ void RunScriptPanel::tick() send({{"command", "run_finished"}, {"status", "refused"}, {"message", _u8L("Scripts can't run while OrcaSlicer is starting or closing.")}}); } } else if (m_running) { - // Ended without reporting its work: its job was refused, or the service stopped. + // Ended without reporting its work: its job was refused, or the runtime stopped. m_running = false; send({{"command", "run_finished"}, {"status", "refused"}, {"message", _u8L("Scripts can't run while OrcaSlicer is starting or closing.")}}); } diff --git a/src/slic3r/GUI/RunScriptPanel.hpp b/src/slic3r/GUI/RunScriptPanel.hpp index a731c7aa88..8c3fb5e35a 100644 --- a/src/slic3r/GUI/RunScriptPanel.hpp +++ b/src/slic3r/GUI/RunScriptPanel.hpp @@ -30,10 +30,10 @@ class RunScriptPane; // The Run Script panel: a dock pane under the 3D view (it can float) whose page (resources/web/dialog/RunScript) edits a // Python script in `# %%` cells and runs them, one at a time or the whole file, in a live session (PythonSession) hosted -// by the MCP service as a person's run_script job. One per app, owned by GUI_App: the script's text, file and unsaved -// state, the session and the recent scripts live here, so they survive the pane, which a main-window rebuild (a language -// change) destroys and the panel builds again. The pane and everything in it are hidden from the automation tools. -// UI thread. +// by the automation runtime as a person's run_script job. One per app, owned by GUI_App: the script's text, file and +// unsaved state, the session and the recent scripts live here, so they survive the pane, which a main-window rebuild (a +// language change) destroys and the panel builds again. The pane and everything in it are hidden from the automation +// tools. UI thread. class RunScriptPanel final : public CodeEditorWindow { public: @@ -94,7 +94,7 @@ private: void run(const nlohmann::json& payload); void refuse(const std::string& message); - // Starts a session on the script's file as it is now; false (and refused) when the service can't host one. + // Starts a session on the script's file as it is now; false (and refused) when the runtime can't host one. bool start_session(); // Ends the session and stops what it runs, its teardown included; it is dropped once it has ended. void end_session(); @@ -102,7 +102,7 @@ private: void submit(PythonWork work, const nlohmann::json& started); void tick(); void finish_run(const PythonSessionEvent& done); - void send_service_state(); + void send_runtime_state(); void read_api(); std::shared_ptr<std::atomic<bool>> m_alive; diff --git a/src/slic3r/GUI/SyntheticInput.hpp b/src/slic3r/GUI/SyntheticInput.hpp index 3bec6ccff0..2ae3894948 100644 --- a/src/slic3r/GUI/SyntheticInput.hpp +++ b/src/slic3r/GUI/SyntheticInput.hpp @@ -13,7 +13,7 @@ class wxWindow; namespace Slic3r { namespace GUI { -// Input state that automation (the MCP server) holds down while it synthesizes a gesture. +// Input state that automation holds down while it synthesizes a gesture. // Synthesized wx events carry their own modifier and button flags, but parts of the 3D view also // ask the system for the keyboard and mouse state; those reads go through get_key_state() and // get_mouse_state(), which add whatever automation is holding. Empty unless a synthesized gesture @@ -31,7 +31,7 @@ void clear(); // Popup and context menus that open while automation acts on the UI go to `capture` instead of // being shown: a native menu loop would hold the UI thread until a person closed the menu, and on // macOS it pauses the queued calls automation runs through. `capture` returns false to let a menu -// show. Empty unless the MCP server runs; clear() leaves it. +// show. Empty unless the GUI instruments are on (`enable_gui_instruments()`); clear() leaves it. void set_menu_capture(std::function<bool(wxMenu& menu, wxWindow& owner)> capture); } // namespace SyntheticInput diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index be0570a489..40be71ff66 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -21,7 +21,7 @@ struct PluginPermissions; // reader maps that form onto the boolean permission. inline constexpr const char* kThreadPermissionTarget = "thread"; -// The audit identities of a Python script a person (the Run Script panel, --mcp-run) or an agent +// The audit identities of a Python script a person (the Run Script panel, --run) or an agent // (run_script) starts. A script is judged as a plugin is, but has no install state to hold a grant: what // the implicit rules don't allow is denied without a prompt, unless scripts run unrestricted // (set_scripts_unrestricted). The identities are reserved: no plugin key may equal them, so a plugin is diff --git a/src/slic3r/plugin/PythonScriptRunner.hpp b/src/slic3r/plugin/PythonScriptRunner.hpp index 0c4e1f1d33..43955d8e99 100644 --- a/src/slic3r/plugin/PythonScriptRunner.hpp +++ b/src/slic3r/plugin/PythonScriptRunner.hpp @@ -18,7 +18,7 @@ class PythonRunScope; class PythonSession; // A Python script a person or an agent starts (run_script, a .py in the Run Script dialog or -// --mcp-run), or a plugin's run_script: code run on the plugin interpreter without being packaged +// --run), or a plugin's run_script: code run on the plugin interpreter without being packaged // as a plugin. struct PythonRunRequest { diff --git a/tests/AGENTS.md b/tests/AGENTS.md index e6f3bf864c..3b1f9c2614 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -9,6 +9,7 @@ Rules for writing tests under `tests/`. [CATCH2.md](CATCH2.md) is the Catch2 ref - `sla_print`: SLA support-tree and pad geometry, support-point generation, raycast. - `libnest2d`: 2D nesting and packing. - `slic3rutils`: the Python plugin system and its slicing-pipeline bindings. +- `automation`: the automation core: the command catalog's type, the dispatch core, the MCP protocol and transport, the replay model; no GUI library. - `filament_group`: filament-to-extruder grouping, checked against golden files. - `cli`: end-to-end runs of the built `orca-slicer` binary, Linux only. These tests carry the `RequiresApp` label, which the CI unit-test job excludes because it receives only `build/tests`; run them with `ctest --test-dir build/tests -C Release -L RequiresApp`. @@ -27,6 +28,7 @@ Rebuild a single suite with `cmake --build build --config Release --target <suit - Pick the suite by the production code the test exercises, not by how the test is written. - A property of a class that holds with no `Print` involved belongs in `libslic3r`. Behavior that depends on print settings, or produces or consumes G-code or slicing state, belongs in `fff_print`. - One file per subsystem, named `test_<subsystem>.cpp`. It owns every test for that subsystem, whether the test reads in-memory state or generated output. +- `test_command_catalog.cpp`, `test_mcp_core.cpp` and `test_mcp_protocol.cpp` exist in both `automation` and `slic3rutils`: a case goes to `automation` when it compiles against `libslic3r_automation`'s headers alone, otherwise to the `slic3rutils` file of the same name. - When you add a file, list it in that suite's `CMakeLists.txt` in the same change. ## Use the existing helpers @@ -35,7 +37,7 @@ Check these before writing your own setup or output-parsing code. - `tests/test_utils.hpp` is shared by every suite. `load_model()` loads a mesh from `tests/data/`, and `ScopedTemporaryFile` gives a temp path that removes itself. - `fff_print/test_helpers.hpp` builds and slices a `Print` and parses the emitted G-code. Read it before writing an fff_print test rather than assembling a `Print` by hand. -- The other suites have their own: `sla_print/sla_test_utils.hpp`, `libnest2d/libnest2d_test_utils.hpp`, `slic3rutils/plugin_test_utils.hpp`, `filament_group/fg_test_utils.hpp`. `libslic3r` has none and uses the shared header. +- The other suites have their own: `sla_print/sla_test_utils.hpp`, `libnest2d/libnest2d_test_utils.hpp`, `slic3rutils/plugin_test_utils.hpp`, `automation/automation_test_utils.hpp`, `filament_group/fg_test_utils.hpp`. `libslic3r` has none and uses the shared header. - Test data lives in `tests/data/` and is reached through the `TEST_DATA_DIR` define. Wrap it in `std::string(...)` before joining a path onto it. ## Writing the test diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 21077cd2c1..ea3d9abbb8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,7 @@ endfunction() add_subdirectory(libnest2d) add_subdirectory(libslic3r) +add_subdirectory(automation) add_subdirectory(slic3rutils) add_subdirectory(fff_print) add_subdirectory(sla_print) diff --git a/tests/automation/CMakeLists.txt b/tests/automation/CMakeLists.txt new file mode 100644 index 0000000000..7febaacc77 --- /dev/null +++ b/tests/automation/CMakeLists.txt @@ -0,0 +1,26 @@ +get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME) + +# The automation core's suite. It links libslic3r_automation and nothing of libslic3r_gui, so it builds +# without wxWidgets and the embedded Python, and a core unit that calls into the GUI library fails to +# link here. +add_executable(${_TEST_NAME}_tests + ${_TEST_NAME}_tests.cpp + automation_test_utils.hpp + test_command_catalog.cpp + test_mcp_core.cpp + test_mcp_http.cpp + test_mcp_paths.cpp + test_mcp_protocol.cpp + test_mcp_replay.cpp + test_mcp_replay_summary.cpp + test_mcp_setup.cpp + test_mcp_token.cpp + ) + +target_link_libraries(${_TEST_NAME}_tests test_common libslic3r_automation libslic3r Catch2::Catch2WithMain) + +set_property(TARGET ${_TEST_NAME}_tests PROPERTY FOLDER "tests") + +orcaslicer_copy_test_dlls() + +orcaslicer_discover_tests(${_TEST_NAME}_tests) diff --git a/tests/automation/automation_test_utils.hpp b/tests/automation/automation_test_utils.hpp new file mode 100644 index 0000000000..4aaf67bf85 --- /dev/null +++ b/tests/automation/automation_test_utils.hpp @@ -0,0 +1,199 @@ +#pragma once + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/UiInvoker.hpp" + +#include <nlohmann/json.hpp> + +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <deque> +#include <functional> +#include <memory> +#include <mutex> +#include <set> +#include <string> +#include <thread> +#include <utility> +#include <vector> + +// Fixtures of the automation core's tests. The slic3rutils suite uses them too, for the cases that run the +// core with a type of the GUI library. +namespace Slic3r { namespace GUI { namespace Mcp { namespace Test { + +inline NativeCommand command(std::string key, bool in_palette = false) +{ + NativeCommand c; + c.key = std::move(key); + c.in_palette = in_palette; + return c; +} + +// Holds one command, as a plugin's operations are held while it is loaded. +class OneCommandSource final : public CommandSource +{ +public: + explicit OneCommandSource(std::string key) : m_command(std::make_shared<const NativeCommand>(command(std::move(key)))) {} + + std::shared_ptr<const NativeCommand> find(const std::string& key) const override + { + return key == m_command->key ? m_command : nullptr; + } + std::vector<std::shared_ptr<const NativeCommand>> all() const override { return {m_command}; } + +private: + std::shared_ptr<const NativeCommand> m_command; +}; + +// Runs handlers directly on the calling thread, as if every call were inline. +class DirectCaller final : public ToolCaller +{ +public: + std::vector<std::string> called; // the tools it ran, in order + + ToolResult call(const NativeCommand& def, const nlohmann::json& args) override + { + called.push_back(def.key); + struct Context final : ToolContext + { + std::string id; + nlohmann::json run_ui(const std::function<nlohmann::json()>& fn) override { return fn(); } + nlohmann::json observe_ui(const std::function<nlohmann::json()>& fn) override { return fn(); } + const std::string& job_id() const override { return id; } + bool cancelled() const override { return false; } + ToolResult call_child(const std::string&, const nlohmann::json&) override { return ToolResult::error("no children"); } + std::set<std::string> lineage() const override { return {}; } + void set_journal_args(nlohmann::json) override {} + void begin_operation() override {} + } ctx; + return def.run(args, ctx); + } +}; + +// A UI thread with an event loop. Closures may run a nested loop (loop_until) the way a modal +// dialog does, so other closures keep running while they are on the stack. +class FakeUiThread final : public UiDispatcher +{ +public: + FakeUiThread() : m_thread([this] { loop_until([this] { return m_stop.load(); }); }) {} + ~FakeUiThread() override + { + m_stop = true; + m_cv.notify_all(); + m_thread.join(); + } + + void post(std::function<void()> fn) override + { + { + std::lock_guard<std::mutex> lock(m_mutex); + m_queue.push_back(std::move(fn)); + } + m_cv.notify_all(); + } + + // Runs queued closures until `done` returns true. Call it only on the UI thread. + void loop_until(const std::function<bool()>& done) + { + for (;;) { + std::function<void()> fn; + { + std::unique_lock<std::mutex> lock(m_mutex); + m_cv.wait_for(lock, std::chrono::milliseconds(5), [&] { return !m_queue.empty(); }); + if (m_queue.empty()) { + lock.unlock(); + if (done()) + return; + continue; + } + fn = std::move(m_queue.front()); + m_queue.pop_front(); + } + fn(); + if (done()) + return; + } + } + +private: + std::mutex m_mutex; + std::condition_variable m_cv; + std::deque<std::function<void()>> m_queue; + std::atomic<bool> m_stop{false}; + std::thread m_thread; +}; + +struct Harness +{ + FakeUiThread ui; + std::mutex guards_mutex; + GuardState guards; + // The guards' dialogs double as the snapshot ModalTracker publishes to other threads. + UiInvoker invoker{ui, + [this] { + std::lock_guard<std::mutex> lock(guards_mutex); + return guards; + }, + {}, + [this] { + std::lock_guard<std::mutex> lock(guards_mutex); + return guards.dialogs; + }}; + JobRegistry jobs; + Journal journal; + CommandCatalog registry; + CoreTiming timing = [] { + CoreTiming t; + t.soft_budget = std::chrono::milliseconds(100); + t.probe_timeout = std::chrono::milliseconds(500); + return t; + }(); + std::unique_ptr<McpCore> core; + + void start() { core = std::make_unique<McpCore>(registry, invoker, jobs, &journal, timing); } + + void set_modal(bool modal, nlohmann::json dialogs = nlohmann::json::array()) + { + std::lock_guard<std::mutex> lock(guards_mutex); + guards.modal = modal; + guards.dialogs = std::move(dialogs); + } + + // A modal dialog's nested event loop on the UI thread, open until `release` is set. + void modal_loop(std::atomic<bool>& release, nlohmann::json dialogs = nlohmann::json::array({{{"title", "Dialog"}}})) + { + set_modal(true, std::move(dialogs)); + ui.loop_until([&] { return release.load(); }); + set_modal(false); + } + + // Dialogs that hold the UI thread until `release` is set: they are published, but nothing posted + // meanwhile runs, as when macOS pauses wx's pending events behind a native file picker. + void hold_ui(std::atomic<bool>& release, nlohmann::json dialogs) + { + set_modal(true, std::move(dialogs)); + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + set_modal(false); + } + + ~Harness() + { + invoker.shutdown(); + jobs.wake_all(); + if (core) + core->shutdown(); + } + + ToolResult call(const std::string& tool, const nlohmann::json& args = nlohmann::json::object()) + { + return core->call(*registry.find(tool), args); + } +}; + +}}}} // namespace Slic3r::GUI::Mcp::Test diff --git a/tests/automation/automation_tests.cpp b/tests/automation/automation_tests.cpp new file mode 100644 index 0000000000..3e775fa1bd --- /dev/null +++ b/tests/automation/automation_tests.cpp @@ -0,0 +1 @@ +// The automation suite's main file. Catch2WithMain provides main(). diff --git a/tests/automation/test_command_catalog.cpp b/tests/automation/test_command_catalog.cpp new file mode 100644 index 0000000000..7685240fc5 --- /dev/null +++ b/tests/automation/test_command_catalog.cpp @@ -0,0 +1,175 @@ +#include <catch2/catch_test_macros.hpp> +#include <catch2/matchers/catch_matchers.hpp> +#include <catch2/matchers/catch_matchers_string.hpp> + +#include "automation_test_utils.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" + +#include <nlohmann/json.hpp> + +#include <functional> +#include <memory> +#include <stdexcept> +#include <string> +#include <type_traits> +#include <vector> + +using Catch::Matchers::ContainsSubstring; +using nlohmann::json; +using Slic3r::GUI::CommandCatalog; +using Slic3r::GUI::CommandCompletion; +using Slic3r::GUI::CommandFn; +using Slic3r::GUI::GuardClass; +using Slic3r::GUI::NativeCommand; +using Slic3r::GUI::Mcp::Test::command; +using Slic3r::GUI::Mcp::Test::OneCommandSource; +namespace Mcp = Slic3r::GUI::Mcp; + +namespace { + +std::vector<std::string> keys_of(const std::vector<NativeCommand>& commands) +{ + std::vector<std::string> keys; + for (const NativeCommand& c : commands) + keys.push_back(c.key); + return keys; +} + +} // namespace + +TEST_CASE("a key added twice is refused", "[CommandCatalog]") +{ + CommandCatalog catalog; + catalog.add(command("a")); + CHECK_THROWS_AS(catalog.add(command("a")), std::logic_error); + CHECK(catalog.commands().size() == 1); +} + +TEST_CASE("a sealed catalog refuses additions", "[CommandCatalog]") +{ + CommandCatalog catalog; + catalog.add(command("a")); + CHECK_FALSE(catalog.sealed()); + catalog.seal(); + CHECK(catalog.sealed()); + CHECK_THROWS_AS(catalog.add(command("b")), std::logic_error); + CHECK_THROWS_AS(catalog.add_source(std::make_unique<OneCommandSource>("plugin.x.y")), std::logic_error); + CHECK(catalog.find("b") == nullptr); +} + +TEST_CASE("find sees added commands, lookup also a source's", "[CommandCatalog]") +{ + CommandCatalog catalog; + catalog.add(command("slice")); + catalog.add_source(std::make_unique<OneCommandSource>("plugin.x.y")); + catalog.seal(); + + CHECK(catalog.find("plugin.x.y") == nullptr); + const std::shared_ptr<const NativeCommand> from_source = catalog.lookup("plugin.x.y"); + REQUIRE(from_source != nullptr); + CHECK(from_source->key == "plugin.x.y"); + + const NativeCommand* added = catalog.find("slice"); + REQUIRE(added != nullptr); + CHECK(catalog.lookup("slice").get() == added); + + CHECK(catalog.lookup("plugin.x.z") == nullptr); + REQUIRE(catalog.source_commands().size() == 1); + CHECK(catalog.source_commands().front()->key == "plugin.x.y"); +} + +TEST_CASE("commands keep the order they were added in", "[CommandCatalog]") +{ + CommandCatalog catalog; + for (const char* key : {"c", "a", "b"}) + catalog.add(command(key)); + catalog.seal(); + CHECK(keys_of(catalog.commands()) == std::vector<std::string>{"c", "a", "b"}); +} + +TEST_CASE("a Design command's title is translated in the Design context, any other's in none", "[CommandCatalog]") +{ + NativeCommand design; + design.key = "shell"; + design.title = "Shell"; + design.group = Slic3r::GUI::kDesignGroup; + REQUIRE(Slic3r::GUI::title_context(design) != nullptr); + CHECK(std::string(Slic3r::GUI::title_context(design)) == "Design"); + NativeCommand other; + other.key = "save_project"; + other.title = "Save project"; + other.group = "Commands"; + CHECK(Slic3r::GUI::title_context(other) == nullptr); +} + +TEST_CASE("a command's function is typed in the catalog's own namespace", "[CommandCatalog]") +{ + STATIC_REQUIRE(std::is_same_v<CommandFn, std::function<Slic3r::GUI::ToolResult(const nlohmann::json&, Slic3r::GUI::ToolContext&)>>); +} + +TEST_CASE("the person's form is the call with no arguments", "[CommandCatalog]") +{ + CHECK(Mcp::person_form(json::object())); + CHECK(Mcp::person_form(json())); + CHECK_FALSE(Mcp::person_form({{"silent", true}})); + CHECK_FALSE(Mcp::person_form({{"path", "a"}})); + CHECK(Mcp::silent_args({{"silent", true}, {"path", "a"}}) == json{{"path", "a"}}); +} + +TEST_CASE("a two-form schema requires its arguments only when some are given", "[CommandCatalog]") +{ + const json s = Mcp::with_silent({{"type", "object"}, + {"properties", {{"path", {{"type", "string"}}}, {"overwrite", {{"type", "boolean"}}}}}, + {"required", {"path"}}, + {"additionalProperties", false}}); + CHECK_FALSE(s.contains("required")); + CHECK(s["then"]["required"] == json::array({"path"})); + CHECK(s["properties"]["silent"]["enum"] == json::array({true})); + CHECK(Mcp::validate_arguments(s, json::object()).empty()); + CHECK(Mcp::validate_arguments(s, {{"path", "a"}}).empty()); + CHECK_THAT(Mcp::validate_arguments(s, {{"overwrite", true}}), ContainsSubstring("path")); + CHECK_THAT(Mcp::validate_arguments(s, {{"silent", true}}), ContainsSubstring("path")); + CHECK_THAT(Mcp::validate_arguments(s, {{"silent", false}}), ContainsSubstring("silent")); +} + +TEST_CASE("a reference entry has the command's fields, and its examples only when it has some", "[CommandCatalog][Reference]") +{ + NativeCommand c = command("export_it", true); + c.title = "Export It"; + c.group = "Commands"; + c.description = "Exports it."; + c.input_schema = {{"type", "object"}, {"properties", {{"path", {{"type", "string"}}}}}}; + c.guard = GuardClass::Recover; + c.completion = CommandCompletion::Export; + c.operations = {"export_gcode"}; + c.open_world = true; + const json entry = Slic3r::GUI::command_reference(c); + CHECK(entry == json{{"key", "export_it"}, + {"title", "Export It"}, + {"group", "Commands"}, + {"description", "Exports it."}, + {"input_schema", c.input_schema}, + {"listed", false}, + {"in_palette", true}, + {"read_only", false}, + {"destructive", false}, + {"idempotent", false}, + {"open_world", true}, + {"guard", "recover"}, + {"completion", "export"}, + {"operations", json::array({"export_gcode"})}}); + + const json call{{"tool", "export_it"}, {"args", {{"path", "a"}}}}; + c.guard = GuardClass::Inspect; + c.completion = CommandCompletion::None; + c.examples = json::array({json{{"title", "Export"}, {"calls", json::array({call})}}}); + const json other = Slic3r::GUI::command_reference(c); + CHECK(other["guard"] == "inspect"); + CHECK(other["completion"] == "none"); + CHECK(other["examples"] == c.examples); + c.guard = GuardClass::Mutate; + CHECK(Slic3r::GUI::command_reference(c)["guard"] == "mutate"); +} diff --git a/tests/automation/test_mcp_core.cpp b/tests/automation/test_mcp_core.cpp new file mode 100644 index 0000000000..370cb6993f --- /dev/null +++ b/tests/automation/test_mcp_core.cpp @@ -0,0 +1,1815 @@ +#include <catch2/catch_test_macros.hpp> +#include <catch2/generators/catch_generators.hpp> + +#include "automation_test_utils.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/FollowedThreads.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/McpProtocol.hpp" +#include "slic3r/GUI/Mcp/UiInvoker.hpp" + +#include <nlohmann/json.hpp> + +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <cstddef> +#include <cstdint> +#include <deque> +#include <functional> +#include <memory> +#include <new> +#include <optional> +#include <set> +#include <stdexcept> +#include <utility> +#include <vector> +#include <future> +#include <mutex> +#include <string> +#include <thread> + +using namespace Slic3r::GUI; +using namespace Slic3r::GUI::Mcp; +using nlohmann::json; +using Slic3r::GUI::CommandCatalog; +using Slic3r::GUI::CommandFn; +using Slic3r::GUI::NativeCommand; +using Slic3r::GUI::Mcp::Test::Harness; +using namespace std::chrono_literals; + +namespace { + +// Plays the UI thread: closures queue up until the test drains them on its own thread. +class ManualDispatcher final : public UiDispatcher +{ +public: + void post(std::function<void()> fn) override + { + std::lock_guard<std::mutex> lock(m_mutex); + m_queue.push_back(std::move(fn)); + } + + // Runs queued closures (including ones queued while running) until the queue is empty. + void drain() + { + for (;;) { + std::function<void()> fn; + { + std::lock_guard<std::mutex> lock(m_mutex); + if (m_queue.empty()) + return; + fn = std::move(m_queue.front()); + m_queue.pop_front(); + } + fn(); + } + } + + // Keeps draining until `done` returns true or `timeout` passes, like an event loop. + bool pump_until(const std::function<bool()>& done, std::chrono::milliseconds timeout = 5000ms) + { + const auto end = std::chrono::steady_clock::now() + timeout; + while (!done()) { + if (std::chrono::steady_clock::now() > end) + return false; + drain(); + std::this_thread::sleep_for(5ms); + } + return true; + } + +private: + std::mutex m_mutex; + std::deque<std::function<void()>> m_queue; +}; + +// A file picker as ModalTracker describes it: native, and untitled on macOS. +const json kNativePicker = json::array({{{"title", ""}, {"message", "Choose one or more files"}, {"native", true}}}); + +// Sets `flag` when the test leaves, failed assertions included, so a closure holding the fake UI +// thread lets go before the harness joins that thread. Declare the flag before the harness and this +// after it: the flag must outlive that join, and be set before it starts. +struct SetOnExit +{ + std::atomic<bool>& flag; + ~SetOnExit() { flag = true; } +}; + +NativeCommand tool(const std::string& name, GuardClass guard, CommandFn handler) +{ + NativeCommand d; + d.key = name; + d.guard = guard; + d.run = std::move(handler); + return d; +} + +// Arguments whose serialized size is just over `mib` MiB. +json args_of_mib(std::size_t mib) { return {{"s", std::string(mib << 20, 'x')}}; } + +} // namespace + +TEST_CASE("a UI call that is never picked up is abandoned and never runs", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }); + bool ran = false; + std::string error; + try { + invoker.run(GuardClass::Mutate, "t", [&] { ran = true; return json(); }, 100ms); + } catch (const ToolFailure& f) { + error = f.what(); + } + CHECK(error.find("safe to retry") != std::string::npos); + ui.drain(); + CHECK_FALSE(ran); +} + +TEST_CASE("a UI call that times out behind a native dialog names the dialog", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [] { return kNativePicker; }); + bool ran = false; + std::string error; + json details; + try { + invoker.run(GuardClass::Inspect, "get_app_state", [&] { ran = true; return json(); }, 100ms); + } catch (const ToolFailure& f) { + error = f.what(); + details = f.details; + } + CHECK(error.find("native dialog") != std::string::npos); + CHECK(details.value("dialogs", json()) == kNativePicker); + ui.drain(); + CHECK_FALSE(ran); +} + +TEST_CASE("a UI call that times out behind a wx dialog keeps the busy message", "[Mcp]") +{ + ManualDispatcher ui; + // The topmost dialog has no "native" field, as Orca's own dialogs in these tests don't. + const json dialogs = json::array({kNativePicker[0], {{"title", "Preferences"}}}); + UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [&] { return dialogs; }); + std::string error; + try { + invoker.run(GuardClass::Inspect, "get_app_state", [] { return json(); }, 100ms); + } catch (const ToolFailure& f) { + error = f.what(); + } + CHECK(error.find("safe to retry") != std::string::npos); + ui.drain(); +} + +TEST_CASE("a UI call returns the closure's value", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }); + auto fut = std::async(std::launch::async, [&] { return invoker.run(GuardClass::Inspect, "t", [] { return json(42); }); }); + ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); + CHECK(fut.get() == json(42)); +} + +TEST_CASE("shutdown wakes waiting callers and later closures do nothing", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }); + std::atomic<bool> ran{false}; + auto fut = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Mutate, "t", [&] { ran = true; return json(); }); + } catch (const ToolFailure& f) { + return f.what(); + } + return "returned"; + }); + std::this_thread::sleep_for(50ms); + invoker.shutdown(); + CHECK(fut.get().find("shutting down") != std::string::npos); + ui.drain(); + CHECK_FALSE(ran); +} + +TEST_CASE("guards refuse mutate calls behind a modal, while closing and while suspended", "[Mcp]") +{ + ManualDispatcher ui; + GuardState guards; + UiInvoker invoker(ui, [&] { return guards; }); + auto attempt = [&](GuardClass g) -> std::string { + auto fut = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(g, "t", [] { return json(); }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); + return fut.get(); + }; + guards.modal = true; + CHECK(attempt(GuardClass::Mutate).find("modal dialog") != std::string::npos); + CHECK(attempt(GuardClass::Inspect) == "ok"); + CHECK(attempt(GuardClass::Recover) == "ok"); + guards = {}; + guards.suspended = true; + CHECK(attempt(GuardClass::Inspect).find("recreated") != std::string::npos); + guards = {}; + guards.closing = true; + CHECK(attempt(GuardClass::Inspect).find("shutting down") != std::string::npos); +} + +TEST_CASE("a mutate call is refused inside another call's nested loop but inspect runs", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }); + std::string nested_mutate, nested_inspect; + std::atomic<bool> release{false}; + + auto outer = std::async(std::launch::async, [&] { + return invoker.run(GuardClass::Mutate, "outer", [&] { + // A nested event loop: other closures run while this one is still on the stack. + auto m = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Mutate, "inner", [] { return json(); }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + auto i = std::async(std::launch::async, [&] { return invoker.run(GuardClass::Inspect, "look", [] { return json("seen"); }); }); + ui.pump_until([&] { return m.wait_for(0ms) == std::future_status::ready && i.wait_for(0ms) == std::future_status::ready; }); + nested_mutate = m.get(); + nested_inspect = i.get().get<std::string>(); + return json(); + }); + }); + ui.pump_until([&] { return outer.wait_for(0ms) == std::future_status::ready; }); + (void) outer.get(); + CHECK(nested_mutate.find("Busy: outer") != std::string::npos); + CHECK(nested_inspect == "seen"); +} + +TEST_CASE("a recover call that targets outside the dialog applies the mutate guard itself", "[Mcp]") +{ + ManualDispatcher ui; + GuardState guards; + UiInvoker invoker(ui, [&] { return guards; }); + auto attempt = [&]() -> std::string { + auto fut = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Recover, "click", [&] { + invoker.require_mutate(); + return json(); + }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); + return fut.get(); + }; + CHECK(attempt() == "ok"); + guards.modal = true; + CHECK(attempt().find("modal dialog") != std::string::npos); + guards = {}; + + // Inside another call's nested loop it is busy, as a mutate call would be. + std::string nested; + auto outer = std::async(std::launch::async, [&] { + return invoker.run(GuardClass::Mutate, "outer", [&] { + auto m = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Recover, "click", [&] { + invoker.require_mutate(); + return json(); + }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + ui.pump_until([&] { return m.wait_for(0ms) == std::future_status::ready; }); + nested = m.get(); + return json(); + }); + }); + ui.pump_until([&] { return outer.wait_for(0ms) == std::future_status::ready; }); + (void) outer.get(); + CHECK(nested.find("Busy: outer") != std::string::npos); +} + +TEST_CASE("a job outlives its reply and wait() returns its result", "[Mcp]") +{ + Harness h; + NativeCommand slow = tool("slow", GuardClass::Mutate, [](const json&, ToolContext&) { + std::this_thread::sleep_for(600ms); + return ToolResult::ok({{"done", true}}); + }); + slow.budget_ms = 200; + h.registry.add(slow); + h.start(); + + const ToolResult envelope = h.call("slow"); + REQUIRE_FALSE(envelope.is_error); + CHECK(envelope.data["status"] == "running"); + const std::string job = envelope.data["job"]; + auto result = h.jobs.wait(job, 3000ms); + REQUIRE(result.has_value()); + CHECK(result->data["done"] == true); +} + +TEST_CASE("blocked_by_dialog is reported after the soft budget when the probe sees a modal", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + h.registry.add(tool("open_modal", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.modal_loop(release, json::array({{{"title", "Unsaved changes"}}})); + return json(); + }); + return ToolResult::ok({{"closed", true}}); + })); + h.start(); + + const ToolResult envelope = h.call("open_modal"); + CHECK(envelope.data["status"] == "blocked_by_dialog"); + CHECK(envelope.data["dialogs"][0]["title"] == "Unsaved changes"); + release = true; + auto result = h.jobs.wait(envelope.data["job"], 3000ms); + REQUIRE(result.has_value()); + CHECK(result->data["closed"] == true); +} + +TEST_CASE("a call working in the topmost dialog is blocked only by another dialog on top", "[Mcp]") +{ + Harness h; + h.registry.add(tool("page_call", GuardClass::Recover, [&](const json&, ToolContext& ctx) { + ctx.works_in_dialog(7); + std::this_thread::sleep_for(400ms); + return ToolResult::ok({{"done", true}}); + })); + h.start(); + auto top = [&](std::uint64_t serial, json dialogs) { + std::lock_guard<std::mutex> lock(h.guards_mutex); + h.guards.modal = true; + h.guards.dialogs = std::move(dialogs); + h.guards.top_dialog = serial; + }; + + // Its own dialog on top: past the soft budget it is still running, and its result comes back. + top(7, json::array({{{"title", "Web dialog"}}})); + CHECK(h.call("page_call").data["done"] == true); + + // Another dialog on top, at any depth (here the same one: its own closed and another opened). + top(8, json::array({{{"title", "Another"}}})); + const ToolResult blocked = h.call("page_call"); + CHECK(blocked.data["status"] == "blocked_by_dialog"); + REQUIRE(h.jobs.wait(blocked.data["job"], 3000ms).has_value()); +} + +TEST_CASE("blocked_by_dialog is reported from the snapshot when a native dialog holds the UI thread", "[Mcp]") +{ + std::atomic<bool> release{false}; + Harness h; + SetOnExit releaser{release}; + h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.hold_ui(release, kNativePicker); + return json(); + }); + return ToolResult::ok({{"closed", true}}); + })); + h.start(); + + const ToolResult envelope = h.call("pick_file"); + release = true; + REQUIRE(envelope.data["status"] == "blocked_by_dialog"); + CHECK(envelope.data["dialogs"] == kNativePicker); + const std::string note = envelope.data.value("note", ""); + CHECK(note.find("only a person") != std::string::npos); + CHECK(note.find("tools that need the UI thread fail") != std::string::npos); + CHECK(note.find("Answer the dialog") == std::string::npos); + auto result = h.jobs.wait(envelope.data["job"], 3000ms); + REQUIRE(result.has_value()); + CHECK(result->data["closed"] == true); +} + +TEST_CASE("a held UI thread under a wx dialog is not reported as blocked_by_dialog", "[Mcp]") +{ + std::atomic<bool> release{false}; + Harness h; + SetOnExit releaser{release}; + NativeCommand hold = tool("hold", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.hold_ui(release, json::array({kNativePicker[0], {{"title", "Preferences"}}})); + return json(); + }); + return ToolResult::ok(); + }); + hold.budget_ms = 1000; + h.registry.add(hold); + h.start(); + + const ToolResult envelope = h.call("hold"); + release = true; + CHECK(envelope.data["status"] == "running"); + CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); +} + +TEST_CASE("shutdown during an unanswered probe replies shutting down", "[Mcp]") +{ + std::atomic<bool> release{false}; + Harness h; + SetOnExit releaser{release}; + h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.hold_ui(release, kNativePicker); + return json(); + }); + return ToolResult::ok(); + })); + h.start(); + + // 300 ms lands inside the probe window: past the 100 ms soft budget, before the 500 ms probe + // gives up. A stop that lands earlier gets the same reply from the check before the probe. + auto reply = std::async(std::launch::async, [&] { return h.call("pick_file"); }); + std::this_thread::sleep_for(300ms); + h.invoker.shutdown(); + const ToolResult r = reply.get(); + release = true; + CHECK(r.is_error); + CHECK(r.message.find("shutting down") != std::string::npos); +} + +TEST_CASE("a native dialog that the probe sees gets the native note", "[Mcp]") +{ + std::atomic<bool> release{false}; + Harness h; + SetOnExit releaser{release}; + h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.modal_loop(release, kNativePicker); + return json(); + }); + return ToolResult::ok(); + })); + h.start(); + + const ToolResult envelope = h.call("pick_file"); + release = true; + REQUIRE(envelope.data["status"] == "blocked_by_dialog"); + const std::string note = envelope.data.value("note", ""); + CHECK(note.find("only a person") != std::string::npos); + CHECK(note.find("tools that need the UI thread fail") == std::string::npos); + CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); +} + +TEST_CASE("a native message box with buttons gets the answer_dialog note", "[Mcp]") +{ + // As ModalTracker describes a message box whose buttons can be pressed (Windows, Linux). + const json box = json::array({{{"title", "Plugin permission request"}, + {"message", "Plugin \"Fixture\" is requesting permission to create a thread."}, + {"native", true}, + {"buttons", json::array({{{"id", 5103}, {"label", "Yes"}}, {{"id", 5104}, {"label", "No"}}})}}}); + std::atomic<bool> release{false}; + Harness h; + SetOnExit releaser{release}; + h.registry.add(tool("ask", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.modal_loop(release, box); + return json(); + }); + return ToolResult::ok(); + })); + h.start(); + + const ToolResult envelope = h.call("ask"); + release = true; + REQUIRE(envelope.data["status"] == "blocked_by_dialog"); + CHECK(envelope.data["dialogs"] == box); + const std::string note = envelope.data.value("note", ""); + CHECK(note.find("answer_dialog") != std::string::npos); + CHECK(note.find("only a person") == std::string::npos); + CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); +} + +TEST_CASE("inspect tools run inline and recover tools run as jobs while another job is blocked", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + h.registry.add(tool("open_modal", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.modal_loop(release); + return json(); + }); + return ToolResult::ok(); + })); + NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext& ctx) { + return ToolResult::ok({{"job", ctx.job_id()}, {"ui", ctx.run_ui([] { return json("ok"); })}}); + }); + look.inline_call = true; + h.registry.add(look); + h.registry.add(tool("answer", GuardClass::Recover, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { release = true; return json(); }); + return ToolResult::ok({{"job", ctx.job_id()}}); + })); + h.start(); + + const ToolResult blocked = h.call("open_modal"); + REQUIRE(blocked.data["status"] == "blocked_by_dialog"); + const ToolResult seen = h.call("look"); + CHECK(seen.data["job"] == ""); + CHECK(seen.data["ui"] == "ok"); + const ToolResult answered = h.call("answer"); + CHECK_FALSE(answered.is_error); + CHECK(answered.data["job"].get<std::string>().rfind("j", 0) == 0); + CHECK(h.jobs.wait(blocked.data["job"], 3000ms).has_value()); +} + +TEST_CASE("a recover call that opens another modal returns blocked_by_dialog", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + h.registry.add(tool("click_edit", GuardClass::Recover, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + h.modal_loop(release); + return json(); + }); + return ToolResult::ok(); + })); + h.start(); + const ToolResult r = h.call("click_edit"); + CHECK(r.data["status"] == "blocked_by_dialog"); + release = true; + CHECK(h.jobs.wait(r.data["job"], 3000ms).has_value()); +} + +TEST_CASE("every mutate call is refused while a slice job runs, but cancel_job and recover tools run", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.begin_operation(); + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + }); + slice.budget_ms = 100; + h.registry.add(slice); + h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + NativeCommand cancel = tool("cancel_job", GuardClass::Mutate, [&](const json&, ToolContext&) { + release = true; + return ToolResult::ok(); + }); + cancel.allowed_during_operation = true; + h.registry.add(cancel); + h.registry.add(tool("answer", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.start(); + + const ToolResult running = h.call("slice"); + REQUIRE(running.data["status"] == "running"); + const ToolResult refused = h.call("new_project"); + CHECK(refused.is_error); + CHECK(refused.message.find("wait for it or stop it with cancel_job") != std::string::npos); + CHECK_FALSE(h.call("answer").is_error); + CHECK_FALSE(h.call("cancel_job").is_error); + CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); + CHECK_FALSE(h.call("new_project").is_error); +} + +TEST_CASE("a submitted call returns its job at once and runs on a job's thread", "[Mcp]") +{ + // Before the harness: the job's thread may still use them until the harness has joined it. + std::atomic<bool> open{false}; + std::promise<ToolResult> ended; + std::mutex seen_mutex; + std::thread::id ran_on; + Harness h; + SetOnExit let_go{open}; + h.registry.add(tool("work", GuardClass::Mutate, [&](const json& args, ToolContext&) { + { + std::lock_guard<std::mutex> lock(seen_mutex); + ran_on = std::this_thread::get_id(); + } + while (!open) + std::this_thread::sleep_for(5ms); + return ToolResult::ok({{"n", args.value("n", 0)}}); + })); + h.start(); + + std::future<ToolResult> result = ended.get_future(); + const std::string job = h.core->submit(*h.registry.find("work"), {{"n", 7}}, [&ended](const ToolResult& r) { ended.set_value(r); }); + CHECK_FALSE(job.empty()); + // It returned while the call is still held. + CHECK(result.wait_for(0ms) == std::future_status::timeout); + open = true; + REQUIRE(result.wait_for(3000ms) == std::future_status::ready); + const ToolResult r = result.get(); + CHECK_FALSE(r.is_error); + CHECK(r.data["n"] == 7); + { + std::lock_guard<std::mutex> lock(seen_mutex); + CHECK(ran_on != std::this_thread::get_id()); + } + // The job is registered as a client's would be, and the call is not journaled. + CHECK(h.jobs.wait(job, 3000ms).has_value()); + CHECK(h.journal.to_replay("r")["steps"].empty()); +} + +TEST_CASE("a submitted change is refused as a client's is while an operation runs, and none starts after shutdown", "[Mcp]") +{ + std::atomic<bool> release{false}; + Harness h; + SetOnExit let_go{release}; + NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.begin_operation(); + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + }); + slice.budget_ms = 100; + h.registry.add(slice); + h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.start(); + + const ToolResult running = h.call("slice"); + REQUIRE(running.data["status"] == "running"); + const ToolResult client = h.call("new_project"); + REQUIRE(client.is_error); + // No job starts, and the refusal comes at once, on the calling thread. + std::optional<ToolResult> refusal; + CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&refusal](const ToolResult& r) { refusal = r; }).empty()); + REQUIRE(refusal.has_value()); + CHECK(refusal->is_error); + CHECK(refusal->message == client.message); + + release = true; + CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); + h.core->shutdown(); + bool called = false; + CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&called](const ToolResult&) { called = true; }).empty()); + CHECK_FALSE(called); +} + +TEST_CASE("a person's call marks its job, a client's call of the same command does not", "[Mcp]") +{ + Harness h; + h.registry.add(tool("work", GuardClass::Mutate, [&h](const json&, ToolContext& ctx) { + return ToolResult::ok({{"person", h.jobs.person_in(ctx.lineage())}}); + })); + h.start(); + + const ToolResult person = h.core->call_person(*h.registry.find("work"), json::object()); + REQUIRE_FALSE(person.is_error); + CHECK(person.data.value("person", false)); + const ToolResult client = h.call("work"); + REQUIRE_FALSE(client.is_error); + CHECK_FALSE(client.data.value("person", true)); + + // A person's pick of a long command is a person's call too. + std::promise<ToolResult> ended; + std::future<ToolResult> result = ended.get_future(); + const std::string job = h.core->submit(*h.registry.find("work"), json::object(), [&ended](const ToolResult& r) { ended.set_value(r); }); + REQUIRE_FALSE(job.empty()); + REQUIRE(result.wait_for(3000ms) == std::future_status::ready); + const ToolResult submitted = result.get(); + REQUIRE_FALSE(submitted.is_error); + CHECK(submitted.data.value("person", false)); + REQUIRE(h.jobs.wait(job, 3000ms).has_value()); +} + +TEST_CASE("an agent's call right after a person's run is not a person's", "[Mcp]") +{ + // Before the harness: the person's job thread may still read them until the harness has joined it. + std::atomic<bool> release{false}; + Harness h; + // A person's run that outlives its reply, then an agent's call of the same command once it has ended. + NativeCommand work = tool("work", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + const bool person = h.jobs.person_in(ctx.lineage()); + while (!release) + std::this_thread::sleep_for(5ms); + return ToolResult::ok({{"person", person}}); + }); + work.budget_ms = 50; + h.registry.add(work); + h.start(); + SetOnExit release_on_exit{release}; + + const ToolResult envelope = h.core->call_person(*h.registry.find("work"), json::object()); + REQUIRE(envelope.data.value("status", "") == "running"); + const std::string job = envelope.data["job"]; + CHECK(h.jobs.person_in({job})); + release = true; + const std::optional<ToolResult> person = h.jobs.wait(job, 3000ms); + REQUIRE(person.has_value()); + CHECK(person->data.value("person", false)); + CHECK_FALSE(h.jobs.person_in({job})); + + // The command's 50 ms budget is the agent's too: a reply past it is the envelope, and the result is its job's. + std::optional<ToolResult> agent = h.call("work"); + if (!agent->is_error && agent->data.value("status", "") == "running") + agent = h.jobs.wait(agent->data["job"], 3000ms); + REQUIRE(agent.has_value()); + REQUIRE_FALSE(agent->is_error); + CHECK_FALSE(agent->data.value("person", true)); +} + +TEST_CASE("a submitted call whose done throws still ends its job", "[Mcp]") +{ + Harness h; + h.registry.add(tool("work", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.start(); + + // done runs on the job's thread: what it throws must not end the process, nor keep the job from finishing. + const std::string job = h.core->submit(*h.registry.find("work"), json::object(), + [](const ToolResult&) { throw std::runtime_error("the caller's own failure"); }); + REQUIRE_FALSE(job.empty()); + CHECK(h.jobs.wait(job, 3000ms).has_value()); +} + +// What a recording's CallObserver hears, in order. +struct HeardCalls final : CallObserver +{ + std::mutex mutex; + std::vector<std::string> events; + void call_started(uint64_t, const NativeCommand& def, const json&, const std::string& parent) override + { + std::lock_guard<std::mutex> lock(mutex); + events.push_back("start " + def.key + (parent.empty() ? "" : " in a job")); + } + void call_args(uint64_t, const json& args) override + { + std::lock_guard<std::mutex> lock(mutex); + events.push_back("args " + args.dump()); + } + void call_ended(uint64_t, const ToolResult& result) override + { + std::lock_guard<std::mutex> lock(mutex); + events.push_back(std::string("end ") + (result.is_error ? "error" : "ok")); + } + std::vector<std::string> take() + { + std::lock_guard<std::mutex> lock(mutex); + return std::exchange(events, {}); + } +}; + +TEST_CASE("the call observer hears inline, job and child calls, and not calls refused before they run", "[Mcp]") +{ + Harness h; + HeardCalls heard; + NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); + look.inline_call = true; + h.registry.add(look); + h.registry.add(tool("click", GuardClass::Recover, [](const json&, ToolContext& ctx) { + // A ref resolved to its locator, as the GUI tools record it. + ctx.set_journal_args({{"target", {{"label", "Slice"}}}}); + return ToolResult::error("gone"); + })); + h.registry.add(tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("click", json::object()); })); + std::atomic<bool> release{false}; + NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.begin_operation(); + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + }); + slice.budget_ms = 100; + h.registry.add(slice); + h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &heard); + + CHECK_FALSE(h.call("look").is_error); + CHECK(heard.take() == std::vector<std::string>{"start look", "end ok"}); + CHECK(h.call("click").is_error); + CHECK(heard.take() == std::vector<std::string>{"start click", R"(args {"target":{"label":"Slice"}})", "end error"}); + h.call("replay"); + CHECK(heard.take() == + std::vector<std::string>{"start replay", "start click in a job", R"(args {"target":{"label":"Slice"}})", "end error", "end error"}); + + const ToolResult running = h.call("slice"); + REQUIRE(running.data["status"] == "running"); + CHECK(heard.take() == std::vector<std::string>{"start slice"}); + CHECK(h.call("replay").is_error); // refused by admission: it never ran + CHECK(heard.take().empty()); + release = true; + REQUIRE(h.jobs.wait(running.data["job"], 3000ms).has_value()); + CHECK(heard.take() == std::vector<std::string>{"end ok"}); +} + +TEST_CASE("an observer that throws fails no call", "[Mcp]") +{ + struct Throwing final : CallObserver + { + void call_started(uint64_t, const NativeCommand&, const json&, const std::string&) override { throw std::runtime_error("started"); } + void call_args(uint64_t, const json&) override { throw std::bad_alloc(); } + void call_ended(uint64_t, const ToolResult&) override { throw std::runtime_error("ended"); } + } throwing; + Harness h; + NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok({{"seen", true}}); }); + look.inline_call = true; + h.registry.add(look); + h.registry.add(tool("act", GuardClass::Mutate, [](const json&, ToolContext& ctx) { + ctx.set_journal_args({{"x", 1}}); + return ToolResult::ok({{"done", true}}); + })); + h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &throwing); + const ToolResult looked = h.call("look"); + CHECK_FALSE(looked.is_error); + CHECK(looked.data["seen"] == true); + const ToolResult acted = h.call("act"); + CHECK_FALSE(acted.is_error); + CHECK(acted.data["done"] == true); +} + +TEST_CASE("the journal records a call without its command's id arguments", "[Mcp]") +{ + Harness h; + NativeCommand move = tool("move", GuardClass::Mutate, [](const json& args, ToolContext& ctx) { + // A handler that replaces what the journal records, as the GUI tools record locators for refs. + if (args.contains("rewrite")) + ctx.set_journal_args({{"object", 2}, {"object_id", 5}}); + return ToolResult::ok(); + }); + move.id_args = {"object_id"}; + h.registry.add(move); + // A command without id_args keeps an argument of that name: it is its own. + h.registry.add(tool("measure", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.start(); + + REQUIRE_FALSE(h.call("move", {{"object", 1}, {"object_id", 9}}).is_error); + REQUIRE_FALSE(h.call("move", {{"rewrite", true}, {"object_id", 9}}).is_error); + REQUIRE_FALSE(h.call("measure", {{"object_id", 4}}).is_error); + const json steps = h.journal.to_replay("s")["steps"]; + REQUIRE(steps.size() == 3); + CHECK(steps[0]["args"] == json{{"object", 1}}); + CHECK(steps[1]["args"] == json{{"object", 2}}); + CHECK(steps[2]["args"] == json{{"object_id", 4}}); +} + +TEST_CASE("without a blocking slot a job call returns its envelope at once and an inline call returns pending", "[Mcp]") +{ + Harness h; + h.timing.blocking_slots = 1; + std::atomic<bool> release{false}; + NativeCommand hold = tool("hold", GuardClass::Inspect, [&](const json&, ToolContext&) { + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + }); + hold.inline_call = true; + h.registry.add(hold); + h.registry.add(tool("work", GuardClass::Mutate, [](const json&, ToolContext&) { + std::this_thread::sleep_for(50ms); + return ToolResult::ok(); + })); + h.start(); + + auto holder = std::async(std::launch::async, [&] { return h.core->call(*h.registry.find("hold"), json::object()); }); + std::this_thread::sleep_for(100ms); + const auto start = std::chrono::steady_clock::now(); + const ToolResult job = h.core->call(*h.registry.find("work"), json::object()); + CHECK(job.data["status"] == "running"); + const ToolResult pending = h.core->call(*h.registry.find("hold"), json::object()); + CHECK(pending.data["status"] == "pending"); + CHECK(std::chrono::steady_clock::now() - start < 500ms); + release = true; + (void) holder.get(); + CHECK(h.jobs.wait(job.data["job"], 3000ms).has_value()); +} + +TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]") +{ + JobRegistry jobs; + const std::string replay_job = jobs.create("run_replay", ""); + const std::string step = jobs.create("slice", replay_job); + const std::string other = jobs.create("open_files", ""); + CHECK(jobs.lineage(step) == std::set<std::string>{step, replay_job}); + CHECK(jobs.any_running_except(jobs.lineage(step))); + jobs.finish(other, ToolResult::ok()); + CHECK_FALSE(jobs.any_running_except(jobs.lineage(step))); + jobs.begin_operation(step); + CHECK(jobs.running_operations() == std::vector<std::string>{step}); +} + +TEST_CASE("idle skips a job set idle, but not the calls it makes", "[Mcp]") +{ + JobRegistry jobs; + const std::string run = jobs.create("run_script", ""); + jobs.set_idle(run); + const std::string child = jobs.create("slice", run); + CHECK(jobs.any_running_except({})); + bool listed_idle = false; + for (const nlohmann::json& job : jobs.list()) + if (job["id"] == run) + listed_idle = job.value("idle", false); + CHECK(listed_idle); + jobs.finish(child, ToolResult::ok()); + CHECK_FALSE(jobs.any_running_except({})); +} + +TEST_CASE("the job registry caps running jobs and forgets old finished ones", "[Mcp]") +{ + JobRegistry jobs; + std::vector<std::string> ids; + for (std::size_t i = 0; i < JobRegistry::kMaxRunning; ++i) + ids.push_back(jobs.create("t", "")); + CHECK_THROWS_AS(jobs.create("t", ""), ToolFailure); + for (const std::string& id : ids) + jobs.finish(id, ToolResult::ok()); + for (std::size_t i = 0; i < JobRegistry::kKeepFinished; ++i) + jobs.finish(jobs.create("t", ""), ToolResult::ok()); + CHECK_THROWS_AS(jobs.wait(ids.front(), 0ms), ToolFailure); +} + +TEST_CASE("a caller waits for its running UI closure even through shutdown", "[Mcp]") +{ + ManualDispatcher ui; + UiInvoker invoker(ui, [] { return GuardState{}; }); + std::atomic<bool> inside{false}, release{false}, finished{false}; + auto caller = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Inspect, "look", [&] { + inside = true; + ui.pump_until([&] { return release.load(); }); // a nested event loop + finished = true; + return json(); + }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + std::thread ui_thread([&] { ui.pump_until([&] { return finished.load(); }, 5000ms); }); + while (!inside) + std::this_thread::sleep_for(5ms); + invoker.shutdown(); + // The closure still uses the caller's stack, so the caller must not have returned. + CHECK(caller.wait_for(200ms) == std::future_status::timeout); + release = true; + ui_thread.join(); + CHECK(caller.get() == "ok"); +} + +TEST_CASE("a closure queued before a UI rebuild does not run after it", "[Mcp]") +{ + ManualDispatcher ui; + std::atomic<uint64_t> generation{1}; + UiInvoker invoker(ui, [] { return GuardState{}; }, [&] { return generation.load(); }); + std::atomic<bool> ran{false}; + auto caller = std::async(std::launch::async, [&]() -> std::string { + try { + invoker.run(GuardClass::Mutate, "click", [&] { + ran = true; + return json(); + }); + return "ok"; + } catch (const ToolFailure& f) { + return f.what(); + } + }); + std::this_thread::sleep_for(50ms); + generation = 2; // a language change rebuilt the UI while the closure waited + ui.pump_until([&] { return caller.wait_for(0ms) == std::future_status::ready; }); + CHECK(caller.get().find("recreated") != std::string::npos); + CHECK_FALSE(ran); +} + +TEST_CASE("operation admission is checked again when a mutate call reaches the UI thread", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + h.registry.add(tool("edit", GuardClass::Mutate, [](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([] { return json("edited"); })); + })); + NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + ctx.run_ui([&] { + ctx.begin_operation(); + return json(); + }); + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + }); + h.registry.add(slice); + h.start(); + // The UI thread is held, so both calls are admitted before either runs; the slice runs first. + std::atomic<bool> hold{true}; + h.ui.post([&] { + while (hold) + std::this_thread::sleep_for(5ms); + }); + auto s = std::async(std::launch::async, [&] { return h.call("slice"); }); + std::this_thread::sleep_for(100ms); + auto e = std::async(std::launch::async, [&] { return h.call("edit"); }); + std::this_thread::sleep_for(100ms); + hold = false; + const ToolResult edited = e.get(); + CHECK(edited.is_error); + CHECK(edited.message.find("Busy: job") != std::string::npos); + release = true; + (void) s.get(); +} + +TEST_CASE("only one operation runs at a time", "[Mcp]") +{ + JobRegistry jobs; + const std::string a = jobs.create("slice", ""); + const std::string b = jobs.create("export", ""); + CHECK(jobs.begin_operation(a).empty()); + CHECK(jobs.begin_operation(b) == a); + jobs.finish(a, ToolResult::ok()); + CHECK(jobs.begin_operation(b).empty()); +} + +TEST_CASE("ancestry lists the job chain nearest first", "[Mcp]") +{ + JobRegistry jobs; + const std::string outer = jobs.create("run_replay", ""); + const std::string inner = jobs.create("run_replay", outer); + const std::string step = jobs.create("auto_answer_dialogs", inner); + CHECK(jobs.ancestry(step) == std::vector<std::string>{step, inner, outer}); +} + +TEST_CASE("a stop asked for a job reaches its descendants and no other job", "[Mcp]") +{ + JobRegistry jobs; + const std::string replay_job = jobs.create("run_replay", ""); + const std::string step = jobs.create("slice", replay_job); + const std::string other = jobs.create("open_files", ""); + CHECK_FALSE(jobs.stop_requested(step)); + jobs.request_stop(replay_job); + CHECK(jobs.stop_requested(replay_job)); + CHECK(jobs.stop_requested(step)); + CHECK_FALSE(jobs.stop_requested(other)); + CHECK_FALSE(jobs.stop_requested("")); +} + +TEST_CASE("a job created as a person's is a person's until it finishes", "[Mcp]") +{ + JobRegistry jobs; + const std::string person = jobs.create("work", "", "", true); + const std::string child = jobs.create("work", person); + const std::string other = jobs.create("work", ""); + CHECK(jobs.person_in({person})); + // A call under the person's run runs as the person's, with no mark of its own. + CHECK(jobs.person_in(jobs.lineage(child))); + CHECK_FALSE(jobs.person_in({child})); + CHECK_FALSE(jobs.person_in({other})); + jobs.finish(person, ToolResult::ok()); + CHECK_FALSE(jobs.person_in({person})); + CHECK_FALSE(jobs.person_in(jobs.lineage(child))); +} + +TEST_CASE("a job allowed to discard is so until it finishes", "[Mcp]") +{ + JobRegistry jobs; + const std::string run = jobs.create("run_replay", ""); + const std::string step = jobs.create("open_project", run); + const std::string other = jobs.create("open_project", ""); + CHECK_FALSE(jobs.discard_allowed_in({run})); + jobs.allow_discard(run); + CHECK(jobs.discard_allowed_in({run})); + CHECK(jobs.discard_allowed_in(jobs.lineage(step))); + CHECK_FALSE(jobs.discard_allowed_in({step})); + CHECK_FALSE(jobs.discard_allowed_in({other})); + CHECK_NOTHROW(jobs.allow_discard("j999")); + CHECK_FALSE(jobs.discard_allowed_in({"j999"})); + jobs.finish(run, ToolResult::ok()); + CHECK_FALSE(jobs.discard_allowed_in({run})); + CHECK_FALSE(jobs.discard_allowed_in(jobs.lineage(step))); + // A finished job is not allowed it afterwards. + jobs.allow_discard(run); + CHECK_FALSE(jobs.discard_allowed_in({run})); +} + +TEST_CASE("a job wait with a stop check looks once at zero timeout and ends when stopped", "[Mcp]") +{ + JobRegistry jobs; + const std::string done = jobs.create("slice", ""); + jobs.finish(done, ToolResult::ok({{"done", true}})); + const std::string running = jobs.create("slice", ""); + const auto never = [] { return false; }; + + const auto finished = jobs.wait(done, 0ms, never); + REQUIRE(finished.has_value()); + CHECK(finished->data["done"] == true); + CHECK_FALSE(jobs.wait(running, 0ms, never).has_value()); + CHECK_THROWS_AS(jobs.wait("j999", 0ms, never), ToolFailure); + + const auto start = std::chrono::steady_clock::now(); + CHECK_FALSE(jobs.wait(running, 5000ms, [] { return true; }).has_value()); + CHECK(std::chrono::steady_clock::now() - start < 2s); +} + +TEST_CASE("a call made by a stopped job sees itself cancelled", "[Mcp]") +{ + Harness h; + // An inline call that polls for cancellation, as wait does. + NativeCommand spin = tool("spin", GuardClass::Inspect, [](const json&, ToolContext& ctx) { + const auto end = std::chrono::steady_clock::now() + 5s; + while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) + std::this_thread::sleep_for(10ms); + return ToolResult::ok({{"cancelled", ctx.cancelled()}}); + }); + spin.inline_call = true; + h.registry.add(spin); + NativeCommand replay = tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("spin", json::object()); }); + replay.budget_ms = 50; + h.registry.add(replay); + h.start(); + + const ToolResult envelope = h.call("replay"); + REQUIRE(envelope.data["status"] == "running"); + const auto asked = std::chrono::steady_clock::now(); + h.jobs.request_stop(envelope.data["job"]); + const auto result = h.jobs.wait(envelope.data["job"], 3000ms); + REQUIRE(result.has_value()); + CHECK(result->data["cancelled"] == true); + CHECK(std::chrono::steady_clock::now() - asked < 2s); +} + +TEST_CASE("a live descendant keeps its lineage after its ancestors are evicted", "[Mcp]") +{ + JobRegistry jobs; + const std::string root = jobs.create("run_replay", ""); + const std::string inner = jobs.create("run_replay", root); + const std::string leaf = jobs.create("wait", inner); + jobs.finish(inner, ToolResult::ok()); + jobs.finish(root, ToolResult::ok()); + for (int i = 0; i < 70; ++i) + jobs.finish(jobs.create("t", ""), ToolResult::ok()); + CHECK_THROWS_AS(jobs.wait(inner, 0ms), ToolFailure); // evicted + const std::set<std::string> lineage = jobs.lineage(leaf); + CHECK(lineage.count(root) == 1); + CHECK(lineage.count(inner) == 1); + CHECK(jobs.ancestry(leaf) == std::vector<std::string>{leaf, inner, root}); +} + +TEST_CASE("a finished job stays while its parent replay runs", "[Mcp]") +{ + JobRegistry jobs; + const std::string replay_job = jobs.create("run_replay", ""); + const std::string saved = jobs.create("run_action", replay_job); + jobs.finish(saved, ToolResult::ok({{"x", 1}})); + for (std::size_t i = 0; i < JobRegistry::kKeepFinished + 5; ++i) + jobs.finish(jobs.create("t", ""), ToolResult::ok()); + CHECK(jobs.wait(saved, 0ms).has_value()); + jobs.finish(replay_job, ToolResult::ok()); + for (std::size_t i = 0; i < JobRegistry::kKeepFinished + 5; ++i) + jobs.finish(jobs.create("t", ""), ToolResult::ok()); + CHECK_THROWS_AS(jobs.wait(saved, 0ms), ToolFailure); +} + +TEST_CASE("finished jobs stay bounded while their parent replay runs", "[Mcp]") +{ + JobRegistry jobs; + const std::string replay_job = jobs.create("run_replay", ""); + const std::string first = jobs.create("t", replay_job); + jobs.finish(first, ToolResult::ok()); + for (std::size_t i = 0; i < JobRegistry::kKeepFinishedMax; ++i) + jobs.finish(jobs.create("t", replay_job), ToolResult::ok()); + CHECK_THROWS_AS(jobs.wait(first, 0ms), ToolFailure); + const std::string recent = jobs.create("t", replay_job); + jobs.finish(recent, ToolResult::ok()); + CHECK(jobs.wait(recent, 0ms).has_value()); +} + +TEST_CASE("the journal keeps a call waiting for its reply when it drops old calls", "[Mcp]") +{ + Journal journal; + const uint64_t waiting = journal.begin("slice", json::object()); + for (int i = 0; i < 6000; ++i) + journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", i}}}}), ToolResult::ok()); + journal.end(waiting, ToolResult::ok()); + const json steps = journal.to_replay("s")["steps"]; + REQUIRE_FALSE(steps.empty()); + CHECK(steps[0]["tool"] == "slice"); + CHECK(steps.size() == 5000); +} + +TEST_CASE("the journal keeps at most 64 MiB of arguments", "[Mcp]") +{ + Journal journal; + const json big = args_of_mib(1); + for (int i = 0; i < 100; ++i) + journal.end(journal.begin("set_settings", big), ToolResult::ok()); + const json steps = journal.to_replay("s")["steps"]; + CHECK(steps.size() < 64); + CHECK(steps.size() > 56); +} + +TEST_CASE("calls waiting for their reply outlast the byte cap and go once they finish", "[Mcp]") +{ + Journal journal; + const json big = args_of_mib(1); + std::vector<uint64_t> waiting; + for (int i = 0; i < 70; ++i) + waiting.push_back(journal.begin("set_settings", big)); + json left; + CHECK(journal.to_replay("s", &left)["steps"].empty()); + CHECK(left.size() == 70); + // Each reply trims on its own, with no later begin or set_args. + for (const uint64_t seq : waiting) + journal.end(seq, ToolResult::ok()); + CHECK(journal.to_replay("s", &left)["steps"].size() < 64); + CHECK(left.empty()); +} + +TEST_CASE("a job's call over the byte cap stays until its job ends", "[Mcp]") +{ + Journal journal; + const json huge = args_of_mib(65); + json left; + + // The reply comes first, as the job's envelope; the job ends later. + const uint64_t seq = journal.begin("thread", huge); + journal.job_started(seq, "j"); + journal.end(seq, ToolResult::ok({{"status", "running"}, {"job", "j"}})); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + REQUIRE(left.size() == 1); + CHECK(left[0] == json{{"tool", "thread"}, {"job", "j"}}); + journal.job_ended(seq, ToolResult::ok()); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + CHECK(left.empty()); + + // The job ends before its reply. + const uint64_t seq2 = journal.begin("thread", huge); + journal.job_started(seq2, "k"); + journal.job_ended(seq2, ToolResult::ok()); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + CHECK(left.empty()); + journal.end(seq2, ToolResult::ok()); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + CHECK(left.empty()); +} + +TEST_CASE("replacing a call's arguments moves the journal's byte total", "[Mcp]") +{ + Journal journal; + const json fifteen = args_of_mib(15); + json left; + for (int i = 0; i < 4; ++i) + journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + // 60 MiB, then 70 MiB once the small call's arguments grow: the first 15 MiB call goes at once, + // while the grown call still waits for its reply. + const uint64_t b = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); + journal.set_args(b, args_of_mib(10)); + CHECK(journal.to_replay("s", &left)["steps"].size() == 3); + CHECK(left.size() == 1); + journal.end(b, ToolResult::ok()); + CHECK(journal.to_replay("s")["steps"].size() == 4); + // Shrinking them back leaves 45 MiB, room for one more 15 MiB call. + journal.set_args(b, {{"values", {{"wall_loops", 3}}}}); + journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + CHECK(journal.to_replay("s")["steps"].size() == 5); +} + +TEST_CASE("clearing the journal resets its byte total", "[Mcp]") +{ + Journal journal; + const json fifteen = args_of_mib(15); + for (int i = 0; i < 4; ++i) + journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + journal.clear(); + // Were the cleared calls' 60 MiB still counted, this 15 MiB call would go once it replied. + journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); + journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + CHECK(journal.to_replay("s")["steps"].size() == 2); +} + +TEST_CASE("one call bigger than the cap is dropped once it has replied", "[Mcp]") +{ + Journal journal; + json left; + const uint64_t seq = journal.begin("thread", args_of_mib(65)); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + REQUIRE(left.size() == 1); + CHECK(left[0] == json{{"tool", "thread"}}); + journal.end(seq, ToolResult::ok()); + CHECK(journal.to_replay("s", &left)["steps"].empty()); + CHECK(left.empty()); + // The total is back to what the remaining calls hold, so a small call stays. + journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + CHECK(journal.to_replay("s")["steps"].size() == 1); +} + +TEST_CASE("a job refused at shutdown after it registered ends its journal entry", "[Mcp]") +{ + ManualDispatcher ui; + McpCore* core_ptr = nullptr; + // A recover call's journal entry reads the open dialogs between the core's two shutdown checks: + // shutting down there lets the call register its job, then refuses it. + UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [&core_ptr] { + core_ptr->shutdown(); + return json::array(); + }); + JobRegistry jobs; + Journal journal; + CommandCatalog registry; + registry.add(tool("answer_dialog", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); + McpCore core(registry, invoker, jobs, &journal, CoreTiming{}); + core_ptr = &core; + + const ToolResult r = core.call(*registry.find("answer_dialog"), args_of_mib(65)); + REQUIRE(r.is_error); + CHECK(r.message == "OrcaSlicer is shutting down"); + // An entry left running would hold its 65 MiB against the cap, so the next call, not it, would go. + journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); + CHECK(journal.to_replay("s")["steps"].size() == 1); +} + +TEST_CASE("drain reports a job thread that has not returned", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + h.registry.add(tool("stuck", GuardClass::Mutate, [&](const json&, ToolContext&) { + while (!release) + std::this_thread::sleep_for(10ms); + return ToolResult::ok(); + })); + h.timing.soft_budget = 50ms; + h.start(); + auto call = std::async(std::launch::async, [&] { return h.call("stuck"); }); + std::this_thread::sleep_for(100ms); + h.core->shutdown(); + CHECK_FALSE(h.core->drain(200ms)); + release = true; + (void) call.get(); + CHECK(h.core->drain(2000ms)); +} + +TEST_CASE("destroying a core waits for a job thread still inside it", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + std::atomic<bool> returned{false}; + h.registry.add(tool("stuck", GuardClass::Mutate, [&](const json&, ToolContext&) { + while (!release) + std::this_thread::sleep_for(10ms); + std::this_thread::sleep_for(50ms); + returned = true; + return ToolResult::ok(); + })); + h.timing.soft_budget = 50ms; + h.start(); + auto call = std::async(std::launch::async, [&] { return h.call("stuck"); }); + std::this_thread::sleep_for(100ms); + h.core->shutdown(); + auto destroy = std::async(std::launch::async, [&] { h.core.reset(); }); + CHECK(destroy.wait_for(300ms) == std::future_status::timeout); + release = true; + destroy.get(); + CHECK(returned); + (void) call.get(); +} + +TEST_CASE("the journal records client calls in order and replays jobs with await false", "[Mcp]") +{ + Journal journal; + const uint64_t a = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + journal.job_started(a, "j7"); + journal.end(a, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j7"}})); + const uint64_t b = journal.begin("answer_dialog", {{"button", "close"}}); + journal.end(b, ToolResult::ok()); + const uint64_t c = journal.begin("wait", {{"for", "job"}, {"job", "j7"}}); + journal.end(c, ToolResult::ok()); + const uint64_t d = journal.begin("screenshot", {{"target", "canvas"}, {"save_path", "/tmp/x/after.png"}}); + journal.end(d, ToolResult::ok()); + const uint64_t e = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); + journal.end(e, ToolResult::error("no")); + + const json exported = journal.to_replay("repro"); + REQUIRE(exported["steps"].size() == 4); + CHECK(exported["steps"][0]["await"] == false); + CHECK(exported["steps"][0]["save_as"] == "job1"); + CHECK(exported["steps"][1]["tool"] == "answer_dialog"); + CHECK(exported["steps"][2]["args"]["job"] == "${jobs.job1}"); + CHECK(exported["steps"][3]["args"]["save_path"] == "${out_dir}/after.png"); +} + +TEST_CASE("only client calls of journaled tools reach the journal", "[Mcp]") +{ + Harness h; + NativeCommand look = tool("get_app_state", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); + look.inline_call = true; + look.journal = false; + h.registry.add(look); + NativeCommand wait = tool("wait", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); + wait.inline_call = true; + h.registry.add(wait); + h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext& ctx) { + ctx.set_journal_args({{"values", {{"wall_loops", 3}}}, {"scope", "process"}}); + return ToolResult::ok(); + })); + h.start(); + h.call("get_app_state"); + h.call("wait", {{"for", "idle"}}); + h.call("set_settings", {{"values", {{"wall_loops", 3}}}}); + const json steps = h.journal.to_replay("x")["steps"]; + REQUIRE(steps.size() == 2); + CHECK(steps[0]["tool"] == "wait"); + CHECK(steps[1]["args"]["scope"] == "process"); +} + +TEST_CASE("a plugin's call runs as the plugin's own job and never reaches the journal", "[Mcp]") +{ + Harness h; + std::string seen, child_seen; + h.registry.add(tool("get_app_state", GuardClass::Inspect, [&child_seen](const json&, ToolContext& ctx) { + child_seen = ctx.caller_plugin(); + return ToolResult::ok(); + })); + h.registry.add(tool("set_settings", GuardClass::Mutate, [&seen](const json&, ToolContext& ctx) { + seen = ctx.caller_plugin(); + // A call it makes, as a replay step does, is the plugin's too. + ctx.call_child("get_app_state", json::object()); + return ToolResult::ok({{"job", ctx.job_id()}}); + })); + h.start(); + const ToolResult r = h.core->call_plugin(*h.registry.find("set_settings"), json::object(), "measure-plugin"); + REQUIRE_FALSE(r.is_error); + CHECK(seen == "measure-plugin"); + CHECK(child_seen == "measure-plugin"); + CHECK(h.jobs.owner(r.data["job"].get<std::string>()) == "measure-plugin"); + CHECK(h.journal.to_replay("x")["steps"].empty()); + + // A client's call has no plugin. + h.call("set_settings"); + CHECK(seen.empty()); + CHECK(h.journal.to_replay("x")["steps"].size() == 1); +} + +TEST_CASE("call_tool is journaled as the tool it calls", "[Mcp]") +{ + Harness h; + h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + NativeCommand api = tool("call_tool", GuardClass::Mutate, [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }); + api.input_schema = {{"type", "object"}, {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}}; + h.registry.add(api); + h.start(); + McpProtocol protocol(h.registry, *h.core, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", ""}); + const PostReply reply = protocol.handle_post(PostRequest{json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, + {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "set_settings"}, {"args", {{"values", {{"wall_loops", 3}}}}}}}}}}.dump()}); + CHECK(json::parse(reply.body)["result"].value("isError", false) == false); + const json steps = h.journal.to_replay("x")["steps"]; + REQUIRE(steps.size() == 1); + CHECK(steps[0]["tool"] == "set_settings"); + CHECK(steps[0]["args"]["values"]["wall_loops"] == 3); +} + +TEST_CASE("a plugin's session tools act only on the jobs of its own calls", "[Mcp]") +{ + Harness h; + h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ToolResult::ok({{"job", ctx.job_id()}}); })); + h.registry.add(tool("peek", GuardClass::Mutate, [&h](const json& args, ToolContext& ctx) { + require_own_job(ctx, h.jobs, args.value("job", std::string()), "waits for"); + return ToolResult::ok(); + })); + h.start(); + const std::string clients = h.call("make").data["job"].get<std::string>(); + const std::string plugins = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").data["job"].get<std::string>(); + + const ToolResult foreign = h.core->call_plugin(*h.registry.find("peek"), json{{"job", clients}}, "measure"); + CHECK(foreign.is_error); + CHECK(foreign.message.find("only the jobs of its own calls") != std::string::npos); + CHECK_FALSE(h.core->call_plugin(*h.registry.find("peek"), json{{"job", plugins}}, "measure").is_error); + // A client's call is not a plugin's, whoever's job it names. + CHECK_FALSE(h.call("peek", json{{"job", plugins}}).is_error); +} + +TEST_CASE("an unloaded plugin's calls start no job, nor do the children of one already running", "[Mcp]") +{ + Harness h; + std::atomic<bool> release{false}; + ToolResult child; + h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.registry.add(tool("slow", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + child = ctx.call_child("make", json::object()); + return ToolResult::ok(); + })); + h.timing.soft_budget = std::chrono::milliseconds(10000); + h.start(); + // A call that was admitted before the unload and is still running when it comes. + std::thread running([&] { h.core->call_plugin(*h.registry.find("slow"), json::object(), "measure"); }); + while (h.jobs.running_owned_by("measure").empty()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + + h.jobs.block_owner("measure"); + const ToolResult late = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure"); + CHECK(late.is_error); + CHECK(late.message.find("unloaded") != std::string::npos); + release = true; + running.join(); + CHECK(child.is_error); + + // Another plugin's calls and a client's are not affected; a load lifts the block. + CHECK_FALSE(h.core->call_plugin(*h.registry.find("make"), json::object(), "other").is_error); + CHECK_FALSE(h.call("make").is_error); + h.jobs.unblock_owner("measure"); + CHECK_FALSE(h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").is_error); +} + +TEST_CASE("a plugin's calls are refused once it unloads, before the block comes, inline calls included", "[Mcp]") +{ + Harness h; + std::atomic<bool> loaded{true}; + std::atomic<bool> release{false}; + std::atomic<int> looks{0}; + ToolResult inline_child; + ToolResult job_child; + // The plugin manager's state, which changes as the plugin unloads; end_plugin_scope()'s block comes later. + h.jobs.set_owner_liveness([&](const std::string& plugin) { return plugin != "measure" || loaded; }); + NativeCommand look = tool("look", GuardClass::Inspect, [&](const json&, ToolContext&) { ++looks; return ToolResult::ok(); }); + look.inline_call = true; + h.registry.add(look); + h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); + h.registry.add(tool("slow", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + inline_child = ctx.call_child("look", json::object()); + job_child = ctx.call_child("make", json::object()); + return ToolResult::ok(); + })); + h.timing.soft_budget = std::chrono::milliseconds(10000); + h.start(); + std::thread running([&] { h.core->call_plugin(*h.registry.find("slow"), json::object(), "measure"); }); + while (h.jobs.running_owned_by("measure").empty()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + + loaded = false; + const ToolResult inline_call = h.core->call_plugin(*h.registry.find("look"), json::object(), "measure"); + CHECK(inline_call.is_error); + CHECK(inline_call.message.find("unloaded") != std::string::npos); + CHECK(h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").is_error); + release = true; + running.join(); + CHECK(inline_child.is_error); + CHECK(job_child.is_error); + CHECK(looks == 0); + + // Another plugin's calls and a client's still run, and so do the plugin's once it is loaded again. + CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "other").is_error); + CHECK_FALSE(h.call("look").is_error); + loaded = true; + CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "measure").is_error); + CHECK(looks == 3); +} + +TEST_CASE("a plugin's job never starts once the plugin unloads, as it registers or right before its handler", "[Mcp]") +{ + // The liveness hook is asked as the call comes in, once its job is registered, and on the job's thread right + // before its handler starts: the plugin unloads just before the asking given here. + const int unload_at = GENERATE(1, 2, 3); + Harness h; + std::atomic<int> asked{0}; + std::atomic<int> ran{0}; + std::atomic<bool> loaded{true}; + h.jobs.set_owner_liveness([&](const std::string&) { + if (++asked == unload_at) + loaded = false; + return loaded.load(); + }); + h.registry.add(tool("make", GuardClass::Mutate, [&](const json&, ToolContext&) { ++ran; return ToolResult::ok(); })); + h.timing.soft_budget = std::chrono::milliseconds(10000); + h.start(); + const ToolResult r = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure"); + CHECK(r.is_error); + CHECK(r.message.find("unloaded") != std::string::npos); + CHECK(ran == 0); + CHECK(h.jobs.running_owned_by("measure").empty()); +} + +TEST_CASE("a plugin's running call is cancelled the moment the plugin unloads", "[Mcp]") +{ + Harness h; + std::atomic<bool> loaded{true}; + std::atomic<bool> started{false}; + h.jobs.set_owner_liveness([&](const std::string&) { return loaded.load(); }); + h.registry.add(tool("spin", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + started = true; + const auto end = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + return ToolResult::ok({{"cancelled", ctx.cancelled()}}); + })); + h.timing.soft_budget = std::chrono::milliseconds(10000); + h.start(); + // No block and no stop request: only the plugin manager's state changes. + std::thread unload([&] { + while (!started) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + loaded = false; + }); + const ToolResult r = h.core->call_plugin(*h.registry.find("spin"), json::object(), "measure"); + unload.join(); + CHECK_FALSE(r.is_error); + CHECK(r.data.value("cancelled", false)); +} + +TEST_CASE("a call under a lineage node sees a stop asked for the node, inline calls included, and a renewed node's calls run", "[Mcp]") +{ + Harness h; + // Polls for cancellation for up to `for_ms`, as wait does. + const auto poll = [](const json& args, ToolContext& ctx) { + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(args.value("for_ms", 5000)); + while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) + std::this_thread::sleep_for(10ms); + return ToolResult::ok({{"cancelled", ctx.cancelled()}}); + }; + NativeCommand inline_poll = tool("inline_poll", GuardClass::Inspect, poll); + inline_poll.inline_call = true; + h.registry.add(inline_poll); + h.registry.add(tool("job_poll", GuardClass::Mutate, poll)); + h.timing.soft_budget = 10000ms; + h.start(); + + const std::string session = h.jobs.create("run_script", ""); + h.jobs.set_idle(session); + LineageNode node(h.jobs, "run_script", session); + const auto call = [&](const char* tool, int for_ms) { + return std::async(std::launch::async, [&h, &node, tool, for_ms] { + return h.core->call_child_named(tool, {{"for_ms", for_ms}}, node.id()); + }); + }; + auto inline_call = call("inline_poll", 5000); + auto job_call = call("job_poll", 5000); + std::this_thread::sleep_for(300ms); + const auto asked = std::chrono::steady_clock::now(); + h.jobs.request_stop(node.id()); + const ToolResult stopped_inline = inline_call.get(); + const ToolResult stopped_job = job_call.get(); + CHECK(std::chrono::steady_clock::now() - asked < 1s); + CHECK(stopped_inline.data.value("cancelled", false)); + CHECK(stopped_job.data.value("cancelled", false)); + + node.renew(); + auto ran_inline = call("inline_poll", 300); + auto ran_job = call("job_poll", 300); + CHECK(ran_inline.get().data["cancelled"] == false); + CHECK(ran_job.get().data["cancelled"] == false); + CHECK_FALSE(h.jobs.stop_requested(session)); + h.jobs.finish(session, ToolResult::ok()); +} + +TEST_CASE("lineage nodes leave no running job behind", "[Mcp]") +{ + JobRegistry jobs; + const std::string session = jobs.create("run_script", ""); + const auto running_nodes = [&] { + int count = 0; + for (const json& job : jobs.list()) + if (job["tool"] == "run_script" && job.value("parent", std::string()) == session && job["state"] == "running") + ++count; + return count; + }; + { + LineageNode node(jobs, "run_script", session); + CHECK(running_nodes() == 1); + } + for (int round = 0; round < 10; ++round) { + LineageNode node(jobs, "run_script", session); + for (int renewal = 0; renewal < 3; ++renewal) + node.renew(); + CHECK(running_nodes() == 1); + } + CHECK(running_nodes() == 0); + jobs.finish(session, ToolResult::ok()); +} + +namespace { + +// Where works wait until the test opens it. +class Gate +{ +public: + void open() + { + { + std::lock_guard<std::mutex> lock(m_mutex); + m_open = true; + } + m_cv.notify_all(); + } + void wait() + { + std::unique_lock<std::mutex> lock(m_mutex); + m_cv.wait(lock, [this] { return m_open; }); + } + +private: + std::mutex m_mutex; + std::condition_variable m_cv; + bool m_open = false; +}; + +// Opens `gate` when the test leaves, failed assertions included, so the threads' destructor joins works that return. +// Declare the gate, then the threads, then this. +struct OpenOnExit +{ + Gate& gate; + ~OpenOnExit() { gate.open(); } +}; + +// Held by a work: what a work holds goes after FollowedThreads counts it as returned, so once this is gone the next +// start() finds the work returned. +struct Released +{ + std::promise<void> gone; + ~Released() { gone.set_value(); } +}; + +} // namespace + +TEST_CASE("a followed thread whose work returned is joined by the next start", "[Mcp]") +{ + Gate gate; + FollowedThreads threads; + OpenOnExit open_on_exit{gate}; + + auto held = std::make_shared<Released>(); + std::future<void> first_gone = held->gone.get_future(); + REQUIRE(threads.start([held = std::move(held)] {})); + REQUIRE(first_gone.wait_for(5s) == std::future_status::ready); + REQUIRE(threads.start([&gate] { gate.wait(); })); + CHECK(threads.size() == 1); + gate.open(); + threads.join_all(); + CHECK(threads.size() == 0); +} + +TEST_CASE("stopping the followed threads reaches only the works still running", "[Mcp]") +{ + Gate gate; + std::atomic<int> first_stops{0}; + std::atomic<int> second_stops{0}; + FollowedThreads threads; + OpenOnExit open_on_exit{gate}; + + auto held = std::make_shared<Released>(); + std::future<void> first_gone = held->gone.get_future(); + REQUIRE(threads.start([held = std::move(held)] {}, [&first_stops] { ++first_stops; })); + REQUIRE(first_gone.wait_for(5s) == std::future_status::ready); + REQUIRE(threads.start([&gate] { gate.wait(); }, [&] { + ++second_stops; + gate.open(); + })); + threads.stop_all(); + // A missed stop fails here rather than hang the join below; the gate opens as the case leaves. + REQUIRE(second_stops == 1); + CHECK(first_stops == 0); + // The second's stop let it return. + threads.join_all(); + CHECK(threads.size() == 0); +} + +TEST_CASE("no followed thread starts after the join", "[Mcp]") +{ + { + FollowedThreads threads; + std::atomic<bool> ran{false}; + threads.join_all(); + CHECK_FALSE(threads.start([&ran] { ran = true; })); + CHECK(threads.size() == 0); + CHECK_FALSE(ran); + } + + // A join that waits for a work refuses starts from its beginning, not once it is done: a start that comes + // before it begins is joined with the rest, and none is left. + Gate gate; + std::atomic<int> late_ran{0}; + FollowedThreads threads; + OpenOnExit open_on_exit{gate}; + REQUIRE(threads.start([&gate] { gate.wait(); })); + std::promise<void> joined; + std::future<void> join_returned = joined.get_future(); + std::thread joiner([&] { + threads.join_all(); + joined.set_value(); + }); + // Only a join that never refuses keeps the loop going this long; it then ends, unrefused, and fails below. + const auto give_up = std::chrono::steady_clock::now() + 30s; + int accepted = 0; + bool refused = false; + while (!refused && std::chrono::steady_clock::now() < give_up) { + if (threads.start([&late_ran] { ++late_ran; })) + ++accepted; + else + refused = true; + } + CHECK(refused); + // Refused while the join still waits for the first work. + CHECK(join_returned.wait_for(0ms) == std::future_status::timeout); + gate.open(); + joiner.join(); + CHECK(join_returned.wait_for(0ms) == std::future_status::ready); + CHECK(late_ran == accepted); + CHECK(threads.size() == 0); +} diff --git a/tests/slic3rutils/test_mcp_http.cpp b/tests/automation/test_mcp_http.cpp similarity index 100% rename from tests/slic3rutils/test_mcp_http.cpp rename to tests/automation/test_mcp_http.cpp diff --git a/tests/automation/test_mcp_paths.cpp b/tests/automation/test_mcp_paths.cpp new file mode 100644 index 0000000000..bb1e8e26a6 --- /dev/null +++ b/tests/automation/test_mcp_paths.cpp @@ -0,0 +1,45 @@ +#include <catch2/catch_test_macros.hpp> + +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "test_utils.hpp" + +#include "libslic3r/Utils.hpp" + +#include <boost/filesystem/operations.hpp> +#include <boost/filesystem/path.hpp> + +#include <string> + +using namespace Slic3r::GUI::Mcp; +namespace fs = boost::filesystem; + +TEST_CASE("files saved without a path go to the run's folder when the command line gave one", "[Mcp]") +{ + ScopedTemporaryDir datadir("orca-mcp"); + // The data folder and the run's folder are process-wide: both go back however the case ends. + struct Restore + { + std::string data_dir = Slic3r::data_dir(); + ~Restore() + { + set_run_output_dir({}); + Slic3r::set_data_dir(data_dir); + } + } restore; + Slic3r::set_data_dir(datadir.string()); + + const fs::path default_dir = output_dir(); + CHECK(default_dir.filename() == "out"); + CHECK(default_dir.parent_path().filename() == "automation"); + CHECK(default_dir.parent_path().parent_path() == datadir.path()); + CHECK(fs::is_directory(default_dir)); + + const fs::path run_dir = datadir.path() / "x"; + REQUIRE_FALSE(fs::exists(run_dir)); + set_run_output_dir(run_dir); + CHECK(output_dir() == run_dir); + CHECK(fs::is_directory(run_dir)); + + set_run_output_dir({}); + CHECK(output_dir() == default_dir); +} diff --git a/tests/automation/test_mcp_protocol.cpp b/tests/automation/test_mcp_protocol.cpp new file mode 100644 index 0000000000..60d4437078 --- /dev/null +++ b/tests/automation/test_mcp_protocol.cpp @@ -0,0 +1,576 @@ +#include <catch2/catch_test_macros.hpp> + +#include "automation_test_utils.hpp" + +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpProtocol.hpp" +#include "slic3r/GUI/Mcp/McpStdioBridge.hpp" + +#include <nlohmann/json.hpp> + +#include <memory> +#include <string> +#include <utility> +#include <vector> + +using namespace Slic3r::GUI; +using namespace Slic3r::GUI::Mcp; +using nlohmann::json; +using Slic3r::GUI::CommandCatalog; +using Slic3r::GUI::CommandSource; +using Slic3r::GUI::NativeCommand; +using Slic3r::GUI::Mcp::Test::DirectCaller; + +namespace { + +struct Fixture +{ + CommandCatalog registry; + DirectCaller caller; + McpProtocol protocol{registry, caller, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", "Use get_app_state first."}}; + + Fixture() + { + NativeCommand echo; + echo.key = "echo"; + echo.listed = true; + echo.description = "Echo text back."; + echo.read_only = true; + echo.idempotent = true; + echo.input_schema = {{"type", "object"}, + {"properties", {{"text", {{"type", "string"}}}}}, + {"required", {"text"}}, + {"additionalProperties", false}}; + echo.run = [](const json& args, ToolContext&) { return ToolResult::ok({{"echo", args["text"]}}); }; + registry.add(echo); + + NativeCommand fail; + fail.key = "fail"; + fail.listed = true; + fail.destructive = true; + fail.open_world = true; + fail.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("it broke", {{"why", "test"}}); }; + registry.add(fail); + } + + PostReply post(const json& msg, const std::string& version = {}, const std::string& method = {}, const std::string& name = {}) + { + return protocol.handle_post(PostRequest{msg.dump(), version, method, name}); + } +}; + +json body(const PostReply& r) { return json::parse(r.body); } + +json modern_params(json params = json::object()) +{ + params["_meta"] = {{"io.modelcontextprotocol/protocolVersion", "2026-07-28"}}; + return params; +} + +} // namespace + +TEST_CASE("initialize echoes a supported client version", "[Mcp]") +{ + Fixture f; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"}, {"params", {{"protocolVersion", "2025-06-18"}}}}); + REQUIRE(r.status == 200); + const json result = body(r)["result"]; + CHECK(result["protocolVersion"] == "2025-06-18"); + CHECK(result["serverInfo"]["name"] == "orcaslicer"); + CHECK(result["capabilities"].contains("tools")); + CHECK(result["instructions"] == "Use get_app_state first."); +} + +TEST_CASE("initialize answers an unsupported version with the latest supported one", "[Mcp]") +{ + Fixture f; + for (const char* requested : {"2025-03-26", "1999-01-01"}) { + const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"}, {"params", {{"protocolVersion", requested}}}}))["result"]; + CHECK(result["protocolVersion"] == "2025-11-25"); + } +} + +TEST_CASE("notifications are accepted with 202 and no body", "[Mcp]") +{ + Fixture f; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"method", "notifications/initialized"}}); + CHECK(r.status == 202); + CHECK(r.body.empty()); +} + +TEST_CASE("tools/list keeps registration order and maps annotations", "[Mcp]") +{ + Fixture f; + const json tools = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/list"}}))["result"]["tools"]; + REQUIRE(tools.size() == 2); + CHECK(tools[0]["name"] == "echo"); + CHECK(tools[1]["name"] == "fail"); + CHECK(tools[0]["annotations"]["readOnlyHint"] == true); + CHECK(tools[0]["annotations"]["idempotentHint"] == true); + CHECK(tools[0]["annotations"]["destructiveHint"] == false); + CHECK(tools[0]["annotations"]["openWorldHint"] == false); + CHECK(tools[1]["annotations"]["readOnlyHint"] == false); + CHECK(tools[1]["annotations"]["destructiveHint"] == true); + CHECK(tools[1]["annotations"]["openWorldHint"] == true); + CHECK(tools[0]["inputSchema"]["required"][0] == "text"); +} + +TEST_CASE("tools/call returns the result as a JSON text block", "[Mcp]") +{ + Fixture f; + const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 3}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"text", "hi"}}}}}}))["result"]; + CHECK_FALSE(result.contains("isError")); + CHECK_FALSE(result.contains("structuredContent")); + REQUIRE(result["content"].size() == 1); + CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"echo", "hi"}}); +} + +TEST_CASE("tool failures and invalid arguments are isError results", "[Mcp]") +{ + Fixture f; + const json failed = body(f.post({{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"}, {"params", {{"name", "fail"}}}}))["result"]; + CHECK(failed["isError"] == true); + CHECK(failed["content"][0]["text"].get<std::string>().find("it broke") != std::string::npos); + + const json bad = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"txt", "hi"}}}}}}))["result"]; + CHECK(bad["isError"] == true); + const std::string text = bad["content"][0]["text"]; + CHECK(text.find("text is required") != std::string::npos); +} + +TEST_CASE("an unknown tool is a JSON-RPC error with suggestions", "[Mcp]") +{ + Fixture f; + const json reply = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, {"params", {{"name", "ecko"}}}})); + CHECK(reply["error"]["code"] == -32602); + CHECK(reply["error"]["data"]["did_you_mean"][0] == "echo"); +} + +TEST_CASE("one edit distance serves every did-you-mean", "[Mcp]") +{ + CHECK(edit_distance("fillet", "filet") == 1); + CHECK(edit_distance("", "abc") == 3); + CHECK(edit_distance("a", "a") == 0); +} + +TEST_CASE("malformed messages are rejected", "[Mcp]") +{ + Fixture f; + PostReply r = f.protocol.handle_post(PostRequest{"{not json", {}, {}, {}}); + CHECK(r.status == 400); + CHECK(body(r)["error"]["code"] == -32700); + + r = f.post(json::array({{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "ping"}}})); + CHECK(r.status == 400); + CHECK(body(r)["error"]["code"] == -32600); + + r = f.post({{"jsonrpc", "2.0"}, {"id", nullptr}, {"method", "ping"}}); + CHECK(body(r)["error"]["code"] == -32600); + + r = f.post({{"jsonrpc", "1.0"}, {"id", 1}, {"method", "ping"}}); + CHECK(body(r)["error"]["code"] == -32600); + + // A jsonrpc that is not a string is the same error, never an exception: the stdio bridge calls + // handle_post directly. + for (const json& version : {json(2), json(nullptr), json::object()}) { + r = f.post({{"jsonrpc", version}, {"id", 1}, {"method", "ping"}}); + CHECK(r.status == 400); + CHECK(body(r)["error"]["code"] == -32600); + } +} + +TEST_CASE("params that are not an object are invalid params", "[Mcp]") +{ + Fixture f; + PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", json::array()}}); + CHECK(body(r)["error"]["code"] == -32602); + r = f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "ping"}, {"params", 3}}); + CHECK(body(r)["error"]["code"] == -32602); +} + +TEST_CASE("the stdio bridge derives no headers from a line that is not a message object", "[Mcp]") +{ + CHECK(bridge_headers(json::array({{{"method", "ping"}}}), "2025-06-18").empty()); + CHECK(bridge_headers(json(42), {}).empty()); + CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", "get_app_state"}}}}, "2025-06-18") + .count("MCP-Protocol-Version") == 1); + // Members of the wrong type are left out rather than thrown on. + CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", 5}}, "").empty()); + CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", 3}}}}, "").count("Mcp-Name") == 0); +} + +TEST_CASE("ping returns an empty result", "[Mcp]") +{ + Fixture f; + CHECK(body(f.post({{"jsonrpc", "2.0"}, {"id", "p"}, {"method", "ping"}}))["result"] == json::object()); +} + +TEST_CASE("a legacy request with an unsupported MCP-Protocol-Version header is 400", "[Mcp]") +{ + Fixture f; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}, "2024-01-01"); + CHECK(r.status == 400); + CHECK(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}, "2025-11-25").status == 200); +} + +TEST_CASE("2026-07-28 server/discover lists versions and capabilities", "[Mcp]") +{ + Fixture f; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "server/discover"}, {"params", modern_params()}}, "2026-07-28", "server/discover"); + REQUIRE(r.status == 200); + const json result = body(r)["result"]; + CHECK(result["resultType"] == "complete"); + CHECK(result["supportedVersions"][0] == "2026-07-28"); + CHECK(result["capabilities"].contains("tools")); + CHECK(result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "orcaslicer"); + CHECK(result.contains("ttlMs")); + CHECK(result.contains("cacheScope")); +} + +TEST_CASE("2026-07-28 results carry resultType complete", "[Mcp]") +{ + Fixture f; + const json list = body(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", modern_params()}}, "2026-07-28", "tools/list"))["result"]; + CHECK(list["resultType"] == "complete"); + CHECK(list.contains("ttlMs")); + CHECK(list.contains("cacheScope")); + + const json call = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/call"}, + {"params", modern_params({{"name", "echo"}, {"arguments", {{"text", "x"}}}})}}, + "2026-07-28", "tools/call", "echo"))["result"]; + CHECK(call["resultType"] == "complete"); +} + +TEST_CASE("2026-07-28 header mismatches are 400 -32020", "[Mcp]") +{ + Fixture f; + const json req{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", modern_params({{"name", "echo"}, {"arguments", {{"text", "x"}}}})}}; + PostReply r = f.post(req, "2026-07-28", "tools/list", "echo"); + CHECK(r.status == 400); + CHECK(body(r)["error"]["code"] == -32020); + + r = f.post(req, "2026-07-28", "tools/call", ""); + CHECK(body(r)["error"]["code"] == -32020); + + r = f.post(req, "", "tools/call", "echo"); + CHECK(body(r)["error"]["code"] == -32020); + + // Mcp-Name may arrive base64-encoded. + r = f.post(req, "2026-07-28", "tools/call", "=?base64?ZWNobw==?="); + CHECK(r.status == 200); +} + +TEST_CASE("2026-07-28 unsupported _meta version is 400 -32022 with the supported list", "[Mcp]") +{ + Fixture f; + json params = modern_params(); + params["_meta"]["io.modelcontextprotocol/protocolVersion"] = "2030-01-01"; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", params}}, "2030-01-01", "tools/list"); + CHECK(r.status == 400); + const json err = body(r)["error"]; + CHECK(err["code"] == -32022); + CHECK(err["data"]["requested"] == "2030-01-01"); + CHECK(err["data"]["supported"][0] == "2026-07-28"); +} + +TEST_CASE("2026-07-28 unknown method is 404 -32601", "[Mcp]") +{ + Fixture f; + const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "resources/list"}, {"params", modern_params()}}, "2026-07-28", "resources/list"); + CHECK(r.status == 404); + CHECK(body(r)["error"]["code"] == -32601); +} + +TEST_CASE("argument validation covers types, enums, ranges and arrays", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", + {{"n", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5}}}, + {"zoom", {{"type", "number"}, {"exclusiveMinimum", 0}}}, + {"mode", {{"type", "string"}, {"enum", {"a", "b"}}}}, + {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}}}, + {"additionalProperties", false}}; + CHECK(validate_arguments(schema, {{"n", 3}, {"mode", "a"}, {"paths", {"x"}}}).empty()); + CHECK(validate_arguments(schema, {{"n", 0}}).find("n must be >= 1") != std::string::npos); + 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); + 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, {{"extra", 1}}).find("unknown argument extra") != std::string::npos); + + // A plugin operation's draft-04 schema gives exclusiveMinimum as a boolean that qualifies minimum. + const json draft4 = {{"type", "object"}, {"properties", {{"zoom", {{"type", "number"}, {"minimum", 0}, {"exclusiveMinimum", true}}}}}}; + std::string draft4_error; + CHECK_NOTHROW(draft4_error = validate_arguments(draft4, {{"zoom", 0.5}})); + CHECK(draft4_error.empty()); +} + +TEST_CASE("argument normalization reads the names agents reach for as the ones a tool takes", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", + {{"target", {{"type", {"string", "object"}}}}, + {"button", {{"type", "string"}}}, + {"objects", {{"type", "array"}, {"items", {{"type", "integer"}}}}}}}, + {"additionalProperties", false}}; + const auto normalized = [&](json args) { + normalize_arguments(schema, args); + return args; + }; + CHECK(normalized({{"ref", "w12"}}) == json{{"target", "w12"}}); + // action stands for id or button, whichever the tool takes. + CHECK(normalized({{"action", "close"}}) == json{{"button", "close"}}); + CHECK(normalized({{"object", 2}}) == json{{"objects", {2}}}); + CHECK(normalized({{"object", "0"}}) == json{{"objects", {0}}}); + // Given both, the call keeps them and validation names the stray one. + const json both = normalized({{"ref", "w12"}, {"target", "w13"}}); + CHECK(both == json{{"ref", "w12"}, {"target", "w13"}}); + CHECK(validate_arguments(schema, both).find("unknown argument ref") != std::string::npos); + // A tool that takes the name itself keeps it. + const json own = {{"type", "object"}, {"properties", {{"text", {{"type", "string"}}}, {"value", {{"type", "string"}}}}}}; + json text{{"text", "abc"}}; + normalize_arguments(own, text); + CHECK(text == json{{"text", "abc"}}); + // Only a value that fits: a click is no button, so the call keeps action for the validator to name. + const json clicks = {{"type", "object"}, + {"properties", {{"button", {{"type", "string"}, {"enum", {"left", "right", "middle"}}}}}}, + {"additionalProperties", false}}; + json click{{"action", "click"}}; + normalize_arguments(clicks, click); + CHECK(click == json{{"action", "click"}}); +} + +TEST_CASE("argument normalization reads a capture's output path as its save_path", "[Mcp]") +{ + const auto normalized = [](const json& properties, json args) { + normalize_arguments({{"type", "object"}, {"properties", properties}, {"additionalProperties", false}}, args); + return args; + }; + // A capture's output file is its save_path; a tool with a path of its own keeps that. + const json capture = {{"save_path", {{"type", "string"}}}}; + CHECK(normalized(capture, {{"path", "/a.png"}}) == json{{"save_path", "/a.png"}}); + const json encode = {{"path", {{"type", "string"}}}, {"save_path", {{"type", "string"}}}}; + CHECK(normalized(encode, {{"path", "/a.mkv"}}) == json{{"path", "/a.mkv"}}); +} + +TEST_CASE("argument normalization leaves a value its enum lacks, and a 3D view under another name, for the validator", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", + {{"scope", {{"type", "string"}, {"enum", {"process", "filament", "part"}}}}, + {"target", {{"type", "string"}, {"enum", {"main", "canvas"}}}}, + {"canvas", {{"type", "string"}, {"enum", {"3d", "preview"}}}}}}, + {"additionalProperties", false}}; + const auto normalized = [&](json args) { + normalize_arguments(schema, args); + return args; + }; + // No value stands for another: the process scope and the main window go by those names alone. + CHECK(normalized({{"scope", "print"}}) == json{{"scope", "print"}}); + CHECK(normalized({{"target", "window"}}) == json{{"target", "window"}}); + CHECK_FALSE(validate_arguments(schema, normalized({{"scope", "print"}})).empty()); + // set_view's 3D view is its canvas. + const json view = normalized({{"view", "preview"}}); + CHECK(view == json{{"view", "preview"}}); + CHECK(validate_arguments(schema, view).find("unknown argument view") != std::string::npos); +} + +TEST_CASE("argument normalization reads values written in another JSON form", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", + {{"n", {{"type", "integer"}}}, + {"flag", {{"type", "boolean"}}}, + {"plate", {{"type", {"string", "integer"}}}}, + {"point", {{"type", "array"}, {"items", {{"type", "number"}}}}}, + {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}, + {"name", {{"type", "string"}}}}}, + {"additionalProperties", false}}; + json args{{"n", "3"}, {"flag", "true"}, {"plate", "1"}, {"point", "[1, 2.5, 3]"}, {"paths", "/a.stl"}, {"name", "7"}}; + normalize_arguments(schema, args); + CHECK(args["n"] == 3); + CHECK(args["flag"] == true); + CHECK(args["plate"] == 1); + CHECK(args["point"] == json{1, 2.5, 3}); + CHECK(args["paths"] == json{"/a.stl"}); + // A string where a string goes stays one. + CHECK(args["name"] == "7"); + CHECK(validate_arguments(schema, args).empty()); + + json kept{{"plate", "all"}, {"n", "2.5"}}; + normalize_arguments(schema, kept); + CHECK(kept["plate"] == "all"); + CHECK(validate_arguments(schema, kept).find("n must be of type integer") != std::string::npos); +} + +TEST_CASE("argument normalization moves a value outside its enum to the argument whose enum takes it", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", + {{"view", {{"type", "string"}, {"enum", {"3d", "preview"}}}}, + {"camera", {{"type", "string"}, {"enum", {"front", "top", "fit"}}}}, + {"tab", {{"type", "string"}, {"enum", {"prepare", "preview"}}}}}}, + {"additionalProperties", false}}; + json moved{{"view", "front"}}; + normalize_arguments(schema, moved); + CHECK(moved == json{{"camera", "front"}}); + + // Both given: the call names its camera, so view's value is an error, not a second camera. + json both{{"view", "front"}, {"camera", "fit"}}; + normalize_arguments(schema, both); + CHECK(both["view"] == "front"); + CHECK(validate_arguments(schema, both).find("view must be one of") != std::string::npos); + + // A value of its own enum stays, even where another enum also takes it. + json own{{"view", "preview"}}; + normalize_arguments(schema, own); + CHECK(own == json{{"view", "preview"}}); + + // Taken by no other enum: left for the validator. + json unknown{{"view", "sideways"}}; + normalize_arguments(schema, unknown); + CHECK(unknown == json{{"view", "sideways"}}); +} + +TEST_CASE("pairs list_windows reports are read as position and size", "[Mcp]") +{ + const json schema = {{"type", "object"}, + {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "integer"}}}}}, + {"size", {{"type", "array"}, {"items", {{"type", "integer"}}}}}}}, + {"additionalProperties", false}}; + json flat{{"x", 10}, {"y", 20}, {"width", 800}, {"height", 600}}; + normalize_arguments(schema, flat); + CHECK(flat == json{{"position", {10, 20}}, {"size", {800, 600}}}); + json half{{"x", 10}}; + normalize_arguments(schema, half); + CHECK(half == json{{"x", 10}}); // left for the validator to name + json given{{"x", 1}, {"y", 2}, {"position", {3, 4}}}; + normalize_arguments(schema, given); + CHECK(given["position"] == json{3, 4}); // never replaces a given argument + const json own = {{"type", "object"}, {"properties", {{"x", {{"type", "integer"}}}, {"y", {{"type", "integer"}}}}}}; + json kept{{"x", 1}, {"y", 2}}; + normalize_arguments(own, kept); + CHECK(kept == json{{"x", 1}, {"y", 2}}); // a tool that takes x and y keeps them +} + +TEST_CASE("a position or size in mm, an array of numbers, takes no pair list_windows reports", "[Mcp]") +{ + // add_part's position and size, and transform's position. + const json schema = {{"type", "object"}, + {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "number"}}}}}, + {"size", {{"type", "array"}, {"items", {{"type", "number"}}}}}}}, + {"additionalProperties", false}}; + const json flat{{"x", 10}, {"y", 20}, {"width", 30}, {"height", 5}}; + json args = flat; + normalize_arguments(schema, args); + CHECK(args == flat); + CHECK(validate_arguments(schema, args).find("unknown argument") != std::string::npos); + // transform's size, whose null keeps an axis. + const json nullable = {{"type", "object"}, + {"properties", {{"size", {{"type", "array"}, {"items", {{"type", {"number", "null"}}}}}}}}, + {"additionalProperties", false}}; + json sized{{"width", 30}, {"height", 5}}; + normalize_arguments(nullable, sized); + CHECK(sized == json{{"width", 30}, {"height", 5}}); +} + +TEST_CASE("an unknown tool is answered with the closest names", "[Mcp]") +{ + Fixture f; + const json direct = body(f.post({{"jsonrpc", "2.0"}, {"id", 7}, {"method", "tools/call"}, {"params", {{"name", "no_such_tool"}}}})); + CHECK(direct["error"]["message"] == "Unknown tool: no_such_tool"); + + NativeCommand api; + api.key = "call_tool"; + api.input_schema = {{"type", "object"}, + {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, + {"required", {"tool"}}}; + api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; + f.registry.add(api); + // call_tool's target names the closest command, and nothing else. + const json typo = body(f.post({{"jsonrpc", "2.0"}, {"id", 9}, {"method", "tools/call"}, + {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; + CHECK(typo["isError"] == true); + CHECK(typo["content"][0]["text"] == "Unknown tool: ech (did you mean echo?)"); +} + +TEST_CASE("a call's arguments are normalized, then validated", "[Mcp]") +{ + NativeCommand capture; + capture.key = "screenshot"; + capture.input_schema = {{"type", "object"}, + {"properties", {{"target", {{"type", "string"}}}, {"save_path", {{"type", "string"}}}}}, + {"additionalProperties", false}}; + // A name agents reach for is read as the one the tool takes. + json aliased{{"path", "/a.png"}}; + CHECK(argument_error(capture, aliased).empty()); + CHECK(aliased == json{{"save_path", "/a.png"}}); + // An argument the tool does not take is refused with the ones it does. + json unknown{{"colour", "red"}}; + const std::string refused = argument_error(capture, unknown); + CHECK(refused.find("unknown argument colour") != std::string::npos); + CHECK(refused.find("save_path") != std::string::npos); +} + +TEST_CASE("call_tool runs and is journaled as the tool it names", "[Mcp]") +{ + Fixture f; + NativeCommand api; + api.key = "call_tool"; + api.input_schema = {{"type", "object"}, + {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, + {"required", {"tool"}}}; + api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; + f.registry.add(api); + + const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"}, + {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", {{"text", "hi"}}}}}}}}))["result"]; + CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"echo", "hi"}}); + REQUIRE(f.caller.called.size() == 1); + CHECK(f.caller.called.back() == "echo"); + + // The target's arguments are checked against its schema, and an unknown tool is named. + const json invalid = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, + {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", json::object()}}}}}}))["result"]; + CHECK(invalid["isError"] == true); + const json unknown = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, + {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; + CHECK(unknown["isError"] == true); + CHECK(unknown["content"][0]["text"].get<std::string>().find("did you mean echo") != std::string::npos); +} + +// Holds the one operation a plugin offers while it is loaded. +class MeasureSource final : public CommandSource +{ +public: + MeasureSource() + { + auto area = std::make_shared<NativeCommand>(); + area->key = "plugin.measure.area"; + area->run = [](const json&, ToolContext&) { return ToolResult::ok({{"area", 12.5}}); }; + m_area = std::move(area); + } + std::shared_ptr<const NativeCommand> find(const std::string& key) const override { return key == m_area->key ? m_area : nullptr; } + std::vector<std::shared_ptr<const NativeCommand>> all() const override { return {m_area}; } + +private: + std::shared_ptr<const NativeCommand> m_area; +}; + +TEST_CASE("a name the table lacks resolves through a source, without being listed", "[Mcp]") +{ + Fixture f; + f.registry.add_source(std::make_unique<MeasureSource>()); + REQUIRE(f.registry.lookup("plugin.measure.area") != nullptr); + CHECK(f.registry.lookup("plugin.measure.volume") == nullptr); + CHECK(f.registry.lookup("echo")->key == "echo"); + const json tools = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/list"}}))["result"]["tools"]; + for (const json& t : tools) + CHECK(t["name"] != "plugin.measure.area"); + const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 3}, {"method", "tools/call"}, + {"params", {{"name", "plugin.measure.area"}, {"arguments", json::object()}}}}))["result"]; + CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"area", 12.5}}); +} diff --git a/tests/slic3rutils/test_mcp_replay.cpp b/tests/automation/test_mcp_replay.cpp similarity index 99% rename from tests/slic3rutils/test_mcp_replay.cpp rename to tests/automation/test_mcp_replay.cpp index 4373f194f2..f99ccae91c 100644 --- a/tests/slic3rutils/test_mcp_replay.cpp +++ b/tests/automation/test_mcp_replay.cpp @@ -2,11 +2,12 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/McpReplay.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include <nlohmann/json.hpp> +#include <cstddef> #include <cstdlib> #include <functional> #include <map> @@ -20,6 +21,7 @@ #include <stdlib.h> // setenv #endif +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; diff --git a/tests/slic3rutils/test_mcp_replay_summary.cpp b/tests/automation/test_mcp_replay_summary.cpp similarity index 89% rename from tests/slic3rutils/test_mcp_replay_summary.cpp rename to tests/automation/test_mcp_replay_summary.cpp index 07976803b9..cca9b132c2 100644 --- a/tests/slic3rutils/test_mcp_replay_summary.cpp +++ b/tests/automation/test_mcp_replay_summary.cpp @@ -2,6 +2,7 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/Mcp/McpReplay.hpp" #include "slic3r/GUI/Mcp/McpReplaySummary.hpp" @@ -9,10 +10,13 @@ #include <optional> #include <string> +#include <utility> #include <vector> using namespace Slic3r::GUI::Mcp; using nlohmann::json; +using Slic3r::GUI::CommandCatalog; +using Slic3r::GUI::NativeCommand; namespace { @@ -20,6 +24,22 @@ using Flags = std::vector<std::string>; const Flags kEveryFlag{"writes_file", "changes_presets", "replaces_project", "sends_to_printer"}; +// The commands the cases call by their key, each with a tile and no place in the tool list, as the app's catalog +// has them. Every other tool the cases name is a typed tool, which the summary describes by its name. +CommandCatalog tile_catalog() +{ + CommandCatalog catalog; + for (const char* key : {"load_project", "export_stl", "sync_presets"}) { + NativeCommand command; + command.key = key; + command.in_palette = true; + command.listed = false; + catalog.add(std::move(command)); + } + catalog.seal(); + return catalog; +} + // Describes the one step of a replay built around `step`, run from C:/replays with output in C:/out. StepDescription describe(const std::string& step, const std::string& vars = "{}") { @@ -30,7 +50,7 @@ StepDescription describe(const std::string& step, const std::string& vars = "{}" ReplayContext ctx; ctx.replay_dir = "C:/replays"; ctx.out_dir = "C:/out"; - return describe_step(replay->steps[0], *replay, ctx); + return describe_step(tile_catalog(), replay->steps[0], *replay, ctx); } Flags flags_of(const StepDescription& d) @@ -118,7 +138,34 @@ TEST_CASE("a command called by name is described as its tile is", "[Mcp]") CHECK(flags_of(by_name) == flags_of(tile)); CHECK(by_name.replace == tile.replace); CHECK(by_name.what == tile.what); - CHECK(describe_call(key, args) == tile.what); + CHECK(describe_call(tile_catalog(), key, args) == tile.what); +} + +TEST_CASE("a step that calls a tile's command by its key is described from the catalog it is given", "[Mcp]") +{ + std::string err; + const auto replay = parse_replay(R"({"orca_replay": 1, "steps": [{"tool": "export_stl", "args": {"path": "C:/a.stl"}}]})", err); + INFO(err); + REQUIRE(replay.has_value()); + ReplayContext ctx; + ctx.out_dir = "C:/out"; + + CommandCatalog catalog; + NativeCommand export_stl; + export_stl.key = "export_stl"; + export_stl.in_palette = true; + export_stl.listed = false; + catalog.add(std::move(export_stl)); + catalog.seal(); + const StepDescription tile = describe_step(catalog, replay->steps[0], *replay, ctx); + REQUIRE(tile.what.is_object()); + CHECK(tile.what.value("kind", "") == "command"); + CHECK(tile.what.value("key", "") == "export_stl"); + + // Without the command in the catalog, the step is described from its arguments, as a typed tool's call is. + const StepDescription unknown = describe_step(CommandCatalog(), replay->steps[0], *replay, ctx); + const std::string kind = unknown.what.is_object() ? unknown.what.value("kind", "") : std::string(); + CHECK(kind != "command"); } TEST_CASE("speed dial actions are flagged by their id", "[Mcp]") @@ -310,8 +357,8 @@ TEST_CASE("saved jobs don't change a step's flags", "[Mcp]") without.out_dir = "C:/out"; ReplayContext with = without; with.jobs = json{{"p", "j12"}}; - const StepDescription a = describe_step(replay->steps[0], *replay, without); - const StepDescription b = describe_step(replay->steps[0], *replay, with); + const StepDescription a = describe_step(tile_catalog(), replay->steps[0], *replay, without); + const StepDescription b = describe_step(tile_catalog(), replay->steps[0], *replay, with); CHECK(flags_of(a) == flags_of(b)); CHECK(a.replace == b.replace); CHECK(a.answers_dialogs == b.answers_dialogs); diff --git a/tests/slic3rutils/test_mcp_setup.cpp b/tests/automation/test_mcp_setup.cpp similarity index 100% rename from tests/slic3rutils/test_mcp_setup.cpp rename to tests/automation/test_mcp_setup.cpp diff --git a/tests/slic3rutils/test_mcp_token.cpp b/tests/automation/test_mcp_token.cpp similarity index 100% rename from tests/slic3rutils/test_mcp_token.cpp rename to tests/automation/test_mcp_token.cpp diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index 309c209a24..5fb3ba592b 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -2915,7 +2915,7 @@ }, { "completion": "none", - "description": "Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python (available: Python runs in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts), design_tab (the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D view it belongs to), slicing state, the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown (camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What is going on: open modal dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running recording.", + "description": "Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python (available: Python runs in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run with --unrestricted-scripts), design_tab (the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D view it belongs to), slicing state, the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown (camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What is going on: open modal dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running recording.", "destructive": false, "group": "core", "guard": "inspect", diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index ae3948a7b3..02b21ac78a 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -743,6 +743,19 @@ TEST_CASE("load_from_json hands a preset's include list to the caller instead of CHECK(config.opt_string("machine_end_gcode") == "M84"); } +TEST_CASE("the command line has one run option and no MCP-named one", "[Config]") { + CHECK(cli_misc_config_def.has("run")); + CHECK(cli_misc_config_def.has("unrestricted_scripts")); + CHECK(cli_misc_config_def.has("cad")); + CHECK(cli_misc_config_def.has("outputdir")); + CHECK_FALSE(cli_misc_config_def.has("mcp_run")); + CHECK_FALSE(cli_misc_config_def.has("mcp_run_out")); + CHECK_FALSE(cli_misc_config_def.has("mcp_token")); + CHECK(cli_misc_config_def.has("mcp")); + CHECK(cli_misc_config_def.has("mcp_port")); + CHECK(cli_misc_config_def.has("mcp_stdio")); +} + TEST_CASE("save_to_json writes the same document to a stream as to a file", "[Config]") { DynamicPrintConfig config; config.set_key_value("layer_height", new ConfigOptionFloat(0.2)); diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 42f01c9351..a0901bb4b6 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -30,15 +30,10 @@ add_executable(${_TEST_NAME}_tests test_lazy.cpp test_mcp_config.cpp test_mcp_core.cpp - test_mcp_http.cpp test_operations.cpp test_mcp_protocol.cpp test_mcp_recording.cpp - test_mcp_replay.cpp - test_mcp_replay_summary.cpp test_mcp_scene.cpp - test_mcp_setup.cpp - test_mcp_token.cpp test_mcp_tools.cpp test_mcp_ui.cpp test_mcp_web.cpp diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index bad9f4af6f..5a70b74c3d 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -3,11 +3,14 @@ #include <catch2/matchers/catch_matchers.hpp> #include <catch2/matchers/catch_matchers_string.hpp> +#include "automation/automation_test_utils.hpp" + #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpPersonContext.hpp" #include "slic3r/GUI/Mcp/McpProtocol.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" @@ -29,33 +32,34 @@ #include <utility> #include <vector> +// The catalog's cases that need the GUI library: the process catalog NativeCommands builds, the commands its +// helpers make, and a person's context. The others are in tests/automation/test_command_catalog.cpp. + using Catch::Matchers::ContainsSubstring; using nlohmann::json; using Slic3r::GUI::AppActionRunResult; using Slic3r::GUI::CommandCatalog; using Slic3r::GUI::CommandCompletion; using Slic3r::GUI::CommandFn; -using Slic3r::GUI::CommandSource; +using Slic3r::GUI::GuardClass; using Slic3r::GUI::NativeCommand; +using Slic3r::GUI::ToolCaller; +using Slic3r::GUI::ToolContext; +using Slic3r::GUI::ToolFailure; +using Slic3r::GUI::ToolResult; +using Slic3r::GUI::Mcp::Test::command; +using Slic3r::GUI::Mcp::Test::OneCommandSource; namespace Mcp = Slic3r::GUI::Mcp; namespace NativeCommands = Slic3r::GUI::NativeCommands; namespace Ops = Slic3r::GUI::Ops; namespace { -NativeCommand command(std::string key, bool in_palette = false) -{ - NativeCommand c; - c.key = std::move(key); - c.in_palette = in_palette; - return c; -} - json no_arguments() { return {{"type", "object"}, {"properties", json::object()}}; } // A call's context without the MCP core: UI closures run in place and nothing is left to wait for. It // counts the operations a call begins and records the commands it submits as jobs. -class TestContext final : public Mcp::ToolContext +class TestContext final : public ToolContext { public: explicit TestContext(bool person = false) : m_person(person) {} @@ -65,14 +69,14 @@ public: json observe_ui(const std::function<json()>& /*fn*/) override { return true; } const std::string& job_id() const override { return m_job; } bool cancelled() const override { return false; } - Mcp::ToolResult call_child(const std::string& /*tool*/, const json& /*args*/) override { return Mcp::ToolResult::error("no child calls"); } + ToolResult call_child(const std::string& /*tool*/, const json& /*args*/) override { return ToolResult::error("no child calls"); } std::set<std::string> lineage() const override { return {}; } void set_journal_args(json args) override { journaled = std::move(args); } void begin_operation() override { ++operations; } - Mcp::ToolResult submit(const std::string& key, const json& /*args*/) override + ToolResult submit(const std::string& key, const json& /*args*/) override { submitted.push_back(key); - return Mcp::ToolResult::ok(); + return ToolResult::ok(); } int operations = 0; @@ -84,22 +88,6 @@ private: std::string m_job; }; -// Holds one command, as a plugin's operations are held while it is loaded. -class OneCommandSource final : public CommandSource -{ -public: - explicit OneCommandSource(std::string key) : m_command(std::make_shared<const NativeCommand>(command(std::move(key)))) {} - - std::shared_ptr<const NativeCommand> find(const std::string& key) const override - { - return key == m_command->key ? m_command : nullptr; - } - std::vector<std::shared_ptr<const NativeCommand>> all() const override { return {m_command}; } - -private: - std::shared_ptr<const NativeCommand> m_command; -}; - std::vector<std::string> keys_of(const std::vector<NativeCommand>& commands) { std::vector<std::string> keys; @@ -153,71 +141,6 @@ std::string first_difference(const std::string& actual, const std::string& expec } // namespace -TEST_CASE("a key added twice is refused", "[CommandCatalog]") -{ - CommandCatalog catalog; - catalog.add(command("a")); - CHECK_THROWS_AS(catalog.add(command("a")), std::logic_error); - CHECK(catalog.commands().size() == 1); -} - -TEST_CASE("a sealed catalog refuses additions", "[CommandCatalog]") -{ - CommandCatalog catalog; - catalog.add(command("a")); - CHECK_FALSE(catalog.sealed()); - catalog.seal(); - CHECK(catalog.sealed()); - CHECK_THROWS_AS(catalog.add(command("b")), std::logic_error); - CHECK_THROWS_AS(catalog.add_source(std::make_unique<OneCommandSource>("plugin.x.y")), std::logic_error); - CHECK(catalog.find("b") == nullptr); -} - -TEST_CASE("find sees added commands, lookup also a source's", "[CommandCatalog]") -{ - CommandCatalog catalog; - catalog.add(command("slice")); - catalog.add_source(std::make_unique<OneCommandSource>("plugin.x.y")); - catalog.seal(); - - CHECK(catalog.find("plugin.x.y") == nullptr); - const std::shared_ptr<const NativeCommand> from_source = catalog.lookup("plugin.x.y"); - REQUIRE(from_source != nullptr); - CHECK(from_source->key == "plugin.x.y"); - - const NativeCommand* added = catalog.find("slice"); - REQUIRE(added != nullptr); - CHECK(catalog.lookup("slice").get() == added); - - CHECK(catalog.lookup("plugin.x.z") == nullptr); - REQUIRE(catalog.source_commands().size() == 1); - CHECK(catalog.source_commands().front()->key == "plugin.x.y"); -} - -TEST_CASE("commands keep the order they were added in", "[CommandCatalog]") -{ - CommandCatalog catalog; - for (const char* key : {"c", "a", "b"}) - catalog.add(command(key)); - catalog.seal(); - CHECK(keys_of(catalog.commands()) == std::vector<std::string>{"c", "a", "b"}); -} - -TEST_CASE("a Design command's title is translated in the Design context, any other's in none", "[CommandCatalog]") -{ - NativeCommand design; - design.key = "shell"; - design.title = "Shell"; - design.group = Slic3r::GUI::kDesignGroup; - REQUIRE(Slic3r::GUI::title_context(design) != nullptr); - CHECK(std::string(Slic3r::GUI::title_context(design)) == "Design"); - NativeCommand other; - other.key = "save_project"; - other.title = "Save project"; - other.group = "Commands"; - CHECK(Slic3r::GUI::title_context(other) == nullptr); -} - TEST_CASE("the process catalog's palette is the Speed Dial's commands", "[CommandCatalog]") { const CommandCatalog& catalog = NativeCommands::instance(); @@ -333,9 +256,9 @@ TEST_CASE("a merged command's call with no arguments is the person's form", "[Co { int tool_calls = 0, person_calls = 0; const json schema{{"type", "object"}, {"properties", {{"path", {{"type", "string"}}}}}, {"required", {"path"}}}; - const auto tool = NativeCommands::long_command("k", "K", "", schema, [&tool_calls](const json&, Mcp::ToolContext&) { + const auto tool = NativeCommands::long_command("k", "K", "", schema, [&tool_calls](const json&, ToolContext&) { ++tool_calls; - return Mcp::ToolResult::ok({{"tool", true}}); + return ToolResult::ok({{"tool", true}}); }); const NativeCommand merged = NativeCommands::with_person_form(tool, "K", "Commands", "menu_save", [&person_calls] { ++person_calls; @@ -348,11 +271,11 @@ TEST_CASE("a merged command's call with no arguments is the person's form", "[Co CHECK(merged.input_schema["properties"].contains("silent")); TestContext agent; - const Mcp::ToolResult asked = merged.run(json::object(), agent); + const ToolResult asked = merged.run(json::object(), agent); CHECK(person_calls == 1); CHECK(tool_calls == 0); CHECK(asked.data["ran"] == "k"); - const Mcp::ToolResult given = merged.run({{"path", "a"}}, agent); + const ToolResult given = merged.run({{"path", "a"}}, agent); CHECK(person_calls == 1); CHECK(tool_calls == 1); CHECK(given.data["tool"] == true); @@ -361,10 +284,10 @@ TEST_CASE("a merged command's call with no arguments is the person's form", "[Co TEST_CASE("an agent's call of a person's form is checked as a mutate call, a person's is not", "[CommandCatalog]") { int person_calls = 0; - auto tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json&, Mcp::ToolContext&) { - return Mcp::ToolResult::ok(); + auto tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json&, ToolContext&) { + return ToolResult::ok(); }); - tool.guard = Mcp::GuardClass::Inspect; // as the recording tools run, behind dialogs + tool.guard = GuardClass::Inspect; // as the recording tools run, behind dialogs const auto person = [&person_calls] { ++person_calls; return AppActionRunResult{AppActionRunResult::Level::Success, "Asked"}; @@ -372,8 +295,8 @@ TEST_CASE("an agent's call of a person's form is checked as a mutate call, a per const NativeCommand opens = NativeCommands::with_person_form(tool, "K", "Commands", "", person); const NativeCommand quiet = NativeCommands::with_person_form(tool, "K", "Commands", "", person, /*person_form_behind_dialogs=*/true); - // An agent's call asks the service's UI for the mutate check before the person's form runs: a context - // without a service refuses it, and the form never runs. + // An agent's call asks the runtime's UI for the mutate check before the person's form runs: a context + // without a runtime refuses it, and the form never runs. TestContext agent; CHECK_THROWS_AS(opens.run(json::object(), agent), std::logic_error); CHECK(person_calls == 0); @@ -390,9 +313,9 @@ TEST_CASE("an agent's call of a person's form is checked as a mutate call, a per TEST_CASE("a silent call is journaled silent", "[CommandCatalog]") { - const NativeCommand tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json& args, Mcp::ToolContext& ctx) { + const NativeCommand tool = NativeCommands::long_command("k", "K", "", no_arguments(), [](const json& args, ToolContext& ctx) { ctx.set_journal_args(args); - return Mcp::ToolResult::ok(); + return ToolResult::ok(); }); const NativeCommand merged = NativeCommands::with_person_form(tool, "K", "Commands", "", [] { return AppActionRunResult{}; }); @@ -408,13 +331,13 @@ TEST_CASE("a recording started with arguments lasts an hour by default", "[Comma CHECK_THAT(start->input_schema["properties"]["max_seconds"]["description"].get<std::string>(), ContainsSubstring("default 3600")); } -TEST_CASE("the catalog needs no service", "[CommandCatalog]") +TEST_CASE("the catalog needs no runtime", "[CommandCatalog]") { - // No McpService is made in this test: the catalog is built without one, and its listing is the tool list. + // No AutomationRuntime is made in this test: the catalog is built without one, and its listing is the tool list. const CommandCatalog& catalog = NativeCommands::instance(); - struct NoApp final : Mcp::ToolCaller + struct NoApp final : ToolCaller { - Mcp::ToolResult call(const NativeCommand&, const json&) override { return Mcp::ToolResult::error("no app"); } + ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("no app"); } } caller; Mcp::McpProtocol protocol(catalog, caller, Mcp::ServerInfo{}); const Mcp::PostReply reply = protocol.handle_post({json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}.dump(), {}, {}, {}}); @@ -462,7 +385,7 @@ TEST_CASE("a command the catalog leaves out is unknown with the reason", "[Comma 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"); + "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"); } #else CHECK(no_cad.left_out("extrude") == nullptr); @@ -556,31 +479,6 @@ TEST_CASE("a sealed catalog is read from eight threads", "[CommandCatalog]") CHECK(first[4].found == nullptr); } -TEST_CASE("the person's form is the call with no arguments", "[CommandCatalog]") -{ - CHECK(Mcp::person_form(json::object())); - CHECK(Mcp::person_form(json())); - CHECK_FALSE(Mcp::person_form({{"silent", true}})); - CHECK_FALSE(Mcp::person_form({{"path", "a"}})); - CHECK(Mcp::silent_args({{"silent", true}, {"path", "a"}}) == json{{"path", "a"}}); -} - -TEST_CASE("a two-form schema requires its arguments only when some are given", "[CommandCatalog]") -{ - const json s = Mcp::with_silent({{"type", "object"}, - {"properties", {{"path", {{"type", "string"}}}, {"overwrite", {{"type", "boolean"}}}}}, - {"required", {"path"}}, - {"additionalProperties", false}}); - CHECK_FALSE(s.contains("required")); - CHECK(s["then"]["required"] == json::array({"path"})); - CHECK(s["properties"]["silent"]["enum"] == json::array({true})); - CHECK(Mcp::validate_arguments(s, json::object()).empty()); - CHECK(Mcp::validate_arguments(s, {{"path", "a"}}).empty()); - CHECK_THAT(Mcp::validate_arguments(s, {{"overwrite", true}}), ContainsSubstring("path")); - CHECK_THAT(Mcp::validate_arguments(s, {{"silent", true}}), ContainsSubstring("path")); - CHECK_THAT(Mcp::validate_arguments(s, {{"silent", false}}), ContainsSubstring("silent")); -} - TEST_CASE("a person's pick runs the function in place", "[CommandCatalog]") { int calls = 0; @@ -589,7 +487,7 @@ TEST_CASE("a person's pick runs the function in place", "[CommandCatalog]") return AppActionRunResult{AppActionRunResult::Level::Success, "Done"}; }); Mcp::PersonContext person; - const Mcp::ToolResult result = c.run(json::object(), person); + const ToolResult result = c.run(json::object(), person); CHECK(calls == 1); REQUIRE(result.notice != nullptr); CHECK(result.notice->level == AppActionRunResult::Level::Success); @@ -599,9 +497,9 @@ TEST_CASE("a person's pick runs the function in place", "[CommandCatalog]") TEST_CASE("a long command picked by a person is submitted", "[CommandCatalog]") { int calls = 0; - const CommandFn fn = [&calls](const json&, Mcp::ToolContext&) { + const CommandFn fn = [&calls](const json&, ToolContext&) { ++calls; - return Mcp::ToolResult::ok(); + return ToolResult::ok(); }; TestContext person(true); NativeCommands::long_command("k", "K", "Commands", no_arguments(), fn).run(json::object(), person); @@ -626,7 +524,7 @@ TEST_CASE("a person's submit refuses an unknown command, and starts no job witho // The lookup comes first; starting the runtime, the job and its notices need the app, which no unit test runs. Mcp::PersonContext person; CHECK_THROWS_WITH(person.submit("no_such_command", json::object()), ContainsSubstring("Unknown command no_such_command")); - CHECK_THROWS_AS(person.submit("run_script", json::object()), Mcp::ToolFailure); + CHECK_THROWS_AS(person.submit("run_script", json::object()), ToolFailure); } TEST_CASE("an Export command called with arguments takes the project, and with none does not", "[CommandCatalog]") @@ -636,7 +534,7 @@ TEST_CASE("an Export command called with arguments takes the project, and with n CHECK(exporting.completion == CommandCompletion::Export); TestContext given; - const Mcp::ToolResult refused = exporting.run({{"path", "a.gcode"}}, given); + const ToolResult refused = exporting.run({{"path", "a.gcode"}}, given); CHECK(given.operations == 1); CHECK(refused.is_error); CHECK(refused.message == "Nothing to export"); @@ -668,7 +566,7 @@ TEST_CASE("a rename to an empty name is refused before anything is renamed", "[C REQUIRE(rename != nullptr); // No app runs here: the refusal comes before the command looks at the object list. TestContext agent; - const Mcp::ToolResult refused = rename->run({{"name", ""}}, agent); + const ToolResult refused = rename->run({{"name", ""}}, agent); CHECK(refused.is_error); CHECK_THAT(refused.message, ContainsSubstring("name")); } @@ -702,7 +600,7 @@ TEST_CASE("a person's undo shows nothing where the Edit menu's is greyed, an age const NativeCommand* command = NativeCommands::find(key); REQUIRE(command != nullptr); TestContext person(true); - const Mcp::ToolResult picked = command->run(design, person); + const ToolResult picked = command->run(design, person); REQUIRE(picked.notice != nullptr); CHECK(picked.notice->message.empty()); CHECK(picked.notice->level != AppActionRunResult::Level::Error); @@ -710,14 +608,14 @@ TEST_CASE("a person's undo shows nothing where the Edit menu's is greyed, an age CHECK_FALSE(picked.notice->done); // An agent's call reaches the Design history's gate, which says why it cannot run. TestContext agent; - CHECK_THROWS_AS(command->run(design, agent), Mcp::ToolFailure); + CHECK_THROWS_AS(command->run(design, agent), ToolFailure); } } TEST_CASE("a command's result reads as run_action's did", "[CommandCatalog]") { using Level = AppActionRunResult::Level; - const Mcp::ToolResult done = NativeCommands::from_run_result("k", {Level::Success, "Done"}); + const ToolResult done = NativeCommands::from_run_result("k", {Level::Success, "Done"}); CHECK_FALSE(done.is_error); CHECK(done.data == json{{"ran", "k"}, {"level", "success"}, {"message", "Done"}}); CHECK(NativeCommands::from_run_result("k", {Level::Busy, "Wait"}).is_error); @@ -726,7 +624,7 @@ TEST_CASE("a command's result reads as run_action's did", "[CommandCatalog]") CHECK(NativeCommands::from_run_result("k", {Level::Info, "Select an object first.", false}).is_error); // What a command adds to its reply joins the reply's fields. - const Mcp::ToolResult ordered = NativeCommands::from_run_result("k", {Level::Success, {}, true, R"({"descending": true})"}); + const ToolResult ordered = NativeCommands::from_run_result("k", {Level::Success, {}, true, R"({"descending": true})"}); CHECK(ordered.data == json{{"ran", "k"}, {"level", "success"}, {"descending", true}}); Ops::Refusal why; @@ -734,7 +632,7 @@ TEST_CASE("a command's result reads as run_action's did", "[CommandCatalog]") why.msgid = "There are no objects."; AppActionRunResult refused{Level::Error, "translated", false}; refused.refusal = std::make_shared<const Ops::Refusal>(why); - const Mcp::ToolResult failed = NativeCommands::from_run_result("k", refused); + const ToolResult failed = NativeCommands::from_run_result("k", refused); CHECK(failed.is_error); CHECK(failed.message == "There are no objects."); CHECK(failed.data["code"] == "no_objects"); @@ -805,9 +703,9 @@ TEST_CASE("the reference leaves out nothing a client is told", "[CommandCatalog] CHECK(entry["open_world"] == annotations["openWorldHint"]); } // The entries marked listed are the tools a client's tools/list names. - struct NoApp final : Mcp::ToolCaller + struct NoApp final : ToolCaller { - Mcp::ToolResult call(const NativeCommand&, const json&) override { return Mcp::ToolResult::error("no app"); } + ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("no app"); } } caller; Mcp::McpProtocol protocol(catalog, caller, Mcp::ServerInfo{}); const Mcp::PostReply reply = protocol.handle_post({json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}.dump(), {}, {}, {}}); @@ -820,45 +718,6 @@ TEST_CASE("the reference leaves out nothing a client is told", "[CommandCatalog] CHECK(listed == tools); } -TEST_CASE("a reference entry has the command's fields, and its examples only when it has some", "[CommandCatalog][Reference]") -{ - NativeCommand c = command("export_it", true); - c.title = "Export It"; - c.group = "Commands"; - c.description = "Exports it."; - c.input_schema = {{"type", "object"}, {"properties", {{"path", {{"type", "string"}}}}}}; - c.guard = Mcp::GuardClass::Recover; - c.completion = CommandCompletion::Export; - c.operations = {"export_gcode"}; - c.open_world = true; - const json entry = Slic3r::GUI::command_reference(c); - CHECK(entry == json{{"key", "export_it"}, - {"title", "Export It"}, - {"group", "Commands"}, - {"description", "Exports it."}, - {"input_schema", c.input_schema}, - {"listed", false}, - {"in_palette", true}, - {"read_only", false}, - {"destructive", false}, - {"idempotent", false}, - {"open_world", true}, - {"guard", "recover"}, - {"completion", "export"}, - {"operations", json::array({"export_gcode"})}}); - - const json call{{"tool", "export_it"}, {"args", {{"path", "a"}}}}; - c.guard = Mcp::GuardClass::Inspect; - c.completion = CommandCompletion::None; - c.examples = json::array({json{{"title", "Export"}, {"calls", json::array({call})}}}); - const json other = Slic3r::GUI::command_reference(c); - CHECK(other["guard"] == "inspect"); - CHECK(other["completion"] == "none"); - CHECK(other["examples"] == c.examples); - c.guard = Mcp::GuardClass::Mutate; - CHECK(Slic3r::GUI::command_reference(c)["guard"] == "mutate"); -} - TEST_CASE("the reference shows both forms of a two-form command", "[CommandCatalog][Reference]") { CommandCatalog catalog = catalog_with_design(); diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index 52f3aec651..a6e98ef103 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -35,9 +35,10 @@ #include "slic3r/GUI/CAD/DesignOffer.hpp" #include "slic3r/GUI/CAD/DesignSketchTool.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/McpToolsCad.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include <TopoDS_Edge.hxx> @@ -222,7 +223,7 @@ bool is_id_param(const std::string& name) } // A call's context that runs its UI closures in place and keeps the arguments it journals. -struct JournalContext final : GUI::Mcp::ToolContext +struct JournalContext final : GUI::ToolContext { explicit JournalContext(bool person = false) : picked(person) {} @@ -231,7 +232,7 @@ struct JournalContext final : GUI::Mcp::ToolContext json observe_ui(const std::function<json()>&) override { return true; } const std::string& job_id() const override { return id; } bool cancelled() const override { return false; } - GUI::Mcp::ToolResult call_child(const std::string&, const json&) override { return GUI::Mcp::ToolResult::error("no children"); } + GUI::ToolResult call_child(const std::string&, const json&) override { return GUI::ToolResult::error("no children"); } std::set<std::string> lineage() const override { return {}; } void set_journal_args(json args) override { journaled = std::move(args); } void begin_operation() override {} @@ -457,7 +458,7 @@ TEST_CASE("a tool refused for the selection says it does not apply and what it t // row's refusal speaks of. const GUI::DesignTool& delete_face = design_row("delete_face"); const int none = int(GUI::OfferSel::None); - const std::optional<GUI::Mcp::ToolFailure> refused = GUI::Mcp::open_refusal(delete_face, false, none); + const std::optional<GUI::ToolFailure> 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); @@ -475,7 +476,7 @@ TEST_CASE("a tool refused for the selection says it does not apply and what it t while (miss < int(GUI::OfferSel::Count) && (t.accepts & GUI::offer_bit(GUI::OfferSel(miss))) != 0) ++miss; REQUIRE(miss < int(GUI::OfferSel::Count)); - const std::optional<GUI::Mcp::ToolFailure> missed = GUI::Mcp::open_refusal(t, t.sketch_mode, miss); + const std::optional<GUI::ToolFailure> missed = GUI::Mcp::open_refusal(t, t.sketch_mode, miss); REQUIRE(missed.has_value()); CHECK(std::string(missed->what()) == "This tool does not apply to what is selected"); CHECK(missed->details.at("selection") == GUI::kDesignSelectionIds[miss]); @@ -499,7 +500,7 @@ TEST_CASE("a Design tool opens only in the mode its row belongs to", "[Mcp][CAD] // In the other mode it is refused whatever is selected there, before the selection is looked at. for (int kind = 0; kind < int(GUI::OfferSel::Count); ++kind) { INFO(kind); - const std::optional<GUI::Mcp::ToolFailure> refused = GUI::Mcp::open_refusal(t, !t.sketch_mode, kind); + const std::optional<GUI::ToolFailure> 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); @@ -785,7 +786,7 @@ TEST_CASE("a CAD call is journaled without its generation and with its silent", CHECK_FALSE(fillet.listed); JournalContext agent; - const GUI::Mcp::ToolResult reply = fillet.run({{"generation", 4}, {"silent", true}, {"radius", 2}}, agent); + const GUI::ToolResult reply = fillet.run({{"generation", 4}, {"silent", true}, {"radius", 2}}, agent); CHECK(agent.journaled == json{{"silent", true}, {"radius", 2}}); // The function still checks the generation, and the reply wraps its value. CHECK(seen == json{{"generation", 4}, {"silent", true}, {"radius", 2}}); @@ -813,9 +814,9 @@ 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&) -> json { - throw GUI::Mcp::ToolFailure("removed no material", {{"code", -32000}}); + throw GUI::ToolFailure("removed no material", {{"code", -32000}}); }); - CHECK_THROWS_AS(refused.run(json::object(), agent), GUI::Mcp::ToolFailure); + CHECK_THROWS_AS(refused.run(json::object(), agent), GUI::ToolFailure); } TEST_CASE("an unknown command is answered with close names only", "[Mcp][CAD]") diff --git a/tests/slic3rutils/test_mcp_config.cpp b/tests/slic3rutils/test_mcp_config.cpp index 3f1fe023f1..5924311c5a 100644 --- a/tests/slic3rutils/test_mcp_config.cpp +++ b/tests/slic3rutils/test_mcp_config.cpp @@ -15,10 +15,10 @@ #include <catch2/matchers/catch_matchers.hpp> #include <catch2/matchers/catch_matchers_string.hpp> -#include "slic3r/GUI/Mcp/McpOptions.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" @@ -43,6 +43,7 @@ #include <vector> using namespace Slic3r; +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; @@ -722,14 +723,46 @@ TEST_CASE("the preferences scope reads the keys it is given, as stored, and list CHECK_THROWS_AS(preferences_settings(config, json{{"keys", {"region"}}, {"compare", ":saved"}}), ToolFailure); } -TEST_CASE("Python scripts run restricted unless a person let them run unrestricted", "[Mcp]") +TEST_CASE("the run's flag lets scripts run unrestricted without changing the setting", "[Mcp]") { + // The flag is process-wide: it goes back off however the case ends. + struct RunFlagOff + { + ~RunFlagOff() { set_python_scripts_for_run(false); } + } run_flag_off; + AppConfig config; - CHECK_FALSE(python_scripts_unrestricted(config)); - config.set_bool(kPythonUnrestrictedKey, true); + config.set_bool("python_scripts_unrestricted", false); + set_python_scripts_for_run(true); + CHECK(python_scripts_set_for_run()); CHECK(python_scripts_unrestricted(config)); - config.set_bool(kPythonUnrestrictedKey, false); + CHECK_FALSE(python_scripts_setting(config)); + CHECK_FALSE(config.get_bool("python_scripts_unrestricted")); + + set_python_scripts_for_run(false); CHECK_FALSE(python_scripts_unrestricted(config)); + config.set_bool("python_scripts_unrestricted", true); + CHECK(python_scripts_unrestricted(config)); + CHECK(python_scripts_setting(config)); + + // Another key, whatever its name, is not the setting. + AppConfig other; + other.set_bool("python_scripts_unrestricted", false); + other.set_bool("mcp_python_unrestricted", true); + CHECK_FALSE(python_scripts_unrestricted(other)); + CHECK_FALSE(python_scripts_setting(other)); +} + +TEST_CASE("the endpoint's port is the option's, then the setting's, then the default", "[Mcp]") +{ + CHECK(endpoint_port(13700, "13800") == 13700); + CHECK(endpoint_port(0, "13800") == 13800); + CHECK(endpoint_port(0, "") == 13619); + CHECK(endpoint_port(0, "abc") == 13619); + CHECK(endpoint_port(0, "0") == 13619); + CHECK(endpoint_port(0, "70000") == 13619); + // An option out of range gives the default, not the setting. + CHECK(endpoint_port(70000, "13800") == 13619); } namespace { diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 5c0e167479..93a70f642a 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -1,221 +1,31 @@ #include <catch2/catch_test_macros.hpp> -#include <catch2/generators/catch_generators.hpp> +#include <catch2/matchers/catch_matchers.hpp> + +#include "automation/automation_test_utils.hpp" #include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/Mcp/JobRegistry.hpp" -#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/McpPersonContext.hpp" -#include "slic3r/GUI/Mcp/McpProtocol.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" -#include "slic3r/GUI/Mcp/McpServicePtr.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" -#include "slic3r/GUI/Mcp/UiInvoker.hpp" #include <nlohmann/json.hpp> -#include <atomic> -#include <chrono> -#include <condition_variable> -#include <cstddef> -#include <cstdint> -#include <deque> -#include <functional> -#include <memory> -#include <new> -#include <optional> -#include <set> -#include <stdexcept> -#include <utility> -#include <vector> -#include <future> -#include <mutex> #include <string> -#include <thread> +#include <utility> +// The dispatch core's cases that name a type of the GUI library: the automation runtime and a tile's +// context. The others are in tests/automation/test_mcp_core.cpp. + +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; -using Slic3r::GUI::CommandCatalog; using Slic3r::GUI::CommandFn; using Slic3r::GUI::NativeCommand; -using namespace std::chrono_literals; +using Slic3r::GUI::Mcp::Test::Harness; namespace { -// Plays the UI thread: closures queue up until the test drains them on its own thread. -class ManualDispatcher final : public UiDispatcher -{ -public: - void post(std::function<void()> fn) override - { - std::lock_guard<std::mutex> lock(m_mutex); - m_queue.push_back(std::move(fn)); - } - - // Runs queued closures (including ones queued while running) until the queue is empty. - void drain() - { - for (;;) { - std::function<void()> fn; - { - std::lock_guard<std::mutex> lock(m_mutex); - if (m_queue.empty()) - return; - fn = std::move(m_queue.front()); - m_queue.pop_front(); - } - fn(); - } - } - - // Keeps draining until `done` returns true or `timeout` passes, like an event loop. - bool pump_until(const std::function<bool()>& done, std::chrono::milliseconds timeout = 5000ms) - { - const auto end = std::chrono::steady_clock::now() + timeout; - while (!done()) { - if (std::chrono::steady_clock::now() > end) - return false; - drain(); - std::this_thread::sleep_for(5ms); - } - return true; - } - -private: - std::mutex m_mutex; - std::deque<std::function<void()>> m_queue; -}; - -// A UI thread with an event loop. Closures may run a nested loop (loop_until) the way a modal -// dialog does, so other closures keep running while they are on the stack. -class FakeUiThread final : public UiDispatcher -{ -public: - FakeUiThread() : m_thread([this] { loop_until([this] { return m_stop.load(); }); }) {} - ~FakeUiThread() override - { - m_stop = true; - m_cv.notify_all(); - m_thread.join(); - } - - void post(std::function<void()> fn) override - { - { - std::lock_guard<std::mutex> lock(m_mutex); - m_queue.push_back(std::move(fn)); - } - m_cv.notify_all(); - } - - // Runs queued closures until `done` returns true. Call it only on the UI thread. - void loop_until(const std::function<bool()>& done) - { - for (;;) { - std::function<void()> fn; - { - std::unique_lock<std::mutex> lock(m_mutex); - m_cv.wait_for(lock, 5ms, [&] { return !m_queue.empty(); }); - if (m_queue.empty()) { - lock.unlock(); - if (done()) - return; - continue; - } - fn = std::move(m_queue.front()); - m_queue.pop_front(); - } - fn(); - if (done()) - return; - } - } - -private: - std::mutex m_mutex; - std::condition_variable m_cv; - std::deque<std::function<void()>> m_queue; - std::atomic<bool> m_stop{false}; - std::thread m_thread; -}; - -// A file picker as ModalTracker describes it: native, and untitled on macOS. -const json kNativePicker = json::array({{{"title", ""}, {"message", "Choose one or more files"}, {"native", true}}}); - -// Sets `flag` when the test leaves, failed assertions included, so a closure holding the fake UI -// thread lets go before the harness joins that thread. Declare the flag before the harness and this -// after it: the flag must outlive that join, and be set before it starts. -struct SetOnExit -{ - std::atomic<bool>& flag; - ~SetOnExit() { flag = true; } -}; - -struct Harness -{ - FakeUiThread ui; - std::mutex guards_mutex; - GuardState guards; - // The guards' dialogs double as the snapshot ModalTracker publishes to other threads. - UiInvoker invoker{ui, - [this] { - std::lock_guard<std::mutex> lock(guards_mutex); - return guards; - }, - {}, - [this] { - std::lock_guard<std::mutex> lock(guards_mutex); - return guards.dialogs; - }}; - JobRegistry jobs; - Journal journal; - CommandCatalog registry; - CoreTiming timing = [] { - CoreTiming t; - t.soft_budget = 100ms; - t.probe_timeout = 500ms; - return t; - }(); - std::unique_ptr<McpCore> core; - - void start() { core = std::make_unique<McpCore>(registry, invoker, jobs, &journal, timing); } - - void set_modal(bool modal, json dialogs = json::array()) - { - std::lock_guard<std::mutex> lock(guards_mutex); - guards.modal = modal; - guards.dialogs = std::move(dialogs); - } - - // A modal dialog's nested event loop on the UI thread, open until `release` is set. - void modal_loop(std::atomic<bool>& release, json dialogs = json::array({{{"title", "Dialog"}}})) - { - set_modal(true, std::move(dialogs)); - ui.loop_until([&] { return release.load(); }); - set_modal(false); - } - - // Dialogs that hold the UI thread until `release` is set: they are published, but nothing posted - // meanwhile runs, as when macOS pauses wx's pending events behind a native file picker. - void hold_ui(std::atomic<bool>& release, json dialogs) - { - set_modal(true, std::move(dialogs)); - while (!release) - std::this_thread::sleep_for(5ms); - set_modal(false); - } - - ~Harness() - { - invoker.shutdown(); - jobs.wake_all(); - if (core) - core->shutdown(); - } - - ToolResult call(const std::string& tool, const json& args = json::object()) { return core->call(*registry.find(tool), args); } -}; - NativeCommand tool(const std::string& name, GuardClass guard, CommandFn handler) { NativeCommand d; @@ -225,709 +35,32 @@ NativeCommand tool(const std::string& name, GuardClass guard, CommandFn handler) return d; } -// Arguments whose serialized size is just over `mib` MiB. -json args_of_mib(std::size_t mib) { return {{"s", std::string(mib << 20, 'x')}}; } - } // namespace -TEST_CASE("a UI call that is never picked up is abandoned and never runs", "[Mcp]") +TEST_CASE("a context with no runtime refuses", "[Mcp]") { - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }); - bool ran = false; - std::string error; - try { - invoker.run(GuardClass::Mutate, "t", [&] { ran = true; return json(); }, 100ms); - } catch (const ToolFailure& f) { - error = f.what(); - } - CHECK(error.find("safe to retry") != std::string::npos); - ui.drain(); - CHECK_FALSE(ran); -} - -TEST_CASE("a UI call that times out behind a native dialog names the dialog", "[Mcp]") -{ - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [] { return kNativePicker; }); - bool ran = false; - std::string error; - json details; - try { - invoker.run(GuardClass::Inspect, "get_app_state", [&] { ran = true; return json(); }, 100ms); - } catch (const ToolFailure& f) { - error = f.what(); - details = f.details; - } - CHECK(error.find("native dialog") != std::string::npos); - CHECK(details.value("dialogs", json()) == kNativePicker); - ui.drain(); - CHECK_FALSE(ran); -} - -TEST_CASE("a UI call that times out behind a wx dialog keeps the busy message", "[Mcp]") -{ - ManualDispatcher ui; - // The topmost dialog has no "native" field, as Orca's own dialogs in these tests don't. - const json dialogs = json::array({kNativePicker[0], {{"title", "Preferences"}}}); - UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [&] { return dialogs; }); - std::string error; - try { - invoker.run(GuardClass::Inspect, "get_app_state", [] { return json(); }, 100ms); - } catch (const ToolFailure& f) { - error = f.what(); - } - CHECK(error.find("safe to retry") != std::string::npos); - ui.drain(); -} - -TEST_CASE("a UI call returns the closure's value", "[Mcp]") -{ - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }); - auto fut = std::async(std::launch::async, [&] { return invoker.run(GuardClass::Inspect, "t", [] { return json(42); }); }); - ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); - CHECK(fut.get() == json(42)); -} - -TEST_CASE("shutdown wakes waiting callers and later closures do nothing", "[Mcp]") -{ - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }); - std::atomic<bool> ran{false}; - auto fut = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Mutate, "t", [&] { ran = true; return json(); }); - } catch (const ToolFailure& f) { - return f.what(); - } - return "returned"; - }); - std::this_thread::sleep_for(50ms); - invoker.shutdown(); - CHECK(fut.get().find("shutting down") != std::string::npos); - ui.drain(); - CHECK_FALSE(ran); -} - -TEST_CASE("guards refuse mutate calls behind a modal, while closing and while suspended", "[Mcp]") -{ - ManualDispatcher ui; - GuardState guards; - UiInvoker invoker(ui, [&] { return guards; }); - auto attempt = [&](GuardClass g) -> std::string { - auto fut = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(g, "t", [] { return json(); }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); - return fut.get(); + Harness h; + const CommandFn needs_runtime = [](const json&, ToolContext& ctx) { + [[maybe_unused]] AutomationRuntime& runtime = ctx.runtime(); + return ToolResult::ok(); }; - guards.modal = true; - CHECK(attempt(GuardClass::Mutate).find("modal dialog") != std::string::npos); - CHECK(attempt(GuardClass::Inspect) == "ok"); - CHECK(attempt(GuardClass::Recover) == "ok"); - guards = {}; - guards.suspended = true; - CHECK(attempt(GuardClass::Inspect).find("recreated") != std::string::npos); - guards = {}; - guards.closing = true; - CHECK(attempt(GuardClass::Inspect).find("shutting down") != std::string::npos); -} - -TEST_CASE("a mutate call is refused inside another call's nested loop but inspect runs", "[Mcp]") -{ - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }); - std::string nested_mutate, nested_inspect; - std::atomic<bool> release{false}; - - auto outer = std::async(std::launch::async, [&] { - return invoker.run(GuardClass::Mutate, "outer", [&] { - // A nested event loop: other closures run while this one is still on the stack. - auto m = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Mutate, "inner", [] { return json(); }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - auto i = std::async(std::launch::async, [&] { return invoker.run(GuardClass::Inspect, "look", [] { return json("seen"); }); }); - ui.pump_until([&] { return m.wait_for(0ms) == std::future_status::ready && i.wait_for(0ms) == std::future_status::ready; }); - nested_mutate = m.get(); - nested_inspect = i.get().get<std::string>(); - return json(); - }); - }); - ui.pump_until([&] { return outer.wait_for(0ms) == std::future_status::ready; }); - (void) outer.get(); - CHECK(nested_mutate.find("Busy: outer") != std::string::npos); - CHECK(nested_inspect == "seen"); -} - -TEST_CASE("a recover call that targets outside the dialog applies the mutate guard itself", "[Mcp]") -{ - ManualDispatcher ui; - GuardState guards; - UiInvoker invoker(ui, [&] { return guards; }); - auto attempt = [&]() -> std::string { - auto fut = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Recover, "click", [&] { - invoker.require_mutate(); - return json(); - }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - ui.pump_until([&] { return fut.wait_for(0ms) == std::future_status::ready; }); - return fut.get(); - }; - CHECK(attempt() == "ok"); - guards.modal = true; - CHECK(attempt().find("modal dialog") != std::string::npos); - guards = {}; - - // Inside another call's nested loop it is busy, as a mutate call would be. - std::string nested; - auto outer = std::async(std::launch::async, [&] { - return invoker.run(GuardClass::Mutate, "outer", [&] { - auto m = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Recover, "click", [&] { - invoker.require_mutate(); - return json(); - }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - ui.pump_until([&] { return m.wait_for(0ms) == std::future_status::ready; }); - nested = m.get(); - return json(); - }); - }); - ui.pump_until([&] { return outer.wait_for(0ms) == std::future_status::ready; }); - (void) outer.get(); - CHECK(nested.find("Busy: outer") != std::string::npos); -} - -TEST_CASE("a job outlives its reply and wait() returns its result", "[Mcp]") -{ - Harness h; - NativeCommand slow = tool("slow", GuardClass::Mutate, [](const json&, ToolContext&) { - std::this_thread::sleep_for(600ms); - return ToolResult::ok({{"done", true}}); - }); - slow.budget_ms = 200; - h.registry.add(slow); - h.start(); - - const ToolResult envelope = h.call("slow"); - REQUIRE_FALSE(envelope.is_error); - CHECK(envelope.data["status"] == "running"); - const std::string job = envelope.data["job"]; - auto result = h.jobs.wait(job, 3000ms); - REQUIRE(result.has_value()); - CHECK(result->data["done"] == true); -} - -TEST_CASE("blocked_by_dialog is reported after the soft budget when the probe sees a modal", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - h.registry.add(tool("open_modal", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.modal_loop(release, json::array({{{"title", "Unsaved changes"}}})); - return json(); - }); - return ToolResult::ok({{"closed", true}}); - })); - h.start(); - - const ToolResult envelope = h.call("open_modal"); - CHECK(envelope.data["status"] == "blocked_by_dialog"); - CHECK(envelope.data["dialogs"][0]["title"] == "Unsaved changes"); - release = true; - auto result = h.jobs.wait(envelope.data["job"], 3000ms); - REQUIRE(result.has_value()); - CHECK(result->data["closed"] == true); -} - -TEST_CASE("a call working in the topmost dialog is blocked only by another dialog on top", "[Mcp]") -{ - Harness h; - h.registry.add(tool("page_call", GuardClass::Recover, [&](const json&, ToolContext& ctx) { - ctx.works_in_dialog(7); - std::this_thread::sleep_for(400ms); - return ToolResult::ok({{"done", true}}); - })); - h.start(); - auto top = [&](std::uint64_t serial, json dialogs) { - std::lock_guard<std::mutex> lock(h.guards_mutex); - h.guards.modal = true; - h.guards.dialogs = std::move(dialogs); - h.guards.top_dialog = serial; - }; - - // Its own dialog on top: past the soft budget it is still running, and its result comes back. - top(7, json::array({{{"title", "Web dialog"}}})); - CHECK(h.call("page_call").data["done"] == true); - - // Another dialog on top, at any depth (here the same one: its own closed and another opened). - top(8, json::array({{{"title", "Another"}}})); - const ToolResult blocked = h.call("page_call"); - CHECK(blocked.data["status"] == "blocked_by_dialog"); - REQUIRE(h.jobs.wait(blocked.data["job"], 3000ms).has_value()); -} - -TEST_CASE("blocked_by_dialog is reported from the snapshot when a native dialog holds the UI thread", "[Mcp]") -{ - std::atomic<bool> release{false}; - Harness h; - SetOnExit releaser{release}; - h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.hold_ui(release, kNativePicker); - return json(); - }); - return ToolResult::ok({{"closed", true}}); - })); - h.start(); - - const ToolResult envelope = h.call("pick_file"); - release = true; - REQUIRE(envelope.data["status"] == "blocked_by_dialog"); - CHECK(envelope.data["dialogs"] == kNativePicker); - const std::string note = envelope.data.value("note", ""); - CHECK(note.find("only a person") != std::string::npos); - CHECK(note.find("tools that need the UI thread fail") != std::string::npos); - CHECK(note.find("Answer the dialog") == std::string::npos); - auto result = h.jobs.wait(envelope.data["job"], 3000ms); - REQUIRE(result.has_value()); - CHECK(result->data["closed"] == true); -} - -TEST_CASE("a held UI thread under a wx dialog is not reported as blocked_by_dialog", "[Mcp]") -{ - std::atomic<bool> release{false}; - Harness h; - SetOnExit releaser{release}; - NativeCommand hold = tool("hold", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.hold_ui(release, json::array({kNativePicker[0], {{"title", "Preferences"}}})); - return json(); - }); - return ToolResult::ok(); - }); - hold.budget_ms = 1000; - h.registry.add(hold); - h.start(); - - const ToolResult envelope = h.call("hold"); - release = true; - CHECK(envelope.data["status"] == "running"); - CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); -} - -TEST_CASE("shutdown during an unanswered probe replies shutting down", "[Mcp]") -{ - std::atomic<bool> release{false}; - Harness h; - SetOnExit releaser{release}; - h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.hold_ui(release, kNativePicker); - return json(); - }); - return ToolResult::ok(); - })); - h.start(); - - // 300 ms lands inside the probe window: past the 100 ms soft budget, before the 500 ms probe - // gives up. A stop that lands earlier gets the same reply from the check before the probe. - auto reply = std::async(std::launch::async, [&] { return h.call("pick_file"); }); - std::this_thread::sleep_for(300ms); - h.invoker.shutdown(); - const ToolResult r = reply.get(); - release = true; - CHECK(r.is_error); - CHECK(r.message.find("shutting down") != std::string::npos); -} - -TEST_CASE("a native dialog that the probe sees gets the native note", "[Mcp]") -{ - std::atomic<bool> release{false}; - Harness h; - SetOnExit releaser{release}; - h.registry.add(tool("pick_file", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.modal_loop(release, kNativePicker); - return json(); - }); - return ToolResult::ok(); - })); - h.start(); - - const ToolResult envelope = h.call("pick_file"); - release = true; - REQUIRE(envelope.data["status"] == "blocked_by_dialog"); - const std::string note = envelope.data.value("note", ""); - CHECK(note.find("only a person") != std::string::npos); - CHECK(note.find("tools that need the UI thread fail") == std::string::npos); - CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); -} - -TEST_CASE("a native message box with buttons gets the answer_dialog note", "[Mcp]") -{ - // As ModalTracker describes a message box whose buttons can be pressed (Windows, Linux). - const json box = json::array({{{"title", "Plugin permission request"}, - {"message", "Plugin \"Fixture\" is requesting permission to create a thread."}, - {"native", true}, - {"buttons", json::array({{{"id", 5103}, {"label", "Yes"}}, {{"id", 5104}, {"label", "No"}}})}}}); - std::atomic<bool> release{false}; - Harness h; - SetOnExit releaser{release}; - h.registry.add(tool("ask", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.modal_loop(release, box); - return json(); - }); - return ToolResult::ok(); - })); - h.start(); - - const ToolResult envelope = h.call("ask"); - release = true; - REQUIRE(envelope.data["status"] == "blocked_by_dialog"); - CHECK(envelope.data["dialogs"] == box); - const std::string note = envelope.data.value("note", ""); - CHECK(note.find("answer_dialog") != std::string::npos); - CHECK(note.find("only a person") == std::string::npos); - CHECK(h.jobs.wait(envelope.data["job"], 3000ms).has_value()); -} - -TEST_CASE("inspect tools run inline and recover tools run as jobs while another job is blocked", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - h.registry.add(tool("open_modal", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.modal_loop(release); - return json(); - }); - return ToolResult::ok(); - })); - NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext& ctx) { - return ToolResult::ok({{"job", ctx.job_id()}, {"ui", ctx.run_ui([] { return json("ok"); })}}); + // Inline, so the handler runs on this thread, where it may assert. + NativeCommand look = tool("look", GuardClass::Inspect, [needs_runtime](const json& args, ToolContext& ctx) { + REQUIRE_THROWS_WITH(ctx.runtime(), "This call runs without the automation runtime"); + return needs_runtime(args, ctx); }); look.inline_call = true; h.registry.add(look); - h.registry.add(tool("answer", GuardClass::Recover, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { release = true; return json(); }); - return ToolResult::ok({{"job", ctx.job_id()}}); - })); + h.registry.add(tool("act", GuardClass::Mutate, needs_runtime)); h.start(); - const ToolResult blocked = h.call("open_modal"); - REQUIRE(blocked.data["status"] == "blocked_by_dialog"); - const ToolResult seen = h.call("look"); - CHECK(seen.data["job"] == ""); - CHECK(seen.data["ui"] == "ok"); - const ToolResult answered = h.call("answer"); - CHECK_FALSE(answered.is_error); - CHECK(answered.data["job"].get<std::string>().rfind("j", 0) == 0); - CHECK(h.jobs.wait(blocked.data["job"], 3000ms).has_value()); -} - -TEST_CASE("a recover call that opens another modal returns blocked_by_dialog", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - h.registry.add(tool("click_edit", GuardClass::Recover, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - h.modal_loop(release); - return json(); - }); - return ToolResult::ok(); - })); - h.start(); - const ToolResult r = h.call("click_edit"); - CHECK(r.data["status"] == "blocked_by_dialog"); - release = true; - CHECK(h.jobs.wait(r.data["job"], 3000ms).has_value()); -} - -TEST_CASE("every mutate call is refused while a slice job runs, but cancel_job and recover tools run", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.begin_operation(); - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - }); - slice.budget_ms = 100; - h.registry.add(slice); - h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - NativeCommand cancel = tool("cancel_job", GuardClass::Mutate, [&](const json&, ToolContext&) { - release = true; - return ToolResult::ok(); - }); - cancel.allowed_during_operation = true; - h.registry.add(cancel); - h.registry.add(tool("answer", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.start(); - - const ToolResult running = h.call("slice"); - REQUIRE(running.data["status"] == "running"); - const ToolResult refused = h.call("new_project"); - CHECK(refused.is_error); - CHECK(refused.message.find("wait for it or stop it with cancel_job") != std::string::npos); - CHECK_FALSE(h.call("answer").is_error); - CHECK_FALSE(h.call("cancel_job").is_error); - CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); - CHECK_FALSE(h.call("new_project").is_error); -} - -TEST_CASE("a context with no service set refuses", "[Mcp]") -{ - Harness h; - const CommandFn needs_service = [](const json&, ToolContext& ctx) { - [[maybe_unused]] McpService& service = ctx.service(); - return ToolResult::ok(); - }; - NativeCommand look = tool("look", GuardClass::Inspect, needs_service); - look.inline_call = true; - h.registry.add(look); - h.registry.add(tool("act", GuardClass::Mutate, needs_service)); - h.start(); - - // A core no McpService owns, as a test builds one: the call fails, inline or as a job, and nothing crashes. + // A core no AutomationRuntime owns, as a test builds one: the call fails, inline or as a job, and nothing crashes. CHECK(h.call("look").is_error); const ToolResult acted = h.call("act"); CHECK(acted.is_error); CHECK_FALSE(acted.data.contains("status")); } -TEST_CASE("a submitted call returns its job at once and runs on a job's thread", "[Mcp]") -{ - // Before the harness: the job's thread may still use them until the harness has joined it. - std::atomic<bool> open{false}; - std::promise<ToolResult> ended; - std::mutex seen_mutex; - std::thread::id ran_on; - Harness h; - SetOnExit let_go{open}; - h.registry.add(tool("work", GuardClass::Mutate, [&](const json& args, ToolContext&) { - { - std::lock_guard<std::mutex> lock(seen_mutex); - ran_on = std::this_thread::get_id(); - } - while (!open) - std::this_thread::sleep_for(5ms); - return ToolResult::ok({{"n", args.value("n", 0)}}); - })); - h.start(); - - std::future<ToolResult> result = ended.get_future(); - const std::string job = h.core->submit(*h.registry.find("work"), {{"n", 7}}, [&ended](const ToolResult& r) { ended.set_value(r); }); - CHECK_FALSE(job.empty()); - // It returned while the call is still held. - CHECK(result.wait_for(0ms) == std::future_status::timeout); - open = true; - REQUIRE(result.wait_for(3000ms) == std::future_status::ready); - const ToolResult r = result.get(); - CHECK_FALSE(r.is_error); - CHECK(r.data["n"] == 7); - { - std::lock_guard<std::mutex> lock(seen_mutex); - CHECK(ran_on != std::this_thread::get_id()); - } - // The job is registered as a client's would be, and the call is not journaled. - CHECK(h.jobs.wait(job, 3000ms).has_value()); - CHECK(h.journal.to_replay("r")["steps"].empty()); -} - -TEST_CASE("a submitted change is refused as a client's is while an operation runs, and none starts after shutdown", "[Mcp]") -{ - std::atomic<bool> release{false}; - Harness h; - SetOnExit let_go{release}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.begin_operation(); - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - }); - slice.budget_ms = 100; - h.registry.add(slice); - h.registry.add(tool("new_project", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.start(); - - const ToolResult running = h.call("slice"); - REQUIRE(running.data["status"] == "running"); - const ToolResult client = h.call("new_project"); - REQUIRE(client.is_error); - // No job starts, and the refusal comes at once, on the calling thread. - std::optional<ToolResult> refusal; - CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&refusal](const ToolResult& r) { refusal = r; }).empty()); - REQUIRE(refusal.has_value()); - CHECK(refusal->is_error); - CHECK(refusal->message == client.message); - - release = true; - CHECK(h.jobs.wait(running.data["job"], 3000ms).has_value()); - h.core->shutdown(); - bool called = false; - CHECK(h.core->submit(*h.registry.find("new_project"), json::object(), [&called](const ToolResult&) { called = true; }).empty()); - CHECK_FALSE(called); -} - -TEST_CASE("a submitted job runs as a person's, a client's call of the same command does not", "[Mcp]") -{ - // The service that owns the core, as GUI_App's does; never started, since the mark needs no endpoint or UI. - // Before the harness, so that it outlives the job threads the harness joins. - McpServicePtr service(new McpService()); - Harness h; - h.registry.add(tool("work", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - return ToolResult::ok({{"person", ctx.service().person_run(ctx.lineage())}}); - })); - h.start(); - h.core->set_service(service.get()); - - std::promise<ToolResult> ended; - std::future<ToolResult> result = ended.get_future(); - const std::string job = h.core->submit(*h.registry.find("work"), json::object(), [&ended](const ToolResult& r) { ended.set_value(r); }); - REQUIRE_FALSE(job.empty()); - REQUIRE(result.wait_for(3000ms) == std::future_status::ready); - const ToolResult submitted = result.get(); - REQUIRE_FALSE(submitted.is_error); - CHECK(submitted.data.value("person", false)); - // The mark ends with the job. - REQUIRE(h.jobs.wait(job, 3000ms).has_value()); - CHECK_FALSE(service->person_run({job})); - const ToolResult client = h.call("work"); - REQUIRE_FALSE(client.is_error); - CHECK_FALSE(client.data.value("person", true)); -} - -TEST_CASE("a submitted call whose done throws still ends its job", "[Mcp]") -{ - Harness h; - h.registry.add(tool("work", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.start(); - - // done runs on the job's thread: what it throws must not end the process, nor keep the job from finishing. - const std::string job = h.core->submit(*h.registry.find("work"), json::object(), - [](const ToolResult&) { throw std::runtime_error("the caller's own failure"); }); - REQUIRE_FALSE(job.empty()); - CHECK(h.jobs.wait(job, 3000ms).has_value()); -} - -// What a recording's CallObserver hears, in order. -struct HeardCalls final : CallObserver -{ - std::mutex mutex; - std::vector<std::string> events; - void call_started(uint64_t, const NativeCommand& def, const json&, const std::string& parent) override - { - std::lock_guard<std::mutex> lock(mutex); - events.push_back("start " + def.key + (parent.empty() ? "" : " in a job")); - } - void call_args(uint64_t, const json& args) override - { - std::lock_guard<std::mutex> lock(mutex); - events.push_back("args " + args.dump()); - } - void call_ended(uint64_t, const ToolResult& result) override - { - std::lock_guard<std::mutex> lock(mutex); - events.push_back(std::string("end ") + (result.is_error ? "error" : "ok")); - } - std::vector<std::string> take() - { - std::lock_guard<std::mutex> lock(mutex); - return std::exchange(events, {}); - } -}; - -TEST_CASE("the call observer hears inline, job and child calls, and not calls refused before they run", "[Mcp]") -{ - Harness h; - HeardCalls heard; - NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); - look.inline_call = true; - h.registry.add(look); - h.registry.add(tool("click", GuardClass::Recover, [](const json&, ToolContext& ctx) { - // A ref resolved to its locator, as the GUI tools record it. - ctx.set_journal_args({{"target", {{"label", "Slice"}}}}); - return ToolResult::error("gone"); - })); - h.registry.add(tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("click", json::object()); })); - std::atomic<bool> release{false}; - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.begin_operation(); - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - }); - slice.budget_ms = 100; - h.registry.add(slice); - h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &heard); - - CHECK_FALSE(h.call("look").is_error); - CHECK(heard.take() == std::vector<std::string>{"start look", "end ok"}); - CHECK(h.call("click").is_error); - CHECK(heard.take() == std::vector<std::string>{"start click", R"(args {"target":{"label":"Slice"}})", "end error"}); - h.call("replay"); - CHECK(heard.take() == - std::vector<std::string>{"start replay", "start click in a job", R"(args {"target":{"label":"Slice"}})", "end error", "end error"}); - - const ToolResult running = h.call("slice"); - REQUIRE(running.data["status"] == "running"); - CHECK(heard.take() == std::vector<std::string>{"start slice"}); - CHECK(h.call("replay").is_error); // refused by admission: it never ran - CHECK(heard.take().empty()); - release = true; - REQUIRE(h.jobs.wait(running.data["job"], 3000ms).has_value()); - CHECK(heard.take() == std::vector<std::string>{"end ok"}); -} - -TEST_CASE("an observer that throws fails no call", "[Mcp]") -{ - struct Throwing final : CallObserver - { - void call_started(uint64_t, const NativeCommand&, const json&, const std::string&) override { throw std::runtime_error("started"); } - void call_args(uint64_t, const json&) override { throw std::bad_alloc(); } - void call_ended(uint64_t, const ToolResult&) override { throw std::runtime_error("ended"); } - } throwing; - Harness h; - NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok({{"seen", true}}); }); - look.inline_call = true; - h.registry.add(look); - h.registry.add(tool("act", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - ctx.set_journal_args({{"x", 1}}); - return ToolResult::ok({{"done", true}}); - })); - h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &throwing); - const ToolResult looked = h.call("look"); - CHECK_FALSE(looked.is_error); - CHECK(looked.data["seen"] == true); - const ToolResult acted = h.call("act"); - CHECK_FALSE(acted.is_error); - CHECK(acted.data["done"] == true); -} - TEST_CASE("a tile's journal update stays inside run_action's envelope", "[Mcp]") { Harness h; @@ -949,822 +82,3 @@ TEST_CASE("a tile's journal update stays inside run_action's envelope", "[Mcp]") CHECK(steps[0]["tool"] == "run_action"); CHECK(steps[0]["args"] == json{{"id", "orca_command:k:orca"}, {"args", {{"a", 1}}}}); } - -TEST_CASE("the journal records a call without its command's id arguments", "[Mcp]") -{ - Harness h; - NativeCommand move = tool("move", GuardClass::Mutate, [](const json& args, ToolContext& ctx) { - // A handler that replaces what the journal records, as the GUI tools record locators for refs. - if (args.contains("rewrite")) - ctx.set_journal_args({{"object", 2}, {"object_id", 5}}); - return ToolResult::ok(); - }); - move.id_args = {"object_id"}; - h.registry.add(move); - // A command without id_args keeps an argument of that name: it is its own. - h.registry.add(tool("measure", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.start(); - - REQUIRE_FALSE(h.call("move", {{"object", 1}, {"object_id", 9}}).is_error); - REQUIRE_FALSE(h.call("move", {{"rewrite", true}, {"object_id", 9}}).is_error); - REQUIRE_FALSE(h.call("measure", {{"object_id", 4}}).is_error); - const json steps = h.journal.to_replay("s")["steps"]; - REQUIRE(steps.size() == 3); - CHECK(steps[0]["args"] == json{{"object", 1}}); - CHECK(steps[1]["args"] == json{{"object", 2}}); - CHECK(steps[2]["args"] == json{{"object_id", 4}}); -} - -TEST_CASE("without a blocking slot a job call returns its envelope at once and an inline call returns pending", "[Mcp]") -{ - Harness h; - h.timing.blocking_slots = 1; - std::atomic<bool> release{false}; - NativeCommand hold = tool("hold", GuardClass::Inspect, [&](const json&, ToolContext&) { - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - }); - hold.inline_call = true; - h.registry.add(hold); - h.registry.add(tool("work", GuardClass::Mutate, [](const json&, ToolContext&) { - std::this_thread::sleep_for(50ms); - return ToolResult::ok(); - })); - h.start(); - - auto holder = std::async(std::launch::async, [&] { return h.core->call(*h.registry.find("hold"), json::object()); }); - std::this_thread::sleep_for(100ms); - const auto start = std::chrono::steady_clock::now(); - const ToolResult job = h.core->call(*h.registry.find("work"), json::object()); - CHECK(job.data["status"] == "running"); - const ToolResult pending = h.core->call(*h.registry.find("hold"), json::object()); - CHECK(pending.data["status"] == "pending"); - CHECK(std::chrono::steady_clock::now() - start < 500ms); - release = true; - (void) holder.get(); - CHECK(h.jobs.wait(job.data["job"], 3000ms).has_value()); -} - -TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]") -{ - JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string step = jobs.create("slice", replay_job); - const std::string other = jobs.create("open_files", ""); - CHECK(jobs.lineage(step) == std::set<std::string>{step, replay_job}); - CHECK(jobs.any_running_except(jobs.lineage(step))); - jobs.finish(other, ToolResult::ok()); - CHECK_FALSE(jobs.any_running_except(jobs.lineage(step))); - jobs.begin_operation(step); - CHECK(jobs.running_operations() == std::vector<std::string>{step}); -} - -TEST_CASE("idle skips a job set idle, but not the calls it makes", "[Mcp]") -{ - JobRegistry jobs; - const std::string run = jobs.create("run_script", ""); - jobs.set_idle(run); - const std::string child = jobs.create("slice", run); - CHECK(jobs.any_running_except({})); - bool listed_idle = false; - for (const nlohmann::json& job : jobs.list()) - if (job["id"] == run) - listed_idle = job.value("idle", false); - CHECK(listed_idle); - jobs.finish(child, ToolResult::ok()); - CHECK_FALSE(jobs.any_running_except({})); -} - -TEST_CASE("the job registry caps running jobs and forgets old finished ones", "[Mcp]") -{ - JobRegistry jobs; - std::vector<std::string> ids; - for (std::size_t i = 0; i < JobRegistry::kMaxRunning; ++i) - ids.push_back(jobs.create("t", "")); - CHECK_THROWS_AS(jobs.create("t", ""), ToolFailure); - for (const std::string& id : ids) - jobs.finish(id, ToolResult::ok()); - for (std::size_t i = 0; i < JobRegistry::kKeepFinished; ++i) - jobs.finish(jobs.create("t", ""), ToolResult::ok()); - CHECK_THROWS_AS(jobs.wait(ids.front(), 0ms), ToolFailure); -} - -TEST_CASE("a caller waits for its running UI closure even through shutdown", "[Mcp]") -{ - ManualDispatcher ui; - UiInvoker invoker(ui, [] { return GuardState{}; }); - std::atomic<bool> inside{false}, release{false}, finished{false}; - auto caller = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Inspect, "look", [&] { - inside = true; - ui.pump_until([&] { return release.load(); }); // a nested event loop - finished = true; - return json(); - }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - std::thread ui_thread([&] { ui.pump_until([&] { return finished.load(); }, 5000ms); }); - while (!inside) - std::this_thread::sleep_for(5ms); - invoker.shutdown(); - // The closure still uses the caller's stack, so the caller must not have returned. - CHECK(caller.wait_for(200ms) == std::future_status::timeout); - release = true; - ui_thread.join(); - CHECK(caller.get() == "ok"); -} - -TEST_CASE("a closure queued before a UI rebuild does not run after it", "[Mcp]") -{ - ManualDispatcher ui; - std::atomic<uint64_t> generation{1}; - UiInvoker invoker(ui, [] { return GuardState{}; }, [&] { return generation.load(); }); - std::atomic<bool> ran{false}; - auto caller = std::async(std::launch::async, [&]() -> std::string { - try { - invoker.run(GuardClass::Mutate, "click", [&] { - ran = true; - return json(); - }); - return "ok"; - } catch (const ToolFailure& f) { - return f.what(); - } - }); - std::this_thread::sleep_for(50ms); - generation = 2; // a language change rebuilt the UI while the closure waited - ui.pump_until([&] { return caller.wait_for(0ms) == std::future_status::ready; }); - CHECK(caller.get().find("recreated") != std::string::npos); - CHECK_FALSE(ran); -} - -TEST_CASE("operation admission is checked again when a mutate call reaches the UI thread", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - h.registry.add(tool("edit", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([] { return json("edited"); })); - })); - NativeCommand slice = tool("slice", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - ctx.run_ui([&] { - ctx.begin_operation(); - return json(); - }); - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - }); - h.registry.add(slice); - h.start(); - // The UI thread is held, so both calls are admitted before either runs; the slice runs first. - std::atomic<bool> hold{true}; - h.ui.post([&] { - while (hold) - std::this_thread::sleep_for(5ms); - }); - auto s = std::async(std::launch::async, [&] { return h.call("slice"); }); - std::this_thread::sleep_for(100ms); - auto e = std::async(std::launch::async, [&] { return h.call("edit"); }); - std::this_thread::sleep_for(100ms); - hold = false; - const ToolResult edited = e.get(); - CHECK(edited.is_error); - CHECK(edited.message.find("Busy: job") != std::string::npos); - release = true; - (void) s.get(); -} - -TEST_CASE("only one operation runs at a time", "[Mcp]") -{ - JobRegistry jobs; - const std::string a = jobs.create("slice", ""); - const std::string b = jobs.create("export", ""); - CHECK(jobs.begin_operation(a).empty()); - CHECK(jobs.begin_operation(b) == a); - jobs.finish(a, ToolResult::ok()); - CHECK(jobs.begin_operation(b).empty()); -} - -TEST_CASE("ancestry lists the job chain nearest first", "[Mcp]") -{ - JobRegistry jobs; - const std::string outer = jobs.create("run_replay", ""); - const std::string inner = jobs.create("run_replay", outer); - const std::string step = jobs.create("auto_answer_dialogs", inner); - CHECK(jobs.ancestry(step) == std::vector<std::string>{step, inner, outer}); -} - -TEST_CASE("a stop asked for a job reaches its descendants and no other job", "[Mcp]") -{ - JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string step = jobs.create("slice", replay_job); - const std::string other = jobs.create("open_files", ""); - CHECK_FALSE(jobs.stop_requested(step)); - jobs.request_stop(replay_job); - CHECK(jobs.stop_requested(replay_job)); - CHECK(jobs.stop_requested(step)); - CHECK_FALSE(jobs.stop_requested(other)); - CHECK_FALSE(jobs.stop_requested("")); -} - -TEST_CASE("a job wait with a stop check looks once at zero timeout and ends when stopped", "[Mcp]") -{ - JobRegistry jobs; - const std::string done = jobs.create("slice", ""); - jobs.finish(done, ToolResult::ok({{"done", true}})); - const std::string running = jobs.create("slice", ""); - const auto never = [] { return false; }; - - const auto finished = jobs.wait(done, 0ms, never); - REQUIRE(finished.has_value()); - CHECK(finished->data["done"] == true); - CHECK_FALSE(jobs.wait(running, 0ms, never).has_value()); - CHECK_THROWS_AS(jobs.wait("j999", 0ms, never), ToolFailure); - - const auto start = std::chrono::steady_clock::now(); - CHECK_FALSE(jobs.wait(running, 5000ms, [] { return true; }).has_value()); - CHECK(std::chrono::steady_clock::now() - start < 2s); -} - -TEST_CASE("a call made by a stopped job sees itself cancelled", "[Mcp]") -{ - Harness h; - // An inline call that polls for cancellation, as wait does. - NativeCommand spin = tool("spin", GuardClass::Inspect, [](const json&, ToolContext& ctx) { - const auto end = std::chrono::steady_clock::now() + 5s; - while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) - std::this_thread::sleep_for(10ms); - return ToolResult::ok({{"cancelled", ctx.cancelled()}}); - }); - spin.inline_call = true; - h.registry.add(spin); - NativeCommand replay = tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ctx.call_child("spin", json::object()); }); - replay.budget_ms = 50; - h.registry.add(replay); - h.start(); - - const ToolResult envelope = h.call("replay"); - REQUIRE(envelope.data["status"] == "running"); - const auto asked = std::chrono::steady_clock::now(); - h.jobs.request_stop(envelope.data["job"]); - const auto result = h.jobs.wait(envelope.data["job"], 3000ms); - REQUIRE(result.has_value()); - CHECK(result->data["cancelled"] == true); - CHECK(std::chrono::steady_clock::now() - asked < 2s); -} - -TEST_CASE("a live descendant keeps its lineage after its ancestors are evicted", "[Mcp]") -{ - JobRegistry jobs; - const std::string root = jobs.create("run_replay", ""); - const std::string inner = jobs.create("run_replay", root); - const std::string leaf = jobs.create("wait", inner); - jobs.finish(inner, ToolResult::ok()); - jobs.finish(root, ToolResult::ok()); - for (int i = 0; i < 70; ++i) - jobs.finish(jobs.create("t", ""), ToolResult::ok()); - CHECK_THROWS_AS(jobs.wait(inner, 0ms), ToolFailure); // evicted - const std::set<std::string> lineage = jobs.lineage(leaf); - CHECK(lineage.count(root) == 1); - CHECK(lineage.count(inner) == 1); - CHECK(jobs.ancestry(leaf) == std::vector<std::string>{leaf, inner, root}); -} - -TEST_CASE("a finished job stays while its parent replay runs", "[Mcp]") -{ - JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string saved = jobs.create("run_action", replay_job); - jobs.finish(saved, ToolResult::ok({{"x", 1}})); - for (std::size_t i = 0; i < JobRegistry::kKeepFinished + 5; ++i) - jobs.finish(jobs.create("t", ""), ToolResult::ok()); - CHECK(jobs.wait(saved, 0ms).has_value()); - jobs.finish(replay_job, ToolResult::ok()); - for (std::size_t i = 0; i < JobRegistry::kKeepFinished + 5; ++i) - jobs.finish(jobs.create("t", ""), ToolResult::ok()); - CHECK_THROWS_AS(jobs.wait(saved, 0ms), ToolFailure); -} - -TEST_CASE("finished jobs stay bounded while their parent replay runs", "[Mcp]") -{ - JobRegistry jobs; - const std::string replay_job = jobs.create("run_replay", ""); - const std::string first = jobs.create("t", replay_job); - jobs.finish(first, ToolResult::ok()); - for (std::size_t i = 0; i < JobRegistry::kKeepFinishedMax; ++i) - jobs.finish(jobs.create("t", replay_job), ToolResult::ok()); - CHECK_THROWS_AS(jobs.wait(first, 0ms), ToolFailure); - const std::string recent = jobs.create("t", replay_job); - jobs.finish(recent, ToolResult::ok()); - CHECK(jobs.wait(recent, 0ms).has_value()); -} - -TEST_CASE("the journal keeps a call waiting for its reply when it drops old calls", "[Mcp]") -{ - Journal journal; - const uint64_t waiting = journal.begin("slice", json::object()); - for (int i = 0; i < 6000; ++i) - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", i}}}}), ToolResult::ok()); - journal.end(waiting, ToolResult::ok()); - const json steps = journal.to_replay("s")["steps"]; - REQUIRE_FALSE(steps.empty()); - CHECK(steps[0]["tool"] == "slice"); - CHECK(steps.size() == 5000); -} - -TEST_CASE("the journal keeps at most 64 MiB of arguments", "[Mcp]") -{ - Journal journal; - const json big = args_of_mib(1); - for (int i = 0; i < 100; ++i) - journal.end(journal.begin("set_settings", big), ToolResult::ok()); - const json steps = journal.to_replay("s")["steps"]; - CHECK(steps.size() < 64); - CHECK(steps.size() > 56); -} - -TEST_CASE("calls waiting for their reply outlast the byte cap and go once they finish", "[Mcp]") -{ - Journal journal; - const json big = args_of_mib(1); - std::vector<uint64_t> waiting; - for (int i = 0; i < 70; ++i) - waiting.push_back(journal.begin("set_settings", big)); - json left; - CHECK(journal.to_replay("s", &left)["steps"].empty()); - CHECK(left.size() == 70); - // Each reply trims on its own, with no later begin or set_args. - for (const uint64_t seq : waiting) - journal.end(seq, ToolResult::ok()); - CHECK(journal.to_replay("s", &left)["steps"].size() < 64); - CHECK(left.empty()); -} - -TEST_CASE("a job's call over the byte cap stays until its job ends", "[Mcp]") -{ - Journal journal; - const json huge = args_of_mib(65); - json left; - - // The reply comes first, as the job's envelope; the job ends later. - const uint64_t seq = journal.begin("thread", huge); - journal.job_started(seq, "j"); - journal.end(seq, ToolResult::ok({{"status", "running"}, {"job", "j"}})); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - REQUIRE(left.size() == 1); - CHECK(left[0] == json{{"tool", "thread"}, {"job", "j"}}); - journal.job_ended(seq, ToolResult::ok()); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - CHECK(left.empty()); - - // The job ends before its reply. - const uint64_t seq2 = journal.begin("thread", huge); - journal.job_started(seq2, "k"); - journal.job_ended(seq2, ToolResult::ok()); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - CHECK(left.empty()); - journal.end(seq2, ToolResult::ok()); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - CHECK(left.empty()); -} - -TEST_CASE("replacing a call's arguments moves the journal's byte total", "[Mcp]") -{ - Journal journal; - const json fifteen = args_of_mib(15); - json left; - for (int i = 0; i < 4; ++i) - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); - // 60 MiB, then 70 MiB once the small call's arguments grow: the first 15 MiB call goes at once, - // while the grown call still waits for its reply. - const uint64_t b = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); - journal.set_args(b, args_of_mib(10)); - CHECK(journal.to_replay("s", &left)["steps"].size() == 3); - CHECK(left.size() == 1); - journal.end(b, ToolResult::ok()); - CHECK(journal.to_replay("s")["steps"].size() == 4); - // Shrinking them back leaves 45 MiB, room for one more 15 MiB call. - journal.set_args(b, {{"values", {{"wall_loops", 3}}}}); - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); - CHECK(journal.to_replay("s")["steps"].size() == 5); -} - -TEST_CASE("clearing the journal resets its byte total", "[Mcp]") -{ - Journal journal; - const json fifteen = args_of_mib(15); - for (int i = 0; i < 4; ++i) - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); - journal.clear(); - // Were the cleared calls' 60 MiB still counted, this 15 MiB call would go once it replied. - journal.end(journal.begin("set_settings", fifteen), ToolResult::ok()); - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); - CHECK(journal.to_replay("s")["steps"].size() == 2); -} - -TEST_CASE("one call bigger than the cap is dropped once it has replied", "[Mcp]") -{ - Journal journal; - json left; - const uint64_t seq = journal.begin("thread", args_of_mib(65)); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - REQUIRE(left.size() == 1); - CHECK(left[0] == json{{"tool", "thread"}}); - journal.end(seq, ToolResult::ok()); - CHECK(journal.to_replay("s", &left)["steps"].empty()); - CHECK(left.empty()); - // The total is back to what the remaining calls hold, so a small call stays. - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); - CHECK(journal.to_replay("s")["steps"].size() == 1); -} - -TEST_CASE("a job refused at shutdown after it registered ends its journal entry", "[Mcp]") -{ - ManualDispatcher ui; - McpCore* core_ptr = nullptr; - // A recover call's journal entry reads the open dialogs between the core's two shutdown checks: - // shutting down there lets the call register its job, then refuses it. - UiInvoker invoker(ui, [] { return GuardState{}; }, {}, [&core_ptr] { - core_ptr->shutdown(); - return json::array(); - }); - JobRegistry jobs; - Journal journal; - CommandCatalog registry; - registry.add(tool("answer_dialog", GuardClass::Recover, [](const json&, ToolContext&) { return ToolResult::ok(); })); - McpCore core(registry, invoker, jobs, &journal, CoreTiming{}); - core_ptr = &core; - - const ToolResult r = core.call(*registry.find("answer_dialog"), args_of_mib(65)); - REQUIRE(r.is_error); - CHECK(r.message == "OrcaSlicer is shutting down"); - // An entry left running would hold its 65 MiB against the cap, so the next call, not it, would go. - journal.end(journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}), ToolResult::ok()); - CHECK(journal.to_replay("s")["steps"].size() == 1); -} - -TEST_CASE("drain reports a job thread that has not returned", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - h.registry.add(tool("stuck", GuardClass::Mutate, [&](const json&, ToolContext&) { - while (!release) - std::this_thread::sleep_for(10ms); - return ToolResult::ok(); - })); - h.timing.soft_budget = 50ms; - h.start(); - auto call = std::async(std::launch::async, [&] { return h.call("stuck"); }); - std::this_thread::sleep_for(100ms); - h.core->shutdown(); - CHECK_FALSE(h.core->drain(200ms)); - release = true; - (void) call.get(); - CHECK(h.core->drain(2000ms)); -} - -TEST_CASE("destroying a core waits for a job thread still inside it", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - std::atomic<bool> returned{false}; - h.registry.add(tool("stuck", GuardClass::Mutate, [&](const json&, ToolContext&) { - while (!release) - std::this_thread::sleep_for(10ms); - std::this_thread::sleep_for(50ms); - returned = true; - return ToolResult::ok(); - })); - h.timing.soft_budget = 50ms; - h.start(); - auto call = std::async(std::launch::async, [&] { return h.call("stuck"); }); - std::this_thread::sleep_for(100ms); - h.core->shutdown(); - auto destroy = std::async(std::launch::async, [&] { h.core.reset(); }); - CHECK(destroy.wait_for(300ms) == std::future_status::timeout); - release = true; - destroy.get(); - CHECK(returned); - (void) call.get(); -} - -TEST_CASE("the journal records client calls in order and replays jobs with await false", "[Mcp]") -{ - Journal journal; - const uint64_t a = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); - journal.job_started(a, "j7"); - journal.end(a, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j7"}})); - const uint64_t b = journal.begin("answer_dialog", {{"button", "close"}}); - journal.end(b, ToolResult::ok()); - const uint64_t c = journal.begin("wait", {{"for", "job"}, {"job", "j7"}}); - journal.end(c, ToolResult::ok()); - const uint64_t d = journal.begin("screenshot", {{"target", "canvas"}, {"save_path", "/tmp/x/after.png"}}); - journal.end(d, ToolResult::ok()); - const uint64_t e = journal.begin("set_settings", {{"values", {{"wall_loops", 3}}}}); - journal.end(e, ToolResult::error("no")); - - const json exported = journal.to_replay("repro"); - REQUIRE(exported["steps"].size() == 4); - CHECK(exported["steps"][0]["await"] == false); - CHECK(exported["steps"][0]["save_as"] == "job1"); - CHECK(exported["steps"][1]["tool"] == "answer_dialog"); - CHECK(exported["steps"][2]["args"]["job"] == "${jobs.job1}"); - CHECK(exported["steps"][3]["args"]["save_path"] == "${out_dir}/after.png"); -} - -TEST_CASE("only client calls of journaled tools reach the journal", "[Mcp]") -{ - Harness h; - NativeCommand look = tool("get_app_state", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); - look.inline_call = true; - look.journal = false; - h.registry.add(look); - NativeCommand wait = tool("wait", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); }); - wait.inline_call = true; - h.registry.add(wait); - h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext& ctx) { - ctx.set_journal_args({{"values", {{"wall_loops", 3}}}, {"scope", "process"}}); - return ToolResult::ok(); - })); - h.start(); - h.call("get_app_state"); - h.call("wait", {{"for", "idle"}}); - h.call("set_settings", {{"values", {{"wall_loops", 3}}}}); - const json steps = h.journal.to_replay("x")["steps"]; - REQUIRE(steps.size() == 2); - CHECK(steps[0]["tool"] == "wait"); - CHECK(steps[1]["args"]["scope"] == "process"); -} - -TEST_CASE("a plugin's call runs as the plugin's own job and never reaches the journal", "[Mcp]") -{ - Harness h; - std::string seen, child_seen; - h.registry.add(tool("get_app_state", GuardClass::Inspect, [&child_seen](const json&, ToolContext& ctx) { - child_seen = ctx.caller_plugin(); - return ToolResult::ok(); - })); - h.registry.add(tool("set_settings", GuardClass::Mutate, [&seen](const json&, ToolContext& ctx) { - seen = ctx.caller_plugin(); - // A call it makes, as a replay step does, is the plugin's too. - ctx.call_child("get_app_state", json::object()); - return ToolResult::ok({{"job", ctx.job_id()}}); - })); - h.start(); - const ToolResult r = h.core->call_plugin(*h.registry.find("set_settings"), json::object(), "measure-plugin"); - REQUIRE_FALSE(r.is_error); - CHECK(seen == "measure-plugin"); - CHECK(child_seen == "measure-plugin"); - CHECK(h.jobs.owner(r.data["job"].get<std::string>()) == "measure-plugin"); - CHECK(h.journal.to_replay("x")["steps"].empty()); - - // A client's call has no plugin. - h.call("set_settings"); - CHECK(seen.empty()); - CHECK(h.journal.to_replay("x")["steps"].size() == 1); -} - -TEST_CASE("call_tool is journaled as the tool it calls", "[Mcp]") -{ - Harness h; - h.registry.add(tool("set_settings", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - NativeCommand api = tool("call_tool", GuardClass::Mutate, [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }); - api.input_schema = {{"type", "object"}, {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}}; - h.registry.add(api); - h.start(); - McpProtocol protocol(h.registry, *h.core, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", ""}); - const PostReply reply = protocol.handle_post(PostRequest{json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "set_settings"}, {"args", {{"values", {{"wall_loops", 3}}}}}}}}}}.dump()}); - CHECK(json::parse(reply.body)["result"].value("isError", false) == false); - const json steps = h.journal.to_replay("x")["steps"]; - REQUIRE(steps.size() == 1); - CHECK(steps[0]["tool"] == "set_settings"); - CHECK(steps[0]["args"]["values"]["wall_loops"] == 3); -} - -TEST_CASE("a plugin's session tools act only on the jobs of its own calls", "[Mcp]") -{ - Harness h; - h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext& ctx) { return ToolResult::ok({{"job", ctx.job_id()}}); })); - h.registry.add(tool("peek", GuardClass::Mutate, [&h](const json& args, ToolContext& ctx) { - require_own_job(ctx, h.jobs, args.value("job", std::string()), "waits for"); - return ToolResult::ok(); - })); - h.start(); - const std::string clients = h.call("make").data["job"].get<std::string>(); - const std::string plugins = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").data["job"].get<std::string>(); - - const ToolResult foreign = h.core->call_plugin(*h.registry.find("peek"), json{{"job", clients}}, "measure"); - CHECK(foreign.is_error); - CHECK(foreign.message.find("only the jobs of its own calls") != std::string::npos); - CHECK_FALSE(h.core->call_plugin(*h.registry.find("peek"), json{{"job", plugins}}, "measure").is_error); - // A client's call is not a plugin's, whoever's job it names. - CHECK_FALSE(h.call("peek", json{{"job", plugins}}).is_error); -} - -TEST_CASE("an unloaded plugin's calls start no job, nor do the children of one already running", "[Mcp]") -{ - Harness h; - std::atomic<bool> release{false}; - ToolResult child; - h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.registry.add(tool("slow", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - while (!release) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - child = ctx.call_child("make", json::object()); - return ToolResult::ok(); - })); - h.timing.soft_budget = std::chrono::milliseconds(10000); - h.start(); - // A call that was admitted before the unload and is still running when it comes. - std::thread running([&] { h.core->call_plugin(*h.registry.find("slow"), json::object(), "measure"); }); - while (h.jobs.running_owned_by("measure").empty()) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - - h.jobs.block_owner("measure"); - const ToolResult late = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure"); - CHECK(late.is_error); - CHECK(late.message.find("unloaded") != std::string::npos); - release = true; - running.join(); - CHECK(child.is_error); - - // Another plugin's calls and a client's are not affected; a load lifts the block. - CHECK_FALSE(h.core->call_plugin(*h.registry.find("make"), json::object(), "other").is_error); - CHECK_FALSE(h.call("make").is_error); - h.jobs.unblock_owner("measure"); - CHECK_FALSE(h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").is_error); -} - -TEST_CASE("a plugin's calls are refused once it unloads, before the block comes, inline calls included", "[Mcp]") -{ - Harness h; - std::atomic<bool> loaded{true}; - std::atomic<bool> release{false}; - std::atomic<int> looks{0}; - ToolResult inline_child; - ToolResult job_child; - // The plugin manager's state, which changes as the plugin unloads; end_plugin_scope()'s block comes later. - h.jobs.set_owner_liveness([&](const std::string& plugin) { return plugin != "measure" || loaded; }); - NativeCommand look = tool("look", GuardClass::Inspect, [&](const json&, ToolContext&) { ++looks; return ToolResult::ok(); }); - look.inline_call = true; - h.registry.add(look); - h.registry.add(tool("make", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); })); - h.registry.add(tool("slow", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - while (!release) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - inline_child = ctx.call_child("look", json::object()); - job_child = ctx.call_child("make", json::object()); - return ToolResult::ok(); - })); - h.timing.soft_budget = std::chrono::milliseconds(10000); - h.start(); - std::thread running([&] { h.core->call_plugin(*h.registry.find("slow"), json::object(), "measure"); }); - while (h.jobs.running_owned_by("measure").empty()) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - - loaded = false; - const ToolResult inline_call = h.core->call_plugin(*h.registry.find("look"), json::object(), "measure"); - CHECK(inline_call.is_error); - CHECK(inline_call.message.find("unloaded") != std::string::npos); - CHECK(h.core->call_plugin(*h.registry.find("make"), json::object(), "measure").is_error); - release = true; - running.join(); - CHECK(inline_child.is_error); - CHECK(job_child.is_error); - CHECK(looks == 0); - - // Another plugin's calls and a client's still run, and so do the plugin's once it is loaded again. - CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "other").is_error); - CHECK_FALSE(h.call("look").is_error); - loaded = true; - CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "measure").is_error); - CHECK(looks == 3); -} - -TEST_CASE("a plugin's job never starts once the plugin unloads, as it registers or right before its handler", "[Mcp]") -{ - // The liveness hook is asked as the call comes in, once its job is registered, and on the job's thread right - // before its handler starts: the plugin unloads just before the asking given here. - const int unload_at = GENERATE(1, 2, 3); - Harness h; - std::atomic<int> asked{0}; - std::atomic<int> ran{0}; - std::atomic<bool> loaded{true}; - h.jobs.set_owner_liveness([&](const std::string&) { - if (++asked == unload_at) - loaded = false; - return loaded.load(); - }); - h.registry.add(tool("make", GuardClass::Mutate, [&](const json&, ToolContext&) { ++ran; return ToolResult::ok(); })); - h.timing.soft_budget = std::chrono::milliseconds(10000); - h.start(); - const ToolResult r = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure"); - CHECK(r.is_error); - CHECK(r.message.find("unloaded") != std::string::npos); - CHECK(ran == 0); - CHECK(h.jobs.running_owned_by("measure").empty()); -} - -TEST_CASE("a plugin's running call is cancelled the moment the plugin unloads", "[Mcp]") -{ - Harness h; - std::atomic<bool> loaded{true}; - std::atomic<bool> started{false}; - h.jobs.set_owner_liveness([&](const std::string&) { return loaded.load(); }); - h.registry.add(tool("spin", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { - started = true; - const auto end = std::chrono::steady_clock::now() + std::chrono::seconds(10); - while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - return ToolResult::ok({{"cancelled", ctx.cancelled()}}); - })); - h.timing.soft_budget = std::chrono::milliseconds(10000); - h.start(); - // No block and no stop request: only the plugin manager's state changes. - std::thread unload([&] { - while (!started) - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - loaded = false; - }); - const ToolResult r = h.core->call_plugin(*h.registry.find("spin"), json::object(), "measure"); - unload.join(); - CHECK_FALSE(r.is_error); - CHECK(r.data.value("cancelled", false)); -} - -TEST_CASE("a call under a lineage node sees a stop asked for the node, inline calls included, and a renewed node's calls run", "[Mcp]") -{ - Harness h; - // Polls for cancellation for up to `for_ms`, as wait does. - const auto poll = [](const json& args, ToolContext& ctx) { - const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(args.value("for_ms", 5000)); - while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) - std::this_thread::sleep_for(10ms); - return ToolResult::ok({{"cancelled", ctx.cancelled()}}); - }; - NativeCommand inline_poll = tool("inline_poll", GuardClass::Inspect, poll); - inline_poll.inline_call = true; - h.registry.add(inline_poll); - h.registry.add(tool("job_poll", GuardClass::Mutate, poll)); - h.timing.soft_budget = 10000ms; - h.start(); - - const std::string session = h.jobs.create("run_script", ""); - h.jobs.set_idle(session); - LineageNode node(h.jobs, "run_script", session); - const auto call = [&](const char* tool, int for_ms) { - return std::async(std::launch::async, [&h, &node, tool, for_ms] { - return h.core->call_child_named(tool, {{"for_ms", for_ms}}, node.id()); - }); - }; - auto inline_call = call("inline_poll", 5000); - auto job_call = call("job_poll", 5000); - std::this_thread::sleep_for(300ms); - const auto asked = std::chrono::steady_clock::now(); - h.jobs.request_stop(node.id()); - const ToolResult stopped_inline = inline_call.get(); - const ToolResult stopped_job = job_call.get(); - CHECK(std::chrono::steady_clock::now() - asked < 1s); - CHECK(stopped_inline.data.value("cancelled", false)); - CHECK(stopped_job.data.value("cancelled", false)); - - node.renew(); - auto ran_inline = call("inline_poll", 300); - auto ran_job = call("job_poll", 300); - CHECK(ran_inline.get().data["cancelled"] == false); - CHECK(ran_job.get().data["cancelled"] == false); - CHECK_FALSE(h.jobs.stop_requested(session)); - h.jobs.finish(session, ToolResult::ok()); -} - -TEST_CASE("lineage nodes leave no running job behind", "[Mcp]") -{ - JobRegistry jobs; - const std::string session = jobs.create("run_script", ""); - const auto running_nodes = [&] { - int count = 0; - for (const json& job : jobs.list()) - if (job["tool"] == "run_script" && job.value("parent", std::string()) == session && job["state"] == "running") - ++count; - return count; - }; - { - LineageNode node(jobs, "run_script", session); - CHECK(running_nodes() == 1); - } - for (int round = 0; round < 10; ++round) { - LineageNode node(jobs, "run_script", session); - for (int renewal = 0; renewal < 3; ++renewal) - node.renew(); - CHECK(running_nodes() == 1); - } - CHECK(running_nodes() == 0); - jobs.finish(session, ToolResult::ok()); -} diff --git a/tests/slic3rutils/test_mcp_protocol.cpp b/tests/slic3rutils/test_mcp_protocol.cpp index 3548aadb5b..cf0b99ad4e 100644 --- a/tests/slic3rutils/test_mcp_protocol.cpp +++ b/tests/slic3rutils/test_mcp_protocol.cpp @@ -1,149 +1,36 @@ #include <catch2/catch_test_macros.hpp> +#include "automation/automation_test_utils.hpp" + #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/Mcp/McpProtocol.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" -#include "slic3r/GUI/Mcp/McpStdioBridge.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "libslic3r_version.h" #include <nlohmann/json.hpp> #include <algorithm> -#include <functional> #include <set> -#include <memory> #include <string> -#include <utility> #include <vector> +// The protocol's cases that read the catalog NativeCommands builds. The others are in +// tests/automation/test_mcp_protocol.cpp. + +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; using Slic3r::GUI::CommandCatalog; -using Slic3r::GUI::CommandSource; using Slic3r::GUI::NativeCommand; +using Slic3r::GUI::Mcp::Test::DirectCaller; namespace NativeCommands = Slic3r::GUI::NativeCommands; namespace { -// Runs handlers directly on the calling thread, as if every call were inline. -class DirectCaller final : public ToolCaller -{ -public: - std::vector<std::string> called; // the tools it ran, in order - - ToolResult call(const NativeCommand& def, const json& args) override - { - called.push_back(def.key); - struct Context final : ToolContext - { - std::string id; - json run_ui(const std::function<json()>& fn) override { return fn(); } - json observe_ui(const std::function<json()>& fn) override { return fn(); } - const std::string& job_id() const override { return id; } - bool cancelled() const override { return false; } - ToolResult call_child(const std::string&, const json&) override { return ToolResult::error("no children"); } - std::set<std::string> lineage() const override { return {}; } - void set_journal_args(json) override {} - void begin_operation() override {} - } ctx; - return def.run(args, ctx); - } -}; - -struct Fixture -{ - CommandCatalog registry; - DirectCaller caller; - McpProtocol protocol{registry, caller, ServerInfo{"orcaslicer", "OrcaSlicer", "9.9.9", "Use get_app_state first."}}; - - Fixture() - { - NativeCommand echo; - echo.key = "echo"; - echo.listed = true; - echo.description = "Echo text back."; - echo.read_only = true; - echo.idempotent = true; - echo.input_schema = {{"type", "object"}, - {"properties", {{"text", {{"type", "string"}}}}}, - {"required", {"text"}}, - {"additionalProperties", false}}; - echo.run = [](const json& args, ToolContext&) { return ToolResult::ok({{"echo", args["text"]}}); }; - registry.add(echo); - - NativeCommand fail; - fail.key = "fail"; - fail.listed = true; - fail.destructive = true; - fail.open_world = true; - fail.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("it broke", {{"why", "test"}}); }; - registry.add(fail); - } - - PostReply post(const json& msg, const std::string& version = {}, const std::string& method = {}, const std::string& name = {}) - { - return protocol.handle_post(PostRequest{msg.dump(), version, method, name}); - } -}; - json body(const PostReply& r) { return json::parse(r.body); } -json modern_params(json params = json::object()) -{ - params["_meta"] = {{"io.modelcontextprotocol/protocolVersion", "2026-07-28"}}; - return params; -} - } // namespace -TEST_CASE("initialize echoes a supported client version", "[Mcp]") -{ - Fixture f; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"}, {"params", {{"protocolVersion", "2025-06-18"}}}}); - REQUIRE(r.status == 200); - const json result = body(r)["result"]; - CHECK(result["protocolVersion"] == "2025-06-18"); - CHECK(result["serverInfo"]["name"] == "orcaslicer"); - CHECK(result["capabilities"].contains("tools")); - CHECK(result["instructions"] == "Use get_app_state first."); -} - -TEST_CASE("initialize answers an unsupported version with the latest supported one", "[Mcp]") -{ - Fixture f; - for (const char* requested : {"2025-03-26", "1999-01-01"}) { - const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"}, {"params", {{"protocolVersion", requested}}}}))["result"]; - CHECK(result["protocolVersion"] == "2025-11-25"); - } -} - -TEST_CASE("notifications are accepted with 202 and no body", "[Mcp]") -{ - Fixture f; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"method", "notifications/initialized"}}); - CHECK(r.status == 202); - CHECK(r.body.empty()); -} - -TEST_CASE("tools/list keeps registration order and maps annotations", "[Mcp]") -{ - Fixture f; - const json tools = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/list"}}))["result"]["tools"]; - REQUIRE(tools.size() == 2); - CHECK(tools[0]["name"] == "echo"); - CHECK(tools[1]["name"] == "fail"); - CHECK(tools[0]["annotations"]["readOnlyHint"] == true); - CHECK(tools[0]["annotations"]["idempotentHint"] == true); - CHECK(tools[0]["annotations"]["destructiveHint"] == false); - CHECK(tools[0]["annotations"]["openWorldHint"] == false); - CHECK(tools[1]["annotations"]["readOnlyHint"] == false); - CHECK(tools[1]["annotations"]["destructiveHint"] == true); - CHECK(tools[1]["annotations"]["openWorldHint"] == true); - CHECK(tools[0]["inputSchema"]["required"][0] == "text"); -} - TEST_CASE("tools/list lists the listed commands in the order they were added", "[Mcp]") { const CommandCatalog& catalog = NativeCommands::instance(); @@ -174,90 +61,6 @@ TEST_CASE("tools/list lists the listed commands in the order they were added", " CHECK(position("slice") < position("click")); } -TEST_CASE("tools/call returns the result as a JSON text block", "[Mcp]") -{ - Fixture f; - const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 3}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"text", "hi"}}}}}}))["result"]; - CHECK_FALSE(result.contains("isError")); - CHECK_FALSE(result.contains("structuredContent")); - REQUIRE(result["content"].size() == 1); - CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"echo", "hi"}}); -} - -TEST_CASE("tool failures and invalid arguments are isError results", "[Mcp]") -{ - Fixture f; - const json failed = body(f.post({{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"}, {"params", {{"name", "fail"}}}}))["result"]; - CHECK(failed["isError"] == true); - CHECK(failed["content"][0]["text"].get<std::string>().find("it broke") != std::string::npos); - - const json bad = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"txt", "hi"}}}}}}))["result"]; - CHECK(bad["isError"] == true); - const std::string text = bad["content"][0]["text"]; - CHECK(text.find("text is required") != std::string::npos); -} - -TEST_CASE("an unknown tool is a JSON-RPC error with suggestions", "[Mcp]") -{ - Fixture f; - const json reply = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, {"params", {{"name", "ecko"}}}})); - CHECK(reply["error"]["code"] == -32602); - CHECK(reply["error"]["data"]["did_you_mean"][0] == "echo"); -} - -TEST_CASE("one edit distance serves every did-you-mean", "[Mcp]") -{ - CHECK(edit_distance("fillet", "filet") == 1); - CHECK(edit_distance("", "abc") == 3); - CHECK(edit_distance("a", "a") == 0); -} - -TEST_CASE("malformed messages are rejected", "[Mcp]") -{ - Fixture f; - PostReply r = f.protocol.handle_post(PostRequest{"{not json", {}, {}, {}}); - CHECK(r.status == 400); - CHECK(body(r)["error"]["code"] == -32700); - - r = f.post(json::array({{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "ping"}}})); - CHECK(r.status == 400); - CHECK(body(r)["error"]["code"] == -32600); - - r = f.post({{"jsonrpc", "2.0"}, {"id", nullptr}, {"method", "ping"}}); - CHECK(body(r)["error"]["code"] == -32600); - - r = f.post({{"jsonrpc", "1.0"}, {"id", 1}, {"method", "ping"}}); - CHECK(body(r)["error"]["code"] == -32600); - - // A jsonrpc that is not a string is the same error, never an exception: the stdio bridge calls - // handle_post directly. - for (const json& version : {json(2), json(nullptr), json::object()}) { - r = f.post({{"jsonrpc", version}, {"id", 1}, {"method", "ping"}}); - CHECK(r.status == 400); - CHECK(body(r)["error"]["code"] == -32600); - } -} - -TEST_CASE("params that are not an object are invalid params", "[Mcp]") -{ - Fixture f; - PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", json::array()}}); - CHECK(body(r)["error"]["code"] == -32602); - r = f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "ping"}, {"params", 3}}); - CHECK(body(r)["error"]["code"] == -32602); -} - -TEST_CASE("the stdio bridge derives no headers from a line that is not a message object", "[Mcp]") -{ - CHECK(bridge_headers(json::array({{{"method", "ping"}}}), "2025-06-18").empty()); - CHECK(bridge_headers(json(42), {}).empty()); - CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", "get_app_state"}}}}, "2025-06-18") - .count("MCP-Protocol-Version") == 1); - // Members of the wrong type are left out rather than thrown on. - CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", 5}}, "").empty()); - CHECK(bridge_headers({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", {{"name", 3}}}}, "").count("Mcp-Name") == 0); -} - TEST_CASE("the catalog the stdio bridge lists without the app holds every tool family", "[Mcp]") { const CommandCatalog& catalog = NativeCommands::instance(); @@ -273,382 +76,8 @@ TEST_CASE("the catalog the stdio bridge lists without the app holds every tool f CHECK(names.count(name) == 1); // Built once, for the life of the process. CHECK(&NativeCommands::instance() == &catalog); - CHECK(McpService::server_info().version == SLIC3R_VERSION); - CHECK_FALSE(McpService::server_info().instructions.empty()); + CHECK(server_info().version == SLIC3R_VERSION); + CHECK_FALSE(server_info().instructions.empty()); // Clients cut the instructions off after 4096 characters. - CHECK(McpService::server_info().instructions.size() <= 4096); -} - -TEST_CASE("ping returns an empty result", "[Mcp]") -{ - Fixture f; - CHECK(body(f.post({{"jsonrpc", "2.0"}, {"id", "p"}, {"method", "ping"}}))["result"] == json::object()); -} - -TEST_CASE("a legacy request with an unsupported MCP-Protocol-Version header is 400", "[Mcp]") -{ - Fixture f; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}, "2024-01-01"); - CHECK(r.status == 400); - CHECK(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}, "2025-11-25").status == 200); -} - -TEST_CASE("2026-07-28 server/discover lists versions and capabilities", "[Mcp]") -{ - Fixture f; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "server/discover"}, {"params", modern_params()}}, "2026-07-28", "server/discover"); - REQUIRE(r.status == 200); - const json result = body(r)["result"]; - CHECK(result["resultType"] == "complete"); - CHECK(result["supportedVersions"][0] == "2026-07-28"); - CHECK(result["capabilities"].contains("tools")); - CHECK(result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "orcaslicer"); - CHECK(result.contains("ttlMs")); - CHECK(result.contains("cacheScope")); -} - -TEST_CASE("2026-07-28 results carry resultType complete", "[Mcp]") -{ - Fixture f; - const json list = body(f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", modern_params()}}, "2026-07-28", "tools/list"))["result"]; - CHECK(list["resultType"] == "complete"); - CHECK(list.contains("ttlMs")); - CHECK(list.contains("cacheScope")); - - const json call = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/call"}, - {"params", modern_params({{"name", "echo"}, {"arguments", {{"text", "x"}}}})}}, - "2026-07-28", "tools/call", "echo"))["result"]; - CHECK(call["resultType"] == "complete"); -} - -TEST_CASE("2026-07-28 header mismatches are 400 -32020", "[Mcp]") -{ - Fixture f; - const json req{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/call"}, {"params", modern_params({{"name", "echo"}, {"arguments", {{"text", "x"}}}})}}; - PostReply r = f.post(req, "2026-07-28", "tools/list", "echo"); - CHECK(r.status == 400); - CHECK(body(r)["error"]["code"] == -32020); - - r = f.post(req, "2026-07-28", "tools/call", ""); - CHECK(body(r)["error"]["code"] == -32020); - - r = f.post(req, "", "tools/call", "echo"); - CHECK(body(r)["error"]["code"] == -32020); - - // Mcp-Name may arrive base64-encoded. - r = f.post(req, "2026-07-28", "tools/call", "=?base64?ZWNobw==?="); - CHECK(r.status == 200); -} - -TEST_CASE("2026-07-28 unsupported _meta version is 400 -32022 with the supported list", "[Mcp]") -{ - Fixture f; - json params = modern_params(); - params["_meta"]["io.modelcontextprotocol/protocolVersion"] = "2030-01-01"; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}, {"params", params}}, "2030-01-01", "tools/list"); - CHECK(r.status == 400); - const json err = body(r)["error"]; - CHECK(err["code"] == -32022); - CHECK(err["data"]["requested"] == "2030-01-01"); - CHECK(err["data"]["supported"][0] == "2026-07-28"); -} - -TEST_CASE("2026-07-28 unknown method is 404 -32601", "[Mcp]") -{ - Fixture f; - const PostReply r = f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "resources/list"}, {"params", modern_params()}}, "2026-07-28", "resources/list"); - CHECK(r.status == 404); - CHECK(body(r)["error"]["code"] == -32601); -} - -TEST_CASE("argument validation covers types, enums, ranges and arrays", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", - {{"n", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5}}}, - {"zoom", {{"type", "number"}, {"exclusiveMinimum", 0}}}, - {"mode", {{"type", "string"}, {"enum", {"a", "b"}}}}, - {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}}}, - {"additionalProperties", false}}; - CHECK(validate_arguments(schema, {{"n", 3}, {"mode", "a"}, {"paths", {"x"}}}).empty()); - CHECK(validate_arguments(schema, {{"n", 0}}).find("n must be >= 1") != std::string::npos); - 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); - 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, {{"extra", 1}}).find("unknown argument extra") != std::string::npos); - - // A plugin operation's draft-04 schema gives exclusiveMinimum as a boolean that qualifies minimum. - const json draft4 = {{"type", "object"}, {"properties", {{"zoom", {{"type", "number"}, {"minimum", 0}, {"exclusiveMinimum", true}}}}}}; - std::string draft4_error; - CHECK_NOTHROW(draft4_error = validate_arguments(draft4, {{"zoom", 0.5}})); - CHECK(draft4_error.empty()); -} - -TEST_CASE("argument normalization reads the names agents reach for as the ones a tool takes", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", - {{"target", {{"type", {"string", "object"}}}}, - {"button", {{"type", "string"}}}, - {"objects", {{"type", "array"}, {"items", {{"type", "integer"}}}}}}}, - {"additionalProperties", false}}; - const auto normalized = [&](json args) { - normalize_arguments(schema, args); - return args; - }; - CHECK(normalized({{"ref", "w12"}}) == json{{"target", "w12"}}); - // action stands for id or button, whichever the tool takes. - CHECK(normalized({{"action", "close"}}) == json{{"button", "close"}}); - CHECK(normalized({{"object", 2}}) == json{{"objects", {2}}}); - CHECK(normalized({{"object", "0"}}) == json{{"objects", {0}}}); - // Given both, the call keeps them and validation names the stray one. - const json both = normalized({{"ref", "w12"}, {"target", "w13"}}); - CHECK(both == json{{"ref", "w12"}, {"target", "w13"}}); - CHECK(validate_arguments(schema, both).find("unknown argument ref") != std::string::npos); - // A tool that takes the name itself keeps it. - const json own = {{"type", "object"}, {"properties", {{"text", {{"type", "string"}}}, {"value", {{"type", "string"}}}}}}; - json text{{"text", "abc"}}; - normalize_arguments(own, text); - CHECK(text == json{{"text", "abc"}}); - // Only a value that fits: a click is no button, so the call keeps action for the validator to name. - const json clicks = {{"type", "object"}, - {"properties", {{"button", {{"type", "string"}, {"enum", {"left", "right", "middle"}}}}}}, - {"additionalProperties", false}}; - json click{{"action", "click"}}; - normalize_arguments(clicks, click); - CHECK(click == json{{"action", "click"}}); -} - -TEST_CASE("argument normalization reads a capture's output path as its save_path", "[Mcp]") -{ - const auto normalized = [](const json& properties, json args) { - normalize_arguments({{"type", "object"}, {"properties", properties}, {"additionalProperties", false}}, args); - return args; - }; - // A capture's output file is its save_path; a tool with a path of its own keeps that. - const json capture = {{"save_path", {{"type", "string"}}}}; - CHECK(normalized(capture, {{"path", "/a.png"}}) == json{{"save_path", "/a.png"}}); - const json encode = {{"path", {{"type", "string"}}}, {"save_path", {{"type", "string"}}}}; - CHECK(normalized(encode, {{"path", "/a.mkv"}}) == json{{"path", "/a.mkv"}}); -} - -TEST_CASE("argument normalization leaves a value its enum lacks, and a 3D view under another name, for the validator", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", - {{"scope", {{"type", "string"}, {"enum", {"process", "filament", "part"}}}}, - {"target", {{"type", "string"}, {"enum", {"main", "canvas"}}}}, - {"canvas", {{"type", "string"}, {"enum", {"3d", "preview"}}}}}}, - {"additionalProperties", false}}; - const auto normalized = [&](json args) { - normalize_arguments(schema, args); - return args; - }; - // No value stands for another: the process scope and the main window go by those names alone. - CHECK(normalized({{"scope", "print"}}) == json{{"scope", "print"}}); - CHECK(normalized({{"target", "window"}}) == json{{"target", "window"}}); - CHECK_FALSE(validate_arguments(schema, normalized({{"scope", "print"}})).empty()); - // set_view's 3D view is its canvas. - const json view = normalized({{"view", "preview"}}); - CHECK(view == json{{"view", "preview"}}); - CHECK(validate_arguments(schema, view).find("unknown argument view") != std::string::npos); -} - -TEST_CASE("argument normalization reads values written in another JSON form", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", - {{"n", {{"type", "integer"}}}, - {"flag", {{"type", "boolean"}}}, - {"plate", {{"type", {"string", "integer"}}}}, - {"point", {{"type", "array"}, {"items", {{"type", "number"}}}}}, - {"paths", {{"type", "array"}, {"items", {{"type", "string"}}}}}, - {"name", {{"type", "string"}}}}}, - {"additionalProperties", false}}; - json args{{"n", "3"}, {"flag", "true"}, {"plate", "1"}, {"point", "[1, 2.5, 3]"}, {"paths", "/a.stl"}, {"name", "7"}}; - normalize_arguments(schema, args); - CHECK(args["n"] == 3); - CHECK(args["flag"] == true); - CHECK(args["plate"] == 1); - CHECK(args["point"] == json{1, 2.5, 3}); - CHECK(args["paths"] == json{"/a.stl"}); - // A string where a string goes stays one. - CHECK(args["name"] == "7"); - CHECK(validate_arguments(schema, args).empty()); - - json kept{{"plate", "all"}, {"n", "2.5"}}; - normalize_arguments(schema, kept); - CHECK(kept["plate"] == "all"); - CHECK(validate_arguments(schema, kept).find("n must be of type integer") != std::string::npos); -} - -TEST_CASE("argument normalization moves a value outside its enum to the argument whose enum takes it", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", - {{"view", {{"type", "string"}, {"enum", {"3d", "preview"}}}}, - {"camera", {{"type", "string"}, {"enum", {"front", "top", "fit"}}}}, - {"tab", {{"type", "string"}, {"enum", {"prepare", "preview"}}}}}}, - {"additionalProperties", false}}; - json moved{{"view", "front"}}; - normalize_arguments(schema, moved); - CHECK(moved == json{{"camera", "front"}}); - - // Both given: the call names its camera, so view's value is an error, not a second camera. - json both{{"view", "front"}, {"camera", "fit"}}; - normalize_arguments(schema, both); - CHECK(both["view"] == "front"); - CHECK(validate_arguments(schema, both).find("view must be one of") != std::string::npos); - - // A value of its own enum stays, even where another enum also takes it. - json own{{"view", "preview"}}; - normalize_arguments(schema, own); - CHECK(own == json{{"view", "preview"}}); - - // Taken by no other enum: left for the validator. - json unknown{{"view", "sideways"}}; - normalize_arguments(schema, unknown); - CHECK(unknown == json{{"view", "sideways"}}); -} - -TEST_CASE("pairs list_windows reports are read as position and size", "[Mcp]") -{ - const json schema = {{"type", "object"}, - {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "integer"}}}}}, - {"size", {{"type", "array"}, {"items", {{"type", "integer"}}}}}}}, - {"additionalProperties", false}}; - json flat{{"x", 10}, {"y", 20}, {"width", 800}, {"height", 600}}; - normalize_arguments(schema, flat); - CHECK(flat == json{{"position", {10, 20}}, {"size", {800, 600}}}); - json half{{"x", 10}}; - normalize_arguments(schema, half); - CHECK(half == json{{"x", 10}}); // left for the validator to name - json given{{"x", 1}, {"y", 2}, {"position", {3, 4}}}; - normalize_arguments(schema, given); - CHECK(given["position"] == json{3, 4}); // never replaces a given argument - const json own = {{"type", "object"}, {"properties", {{"x", {{"type", "integer"}}}, {"y", {{"type", "integer"}}}}}}; - json kept{{"x", 1}, {"y", 2}}; - normalize_arguments(own, kept); - CHECK(kept == json{{"x", 1}, {"y", 2}}); // a tool that takes x and y keeps them -} - -TEST_CASE("a position or size in mm, an array of numbers, takes no pair list_windows reports", "[Mcp]") -{ - // add_part's position and size, and transform's position. - const json schema = {{"type", "object"}, - {"properties", {{"position", {{"type", "array"}, {"items", {{"type", "number"}}}}}, - {"size", {{"type", "array"}, {"items", {{"type", "number"}}}}}}}, - {"additionalProperties", false}}; - const json flat{{"x", 10}, {"y", 20}, {"width", 30}, {"height", 5}}; - json args = flat; - normalize_arguments(schema, args); - CHECK(args == flat); - CHECK(validate_arguments(schema, args).find("unknown argument") != std::string::npos); - // transform's size, whose null keeps an axis. - const json nullable = {{"type", "object"}, - {"properties", {{"size", {{"type", "array"}, {"items", {{"type", {"number", "null"}}}}}}}}, - {"additionalProperties", false}}; - json sized{{"width", 30}, {"height", 5}}; - normalize_arguments(nullable, sized); - CHECK(sized == json{{"width", 30}, {"height", 5}}); -} - -TEST_CASE("an unknown tool is answered with the closest names", "[Mcp]") -{ - Fixture f; - const json direct = body(f.post({{"jsonrpc", "2.0"}, {"id", 7}, {"method", "tools/call"}, {"params", {{"name", "no_such_tool"}}}})); - CHECK(direct["error"]["message"] == "Unknown tool: no_such_tool"); - - NativeCommand api; - api.key = "call_tool"; - api.input_schema = {{"type", "object"}, - {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, - {"required", {"tool"}}}; - api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; - f.registry.add(api); - // call_tool's target names the closest command, and nothing else. - const json typo = body(f.post({{"jsonrpc", "2.0"}, {"id", 9}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; - CHECK(typo["isError"] == true); - CHECK(typo["content"][0]["text"] == "Unknown tool: ech (did you mean echo?)"); -} - -TEST_CASE("a call's arguments are normalized, then validated", "[Mcp]") -{ - NativeCommand capture; - capture.key = "screenshot"; - capture.input_schema = {{"type", "object"}, - {"properties", {{"target", {{"type", "string"}}}, {"save_path", {{"type", "string"}}}}}, - {"additionalProperties", false}}; - // A name agents reach for is read as the one the tool takes. - json aliased{{"path", "/a.png"}}; - CHECK(argument_error(capture, aliased).empty()); - CHECK(aliased == json{{"save_path", "/a.png"}}); - // An argument the tool does not take is refused with the ones it does. - json unknown{{"colour", "red"}}; - const std::string refused = argument_error(capture, unknown); - CHECK(refused.find("unknown argument colour") != std::string::npos); - CHECK(refused.find("save_path") != std::string::npos); -} - -TEST_CASE("call_tool runs and is journaled as the tool it names", "[Mcp]") -{ - Fixture f; - NativeCommand api; - api.key = "call_tool"; - api.input_schema = {{"type", "object"}, - {"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}}, - {"required", {"tool"}}}; - api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); }; - f.registry.add(api); - - const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", {{"text", "hi"}}}}}}}}))["result"]; - CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"echo", "hi"}}); - REQUIRE(f.caller.called.size() == 1); - CHECK(f.caller.called.back() == "echo"); - - // The target's arguments are checked against its schema, and an unknown tool is named. - const json invalid = body(f.post({{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "echo"}, {"args", json::object()}}}}}}))["result"]; - CHECK(invalid["isError"] == true); - const json unknown = body(f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, - {"params", {{"name", "call_tool"}, {"arguments", {{"tool", "ech"}}}}}}))["result"]; - CHECK(unknown["isError"] == true); - CHECK(unknown["content"][0]["text"].get<std::string>().find("did you mean echo") != std::string::npos); -} - -// Holds the one operation a plugin offers while it is loaded. -class MeasureSource final : public CommandSource -{ -public: - MeasureSource() - { - auto area = std::make_shared<NativeCommand>(); - area->key = "plugin.measure.area"; - area->run = [](const json&, ToolContext&) { return ToolResult::ok({{"area", 12.5}}); }; - m_area = std::move(area); - } - std::shared_ptr<const NativeCommand> find(const std::string& key) const override { return key == m_area->key ? m_area : nullptr; } - std::vector<std::shared_ptr<const NativeCommand>> all() const override { return {m_area}; } - -private: - std::shared_ptr<const NativeCommand> m_area; -}; - -TEST_CASE("a name the table lacks resolves through a source, without being listed", "[Mcp]") -{ - Fixture f; - f.registry.add_source(std::make_unique<MeasureSource>()); - REQUIRE(f.registry.lookup("plugin.measure.area") != nullptr); - CHECK(f.registry.lookup("plugin.measure.volume") == nullptr); - CHECK(f.registry.lookup("echo")->key == "echo"); - const json tools = body(f.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/list"}}))["result"]["tools"]; - for (const json& t : tools) - CHECK(t["name"] != "plugin.measure.area"); - const json result = body(f.post({{"jsonrpc", "2.0"}, {"id", 3}, {"method", "tools/call"}, - {"params", {{"name", "plugin.measure.area"}, {"arguments", json::object()}}}}))["result"]; - CHECK(json::parse(result["content"][0]["text"].get<std::string>()) == json{{"area", 12.5}}); + CHECK(server_info().instructions.size() <= 4096); } diff --git a/tests/slic3rutils/test_mcp_recording.cpp b/tests/slic3rutils/test_mcp_recording.cpp index 3d1c82f2bd..96b03d7d25 100644 --- a/tests/slic3rutils/test_mcp_recording.cpp +++ b/tests/slic3rutils/test_mcp_recording.cpp @@ -3,10 +3,10 @@ #include <catch2/matchers/catch_matchers.hpp> #include <catch2/matchers/catch_matchers_floating_point.hpp> +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/McpPaths.hpp" #include "slic3r/GUI/Mcp/McpRecorder.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/MkvWriter.hpp" #include "slic3r/GUI/Mcp/RecordingSettings.hpp" #include "slic3r/GUI/Mcp/RecordingSink.hpp" @@ -54,6 +54,7 @@ #include <utility> #include <vector> +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; using namespace std::chrono_literals; diff --git a/tests/slic3rutils/test_mcp_results.cpp b/tests/slic3rutils/test_mcp_results.cpp index d2f8387b0f..9861959a94 100644 --- a/tests/slic3rutils/test_mcp_results.cpp +++ b/tests/slic3rutils/test_mcp_results.cpp @@ -25,6 +25,7 @@ #include "libvgcode/include/Types.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLToolbar.hpp" #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" @@ -32,15 +33,14 @@ #include "slic3r/GUI/MeshUtils.hpp" #include "slic3r/GUI/Mcp/CanvasTarget.hpp" #include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpCore.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/McpPaths.hpp" #include "slic3r/GUI/Mcp/McpProtocol.hpp" #include "slic3r/GUI/Mcp/McpReplay.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" -#include "slic3r/GUI/Mcp/McpServicePtr.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include "slic3r/GUI/Mcp/ModalTracker.hpp" #include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/Mcp/UiInvoker.hpp" @@ -1141,8 +1141,8 @@ TEST_CASE("a menu opened while a call acts on the UI is listed, run by its path wxInitializer init; REQUIRE(init.IsOk()); { - McpServicePtr service(new McpService()); - UiInspector inspector(*service); + ModalTracker modals; + UiInspector inspector(modals, [] { return uint64_t(1); }); inspector.capture_menus(true); // A menu as MenuFactory builds one: handlers on the menu, item states from wxEVT_UPDATE_UI @@ -2241,8 +2241,8 @@ TEST_CASE("set_widget_value false is refused on a selected radio button, which s GuiApp app; REQUIRE(app.init.IsOk()); { - McpServicePtr service(new McpService()); - UiInspector inspector(*service); + ModalTracker modals; + UiInspector inspector(modals, [] { return uint64_t(1); }); wxFrame frame(nullptr, wxID_ANY, "radios"); auto* first = new wxRadioButton(&frame, wxID_ANY, "First", wxPoint(0, 0), wxDefaultSize, wxRB_GROUP); auto* second = new wxRadioButton(&frame, wxID_ANY, "Second", wxPoint(0, 30)); diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index f602c5b2c3..b398549864 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -25,6 +25,7 @@ #include <imgui/imgui.h> #include <nlohmann/json.hpp> +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/IMSlider.hpp" @@ -33,7 +34,6 @@ #include "slic3r/GUI/Mcp/McpCore.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/UiInvoker.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/NotificationManager.hpp" @@ -82,12 +82,12 @@ TEST_CASE("size targets scale uniformly when one axis is given", "[Mcp][Scene]") CHECK(Mcp::size_factors(current, json::array({80, 30, nullptr})).isApprox(Vec3d(4. / 3., 1.5, 1.))); CHECK(Mcp::size_factors(current, json::array({30, 10, 5})).isApprox(Vec3d(0.5, 0.5, 1.))); - CHECK_THROWS_AS(Mcp::size_factors(current, json::array({0, nullptr, nullptr})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::size_factors(current, json::array({-80, nullptr, nullptr})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::size_factors(current, json::array({80, 30})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::size_factors(current, json::array({nullptr, nullptr, nullptr})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({0, nullptr, nullptr})), ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({-80, nullptr, nullptr})), ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({80, 30})), ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({nullptr, nullptr, nullptr})), ToolFailure); // A flat shape has no size to scale along its flat axis. - CHECK_THROWS_AS(Mcp::size_factors(Vec3d(50., 50., 0.), json::array({nullptr, nullptr, 2})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(Vec3d(50., 50., 0.), json::array({nullptr, nullptr, 2})), ToolFailure); } TEST_CASE("a primitive's size has one number above 0 per dimension its dialog asks for", "[Mcp][Scene]") @@ -302,45 +302,45 @@ struct Harness Harness() { timing.soft_budget = 100ms; - add("arrange", Mcp::GuardClass::Mutate, [this](const json&, Mcp::ToolContext& ctx) { + add("arrange", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { worker.start(job_length); return json(); }); while (ctx.observe_ui([&] { return json(worker.busy()); }).get<bool>()) std::this_thread::sleep_for(20ms); - return Mcp::ToolResult::ok({{"arranged", true}}); + return ToolResult::ok({{"arranged", true}}); }); - add("run_action", Mcp::GuardClass::Mutate, [this](const json&, Mcp::ToolContext& ctx) { + add("run_action", GuardClass::Mutate, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { worker.start(job_length); return json(); }); - return Mcp::ToolResult::ok({{"ran", "obj_arrange"}}); + return ToolResult::ok({{"ran", "obj_arrange"}}); }); - add("click", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { + add("click", GuardClass::Recover, [this](const json&, ToolContext& ctx) { ctx.run_ui([&] { core->admit({}); // the target is outside any dialog ui.post([this] { worker.start(job_length); }); return json(); }); ctx.observe_ui([] { return json(); }); // settle - return Mcp::ToolResult::ok(); + return ToolResult::ok(); }); - add("press_keys", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { - return Mcp::ToolResult::ok(ctx.run_ui([&] { + add("press_keys", GuardClass::Recover, [this](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { core->admit({}); return json("deleted"); })); }); - add("answer_dialog", Mcp::GuardClass::Recover, - [](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([] { return json("pressed"); })); }); - add("edit", Mcp::GuardClass::Mutate, - [](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([] { return json("edited"); })); }); - add("read", Mcp::GuardClass::Inspect, - [this](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([&] { return json(worker.busy()); })); }); - add("cancel_job", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { - return Mcp::ToolResult::ok(ctx.run_ui([&] { + add("answer_dialog", GuardClass::Recover, + [](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([] { return json("pressed"); })); }); + add("edit", GuardClass::Mutate, + [](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([] { return json("edited"); })); }); + add("read", GuardClass::Inspect, + [this](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return json(worker.busy()); })); }); + add("cancel_job", GuardClass::Recover, [this](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { for (const std::string& op : jobs.running_operations()) if (core->cancel_worker(op)) return json(op); @@ -356,12 +356,12 @@ struct Harness core->shutdown(); } - void add(const std::string& name, Mcp::GuardClass guard, CommandFn handler) + void add(const std::string& name, GuardClass guard, CommandFn handler) { NativeCommand d; d.key = name; d.guard = guard; - d.inline_call = guard == Mcp::GuardClass::Inspect; + d.inline_call = guard == GuardClass::Inspect; d.allowed_during_operation = name == "cancel_job"; d.budget_ms = 200; d.run = std::move(handler); @@ -372,17 +372,17 @@ struct Harness core = std::make_unique<Mcp::McpCore>(registry, invoker, jobs, &journal, timing, Mcp::WorkerHooks{[this] { return worker.busy(); }, [this] { worker.cancel(); }}); } - Mcp::ToolResult call(const std::string& tool) { return core->call(*registry.find(tool), json::object()); } + ToolResult call(const std::string& tool) { return core->call(*registry.find(tool), json::object()); } // Starts a worker job with `tool`, which outlives the reply budget; returns the call's job. std::string start_job(const std::string& tool) { - const Mcp::ToolResult started = call(tool); + const ToolResult started = call(tool); REQUIRE_FALSE(started.is_error); REQUIRE(started.data["status"] == "running"); return started.data["job"]; } - bool refused_by(const Mcp::ToolResult& r, const std::string& job) + bool refused_by(const ToolResult& r, const std::string& job) { return r.is_error && r.message.find("Busy: job " + job + " is running an operation") != std::string::npos; } @@ -416,7 +416,7 @@ TEST_CASE("a cancelled worker job keeps admission until the worker is really idl { h.start(); const std::string job = h.start_job("arrange"); - const Mcp::ToolResult cancel = h.call("cancel_job"); + const ToolResult cancel = h.call("cancel_job"); REQUIRE_FALSE(cancel.is_error); CHECK(cancel.data == job); CHECK(h.refused_by(h.call("edit"), job)); @@ -485,16 +485,16 @@ TEST_CASE("a worker job that starts between a call's closures is the call's, who // The worker doesn't record who queued a job, so a person's job that starts while a call that // found the worker idle is still running is claimed by that call, as one its change queued is. Harness h; - h.add("settle", Mcp::GuardClass::Mutate, [](const json&, Mcp::ToolContext& ctx) { + h.add("settle", GuardClass::Mutate, [](const json&, ToolContext& ctx) { ctx.run_ui([] { return json("edited"); }); for (int i = 0; i < 10; ++i) { ctx.observe_ui([] { return json(); }); std::this_thread::sleep_for(20ms); } - return Mcp::ToolResult::ok(); + return ToolResult::ok(); }); h.start(); - Mcp::ToolResult settled; + ToolResult settled; std::thread caller([&h, &settled] { settled = h.call("settle"); }); std::this_thread::sleep_for(60ms); h.ui.post([&h] { h.worker.start(h.job_length); }); // a person starts Text typing @@ -512,11 +512,11 @@ TEST_CASE("a worker job a person started refuses changes but not reads, and canc h.start(); h.worker.start(800ms); // Text typing for (const char* change : {"edit", "press_keys"}) { - const Mcp::ToolResult refused = h.call(change); + const ToolResult refused = h.call(change); CHECK(refused.is_error); CHECK(refused.message.find("Busy: a background job") != std::string::npos); } - const Mcp::ToolResult read = h.call("read"); + const ToolResult read = h.call("read"); CHECK_FALSE(read.is_error); CHECK(read.data == true); CHECK(h.call("cancel_job").data.is_null()); @@ -788,19 +788,19 @@ TEST_CASE("a shape's size needs one positive number per field of the size dialog // No size: the built-in one. CHECK(Mcp::part_shape_size("disc", json()).empty()); - CHECK_THROWS_AS(Mcp::part_shape_size("cube", json::array({40, 30})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("sphere", json::array({8, 8})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({0, 3})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({-6, 3})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({std::nan(""), 3})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({"6", 3})), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json(6)), Mcp::ToolFailure); - CHECK_THROWS_AS(Mcp::part_shape_size("slab", json()), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cube", json::array({40, 30})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("sphere", json::array({8, 8})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({0, 3})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({-6, 3})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({std::nan(""), 3})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({"6", 3})), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json(6)), ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("slab", json()), ToolFailure); // The message names the fields, as the dialog does. try { Mcp::part_shape_size("torus", json::array({20})); FAIL("a torus with one size was accepted"); - } catch (const Mcp::ToolFailure& e) { + } catch (const ToolFailure& e) { CHECK(std::string(e.what()) == "A torus's size is [Inner diameter, Tube diameter] in mm, each above 0"); } } @@ -869,9 +869,9 @@ TEST_CASE("height ranges are checked before the object changes", "[Mcp][Scene][L CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 20), range(5, 10)})), ContainsSubstring("0-20 and 5-10 overlap")); // Empty, reversed, below the bed or without a top. CHECK_THROWS_WITH(parse_ranges(json::array({range(5, 5)})), ContainsSubstring("0 <= min_z < max_z")); - CHECK_THROWS_AS(parse_ranges(json::array({range(6, 5)})), Mcp::ToolFailure); - CHECK_THROWS_AS(parse_ranges(json::array({range(-1, 5)})), Mcp::ToolFailure); - CHECK_THROWS_AS(parse_ranges(json::array({json{{"min_z", 0}}})), Mcp::ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({range(6, 5)})), ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({range(-1, 5)})), ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({json{{"min_z", 0}}})), ToolFailure); // A layer height given is checked against the printer's, with the range's filament. int asked = -1; @@ -890,11 +890,11 @@ TEST_CASE("height ranges are checked before the object changes", "[Mcp][Scene][L // Filaments are 0 (the object's) up to the slot count. CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"extruder", 3}})})), ContainsSubstring("1-2")); - CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"extruder", -1}})})), Mcp::ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"extruder", -1}})})), ToolFailure); // Values are parsed strictly. CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"sparse_infill_density", "lots"}})})), ContainsSubstring("Invalid value for sparse_infill_density")); - CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"wall_loops", nullptr}})})), Mcp::ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"wall_loops", nullptr}})})), ToolFailure); } TEST_CASE("range settings take the keys the range settings page offers", "[Mcp][Scene][Layers]") @@ -912,13 +912,13 @@ TEST_CASE("range settings take the keys the range settings page offers", "[Mcp][ try { parse_ranges(json::array({range(0, 5, {{"enable_support", true}})})); FAIL("an object setting was accepted for a range"); - } catch (const Mcp::ToolFailure& e) { + } catch (const ToolFailure& e) { CHECK_THAT(e.what(), ContainsSubstring("not a height range setting")); } try { parse_ranges(json::array({range(0, 5, {{"sparse_infill_dens", "20%"}})})); FAIL("an unknown key was accepted"); - } catch (const Mcp::ToolFailure& e) { + } catch (const ToolFailure& e) { REQUIRE(e.details.contains("similar")); CHECK(std::find(e.details["similar"].begin(), e.details["similar"].end(), json("sparse_infill_density")) != e.details["similar"].end()); } diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 51dc0c1d5f..9e15e9b4b9 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -20,9 +20,10 @@ #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/WindowControl.hpp" #include "slic3r/GUI/Camera.hpp" @@ -45,6 +46,7 @@ #include <utility> #include <vector> +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; using nlohmann::json; using Slic3r::GUI::CommandCatalog; @@ -192,7 +194,8 @@ TEST_CASE("run_action says where an action it cannot find is", "[Mcp][SpeedDial] CHECK_THAT(why, Catch::Matchers::ContainsSubstring("call_tool {\"tool\": \"shell\"}")); } else { CHECK(why == id + " is a Design tab tile, and the CAD feature was off when OrcaSlicer started: a person " - "turns it on in Preferences > Features and restarts OrcaSlicer"); + "turns it on in Preferences > Features and restarts OrcaSlicer, or starts it with " + "--cad"); } } // A Design command without a tile is any unknown action. diff --git a/tests/slic3rutils/test_mcp_ui.cpp b/tests/slic3rutils/test_mcp_ui.cpp index 3812e19aa0..1bca3e84ec 100644 --- a/tests/slic3rutils/test_mcp_ui.cpp +++ b/tests/slic3rutils/test_mcp_ui.cpp @@ -26,9 +26,8 @@ #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/MeshUtils.hpp" #include "slic3r/GUI/Mcp/CanvasTarget.hpp" -#include "slic3r/GUI/Mcp/McpService.hpp" -#include "slic3r/GUI/Mcp/McpServicePtr.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/Mcp/UiRefs.hpp" @@ -46,6 +45,7 @@ #include <cmath> #include <cstddef> +#include <cstdint> #include <cstdlib> #include <optional> #include <set> @@ -532,8 +532,10 @@ TEST_CASE("a key goes to the hooks of the target and its parents before the targ wxInitializer init; REQUIRE(init.IsOk()); { - McpServicePtr service(new McpService()); - UiInspector inspector(*service); + // With no automation runtime, it sends a key as a real key press goes: to the hooks of the target and its + // parents before the target. + ModalTracker modals; + UiInspector inspector(modals, [] { return uint64_t(1); }); // A panel whose hook takes Escape, as the Design tab's does, in a frame with a hook of its own. wxFrame frame(nullptr, wxID_ANY, "keys"); diff --git a/tests/slic3rutils/test_mcp_web.cpp b/tests/slic3rutils/test_mcp_web.cpp index 23142a9679..b0114c7b78 100644 --- a/tests/slic3rutils/test_mcp_web.cpp +++ b/tests/slic3rutils/test_mcp_web.cpp @@ -12,7 +12,7 @@ #include <catch2/catch_test_macros.hpp> #include "libslic3r/Utils.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/ModalTracker.hpp" #include "slic3r/GUI/Mcp/UiRefs.hpp" #include "slic3r/GUI/Mcp/WebPages.hpp" @@ -47,6 +47,7 @@ using json = nlohmann::json; using namespace Slic3r; +using namespace Slic3r::GUI; using namespace Slic3r::GUI::Mcp; namespace { diff --git a/tests/slic3rutils/test_operations.cpp b/tests/slic3rutils/test_operations.cpp index f354fbd1c4..e658ab8cd6 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -2,7 +2,6 @@ #include <catch2/catch_test_macros.hpp> #include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" diff --git a/tools/mcp/README.md b/tools/mcp/README.md index f91f7a2f89..c9e1e10497 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -20,12 +20,11 @@ an `OrcaSlicer.conf` that has a finished setup wizard and one printer and filame Carbon 0.4 by default), with update checks and daily tips turned off, and with the Orca Cloud login kept in a token file in the datadir (`use_encrypted_token_file`) instead of the system's secret store, so the instance starts signed out and never reads your login: on macOS that read would stop a newly built app at -a keychain prompt. `--cad` turns the Design -(CAD) tab on, and with it its commands: it sets `enable_cad_feature` in a fresh datadir's -`OrcaSlicer.conf`, and in a reused one too, since the app creates the Design tab and its commands only at -startup, when that setting is on. -`--unrestricted-scripts` lets Python scripts (`run_script`) run unrestricted the same way, by setting -`mcp_python_unrestricted`, since no tool can turn that on. The token comes from +a keychain prompt. `--cad` starts the app with +`--cad`, which turns the Design (CAD) tab on for that run, and with it its commands, and +`--unrestricted-scripts` starts it with `--unrestricted-scripts`, which lets Python scripts +(`run_script`) run unrestricted for that run. Neither writes the datadir's `OrcaSlicer.conf`, and a later +launch without them has the settings the datadir holds. The token comes from `ORCA_MCP_TOKEN` or is generated, and it reaches the app through the environment, not the command line. On Linux, `launch` also sets `SSL_CERT_FILE`, so a fresh datadir doesn't prompt for a CA bundle. On Windows, it gives the instance its own WebView2 profile in the datadir, apart from the one @@ -139,13 +138,30 @@ tools/mcp/orca_mcp.py run-replay tools/mcp/smoke_test.json --out /tmp/orca-smoke tools/mcp/orca_mcp.py stop ``` -Without the harness, `orca-slicer --datadir DIR --mcp-run tools/mcp/smoke_test.json ---mcp-run-out /tmp/orca-smoke` runs the replay and exits. On Linux, set `SSL_CERT_FILE` (for +Without the harness, `orca-slicer --datadir DIR --run tools/mcp/smoke_test.json +--outputdir /tmp/orca-smoke` runs the replay and exits. On Linux, set `SSL_CERT_FILE` (for example to `/etc/ssl/certs/ca-certificates.crt`) as the harness does; otherwise a prompt for the CA bundle blocks startup before the replay can run. The exit code is 0 when it passes, 1 -when a step fails and 2 when the replay is invalid. The run leaves `result.json` and the -screenshots in the output directory. `tests/replay_basic.json` is the smallest such check: load, -change a setting, slice and capture. +when a step fails and 2 when the replay is invalid, cannot be read or is neither a `.json` nor a `.py` +file. The run leaves `result.json` and the screenshots in the `--outputdir` folder, or without it in +`<replay name>.out` beside the replay. Files that a step or a script saves without a path go to the +`--outputdir` folder too, or without it to `<datadir>/automation/out`. A `--run` launch is never handed to a window that is already open, whatever +the single-instance preference says, and it is refused with an action or `--downward-check`, which start +no GUI. `tests/replay_basic.json` is the smallest such check: load, change a setting, slice and capture. + +`test_command_line.py [--bin PATH] [CHECK ...]` checks that command line, starting the built app as its own +child on fresh data folders: that the options it does not have are refused before any GUI starts, `--run`'s exit +codes and folders, its refusal beside an action or `--downward-check`, that `--mcp-port` alone opens the server, +that `--unrestricted-scripts` and `--cad` hold for the run without writing the configuration, and a run beside a +window already open on the same data folder. It prints one line per check and takes about two to three minutes. + +`test_runtime_lifecycle.py [--bin PATH] [CHECK ...]` checks how the app's automation behaves while the app closes, +and while its server is switched off and on during a call, starting the built app as its own child on fresh data +folders. The app is closed with the File menu's Quit while a job runs, while a recording runs, and while a call no +stop interrupts is still running, where the app keeps the runtime rather than free it under the call and logs that +a call did not return; a `--run` with the endpoint never opened exits on its own; and the server, switched off and +on in Preferences during a call, serves on the port it had. It prints one line per check and takes about three +minutes. `test_plugin_tools.py` checks a plugin's calls into the tools in the running app: it side-loads `tests/plugins/mcp_tools_fixture` into a fresh data folder and launches twice: over MCP, with the Design tab @@ -156,18 +172,18 @@ and a thread it starts reach the tools, an auto-answer rule it sets is the plugi refused, nothing it calls is journaled, a script that finds its progress dialog handle can use it, `tests/plugins/mcp_tools_broken`, whose load fails, offers none of its operations, and unticking the plugin in the Plugins dialog withdraws its operation and ends its rule); and without MCP, -where a `--mcp-run` runs the plugin's script and its rule is still the plugin's. Run it as +where a `--run` runs the plugin's script and its rule is still the plugin's. Run it as `python tools/mcp/test_plugin_tools.py`. The Run Script panel's `.py` files are not driven from here: the panel is hidden from automation and opens its files through a file picker, so how it reads and saves them is covered by the unit tests of `decode_python_source()` and `encode_python_source()`. -A `.py` file given to `--mcp-run` runs as a Python script (`run_script`) instead, exiting 0 when it +A `.py` file given to `--run` runs as a Python script (`run_script`) instead, exiting 0 when it finishes and 1 when it raises, is cancelled or runs out of time; its traceback goes to the log. A script's own file access is held to OrcaSlicer's folders, and it starts no programs or threads and reaches -no network, until the setting lets scripts run unrestricted: set `"mcp_python_unrestricted": "true"` in the -`app` section of the datadir's `OrcaSlicer.conf` before the launch, as -`orca_mcp.py launch --unrestricted-scripts` does, since no tool can turn it on. +no network, unless scripts run unrestricted: start the app with `--unrestricted-scripts` for one run (as +`orca_mcp.py launch --unrestricted-scripts` does), or a person turns the setting on in Preferences. No tool +can turn either on. A `.py` file runs as Python runs it (`python file.py`), with the whole plugin API: `__name__` is `"__main__"`, `__file__` and `sys.argv` name it, the modules beside it import (afresh each run, so an edit diff --git a/tools/mcp/orca_mcp.py b/tools/mcp/orca_mcp.py index 02949e8d88..aa4cfb4e27 100755 --- a/tools/mcp/orca_mcp.py +++ b/tools/mcp/orca_mcp.py @@ -255,10 +255,8 @@ def write_conf(conf, data): f.write("\n") -def seed_datadir(datadir, printer, cad=False, unrestricted_scripts=False): - """Seed a fresh datadir's OrcaSlicer.conf. A datadir that has one keeps it, except for the settings - cad and unrestricted_scripts turn on, which only the file can: the app creates the Design tab only at - startup, when its setting is on, and no tool lets Python scripts run unrestricted. +def seed_datadir(datadir, printer): + """Seed a fresh datadir's OrcaSlicer.conf. A datadir that has one keeps it. A fresh datadir keeps the Orca Cloud login in its own token file (use_encrypted_token_file), not in the system's secret store, so the instance starts signed out and never reads the person's login: on macOS @@ -266,26 +264,13 @@ def seed_datadir(datadir, printer, cad=False, unrestricted_scripts=False): vendor, model, nozzle, filament = printer os.makedirs(datadir, exist_ok=True) conf = os.path.join(datadir, "OrcaSlicer.conf") - switches = {} - if cad: - switches["enable_cad_feature"] = True - if unrestricted_scripts: - switches["mcp_python_unrestricted"] = "true" if os.path.exists(conf): - if switches: - with open(conf, encoding="utf-8") as f: - text = f.read() - # The app ends the file with a checksum line after the JSON; a mismatch only logs. - data = json.loads(text[:text.rfind("}") + 1]) - data.setdefault("app", {}).update(switches) - write_conf(conf, data) return write_conf(conf, {"firstguide": {"finish": True}, "models": [{"model": model, "nozzle_diameter": nozzle, "vendor": vendor}], "filaments": [filament], "presets": {"machine": f"{model} {nozzle} nozzle"}, - "app": {"check_for_updates": False, "show_daily_tips": False, "use_encrypted_token_file": True, - **switches}}) + "app": {"check_for_updates": False, "show_daily_tips": False, "use_encrypted_token_file": True}}) # The headless compositors --headless tries, in order, by the binary each needs. @@ -469,13 +454,15 @@ def launch(args): if args.printer: model, _, nozzle = args.printer.partition("@") printer = (args.vendor, model, nozzle or "0.4", args.filament or DEFAULT_PRINTER[3]) - seed_datadir(datadir, printer, args.cad, args.unrestricted_scripts) + seed_datadir(datadir, printer) env = dict(os.environ, ORCA_MCP_TOKEN=token) binary = find_binary(args.bin) server, display_env, server_pid = start_display(args, datadir) app_env(env, datadir, display_env) - cmd = [binary, "--datadir", datadir, "--mcp", "--mcp-port", str(args.port)] + args.extra + # The two flags hold for this run and never write the datadir's settings. + flags = (["--cad"] if args.cad else []) + (["--unrestricted-scripts"] if args.unrestricted_scripts else []) + cmd = [binary, "--datadir", datadir, "--mcp", "--mcp-port", str(args.port)] + flags + args.extra log = open(os.path.join(datadir, "mcp-launch.log"), "w") proc = subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) @@ -540,9 +527,10 @@ def main(): p.add_argument("--printer", help="\"<model>@<nozzle>\" for a fresh datadir, e.g. \"Bambu Lab X1 Carbon@0.4\"") p.add_argument("--vendor", default="BBL") p.add_argument("--filament") - p.add_argument("--cad", action="store_true", help="turn the Design (CAD) tab on, for its commands (search_tools group Design)") + p.add_argument("--cad", action="store_true", + help="start the app with --cad: the Design (CAD) tab on for this run, for its commands (search_tools group Design)") p.add_argument("--unrestricted-scripts", action="store_true", - help="let Python scripts (run_script) run unrestricted, which no tool can turn on") + help="start the app with --unrestricted-scripts: Python scripts (run_script) unrestricted for this run") p.add_argument("--timeout", type=int, default=120) p.add_argument("--print-config", action="store_true", help="print client setup commands") p.add_argument("extra", nargs="*", help="extra orca-slicer arguments after --") diff --git a/tools/mcp/smoke_test.json b/tools/mcp/smoke_test.json index 354acc6cc7..3194e207af 100644 --- a/tools/mcp/smoke_test.json +++ b/tools/mcp/smoke_test.json @@ -3,7 +3,7 @@ // instance with // tools/mcp/orca_mcp.py run-replay tools/mcp/smoke_test.json --out /tmp/smoke // or headless with -// orca-slicer --mcp-run tools/mcp/smoke_test.json --mcp-run-out /tmp/smoke +// orca-slicer --run tools/mcp/smoke_test.json --outputdir /tmp/smoke { "orca_replay": 1, "name": "smoke", diff --git a/tools/mcp/test_command_line.py b/tools/mcp/test_command_line.py new file mode 100644 index 0000000000..ce42ac9efc --- /dev/null +++ b/tools/mcp/test_command_line.py @@ -0,0 +1,473 @@ +"""Checks OrcaSlicer's command line: the options it refuses, what --run does with its file and its folders, where --run +is refused, what --mcp-port opens, the two flags that hold for one run, and a run beside a window already open. + +Each check starts the built app as this script's child, on a fresh data folder with a short path under the temporary +folder, seeded as orca_mcp.py launch seeds one, with preset sync off and the update check sent to the loopback's +discard port. Only a process's parent can read its exit code on every system. The replays and scripts a check runs are +written by the check into a temporary folder of its own. An app that serves is closed as a person closes it, by a click +on the File menu's Quit item that list_widgets lists; an app still running when its check is done is killed with its +child processes. + +- refused_options: --mcp-run r.json, --mcp-run-out d, --mcp-token t and --no-mcp each exit non-zero within 10 s with + "Invalid option" on stderr, and the data folder holds only the seeded OrcaSlicer.conf, which a GUI that started + would have added its log and cache folders to. +- run_invalid_file: --run missing.json exits 2, and so does --run a.txt, whose text is a valid replay. +- run_replay_folders: --run r.json, a replay whose one step is get_app_state, exits 0 with result.json in r.out beside + it; with --outputdir D, a folder that does not exist yet, it exits 0, D holds result.json, and r.out is not created. +- run_script_output_folder: --run s.py, whose code takes a screenshot with no path, exits 0 with one .png in D when + given --outputdir D, and without it in <datadir>/automation/out, while <datadir>/mcp/out does not exist. +- run_refused_without_gui: --run s.py beside --export-3mf out.3mf model.stl, and beside --downward-check, each exit + with CLI_INVALID_PARAMS within 10 s, stderr says "--run cannot be combined with" the other option, and the data + folder holds only OrcaSlicer.conf. +- mcp_port_opens_endpoint: --mcp-port P alone, with mcp_enabled false in the conf, serves on P; --mcp-port 0 alone, + with mcp_port 13694 in the conf, serves on 13694. A server counts as this app's when its discovery file names the + app's pid. +- unrestricted_scripts_flag: --unrestricted-scripts --run r.py, where r.py reads a file the test wrote in a temporary + folder that is neither the data folder, the resources folder nor the script's own, exits 0, and the conf's + python_scripts_unrestricted is absent or false after exit; without the flag the same run exits 1. +- cad_flag: --cad --mcp on a fresh data folder: search_tools {group: Design} finds commands and get_app_state has no + cad_note; after exit the conf's enable_cad_feature is absent or false. A second start without the flag on the same + folder finds no Design command. +- run_beside_open_window: with single_instance true in the conf and a first window serving on the same data folder, + --run r.json runs in a second process, exits 0 and writes its result.json, and the first window has loaded no + object; then, with that window closed, two --run r.json processes started together on that folder both exit 0. + +Prints one line per check and exits 1 when one fails. Checks named on the command line run alone, in that order. Run it +as python tools/mcp/test_command_line.py [--bin PATH] [CHECK ...]. +""" +import http.client +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from orca_mcp import DEFAULT_PRINTER, McpError, OrcaMcp, app_env, find_binary, seed_datadir, write_conf # noqa: E402 + +PORT = 13694 # the port the checks that serve listen on, and the conf's mcp_port where one is seeded +GIVEN_PORT = 13693 # the port --mcp-port gives in mcp_port_opens_endpoint +TOKEN = "command-line-test-token" +REFUSE_LIMIT_S = 10 # a refused command line ends before any GUI starts +RUN_LIMIT_S = 120 # from the start of a --run until the process is gone, a first start's profile copy included +READY_LIMIT_S = 120 +EXIT_LIMIT_S = 45 # from the click on Quit, past the app's 30 s exit watchdog +INVALID_PARAMS = (-2, 254) # CLI_INVALID_PARAMS as Windows and POSIX report it +DROPPED = (McpError, OSError, http.client.HTTPException) + +REPLAY = {"orca_replay": 1, "name": "the app's state", "steps": [{"tool": "get_app_state"}]} +SCREENSHOT_SCRIPT = """ +import orca +orca.host.tools.call("screenshot", {"include_image": False}) +""" + +results = [] + + +def check(name, problems, evidence): + results.append(not problems) + print(("PASS " if not problems else "FAIL ") + name + " " + ("; ".join(problems) if problems else evidence), flush=True) + + +def remove(folder): + """Removes a temporary folder, retrying while the app's helper processes (WebView2) let go of its files.""" + for _ in range(20): + shutil.rmtree(folder, ignore_errors=True) + if not os.path.exists(folder): + return + time.sleep(0.5) + + +def exit_code(code): + """The process's exit code as a signed number: Windows reports a negative one as its unsigned 32-bit value.""" + return code - (1 << 32) if code is not None and code >= (1 << 31) else code + + +def write(path, text): + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + +def read_conf(datadir): + """The app section of the data folder's OrcaSlicer.conf, which ends with a checksum line after the JSON.""" + with open(os.path.join(datadir, "OrcaSlicer.conf"), encoding="utf-8") as f: + text = f.read() + return json.loads(text[:text.rfind("}") + 1]).get("app", {}) + + +def is_off(value): + return value in (None, False, "false", "0") + + +class Work: + """A check's temporary folder, short enough for the first start's profile copy: the data folder is its `data` + subfolder, launched from with no .py file in it, and the check's files go in `files`.""" + + def __init__(self, **app): + self.root = tempfile.mkdtemp(prefix="ocl-") + self.datadir = os.path.join(self.root, "data") + self.files = os.path.join(self.root, "files") + os.makedirs(self.files) + seed_datadir(self.datadir, DEFAULT_PRINTER) + conf = os.path.join(self.datadir, "OrcaSlicer.conf") + with open(conf, encoding="utf-8") as f: + data = json.load(f) + data["app"].update({"sync_user_preset": False, "version_check_url": "http://127.0.0.1:9/", **app}) + write_conf(conf, data) + self.apps = [] + + def file(self, name, text=None): + path = os.path.join(self.files, name) + return write(path, text) if text is not None else path + + def start(self, binary, *args, name="app"): + app = App(binary, self.datadir, self.root, name, args) + self.apps.append(app) + return app + + def only_conf_in_datadir(self): + """What the data folder holds besides OrcaSlicer.conf, as a problem, or None.""" + extra = sorted(set(os.listdir(self.datadir)) - {"OrcaSlicer.conf"}) + return f"the data folder gained {extra}, so the GUI started" if extra else None + + def __enter__(self): + return self + + def __exit__(self, *exc): + for app in self.apps: + app.close() + remove(self.root) + + +class App: + """One start of the app, its output in files beside the data folder.""" + + def __init__(self, binary, datadir, root, name, args): + self.datadir = datadir + self.stderr_path = os.path.join(root, name + ".stderr.txt") + env = app_env(dict(os.environ, ORCA_MCP_TOKEN=TOKEN), datadir) + with open(os.path.join(root, name + ".stdout.txt"), "w") as out, open(self.stderr_path, "w") as err: + self.proc = subprocess.Popen([binary, "--datadir", datadir, *args], env=env, cwd=datadir, stdout=out, stderr=err) + self.started = time.monotonic() + self.orca = None + + def wait(self, limit): + """The exit code once the process is gone within `limit` s of its start, else None after killing it.""" + try: + return exit_code(self.proc.wait(timeout=max(0.0, limit - (time.monotonic() - self.started)))) + except subprocess.TimeoutExpired: + self.kill() + return None + + def stderr(self): + with open(self.stderr_path, encoding="utf-8", errors="replace") as f: + return f.read() + + def serve(self, port): + """Waits until this app's server answers on `port` and returns "", or why it did not. The discovery file + names the pid that wrote it, which tells this app from another one on the port.""" + orca = OrcaMcp(port, TOKEN) + deadline = time.monotonic() + READY_LIMIT_S + while time.monotonic() < deadline and self.proc.poll() is None: + try: + if not orca.call("wait", _timeout=15, **{"for": "ready", "timeout_s": 5}).get("satisfied"): + continue + except DROPPED: + time.sleep(0.5) + continue + try: + with open(os.path.join(self.datadir, "mcp", "server.json"), encoding="utf-8") as f: + info = json.load(f) + except (OSError, ValueError) as e: + return f"a server is ready on port {port}, but this app wrote no discovery file ({e})" + if info.get("pid") != self.proc.pid or info.get("port") != port: + return f"a server is ready on port {port}, but the discovery file says {info}" + self.orca = orca + return "" + if self.proc.poll() is not None: + return f"the app exited with code {exit_code(self.proc.returncode)} before it served on {port}" + return f"the app did not serve on {port} in {READY_LIMIT_S} s" + + def quit(self): + """Closes the app with File > Quit, as a person does, and returns its exit code, or None when it was killed. + The click's reply may not arrive, since the server closes with the app.""" + if self.orca is not None and self.proc.poll() is None: + try: + _, texts = self.orca.call_with_text("list_widgets", _timeout=10, query="Quit") + found = re.search(r'\[(\w+)\] menu_item "Quit"', "".join(texts)) + if found: + self.orca.call_raw("click", {"target": found.group(1)}, timeout=10) + except DROPPED: + pass + try: + return exit_code(self.proc.wait(timeout=EXIT_LIMIT_S)) + except subprocess.TimeoutExpired: + self.kill() + return None + + def kill(self): + if self.proc.poll() is None: + if os.name == "nt": + subprocess.run(["taskkill", "/T", "/F", "/PID", str(self.proc.pid)], capture_output=True) + else: + self.proc.kill() + self.proc.wait() + + def close(self): + if self.proc.poll() is None: + if self.orca is not None: + self.quit() + self.kill() + + +def refused_options(binary): + problems = [] + for label, args in (("--mcp-run r.json", lambda work: ["--mcp-run", work.file("r.json", json.dumps(REPLAY))]), + ("--mcp-run-out d", lambda work: ["--mcp-run-out", work.file("d")]), + ("--mcp-token t", lambda work: ["--mcp-token", "t"]), + ("--no-mcp", lambda work: ["--no-mcp"])): + with Work() as work: + app = work.start(binary, *args(work)) + code = app.wait(REFUSE_LIMIT_S) + if code is None: + problems.append(f"{label}: still running {REFUSE_LIMIT_S} s after its start") + elif code == 0: + problems.append(f"{label}: exit code 0") + if "Invalid option" not in app.stderr(): + problems.append(f"{label}: no \"Invalid option\" on stderr") + if (gui := work.only_conf_in_datadir()) is not None: + problems.append(f"{label}: {gui}") + check("refused_options", problems, "each exits non-zero within 10 s with \"Invalid option\" and no GUI") + + +def run_invalid_file(binary): + problems = [] + with Work() as work: + missing = work.file("missing.json") + code = work.start(binary, "--run", missing, name="missing").wait(RUN_LIMIT_S) + if code != 2: + problems.append(f"--run missing.json: exit code {code}") + text = work.file("a.txt", json.dumps(REPLAY)) + code = work.start(binary, "--run", text, name="txt").wait(RUN_LIMIT_S) + if code != 2: + problems.append(f"--run a.txt: exit code {code}") + check("run_invalid_file", problems, "--run missing.json and --run a.txt each exit 2") + + +def run_replay_folders(binary): + problems = [] + with Work() as work: + replay = work.file("r.json", json.dumps(REPLAY)) + beside = os.path.join(work.files, "r.out") + code = work.start(binary, "--run", replay, name="beside").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--run r.json: exit code {code}") + if not os.path.isfile(os.path.join(beside, "result.json")): + problems.append("--run r.json: no result.json in r.out") + shutil.rmtree(beside, ignore_errors=True) + given = os.path.join(work.root, "given", "D") + code = work.start(binary, "--run", replay, "--outputdir", given, name="given").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--run r.json --outputdir D: exit code {code}") + if not os.path.isfile(os.path.join(given, "result.json")): + problems.append("--run r.json --outputdir D: no result.json in D") + if os.path.exists(beside): + problems.append("--run r.json --outputdir D: r.out was created") + check("run_replay_folders", problems, "result.json in r.out, and with --outputdir in D alone") + + +def pngs(folder): + try: + return [n for n in os.listdir(folder) if n.lower().endswith(".png")] + except OSError: + return [] + + +def run_script_output_folder(binary): + problems = [] + with Work() as work: + script = work.file("s.py", SCREENSHOT_SCRIPT) + given = os.path.join(work.root, "D") + code = work.start(binary, "--run", script, "--outputdir", given, name="given").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--run s.py --outputdir D: exit code {code}") + if len(pngs(given)) != 1: + problems.append(f"--run s.py --outputdir D: D holds {pngs(given)}") + default = os.path.join(work.datadir, "automation", "out") + if pngs(default): + problems.append(f"--run s.py --outputdir D: <datadir>/automation/out holds {pngs(default)}") + code = work.start(binary, "--run", script, name="default").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--run s.py: exit code {code}") + if len(pngs(default)) != 1: + problems.append(f"--run s.py: <datadir>/automation/out holds {pngs(default)}") + if os.path.exists(os.path.join(work.datadir, "mcp", "out")): + problems.append("--run s.py: <datadir>/mcp/out exists") + check("run_script_output_folder", problems, "the screenshot in D with --outputdir, else in <datadir>/automation/out") + + +def run_refused_without_gui(binary): + problems = [] + for other, extra in (("--export-3mf", ["--export-3mf", "out.3mf", "model.stl"]), ("--downward-check", ["--downward-check"])): + with Work() as work: + script = work.file("s.py", SCREENSHOT_SCRIPT) + app = work.start(binary, "--run", script, *extra) + code = app.wait(REFUSE_LIMIT_S) + if code not in INVALID_PARAMS: + problems.append(f"--run s.py {other}: exit code {code}") + if f"--run cannot be combined with {other}" not in app.stderr(): + problems.append(f"--run s.py {other}: stderr says {app.stderr().strip()[:200]!r}") + if (gui := work.only_conf_in_datadir()) is not None: + problems.append(f"--run s.py {other}: {gui}") + check("run_refused_without_gui", problems, "each exits CLI_INVALID_PARAMS naming --run, with no GUI") + + +def mcp_port_opens_endpoint(binary): + problems = [] + with Work(mcp_enabled=False) as work: + app = work.start(binary, "--mcp-port", str(GIVEN_PORT)) + if (why := app.serve(GIVEN_PORT)): + problems.append(f"--mcp-port {GIVEN_PORT}: {why}") + app.quit() + with Work(mcp_enabled=False, mcp_port=str(PORT)) as work: + app = work.start(binary, "--mcp-port", "0") + if (why := app.serve(PORT)): + problems.append(f"--mcp-port 0: {why}") + app.quit() + check("mcp_port_opens_endpoint", problems, f"--mcp-port {GIVEN_PORT} serves there, --mcp-port 0 on the conf's {PORT}") + + +def unrestricted_scripts_flag(binary): + problems = [] + outside = tempfile.mkdtemp(prefix="ocl-out-") + try: + target = write(os.path.join(outside, "outside.txt"), "outside") + with Work() as work: + script = work.file("r.py", f""" +with open({target!r}, encoding="utf-8") as f: + if f.read() != "outside": + raise RuntimeError("the file read back otherwise") +""") + code = work.start(binary, "--unrestricted-scripts", "--run", script, name="flag").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--unrestricted-scripts --run r.py: exit code {code}") + value = read_conf(work.datadir).get("python_scripts_unrestricted") + if not is_off(value): + problems.append(f"the conf's python_scripts_unrestricted is {value!r} after exit") + code = work.start(binary, "--run", script, name="no-flag").wait(RUN_LIMIT_S) + if code != 1: + problems.append(f"--run r.py without the flag: exit code {code}") + finally: + remove(outside) + check("unrestricted_scripts_flag", problems, + "the script read outside with the flag, the setting stayed off, and without the flag it exited 1") + + +def design_commands(orca): + """How many commands search_tools lists in the group Design, and "" or why the answer was not one. With the Design + tab off no command has that group, and search_tools refuses it as unknown, naming the groups there are; that + refusal counts as none, and any other error is a problem.""" + try: + return len(orca.call("search_tools", group="Design").get("names", [])), "" + except McpError as e: + refused = re.search(r"Unknown group: Design; the groups are ([^\"]*)", str(e)) + if refused and "Design" not in [g.strip() for g in refused.group(1).split(",")]: + return 0, "" + return 0, f"search_tools {{group: Design}} failed: {str(e)[:300]}" + + +def cad_flag(binary): + problems = [] + found = 0 + with Work(mcp_port=str(PORT)) as work: + app = work.start(binary, "--cad", "--mcp", name="flag") + if (why := app.serve(PORT)): + problems.append(f"--cad --mcp: {why}") + else: + found, error = design_commands(app.orca) + if error: + problems.append(f"--cad --mcp: {error}") + elif found == 0: + problems.append("--cad --mcp: search_tools finds no Design command") + note = app.orca.call("get_app_state").get("cad_note") + if note is not None: + problems.append(f"--cad --mcp: get_app_state has cad_note {note!r}") + app.quit() + value = read_conf(work.datadir).get("enable_cad_feature") + if not is_off(value): + problems.append(f"the conf's enable_cad_feature is {value!r} after exit") + app = work.start(binary, "--mcp", name="no-flag") + if (why := app.serve(PORT)): + problems.append(f"--mcp: {why}") + else: + count, error = design_commands(app.orca) + if error: + problems.append(f"--mcp without --cad: {error}") + elif count != 0: + problems.append(f"--mcp without --cad: search_tools finds {count} Design commands") + app.quit() + check("cad_flag", problems, f"{found} Design commands with --cad, none without, enable_cad_feature stayed off") + + +def run_beside_open_window(binary): + problems = [] + with Work(single_instance=True) as work: + replay = work.file("r.json", json.dumps(REPLAY)) + first = work.start(binary, "--mcp", "--mcp-port", str(PORT), name="first") + if (why := first.serve(PORT)): + return check("run_beside_open_window", [f"the first window: {why}"], "") + out = os.path.join(work.root, "second") + code = work.start(binary, "--run", replay, "--outputdir", out, name="second").wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"--run r.json beside the first window: exit code {code}") + if not os.path.isfile(os.path.join(out, "result.json")): + problems.append("--run r.json beside the first window: no result.json") + objects = first.orca.call("get_app_state").get("objects") + if objects != 0: + problems.append(f"the first window has {objects} objects") + first.quit() + both = [(os.path.join(work.root, f"together{i}"), work.start(binary, "--run", replay, "--outputdir", + os.path.join(work.root, f"together{i}"), + name=f"together{i}")) for i in (1, 2)] + for i, (folder, app) in enumerate(both, 1): + code = app.wait(RUN_LIMIT_S) + if code != 0: + problems.append(f"run {i} of two started together: exit code {code}") + if not os.path.isfile(os.path.join(folder, "result.json")): + problems.append(f"run {i} of two started together: no result.json") + check("run_beside_open_window", problems, + "the run beside an open window exited 0 there and loaded nothing into it; two together both exited 0") + + +CHECKS = {f.__name__: f for f in (refused_options, run_invalid_file, run_replay_folders, run_script_output_folder, + run_refused_without_gui, mcp_port_opens_endpoint, unrestricted_scripts_flag, cad_flag, + run_beside_open_window)} + + +def main(): + argv = sys.argv[1:] + explicit = None + if "--bin" in argv: + i = argv.index("--bin") + explicit = argv[i + 1] if i + 1 < len(argv) else None + del argv[i:i + 2] + unknown = [a for a in argv if a not in CHECKS] + if unknown: + print(f"unknown check {', '.join(unknown)}; the {len(CHECKS)} checks are {', '.join(CHECKS)}\n" + f"usage: python tools/mcp/test_command_line.py [--bin PATH] [CHECK ...]") + return 2 + binary = find_binary(explicit) + for name in argv or CHECKS: + CHECKS[name](binary) + failed = results.count(False) + print(f"{len(results) - failed} of {len(results)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_orca_mcp_attach.py b/tools/mcp/test_orca_mcp_attach.py index d55cb829d2..6912c0fa3a 100755 --- a/tools/mcp/test_orca_mcp_attach.py +++ b/tools/mcp/test_orca_mcp_attach.py @@ -260,11 +260,10 @@ def check_seed_datadir(): reused = scratch("orca-seed-reused-") orca_mcp.write_conf(os.path.join(reused, "OrcaSlicer.conf"), {"app": {"use_encrypted_token_file": False}}) - orca_mcp.seed_datadir(reused, orca_mcp.DEFAULT_PRINTER, cad=True) - app = read_conf(reused)["app"] - assert app.get("enable_cad_feature") is True, app - assert app.get("use_encrypted_token_file") is False, app - ok("seed_datadir() leaves a reused datadir's login where its conf keeps it") + orca_mcp.seed_datadir(reused, orca_mcp.DEFAULT_PRINTER) + conf = read_conf(reused) + assert conf == {"app": {"use_encrypted_token_file": False}}, conf + ok("seed_datadir() leaves a reused datadir's conf as it is, its login where the conf keeps it") def main(): diff --git a/tools/mcp/test_plugin_tools.py b/tools/mcp/test_plugin_tools.py index 76a26c2941..60e4e712df 100644 --- a/tools/mcp/test_plugin_tools.py +++ b/tools/mcp/test_plugin_tools.py @@ -2,8 +2,8 @@ Launches OrcaSlicer on a fresh data folder with the Design tab on (in a build with CAD) and tests/plugins/mcp_tools_fixture side-loaded, and tests/plugins/mcp_tools_broken, whose load fails after declaring an -operation: over MCP, then once without MCP, running a replay with --mcp-run, so the plugin's calls go to the -service started without its endpoint. The first launch also checks that the plugin is sent the NewProject event when +operation: over MCP, then once without MCP, running a replay with --run, so the plugin's calls go to the +runtime started without its endpoint. The first launch also checks that the plugin is sent the NewProject event when the new_project tool or command starts a project, and ends by unticking the fixture in the Plugins dialog, as a person unloads it. Run it as python tools/mcp/test_plugin_tools.py [--bin PATH]. @@ -222,7 +222,7 @@ def main(): harness(env, "stop") time.sleep(3) - # --- Without MCP: a launch replay runs the plugin's script, whose calls reach the service without its endpoint. --- + # --- Without MCP: a launch replay runs the plugin's script, whose calls reach the runtime without its endpoint. --- install(datadir) # enabled again: unticking it saved it disabled steps = os.path.join(datadir, "plugin_rule.json") with open(steps, "w", encoding="utf-8") as f: @@ -232,7 +232,7 @@ def main(): out = os.path.join(plugin_dir, "out_rule.json") if os.path.exists(out): os.remove(out) - subprocess.run([binary, "--datadir", datadir, "--mcp-run", steps], env=env, timeout=600) + subprocess.run([binary, "--datadir", datadir, "--run", steps], env=env, timeout=600) try: with open(out, encoding="utf-8") as f: offline = json.load(f) diff --git a/tools/mcp/test_runtime_lifecycle.py b/tools/mcp/test_runtime_lifecycle.py new file mode 100644 index 0000000000..a3e773476c --- /dev/null +++ b/tools/mcp/test_runtime_lifecycle.py @@ -0,0 +1,471 @@ +"""Checks how OrcaSlicer's automation behaves while the app closes, and while its server is switched off and on +during a call. + +Each of the five checks launches OrcaSlicer on a fresh data folder of its own, with the MCP server on unless it says +otherwise. The app is started here, as orca_mcp.py launch starts it, but as this script's child: only a process's parent +can read its exit code on every system. It is closed as a person closes it, by a click on the File menu's Quit item that +list_widgets lists; the click's reply may not arrive, since the server closes with the app. orca_mcp.py stop would not +do: on Windows it kills the process. + +- exit_with_job_running: a run_script whose code sleeps in 0.2 s steps for 120 s replies running once its reply budget + is spent, and the app is closed. It passes when the process is gone within 20 s with exit code 0 and no line of the + log under <datadir>/log contains "did not return". +- exit_with_recording: a run_script whose code starts a recording through orca.host.tools into a temporary folder and + then sleeps as above; 3 s later the app is closed. It passes as the first does, and when the recording's file is a + finished one: the writer puts the header down at once and patches the Segment's size and the Duration only as it + closes the file (MkvWriter.cpp), so the file is read for a known Segment size that ends at the file's end, a Duration + above 0 and at least one Cluster. +- exit_without_endpoint: the app is started with the server off and --run on a replay whose one step is + get_app_state, expecting mcp.serving false. It passes when the process exits with code 0 within 60 s, the replay's + result.json says passed (so the endpoint stayed off) and the log has no line containing "did not return". +- server_off_and_on_during_a_call: a run_script whose code opens Preferences, switches the server off with the widget + named mcp_enabled, keeps get_app_state's mcp.serving, switches it on, reads it again, closes the dialog and returns + both values. Closing the endpoint drops every connection, the one waiting for the run's job too, so the code waits + until the test holds its job before it switches, and the test reconnects and reads the job with wait {for: "job"}. It + passes when the job finished, the values are false then true, and the server answers on the port it had before. +- exit_with_stuck_call: as exit_with_job_running, but the code is one time.sleep(120), a call no stop interrupts, so + the run is still inside it when the app closes. It passes when the process is gone within 25 s with exit code 0 and + the log has a line containing "did not return": the app left the runtime in place under the call rather than free + it. A missing line means the runtime was freed under the call or the call was interrupted, a change to explain. + Its limit is longer than the others' since its exit holds the runtime's 10 s drain. + +Prints one line per check, five in all, and exits 1 when one fails. Checks named on the command line run alone, in +that order. Run it as python tools/mcp/test_runtime_lifecycle.py [--bin PATH] [CHECK ...]. +""" +import http.client +import json +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from orca_mcp import DEFAULT_PRINTER, McpError, OrcaMcp, app_env, find_binary, seed_datadir, write_conf # noqa: E402 + +PORT = 13694 +TOKEN = "runtime-lifecycle-test-token" +EXIT_LIMIT_S = 20 # from the click on Quit until the process is gone +# exit_with_stuck_call's limit from the click on Quit: its exit holds the runtime deleter's 10 s drain by design, and +# the limit stays below the app's 30 s exit watchdog, so an exit the watchdog forces still fails the check. +STUCK_EXIT_LIMIT_S = 25 +RUN_EXIT_LIMIT_S = 60 # from the start of a --run until the process is gone +# What AutomationRuntimeDeleter logs when a call has not returned by the time the runtime goes. Only these words are +# matched: the rest of the line may be worded otherwise. +STUCK = "did not return" +# What a call over a closing or closed endpoint can end in: the server's refusal, a refused or dropped connection, or a +# reply cut off. +DROPPED = (McpError, OSError, http.client.HTTPException) + +# Sleeps in 0.2 s steps: a stop interrupts a run at its next bytecode, which one long sleep would put off until it ends. +SLEEPER = """ +import time +end = time.monotonic() + 120 +while time.monotonic() < end: + time.sleep(0.2) +""" +# One sleep, which no stop interrupts: the run is still inside its call when the app closes. +STUCK_SLEEPER = """ +import time +time.sleep(120) +""" +RECORDER = """ +import orca +orca.host.tools.call("start_recording", {"save_path": args["save_path"]}) +""" + SLEEPER +# The run waits for the go file, which the test writes once it holds the run's job: the switch closes the connection a +# reply would come back on. +SWITCHER = """ +import os +import time +import orca +tools = orca.host.tools +opened = tools.call("run_action", {"id": "orca_command:open_preferences:orca", "args": {"tab": "general", "key": "mcp_enabled"}}) +deadline = time.monotonic() + 60 +while not os.path.exists(args["go"]): + if time.monotonic() > deadline: + raise TimeoutError("the test never wrote the go file") + time.sleep(0.1) +switch = {"name": "mcp_enabled", "within": "Preferences"} +tools.call("set_widget_value", {"target": switch, "value": False}) +off = tools.call("get_app_state")["mcp"]["serving"] +tools.call("set_widget_value", {"target": switch, "value": True}) +on = tools.call("get_app_state")["mcp"]["serving"] +tools.call("answer_dialog", {"dialog": {"title": "Preferences"}, "button": "close"}) +if opened.get("job"): + tools.call("wait", {"for": "job", "job": opened["job"], "timeout_s": 30}) +result = [off, on] +""" + +# The ids of the Matroska elements a finished recording is read for. +SEGMENT = bytes.fromhex("18538067") +DURATION = bytes.fromhex("448988") # the Duration id and its 8-byte payload size +CLUSTER = bytes.fromhex("1F43B675") + +results = [] + + +def check(name, problems, evidence): + results.append(not problems) + print(("PASS " if not problems else "FAIL ") + name + " " + ("; ".join(problems) if problems else evidence), flush=True) + + +def remove(folder): + """Removes a temporary folder, retrying while the app's helper processes (WebView2) let go of its files.""" + for _ in range(20): + shutil.rmtree(folder, ignore_errors=True) + if not os.path.exists(folder): + return + time.sleep(0.5) + + +def seed(datadir): + """orca_mcp.py launch's fresh data folder, with preset sync off and the update check sent to the loopback's discard + port, where nothing answers.""" + seed_datadir(datadir, DEFAULT_PRINTER) + conf = os.path.join(datadir, "OrcaSlicer.conf") + with open(conf, encoding="utf-8") as f: + data = json.load(f) + data["app"].update({"sync_user_preset": False, "version_check_url": "http://127.0.0.1:9/"}) + write_conf(conf, data) + + +class Instance: + """A private OrcaSlicer on a fresh data folder, started as this script's child, its working folder that data folder, + which holds no .py file to shadow a module run_script needs. On leaving, an app still running is closed as a person + closes it when the server on PORT is its own, then killed if it outlives its exit watchdog, and the folder is + removed.""" + + def __init__(self, binary, *args, serve=True): + self.datadir = tempfile.mkdtemp(prefix="orca-lifecycle-") + seed(self.datadir) + env = app_env(dict(os.environ, ORCA_MCP_TOKEN=TOKEN), self.datadir) + cmd = [binary, "--datadir", self.datadir, *(["--mcp", "--mcp-port", str(PORT)] if serve else []), *args] + with open(os.path.join(self.datadir, "mcp-launch.log"), "w") as out: + self.proc = subprocess.Popen(cmd, env=env, cwd=self.datadir, stdout=out, stderr=subprocess.STDOUT) + self.orca = OrcaMcp(PORT, TOKEN) + self.serves_here = False + try: + self.not_ready = self._wait_ready(120) if serve else "" + except BaseException: + self.__exit__() + raise + + def _wait_ready(self, timeout): + """Why this instance's server is not ready on PORT, or "" once it is. The discovery file the server writes into + the fresh data folder tells this app from another one that may hold the port.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline and self.proc.poll() is None: + try: + if not self.orca.call("wait", _timeout=15, **{"for": "ready", "timeout_s": 5}).get("satisfied"): + continue + except DROPPED: + time.sleep(0.5) + continue + try: + with open(os.path.join(self.datadir, "mcp", "server.json"), encoding="utf-8") as f: + info = json.load(f) + except (OSError, ValueError) as e: + return f"a server is ready on port {PORT}, but this app wrote no discovery file ({e})" + if info.get("pid") != self.proc.pid or info.get("port") != PORT: + return f"a server is ready on port {PORT}, but this app's discovery file says {info}" + self.serves_here = True + return "" + if self.proc.poll() is not None: + return f"the app exited with code {self.proc.returncode} before it was ready" + return f"the app was not ready in {timeout} s" + + def __enter__(self): + return self + + def __exit__(self, *exc): + if self.proc.poll() is None: + # Never another app's: one that holds the port is not this test's to close. + if self.serves_here: + quit_app(self.orca) + try: + self.proc.wait(timeout=45) # past the app's 30 s exit watchdog + except subprocess.TimeoutExpired: + self.proc.kill() + self.proc.wait() + print(f"NOTE the app on {self.datadir} did not close and was killed", flush=True) + remove(self.datadir) + + +def quit_app(orca): + """Clicks the File menu's Quit item, as a person closes the app, and says what came of the click: its reply, or why + none came. The reply may not arrive, since the server closes with the app.""" + try: + _, texts = orca.call_with_text("list_widgets", _timeout=10, query="Quit") + except DROPPED as e: + return f"list_widgets failed: {e}" + found = re.search(r'\[(\w+)\] menu_item "Quit"', "".join(texts)) + if not found: + return "list_widgets lists no Quit menu item" + try: + reply = orca.call_raw("click", {"target": found.group(1)}, timeout=10) + except DROPPED as e: + return f"the click's reply was lost ({type(e).__name__})" + return "the click replied " + json.dumps(reply)[:300] + + +def log_lines_containing(datadir, text): + """The lines of the app's log files under <datadir>/log that contain `text`, or None when there is no log.""" + folder = os.path.join(datadir, "log") + try: + paths = [p for p in (os.path.join(folder, n) for n in os.listdir(folder)) if os.path.isfile(p)] + except OSError: + return None + if not paths: + return None + lines = [] + for path in paths: + with open(path, encoding="utf-8", errors="replace") as f: + lines += [line.strip() for line in f if text in line] + return lines + + +def log_problems(datadir): + stuck = log_lines_containing(datadir, STUCK) + if stuck is None: + return [f"no log under {os.path.join(datadir, 'log')} to read"] + return ["the log says: " + line[:300] for line in stuck] + + +def close_as_a_person(app, limit=None): + """Closes the app with File > Quit and returns what is wrong with how the process ended (still running `limit` + seconds after the click, EXIT_LIMIT_S unless given, or a non-zero exit code), and the seconds it took.""" + limit = EXIT_LIMIT_S if limit is None else limit + start = time.monotonic() + clicked = quit_app(app.orca) + try: + code = app.proc.wait(timeout=max(0.0, limit - (time.monotonic() - start))) + problems = [] + except subprocess.TimeoutExpired: + problems = [f"still running {limit} s after Quit ({clicked})"] + try: + code = app.proc.wait(timeout=45) # past the exit watchdog, to read how it ended + except subprocess.TimeoutExpired: + return problems, time.monotonic() - start + took = time.monotonic() - start + if code != 0: + problems.append(f"exit code {code} after {took:.1f} s ({clicked})") + return problems, took + + +def call(orca, tool, **args): + """A tool's reply, or {"error": ...} when the call failed.""" + try: + return orca.call(tool, **args) + except DROPPED as e: + return {"error": f"{type(e).__name__}: {e}"} + + +def ebml_size(data, at): + """The value of the EBML size field at data[at] and its length in bytes, (None, 0) when it is malformed.""" + if at >= len(data): + return None, 0 + length = 1 + while length <= 8 and not data[at] & (0x80 >> (length - 1)): + length += 1 + if length > 8 or at + length > len(data): + return None, 0 + value = data[at] & (0xFF >> length) + for b in data[at + 1:at + length]: + value = value << 8 | b + return value, length + + +def unfinished_recording(path): + """Why the Matroska file at `path` is not a finished recording, or "" when it is.""" + try: + with open(path, "rb") as f: + data = f.read() + except OSError as e: + return f"cannot read it ({e})" + at = data.find(SEGMENT) + if at < 0: + return "it has no Segment" + size, length = ebml_size(data, at + 4) + if size is None: + return "its Segment's size is malformed" + if size == (1 << (7 * length)) - 1: # all value bits set: 01 FF FF FF FF FF FF FF in the writer's 8 bytes + return "its Segment's size is still unknown" + if at + 4 + length + size != len(data): + return f"its Segment ends at byte {at + 4 + length + size}, the file at {len(data)}" + d = data.find(DURATION, at) + if d < 0 or d + 11 > len(data): + return "it has no Duration" + duration = struct.unpack(">d", data[d + 3:d + 11])[0] + if not duration > 0: + return f"its Duration is {duration}" + if data.find(CLUSTER, at) < 0: + return "it has no Cluster" + return "" + + +def exit_with_job_running(binary): + name = "exit_with_job_running" + with Instance(binary) as app: + if app.not_ready: + return check(name, [app.not_ready], "") + reply = call(app.orca, "run_script", code=SLEEPER) + if reply.get("status") != "running": + return check(name, ["run_script did not reply running: " + json.dumps(reply)[:300]], "") + problems, took = close_as_a_person(app) + check(name, problems + log_problems(app.datadir), + f"run_script replied running; exit code 0 {took:.1f} s after Quit; no \"{STUCK}\" in the log") + + +def exit_with_recording(binary): + name = "exit_with_recording" + folder = tempfile.mkdtemp(prefix="orca-lifecycle-recording-") + video = os.path.join(folder, "session.mkv") + try: + with Instance(binary) as app: + if app.not_ready: + return check(name, [app.not_ready], "") + # No reply within 3 s means the script runs on, as it should; the call goes on in the app. + try: + early = app.orca.call("run_script", _timeout=3, code=RECORDER, args={"save_path": video}) + except McpError as e: + early = {"error": str(e)} + except (OSError, http.client.HTTPException): + early = None + if early is not None: + return check(name, ["the script ended within 3 s: " + json.dumps(early)[:300]], "") + deadline = time.monotonic() + 10 + while not os.path.exists(video) and time.monotonic() < deadline: + time.sleep(0.2) + if not os.path.exists(video): + return check(name, ["no recording was started"], "") + problems, took = close_as_a_person(app) + problems += log_problems(app.datadir) + why = unfinished_recording(video) + if why: + problems.append("the recording is not finished: " + why) + check(name, problems, f"exit code 0 {took:.1f} s after Quit; no \"{STUCK}\" in the log; the recording " + f"({os.path.getsize(video)} bytes) is finished") + finally: + remove(folder) + + +def exit_without_endpoint(binary): + name = "exit_without_endpoint" + folder = tempfile.mkdtemp(prefix="orca-lifecycle-replay-") + replay, out = os.path.join(folder, "state.json"), os.path.join(folder, "out") + os.makedirs(out) + with open(replay, "w", encoding="utf-8") as f: + # The expect makes a run that opened the endpoint fail the replay, and with it the check. + json.dump({"orca_replay": 1, "name": "the app's state without the server", + "steps": [{"tool": "get_app_state", "expect": {"/mcp/serving": {"eq": False}}}]}, f) + try: + with Instance(binary, "--run", replay, "--outputdir", out, serve=False) as app: + start = time.monotonic() + try: + code = app.proc.wait(timeout=RUN_EXIT_LIMIT_S) + except subprocess.TimeoutExpired: + return check(name, [f"still running {RUN_EXIT_LIMIT_S} s after its start"], "") + took = time.monotonic() - start + problems = [] if code == 0 else [f"exit code {code}"] + try: + with open(os.path.join(out, "result.json"), encoding="utf-8") as f: + passed = json.load(f).get("passed") + except (OSError, ValueError) as e: + passed = f"unreadable ({e})" + if passed is not True: + problems.append(f"result.json's passed is {passed}") + check(name, problems + log_problems(app.datadir), + f"exit code 0 {took:.1f} s after its start; result.json passed; no \"{STUCK}\" in the log") + finally: + remove(folder) + + +def server_off_and_on_during_a_call(binary): + name = "server_off_and_on_during_a_call" + with Instance(binary) as app: + if app.not_ready: + return check(name, [app.not_ready], "") + before = call(app.orca, "get_app_state").get("mcp", {}).get("port") + go = os.path.join(app.datadir, "go") + # The call replies blocked_by_dialog once the Preferences dialog the run opened is up. + reply = call(app.orca, "run_script", code=SWITCHER, args={"go": go}) + job = reply.get("job") + if reply.get("status") not in ("running", "blocked_by_dialog") or not job: + return check(name, ["run_script did not reply with a running job: " + json.dumps(reply)[:300]], "") + open(go, "w").close() + drops, done = 0, None + deadline = time.monotonic() + 90 + while done is None and time.monotonic() < deadline: + try: + r = app.orca.call("wait", **{"for": "job", "job": job, "timeout_s": 10}) + except DROPPED: + drops += 1 + time.sleep(0.5) + continue + if r.get("status") != "running" or r.get("job") != job: + done = r + if done is None: + return check(name, [f"the job never finished, or the server never came back on port {PORT}"], "") + after = call(app.orca, "get_app_state").get("mcp", {}).get("port") + problems = [] + if done.get("status") != "finished": + problems.append("the job did not finish: " + json.dumps(done)[:300]) + elif done.get("result") != [False, True]: + problems.append(f"mcp.serving read {done.get('result')}, not [false, true]") + if before != PORT or after != before: + problems.append(f"the port was {before} before and {after} after") + check(name, problems, f"job {job} finished; mcp.serving false then true; port {before} before and after; " + f"connections dropped while waiting: {drops}") + + +def exit_with_stuck_call(binary): + name = "exit_with_stuck_call" + with Instance(binary) as app: + if app.not_ready: + return check(name, [app.not_ready], "") + reply = call(app.orca, "run_script", code=STUCK_SLEEPER) + if reply.get("status") != "running": + return check(name, ["run_script did not reply running: " + json.dumps(reply)[:300]], "") + problems, took = close_as_a_person(app, STUCK_EXIT_LIMIT_S) + stuck = log_lines_containing(app.datadir, STUCK) + if stuck is None: + problems.append(f"no log under {os.path.join(app.datadir, 'log')} to read") + elif not stuck: + problems.append(f"no \"{STUCK}\" line in the log: the runtime was freed under the call, or the call was " + f"interrupted") + line = " ".join(stuck[0].split())[:200] if stuck else "" + check(name, problems, f"run_script replied running; exit code 0 {took:.1f} s after Quit; the log says: {line}") + + +CHECKS = {f.__name__: f for f in (exit_with_job_running, exit_with_recording, exit_without_endpoint, + server_off_and_on_during_a_call, exit_with_stuck_call)} + + +def main(): + argv = sys.argv[1:] + explicit = None + if "--bin" in argv: + i = argv.index("--bin") + explicit = argv[i + 1] if i + 1 < len(argv) else None + del argv[i:i + 2] + unknown = [a for a in argv if a not in CHECKS] + if unknown: + print(f"unknown check {', '.join(unknown)}; the {len(CHECKS)} checks are {', '.join(CHECKS)}\n" + f"usage: python tools/mcp/test_runtime_lifecycle.py [--bin PATH] [CHECK ...]") + return 2 + binary = find_binary(explicit) + print(f"binary: {binary}", flush=True) + for name in argv or CHECKS: + CHECKS[name](binary) + failed = results.count(False) + print(f"\n{len(results) - failed}/{len(results)} passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/tests/replay_basic.json b/tools/mcp/tests/replay_basic.json index 1a31fd28b1..c921dfe29a 100644 --- a/tools/mcp/tests/replay_basic.json +++ b/tools/mcp/tests/replay_basic.json @@ -1,6 +1,6 @@ // Opens a model, changes a print setting, slices and captures the preview: the smallest end-to-end -// check of --mcp-run. Run from anywhere: -// orca-slicer --mcp-run tools/mcp/tests/replay_basic.json --mcp-run-out /tmp/out +// check of --run. Run from anywhere: +// orca-slicer --run tools/mcp/tests/replay_basic.json --outputdir /tmp/out { "orca_replay": 1, "name": "basic slice",