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 <datadir>/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.
This commit is contained in:
SoftFever committed 2026-11-14 23:41:01 +08:00
1 parent b4be9d8374
commit fece418ae0
147 files changed
+7575 -5288

No files matched your search

+2 -2
View File
@@ -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
+300 -163
View File
@@ -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 `<datadir>/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, `<datadir>/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 `<datadir>/mcp/out/OrcaSlicer-screenshot-<timestamp>.png`. The image
views leaves them out. The full-size PNG goes to `save_path` or `OrcaSlicer-screenshot-<timestamp>.png` in the output
folder (`output_dir()`: the `--outputdir` of a `--run` launch, else `<datadir>/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 `<replay name>.out` beside it. An inline replay's defaults to
`<datadir>/mcp/out/replay-<timestamp>`, which is also its `${replay_dir}`.
`replay-<timestamp>` 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 `<replay name>.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 `<replay name>.out` next to the replay, and `output_dir()` is
`<datadir>/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 `<run_script>`, 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 `<datadir>/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`.
+5 -4
View File
@@ -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
+30 -21
View File
@@ -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 <replay name>.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"
@@ -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;
+1 -1
View File
@@ -922,7 +922,7 @@ function HandleStudio(msg) {
applyScript(msg.script || { none: true });
renderRecent();
break;
case "service":
case "runtime":
S.ready = !!msg.ready;
render();
break;
@@ -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
+2
View File
@@ -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)
+23 -7
View File
@@ -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<ConfigOptionBool>("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<ConfigOptionInt>("mcp_port"))
params.mcp.port = opt->value;
if (const auto *opt = m_config.opt<ConfigOptionString>("mcp_token"))
params.mcp.token = opt->value;
// Resolved now: the GUI moves the working directory to <data_dir>/log before the replay or script runs.
if (const auto *opt = m_config.opt<ConfigOptionString>("mcp_run"))
params.mcp.run_file = resolve_cli_input_path(opt->value);
if (const auto *opt = m_config.opt<ConfigOptionString>("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);
+18 -20
View File
@@ -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 <replay name>.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());
+69
View File
@@ -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 ()
+9 -33
View File
@@ -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.
+15
View File
@@ -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:<key>:orca" (NativeCommands::make_action()).
inline constexpr const char* kCommandPrefix = "orca_command";
}} // namespace Slic3r::GUI
+1
View File
@@ -1,5 +1,6 @@
#include "ActionRegistry.hpp"
#include "ActionIds.hpp"
#include "CommandCatalog.hpp"
#include "GUI.hpp"
#include "GUI_App.hpp"
-8
View File
@@ -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:<key>: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)
+23 -29
View File
@@ -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)
+4 -4
View File
@@ -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);
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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 <wx/string.h>
#include <wx/textctrl.h>
#include <wx/event.h>
+6 -5
View File
@@ -1,6 +1,7 @@
#include "CommandCatalog.hpp"
#include "Mcp/McpTypes.hpp"
#include "CommandTypes.hpp"
#include "Mcp/McpArguments.hpp"
#include <nlohmann/json.hpp>
@@ -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";
}
+6 -6
View File
@@ -1,6 +1,6 @@
#pragma once
#include "Mcp/McpTypes.hpp"
#include "CommandTypes.hpp"
#include <nlohmann/json.hpp>
@@ -11,8 +11,8 @@
#include <unordered_map>
#include <vector>
// 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<Mcp::ToolResult(const nlohmann::json& args, Mcp::ToolContext& ctx)>;
using CommandFn = std::function<ToolResult(const nlohmann::json& args, ToolContext& ctx)>;
// 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
+138
View File
@@ -0,0 +1,138 @@
#pragma once
#include <nlohmann/json.hpp>
#include <cstdint>
#include <functional>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// 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<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 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<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 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<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;
}
};
// 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
+1 -1
View File
@@ -11,7 +11,7 @@
#include <wx/gdicmn.h>
#include <wx/sizer.h>
#include "slic3r/GUI/Widgets/TextInput.hpp"
#include "slic3r/GUI/Mcp/McpTypes.hpp"
#include "slic3r/GUI/Mcp/WindowNames.hpp"
#include <wx/event.h>
#include <string>
#include "slic3r/GUI/wxExtensions.hpp"
+109 -88
View File
@@ -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<wxTimer>();
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<Mcp::McpEndpoint>(*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)
+38 -24
View File
@@ -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<void(int status, int percent, bool& cancel)> InstallProgressFn;
@@ -386,10 +389,11 @@ private:
bool m_show_error_msgdlg{false};
wxString m_info_dialog_content;
std::unique_ptr<HttpServer> 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<Mcp::McpEndpoint> m_mcp_endpoint;
std::unique_ptr<RunScriptPanel> m_run_script_panel;
bool m_mcp_wanted = false; // the endpoint should be open: --mcp, the preference, or Preferences
std::unique_ptr<wxTimer> 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(); }
+5 -4
View File
@@ -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 &params)
//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 &params)
} 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) {
+3
View File
@@ -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 &params);
+6 -6
View File
@@ -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;
+3 -1
View File
@@ -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()) {
+2 -1
View File
@@ -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
+8 -9
View File
@@ -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();
+581
View File
@@ -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 <boost/log/trivial.hpp>
#include <wx/app.h>
#include <wx/event.h>
#include <wx/thread.h>
#include <wx/timer.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace Slic3r { namespace GUI { namespace Mcp {
using nlohmann::json;
namespace {
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; }
} // 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<WxDispatcher>();
m_modals = std::make_unique<ModalTracker>();
m_recorder = std::make_unique<McpRecorder>(*m_modals, [this] { return m_generation.load(); }, [this] { return m_suspended.load(); },
[this](std::function<void()> 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<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) {
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<McpCore>(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<WebPresses>();
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<UiInspector>(*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<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();
}
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<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
return m_core->drain(std::max(left, std::chrono::milliseconds(0)));
}
AutoAnswerSet AutomationRuntime::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 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<std::mutex> lock(m_rules_mutex);
m_run_rule_layers.emplace(job, std::vector<int>{});
}
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<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 AutomationRuntime::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 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<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 AutomationRuntime::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 AutomationRuntime::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 AutomationRuntime::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);
}
void AutomationRuntime::open_client_scope()
{
std::lock_guard<std::mutex> lock(m_rules_mutex);
m_client_scope_open = true;
}
bool AutomationRuntime::client_scope_open() const
{
std::lock_guard<std::mutex> 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<std::mutex> 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<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) << "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<void()>& fn : std::exchange(m_on_ready, {}))
fn();
}
void AutomationRuntime::on_ready(std::function<void()> fn)
{
if (m_ready)
fn();
else
m_on_ready.push_back(std::move(fn));
}
void AutomationRuntime::post_ui(std::function<void()> 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<void()> 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<ToolResult> 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<ToolResult> 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::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;
}
}}} // namespace Slic3r::GUI::Mcp
+227
View File
@@ -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 <nlohmann/json.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <vector>
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<bool(nlohmann::json& args)> 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<void(const std::optional<ToolResult>&)> ended;
// Asks the call to end early. stop_followed() calls it while the call has not ended. Optional.
std::function<void()> 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<void()> 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<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 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<void()> 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<ToolResult> call_to_end(const NativeCommand& command, const nlohmann::json& args, bool person);
void set_ready();
GuardState guards_on_ui() const;
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;
// Null until enable_gui_instruments(). UI thread.
std::unique_ptr<UiInspector> m_inspector;
// Made by start(). Shared with the page calls that release its presses, whose replies may come after the runtime.
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_client_scope_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::vector<std::function<void()>> m_on_ready; // UI thread
std::set<std::string> 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
@@ -0,0 +1,19 @@
#pragma once
#include <memory>
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<AutomationRuntime, AutomationRuntimeDeleter>;
}}} // namespace Slic3r::GUI::Mcp
+88
View File
@@ -0,0 +1,88 @@
#include "FollowedThreads.hpp"
#include <atomic>
#include <cstddef>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
namespace Slic3r { namespace GUI { namespace Mcp {
FollowedThreads::~FollowedThreads() { join_all(); }
bool FollowedThreads::start(std::function<void()> work, std::function<void()> stop)
{
std::lock_guard<std::mutex> 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<std::atomic<bool>>(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<std::function<void()>> stops;
{
std::lock_guard<std::mutex> 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<void()>& stop : stops)
stop();
}
void FollowedThreads::join_all()
{
std::list<Followed> joining;
{
std::lock_guard<std::mutex> 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<std::mutex> lock(m_mutex);
m_joining -= joining.size();
}
std::size_t FollowedThreads::size() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_threads.size() + m_joining;
}
}}} // namespace Slic3r::GUI::Mcp
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <thread>
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<void()> work, std::function<void()> 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<std::atomic<bool>> returned;
std::function<void()> stop;
};
mutable std::mutex m_mutex;
std::list<Followed> 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
+30 -4
View File
@@ -1,5 +1,5 @@
#include "JobRegistry.hpp"
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <algorithm>
#include <chrono>
@@ -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<std::mutex> 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<std::mutex> 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<ToolResult> JobRegistry::wait(const std::string& id, std::chrono::
}
}
bool JobRegistry::person_in(const std::set<std::string>& lineage) const
{
std::lock_guard<std::mutex> 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<std::mutex> 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<std::string>& lineage) const
{
std::lock_guard<std::mutex> 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<std::mutex> lock(m_mutex);
+17 -7
View File
@@ -1,6 +1,6 @@
#pragma once
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <nlohmann/json.hpp>
@@ -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<std::string>& 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<std::string>& 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;
};
+138
View File
@@ -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 <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/log/trivial.hpp>
#include <boost/nowide/fstream.hpp>
#include <nlohmann/json.hpp>
#include <wx/app.h>
#include <atomic>
#include <exception>
#include <ios>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
namespace Slic3r { namespace GUI { namespace Mcp {
using nlohmann::json;
namespace {
std::atomic<int> 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<ToolResult>& 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
+16
View File
@@ -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
+2 -2
View File
@@ -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"
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include "slic3r/GUI/CommandCatalog.hpp"
#include <nlohmann/json.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
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<const NativeCommand>& 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<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
+19 -17
View File
@@ -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 <algorithm>
#include <chrono>
@@ -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<void(const ToolResult&)> 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<void(const ToolResult&)>& done, ToolResult& refused)
bool person, uint64_t seq, uint64_t call, const std::function<void(const ToolResult&)>& 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));
+18 -14
View File
@@ -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 <nlohmann/json.hpp>
@@ -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<void(const ToolResult&)> 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<void(const ToolResult&)>& done, ToolResult& refused);
bool person, uint64_t seq, uint64_t call, const std::function<void(const ToolResult&)>& 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<uint64_t> m_next_call{1};
// The job whose call started the worker's current job, and whether a cancel was asked for it.
+244
View File
@@ -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 <boost/log/trivial.hpp>
#include <boost/nowide/cstdlib.hpp>
#include <wx/event.h>
#include <wx/timer.h>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#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 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<void(const std::string&)> 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<wxTimer>();
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<McpProtocol>(NativeCommands::instance(), m_runtime.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);
});
// 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<std::mutex> 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
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <nlohmann/json.hpp>
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
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<void(const std::string&)> 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<void(const std::string&)> 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<McpProtocol> m_protocol;
std::shared_ptr<RequestGate> m_gate;
std::unique_ptr<McpHttpServer> 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<wxTimer> m_retry_timer;
};
}}} // namespace Slic3r::GUI::Mcp
+2 -2
View File
@@ -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 <boost/filesystem/path.hpp>
+1 -2
View File
@@ -1,8 +1,7 @@
#pragma once
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandCatalog.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <nlohmann/json.hpp>
+8 -8
View File
@@ -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
+22 -2
View File
@@ -1,5 +1,4 @@
#include "McpPaths.hpp"
#include "McpToken.hpp"
#include "libslic3r/Utils.hpp"
@@ -11,6 +10,7 @@
#include <algorithm>
#include <cstddef>
#include <ctime>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
@@ -154,14 +154,34 @@ std::optional<fs::path> 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<std::mutex> 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<std::mutex> 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<std::string>& companions,
std::time_t when)
{
+4 -2
View File
@@ -30,9 +30,11 @@ std::optional<boost::filesystem::path> resolve_output_path(const std::string& pa
// An existing directory (multi-file exports).
std::optional<boost::filesystem::path> resolve_output_dir(const std::string& path, std::string& err);
// Where screenshots, recordings and replay outputs go when no path is given: <datadir>/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 <datadir>/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-<kind>-YYYYMMDD-HHMMSS<extension>" 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
+11 -13
View File
@@ -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<GUI_App*>(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<const NativeCommand> 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<std::optional<ToolResult>>();
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<std::optional<ToolResult>>();
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;
+15 -13
View File
@@ -1,6 +1,6 @@
#pragma once
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <nlohmann/json.hpp>
@@ -11,19 +11,21 @@
#include <utility>
// 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: <title>", 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); }
+65 -9
View File
@@ -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
+28 -16
View File
@@ -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
+25 -21
View File
@@ -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";
+10
View File
@@ -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
+2 -1
View File
@@ -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>
+4 -2
View File
@@ -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
+56 -18
View File
@@ -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();
}
+19 -6
View File
@@ -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
+1 -1
View File
@@ -1,6 +1,6 @@
#include "McpReplay.hpp"
#include "McpPaths.hpp"
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <algorithm>
#include <chrono>
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <boost/filesystem/path.hpp>
#include <nlohmann/json.hpp>
+14 -14
View File
@@ -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();
}
+9 -6
View File
@@ -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}
+70
View File
@@ -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
File diff suppressed because it is too large. Load diff
-298
View File
@@ -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
-19
View File
@@ -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
+10 -8
View File
@@ -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);
+8 -4
View File
@@ -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
+24 -7
View File
@@ -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`
+3 -1
View File
@@ -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"
+2 -1
View File
@@ -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"
+28 -23
View File
@@ -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()}});
+11 -8
View File
@@ -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)
{
+1 -1
View File
@@ -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>
+1 -1
View File
@@ -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"
+2 -1
View File
@@ -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"
+1 -1
View File
@@ -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"
+9 -8
View File
@@ -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)
+91 -36
View File
@@ -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);
+28 -16
View File
@@ -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")) {
+19 -18
View File
@@ -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));
});
+11 -10
View File
@@ -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.
+166 -165
View File
@@ -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.
+11 -11
View File
@@ -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);
-212
View File
@@ -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
+2 -1
View File
@@ -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"
+30 -7
View File
@@ -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);
+11 -6
View File
@@ -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
+1 -1
View File
@@ -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"
+22 -22
View File
@@ -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;
+9 -4
View File
@@ -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);
+1 -1
View File
@@ -1,4 +1,4 @@
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include "UiInvoker.hpp"
#include <algorithm>
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <nlohmann/json.hpp>
+1 -1
View File
@@ -1,6 +1,6 @@
#include "UiRefs.hpp"
#include "McpTypes.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include <nlohmann/json.hpp>
+3 -1
View File
@@ -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");
+2 -1
View File
@@ -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>
+6 -3
View File
@@ -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
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more