mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-25 23:01:09 -05:00
Add the Agent Activity pane
A new pane, opened from View > Agent Activity or the Speed Dial, lists live what an AI agent and other automation (Action Replay, Run Script, the command line, plugins) do in OrcaSlicer while it is open: each call with its source, what it changed, failures with their reason, the steps of a run and the dialogs a rule answered. Opening a call shows its request and response with passwords, keys and typed text masked, so a person can watch and check what an agent is doing to their project.
This commit is contained in:
1 parent
eae8929b41
commit
5eefef82fc
71 files changed
+5320
-413
No files matched your search
+119
-4
@@ -63,7 +63,8 @@ application/json` (415) and the size cap (413). No CORS headers are sent, so bro
|
||||
`McpProtocol` picks one of two protocol eras for each message.
|
||||
|
||||
- **Handshake era.** `initialize` echoes the client's version if it is 2025-11-25 or 2025-06-18,
|
||||
and answers 2025-11-25 otherwise. Then come `notifications/initialized`, `ping`, `tools/list`
|
||||
and answers 2025-11-25 otherwise; the name it gives (`clientInfo.name`) names its calls in the Agent Activity
|
||||
pane. Then come `notifications/initialized`, `ping`, `tools/list`
|
||||
and `tools/call`. A present `MCP-Protocol-Version` header must be supported (400).
|
||||
- **2026-07-28.** A request whose `params._meta` carries
|
||||
`io.modelcontextprotocol/protocolVersion` is served without a handshake. `server/discover`
|
||||
@@ -2404,7 +2405,7 @@ key, whatever its command is named), its title, its Speed Dial section (the item
|
||||
come from several sections: `export_gcode` is in Slice & Export, `export_stl_multi` in Export), its icon and
|
||||
the value its second phase collects (`input`). A person's pins and run counts are stored under the id, so the
|
||||
ids of the menu items a released build stored stay the ids of actions. `tests/data/speed_dial_actions.json`
|
||||
holds the 129 actions (key, title, section, icon, input), and the unit test "every Speed Dial action of today
|
||||
holds the 130 actions (key, title, section, icon, input), and the unit test "every Speed Dial action of today
|
||||
is still a command's action" finds each in the Speed Dial with that presentation and no other; "a menu item's id
|
||||
is an action's key, not a command" holds that no menu item's id is a command's name.
|
||||
|
||||
@@ -3861,7 +3862,8 @@ is in neither. Recordings and screenshots show it as the person sees it, since c
|
||||
shows, so its pulsing dot is in the frames and a recording never sees an idle window: each frame in which the
|
||||
dot changed is queued.
|
||||
|
||||
**Captions.** `McpCore` reports each call it runs to a `CallObserver`: when its handler starts, when
|
||||
**Captions.** `McpCore` reports each call it runs to its `CallObserver`s, the recorder and the activity log
|
||||
(see Agent Activity pane): when its handler starts, when
|
||||
`set_journal_args()` replaces its arguments (refs become locators), and its final result (a job's,
|
||||
worker job included). Calls refused before they run are not reported. The recorder captions calls
|
||||
that are not `Inspect` (mutate and recover tools, replay steps included) as the tool's translated
|
||||
@@ -4686,6 +4688,119 @@ doing. `tool_call {tool, args}` runs any command of the catalog, listed or not,
|
||||
arguments are normalized and validated, and the call runs as the target's own, with its guard, mode, budget and
|
||||
journal flag, so the journal records the target.
|
||||
|
||||
## Agent Activity pane
|
||||
|
||||
View › Agent Activity, a check item that is on while the pane is on screen, its Speed Dial action
|
||||
`toggle_agent_activity_panel` and the command `view_toggle_activity_panel`, which the tool list does not show, show or
|
||||
hide the Agent Activity pane (`AgentActivityPanel`, page `resources/web/dialog/AgentActivity/`). While it is open, it
|
||||
lists, live, every call automation makes in the app, reads included: an agent's, a run's from Action Replay, the Run Script panel or the
|
||||
command line (`--run`), and a plugin's, with the dialogs auto-answer rules answered and the agent's calls the protocol
|
||||
refused before they ran. A person's own picks from the Speed Dial and the menus are left out, with what they run. The
|
||||
pane only watches: it stops, pauses and exports nothing, and it opens only when a person opens it.
|
||||
|
||||
**Origins.** Each call into the core says who made it, and `CallObserver::call_started()` gets that with the call's
|
||||
own job: `McpCore::call()` and `call_person()` take an origin, a JSON object whose `source` is `agent`,
|
||||
`action_replay`, `run_script`, `command_line`, `plugin` or `person`. The protocol gives an agent's: `client`, the name
|
||||
of the handshakes it answered while only one name has come since it was made, else empty (shown as "Agent"), since
|
||||
two clients' calls can't be told apart over stateless HTTP, and a 2026-07-28 call has no handshake; and `request`, the
|
||||
JSON-RPC message as it came, so a `tool_call` shows the wrapper and the command it names. The runtime's followed calls
|
||||
carry their front end's (`FollowedCall::origin`): Action Replay's runs, the Run Script panel's session, `--run`, and a
|
||||
person's recording's encode as the person's. `call_plugin()` gives `plugin` with the plugin's key, and `submit()`, a
|
||||
person's pick, `person`. A child call has none: its parent's job says where it comes from. A recording's encode that
|
||||
`recording_stop` starts names the stop's job as `under`, and is listed with the stop. The core tells each of its
|
||||
observers in turn. A call that runs as a job is also told as it is queued (`call_queued()`), on the thread that made
|
||||
it, right after its job is registered and before its thread starts: its parent, or the call it is `under`, still runs
|
||||
then. Every queued call is later ended, also one whose thread can't start or whose plugin unloaded before its handler.
|
||||
|
||||
**The log.** `ActivityLog` (no wx) is an observer the runtime makes as it starts. It lists only while it records
|
||||
(`set_recording()`), which the pane turns on while the person has it open: docked while another tab is up and across a
|
||||
main-window rebuild too, off as they hide or close it and as the panel goes at exit. Nothing that comes while it is off
|
||||
is listed, but what it already lists still ends, the list stays until Clear list, and the log keeps what placing and
|
||||
masking later entries needs: the marks and the masking records below. An entry is a call, a dialog a rule answered, or a
|
||||
work of the Run Script panel, with its source and label, tool, arguments, request (an agent's message, else
|
||||
`{tool, args}` as the app runs the call), response (the final result's data, or `{isError, message, details}`; a job's
|
||||
once it ends), status, error, times, job and the entry it nests under. A replay whose step failed and a script that
|
||||
did not finish report success to their caller; the log reads their result and fails them, with the script's exception
|
||||
as the error, or else a `failure` the pane words in the UI's language: the failed step's number and error, or how the
|
||||
script ended (stopped, out of time, Python unavailable, not run), whose runner message is agent-facing English. A Run
|
||||
Script work's end reads the same way. It is numbered as Action Replay numbers its steps: the top-level calls and works count up, the entries
|
||||
under a run from 1, and a dialog takes no number. Every job call, listed or not, leaves marks by its job, set as it is
|
||||
queued and dropped as it ends: its run's source, client and plugin, or that it is a person's pick or a Run Script
|
||||
session. A child job copies its nearest marked ancestor's, which still runs then, so a run that outlives its parent keeps
|
||||
them. A child call nests under the nearest of its parent jobs that has an entry (`JobRegistry::ancestry()`), past any
|
||||
that has none; with no such job, its marks place it: a run that started before the pane opened lists its later calls at
|
||||
the top level under its own source, and a person's pick's calls stay out however late they come. A Run Script session
|
||||
has no entry of its own: each work the panel runs in it is one, which the panel reports as it submits the work
|
||||
(`work_started()`, the code its request) and as it ends (`work_ended()`: the Finished event's result or error, or a
|
||||
stop when its session ends without one or the panel lets the session go). A call the session makes goes under the work
|
||||
running at the time, or at the top level between works.
|
||||
|
||||
The protocol reports a `tools/call` it refuses before the core sees it, for an unknown tool, arguments the schema
|
||||
refuses or a `tool_call` it can't resolve (`McpProtocol::set_on_refused()`), and the endpoint hands it to the log as a
|
||||
failed entry. Calls the core refuses (admission, blocking slots) are not reported, as they aren't to the recorder.
|
||||
`ModalTracker` reports each answer a rule gives (`set_on_answered()`, wherever a rule's `uses` grows) with the rule's
|
||||
layer; the runtime finds the run, plugin or client whose layer it is, and the log places the dialog's entry there. Each
|
||||
`dialog_auto_answer` call puts its rules in a layer of their own, which no later call changes (a client's next call
|
||||
replaces the layer). The runtime tells the log the layer and the call's job while it still holds the rules lock that an
|
||||
answer's report takes first (`rules_set()`), so no answer comes before it: an answer links the call that set its
|
||||
rules, and none when that call isn't listed, made while the log didn't record or dropped since. A client's answer
|
||||
carries the client of the call that set the rule. The log keeps a layer while its call is listed, and the latest others,
|
||||
up to 4000 layers in all.
|
||||
|
||||
Arguments, requests, responses and errors are masked as captions are: `hidden_values()` gives what `caption_detail()`
|
||||
leaves out of a call (sensitive values, typed text, a value set into a field not found by its key, a page's
|
||||
JavaScript), and `mask_hidden()` replaces it, and every member of a sensitive key, by `•••`, inside longer text only
|
||||
from three characters on. A string that is JSON text (a replay given as its text) is read as JSON and, when that masks
|
||||
something, written out again masked, so what the text escapes is masked too. What nests arrays and objects deeper than
|
||||
64 levels, a payload or JSON text in one, is neither read nor shown (`•••`), since masking recurses through what it
|
||||
reads and nlohmann's copy recurses too, so the depth is checked before anything is copied; a job call whose arguments or
|
||||
result nest deeper has no masking record, and a call whose own arguments do shows no result, nor a dialog answered
|
||||
while it runs. A run whose result nests deeper is still failed when the fields that tell its outcome say so, which are
|
||||
read without going down the deep branches, but the pane words the failure without its reason. A replay hides what each
|
||||
of its steps hides, as written and with its placeholders put in by the replay engine's own substitution
|
||||
(`substitute_args_lenient()`, which leaves Python source as written, as a run does), and each value a placeholder in a
|
||||
hidden value puts in, directly or through another placeholder (a variable, an environment variable), with every string
|
||||
and number inside one that is an object or an array; the log has no saved jobs or folders, whose placeholders put in
|
||||
nothing secret. Variables that put each other in grow as the power of the nesting, so the log puts in at most 1 MiB for
|
||||
the replays written in one call and keeps the rest as written: what that cuts short only shows whole in a payload over
|
||||
32 KiB, which is shown by its size. A call
|
||||
that names a job (`app_wait`,
|
||||
`job_cancel`) also hides what that job's call hid, as the call ends. Every job call, listed or not, has a masking record
|
||||
from when it starts: what its arguments, their rewrite and its result hide, kept for the last 2000 job calls within
|
||||
4 MiB. A value longer than 32 KiB drops its record, since a shortened error could show part of it. A call naming a job
|
||||
with no record as it ends is `withheld`: it shows neither its response nor its error text, which may repeat that job's
|
||||
secrets. A dialog's title and message hide what the calls running as it is answered hide, also the start of a value a
|
||||
message ends in where `ModalTracker` cut it (from three bytes on, as written and escaped); past 10 000 such values or
|
||||
1 MiB of them, which would hold up the UI thread that reports the answer, the title and message are not shown. A
|
||||
payload over 32 KiB as JSON is `{truncated: true, bytes}`, unmasked since it shows nothing, and one, or an error, whose
|
||||
check would scan more than 256 MiB (values × length) is `•••`. The log keeps 2000 entries, dropping the oldest whose calls have all ended, with what is
|
||||
nested under them. Each change moves a version on: `changes_since()` gives the entries changed since a version and the
|
||||
ids dropped, or every entry with `reset` when the reader is too far behind or Clear list has run (`clear()`, which
|
||||
keeps what still runs and the masking records, and numbers from 1 again once nothing is left). The log
|
||||
calls its `changed` hook once until the next read, which the runtime posts to the UI thread for the pane, so nothing
|
||||
runs for it while no pane reads it. What an observer throws, the core drops, so the log never fails a call.
|
||||
|
||||
**The pane.** A Plater dock pane, docked on the right of the 3D view at first (420 × 640 DIPs) and kept where the
|
||||
person moves it by the saved layout; its close button hides it. Docked it shows on Prepare and Preview, and showing it
|
||||
from another tab selects Prepare; floated it stays up on every tab, the Design tab included
|
||||
(`add_dock_pane(..., floats_on_every_tab)`). `GUI_App` owns `AgentActivityPanel`, which builds the pane again after a
|
||||
main-window rebuild, as the Run Script panel does. While the pane is on screen it reads the log's changes at most ten
|
||||
times a second and words them on the UI thread for its page: a call's translated title and target as the recording
|
||||
captions word them (`shown_title()`, `caption_detail()`), the source's label (the agent's name or "Agent", Action
|
||||
Replay, Run Script, Command line, the plugin's name), the effect tags Action Replay shows (`describe_step()`), and a
|
||||
screenshot's thumbnail. The page draws the rail Action Replay draws its steps with (`css/step_rail.css`): a read is a
|
||||
quiet line with a hollow dot, a change a filled one, a failure red with its reason, a running call a ringing dot with
|
||||
its job; a run and a Run Script work hold their own steps, shown while they run or once opened. An opened step shows
|
||||
its request and its response as JSON, laid out as the Run Script console lays out a result, with Copy, which the host
|
||||
puts on the clipboard. Everything, Changes or Failures, a source and Find a call filter the list. It follows the
|
||||
newest call until the person scrolls up, and then counts the calls that came below.
|
||||
|
||||
**Out of the tools' reach.** As the Run Script panel's, the pane is named `kHiddenFromAutomation`, as is the frame it
|
||||
floats in (`AuiMgr::CreateFloatingFrame()`): `skipped_by_walks()` keeps the walks of `widget_list`, locators and
|
||||
`webview_run_javascript`'s search for a web view out of it, and `window_list` lists the floating frame as hidden, with
|
||||
no ref. Its page navigates nowhere but its own loads. Docked, the pane is part of the main window and shows in its
|
||||
screenshots and recordings; floating, it stays out of them, as the person's own dialogs do.
|
||||
|
||||
## stdio bridge
|
||||
|
||||
`orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]` serves clients that speak only stdio,
|
||||
@@ -4829,7 +4944,7 @@ In `tests/slic3rutils/`, the files of the same name hold the cases that need the
|
||||
`test_mcp_core` a context with no runtime and an action'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 commands in their places' groups in the tool list's order,
|
||||
which are listed, the Speed Dial's 129 actions held as data in `tests/data/speed_dial_actions.json` (tagged
|
||||
which are listed, the Speed Dial's 130 actions held as data in `tests/data/speed_dial_actions.json` (tagged
|
||||
`[SpeedDial]`: each found with its id, title, section, icon and input, every menu item's id an action's key and
|
||||
no command, every action's arguments fitting its command's schema), the person's forms of the commands with
|
||||
actions and what a pick of an action runs in place, the names of `retired_names.hpp`, which no command has, the
|
||||
|
||||
@@ -128,6 +128,7 @@ src/slic3r/GUI/Jobs/UpgradeNetworkJob.cpp
|
||||
src/slic3r/GUI/AboutDialog.cpp
|
||||
src/slic3r/GUI/ActionRegistry.cpp
|
||||
src/slic3r/GUI/ActionReplayDialog.cpp
|
||||
src/slic3r/GUI/AgentActivityPanel.cpp
|
||||
src/slic3r/GUI/AMSMaterialsSetting.cpp
|
||||
src/slic3r/GUI/ExtrusionCalibration.cpp
|
||||
src/slic3r/GUI/AmsMappingPopup.cpp
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
<title>Action Replay</title>
|
||||
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../js/code_editor.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../css/step_rail.css" />
|
||||
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||
<script type="text/javascript" src="../../include/i18n.js"></script>
|
||||
<script type="text/javascript" src="../js/globalapi.js"></script>
|
||||
|
||||
@@ -1,29 +1,14 @@
|
||||
/* Action Replay. Colours come from the host theme contract (--orca-*) and theme.css's status roles,
|
||||
* so the page follows the app in light and dark. The one distinctive element is the step rail: an
|
||||
* accent thread that fills down the list as steps pass. Everything else stays quiet and host-native. */
|
||||
* so the page follows the app in light and dark. The one distinctive element is the step rail
|
||||
* (../css/step_rail.css): an accent thread that fills down the list as steps pass. Everything else
|
||||
* stays quiet and host-native. */
|
||||
|
||||
:root {
|
||||
--sr-bg: var(--orca-bg, #ffffff);
|
||||
--sr-fg: var(--orca-fg, #262e30);
|
||||
--sr-muted: var(--orca-muted, #6b7478);
|
||||
--sr-rule: var(--border, #dcdfe1);
|
||||
--sr-accent: var(--orca-accent, #009688);
|
||||
--sr-accent-fg: var(--orca-accent-fg, #ffffff);
|
||||
--sr-pass: var(--plugin-status-ok, #137333);
|
||||
--sr-fail: var(--plugin-status-danger, #b42318);
|
||||
--sr-fail-bg: var(--plugin-status-danger-bg, rgba(180, 35, 24, 0.12));
|
||||
--sr-warn: var(--plugin-status-warn, #a15c00);
|
||||
--sr-warn-bg: var(--plugin-status-warn-bg, rgba(199, 122, 22, 0.12));
|
||||
--sr-hover: var(--row-hover, #f7f9fb);
|
||||
--sr-footer: var(--footer-bg, #fafafa);
|
||||
--sr-btn-bg: var(--btn-bg, #ffffff);
|
||||
--sr-btn-border: var(--btn-border, #cccccc);
|
||||
--sr-btn-hover: var(--btn-hover, #f0f0f0);
|
||||
--sr-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
--sr-ring: rgba(0, 150, 136, 0.25);
|
||||
--sr-ring-soft: rgba(0, 150, 136, 0.1);
|
||||
--sr-mono: var(--code-font);
|
||||
--sr-dot: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -151,85 +136,11 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accen
|
||||
/* ---- no steps yet ---- */
|
||||
.steps-hint { margin: 0; padding: 12px 14px; color: var(--sr-muted); }
|
||||
|
||||
/* ---- the step rail ---- */
|
||||
.rail { list-style: none; margin: 0; padding: 6px 0 10px; }
|
||||
/* ---- the step rail: what only Action Replay's steps have ---- */
|
||||
/* The last steps that parsed, kept while the text doesn't, so typing doesn't empty the list. */
|
||||
.rail.is-stale { opacity: 0.45; }
|
||||
.step {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: var(--sr-dot) minmax(0, 1fr) auto;
|
||||
column-gap: 10px;
|
||||
padding: 0 12px 0 14px;
|
||||
}
|
||||
/* The thread from this step's dot down to the next one; it takes the accent once the step passed. */
|
||||
.step::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: calc(14px + var(--sr-dot) / 2 - 1px);
|
||||
top: calc(6px + var(--sr-dot));
|
||||
bottom: -6px;
|
||||
width: 2px;
|
||||
background: var(--sr-rule);
|
||||
transition: background-color 240ms ease;
|
||||
}
|
||||
.step:last-child::before { display: none; }
|
||||
.step.is-done::before, .step.is-warn::before { background: var(--sr-accent); }
|
||||
.dot {
|
||||
margin-top: 6px;
|
||||
width: var(--sr-dot);
|
||||
height: var(--sr-dot);
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--sr-rule);
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.step.is-done .dot { background: var(--sr-accent); border-color: var(--sr-accent); color: var(--sr-accent-fg); }
|
||||
.step.is-warn .dot { background: var(--sr-warn); border-color: var(--sr-warn); color: #ffffff; }
|
||||
.step.is-fail .dot, .step.is-stopped .dot { background: var(--sr-fail); border-color: var(--sr-fail); color: #ffffff; }
|
||||
.step.is-skip .dot { border-style: dashed; }
|
||||
.step.is-running .dot { border-color: var(--sr-accent); color: var(--sr-accent); animation: sr-ring 1.4s ease-in-out infinite; }
|
||||
@keyframes sr-ring {
|
||||
0%, 100% { box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
50% { box-shadow: 0 0 0 5px var(--sr-ring-soft); }
|
||||
}
|
||||
|
||||
.step-main { min-width: 0; }
|
||||
.step-head {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 6px 4px 6px 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.step-title { font-weight: 600; }
|
||||
.step.is-wait .step-title, .step.is-skip .step-title { font-weight: 400; color: var(--sr-muted); }
|
||||
.step-what, .step-args { display: block; color: var(--sr-muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.step-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
padding: 0 6px;
|
||||
border-radius: 3px;
|
||||
color: var(--sr-warn);
|
||||
background: var(--sr-warn-bg);
|
||||
}
|
||||
.tag.is-check { color: var(--sr-muted); background: none; border: 1px solid var(--sr-rule); }
|
||||
|
||||
.step-side { display: flex; align-items: flex-start; gap: 6px; padding-top: 7px; }
|
||||
.time { font-size: 12px; color: var(--sr-muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.step.is-running .time { color: var(--sr-accent); }
|
||||
.play {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
@@ -244,48 +155,12 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accen
|
||||
opacity: 0;
|
||||
}
|
||||
.step:hover .play:not(:disabled), .play:focus-visible { opacity: 1; border-color: var(--sr-rule); }
|
||||
|
||||
/* ---- an opened step ---- */
|
||||
.step-detail { padding: 2px 0 10px; font-size: 12px; }
|
||||
.step.is-open { background: var(--sr-hover); }
|
||||
.args { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 12px; margin: 0 0 6px; }
|
||||
.args dt { color: var(--sr-muted); }
|
||||
.args dd { margin: 0; font-family: var(--sr-mono); font-size: 11.5px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.result-line { margin: 2px 0; }
|
||||
.checks { list-style: none; margin: 0 0 6px; padding: 0; color: var(--sr-muted); }
|
||||
.checks li { margin: 2px 0; overflow-wrap: anywhere; }
|
||||
.checks li.is-met::before { content: "\2713\00a0"; color: var(--sr-pass); }
|
||||
.failure {
|
||||
margin: 4px 0 6px;
|
||||
padding: 6px 8px;
|
||||
border-left: 2px solid var(--sr-fail);
|
||||
border-radius: 0 3px 3px 0;
|
||||
background: var(--sr-fail-bg);
|
||||
}
|
||||
.step.is-warn .failure { border-left-color: var(--sr-warn); background: var(--sr-warn-bg); }
|
||||
.failure-detail { display: block; margin-top: 3px; color: var(--sr-muted); overflow-wrap: anywhere; }
|
||||
.files { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 4px 0; }
|
||||
.thumb {
|
||||
display: block;
|
||||
width: 160px;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.actions { display: flex; gap: 12px; align-items: center; margin-top: 6px; }
|
||||
.raw {
|
||||
margin: 6px 0 0;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
font-family: var(--sr-mono);
|
||||
font-size: 11px;
|
||||
white-space: pre;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
/* ---- source editor ----
|
||||
* Ace (../js/code_editor.js), filling the section; code_editor.css colours what is inside it. */
|
||||
@@ -320,6 +195,5 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accen
|
||||
.outcome-detail { font-size: 12px; color: var(--sr-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.step.is-running .dot { animation: none; box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
.step::before, .chevron { transition: none; }
|
||||
.chevron { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
// The Agent Activity pane's page. The host (AgentActivityPanel) sends the activity log's entries as they change, with
|
||||
// their titles, targets and source labels in the UI's language; this page draws them as a step rail, filters them, and
|
||||
// asks the host to clear the list or copy a request or response.
|
||||
|
||||
const M = AgentActivityModel;
|
||||
const MASK = "\u2022\u2022\u2022";
|
||||
|
||||
const S = {
|
||||
store: M.createStore(),
|
||||
open: new Set(), // the entries the person opened
|
||||
show: "all", // all | changes | failures
|
||||
source: "all", // a sourceKey(), or all
|
||||
find: "",
|
||||
following: true, // the list follows the newest call until the person scrolls up
|
||||
newBelow: 0, // calls that came while the person read further up
|
||||
tree: { top: [], children: new Map() },
|
||||
};
|
||||
const rows = new Map(); // entry id -> its <li>
|
||||
|
||||
const ICON = {
|
||||
agent: '<svg viewBox="0 0 16 16"><path d="M8 1.5c.5 3.2 1.8 5 5.5 6.5-3.7 1.5-5 3.3-5.5 6.5-.5-3.2-1.8-5-5.5-6.5C6.2 6.5 7.5 4.7 8 1.5z" fill="currentColor"/></svg>',
|
||||
action_replay: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3.4 8.6A4.7 4.7 0 1 0 5 4.4"/><path d="M2.8 2.2v3.3h3.3"/></svg>',
|
||||
run_script: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="2.5" width="13" height="11" rx="2"/><path d="M4.5 6.5 6.5 8l-2 1.5M8.2 10h3.3"/></svg>',
|
||||
command_line: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 4.5 6 8l-3.5 3.5M7.5 12h6"/></svg>',
|
||||
plugin: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"><path d="M6.2 2.6a1.6 1.6 0 0 1 3.2 0V4h3.1v3.1h-1.3a1.6 1.6 0 0 0 0 3.2h1.3v3.2H3.3v-3.2h1.2a1.6 1.6 0 0 0 0-3.2H3.3V4h2.9z"/></svg>',
|
||||
dialog: '<svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"><path d="M1.8 2.2h8.4v5.6H5.4L3 9.8V7.8H1.8z"/></svg>',
|
||||
};
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
|
||||
function send(command, extra) { SendWXMessage(JSON.stringify(Object.assign({ command }, extra || {}))); }
|
||||
|
||||
function el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
// An icon from the fixed set above, never from an entry.
|
||||
function icon(name) {
|
||||
const span = el("span", "icon");
|
||||
span.innerHTML = ICON[name] || ICON.agent;
|
||||
return span;
|
||||
}
|
||||
|
||||
// ---- JSON, laid out as the Run Script console lays out a result ---------------------------------------------------
|
||||
|
||||
function jsonBlock(value) {
|
||||
const pre = el("pre", "raw");
|
||||
if (M.truncated(value)) {
|
||||
pre.className = "raw is-note";
|
||||
pre.textContent = M.tr("too_large", "Too large to show here (%s bytes).", value.bytes);
|
||||
return pre;
|
||||
}
|
||||
const shown = RunScriptModel.formatJson(JSON.stringify(value));
|
||||
const tokens = RunScriptModel.jsonTokens(shown);
|
||||
if (!tokens) {
|
||||
pre.textContent = shown;
|
||||
return pre;
|
||||
}
|
||||
for (const token of tokens) {
|
||||
if (token.type === "space") pre.append(document.createTextNode(token.text));
|
||||
else pre.append(el("span", "j-" + token.type + (token.text === '"' + MASK + '"' ? " mask" : ""), token.text));
|
||||
}
|
||||
return pre;
|
||||
}
|
||||
|
||||
// ---- a step -------------------------------------------------------------------------------------------------------
|
||||
|
||||
function makeRow(entry) {
|
||||
const row = el("li", "step");
|
||||
row.dataset.id = entry.id;
|
||||
row.append(el("span", "dot"));
|
||||
const main = el("div", "step-main");
|
||||
const head = el("button", "step-head");
|
||||
head.type = "button";
|
||||
head.setAttribute("aria-expanded", "false");
|
||||
head.append(el("span", "step-title"), el("span", "step-what"));
|
||||
head.addEventListener("click", () => toggle(entry.id));
|
||||
const nested = el("ol", "rail nested");
|
||||
nested.hidden = true;
|
||||
const detail = el("div", "step-detail");
|
||||
detail.hidden = true;
|
||||
main.append(head, el("div", "step-tags"), el("div", "failure"), nested, detail);
|
||||
row.append(main, el("div", "step-side"));
|
||||
return row;
|
||||
}
|
||||
|
||||
function nestedOf(row) { return row.querySelector(":scope > .step-main > .rail.nested"); }
|
||||
|
||||
function anyRunning(entry) {
|
||||
return entry.status === "running" || (S.tree.children.get(entry.id) || []).some(anyRunning);
|
||||
}
|
||||
|
||||
function renderRow(entry) {
|
||||
const row = rows.get(entry.id);
|
||||
const open = S.open.has(entry.id);
|
||||
const children = S.tree.children.get(entry.id) || [];
|
||||
const status = { running: "is-running", done: "is-done", failed: "is-fail" }[entry.status] || "is-done";
|
||||
row.className = "step " + status + (entry.status !== "running" ? " is-ended" : "") + (entry.read ? " is-read" : "") +
|
||||
(entry.kind === "dialog" ? " is-dialog" : "") + (open ? " is-open" : "") + (row.classList.contains("is-hidden") ? " is-hidden" : "") +
|
||||
(row.classList.contains("is-last") ? " is-last" : "");
|
||||
|
||||
const dot = row.querySelector(":scope > .dot");
|
||||
dot.textContent = "";
|
||||
if (entry.kind === "dialog") dot.append(icon("dialog"));
|
||||
else dot.textContent = entry.number ? String(entry.number) : "";
|
||||
dot.title = entry.kind === "dialog" ? M.tr("dialog_answered", "A dialog a rule answered")
|
||||
: entry.read ? M.tr("read_call", "A call that only reads") : M.tr("change_call", "A call that changes something");
|
||||
|
||||
const head = row.querySelector(":scope > .step-main > .step-head");
|
||||
head.setAttribute("aria-expanded", String(open));
|
||||
head.querySelector(".step-title").textContent = entry.title || entry.tool || "";
|
||||
const what = head.querySelector(".step-what");
|
||||
what.textContent = entry.what || "";
|
||||
if (entry.kind === "dialog" && entry.request && entry.request.button) what.append(el("span", "pressed", entry.request.button));
|
||||
if (entry.status === "running" && entry.job && !entry.read)
|
||||
what.append(el("span", "res is-run", (entry.what ? " " : "") + M.tr("running_as_job", "running as job %s", entry.job)));
|
||||
|
||||
const tags = row.querySelector(":scope > .step-main > .step-tags");
|
||||
tags.textContent = "";
|
||||
// What a call does beyond the open project, labelled by the host as Action Replay's steps are ("flag_" + id).
|
||||
for (const id of entry.flags || []) tags.append(el("span", "tag", M.tr("flag_" + id, id)));
|
||||
tags.hidden = !tags.childNodes.length;
|
||||
|
||||
const failure = row.querySelector(":scope > .step-main > .failure");
|
||||
failure.hidden = entry.status !== "failed" || !entry.error;
|
||||
failure.textContent = entry.status === "failed" ? (entry.error || "").split("\n")[0] : "";
|
||||
|
||||
// A run's own steps, while it runs or once opened.
|
||||
const nested = nestedOf(row);
|
||||
nested.hidden = !children.length || !(open || anyRunning(entry));
|
||||
|
||||
const detail = row.querySelector(":scope > .step-main > .step-detail");
|
||||
detail.hidden = !open;
|
||||
if (open) fillDetail(detail, entry);
|
||||
|
||||
const side = row.querySelector(":scope > .step-side");
|
||||
side.textContent = "";
|
||||
if (!entry.parent || !S.store.has(entry.parent)) {
|
||||
const src = el("span", "src");
|
||||
src.title = entry.source_label || "";
|
||||
src.append(el("span", "src-name", entry.source_label || ""), icon(entry.source));
|
||||
side.append(src, el("span", "clock", M.clock(entry.started)));
|
||||
}
|
||||
side.append(el("span", "time", entry.kind === "dialog" ? "" : M.duration(M.elapsed(entry, Date.now()))));
|
||||
}
|
||||
|
||||
function fillDetail(detail, entry) {
|
||||
detail.textContent = "";
|
||||
if (entry.kind === "dialog") {
|
||||
const d = entry.request || {};
|
||||
detail.append(el("div", "kv-head", M.tr("dialog", "Dialog")));
|
||||
const dl = el("dl", "args plain");
|
||||
for (const [key, fallback, value] of [["dialog_title", "Title", d.title], ["dialog_message", "Message", d.message], ["pressed", "Pressed", d.button]])
|
||||
if (value) dl.append(el("dt", "", M.tr(key, fallback)), el("dd", "", value));
|
||||
detail.append(dl);
|
||||
const rule = M.ruleSetter(entry, S.store);
|
||||
const ruleHead = el("div", "kv-head", M.tr("rule", "Rule"));
|
||||
if (rule) {
|
||||
ruleHead.append(el("span", "meta", M.tr("set_by", "set by call %s, %s", rule.number, rule.title || rule.tool)));
|
||||
const show = el("button", "link", M.tr("show_call", "Show that call"));
|
||||
show.type = "button";
|
||||
show.addEventListener("click", () => reveal(rule.id));
|
||||
ruleHead.append(show);
|
||||
} else ruleHead.append(el("span", "meta", M.tr("rule_gone", "the call that set it isn't listed")));
|
||||
detail.append(ruleHead);
|
||||
const rl = el("dl", "args");
|
||||
// The rule's own arguments, by their names.
|
||||
rl.append(el("dt", "", "match"), el("dd", "", d.match || ""), el("dt", "", "button"), el("dd", "", d.button || ""));
|
||||
detail.append(rl);
|
||||
return;
|
||||
}
|
||||
const parent = S.store.get(entry.parent);
|
||||
detail.append(section(M.tr("request", "Request"), M.requestNote(entry, parent && (parent.title || parent.tool)), entry.request,
|
||||
M.tr("copy_request", "Copy request")));
|
||||
const state = M.responseState(entry);
|
||||
detail.append(section(M.tr("response", "Response"), M.responseNote(entry, Date.now()), state === "value" ? entry.response : undefined,
|
||||
M.tr("copy_response", "Copy response"), state === "withheld"));
|
||||
// The files its result names, as Action Replay lists a step's: a screenshot opens in the system's viewer, and each
|
||||
// file shows in its folder. The host finds a file by the entry and its place in the list.
|
||||
const files = entry.files || [];
|
||||
if (files.length) {
|
||||
const box = el("div", "files");
|
||||
if (entry.thumb) {
|
||||
const img = el("img", "thumb");
|
||||
img.src = entry.thumb;
|
||||
img.alt = files[0];
|
||||
img.addEventListener("click", () => send("open_file", { id: entry.id, index: 0 }));
|
||||
box.append(img);
|
||||
}
|
||||
files.forEach((name, index) => {
|
||||
const link = el("button", "link", name);
|
||||
link.type = "button";
|
||||
link.title = M.tr("show_in_folder", "Show in folder");
|
||||
link.addEventListener("click", () => send("show_file", { id: entry.id, index }));
|
||||
box.append(link);
|
||||
});
|
||||
detail.append(box);
|
||||
}
|
||||
}
|
||||
|
||||
// A titled JSON block with its note and a Copy link; "Nothing yet." while a call has no response, and a note in place of
|
||||
// a response the host withheld.
|
||||
function section(title, note, value, copyLabel, withheld) {
|
||||
const wrap = el("div", "kv");
|
||||
const head = el("div", "kv-head", title);
|
||||
head.append(el("span", "meta", note));
|
||||
if (value !== undefined && !M.truncated(value)) {
|
||||
const copy = el("button", "link", copyLabel);
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
send("copy", { text: JSON.stringify(value, null, 2) });
|
||||
copy.textContent = M.tr("copied", "Copied");
|
||||
setTimeout(() => { copy.textContent = copyLabel; }, 1200);
|
||||
});
|
||||
head.append(copy);
|
||||
}
|
||||
wrap.append(head, withheld ? el("p", "none", M.tr("withheld", "Can't be shown: it repeats a call whose record the pane no longer has."))
|
||||
: value === undefined ? el("p", "none", M.tr("nothing_yet_response", "Nothing yet."))
|
||||
: jsonBlock(value));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function toggle(id) {
|
||||
if (S.open.has(id)) S.open.delete(id);
|
||||
else S.open.add(id);
|
||||
const entry = S.store.get(id);
|
||||
if (entry) renderRow(entry);
|
||||
refresh();
|
||||
}
|
||||
|
||||
// Opens an entry and scrolls to it: the call a dialog's rule came from.
|
||||
function reveal(id) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry) return;
|
||||
S.open.add(id);
|
||||
const above = ancestors(entry);
|
||||
for (const up of above) S.open.add(up.id);
|
||||
for (const shown of [entry].concat(above)) renderRow(shown);
|
||||
refresh();
|
||||
S.following = false;
|
||||
const row = rows.get(id);
|
||||
const list = $("list");
|
||||
if (row) list.scrollTop = row.getBoundingClientRect().top - list.getBoundingClientRect().top + list.scrollTop - 8;
|
||||
}
|
||||
|
||||
function ancestors(entry) {
|
||||
const out = [];
|
||||
for (let up = S.store.get(entry.parent); up; up = S.store.get(up.parent)) out.push(up);
|
||||
return out;
|
||||
}
|
||||
|
||||
function atBottom(list) { return list.scrollHeight - list.scrollTop - list.clientHeight < 30; }
|
||||
|
||||
// ---- the list -----------------------------------------------------------------------------------------------------
|
||||
|
||||
function onEntries(msg) {
|
||||
const list = $("list");
|
||||
const wasAtBottom = atBottom(list);
|
||||
const before = S.tree.top.length;
|
||||
if (msg.reset) {
|
||||
rows.clear();
|
||||
$("rail").textContent = "";
|
||||
S.open.clear();
|
||||
}
|
||||
for (const id of msg.removed || []) {
|
||||
const row = rows.get(id);
|
||||
if (row) row.remove();
|
||||
rows.delete(id);
|
||||
S.open.delete(id);
|
||||
}
|
||||
M.apply(S.store, msg);
|
||||
S.tree = M.tree(S.store);
|
||||
// A new row goes last under its parent, or at the end of the list: ids only grow.
|
||||
const place = (entry) => {
|
||||
if (!rows.has(entry.id)) rows.set(entry.id, makeRow(entry));
|
||||
const row = rows.get(entry.id);
|
||||
const host = entry.parent && rows.has(entry.parent) ? nestedOf(rows.get(entry.parent)) : $("rail");
|
||||
if (row.parentNode !== host) host.append(row);
|
||||
};
|
||||
const changed = new Set((msg.entries || []).map((e) => e.id));
|
||||
const walk = (entries) => {
|
||||
for (const entry of entries) {
|
||||
if (msg.reset || changed.has(entry.id) || !rows.has(entry.id)) place(entry);
|
||||
walk(S.tree.children.get(entry.id) || []);
|
||||
}
|
||||
};
|
||||
walk(S.tree.top);
|
||||
// Each changed entry and, once each, the runs above them, whose running state and counts follow their steps.
|
||||
const render = new Set();
|
||||
for (const id of changed) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry) continue;
|
||||
render.add(entry);
|
||||
for (const up of ancestors(entry)) render.add(up);
|
||||
}
|
||||
for (const entry of render) renderRow(entry);
|
||||
const following = S.following || wasAtBottom || msg.reset;
|
||||
S.newBelow = following ? 0 : S.newBelow + Math.max(0, S.tree.top.length - before);
|
||||
refresh();
|
||||
if (following) list.scrollTop = list.scrollHeight;
|
||||
}
|
||||
|
||||
// Which rows show, the thread's end, the source names that repeat, the toolbar.
|
||||
function refresh() {
|
||||
const { shown, last } = M.visibility(S.tree, { show: S.show, source: S.source, find: S.find });
|
||||
for (const [id, row] of rows) {
|
||||
row.classList.toggle("is-hidden", !shown.has(id));
|
||||
row.classList.toggle("is-last", last.has(id));
|
||||
}
|
||||
let previous = null;
|
||||
for (const entry of S.tree.top) {
|
||||
if (!shown.has(entry.id)) continue;
|
||||
const src = rows.has(entry.id) ? rows.get(entry.id).querySelector(":scope > .step-side .src") : null;
|
||||
if (src) src.classList.toggle("same", entry.source_label === previous);
|
||||
previous = entry.source_label;
|
||||
}
|
||||
const empty = $("empty");
|
||||
empty.hidden = S.tree.top.some((e) => shown.has(e.id));
|
||||
empty.textContent = S.tree.top.length ? M.tr("no_match", "No call matches.")
|
||||
: M.tr("empty", "Calls from agents, Action Replay, Run Script and plugins appear here as they run.");
|
||||
$("latest").hidden = !S.newBelow;
|
||||
$("latest-n").textContent = M.tr("new_calls", "New calls: %s", S.newBelow);
|
||||
renderToolbar();
|
||||
}
|
||||
|
||||
function renderToolbar() {
|
||||
document.querySelectorAll(".seg button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.show === S.show)));
|
||||
const sources = M.sources(S.tree.top);
|
||||
const picked = sources.find((s) => s.key === S.source);
|
||||
if (S.source !== "all" && !picked) S.source = "all";
|
||||
$("src-label").textContent = picked ? picked.label : M.tr("everyone", "Everyone");
|
||||
|
||||
const status = M.status(S.tree.top);
|
||||
const counts = M.counts(S.tree.top);
|
||||
const box = $("status");
|
||||
box.textContent = "";
|
||||
const who = el("span", status.busy ? "is-busy" : "");
|
||||
who.append(el("span", "sdot"), el("span", "who", status.text));
|
||||
box.append(who, el("span", "counts", M.tr("calls", "Calls: %s", counts.calls)));
|
||||
if (counts.failed) {
|
||||
const failed = el("button", "nfail", M.tr("failed", "Failed: %s", counts.failed));
|
||||
failed.type = "button";
|
||||
failed.addEventListener("click", () => setShow("failures"));
|
||||
box.append(failed);
|
||||
}
|
||||
}
|
||||
|
||||
function setShow(show) {
|
||||
S.show = show;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function renderSourceMenu() {
|
||||
const menu = $("src-menu");
|
||||
menu.textContent = "";
|
||||
const items = [{ key: "all", label: M.tr("everyone", "Everyone"), count: S.tree.top.length }].concat(M.sources(S.tree.top));
|
||||
for (const item of items) {
|
||||
const b = el("button");
|
||||
b.type = "button";
|
||||
b.setAttribute("role", "menuitemradio");
|
||||
b.setAttribute("aria-checked", String(S.source === item.key));
|
||||
b.append(el("span", "tick", S.source === item.key ? "✓" : ""));
|
||||
if (item.source) b.append(icon(item.source));
|
||||
b.append(el("span", "label", item.label), el("span", "mc", String(item.count)));
|
||||
b.addEventListener("click", () => {
|
||||
S.source = item.key;
|
||||
closeSourceMenu();
|
||||
refresh();
|
||||
});
|
||||
menu.append(b);
|
||||
}
|
||||
}
|
||||
|
||||
function closeSourceMenu() {
|
||||
$("src-menu").hidden = true;
|
||||
$("src-btn").setAttribute("aria-expanded", "false");
|
||||
}
|
||||
|
||||
// The running calls' durations, four times a second.
|
||||
function tick() {
|
||||
const now = Date.now();
|
||||
for (const [id, row] of rows) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry || entry.status !== "running") continue;
|
||||
const time = row.querySelector(":scope > .step-side .time");
|
||||
if (time) time.textContent = M.duration(now - entry.started);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- host messages ------------------------------------------------------------------------------------------------
|
||||
|
||||
function HandleStudio(msg) {
|
||||
switch (msg.command) {
|
||||
case "entries": onEntries(msg); break;
|
||||
}
|
||||
}
|
||||
|
||||
function OnInit() {
|
||||
TranslatePage();
|
||||
$("clear").addEventListener("click", () => send("clear"));
|
||||
document.querySelectorAll(".seg button").forEach((b) => b.addEventListener("click", () => setShow(b.dataset.show)));
|
||||
$("src-btn").addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const menu = $("src-menu");
|
||||
if (!menu.hidden) return closeSourceMenu();
|
||||
renderSourceMenu();
|
||||
menu.hidden = false;
|
||||
$("src-btn").setAttribute("aria-expanded", "true");
|
||||
});
|
||||
document.addEventListener("click", (e) => { if (!$("src-menu").contains(e.target)) closeSourceMenu(); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeSourceMenu(); });
|
||||
$("find").addEventListener("input", () => {
|
||||
S.find = $("find").value;
|
||||
refresh();
|
||||
});
|
||||
const list = $("list");
|
||||
list.addEventListener("scroll", () => {
|
||||
S.following = atBottom(list);
|
||||
if (S.following && S.newBelow) {
|
||||
S.newBelow = 0;
|
||||
$("latest").hidden = true;
|
||||
}
|
||||
});
|
||||
$("latest").addEventListener("click", () => {
|
||||
S.following = true;
|
||||
S.newBelow = 0;
|
||||
list.scrollTop = list.scrollHeight;
|
||||
$("latest").hidden = true;
|
||||
});
|
||||
setInterval(tick, 250);
|
||||
refresh();
|
||||
send("ready");
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// The Agent Activity page's pure logic: the host's entries merged into one list and nested by run, what the filters
|
||||
// show, what the toolbar counts and names, and the times and notes a step shows. Loaded by the page as a script and by
|
||||
// agent_activity_model.test.js as a module.
|
||||
(function (root, factory) {
|
||||
"use strict";
|
||||
const api = factory();
|
||||
if (typeof module === "object" && module.exports) module.exports = api;
|
||||
else root.AgentActivityModel = api;
|
||||
})(typeof globalThis === "object" ? globalThis : this, function () {
|
||||
"use strict";
|
||||
|
||||
// The page's T() (i18n.js) where it is loaded; the English with its %s filled in a test.
|
||||
function tr(key, fallback, ...args) {
|
||||
if (typeof T === "function") return T(key, fallback, ...args);
|
||||
let text = fallback;
|
||||
args.forEach((arg) => { text = text.replace("%s", () => String(arg)); });
|
||||
return text;
|
||||
}
|
||||
|
||||
// ---- the list ----------------------------------------------------------------------------------------------------
|
||||
|
||||
// The entries by id. apply() merges a host message {reset, entries, removed}: with reset, what the host sends is all
|
||||
// there is.
|
||||
function createStore() { return new Map(); }
|
||||
function apply(store, msg) {
|
||||
if (msg.reset) store.clear();
|
||||
for (const entry of msg.entries || []) store.set(entry.id, entry);
|
||||
for (const id of msg.removed || []) store.delete(id);
|
||||
}
|
||||
|
||||
// The top-level entries oldest first, and the entries nested under each id, oldest first. An entry whose parent is
|
||||
// gone stands at the top level.
|
||||
function tree(store) {
|
||||
const top = [];
|
||||
const children = new Map();
|
||||
const ids = Array.from(store.keys()).sort((a, b) => a - b);
|
||||
for (const id of ids) {
|
||||
const entry = store.get(id);
|
||||
if (entry.parent && store.has(entry.parent)) {
|
||||
if (!children.has(entry.parent)) children.set(entry.parent, []);
|
||||
children.get(entry.parent).push(entry);
|
||||
} else top.push(entry);
|
||||
}
|
||||
return { top, children };
|
||||
}
|
||||
|
||||
// ---- filters -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// What the source menu sorts by: a plugin's entries by the plugin.
|
||||
function sourceKey(entry) { return entry.source === "plugin" ? "plugin:" + (entry.plugin || "") : entry.source || ""; }
|
||||
|
||||
// Whether `entry`, or an entry nested under it, passes Everything / Changes / Failures and Find a call. A dialog a rule
|
||||
// answered changed something: a button was pressed.
|
||||
function matches(entry, filter, children) {
|
||||
const find = (filter.find || "").trim().toLowerCase();
|
||||
const self = (filter.show === "all" || !filter.show || (filter.show === "changes" && !entry.read) ||
|
||||
(filter.show === "failures" && entry.status === "failed")) &&
|
||||
(!find || [entry.title, entry.what, entry.tool, entry.source_label].join(" ").toLowerCase().includes(find));
|
||||
return self || (children.get(entry.id) || []).some((c) => matches(c, filter, children));
|
||||
}
|
||||
|
||||
// Whether a top-level entry shows: its source is the one the menu picked, and it matches.
|
||||
function showsAtTop(entry, filter, children) {
|
||||
return (!filter.source || filter.source === "all" || sourceKey(entry) === filter.source) && matches(entry, filter, children);
|
||||
}
|
||||
|
||||
// Whether an entry nested under a shown one shows: all of them under Everything with nothing to find, else those
|
||||
// that match.
|
||||
function showsNested(entry, filter, children) {
|
||||
return ((filter.show === "all" || !filter.show) && !(filter.find || "").trim()) || matches(entry, filter, children);
|
||||
}
|
||||
|
||||
// Which entries show under `filter`, and which shown entry ends its list, where its thread stops: {shown, last}, sets of
|
||||
// ids. A top-level entry shows by showsAtTop(), an entry nested under a shown one by showsNested(), at any depth.
|
||||
function visibility(tree, filter) {
|
||||
const shown = new Set();
|
||||
const last = new Set();
|
||||
const walk = (entries, top) => {
|
||||
let end = null;
|
||||
for (const entry of entries) {
|
||||
if (!(top ? showsAtTop(entry, filter, tree.children) : showsNested(entry, filter, tree.children))) continue;
|
||||
shown.add(entry.id);
|
||||
end = entry;
|
||||
walk(tree.children.get(entry.id) || [], false);
|
||||
}
|
||||
if (end) last.add(end.id);
|
||||
};
|
||||
walk(tree.top, true);
|
||||
return { shown, last };
|
||||
}
|
||||
|
||||
// ---- the toolbar -------------------------------------------------------------------------------------------------
|
||||
|
||||
// The calls listed at the top level, which the last number counts, and how many of them failed. A dialog is no call.
|
||||
function counts(top) {
|
||||
const calls = top.filter((e) => e.kind !== "dialog");
|
||||
return { calls: calls.length, failed: calls.filter((e) => e.status === "failed").length };
|
||||
}
|
||||
|
||||
// The sources of the top-level entries, in the order they first came, with their labels and how many entries each.
|
||||
function sources(top) {
|
||||
const out = new Map();
|
||||
for (const entry of top) {
|
||||
const key = sourceKey(entry);
|
||||
if (!out.has(key)) out.set(key, { key, source: entry.source, label: entry.source_label || "", count: 0 });
|
||||
const item = out.get(key);
|
||||
++item.count;
|
||||
// The newest label: an agent's name may have become "Agent" since.
|
||||
if (entry.source_label) item.label = entry.source_label;
|
||||
}
|
||||
return Array.from(out.values());
|
||||
}
|
||||
|
||||
// What the status says: who works now (the newest running top-level entry's source), else whether anything ran.
|
||||
function status(top) {
|
||||
const running = top.filter((e) => e.status === "running");
|
||||
if (running.length) return { busy: true, text: tr("working", "%s is working", running[running.length - 1].source_label) };
|
||||
return { busy: false, text: top.length ? tr("idle", "Idle") : tr("nothing_yet", "Nothing yet") };
|
||||
}
|
||||
|
||||
// ---- a step ------------------------------------------------------------------------------------------------------
|
||||
|
||||
// A duration: tenths of a second under ten seconds, then whole seconds, then minutes and seconds.
|
||||
function duration(ms) {
|
||||
const s = Math.max(0, ms) / 1000;
|
||||
if (s < 60) return tr("seconds", "%s s", s < 10 ? s.toFixed(1) : Math.floor(s));
|
||||
return tr("minutes_seconds", "%s min %s s", Math.floor(s / 60), Math.floor(s % 60));
|
||||
}
|
||||
|
||||
// The time of day `ms` (since the epoch) was, as hours, minutes and seconds.
|
||||
function clock(ms) {
|
||||
const d = new Date(ms);
|
||||
const two = (n) => String(n).padStart(2, "0");
|
||||
return `${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function elapsed(entry, now) { return (entry.ended || now) - entry.started; }
|
||||
|
||||
// Calls a person sees run for longer than this ran as a job the agent was told to wait for.
|
||||
const LONG_MS = 1500;
|
||||
|
||||
// The note beside Response: how the call answered, or that it still runs.
|
||||
function responseNote(entry, now) {
|
||||
const took = duration(elapsed(entry, now));
|
||||
if (entry.status === "running")
|
||||
return entry.job ? tr("running_no_result", "running as job %s; no result yet", entry.job) : tr("waiting_reply", "waiting for the reply");
|
||||
if (entry.status === "failed") return tr("failed_after", "failed after %s", took);
|
||||
if (entry.job && elapsed(entry, now) > LONG_MS) return tr("ran_as_job", "ran as job %s; finished after %s", entry.job, took);
|
||||
return tr("answered_in", "answered in %s", took);
|
||||
}
|
||||
|
||||
// Whether an agent's request went through tool_call, the tool for commands the tool list leaves out.
|
||||
function viaToolCall(entry) {
|
||||
const params = entry.request && entry.request.params;
|
||||
return !!params && params.name === "tool_call";
|
||||
}
|
||||
|
||||
// The note beside Request: where it came from.
|
||||
function requestNote(entry, parentTitle) {
|
||||
const at = clock(entry.started);
|
||||
if (entry.parent && parentTitle) return tr("made_by", "made by %s", parentTitle);
|
||||
if (entry.kind === "work") return tr("work_at", "run in the Run Script panel at %s", at);
|
||||
if (entry.source === "agent" && entry.request && entry.request.method === "tools/call")
|
||||
return viaToolCall(entry) ? tr("tools_call_via", "tools/call from %s through tool_call, at %s", entry.source_label, at)
|
||||
: tr("tools_call_from", "tools/call from %s at %s", entry.source_label, at);
|
||||
return tr("sent_at", "sent at %s", at);
|
||||
}
|
||||
|
||||
// What an entry's Response section shows: "withheld" when the host can't show it (it repeats a job's result whose masking
|
||||
// record the host no longer has), "pending" while there is none yet, else "value".
|
||||
function responseState(entry) {
|
||||
if (entry.withheld === true) return "withheld";
|
||||
return entry.response === null || entry.response === undefined ? "pending" : "value";
|
||||
}
|
||||
|
||||
// The entry of the call that set the rule a dialog's answer came from, or null when the list doesn't hold it.
|
||||
function ruleSetter(entry, store) {
|
||||
return (entry.rule && store.get(entry.rule)) || null;
|
||||
}
|
||||
|
||||
// A request or response the host left out for its size: {truncated: true, bytes}.
|
||||
function truncated(value) {
|
||||
return !!value && typeof value === "object" && value.truncated === true && typeof value.bytes === "number" && Object.keys(value).length === 2;
|
||||
}
|
||||
|
||||
return { tr, createStore, apply, tree, sourceKey, matches, showsAtTop, showsNested, visibility, counts, sources, status, duration, clock,
|
||||
elapsed, responseNote, requestNote, viaToolCall, responseState, ruleSetter, truncated };
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
"use strict";
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const model = require("./agent_activity_model.js");
|
||||
|
||||
// An entry as the host sends it, with what a test leaves out filled in.
|
||||
function entry(fields) {
|
||||
return Object.assign({ id: 1, parent: 0, number: 1, kind: "call", source: "agent", source_label: "Claude Code", plugin: "",
|
||||
tool: "app_state", title: "Get app state", what: "", read: false, status: "done", error: "", job: "",
|
||||
started: 1000, ended: 1200, request: {}, response: {}, rule: 0 }, fields);
|
||||
}
|
||||
|
||||
test("the host's changes merge into the list, and a reset starts it over", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { reset: true, entries: [entry({ id: 1 }), entry({ id: 2, status: "running" })] });
|
||||
model.apply(store, { entries: [entry({ id: 2, status: "done" }), entry({ id: 3 })], removed: [1] });
|
||||
assert.deepEqual(Array.from(store.keys()).sort(), [2, 3]);
|
||||
assert.equal(store.get(2).status, "done");
|
||||
model.apply(store, { reset: true, entries: [entry({ id: 9 })] });
|
||||
assert.deepEqual(Array.from(store.keys()), [9]);
|
||||
});
|
||||
|
||||
test("a run's steps nest under it in order, and a step whose run is gone stands at the top", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [entry({ id: 5, parent: 1 }), entry({ id: 1 }), entry({ id: 3, parent: 1 }), entry({ id: 7, parent: 4 })] });
|
||||
const { top, children } = model.tree(store);
|
||||
assert.deepEqual(top.map((e) => e.id), [1, 7]);
|
||||
assert.deepEqual(children.get(1).map((e) => e.id), [3, 5]);
|
||||
});
|
||||
|
||||
test("Changes leaves out reads, Failures shows failed calls, and a run shows when one of its steps matches", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, read: true }),
|
||||
entry({ id: 2, title: "Slice", what: "Plate 1" }),
|
||||
entry({ id: 3, tool: "replay_run", title: "Run a replay" }),
|
||||
entry({ id: 4, parent: 3, title: "Export", status: "failed", error: "Disk full" }),
|
||||
entry({ id: 5, kind: "dialog", title: "Answered a dialog", read: false }),
|
||||
] });
|
||||
const { top, children } = model.tree(store);
|
||||
const shown = (filter) => top.filter((e) => model.showsAtTop(e, filter, children)).map((e) => e.id);
|
||||
assert.deepEqual(shown({ show: "all" }), [1, 2, 3, 5]);
|
||||
assert.deepEqual(shown({ show: "changes" }), [2, 3, 5]);
|
||||
assert.deepEqual(shown({ show: "failures" }), [3]);
|
||||
assert.deepEqual(shown({ show: "all", find: "plate 1" }), [2]);
|
||||
assert.deepEqual(shown({ show: "all", find: "EXPORT" }), [3]);
|
||||
// Under a shown run, Everything with nothing to find shows every step; otherwise the ones that match.
|
||||
const step = store.get(4);
|
||||
assert.equal(model.showsNested(step, { show: "all" }, children), true);
|
||||
assert.equal(model.showsNested(step, { show: "changes", find: "slice" }, children), false);
|
||||
});
|
||||
|
||||
test("the source menu lists each source once with its newest label, and a plugin's entries by plugin", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, source: "agent", source_label: "Claude Code" }),
|
||||
entry({ id: 2, source: "plugin", plugin: "brim", source_label: "Brim Ears" }),
|
||||
entry({ id: 3, source: "agent", source_label: "Agent" }),
|
||||
entry({ id: 4, source: "plugin", plugin: "fill", source_label: "Fill" }),
|
||||
entry({ id: 5, parent: 2, source: "plugin", plugin: "brim", source_label: "Brim Ears" }),
|
||||
] });
|
||||
const { top, children } = model.tree(store);
|
||||
assert.deepEqual(model.sources(top).map((s) => [s.key, s.label, s.count]),
|
||||
[["agent", "Agent", 2], ["plugin:brim", "Brim Ears", 1], ["plugin:fill", "Fill", 1]]);
|
||||
assert.deepEqual(top.filter((e) => model.showsAtTop(e, { show: "all", source: "plugin:brim" }, children)).map((e) => e.id), [2]);
|
||||
});
|
||||
|
||||
test("the counts are of top-level calls, without dialogs, and the status names who works", () => {
|
||||
const top = [entry({ id: 1 }), entry({ id: 2, status: "failed" }), entry({ id: 3, kind: "dialog" }),
|
||||
entry({ id: 4, status: "running", source_label: "Action Replay" })];
|
||||
assert.deepEqual(model.counts(top), { calls: 3, failed: 1 });
|
||||
assert.deepEqual(model.status(top), { busy: true, text: "Action Replay is working" });
|
||||
assert.deepEqual(model.status([entry({ id: 1 })]), { busy: false, text: "Idle" });
|
||||
assert.deepEqual(model.status([]), { busy: false, text: "Nothing yet" });
|
||||
});
|
||||
|
||||
test("durations read in tenths, seconds, then minutes", () => {
|
||||
assert.equal(model.duration(420), "0.4 s");
|
||||
assert.equal(model.duration(12400), "12 s");
|
||||
assert.equal(model.duration(125000), "2 min 5 s");
|
||||
});
|
||||
|
||||
test("the response note says how the call answered, or that it still runs", () => {
|
||||
const now = 10000;
|
||||
assert.equal(model.responseNote(entry({ started: 1000, ended: 1300 }), now), "answered in 0.3 s");
|
||||
assert.equal(model.responseNote(entry({ job: "j4", started: 1000, ended: 9000 }), now), "ran as job j4; finished after 8.0 s");
|
||||
assert.equal(model.responseNote(entry({ job: "j4", status: "running", ended: 0 }), now), "running as job j4; no result yet");
|
||||
assert.equal(model.responseNote(entry({ status: "running", ended: 0 }), now), "waiting for the reply");
|
||||
assert.equal(model.responseNote(entry({ status: "failed", started: 1000, ended: 1500 }), now), "failed after 0.5 s");
|
||||
});
|
||||
|
||||
test("the request note names an agent's tools/call, through tool_call where it went, and a step's run", () => {
|
||||
const started = new Date(2026, 10, 23, 14, 2, 5).getTime();
|
||||
const call = entry({ started, request: { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "plate_slice" } } });
|
||||
assert.equal(model.requestNote(call), "tools/call from Claude Code at 14:02:05");
|
||||
const wrapped = entry({ started, request: { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "tool_call", arguments: { tool: "sketch_create" } } } });
|
||||
assert.equal(model.requestNote(wrapped), "tools/call from Claude Code through tool_call, at 14:02:05");
|
||||
assert.equal(model.requestNote(entry({ parent: 2 }), "Run a replay"), "made by Run a replay");
|
||||
assert.equal(model.requestNote(entry({ started, kind: "work", source: "run_script" })), "run in the Run Script panel at 14:02:05");
|
||||
});
|
||||
|
||||
test("a payload the host left out for its size is told apart from one that only looks like it", () => {
|
||||
assert.equal(model.truncated({ truncated: true, bytes: 40000 }), true);
|
||||
assert.equal(model.truncated({ truncated: true, bytes: 40000, extra: 1 }), false);
|
||||
assert.equal(model.truncated({ truncated: "yes", bytes: 1 }), false);
|
||||
assert.equal(model.truncated(null), false);
|
||||
});
|
||||
|
||||
test("the filters reach every depth: a replay's script's steps show or hide by their own match", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, tool: "replay_run", title: "Run a replay" }),
|
||||
entry({ id: 2, parent: 1, tool: "script_run", title: "Run a Python script" }),
|
||||
entry({ id: 3, parent: 2, read: true, title: "List objects" }),
|
||||
entry({ id: 4, parent: 2, title: "Export", status: "failed", error: "Disk full" }),
|
||||
entry({ id: 5, read: true, title: "Get app state" }),
|
||||
] });
|
||||
const tree = model.tree(store);
|
||||
const failures = model.visibility(tree, { show: "failures" });
|
||||
assert.deepEqual(Array.from(failures.shown).sort(), [1, 2, 4]);
|
||||
assert.deepEqual(Array.from(failures.last).sort(), [1, 2, 4]); // each list's last shown entry
|
||||
const all = model.visibility(tree, { show: "all" });
|
||||
assert.deepEqual(Array.from(all.shown).sort(), [1, 2, 3, 4, 5]);
|
||||
assert.deepEqual(Array.from(all.last).sort(), [2, 4, 5]);
|
||||
const changes = model.visibility(tree, { show: "changes" });
|
||||
assert.equal(changes.shown.has(3), false);
|
||||
assert.equal(changes.shown.has(5), false);
|
||||
});
|
||||
|
||||
test("a withheld response is told by the entry, not by what the response holds", () => {
|
||||
assert.equal(model.responseState(entry({ withheld: true, response: null })), "withheld");
|
||||
assert.equal(model.responseState(entry({ withheld: false, response: { withheld: true } })), "value");
|
||||
assert.equal(model.responseState(entry({ status: "running", response: null })), "pending");
|
||||
assert.equal(model.responseState(entry({ response: { ok: true } })), "value");
|
||||
});
|
||||
|
||||
test("a dialog's rule links the call that set it only while the list holds that call", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [entry({ id: 4, tool: "dialog_auto_answer" }), entry({ id: 6, kind: "dialog", rule: 4 })] });
|
||||
assert.equal(model.ruleSetter(store.get(6), store).id, 4);
|
||||
assert.equal(model.ruleSetter(entry({ kind: "dialog", rule: 0 }), store), null);
|
||||
model.apply(store, { entries: [], removed: [4] });
|
||||
assert.equal(model.ruleSetter(store.get(6), store), null);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Agent Activity</title>
|
||||
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../js/code_editor.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../css/step_rail.css" />
|
||||
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||
<script type="text/javascript" src="../../include/i18n.js"></script>
|
||||
<script type="text/javascript" src="../js/globalapi.js"></script>
|
||||
<script type="text/javascript" src="../RunScript/run_script_model.js"></script>
|
||||
<script type="text/javascript" src="./agent_activity_model.js"></script>
|
||||
<script type="text/javascript" src="./agent_activity.js"></script>
|
||||
</head>
|
||||
<body onload="OnInit()">
|
||||
<div class="pane">
|
||||
<div class="toolbar" role="toolbar" aria-label="Agent Activity" data-i18n-aria-label="pane">
|
||||
<button type="button" id="clear" class="btn" data-i18n="clear">Clear list</button>
|
||||
<span class="tsep"></span>
|
||||
<div class="seg" role="group" aria-label="Show" data-i18n-aria-label="show">
|
||||
<button type="button" data-show="all" aria-pressed="true" data-i18n="show_all">Everything</button><button type="button" data-show="changes" aria-pressed="false" data-i18n="show_changes">Changes</button><button type="button" data-show="failures" aria-pressed="false" data-i18n="show_failures">Failures</button>
|
||||
</div>
|
||||
<div class="menu-wrap">
|
||||
<button type="button" id="src-btn" class="btn" aria-haspopup="menu" aria-expanded="false"><span class="t-opt" data-i18n="from">From:</span><span id="src-label"></span><svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M2 3.5 5 6.5 8 3.5"/></svg></button>
|
||||
<div class="menu" id="src-menu" role="menu" hidden></div>
|
||||
</div>
|
||||
<input class="find" id="find" type="search" placeholder="Find a call" aria-label="Find a call" data-i18n-placeholder="find" data-i18n-aria-label="find" />
|
||||
<div class="status" id="status" aria-live="polite"></div>
|
||||
</div>
|
||||
<div class="list-wrap">
|
||||
<div class="list" id="list">
|
||||
<p class="empty" id="empty"></p>
|
||||
<ol class="rail" id="rail"></ol>
|
||||
</div>
|
||||
<button type="button" class="latest" id="latest" hidden><svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 3.5 5 6.5 8 3.5"/></svg><span id="latest-n"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,239 @@
|
||||
/* Agent Activity. The step rail comes from ../css/step_rail.css, as Action Replay's; this adds the toolbar, a read's
|
||||
* quiet line, a dialog's step, the nested steps of a run, and the request and response under an opened step. Colours
|
||||
* come from the host theme contract (--orca-*), theme.css's status roles and code_editor.css's JSON colours. */
|
||||
|
||||
:root {
|
||||
--aa-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
--aa-accent-text: var(--plugin-source-mine-text, #00897b);
|
||||
--aa-btn-bg: var(--btn-bg, #ffffff);
|
||||
--aa-btn-border: var(--btn-border, #cccccc);
|
||||
--aa-btn-hover: var(--btn-hover, #f0f0f0);
|
||||
--aa-menu-bg: var(--ctx-bg, #ffffff);
|
||||
}
|
||||
:root[data-orca-theme="dark"] { --aa-accent-text: #4db6ac; }
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-fg);
|
||||
font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
[hidden] { display: none !important; }
|
||||
button:focus-visible, input:focus-visible { outline: 2px solid var(--sr-accent); outline-offset: 1px; }
|
||||
|
||||
.pane { height: 100%; display: flex; flex-direction: column; container-type: inline-size; container-name: pane; }
|
||||
|
||||
/* ---- toolbar, as the Run Script panel's ---- */
|
||||
.toolbar { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--sr-rule); }
|
||||
.btn {
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
color: var(--sr-fg);
|
||||
background: var(--aa-btn-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 2px 10px;
|
||||
height: 24px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.btn svg { width: 10px; height: 10px; flex: none; }
|
||||
.btn:hover:not(:disabled) { background: var(--aa-btn-hover); }
|
||||
.tsep { width: 1px; height: 16px; background: var(--sr-rule); margin: 0 2px; }
|
||||
.seg { display: inline-flex; border: 1px solid var(--aa-btn-border); border-radius: 4px; overflow: hidden; height: 24px; }
|
||||
.seg button { font: inherit; font-size: 12px; border: 0; background: var(--aa-btn-bg); color: var(--sr-fg); padding: 0 9px; cursor: pointer; }
|
||||
.seg button + button { border-left: 1px solid var(--aa-btn-border); }
|
||||
.seg button[aria-pressed="true"] { background: var(--aa-tint); color: var(--aa-accent-text); font-weight: 600; }
|
||||
.menu-wrap { position: relative; }
|
||||
.menu {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
min-width: 200px;
|
||||
max-width: 280px;
|
||||
background: var(--aa-menu-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
|
||||
padding: 4px;
|
||||
}
|
||||
.menu button {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--sr-fg);
|
||||
padding: 5px 8px;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
text-align: left;
|
||||
}
|
||||
.menu button:hover { background: var(--sr-hover); }
|
||||
.menu .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.menu .mc { margin-left: auto; color: var(--sr-muted); font-variant-numeric: tabular-nums; }
|
||||
.menu .tick { width: 12px; flex: none; color: var(--aa-accent-text); }
|
||||
.menu .icon { color: var(--sr-muted); }
|
||||
.find {
|
||||
height: 24px;
|
||||
width: 150px;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
color: var(--sr-fg);
|
||||
background: var(--sr-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
.find::placeholder { color: var(--sr-muted); }
|
||||
.status { margin-left: auto; min-width: 0; display: flex; align-items: center; gap: 12px; font-size: 12px; color: var(--sr-muted); white-space: nowrap; }
|
||||
.status .sdot { width: 7px; height: 7px; border-radius: 50%; background: var(--sr-muted); opacity: 0.5; display: inline-block; margin-right: 5px; }
|
||||
.status .is-busy .sdot { background: var(--aa-accent-text); opacity: 1; animation: aa-pulse 1.2s ease-in-out infinite; }
|
||||
.status .who { color: var(--sr-fg); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.status > span:first-child { min-width: 0; display: inline-flex; align-items: center; }
|
||||
.status .nfail {
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--sr-fail);
|
||||
border: 0;
|
||||
background: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
@keyframes aa-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
|
||||
|
||||
.icon { display: inline-flex; }
|
||||
.icon svg { width: 12px; height: 12px; flex: none; }
|
||||
.link {
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--aa-accent-text);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ---- the list ---- */
|
||||
.list-wrap { position: relative; flex: 1; min-height: 0; }
|
||||
.list { position: absolute; inset: 0; overflow: auto; }
|
||||
.empty { margin: 0; padding: 14px 16px; color: var(--sr-muted); }
|
||||
.latest {
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
bottom: 10px;
|
||||
z-index: 2;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--sr-accent);
|
||||
background: var(--sr-bg);
|
||||
color: var(--aa-accent-text);
|
||||
border-radius: 12px;
|
||||
padding: 2px 10px 2px 8px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
.latest svg { width: 10px; height: 10px; }
|
||||
|
||||
/* ---- the step rail, as a list of calls ---- */
|
||||
.step { padding: 0 10px 0 12px; }
|
||||
.step.is-hidden { display: none; }
|
||||
.step::before { left: calc(12px + var(--sr-dot) / 2 - 1px); }
|
||||
.step.is-last::before { display: none; }
|
||||
/* The thread takes the accent once the call has ended, failed or not. */
|
||||
.step.is-ended::before { background: var(--sr-accent); }
|
||||
.dot { font-size: 10.5px; letter-spacing: -0.02em; }
|
||||
.dot .icon svg { width: 11px; height: 11px; }
|
||||
/* A read passed too, but changed nothing: the hollow dot. */
|
||||
.step.is-read.is-done .dot { background: var(--sr-bg); border-color: var(--sr-accent); color: var(--aa-accent-text); }
|
||||
.step.is-running .dot { color: var(--aa-accent-text); }
|
||||
.step.is-dialog .dot { background: var(--aa-tint); border-color: var(--sr-accent); color: var(--aa-accent-text); }
|
||||
.step-head:hover .step-title { text-decoration: underline; text-decoration-color: var(--sr-rule); text-underline-offset: 3px; }
|
||||
.step-what .res.is-run { color: var(--aa-accent-text); }
|
||||
.step-what .pressed {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
color: var(--sr-fg);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
.failure { margin: 0 0 6px; padding: 5px 8px; font-size: 12px; overflow-wrap: anywhere; }
|
||||
|
||||
/* A read is one quiet line: title and target side by side, no weight. */
|
||||
.step.is-read .dot { margin-top: 2px; }
|
||||
.step.is-read::before { top: calc(2px + var(--sr-dot)); }
|
||||
.step.is-read .step-head { display: flex; align-items: baseline; gap: 8px; padding: 2px 4px 2px 0; min-width: 0; }
|
||||
.step.is-read .step-title { font-weight: 400; color: var(--sr-muted); white-space: nowrap; }
|
||||
.step.is-read .step-what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.step.is-read.is-open .step-what { white-space: normal; }
|
||||
|
||||
.step-side { align-self: start; align-items: center; justify-content: flex-end; gap: 10px; font-size: 12px; color: var(--sr-muted); white-space: nowrap; }
|
||||
.step.is-read .step-side { padding-top: 3px; }
|
||||
.src { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 140px; }
|
||||
.src-name { overflow: hidden; text-overflow: ellipsis; }
|
||||
.src.same .src-name { display: none; }
|
||||
.clock { width: 54px; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.time { width: 50px; text-align: right; }
|
||||
.step.is-running > .step-side .time { color: var(--aa-accent-text); }
|
||||
/* ---- an opened step: its request and its response, as JSON ---- */
|
||||
.kv-head { display: flex; align-items: baseline; gap: 10px; margin: 6px 0 3px; font-weight: 600; }
|
||||
.kv-head .meta { font-weight: 400; color: var(--sr-muted); min-width: 0; overflow-wrap: anywhere; }
|
||||
.kv-head .link { margin-left: auto; }
|
||||
.args { margin: 0; }
|
||||
.args.plain dd { font-family: inherit; font-size: 12px; }
|
||||
.none { margin: 0; color: var(--sr-muted); }
|
||||
/* Long lines wrap: a pane this narrow shows a value whole rather than behind a sideways scroll, whose bar WebKit would
|
||||
paint over the heading below. */
|
||||
.raw { margin: 0; max-height: 240px; line-height: 1.45; color: var(--sr-fg); background: var(--sr-bg); white-space: pre-wrap; overflow-wrap: anywhere; overflow-x: hidden; }
|
||||
.raw.is-note { color: var(--sr-muted); font-family: inherit; white-space: normal; }
|
||||
.raw .j-key { color: var(--code-key); }
|
||||
.raw .j-string { color: var(--code-string); }
|
||||
.raw .j-number { color: var(--code-number); }
|
||||
.raw .j-literal { color: var(--code-keyword); }
|
||||
.raw .j-punct { color: var(--code-punct); }
|
||||
.raw .mask { color: var(--sr-muted); letter-spacing: 0.1em; }
|
||||
.files { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 6px; }
|
||||
.thumb { width: 168px; cursor: pointer; }
|
||||
|
||||
/* ---- a run's own steps, nested under its row as Action Replay lists them ---- */
|
||||
.rail.nested { padding: 0 0 6px; }
|
||||
.rail.nested .step { --sr-dot: 16px; padding-left: 0; padding-right: 0; font-size: 12.5px; }
|
||||
.rail.nested .step::before { left: calc(var(--sr-dot) / 2 - 1px); }
|
||||
.rail.nested .dot { font-size: 9.5px; }
|
||||
.rail.nested .step.is-open { background: transparent; }
|
||||
|
||||
/* A narrow pane (docked right, a small floating window) keeps the rail and drops the extras. */
|
||||
@container pane (max-width: 560px) {
|
||||
.clock, .src-name, .t-opt, .status .counts { display: none !important; }
|
||||
.find { flex: 1 1 90px; width: auto; min-width: 90px; }
|
||||
.status { margin-left: 0; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.status .is-busy .sdot { animation: none; }
|
||||
}
|
||||
@@ -334,7 +334,7 @@ function runCell() {
|
||||
const code = cellText(cell, text.split("\n"));
|
||||
S.pending = { kind: "cell", cells, text, cell, code };
|
||||
S.message = null;
|
||||
send("run", { kind: "cell", text, first_line: cell.start, last_line: cell.end, code });
|
||||
send("run", { kind: "cell", text, first_line: cell.start, last_line: cell.end, cell: cell.index, title: cell.title, code });
|
||||
render();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/* The step rail that Action Replay and Agent Activity draw a list of calls with: a numbered dot per step on a
|
||||
* thread that takes the accent as steps pass, the step's title and target, its time at the side, and its detail
|
||||
* when opened. Colours come from the host theme contract (--orca-*) and theme.css's status roles, so it follows the
|
||||
* app in light and dark. A page links it after theme.css and before its own style.css. */
|
||||
|
||||
:root {
|
||||
--sr-bg: var(--orca-bg, #ffffff);
|
||||
--sr-fg: var(--orca-fg, #262e30);
|
||||
--sr-muted: var(--orca-muted, #6b7478);
|
||||
--sr-rule: var(--border, #dcdfe1);
|
||||
--sr-accent: var(--orca-accent, #009688);
|
||||
--sr-accent-fg: var(--orca-accent-fg, #ffffff);
|
||||
--sr-pass: var(--plugin-status-ok, #137333);
|
||||
--sr-fail: var(--plugin-status-danger, #b42318);
|
||||
--sr-fail-bg: var(--plugin-status-danger-bg, rgba(180, 35, 24, 0.12));
|
||||
--sr-warn: var(--plugin-status-warn, #a15c00);
|
||||
--sr-warn-bg: var(--plugin-status-warn-bg, rgba(199, 122, 22, 0.12));
|
||||
--sr-hover: var(--row-hover, #f7f9fb);
|
||||
--sr-ring: rgba(0, 150, 136, 0.25);
|
||||
--sr-ring-soft: rgba(0, 150, 136, 0.1);
|
||||
--sr-mono: var(--code-font);
|
||||
--sr-dot: 20px;
|
||||
}
|
||||
|
||||
.rail { list-style: none; margin: 0; padding: 6px 0 10px; }
|
||||
.step {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: var(--sr-dot) minmax(0, 1fr) auto;
|
||||
column-gap: 10px;
|
||||
padding: 0 12px 0 14px;
|
||||
}
|
||||
/* The thread from this step's dot down to the next one; it takes the accent once the step passed. */
|
||||
.step::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: calc(14px + var(--sr-dot) / 2 - 1px);
|
||||
top: calc(6px + var(--sr-dot));
|
||||
bottom: -6px;
|
||||
width: 2px;
|
||||
background: var(--sr-rule);
|
||||
transition: background-color 240ms ease;
|
||||
}
|
||||
.step:last-child::before { display: none; }
|
||||
.step.is-done::before, .step.is-warn::before { background: var(--sr-accent); }
|
||||
.dot {
|
||||
margin-top: 6px;
|
||||
width: var(--sr-dot);
|
||||
height: var(--sr-dot);
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--sr-rule);
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.step.is-done .dot { background: var(--sr-accent); border-color: var(--sr-accent); color: var(--sr-accent-fg); }
|
||||
.step.is-warn .dot { background: var(--sr-warn); border-color: var(--sr-warn); color: #ffffff; }
|
||||
.step.is-fail .dot, .step.is-stopped .dot { background: var(--sr-fail); border-color: var(--sr-fail); color: #ffffff; }
|
||||
.step.is-running .dot { border-color: var(--sr-accent); color: var(--sr-accent); animation: sr-ring 1.4s ease-in-out infinite; }
|
||||
@keyframes sr-ring {
|
||||
0%, 100% { box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
50% { box-shadow: 0 0 0 5px var(--sr-ring-soft); }
|
||||
}
|
||||
|
||||
.step-main { min-width: 0; }
|
||||
.step-head {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 6px 4px 6px 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.step-title { font-weight: 600; }
|
||||
.step-what, .step-args { display: block; color: var(--sr-muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.step-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
padding: 0 6px;
|
||||
border-radius: 3px;
|
||||
color: var(--sr-warn);
|
||||
background: var(--sr-warn-bg);
|
||||
}
|
||||
.tag.is-check { color: var(--sr-muted); background: none; border: 1px solid var(--sr-rule); }
|
||||
|
||||
.step-side { display: flex; align-items: flex-start; gap: 6px; padding-top: 7px; }
|
||||
.time { font-size: 12px; color: var(--sr-muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.step.is-running .time { color: var(--sr-accent); }
|
||||
|
||||
/* ---- an opened step ---- */
|
||||
.step-detail { padding: 2px 0 10px; font-size: 12px; }
|
||||
.step.is-open { background: var(--sr-hover); }
|
||||
.args { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 12px; margin: 0 0 6px; }
|
||||
.args dt { color: var(--sr-muted); }
|
||||
.args dd { margin: 0; font-family: var(--sr-mono); font-size: 11.5px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.failure {
|
||||
margin: 4px 0 6px;
|
||||
padding: 6px 8px;
|
||||
border-left: 2px solid var(--sr-fail);
|
||||
border-radius: 0 3px 3px 0;
|
||||
background: var(--sr-fail-bg);
|
||||
}
|
||||
.step.is-warn .failure { border-left-color: var(--sr-warn); background: var(--sr-warn-bg); }
|
||||
.failure-detail { display: block; margin-top: 3px; color: var(--sr-muted); overflow-wrap: anywhere; }
|
||||
.thumb {
|
||||
display: block;
|
||||
width: 160px;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.raw {
|
||||
margin: 6px 0 0;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
font-family: var(--sr-mono);
|
||||
font-size: 11px;
|
||||
white-space: pre;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.step.is-running .dot { animation: none; box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
.step::before { transition: none; }
|
||||
}
|
||||
@@ -145,6 +145,8 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/ActionRegistry.hpp
|
||||
GUI/ActionReplayDialog.cpp
|
||||
GUI/ActionReplayDialog.hpp
|
||||
GUI/AgentActivityPanel.cpp
|
||||
GUI/AgentActivityPanel.hpp
|
||||
GUI/NativeCommandMenuItems.hpp
|
||||
GUI/NativeCommands.cpp
|
||||
GUI/NativeCommands.hpp
|
||||
@@ -174,6 +176,8 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/Operations/RunStatus.hpp
|
||||
GUI/SyntheticInput.cpp
|
||||
GUI/SyntheticInput.hpp
|
||||
GUI/Mcp/ActivityLog.cpp
|
||||
GUI/Mcp/ActivityLog.hpp
|
||||
GUI/Mcp/AutomationRuntime.cpp
|
||||
GUI/Mcp/AutomationRuntime.hpp
|
||||
GUI/Mcp/AutomationRuntimePtr.hpp
|
||||
|
||||
@@ -235,8 +235,29 @@ std::string expect_text(const json& r)
|
||||
return {};
|
||||
}
|
||||
|
||||
// A screenshot as a 160 px wide PNG data URL for the step's row, or "" when it can't be read.
|
||||
std::string thumbnail(const std::string& path)
|
||||
} // namespace
|
||||
|
||||
json flag_strings()
|
||||
{
|
||||
return {
|
||||
{"flag_writes_file", _u8L("Writes a file")},
|
||||
{"flag_changes_presets", _u8L("Changes presets")},
|
||||
{"flag_replaces_project", _u8L("Replaces the project")},
|
||||
{"flag_sends_to_printer", _u8L("Sends to a printer")},
|
||||
{"flag_runs_program", _u8L("Can run a program")},
|
||||
};
|
||||
}
|
||||
|
||||
std::string script_status_text(const std::string& status)
|
||||
{
|
||||
return status == "cancelled" ? _u8L("The script was stopped.") :
|
||||
status == "timed_out" ? _u8L("The script ran out of time.") :
|
||||
status == "unavailable" ? _u8L("Python is not available in this OrcaSlicer.") :
|
||||
status == "refused" ? _u8L("The script could not run.") :
|
||||
_u8L("The script raised an exception.");
|
||||
}
|
||||
|
||||
std::string screenshot_thumbnail(const std::string& path)
|
||||
{
|
||||
wxImage image;
|
||||
if (!image.LoadFile(from_u8(path), wxBITMAP_TYPE_PNG) || !image.IsOk() || image.GetWidth() <= 0)
|
||||
@@ -252,8 +273,6 @@ std::string thumbnail(const std::string& path)
|
||||
return "data:image/png;base64," + into_u8(wxBase64Encode(bytes.data(), bytes.size()));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ActionReplayDialog::ActionReplayDialog(wxWindow* parent) : WebViewHostDialog(parent)
|
||||
{
|
||||
// The window is one the GUI tools reach, as any of the app's windows, so an agent or a test can read and close it;
|
||||
@@ -322,7 +341,7 @@ nlohmann::json ActionReplayDialog::localized_strings() const
|
||||
#else
|
||||
const std::string control = ctrl, enter = "Enter";
|
||||
#endif
|
||||
return {
|
||||
json strings = {
|
||||
{"key_suggest", control + "Space"},
|
||||
{"key_run", ctrl + enter},
|
||||
{"key_save", ctrl + "S"},
|
||||
@@ -360,11 +379,6 @@ nlohmann::json ActionReplayDialog::localized_strings() const
|
||||
{"show_in_folder", _u8L("Show in folder")},
|
||||
{"skipped", _u8L("Skipped")},
|
||||
{"checks_result", _u8L("Checks the result")},
|
||||
{"flag_writes_file", _u8L("Writes a file")},
|
||||
{"flag_changes_presets", _u8L("Changes presets")},
|
||||
{"flag_replaces_project", _u8L("Replaces the project")},
|
||||
{"flag_sends_to_printer", _u8L("Sends to a printer")},
|
||||
{"flag_runs_program", _u8L("Can run a program")},
|
||||
// TRN A duration; %s is a number of seconds such as 0.8.
|
||||
{"seconds", _u8L("%s s")},
|
||||
// TRN %s is the number of the step that is running.
|
||||
@@ -375,6 +389,8 @@ nlohmann::json ActionReplayDialog::localized_strings() const
|
||||
{"starting", _u8L("OrcaSlicer is still starting…")},
|
||||
{"code_editor", code_editor_strings()},
|
||||
};
|
||||
strings.update(flag_strings());
|
||||
return strings;
|
||||
}
|
||||
|
||||
void ActionReplayDialog::on_script_message(const nlohmann::json& payload)
|
||||
@@ -830,10 +846,7 @@ json ActionReplayDialog::step_view(const json& entry) const
|
||||
else
|
||||
view["failure_text"] = _u8L("This step needs a job that no step of this replay saves.");
|
||||
} else if (kind == "python") {
|
||||
const std::string status = reason.value("status", "");
|
||||
view["failure_text"] = status == "cancelled" ? _u8L("The script was stopped.") :
|
||||
status == "timed_out" ? _u8L("The script ran out of time.") :
|
||||
_u8L("The script raised an exception.");
|
||||
view["failure_text"] = script_status_text(reason.value("status", ""));
|
||||
const json result = entry.value("result", json::object());
|
||||
view["failure_detail"] = result.value("traceback", std::string()).empty() ? entry.value("error", std::string()) :
|
||||
result.value("traceback", std::string());
|
||||
@@ -883,7 +896,7 @@ json ActionReplayDialog::step_view(const json& entry) const
|
||||
for (const std::string& path : Mcp::result_files(result))
|
||||
files.push_back({{"path", path}, {"name", Mcp::path_to_utf8(Mcp::path_from_utf8(path).filename())}});
|
||||
if (tool == "window_screenshot" && !files.empty())
|
||||
if (const std::string url = thumbnail(files[0]["path"].get<std::string>()); !url.empty())
|
||||
if (const std::string url = screenshot_thumbnail(files[0]["path"].get<std::string>()); !url.empty())
|
||||
view["thumbnail"] = url;
|
||||
view["files"] = std::move(files);
|
||||
return view;
|
||||
|
||||
@@ -38,6 +38,18 @@ struct ReplayContext;
|
||||
// titled as its own action is, and a call that is one of its actions (`what`'s `action`) as that action.
|
||||
std::pair<std::string, std::string> replay_what_text(const nlohmann::json& what, const CommandCatalog& catalog);
|
||||
|
||||
// A screenshot as a 160 px wide PNG data URL for a step's row, as Action Replay and Agent Activity show one, or "" when
|
||||
// the file at `path` can't be read as a PNG.
|
||||
std::string screenshot_thumbnail(const std::string& path);
|
||||
|
||||
// The labels of what a step does beyond the open project (describe_step()'s flags), keyed "flag_" + flag_id(), for the
|
||||
// strings of a page that tags steps with them: Action Replay's and Agent Activity's.
|
||||
nlohmann::json flag_strings();
|
||||
|
||||
// A Python script's ending other than by finishing, by its status (cancelled, timed_out, unavailable, refused; any other
|
||||
// is a raised exception), as Action Replay and Agent Activity word it.
|
||||
std::string script_status_text(const std::string& status);
|
||||
|
||||
// The Action Replay window: a person opens or writes a replay file (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
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
#include "AgentActivityPanel.hpp"
|
||||
|
||||
#include "ActionReplayDialog.hpp"
|
||||
#include "CommandCatalog.hpp"
|
||||
#include "GUI.hpp"
|
||||
#include "GUI_App.hpp"
|
||||
#include "I18N.hpp"
|
||||
#include "MainFrame.hpp"
|
||||
#include "NativeCommands.hpp"
|
||||
#include "Plater.hpp"
|
||||
#include "format.hpp"
|
||||
#include "Mcp/ActivityLog.hpp"
|
||||
#include "Mcp/AutomationRuntime.hpp"
|
||||
#include "Mcp/McpPaths.hpp"
|
||||
#include "Mcp/McpReplay.hpp"
|
||||
#include "Mcp/McpReplaySummary.hpp"
|
||||
#include "Mcp/McpTools.hpp"
|
||||
#include "Mcp/VideoOverlay.hpp"
|
||||
#include "Mcp/WindowNames.hpp"
|
||||
#include "Widgets/WebView.hpp"
|
||||
#include "Widgets/WebViewHostDialog.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "slic3r/plugin/PluginDescriptor.hpp"
|
||||
#include "slic3r/plugin/PluginManager.hpp"
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
#include <wx/app.h>
|
||||
#include <wx/clipbrd.h>
|
||||
#include <wx/dataobj.h>
|
||||
#include <wx/defs.h>
|
||||
#include <wx/event.h>
|
||||
#include <wx/filename.h>
|
||||
#include <wx/gdicmn.h>
|
||||
#include <wx/panel.h>
|
||||
#include <wx/string.h>
|
||||
#include <wx/timer.h>
|
||||
#include <wx/translation.h>
|
||||
#include <wx/utils.h>
|
||||
#include <wx/webview.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
using nlohmann::json;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
// The least time between two refreshes of the page, and how often a pane off screen with changes waiting looks again.
|
||||
constexpr std::chrono::milliseconds kRefreshEvery{100};
|
||||
constexpr std::chrono::milliseconds kOffScreenRetry{500};
|
||||
|
||||
// The page's text.
|
||||
json page_strings()
|
||||
{
|
||||
json strings = {
|
||||
{"pane", _u8L("Agent Activity")},
|
||||
// TRN A button of the Agent Activity pane: it empties the list of calls.
|
||||
{"clear", _u8L("Clear list")},
|
||||
{"show", _u8L("Show")},
|
||||
// TRN Agent Activity pane: show every call, reads included.
|
||||
{"show_all", _u8L("Everything")},
|
||||
// TRN Agent Activity pane: show only the calls that change something.
|
||||
{"show_changes", _u8L("Changes")},
|
||||
// TRN Agent Activity pane: show only the calls that failed.
|
||||
{"show_failures", _u8L("Failures")},
|
||||
// TRN Agent Activity pane, before who made the calls listed, such as "Everyone" or "Claude Code".
|
||||
{"from", _u8L("From:")},
|
||||
{"everyone", _u8L("Everyone")},
|
||||
{"find", _u8L("Find a call")},
|
||||
{"empty", _u8L("Calls from agents, Action Replay, Run Script and plugins appear here as they run.")},
|
||||
{"no_match", _u8L("No call matches.")},
|
||||
// TRN Agent Activity pane, while a call runs. %s is who made it, such as "Claude Code" or "Action Replay".
|
||||
{"working", _u8L("%s is working")},
|
||||
{"idle", _u8L("Idle")},
|
||||
{"nothing_yet", _u8L("Nothing yet")},
|
||||
// TRN Agent Activity pane: how many calls are listed. %s is the number.
|
||||
{"calls", _u8L("Calls: %s")},
|
||||
// TRN Agent Activity pane: how many listed calls failed. %s is the number.
|
||||
{"failed", _u8L("Failed: %s")},
|
||||
// TRN Agent Activity pane: a button that scrolls to calls that came while the person read further up. %s is their number.
|
||||
{"new_calls", _u8L("New calls: %s")},
|
||||
// TRN A duration under a minute. %s is the seconds, with one decimal under ten.
|
||||
{"seconds", _u8L("%s s")},
|
||||
// TRN A duration of a minute or more: the minutes, then the seconds.
|
||||
{"minutes_seconds", _u8L("%s min %s s")},
|
||||
// TRN Agent Activity pane, after a running call. %s is its job, such as "j4".
|
||||
{"running_as_job", _u8L("running as job %s")},
|
||||
{"read_call", _u8L("A call that only reads")},
|
||||
{"change_call", _u8L("A call that changes something")},
|
||||
{"dialog_answered", _u8L("A dialog a rule answered")},
|
||||
{"request", _u8L("Request")},
|
||||
{"response", _u8L("Response")},
|
||||
{"copy_request", _u8L("Copy request")},
|
||||
{"copy_response", _u8L("Copy response")},
|
||||
{"copied", _u8L("Copied")},
|
||||
// TRN Agent Activity pane: a call that has no response yet.
|
||||
{"nothing_yet_response", _u8L("Nothing yet.")},
|
||||
// TRN Agent Activity pane: a request or response left out for its size. %s is its size in bytes.
|
||||
{"too_large", _u8L("Too large to show here (%s bytes).")},
|
||||
// TRN Agent Activity pane, beside an agent's request. The first %s is the agent, such as "Claude Code"; the second the time.
|
||||
{"tools_call_from", _u8L("tools/call from %s at %s")},
|
||||
// TRN Agent Activity pane, beside an agent's request sent through tool_call (keep both names). The first %s is the agent; the second the time.
|
||||
{"tools_call_via", _u8L("tools/call from %s through tool_call, at %s")},
|
||||
// TRN Agent Activity pane, beside a step's request. %s is the title of the run that made it, such as "Run a replay".
|
||||
{"made_by", _u8L("made by %s")},
|
||||
// TRN Agent Activity pane, beside the code of a cell or console line. %s is the time.
|
||||
{"work_at", _u8L("run in the Run Script panel at %s")},
|
||||
// TRN Agent Activity pane, beside a request. %s is the time.
|
||||
{"sent_at", _u8L("sent at %s")},
|
||||
// TRN Agent Activity pane, beside a response. %s is a duration.
|
||||
{"answered_in", _u8L("answered in %s")},
|
||||
// TRN Agent Activity pane, beside a response. The first %s is the job, such as "j4"; the second a duration.
|
||||
{"ran_as_job", _u8L("ran as job %s; finished after %s")},
|
||||
// TRN Agent Activity pane, while a call runs. %s is its job, such as "j4".
|
||||
{"running_no_result", _u8L("running as job %s; no result yet")},
|
||||
{"waiting_reply", _u8L("waiting for the reply")},
|
||||
// TRN Agent Activity pane, beside a failed call's response. %s is a duration.
|
||||
{"failed_after", _u8L("failed after %s")},
|
||||
// TRN Agent Activity pane: a dialog an auto-answer rule answered.
|
||||
{"dialog", _u8L("Dialog")},
|
||||
{"dialog_title", _u8L("Title")},
|
||||
{"dialog_message", _u8L("Message")},
|
||||
// TRN Agent Activity pane: the button an auto-answer rule pressed in a dialog.
|
||||
{"pressed", _u8L("Pressed")},
|
||||
// TRN Agent Activity pane: the auto-answer rule that answered a dialog.
|
||||
{"rule", _u8L("Rule")},
|
||||
// TRN Agent Activity pane, beside a rule. The first %s is the number of the call that set it; the second its title.
|
||||
{"set_by", _u8L("set by call %s, %s")},
|
||||
{"show_call", _u8L("Show that call")},
|
||||
// TRN Agent Activity pane, beside the rule that answered a dialog, when the call that set it isn't in the list.
|
||||
{"rule_gone", _u8L("the call that set it isn't listed")},
|
||||
// TRN Agent Activity pane: in place of a response that repeats an earlier call's result the pane can't mask.
|
||||
{"withheld", _u8L("Can't be shown: it repeats a call whose record the pane no longer has.")},
|
||||
{"show_in_folder", _u8L("Show in folder")},
|
||||
};
|
||||
strings.update(flag_strings());
|
||||
return strings;
|
||||
}
|
||||
|
||||
// Who made an entry's calls, as the pane names them.
|
||||
std::string source_label(const json& entry)
|
||||
{
|
||||
const std::string source = Mcp::arg_string(entry, "source");
|
||||
if (source == "agent") {
|
||||
const std::string client = Mcp::arg_string(entry, "client");
|
||||
// TRN Agent Activity pane: an AI agent whose name the app doesn't know.
|
||||
return client.empty() ? _u8L("Agent") : client;
|
||||
}
|
||||
if (source == "action_replay")
|
||||
return _u8L("Action Replay");
|
||||
if (source == "run_script")
|
||||
return _u8L("Run Script");
|
||||
if (source == "command_line")
|
||||
// TRN Agent Activity pane: a replay or script OrcaSlicer was started with (--run).
|
||||
return _u8L("Command line");
|
||||
if (source == "plugin") {
|
||||
const std::string key = Mcp::arg_string(entry, "plugin");
|
||||
PluginDescriptor descriptor;
|
||||
if (PluginManager::instance().try_get_plugin_descriptor(key, descriptor) && !descriptor.name.empty())
|
||||
return descriptor.name;
|
||||
return key;
|
||||
}
|
||||
// TRN Agent Activity pane: automation whose source the app doesn't know.
|
||||
return _u8L("Automation");
|
||||
}
|
||||
|
||||
// The first line of `text`, shortened.
|
||||
std::string first_line(const std::string& text) { return Mcp::shorten(text, 160); }
|
||||
|
||||
} // namespace
|
||||
|
||||
// The panel's dock pane: a web view on the page, hidden from the automation tools with everything inside it.
|
||||
class AgentActivityPane : public wxPanel
|
||||
{
|
||||
public:
|
||||
AgentActivityPane(wxWindow* parent, AgentActivityPanel& owner);
|
||||
~AgentActivityPane() override;
|
||||
AgentActivityPane(const AgentActivityPane&) = delete;
|
||||
AgentActivityPane& operator=(const AgentActivityPane&) = delete;
|
||||
|
||||
// HandleStudio(payload) on the page, after the current event and only while the pane lives.
|
||||
void send(const json& payload);
|
||||
|
||||
private:
|
||||
AgentActivityPanel& m_owner;
|
||||
wxWebView* m_web = nullptr;
|
||||
wxFileName m_page;
|
||||
std::shared_ptr<std::atomic<bool>> m_alive = std::make_shared<std::atomic<bool>>(true);
|
||||
};
|
||||
|
||||
AgentActivityPane::AgentActivityPane(wxWindow* parent, AgentActivityPanel& owner)
|
||||
: wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, Mcp::kHiddenFromAutomation), m_owner(owner)
|
||||
{
|
||||
const fs::path page = fs::path(resources_dir()) / "web" / "dialog" / "AgentActivity" / "index.html";
|
||||
m_page = wxFileName(from_path(page));
|
||||
m_web = WebViewHostDialog::create_pane_web_view(
|
||||
this, page, page_strings(), m_alive, [owner = &m_owner](const json& payload) { owner->handle(payload); },
|
||||
// The page goes nowhere but its own loads.
|
||||
[this](wxWebViewEvent& event) {
|
||||
if (WebViewHostDialog::own_page_navigation(event.GetURL(), m_page))
|
||||
event.Skip();
|
||||
else
|
||||
event.Veto();
|
||||
});
|
||||
}
|
||||
|
||||
AgentActivityPane::~AgentActivityPane()
|
||||
{
|
||||
m_alive->store(false);
|
||||
m_owner.pane_destroyed(this);
|
||||
}
|
||||
|
||||
void AgentActivityPane::send(const json& payload)
|
||||
{
|
||||
wxString script = "HandleStudio(" + wxString::FromUTF8(payload.dump(-1, ' ', false, json::error_handler_t::replace)) + ")";
|
||||
wxGetApp().CallAfter([this, script = std::move(script), alive = m_alive] {
|
||||
if (alive->load() && m_web != nullptr)
|
||||
WebView::RunScript(m_web, script);
|
||||
});
|
||||
}
|
||||
|
||||
AgentActivityPanel::AgentActivityPanel() : m_alive(std::make_shared<std::atomic<bool>>(true))
|
||||
{
|
||||
m_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { refresh(); });
|
||||
// The pane comes back after a rebuild once the old main window is gone, as the Run Script panel's does.
|
||||
wxGetApp().Bind(wxEVT_IDLE, [this, alive = m_alive](wxIdleEvent& event) {
|
||||
event.Skip();
|
||||
if (!alive->load() || !std::exchange(m_rebuild_pending, false))
|
||||
return;
|
||||
wxGetApp().CallAfter([this, alive] {
|
||||
if (alive->load() && m_wanted && m_pane == nullptr)
|
||||
show();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
AgentActivityPanel::~AgentActivityPanel()
|
||||
{
|
||||
m_alive->store(false);
|
||||
m_timer.Stop();
|
||||
// The panel goes at exit, before the runtime: nothing is recorded any more.
|
||||
if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) {
|
||||
runtime->activity().set_recording(false);
|
||||
runtime->set_activity_listener({});
|
||||
}
|
||||
}
|
||||
|
||||
void AgentActivityPanel::set_wanted(bool wanted)
|
||||
{
|
||||
m_wanted = wanted;
|
||||
// The log records while the person has the pane open, docked on another tab and across a main-window rebuild too.
|
||||
if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started())
|
||||
runtime->activity().set_recording(wanted);
|
||||
}
|
||||
|
||||
void AgentActivityPanel::toggle()
|
||||
{
|
||||
if (on_screen()) {
|
||||
set_wanted(false);
|
||||
if (Plater* plater = wxGetApp().plater(); plater != nullptr)
|
||||
plater->show_dock_pane(m_pane, false);
|
||||
} else
|
||||
show();
|
||||
}
|
||||
|
||||
void AgentActivityPanel::show()
|
||||
{
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (frame == nullptr || plater == nullptr)
|
||||
return;
|
||||
// The log lives in the automation runtime, started here without the network endpoint when nothing has started it.
|
||||
Mcp::AutomationRuntime* runtime = wxGetApp().automation();
|
||||
if (runtime == nullptr)
|
||||
return;
|
||||
runtime->set_activity_listener([this, alive = m_alive] {
|
||||
if (alive->load())
|
||||
changed();
|
||||
});
|
||||
set_wanted(true);
|
||||
// Docked, the pane shows on Prepare and Preview only; floated, on every tab.
|
||||
const bool floating = m_pane != nullptr && plater->is_dock_pane_floating(m_pane);
|
||||
if (!floating && !frame->is_prepare_or_preview_tab())
|
||||
frame->select_tab(wxString(TAB_ID_PREPARE));
|
||||
if (m_pane == nullptr) {
|
||||
m_pane = new AgentActivityPane(plater, *this);
|
||||
plater->add_dock_pane(
|
||||
m_pane, "agent_activity", _L("Agent Activity"), "right", wxSize(420, 640),
|
||||
[this, alive = m_alive] {
|
||||
if (alive->load())
|
||||
set_wanted(false);
|
||||
},
|
||||
true, true);
|
||||
} else
|
||||
plater->show_dock_pane(m_pane, true);
|
||||
refresh();
|
||||
}
|
||||
|
||||
bool AgentActivityPanel::on_screen() const { return m_pane != nullptr && m_pane->IsShownOnScreen(); }
|
||||
|
||||
void AgentActivityPanel::forget_pane()
|
||||
{
|
||||
m_pane = nullptr;
|
||||
m_page_ready = false;
|
||||
m_version = 0;
|
||||
}
|
||||
|
||||
void AgentActivityPanel::pane_destroyed(AgentActivityPane* pane)
|
||||
{
|
||||
if (m_pane == pane)
|
||||
forget_pane();
|
||||
}
|
||||
|
||||
void AgentActivityPanel::main_window_closing()
|
||||
{
|
||||
m_timer.Stop();
|
||||
forget_pane();
|
||||
}
|
||||
|
||||
void AgentActivityPanel::main_window_rebuilt()
|
||||
{
|
||||
m_rebuild_pending = m_wanted;
|
||||
if (m_rebuild_pending)
|
||||
wxWakeUpIdle();
|
||||
}
|
||||
|
||||
void AgentActivityPanel::handle(const json& payload)
|
||||
{
|
||||
const std::string command = Mcp::arg_string(payload, "command");
|
||||
if (command == "ready") {
|
||||
m_page_ready = true;
|
||||
m_version = 0;
|
||||
refresh();
|
||||
} else if (command == "clear") {
|
||||
if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started())
|
||||
runtime->activity().clear();
|
||||
} else if (command == "copy") {
|
||||
if (wxTheClipboard->Open()) {
|
||||
wxTheClipboard->SetData(new wxTextDataObject(wxString::FromUTF8(Mcp::arg_string(payload, "text"))));
|
||||
wxTheClipboard->Close();
|
||||
}
|
||||
} else if (command == "open_file" || command == "show_file") {
|
||||
// A file of an entry's result, named by the entry and its place in the list the page was given, never by a path:
|
||||
// the image opens in the system's viewer, as Action Replay opens one, and any file shows in its folder.
|
||||
const auto id = payload.find("id");
|
||||
const auto index = payload.find("index");
|
||||
if (id == payload.end() || !id->is_number_unsigned() || index == payload.end() || !index->is_number_unsigned())
|
||||
return;
|
||||
const auto files = m_files.find(id->get<uint64_t>());
|
||||
if (files == m_files.end() || index->get<uint64_t>() >= files->second.size())
|
||||
return;
|
||||
const std::string& path = files->second[index->get<std::size_t>()];
|
||||
if (command == "open_file")
|
||||
wxLaunchDefaultApplication(from_u8(path));
|
||||
else
|
||||
desktop_open_any_folder(Mcp::path_to_utf8(Mcp::path_from_utf8(path).parent_path()));
|
||||
}
|
||||
}
|
||||
|
||||
void AgentActivityPanel::changed()
|
||||
{
|
||||
if (m_timer.IsRunning())
|
||||
return;
|
||||
const auto since = std::chrono::steady_clock::now() - m_last_refresh;
|
||||
if (since >= kRefreshEvery)
|
||||
refresh();
|
||||
else
|
||||
m_timer.StartOnce(int(std::chrono::duration_cast<std::chrono::milliseconds>(kRefreshEvery - since).count()) + 1);
|
||||
}
|
||||
|
||||
void AgentActivityPanel::refresh()
|
||||
{
|
||||
if (m_pane == nullptr || !m_page_ready)
|
||||
return;
|
||||
// A pane off screen reads nothing, and the log reports no more changes until it is read: while the pane is wanted
|
||||
// (docked off Prepare and Preview, the app's window minimized), it looks again until it shows.
|
||||
if (!on_screen()) {
|
||||
if (m_wanted && !m_timer.IsRunning())
|
||||
m_timer.StartOnce(int(kOffScreenRetry.count()));
|
||||
return;
|
||||
}
|
||||
Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started();
|
||||
if (runtime == nullptr)
|
||||
return;
|
||||
m_last_refresh = std::chrono::steady_clock::now();
|
||||
const json changes = runtime->activity().changes_since(m_version);
|
||||
// The page holds nothing yet at version 0.
|
||||
const bool reset = m_version == 0 || changes.value("reset", false);
|
||||
m_version = changes.value("version", uint64_t(0));
|
||||
json entries = json::array();
|
||||
for (const json& entry : changes["entries"]) {
|
||||
// Wording runs on the UI thread, where an exception would end the app: an entry it fails on shows by its tool.
|
||||
try {
|
||||
entries.push_back(page_entry(entry));
|
||||
} catch (const std::exception&) {
|
||||
json plain = entry;
|
||||
plain.erase("args");
|
||||
plain["title"] = Mcp::arg_string(entry, "tool");
|
||||
plain["what"] = "";
|
||||
plain["source_label"] = source_label(entry);
|
||||
plain["flags"] = json::array();
|
||||
entries.push_back(std::move(plain));
|
||||
}
|
||||
}
|
||||
for (const json& id : changes["removed"]) {
|
||||
m_files.erase(id.get<uint64_t>());
|
||||
m_thumbs.erase(id.get<uint64_t>());
|
||||
}
|
||||
if (!reset && entries.empty() && changes["removed"].empty())
|
||||
return;
|
||||
m_pane->send({{"command", "entries"}, {"reset", reset}, {"entries", std::move(entries)}, {"removed", changes["removed"]}});
|
||||
}
|
||||
|
||||
json AgentActivityPanel::page_entry(const json& entry)
|
||||
{
|
||||
json out = entry;
|
||||
json args = out.contains("args") ? std::move(out["args"]) : json::object();
|
||||
const json& request = entry["request"];
|
||||
const std::string kind = Mcp::arg_string(entry, "kind");
|
||||
const std::string tool = Mcp::arg_string(entry, "tool");
|
||||
out.erase("args");
|
||||
out["source_label"] = source_label(entry);
|
||||
out["flags"] = json::array();
|
||||
if (kind == "dialog") {
|
||||
// TRN Agent Activity pane: the title of a step where an auto-answer rule answered a dialog.
|
||||
out["title"] = _u8L("Answered a dialog");
|
||||
out["what"] = Mcp::arg_string(request, "title");
|
||||
} else if (kind == "work") {
|
||||
const std::string work = Mcp::arg_string(request, "work");
|
||||
const std::string file = Mcp::path_to_utf8(Mcp::path_from_utf8(Mcp::arg_string(request, "file")).filename());
|
||||
const std::string title = Mcp::arg_string(request, "title");
|
||||
const int cell = request.is_object() ? request.value("cell", 0) : 0;
|
||||
if (work == "file") {
|
||||
out["title"] = _u8L("Run all");
|
||||
out["what"] = file;
|
||||
} else if (work == "console") {
|
||||
// TRN Agent Activity pane: the title of a step where a person ran a line in the Run Script panel's console.
|
||||
out["title"] = _u8L("Run a console line");
|
||||
out["what"] = first_line(Mcp::arg_string(request, "code"));
|
||||
} else {
|
||||
// TRN Agent Activity pane: the title of a step where a person ran a cell in the Run Script panel.
|
||||
out["title"] = _u8L("Run a cell");
|
||||
// TRN Agent Activity pane: the cell a person ran. %1% is the script's file name, %2% the cell's number, %3% its title.
|
||||
out["what"] = title.empty() ? format(_u8L("%1%, cell %2%"), file, cell) : format(_u8L("%1%, cell %2%: %3%"), file, cell, title);
|
||||
}
|
||||
} else {
|
||||
const std::shared_ptr<const NativeCommand> def = NativeCommands::instance().lookup(tool);
|
||||
if (def == nullptr) {
|
||||
out["title"] = tool;
|
||||
out["what"] = "";
|
||||
} else {
|
||||
// The arguments of a call the protocol refused were never checked, and the wording reads them by type: what
|
||||
// it can't read leaves the call titled by its tool, as one the catalog doesn't know.
|
||||
try {
|
||||
// Worded as the recording captions word the call.
|
||||
const auto [title, titled] = shown_title(NativeCommands::instance(), *def, args);
|
||||
const char* context = title_context(*titled);
|
||||
out["title"] = into_u8(context != nullptr ? I18N::translate(title, context) : wxGetTranslation(from_u8(title)));
|
||||
out["what"] = Mcp::caption_detail(tool, args);
|
||||
// A run's own steps show what they do: read before it runs, a run given no file reads as doing everything.
|
||||
if (!entry.value("read", false) && tool != "replay_run" && tool != "script_run") {
|
||||
Mcp::ReplayStep step;
|
||||
step.tool = tool;
|
||||
step.args = args.is_object() ? std::move(args) : json::object();
|
||||
for (const Mcp::StepFlag flag :
|
||||
Mcp::describe_step(NativeCommands::instance(), step, Mcp::Replay{}, Mcp::ReplayContext{}).flags)
|
||||
out["flags"].push_back(Mcp::flag_id(flag));
|
||||
}
|
||||
} catch (const std::exception&) {
|
||||
out["title"] = tool;
|
||||
out["what"] = "";
|
||||
out["flags"] = json::array();
|
||||
}
|
||||
}
|
||||
}
|
||||
// A failure the log read from a run's result, which the call itself reported as a success.
|
||||
if (const json failure = entry.value("failure", json()); failure.contains("script")) {
|
||||
out["error"] = script_status_text(Mcp::arg_string(failure, "script"));
|
||||
} else if (failure.contains("why")) {
|
||||
const std::string why = Mcp::arg_string(failure, "why");
|
||||
if (const int step = failure.value("step", 0); step > 0)
|
||||
// TRN Agent Activity pane: why a replay failed. %1% is the number of the step that failed, %2% that step's
|
||||
// error, in English.
|
||||
out["error"] = why.empty() ? format(_u8L("Step %1% failed"), step) : format(_u8L("Step %1% failed: %2%"), step, why);
|
||||
else
|
||||
// TRN Agent Activity pane: a replay failed without saying which step.
|
||||
out["error"] = why.empty() ? _u8L("The replay failed.") : why;
|
||||
}
|
||||
// The files a finished call's result names, by name, and a screenshot's thumbnail, read once the call has written
|
||||
// them. A path the log masked names no file, and gets no link.
|
||||
const uint64_t id = entry.value("id", uint64_t(0));
|
||||
if (Mcp::arg_string(entry, "status") == "done") {
|
||||
auto files = m_files.find(id);
|
||||
if (files == m_files.end()) {
|
||||
std::vector<std::string> existing;
|
||||
for (const std::string& path : Mcp::result_files(entry["response"])) {
|
||||
boost::system::error_code ec;
|
||||
if (fs::is_regular_file(Mcp::path_from_utf8(path), ec))
|
||||
existing.push_back(path);
|
||||
}
|
||||
files = m_files.emplace(id, std::move(existing)).first;
|
||||
}
|
||||
if (!files->second.empty()) {
|
||||
out["files"] = json::array();
|
||||
for (const std::string& path : files->second)
|
||||
out["files"].push_back(Mcp::path_to_utf8(Mcp::path_from_utf8(path).filename()));
|
||||
}
|
||||
if (tool == "window_screenshot" && !files->second.empty()) {
|
||||
auto thumb = m_thumbs.find(id);
|
||||
if (thumb == m_thumbs.end())
|
||||
thumb = m_thumbs.emplace(id, screenshot_thumbnail(files->second.front())).first;
|
||||
if (!thumb->second.empty())
|
||||
out["thumb"] = thumb->second;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <wx/timer.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
class AgentActivityPane;
|
||||
|
||||
// The Agent Activity pane: a dock pane on the right of the 3D view (it can float, and floated it stays up on every tab)
|
||||
// whose page (resources/web/dialog/AgentActivity) lists, live, what automation does in the app while the pane is open:
|
||||
// the automation runtime's activity log (Mcp::ActivityLog), which records while the person has the pane open, with each
|
||||
// call's title and target worded as the recording captions word them. It opens only when the person opens it, from View
|
||||
// > Agent Activity or its Speed Dial action, and it only watches. One per app, owned by GUI_App, so it outlives the
|
||||
// pane, which a main-window rebuild (a language change) destroys and the panel builds again. The pane and everything in
|
||||
// it are hidden from the automation tools. UI thread.
|
||||
class AgentActivityPanel
|
||||
{
|
||||
public:
|
||||
AgentActivityPanel();
|
||||
~AgentActivityPanel();
|
||||
AgentActivityPanel(const AgentActivityPanel&) = delete;
|
||||
AgentActivityPanel& operator=(const AgentActivityPanel&) = delete;
|
||||
|
||||
// Hides the pane when it is on screen, else shows it, as View > Agent Activity and the Speed Dial do.
|
||||
void toggle();
|
||||
// Builds the pane on first use and shows it, selecting Prepare when the pane is docked and the current tab is
|
||||
// neither Prepare nor Preview.
|
||||
void show();
|
||||
// The pane's window is shown on screen.
|
||||
bool on_screen() const;
|
||||
|
||||
// MainFrame::shutdown(), before the dock panes go: the pane goes.
|
||||
void main_window_closing();
|
||||
// The end of GUI_App::recreate_GUI(): the pane comes back if it was on screen, once the old main window is deleted.
|
||||
void main_window_rebuilt();
|
||||
|
||||
private:
|
||||
friend class AgentActivityPane;
|
||||
|
||||
void pane_destroyed(AgentActivityPane* pane);
|
||||
// The pane is gone (or going with the main window): the page with it.
|
||||
void forget_pane();
|
||||
// The person has the pane open or not: the activity log records while they do.
|
||||
void set_wanted(bool wanted);
|
||||
void handle(const nlohmann::json& payload);
|
||||
// The log changed: the page gets the changes at most ten times a second, and only while the pane is on screen.
|
||||
void changed();
|
||||
void refresh();
|
||||
// A log entry as the page shows it: its title, target, source and effects in the UI's language, a screenshot's
|
||||
// thumbnail, and no arguments.
|
||||
nlohmann::json page_entry(const nlohmann::json& entry);
|
||||
|
||||
std::shared_ptr<std::atomic<bool>> m_alive;
|
||||
AgentActivityPane* m_pane = nullptr;
|
||||
bool m_wanted = false;
|
||||
// The main window was rebuilt and the pane is wanted back: built at the next idle.
|
||||
bool m_rebuild_pending = false;
|
||||
// The page has loaded and holds the log as of this version (0: nothing yet).
|
||||
bool m_page_ready = false;
|
||||
uint64_t m_version = 0;
|
||||
wxTimer m_timer;
|
||||
std::chrono::steady_clock::time_point m_last_refresh{};
|
||||
// A finished entry's files that exist, from its result (Mcp::result_files()), which the page opens by their place in
|
||||
// the list; and a screenshot entry's thumbnail. Each made once.
|
||||
std::map<uint64_t, std::vector<std::string>> m_files;
|
||||
std::map<uint64_t, std::string> m_thumbs;
|
||||
};
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -127,12 +127,13 @@ public:
|
||||
};
|
||||
|
||||
// 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.
|
||||
// journal; tests call the command's function directly. `origin` says who made the call, for the core's
|
||||
// observers (Mcp::CallObserver::call_started); null when nothing says.
|
||||
class ToolCaller
|
||||
{
|
||||
public:
|
||||
virtual ~ToolCaller() = default;
|
||||
virtual ToolResult call(const NativeCommand& command, const nlohmann::json& args) = 0;
|
||||
virtual ToolResult call(const NativeCommand& command, const nlohmann::json& args, const nlohmann::json& origin = nlohmann::json()) = 0;
|
||||
};
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -195,6 +195,7 @@
|
||||
#include "3DScene.hpp"
|
||||
#include "MainFrame.hpp"
|
||||
#include "Plater.hpp"
|
||||
#include "AgentActivityPanel.hpp"
|
||||
#include "RunScriptPanel.hpp"
|
||||
#include "GLCanvas3D.hpp"
|
||||
#include "EncodedFilament.hpp"
|
||||
@@ -5133,6 +5134,8 @@ void GUI_App::recreate_GUI(const wxString &msg_name)
|
||||
m_automation->resume();
|
||||
if (m_run_script_panel)
|
||||
m_run_script_panel->main_window_rebuilt();
|
||||
if (m_agent_activity_panel)
|
||||
m_agent_activity_panel->main_window_rebuilt();
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "recreate_GUI exit";
|
||||
}
|
||||
@@ -8602,8 +8605,9 @@ void GUI_App::stop_automation()
|
||||
|
||||
void GUI_App::destroy_automation()
|
||||
{
|
||||
// The Run Script panel's session is a job of the runtime: it goes first.
|
||||
// The Run Script panel's session is a job of the runtime, and the Agent Activity pane listens to its log: they go first.
|
||||
m_run_script_panel.reset();
|
||||
m_agent_activity_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.
|
||||
@@ -8625,6 +8629,13 @@ RunScriptPanel& GUI_App::run_script_panel()
|
||||
return *m_run_script_panel;
|
||||
}
|
||||
|
||||
AgentActivityPanel& GUI_App::agent_activity_panel()
|
||||
{
|
||||
if (!m_agent_activity_panel)
|
||||
m_agent_activity_panel = std::make_unique<AgentActivityPanel>();
|
||||
return *m_agent_activity_panel;
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
static const wxLanguageInfo* linux_get_existing_locale_language(const wxLanguageInfo* language,
|
||||
const wxLanguageInfo* system_language)
|
||||
|
||||
@@ -100,6 +100,7 @@ class ObjectSettings;
|
||||
class ObjectList;
|
||||
class ObjectLayers;
|
||||
class Plater;
|
||||
class AgentActivityPanel;
|
||||
class RunScriptPanel;
|
||||
class ParamsPanel;
|
||||
class NotificationManager;
|
||||
@@ -397,6 +398,7 @@ private:
|
||||
// opened it.
|
||||
std::unique_ptr<Mcp::McpEndpoint> m_mcp_endpoint;
|
||||
std::unique_ptr<RunScriptPanel> m_run_script_panel;
|
||||
std::unique_ptr<AgentActivityPanel> m_agent_activity_panel;
|
||||
bool m_show_gcode_window{true};
|
||||
boost::thread m_check_network_thread;
|
||||
public:
|
||||
@@ -708,6 +710,10 @@ public:
|
||||
// its session, goes away.
|
||||
RunScriptPanel& run_script_panel();
|
||||
RunScriptPanel* run_script_panel_if_built() { return m_run_script_panel.get(); }
|
||||
// The Agent Activity pane's controller, built on first use and kept until the automation runtime, whose activity
|
||||
// log it shows, goes away.
|
||||
AgentActivityPanel& agent_activity_panel();
|
||||
AgentActivityPanel* agent_activity_panel_if_built() { return m_agent_activity_panel.get(); }
|
||||
|
||||
void on_show_check_privacy_dlg(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER);
|
||||
void show_check_privacy_dlg(wxCommandEvent& evt);
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
#include "PrintHostDialogs.hpp"
|
||||
#include "RecordingIndicator.hpp"
|
||||
#include "ActionReplayDialog.hpp"
|
||||
#include "AgentActivityPanel.hpp"
|
||||
#include "RunScriptPanel.hpp"
|
||||
#include "CodeEditorWindow.hpp"
|
||||
#include "NativeCommands.hpp"
|
||||
@@ -1378,6 +1379,8 @@ void MainFrame::shutdown()
|
||||
m_plugin_pages->shutdown();
|
||||
if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built())
|
||||
panel->main_window_closing();
|
||||
if (AgentActivityPanel* panel = wxGetApp().agent_activity_panel_if_built())
|
||||
panel->main_window_closing();
|
||||
if (m_plater != nullptr)
|
||||
m_plater->remove_dock_panes();
|
||||
#ifdef SLIC3R_CAD
|
||||
@@ -3701,6 +3704,15 @@ void MainFrame::init_menubar_as_editor()
|
||||
[]() { return wxGetApp().app_config->get("show_imex_toolhead_boxes") != "false"; },
|
||||
this);
|
||||
|
||||
append_menu_check_item(
|
||||
viewMenu, wxID_ANY, _L("Agent Activity"), _L("Show or hide the Agent Activity pane, which lists what automation does in the app"),
|
||||
[](wxCommandEvent&) { wxGetApp().agent_activity_panel().toggle(); }, this, []() { return true; },
|
||||
[]() {
|
||||
AgentActivityPanel* panel = wxGetApp().agent_activity_panel_if_built();
|
||||
return panel != nullptr && panel->on_screen();
|
||||
},
|
||||
this);
|
||||
|
||||
append_menu_item(
|
||||
viewMenu, wxID_ANY, _L("Reset Window Layout"), _L("Reset to default window layout"),
|
||||
[this](wxCommandEvent&) { m_plater->reset_window_layout(); }, "", this,
|
||||
|
||||
@@ -0,0 +1,962 @@
|
||||
#include "ActivityLog.hpp"
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
#include "McpReplay.hpp"
|
||||
#include "VideoOverlay.hpp"
|
||||
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t now_ms()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
std::string text_of(const json& v, const char* key)
|
||||
{
|
||||
return v.is_object() && v.contains(key) && v[key].is_string() ? v[key].get<std::string>() : std::string();
|
||||
}
|
||||
|
||||
// `value`, or what stands for it once it is over ActivityLog::kMaxBytes as JSON. Text that is not UTF-8 is counted as the
|
||||
// pane sends it, with the bad bytes replaced.
|
||||
json capped(json value)
|
||||
{
|
||||
const std::size_t bytes = value.dump(-1, ' ', false, json::error_handler_t::replace).size();
|
||||
if (bytes <= ActivityLog::kMaxBytes)
|
||||
return value;
|
||||
return {{"truncated", true}, {"bytes", bytes}};
|
||||
}
|
||||
|
||||
// Whether `value` nests arrays and objects deeper than ActivityLog::kMaxDepth, found without recursing.
|
||||
bool too_deep(const json& value)
|
||||
{
|
||||
std::vector<std::pair<const json*, int>> stack{{&value, 0}};
|
||||
while (!stack.empty()) {
|
||||
const auto [v, depth] = stack.back();
|
||||
stack.pop_back();
|
||||
if (!v->is_structured())
|
||||
continue;
|
||||
if (depth >= ActivityLog::kMaxDepth)
|
||||
return true;
|
||||
for (const json& item : *v)
|
||||
stack.emplace_back(&item, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// `value` as the log takes it in: itself, or the mask when it nests too deep for the log to read it, since masking and
|
||||
// reading what calls hide walk it recursively; what can't be read is not shown.
|
||||
json readable(const json& value) { return too_deep(value) ? json(kMask) : value; }
|
||||
|
||||
// As readable(), for a value whose depth `deep` tells, without a copy.
|
||||
const json& readable(const json& value, bool deep)
|
||||
{
|
||||
static const json mask(kMask);
|
||||
return deep ? mask : value;
|
||||
}
|
||||
|
||||
// The JSON a string holds when it is JSON text, an object or an array, comments allowed as a replay's text allows them;
|
||||
// null for any other text. Neither the parser nor destroying what it made recurses, but copying it would: it is only
|
||||
// moved until too_deep() has passed it.
|
||||
json json_text(const std::string& text)
|
||||
{
|
||||
const std::size_t first = text.find_first_not_of(" \t\r\n");
|
||||
if (first == std::string::npos || (text[first] != '{' && text[first] != '[' && text[first] != '/'))
|
||||
return {};
|
||||
json parsed = json::parse(text, nullptr, false, true);
|
||||
if (!parsed.is_structured())
|
||||
return {};
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// `value` masked as mask_hidden() masks it, with each string that is JSON text (a replay given as its text) read as JSON:
|
||||
// when that masks something, it is written out again masked, so that what the text escapes (h for h) is masked too.
|
||||
// JSON text too deep to read is not shown.
|
||||
json masked(json value, const std::vector<std::string>& values)
|
||||
{
|
||||
const std::function<void(json&)> read_texts = [&](json& v) {
|
||||
if (v.is_structured()) {
|
||||
for (json& item : v)
|
||||
read_texts(item);
|
||||
return;
|
||||
}
|
||||
if (!v.is_string())
|
||||
return;
|
||||
const json parsed = json_text(v.get_ref<const std::string&>());
|
||||
if (parsed.is_null())
|
||||
return;
|
||||
if (too_deep(parsed)) {
|
||||
v = kMask;
|
||||
return;
|
||||
}
|
||||
json out = parsed;
|
||||
read_texts(out);
|
||||
out = mask_hidden(std::move(out), values);
|
||||
if (out != parsed)
|
||||
v = out.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
};
|
||||
read_texts(value);
|
||||
return mask_hidden(std::move(value), values);
|
||||
}
|
||||
|
||||
// `hidden` with each value once: masking looks for every value in every string.
|
||||
std::vector<std::string> unique_values(std::vector<std::string> hidden)
|
||||
{
|
||||
std::sort(hidden.begin(), hidden.end());
|
||||
hidden.erase(std::unique(hidden.begin(), hidden.end()), hidden.end());
|
||||
return hidden;
|
||||
}
|
||||
|
||||
// A payload as an entry shows it: past kMaxBytes as JSON, what stands for its size, which shows nothing to mask; the mask
|
||||
// when checking it against what it must hide would scan more than kMaxMaskWork bytes, holding up the call's thread and
|
||||
// the pane, which waits for the log; else masked.
|
||||
json shown(json value, const std::vector<std::string>& hidden)
|
||||
{
|
||||
const std::size_t bytes = value.dump(-1, ' ', false, json::error_handler_t::replace).size();
|
||||
if (bytes > ActivityLog::kMaxBytes)
|
||||
return {{"truncated", true}, {"bytes", bytes}};
|
||||
const std::vector<std::string> values = unique_values(hidden);
|
||||
if (values.size() * bytes > ActivityLog::kMaxMaskWork)
|
||||
return kMask;
|
||||
// Masking may lengthen it: a short value becomes the mask.
|
||||
return capped(masked(std::move(value), values));
|
||||
}
|
||||
|
||||
// An error's text as an entry shows it: masked, then cut to kMaxBytes; the mask past kMaxMaskWork, as for a payload.
|
||||
std::string shown_text(const std::string& text, const std::vector<std::string>& hidden)
|
||||
{
|
||||
const std::vector<std::string> values = unique_values(hidden);
|
||||
if (values.size() * text.size() > ActivityLog::kMaxMaskWork)
|
||||
return kMask;
|
||||
return shorten(masked(json(text), values).get<std::string>(), ActivityLog::kMaxBytes);
|
||||
}
|
||||
|
||||
// A call's response as JSON: what it returned, or its error with the details it gave; data that nests too deep
|
||||
// (`deep`), the mask.
|
||||
json response_of(const ToolResult& r, bool deep)
|
||||
{
|
||||
const json& data = readable(r.data, deep);
|
||||
if (!r.is_error)
|
||||
return data;
|
||||
json out{{"isError", true}, {"message", r.message}};
|
||||
if (!r.data.is_null() && !(r.data.is_object() && r.data.empty()))
|
||||
out["details"] = data;
|
||||
return out;
|
||||
}
|
||||
|
||||
void nested_hidden(const json& value, std::vector<std::string>& out, std::size_t& budget);
|
||||
|
||||
// A replay given as an object, or as its JSON text, read; null for anything else, and for one too deep to read, whose
|
||||
// text masked() then doesn't show.
|
||||
json replay_of(const json& value)
|
||||
{
|
||||
if (value.is_string()) {
|
||||
json replay = json_text(value.get<std::string>());
|
||||
if (!replay.is_object() || too_deep(replay))
|
||||
return {};
|
||||
return replay;
|
||||
}
|
||||
if (!value.is_object() || too_deep(value))
|
||||
return {};
|
||||
return value;
|
||||
}
|
||||
|
||||
// The text a replay puts in for a placeholder: a string as it is, any other value as JSON.
|
||||
std::string var_text(const json& var)
|
||||
{
|
||||
return var.is_string() ? var.get<std::string>() : var.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
// The placeholders `text` holds (`${BODY}`), by their bodies, in order: "vars.p", "env:HOME", ...
|
||||
std::vector<std::string> placeholders(const std::string& text)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
for (std::size_t at = text.find("${"); at != std::string::npos; at = text.find("${", at + 2)) {
|
||||
const std::size_t end = text.find('}', at + 2);
|
||||
if (end == std::string::npos)
|
||||
break;
|
||||
out.push_back(text.substr(at + 2, end - at - 2));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The values a replay puts in for the placeholders `texts` hold, and for those the values hold in turn, however long the
|
||||
// chain, each once. A null puts in nothing to hide.
|
||||
std::vector<json> named_values(std::vector<std::string> texts, const Replay& replay, const ReplayContext& context)
|
||||
{
|
||||
std::set<std::string> seen;
|
||||
std::vector<json> out;
|
||||
while (!texts.empty()) {
|
||||
const std::string text = std::move(texts.back());
|
||||
texts.pop_back();
|
||||
for (const std::string& body : placeholders(text))
|
||||
if (seen.insert(body).second)
|
||||
if (std::optional<json> value = resolve_placeholder(body, replay, context); value && !value->is_null()) {
|
||||
texts.push_back(var_text(*value));
|
||||
out.push_back(std::move(*value));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void call_hidden(const std::string& tool, const json& args, std::vector<std::string>& out, std::size_t& budget);
|
||||
|
||||
// Adds to `out` what a replay must not show as it runs: every value of a sensitive key anywhere in it, its variables
|
||||
// included; what each step hides, as written and with its placeholders put in as the replay puts them in
|
||||
// (substitute_args()), with the replay's own variables (which its text holds) and with `vars` the caller's, which win;
|
||||
// and each value a placeholder in a hidden value puts in, directly or through another one (a variable, an environment
|
||||
// variable), as written, put in and by every string and number inside it, which the replay's and the caller's `vars`
|
||||
// show apart from the text it goes into ("password=${vars.p}"). What the placeholders put in is charged to `budget`
|
||||
// (substitute_lenient()).
|
||||
void replay_hidden(const json& replay, const json& vars, std::vector<std::string>& out, std::size_t& budget)
|
||||
{
|
||||
if (!replay.is_object())
|
||||
return;
|
||||
const std::vector<std::string> sensitive = hidden_values({}, replay);
|
||||
out.insert(out.end(), sensitive.begin(), sensitive.end());
|
||||
Replay own;
|
||||
if (replay.contains("vars") && replay["vars"].is_object())
|
||||
own.vars = replay["vars"];
|
||||
Replay all;
|
||||
all.vars = own.vars;
|
||||
if (vars.is_object() && !too_deep(vars))
|
||||
all.vars.update(vars);
|
||||
if (!replay.contains("steps") || !replay["steps"].is_array())
|
||||
return;
|
||||
// The log has no saved jobs or folders: those placeholders put in nothing secret.
|
||||
const ReplayContext context;
|
||||
static const json no_args = json::object();
|
||||
for (const json& step : replay["steps"]) {
|
||||
if (!step.is_object() || !step.contains("tool") || !step["tool"].is_string())
|
||||
continue;
|
||||
const std::string& tool = step["tool"].get_ref<const std::string&>();
|
||||
const json& args = step.contains("args") ? step["args"] : no_args;
|
||||
std::vector<std::string> written;
|
||||
call_hidden(tool, args, written, budget);
|
||||
out.insert(out.end(), written.begin(), written.end());
|
||||
for (const Replay* set : {&own, &all}) {
|
||||
call_hidden(tool, substitute_args_lenient(tool, args, *set, context, budget), out, budget);
|
||||
for (const json& value : named_values(written, *set, context)) {
|
||||
const json put = substitute_lenient(value, *set, context, budget);
|
||||
out.push_back(var_text(value));
|
||||
out.push_back(var_text(put));
|
||||
scalars(value, out);
|
||||
scalars(put, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Adds to `out` what a call of `tool` with `args` hides by its own tool's rule: its hidden values and, for a
|
||||
// replay_run, what its replay, given as an object or as its JSON text, hides with its variables.
|
||||
void tool_hidden(const std::string& tool, const json& args, std::vector<std::string>& out, std::size_t& budget)
|
||||
{
|
||||
const std::vector<std::string> hidden = hidden_values(tool, args);
|
||||
out.insert(out.end(), hidden.begin(), hidden.end());
|
||||
if (tool == "replay_run" && args.is_object() && args.contains("replay"))
|
||||
replay_hidden(replay_of(args["replay"]), args.contains("vars") ? args["vars"] : json(), out, budget);
|
||||
}
|
||||
|
||||
// Adds to `out` what the calls written inside `value` must not show: every object with a `tool` and its `args`, as a
|
||||
// call, a replay's steps, a tool_call's target and a replay's result write them, by its own tool's rule
|
||||
// (tool_hidden()), with what their replays' placeholders put in charged to `budget`.
|
||||
void nested_hidden(const json& value, std::vector<std::string>& out, std::size_t& budget)
|
||||
{
|
||||
if (value.is_object()) {
|
||||
if (value.contains("tool") && value["tool"].is_string() && value.contains("args"))
|
||||
tool_hidden(value["tool"].get_ref<const std::string&>(), value["args"], out, budget);
|
||||
for (const auto& [key, member] : value.items())
|
||||
nested_hidden(member, out, budget);
|
||||
} else if (value.is_array()) {
|
||||
for (const json& item : value)
|
||||
nested_hidden(item, out, budget);
|
||||
}
|
||||
}
|
||||
|
||||
void nested_hidden(const json& value, std::vector<std::string>& out)
|
||||
{
|
||||
std::size_t budget = ActivityLog::kMaxPutIn;
|
||||
nested_hidden(value, out, budget);
|
||||
}
|
||||
|
||||
// Adds to `out` what a call of `tool` with `args` must not show: its own hidden values and those of the calls written
|
||||
// inside its arguments.
|
||||
void call_hidden(const std::string& tool, const json& args, std::vector<std::string>& out, std::size_t& budget)
|
||||
{
|
||||
tool_hidden(tool, args, out, budget);
|
||||
nested_hidden(args, out, budget);
|
||||
}
|
||||
|
||||
std::vector<std::string> call_hidden(const std::string& tool, const json& args)
|
||||
{
|
||||
std::vector<std::string> hidden;
|
||||
std::size_t budget = ActivityLog::kMaxPutIn;
|
||||
call_hidden(tool, args, hidden, budget);
|
||||
return hidden;
|
||||
}
|
||||
|
||||
// What a call's result repeats of the calls written in it (a replay's steps), for one not too deep to read.
|
||||
std::vector<std::string> repeated_hidden(const json& data, bool deep)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
if (!deep)
|
||||
nested_hidden(data, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// A run's failure that its tool reports in a successful result, for the pane: {message} for the message of a script
|
||||
// that raised, {script: status} for one that ended otherwise (stopped, out of time, Python unavailable, refused) or
|
||||
// without a message, which the pane words; {step, why} for a replay's failed step, without `step` when the result
|
||||
// names none. Null for none. A Python script that raised, was cancelled or ran out of time, and a replay whose step
|
||||
// failed, end without an error for their caller, which reads the outcome.
|
||||
json reported_failure(const std::string& tool, const json& data)
|
||||
{
|
||||
if (!data.is_object())
|
||||
return {};
|
||||
if (tool == "script_run" && data.contains("status") && data["status"].is_string() && data["status"] != "finished") {
|
||||
const std::string status = data["status"].get<std::string>();
|
||||
const std::string message = text_of(data, "message");
|
||||
// The runner's own message for a stop, a time-out or no Python is agent-facing; the pane says it in the UI's
|
||||
// language. A script's exception is its own text.
|
||||
const bool worded =
|
||||
message.empty() || status == "cancelled" || status == "timed_out" || status == "unavailable" || status == "refused";
|
||||
return worded ? json{{"script", status}} : json{{"message", message}};
|
||||
}
|
||||
if (tool == "replay_run" && data.contains("passed") && data["passed"] == false) {
|
||||
const int failed = data.contains("failed_step") && data["failed_step"].is_number_integer() ? data["failed_step"].get<int>() : 0;
|
||||
// The step by its number: a run of one step reports only that one.
|
||||
std::string why;
|
||||
if (failed > 0 && data.contains("steps") && data["steps"].is_array())
|
||||
for (const json& step : data["steps"])
|
||||
if (step.is_object() && step.contains("index") && step["index"] == failed) {
|
||||
why = text_of(step, "expect_failure");
|
||||
if (why.empty())
|
||||
why = text_of(step, "error");
|
||||
}
|
||||
json out{{"why", why}};
|
||||
if (failed > 0)
|
||||
out["step"] = failed;
|
||||
return out;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// `text` with the start of `value` masked where the text ends in it and then "...": ModalTracker cuts a long message
|
||||
// there, and a value can straddle the cut. A start shorter than three bytes is left, as mask_hidden() leaves a value that
|
||||
// short inside other text, so a value of three bytes or less has no start to mask.
|
||||
void mask_cut_start(std::string& text, const std::string& value)
|
||||
{
|
||||
static const std::string cut = "...";
|
||||
if (value.size() < 4 || text.size() < cut.size() || text.compare(text.size() - cut.size(), cut.size(), cut) != 0)
|
||||
return;
|
||||
const std::size_t body = text.size() - cut.size();
|
||||
// As it is, and as text that dumps JSON writes it, as mask_hidden() matches a value.
|
||||
std::string escaped;
|
||||
if (value.find_first_of("\"\\\b\f\n\r\t") != std::string::npos) {
|
||||
escaped = json(value).dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
escaped = escaped.substr(1, escaped.size() - 2);
|
||||
}
|
||||
const std::string* forms[] = {&value, &escaped};
|
||||
for (const std::string* form : forms)
|
||||
for (std::size_t n = std::min(form->size() - (form->empty() ? 0 : 1), body); n >= 3; --n)
|
||||
if (text.compare(body - n, n, *form, 0, n) == 0) {
|
||||
text.replace(body - n, n, kMask);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ActivityLog::ActivityLog(const JobRegistry& jobs, std::function<void()> changed) : m_jobs(jobs), m_changed(std::move(changed)) {}
|
||||
|
||||
ActivityLog::Entry& ActivityLog::add(Entry e)
|
||||
{
|
||||
e.id = m_next_id++;
|
||||
e.started = now_ms();
|
||||
const bool numbered = e.kind != "dialog";
|
||||
if (e.parent != 0) {
|
||||
const auto parent = m_entries.find(e.parent);
|
||||
if (parent == m_entries.end())
|
||||
e.parent = 0;
|
||||
else if (numbered)
|
||||
e.number = ++parent->second.nested;
|
||||
}
|
||||
if (e.parent == 0 && numbered)
|
||||
e.number = m_next_number++;
|
||||
e.args = shown(std::move(e.args), e.hidden);
|
||||
e.request = shown(std::move(e.request), e.hidden);
|
||||
touch(e);
|
||||
const uint64_t id = e.id;
|
||||
if (!e.job.empty())
|
||||
m_job_entries[e.job] = id;
|
||||
m_entries.emplace(id, std::move(e));
|
||||
trim();
|
||||
// The new entry is the newest of all and running or just failed; trim() drops older ones.
|
||||
return m_entries.at(id);
|
||||
}
|
||||
|
||||
void ActivityLog::finish(Entry& e, const ToolResult& result, bool unread, bool deep, const std::vector<std::string>& nested)
|
||||
{
|
||||
// A call whose own arguments couldn't be read can't be masked. One that reads a job repeats what that job's call
|
||||
// hid as it is now: its arguments may have been rewritten, or its record dropped, since this call started.
|
||||
e.withheld = unread;
|
||||
if (!e.reads_job.empty()) {
|
||||
const std::vector<std::string>* of_job = job_hidden(e.reads_job);
|
||||
if (of_job != nullptr)
|
||||
e.hidden.insert(e.hidden.end(), of_job->begin(), of_job->end());
|
||||
e.withheld = e.withheld || of_job == nullptr;
|
||||
}
|
||||
json response = response_of(result, deep);
|
||||
// A replay's result repeats its steps' arguments.
|
||||
e.hidden.insert(e.hidden.end(), nested.begin(), nested.end());
|
||||
json failure = result.is_error ? json{{"message", result.message}} : reported_failure(e.tool, result.data);
|
||||
// A result too deep to read still tells how the run went, from fields read without going down its deep branches, but
|
||||
// not why: its text may repeat what the log couldn't read to hide. The pane words the failure without it.
|
||||
if (!result.is_error && deep) {
|
||||
if (failure.contains("message"))
|
||||
failure = {{"script", text_of(result.data, "status")}};
|
||||
else if (failure.contains("why"))
|
||||
failure["why"] = "";
|
||||
}
|
||||
e.status = failure.is_null() ? "done" : "failed";
|
||||
if (!e.withheld) {
|
||||
e.response = shown(std::move(response), e.hidden);
|
||||
// The row shows the error's first line; the whole of it is in the response.
|
||||
if (failure.contains("message"))
|
||||
e.error = shown_text(failure["message"].get<std::string>(), e.hidden);
|
||||
else {
|
||||
if (failure.contains("why"))
|
||||
failure["why"] = shown_text(failure["why"].get<std::string>(), e.hidden);
|
||||
e.failure = std::move(failure);
|
||||
}
|
||||
}
|
||||
e.ended = now_ms();
|
||||
std::vector<std::string>().swap(e.hidden);
|
||||
touch(e);
|
||||
}
|
||||
|
||||
const std::vector<std::string>* ActivityLog::job_hidden(const std::string& job) const
|
||||
{
|
||||
const auto kept = m_job_hidden.find(job);
|
||||
return kept != m_job_hidden.end() ? &kept->second : nullptr;
|
||||
}
|
||||
|
||||
const ActivityLog::Entry* ActivityLog::job_entry(const std::string& job) const
|
||||
{
|
||||
const auto it = m_job_entries.find(job);
|
||||
const auto entry = it != m_job_entries.end() ? m_entries.find(it->second) : m_entries.end();
|
||||
return entry != m_entries.end() ? &entry->second : nullptr;
|
||||
}
|
||||
|
||||
void ActivityLog::keep_hidden(const std::string& job, const std::vector<std::string>& hidden, bool start)
|
||||
{
|
||||
auto it = m_job_hidden.find(job);
|
||||
if (it == m_job_hidden.end()) {
|
||||
// A record dropped since its call started is not made again with only part of what the call hid.
|
||||
if (!start)
|
||||
return;
|
||||
it = m_job_hidden.emplace(job, std::vector<std::string>()).first;
|
||||
m_job_hidden_order.push_back(job);
|
||||
}
|
||||
for (const std::string& v : hidden) {
|
||||
if (v.size() > kMaxBytes) {
|
||||
drop_hidden(job);
|
||||
return;
|
||||
}
|
||||
it->second.push_back(v);
|
||||
m_job_hidden_bytes += v.size();
|
||||
}
|
||||
while (!m_job_hidden_order.empty() && (m_job_hidden_order.size() > kMaxEntries || m_job_hidden_bytes > kMaxKeptHiddenBytes)) {
|
||||
drop_hidden(m_job_hidden_order.front());
|
||||
m_job_hidden_order.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityLog::drop_hidden(const std::string& job)
|
||||
{
|
||||
const auto record = m_job_hidden.find(job);
|
||||
if (record == m_job_hidden.end())
|
||||
return;
|
||||
for (const std::string& v : record->second)
|
||||
m_job_hidden_bytes -= v.size();
|
||||
m_job_hidden.erase(record);
|
||||
}
|
||||
|
||||
void ActivityLog::set_recording(bool on)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_recording = on;
|
||||
}
|
||||
|
||||
void ActivityLog::mark(const std::string& job, const std::string& parent, const json& origin)
|
||||
{
|
||||
if (job.empty() || m_marks.count(job) != 0)
|
||||
return;
|
||||
json marks;
|
||||
const std::string above = parent.empty() ? text_of(origin, "under") : parent;
|
||||
if (!above.empty())
|
||||
for (const std::string& up : m_jobs.ancestry(above))
|
||||
if (const auto it = m_marks.find(up); it != m_marks.end()) {
|
||||
marks = it->second;
|
||||
break;
|
||||
}
|
||||
if (marks.is_null()) {
|
||||
const std::string source = text_of(origin, "source");
|
||||
if (source == "person")
|
||||
marks = {{"person", true}};
|
||||
else if (source == "run_script" && parent.empty())
|
||||
marks = {{"session", true}};
|
||||
else
|
||||
marks = {{"source", source}, {"client", text_of(origin, "client")}, {"plugin", text_of(origin, "plugin")}};
|
||||
}
|
||||
m_marks[job] = std::move(marks);
|
||||
}
|
||||
|
||||
void ActivityLog::call_queued(uint64_t call, const std::string& job, const std::string& parent, const json& origin)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
mark(job, parent, origin);
|
||||
m_running[call] = {0, job, {}};
|
||||
}
|
||||
|
||||
void ActivityLog::call_started(uint64_t call, const NativeCommand& def, const json& given_args, const std::string& parent,
|
||||
const std::string& job, const json& origin)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
// For a call that was not queued: an inline one has no job, and a caller may report a job call only as it starts.
|
||||
mark(job, parent, origin);
|
||||
// Arguments too deep to read are not shown, and leave the job without a record; neither is what the call returns,
|
||||
// nor a dialog answered while it runs, which may repeat them.
|
||||
const bool deep = too_deep(given_args);
|
||||
m_running[call] = {0, job, def.key, deep};
|
||||
// A call with no job leaves nothing for later calls to read (mark() makes no marks for it): unlisted, it needs
|
||||
// no more.
|
||||
if (job.empty() && !m_recording)
|
||||
return;
|
||||
const json& args = readable(given_args, deep);
|
||||
std::vector<std::string> hidden = call_hidden(def.key, args);
|
||||
// Every job call's, listed or not, for a later call that repeats its result.
|
||||
if (!job.empty() && !deep)
|
||||
keep_hidden(job, hidden, true);
|
||||
// A call another call started to outlive it is placed as that call's child.
|
||||
const std::string above_of = parent.empty() ? text_of(origin, "under") : parent;
|
||||
// A person's pick is the person's own doing, and a Run Script session is shown by the works it runs.
|
||||
if (const auto marked = m_marks.find(job); above_of.empty() && marked != m_marks.end() &&
|
||||
(marked->second.contains("person") || marked->second.contains("session")))
|
||||
return;
|
||||
if (!m_recording)
|
||||
return;
|
||||
Entry e;
|
||||
e.kind = "call";
|
||||
e.tool = def.key;
|
||||
e.read = def.guard == GuardClass::Inspect;
|
||||
e.job = job;
|
||||
e.hidden = std::move(hidden);
|
||||
// A call that reads a job (app_wait's result, job_cancel's) may repeat what that job's call hid; with no record
|
||||
// of it as it ends, what it returns is not shown (finish()).
|
||||
if (args.is_object() && args.contains("job") && args["job"].is_string()) {
|
||||
e.reads_job = args["job"].get<std::string>();
|
||||
if (const std::vector<std::string>* of_job = job_hidden(e.reads_job))
|
||||
e.hidden.insert(e.hidden.end(), of_job->begin(), of_job->end());
|
||||
}
|
||||
e.source = text_of(origin, "source");
|
||||
e.client = text_of(origin, "client");
|
||||
if (above_of.empty())
|
||||
e.plugin = text_of(origin, "plugin");
|
||||
else if (!place(above_of, job, e))
|
||||
return;
|
||||
// An agent's own request is the message it sent; anyone else's, and a call made under another, the call as the
|
||||
// app runs it.
|
||||
e.request = above_of.empty() && e.source == "agent" && origin.contains("request") ? readable(origin["request"]) :
|
||||
json{{"tool", def.key}, {"args", args}};
|
||||
e.args = args;
|
||||
m_running[call].entry = add(std::move(e)).id;
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
bool ActivityLog::place(const std::string& above, const std::string& own_job, Entry& e) const
|
||||
{
|
||||
const auto by_marks = [&](const json& marks) {
|
||||
if (marks.contains("person"))
|
||||
return false;
|
||||
// A Run Script session has no entry: what is made in it goes under the work it runs.
|
||||
if (marks.contains("session")) {
|
||||
e.source = "run_script";
|
||||
if (const auto work = m_entries.find(m_work); work != m_entries.end() && work->second.status == "running")
|
||||
e.parent = m_work;
|
||||
return true;
|
||||
}
|
||||
// A run that started before recording has no entry: what it makes goes to the top level as its own.
|
||||
e.source = text_of(marks, "source");
|
||||
e.client = text_of(marks, "client");
|
||||
e.plugin = text_of(marks, "plugin");
|
||||
return true;
|
||||
};
|
||||
// The nearest job above that has an entry, past any that has none: a run started while the log didn't record may be
|
||||
// nested in one it lists.
|
||||
const std::vector<std::string> chain = m_jobs.ancestry(above);
|
||||
for (const std::string& job : chain)
|
||||
if (const Entry* run = job_entry(job)) {
|
||||
e.parent = run->id;
|
||||
e.source = run->source;
|
||||
e.client = run->client;
|
||||
e.plugin = run->plugin;
|
||||
return true;
|
||||
}
|
||||
for (const std::string& job : chain)
|
||||
if (const auto marked = m_marks.find(job); marked != m_marks.end())
|
||||
return by_marks(marked->second);
|
||||
// Every job above has ended: a job call has the marks it copied from them as it was queued.
|
||||
if (const auto own = m_marks.find(own_job); !own_job.empty() && own != m_marks.end())
|
||||
return by_marks(own->second);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ActivityLog::call_args(uint64_t call, const json& given_args)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_running.find(call);
|
||||
if (it == m_running.end())
|
||||
return;
|
||||
const bool deep = too_deep(given_args);
|
||||
it->second.unread = it->second.unread || deep;
|
||||
if (deep)
|
||||
drop_hidden(it->second.job);
|
||||
// A later call that repeats the job's result must hide what the rewrite reveals, whether or not this one is
|
||||
// listed; with neither a record nor an entry to take it, nothing does.
|
||||
const bool kept = job_hidden(it->second.job) != nullptr;
|
||||
const auto entry = m_entries.find(it->second.entry);
|
||||
if (!kept && entry == m_entries.end())
|
||||
return;
|
||||
const json& args = readable(given_args, deep);
|
||||
const std::vector<std::string> extra = call_hidden(it->second.tool, args);
|
||||
if (kept)
|
||||
keep_hidden(it->second.job, extra, false);
|
||||
if (entry == m_entries.end())
|
||||
return;
|
||||
Entry& e = entry->second;
|
||||
e.hidden.insert(e.hidden.end(), extra.begin(), extra.end());
|
||||
e.args = shown(args, e.hidden);
|
||||
// The request shows the call as made; what the rewrite reveals is masked there too.
|
||||
e.request = shown(std::move(e.request), e.hidden);
|
||||
touch(e);
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::call_ended(uint64_t call, const ToolResult& result)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_running.find(call);
|
||||
if (it == m_running.end())
|
||||
return;
|
||||
const Running run = std::move(it->second);
|
||||
m_running.erase(it);
|
||||
// A job's marks go with its call: the jobs under it copied them as they were queued.
|
||||
m_marks.erase(run.job);
|
||||
const auto e = m_entries.find(run.entry);
|
||||
if (run.job.empty() && e == m_entries.end())
|
||||
return;
|
||||
// What its result repeats of the calls written in it (a replay's steps) joins its record and its entry's mask.
|
||||
const bool deep = too_deep(result.data);
|
||||
const std::vector<std::string> nested = repeated_hidden(result.data, deep);
|
||||
if (!run.job.empty() && deep)
|
||||
drop_hidden(run.job);
|
||||
else if (!run.job.empty())
|
||||
keep_hidden(run.job, nested, false);
|
||||
if (e == m_entries.end())
|
||||
return;
|
||||
finish(e->second, result, run.unread, deep, nested);
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::refused(const std::string& tool, const json& origin, const ToolResult& error)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_recording)
|
||||
return;
|
||||
Entry e;
|
||||
e.kind = "call";
|
||||
e.tool = tool;
|
||||
e.source = text_of(origin, "source");
|
||||
e.client = text_of(origin, "client");
|
||||
e.request = origin.is_object() && origin.contains("request") ? readable(origin["request"]) : json();
|
||||
const json& params = e.request.is_object() && e.request.contains("params") ? e.request["params"] : json();
|
||||
const json arguments = params.is_object() && params.contains("arguments") ? params["arguments"] : json::object();
|
||||
// What the request must not show, for the tool it called and, through tool_call, the tool that names.
|
||||
e.hidden = call_hidden(text_of(params, "name"), arguments);
|
||||
// A tool_call is the call of the tool it names, with that tool's arguments.
|
||||
e.args = text_of(params, "name") == "tool_call" && tool != "tool_call" && arguments.is_object() && arguments.contains("args") ?
|
||||
arguments["args"] :
|
||||
arguments;
|
||||
const bool deep = too_deep(error.data);
|
||||
finish(add(std::move(e)), error, false, deep, repeated_hidden(error.data, deep));
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::rules_set(const std::string& job, int layer)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (layer == 0)
|
||||
return;
|
||||
Layer& set = m_layers[layer];
|
||||
if (const Entry* listed = job_entry(job)) {
|
||||
set.entry = listed->id;
|
||||
set.client = listed->client;
|
||||
} else if (const auto marked = m_marks.find(job); marked != m_marks.end())
|
||||
// Not listed: the answers still name the client that set the rules.
|
||||
set.client = text_of(marked->second, "client");
|
||||
// A layer whose call is listed stays while it is; the latest others stay for their client, up to 2 × kMaxEntries
|
||||
// layers in all.
|
||||
for (auto it = m_layers.begin(); it != m_layers.end() && m_layers.size() > 2 * kMaxEntries;)
|
||||
it = m_entries.count(it->second.entry) != 0 ? std::next(it) : m_layers.erase(it);
|
||||
}
|
||||
|
||||
void ActivityLog::dialog_answered(int layer, const std::string& run, const std::string& plugin, const json& dialog)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_recording)
|
||||
return;
|
||||
Entry e;
|
||||
e.kind = "dialog";
|
||||
e.status = "done";
|
||||
e.source = !plugin.empty() ? "plugin" : "agent";
|
||||
e.plugin = plugin;
|
||||
// The layer is the rules of one dialog_auto_answer call, which no later call changes.
|
||||
if (const auto set = m_layers.find(layer); set != m_layers.end()) {
|
||||
if (m_entries.count(set->second.entry) != 0)
|
||||
e.rule = set->second.entry;
|
||||
if (run.empty() && plugin.empty())
|
||||
e.client = set->second.client;
|
||||
}
|
||||
if (!run.empty() && !place(run, {}, e))
|
||||
return;
|
||||
// The dialog may show what the calls running as it is answered hide (a key a call set, then refused in a message),
|
||||
// also where ModalTracker cut a long message. Past kMaxDialogValues of them, which would hold up the UI thread
|
||||
// that reports the answer, its title and message are not shown.
|
||||
e.request = dialog;
|
||||
for (const char* key : {"title", "message"})
|
||||
if (!e.request.contains(key) || !e.request[key].is_string())
|
||||
e.request[key] = "";
|
||||
std::vector<const std::vector<std::string>*> running_hidden;
|
||||
std::size_t count = 0, bytes = 0;
|
||||
bool unread = false;
|
||||
for (const auto& [call, running] : m_running) {
|
||||
unread = unread || running.unread;
|
||||
if (const auto it = m_entries.find(running.entry); it != m_entries.end())
|
||||
running_hidden.push_back(&it->second.hidden);
|
||||
if (const std::vector<std::string>* kept = job_hidden(running.job))
|
||||
running_hidden.push_back(kept);
|
||||
}
|
||||
for (const std::vector<std::string>* values : running_hidden) {
|
||||
count += values->size();
|
||||
for (std::size_t i = 0; i < values->size() && count <= kMaxDialogValues && bytes <= kMaxDialogBytes; ++i)
|
||||
bytes += (*values)[i].size();
|
||||
}
|
||||
if (unread || count > kMaxDialogValues || bytes > kMaxDialogBytes) {
|
||||
e.request["title"] = kMask;
|
||||
e.request["message"] = kMask;
|
||||
} else
|
||||
for (const std::vector<std::string>* values : running_hidden)
|
||||
for (const std::string& v : *values) {
|
||||
mask_cut_start(e.request["message"].get_ref<std::string&>(), v);
|
||||
e.hidden.push_back(v);
|
||||
}
|
||||
Entry& added = add(std::move(e));
|
||||
added.ended = added.started;
|
||||
std::vector<std::string>().swap(added.hidden);
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::work_started(json work)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
// A work run while not recording is not listed, and neither is a call it makes listed under it.
|
||||
m_work = 0;
|
||||
if (!m_recording)
|
||||
return;
|
||||
Entry e;
|
||||
e.kind = "work";
|
||||
e.tool = "script_run";
|
||||
e.source = "run_script";
|
||||
e.args = json::object();
|
||||
e.request = std::move(work);
|
||||
m_work = add(std::move(e)).id;
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::work_ended(const std::string& status, const std::string& message, const json& result)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto work = m_entries.find(std::exchange(m_work, 0));
|
||||
if (work == m_entries.end() || work->second.status != "running")
|
||||
return;
|
||||
// As script_run's result reads, which tells its failure (reported_failure()).
|
||||
json out{{"status", status}};
|
||||
if (!message.empty())
|
||||
out["message"] = message;
|
||||
if (!result.is_null())
|
||||
out["result"] = readable(result);
|
||||
const bool deep = too_deep(out);
|
||||
const std::vector<std::string> nested = repeated_hidden(out, deep);
|
||||
finish(work->second, ToolResult::ok(std::move(out)), false, deep, nested);
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
bool ActivityLog::ended_with_nested(uint64_t id, std::vector<uint64_t>& ids) const
|
||||
{
|
||||
// Nested entries come after their parent, so one pass from it collects them all.
|
||||
std::set<uint64_t> tree{id};
|
||||
for (auto it = m_entries.find(id); it != m_entries.end(); ++it) {
|
||||
const Entry& e = it->second;
|
||||
if (e.id != id && tree.count(e.parent) == 0)
|
||||
continue;
|
||||
if (e.status == "running")
|
||||
return false;
|
||||
tree.insert(e.id);
|
||||
}
|
||||
ids.insert(ids.end(), tree.begin(), tree.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
void ActivityLog::remove(const std::vector<uint64_t>& ids)
|
||||
{
|
||||
for (const uint64_t id : ids) {
|
||||
const auto it = m_entries.find(id);
|
||||
if (it == m_entries.end())
|
||||
continue;
|
||||
if (const auto job = m_job_entries.find(it->second.job); job != m_job_entries.end() && job->second == id)
|
||||
m_job_entries.erase(job);
|
||||
m_entries.erase(it);
|
||||
m_removed.emplace_back(++m_version, id);
|
||||
}
|
||||
// A reader older than a removal this forgets would miss it.
|
||||
while (m_removed.size() > kMaxEntries) {
|
||||
m_reset_version = std::max(m_reset_version, m_removed.front().first);
|
||||
m_removed.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityLog::trim()
|
||||
{
|
||||
for (auto it = m_entries.begin(); m_entries.size() > kMaxEntries && it != m_entries.end();) {
|
||||
std::vector<uint64_t> ids;
|
||||
if (!ended_with_nested(it->first, ids)) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
// What it dropped is `it` and entries after it: the next one left comes after `it`.
|
||||
const uint64_t root = it->first;
|
||||
remove(ids);
|
||||
it = m_entries.upper_bound(root);
|
||||
}
|
||||
}
|
||||
|
||||
json ActivityLog::changes_since(uint64_t version)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_pending = false;
|
||||
const bool reset = version < m_reset_version || version > m_version;
|
||||
json out{{"version", m_version}, {"reset", reset}, {"entries", json::array()}, {"removed", json::array()}};
|
||||
for (const auto& [id, e] : m_entries) {
|
||||
if (!reset && e.version <= version)
|
||||
continue;
|
||||
out["entries"].push_back({{"id", e.id},
|
||||
{"parent", e.parent},
|
||||
{"number", e.number},
|
||||
{"kind", e.kind},
|
||||
{"source", e.source},
|
||||
{"client", e.client},
|
||||
{"plugin", e.plugin},
|
||||
{"tool", e.tool},
|
||||
{"read", e.read},
|
||||
{"args", e.args},
|
||||
{"request", e.request},
|
||||
{"response", e.response},
|
||||
{"status", e.status},
|
||||
{"error", e.error},
|
||||
{"failure", e.failure},
|
||||
{"withheld", e.withheld},
|
||||
{"job", e.job},
|
||||
{"started", e.started},
|
||||
{"ended", e.ended},
|
||||
{"rule", e.rule}});
|
||||
}
|
||||
if (!reset)
|
||||
for (const auto& [v, id] : m_removed)
|
||||
if (v > version)
|
||||
out["removed"].push_back(id);
|
||||
return out;
|
||||
}
|
||||
|
||||
void ActivityLog::clear()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
std::vector<uint64_t> ids;
|
||||
for (const auto& [id, e] : m_entries)
|
||||
if (e.parent == 0) {
|
||||
std::vector<uint64_t> tree;
|
||||
if (ended_with_nested(id, tree))
|
||||
ids.insert(ids.end(), tree.begin(), tree.end());
|
||||
}
|
||||
remove(ids);
|
||||
if (m_entries.empty())
|
||||
m_next_number = 1;
|
||||
// Readers start over from what is left.
|
||||
m_reset_version = ++m_version;
|
||||
}
|
||||
notify();
|
||||
}
|
||||
|
||||
void ActivityLog::notify()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (m_pending)
|
||||
return;
|
||||
m_pending = true;
|
||||
}
|
||||
if (!m_changed)
|
||||
return;
|
||||
try {
|
||||
m_changed();
|
||||
} catch (...) {
|
||||
// The pane reads the change at its next refresh.
|
||||
}
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,228 @@
|
||||
#pragma once
|
||||
|
||||
#include "McpCore.hpp"
|
||||
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
class JobRegistry;
|
||||
|
||||
// What the Agent Activity pane lists: every call automation makes, reads included (an agent's, a run's from Action
|
||||
// Replay, the Run Script panel or the command line, a plugin's), and the calls the protocol refused before they ran. A
|
||||
// person's own picks are left out, with every call made under them.
|
||||
//
|
||||
// An entry nests under the entry of the run that made it: a child call under the nearest of its parent jobs that has an
|
||||
// entry. A Run Script panel session has no entry of its own: each work it runs has one (work_started()), and a call made
|
||||
// in the session nests under the work running at the time, or is at the top level between works. A replay or script run
|
||||
// whose result reports a failure (a step that failed, a script that raised) is failed, as its caller reads it.
|
||||
//
|
||||
// Arguments, requests, responses and errors are masked as captions are (hidden_values(), mask_hidden()), JSON text
|
||||
// inside them read as JSON: an entry hides what its own call hides, what each call written inside it hides (a replay's
|
||||
// steps, with the variables they use, in its arguments and its result), and, for a call that names a job (app_wait), what
|
||||
// that job's call hid as it ends; with no record of that, its result isn't shown. A dialog hides what the calls running
|
||||
// as it is answered hide, also where its message was cut. Each past kMaxBytes shows only its size, unmasked. What nests deeper than kMaxDepth,
|
||||
// a payload or JSON text in one, is not read and not shown. The log keeps kMaxEntries entries, dropping the oldest finished ones
|
||||
// first, with what is nested under them.
|
||||
//
|
||||
// It lists only while recording (set_recording()), which the pane turns on while it is open. What comes while it is off
|
||||
// is not listed, but what it already lists still ends, and it keeps what placing and masking later entries needs: each
|
||||
// job's marks (m_marks), so that a run started before recording lists its later calls at the top level under its
|
||||
// source and a person's pick's calls stay out, and each job call's masking record (m_job_hidden).
|
||||
//
|
||||
// The pane reads it on the UI thread with changes_since(). No wx: the runtime makes it before the core, which reports
|
||||
// every call to it on the call's thread. Thread-safe; every method is quick.
|
||||
class ActivityLog final : public CallObserver
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t kMaxEntries = 2000;
|
||||
static constexpr std::size_t kMaxBytes = 32 * 1024;
|
||||
// The masking records of job calls, kept for later waits on their jobs, are bounded by this many bytes.
|
||||
static constexpr std::size_t kMaxKeptHiddenBytes = 4 * 1024 * 1024;
|
||||
// A payload, or JSON text inside one, that nests arrays and objects deeper than this is not read (masking recurses
|
||||
// through what it reads) and not shown; a job call's whose arguments or result nest deeper has no masking record.
|
||||
static constexpr int kMaxDepth = 64;
|
||||
// A dialog answered while the calls running hide more values, or more bytes of them, than this shows neither title
|
||||
// nor message: checking them all would hold up the UI thread that reports the answer. Nor does one answered while a
|
||||
// call whose arguments couldn't be read runs.
|
||||
static constexpr std::size_t kMaxDialogValues = 10000;
|
||||
// A payload or an error checked against what it must hide by scanning more bytes than this (values × its length) is
|
||||
// not shown, so that masking never holds up a call's thread or the pane for long.
|
||||
static constexpr std::size_t kMaxMaskWork = 256 * 1024 * 1024;
|
||||
static constexpr std::size_t kMaxDialogBytes = 1024 * 1024;
|
||||
// What the variables of the replays written in a call may put into their steps, in bytes, as the log reads what the
|
||||
// call must hide; past it, the rest is kept as written. Variables that put each other in over and over
|
||||
// grow as the power of the nesting, which a replay allows nine levels deep.
|
||||
static constexpr std::size_t kMaxPutIn = 1024 * 1024;
|
||||
|
||||
// `jobs` gives a child call's parent chain. `changed` is called, on the thread that changed the log, when it changes
|
||||
// while no change waits for changes_since(): at most once between two reads. It must be quick; what it throws is
|
||||
// dropped.
|
||||
ActivityLog(const JobRegistry& jobs, std::function<void()> changed);
|
||||
|
||||
// Whether the log lists what comes: on while the pane is open. While off it adds no entry, but the entries it holds
|
||||
// still change and end, and it keeps the marks of the runs going and the masking records of job calls (see the class
|
||||
// comment), so what it lists once on again is placed and masked. Off at first. Any thread.
|
||||
void set_recording(bool on);
|
||||
|
||||
void call_queued(uint64_t call, const std::string& job, const std::string& parent, const nlohmann::json& origin) override;
|
||||
void call_started(uint64_t call, const NativeCommand& command, const nlohmann::json& args, const std::string& parent,
|
||||
const std::string& job, const nlohmann::json& origin) override;
|
||||
void call_args(uint64_t call, const nlohmann::json& args) override;
|
||||
void call_ended(uint64_t call, const ToolResult& result) override;
|
||||
|
||||
// A tools/call the protocol refused before the core saw it (McpProtocol::set_on_refused()): a failed entry.
|
||||
void refused(const std::string& tool, const nlohmann::json& origin, const ToolResult& error);
|
||||
// The dialog_auto_answer call of the job `job` put its rules in the ModalTracker layer `layer`: an answer by that
|
||||
// layer links that call's entry, when it has one. The runtime tells it under the lock an answer's report takes first
|
||||
// (AutomationRuntime::set_auto_answer()), so it is told before any answer by the layer.
|
||||
void rules_set(const std::string& job, int layer);
|
||||
// A rule of the ModalTracker layer `layer` answered a dialog, `dialog` being {title, message, match, button}: an
|
||||
// entry under the run whose rule it was (`run`, the run's job), else at the top level as `plugin`'s, else as a
|
||||
// client's, linked to the entry of the call that set the layer's rules (rules_set()).
|
||||
void dialog_answered(int layer, const std::string& run, const std::string& plugin, const nlohmann::json& dialog);
|
||||
// The Run Script panel, which runs one session at a time, starts a work in it: `work` is {work: "cell", "file" (Run
|
||||
// all) or "console", file, cell, title, lines: [first, last], code}, the work's request. Its calls nest under it
|
||||
// until work_ended(), which `status` (PythonSessionEvent's: finished, raised, cancelled, ...) ends as done when
|
||||
// "finished", with the JSON `result` the work left, and as failed otherwise, read as a script_run result
|
||||
// {status, message, result} is. The panel ends every work it starts, also one its session ends under or that it lets
|
||||
// go of.
|
||||
void work_started(nlohmann::json work);
|
||||
void work_ended(const std::string& status, const std::string& message, const nlohmann::json& result);
|
||||
|
||||
// The entries added or changed since `version`, which a read returns as `version` for the next:
|
||||
// {version, reset, entries: [entry...], removed: [id...]}. With `reset`, the reader drops what it holds: `entries`
|
||||
// then holds every entry. An entry is {id, parent (0 at the top level), number, kind ("call"), source, client,
|
||||
// plugin, tool, read, args, request, response (null while running), status ("running", "done" or "failed"),
|
||||
// error, failure, withheld, job, started, ended (milliseconds since the epoch, 0 while running), rule}. `number`
|
||||
// counts the top-level calls and works, and from 1 the calls nested under each; a dialog's is 0. A dialog's entry
|
||||
// (kind "dialog") holds the dialog as its request and the id of the call that set the rule as `rule` (0 when the log
|
||||
// doesn't hold it). A work's (kind "work") holds the work as its request. `error` is the failure as the call gave it;
|
||||
// `failure` is one the log read from a run's result for the pane to word: {step, why} for a replay's failed step
|
||||
// (without `step` when the result names none), {script: status} for a script that ended other than by raising, or
|
||||
// without a message. A call whose own arguments nest too deep to read, or that repeats a job's result the log has no
|
||||
// masking record for as it ends, is `withheld`: its response is null and its error empty.
|
||||
nlohmann::json changes_since(uint64_t version);
|
||||
// Drops every entry whose calls have all ended, as the pane's Clear list does; running ones stay, and the numbering
|
||||
// starts again once none is left. The masking records stay, so a later wait on a cleared job still shows its result.
|
||||
void clear();
|
||||
|
||||
private:
|
||||
struct Entry
|
||||
{
|
||||
uint64_t id = 0;
|
||||
uint64_t parent = 0;
|
||||
uint64_t version = 0; // the log's version when it last changed
|
||||
int number = 0;
|
||||
int nested = 0; // entries added under it, which number the next one
|
||||
std::string kind;
|
||||
std::string source, client, plugin;
|
||||
std::string tool;
|
||||
bool read = false;
|
||||
nlohmann::json args, request, response;
|
||||
std::string status = "running";
|
||||
std::string error;
|
||||
nlohmann::json failure;
|
||||
std::string job;
|
||||
int64_t started = 0, ended = 0;
|
||||
uint64_t rule = 0; // a dialog's: the dialog_auto_answer entry that set the rule
|
||||
std::string reads_job; // the job a call that reads one (app_wait, job_cancel) names
|
||||
bool withheld = false; // its arguments nest too deep to read, or that job had no masking record as it
|
||||
// ended: its result and error aren't shown
|
||||
// What its request and response must not show, until it ends.
|
||||
std::vector<std::string> hidden;
|
||||
};
|
||||
|
||||
// A core call that has not ended: its entry (0 for one not listed), its job, its tool (empty until it starts), and
|
||||
// whether its arguments nest too deep to read.
|
||||
struct Running
|
||||
{
|
||||
uint64_t entry = 0;
|
||||
std::string job, tool;
|
||||
bool unread = false;
|
||||
};
|
||||
|
||||
// The client of a ModalTracker layer's rules, and the entry of the call that set them (0 for one not listed).
|
||||
struct Layer
|
||||
{
|
||||
uint64_t entry = 0;
|
||||
std::string client;
|
||||
};
|
||||
|
||||
// Adds `e` under `e.parent`, numbering it, and drops old entries past kMaxEntries. Under the lock.
|
||||
Entry& add(Entry e);
|
||||
// Sets the marks of `job` (see m_marks) from the nearest marked job above it (`parent`, or the call it is `under`),
|
||||
// else from `origin`; a job marked already keeps its marks. Under the lock.
|
||||
void mark(const std::string& job, const std::string& parent, const nlohmann::json& origin);
|
||||
// Where an entry made under the job `above` goes: under the nearest job above it that has an entry (its `parent`,
|
||||
// `source`, `client` and `plugin` set from it), else by the nearest marks above it, else, when every job above has
|
||||
// ended, by the marks of the entry's own job `own_job`: at the top level as that run's, as a Run Script session's
|
||||
// (under the work running), or nowhere (false) under a person's pick. Under the lock.
|
||||
bool place(const std::string& above, const std::string& own_job, Entry& e) const;
|
||||
// Ends `e` with `result`: its response, error, failure and status. `unread`: the call's arguments nest too deep to
|
||||
// read; `deep`: so does `result`'s data; `nested`: what that data repeats of the calls written in it (a replay's
|
||||
// steps). Under the lock.
|
||||
void finish(Entry& e, const ToolResult& result, bool unread, bool deep, const std::vector<std::string>& nested);
|
||||
void touch(Entry& e) { e.version = ++m_version; }
|
||||
// What the call of `job` hid; null when the log has no record of it. Under the lock.
|
||||
const std::vector<std::string>* job_hidden(const std::string& job) const;
|
||||
// The entry of the call of `job`, null for one not listed. Under the lock.
|
||||
const Entry* job_entry(const std::string& job) const;
|
||||
// Adds `hidden` to the masking record of the call of `job`, which `start` (its call starting) makes, within the bounds
|
||||
// of m_job_hidden. A value longer than kMaxBytes, which a capped payload can't hold but a shortened error can show a
|
||||
// part of, drops the record: a call that repeats the job's result then shows none of it. Under the lock.
|
||||
void keep_hidden(const std::string& job, const std::vector<std::string>& hidden, bool start);
|
||||
// Drops the masking record of `job`'s call, if any. Under the lock.
|
||||
void drop_hidden(const std::string& job);
|
||||
// Whether `id` and every entry nested under it have ended; collects them into `ids`. Under the lock.
|
||||
bool ended_with_nested(uint64_t id, std::vector<uint64_t>& ids) const;
|
||||
void remove(const std::vector<uint64_t>& ids);
|
||||
void trim();
|
||||
// Calls `changed` once for changes made since the last read. Not under the lock.
|
||||
void notify();
|
||||
|
||||
const JobRegistry& m_jobs;
|
||||
std::function<void()> m_changed;
|
||||
|
||||
std::mutex m_mutex;
|
||||
std::map<uint64_t, Entry> m_entries; // by id, oldest first
|
||||
uint64_t m_next_id = 1;
|
||||
int m_next_number = 1;
|
||||
uint64_t m_version = 0;
|
||||
// A reader whose version is older than this missed what changes_since() can tell it: it starts over.
|
||||
uint64_t m_reset_version = 0;
|
||||
std::deque<std::pair<uint64_t, uint64_t>> m_removed; // (version, id) of the entries dropped lately
|
||||
bool m_pending = false; // a change waits for changes_since()
|
||||
|
||||
bool m_recording = false;
|
||||
std::map<uint64_t, Running> m_running; // by call id
|
||||
std::map<std::string, uint64_t> m_job_entries; // a call's job -> its entry
|
||||
// What a job's call is, for the calls made under it, from when it is queued until it ends, listed or not: a run's
|
||||
// {source, client, plugin}, {person: true} for a person's pick, or {session: true} for a Run Script session and the
|
||||
// jobs under it. A child job copies its nearest marked ancestor's as it is queued, while that ancestor runs, so a run
|
||||
// that outlives its parent keeps them.
|
||||
std::map<std::string, nlohmann::json> m_marks;
|
||||
// What each job's call hid, possibly nothing, listed or not, by its job, from when it starts: the last kMaxEntries
|
||||
// of them, within kMaxKeptHiddenBytes.
|
||||
std::map<std::string, std::vector<std::string>> m_job_hidden;
|
||||
std::deque<std::string> m_job_hidden_order;
|
||||
std::size_t m_job_hidden_bytes = 0;
|
||||
// The layers rules_set() was told of, by layer: each one whose call is listed, and the latest others, up to
|
||||
// 2 × kMaxEntries in all.
|
||||
std::map<int, Layer> m_layers;
|
||||
uint64_t m_work = 0; // the entry of the work the Run Script panel runs, 0 for none
|
||||
};
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "AutomationRuntime.hpp"
|
||||
|
||||
#include "ActivityLog.hpp"
|
||||
#include "AutomationRuntimePtr.hpp"
|
||||
#include "FollowedThreads.hpp"
|
||||
#include "JobRegistry.hpp"
|
||||
@@ -149,6 +150,14 @@ bool AutomationRuntime::start(std::string& err)
|
||||
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)); });
|
||||
// The pane reads the log on the UI thread, once for any number of changes, finding the runtime again there:
|
||||
// it may be gone by the time the closure runs.
|
||||
m_activity = std::make_unique<ActivityLog>(m_jobs, [this] {
|
||||
post_ui([] {
|
||||
if (AutomationRuntime* runtime = wxGetApp().automation_if_started(); runtime != nullptr && runtime->m_activity_listener)
|
||||
runtime->m_activity_listener();
|
||||
});
|
||||
});
|
||||
// A call's window for taking menus is the inspector's: none before there is one, and it takes no menu
|
||||
// while the GUI instruments are off.
|
||||
m_invoker = std::make_unique<UiInvoker>(*m_dispatcher, [this] { return guards_on_ui(); }, [this] { return m_generation.load(); },
|
||||
@@ -165,9 +174,11 @@ bool AutomationRuntime::start(std::string& err)
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP reply budget capped at " << timing.reply_budget_cap.count()
|
||||
<< " ms by ORCA_MCP_REPLY_BUDGET_MS";
|
||||
m_core = std::make_unique<McpCore>(NativeCommands::instance(), *m_invoker, m_jobs, &m_journal, timing,
|
||||
ui_job_worker_hooks(), m_recorder.get());
|
||||
ui_job_worker_hooks(), std::vector<CallObserver*>{m_recorder.get(), m_activity.get()});
|
||||
// A command reaches the runtime through its call's context (ToolContext::runtime()).
|
||||
m_core->set_runtime(this);
|
||||
m_modals->set_on_answered([this](int layer, const std::string& title, const std::string& message, const std::string& pattern,
|
||||
const std::string& button) { rule_answered(layer, title, message, pattern, button); });
|
||||
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";
|
||||
@@ -331,32 +342,39 @@ AutoAnswerSet AutomationRuntime::set_auto_answer(std::vector<AutoAnswerRule> rul
|
||||
// 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};
|
||||
const AutoAnswerSet set = [&]() -> AutoAnswerSet {
|
||||
// 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");
|
||||
}
|
||||
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};
|
||||
// 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};
|
||||
}();
|
||||
// Still under the rules lock, which an answer's report takes before it reaches the activity log (rule_answered()):
|
||||
// the log knows whose the layer is before any answer by it.
|
||||
if (set.layer != 0 && !ancestry.empty())
|
||||
m_activity->rules_set(ancestry.front(), set.layer);
|
||||
return set;
|
||||
}
|
||||
|
||||
void AutomationRuntime::begin_run_scope(const std::string& job)
|
||||
@@ -430,6 +448,26 @@ void AutomationRuntime::cancel_operations_of(const std::string& job)
|
||||
plater->cancel_slicing();
|
||||
}
|
||||
|
||||
void AutomationRuntime::rule_answered(int layer, const std::string& title, const std::string& message, const std::string& pattern,
|
||||
const std::string& button)
|
||||
{
|
||||
// Whose the layer is: a run's, a plugin's, else a client's.
|
||||
std::string run, plugin;
|
||||
const std::string prefix = plugin_scope_key({});
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_rules_mutex);
|
||||
for (const auto& [owner, layers] : m_run_rule_layers)
|
||||
if (std::find(layers.begin(), layers.end(), layer) != layers.end()) {
|
||||
if (owner.compare(0, prefix.size(), prefix) == 0)
|
||||
plugin = owner.substr(prefix.size());
|
||||
else
|
||||
run = owner;
|
||||
break;
|
||||
}
|
||||
}
|
||||
m_activity->dialog_answered(layer, run, plugin, {{"title", title}, {"message", message}, {"match", pattern}, {"button", button}});
|
||||
}
|
||||
|
||||
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());
|
||||
@@ -610,7 +648,7 @@ bool AutomationRuntime::follow(FollowedCall call)
|
||||
}
|
||||
std::optional<ToolResult> r;
|
||||
try {
|
||||
r = call_to_end(call.command, call.args, call.person);
|
||||
r = call_to_end(call.command, call.args, call.person, call.origin);
|
||||
} catch (const std::exception& e) {
|
||||
r = ToolResult::error(std::string("Internal error: ") + e.what());
|
||||
} catch (...) {
|
||||
@@ -631,9 +669,9 @@ bool AutomationRuntime::follow(FollowedCall call)
|
||||
|
||||
void AutomationRuntime::stop_followed() { m_followed.stop_all(); }
|
||||
|
||||
std::optional<ToolResult> AutomationRuntime::call_to_end(const NativeCommand& def, const json& args, bool person)
|
||||
std::optional<ToolResult> AutomationRuntime::call_to_end(const NativeCommand& def, const json& args, bool person, const json& origin)
|
||||
{
|
||||
ToolResult r = person ? m_core->call_person(def, args) : m_core->call(def, args);
|
||||
ToolResult r = person ? m_core->call_person(def, args, origin) : m_core->call(def, args, origin);
|
||||
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;
|
||||
|
||||
@@ -22,12 +22,14 @@
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
class wxTimer;
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
class ActivityLog;
|
||||
class McpRecorder;
|
||||
class ModalTracker;
|
||||
class UiInspector;
|
||||
@@ -50,6 +52,8 @@ struct FollowedCall
|
||||
{
|
||||
NativeCommand command;
|
||||
nlohmann::json args = nlohmann::json::object();
|
||||
// Who started it, for the Agent Activity pane, as McpCore::call() takes it: {source: "action_replay"}, ...
|
||||
nlohmann::json origin;
|
||||
// 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
|
||||
@@ -144,6 +148,10 @@ public:
|
||||
WebPresses& web_presses() { return *m_web_presses; }
|
||||
// recording_start and its kin; also told about every call, for the captions.
|
||||
McpRecorder& recorder() { return *m_recorder; }
|
||||
// What the Agent Activity pane lists: told about every call, and about the calls the endpoint refuses. Any thread.
|
||||
ActivityLog& activity() { return *m_activity; }
|
||||
// Called on the UI thread when the activity log has changed since it was last read; empty for none. UI thread.
|
||||
void set_activity_listener(std::function<void()> listener) { m_activity_listener = std::move(listener); }
|
||||
|
||||
// Auto-answer rules from dialog_auto_answer. 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
|
||||
@@ -198,7 +206,12 @@ private:
|
||||
|
||||
// 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);
|
||||
std::optional<ToolResult> call_to_end(const NativeCommand& command, const nlohmann::json& args, bool person,
|
||||
const nlohmann::json& origin);
|
||||
// An auto-answer rule of `layer` answered a dialog: the activity log lists it with the run, plugin or client whose
|
||||
// rule it was. UI thread.
|
||||
void rule_answered(int layer, const std::string& title, const std::string& message, const std::string& pattern,
|
||||
const std::string& button);
|
||||
void set_ready();
|
||||
GuardState guards_on_ui() const;
|
||||
// Whether something drives the GUI (see enable_gui_instruments()). UI thread.
|
||||
@@ -217,8 +230,10 @@ private:
|
||||
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.
|
||||
// Before the core, which reports its calls to them.
|
||||
std::unique_ptr<McpRecorder> m_recorder;
|
||||
std::unique_ptr<ActivityLog> m_activity;
|
||||
std::function<void()> m_activity_listener; // UI thread
|
||||
std::unique_ptr<UiInvoker> m_invoker;
|
||||
std::unique_ptr<McpCore> m_core;
|
||||
// Null until enable_gui_instruments(). UI thread.
|
||||
|
||||
@@ -178,6 +178,7 @@ void start_launch_run(AutomationRuntime& runtime, const McpLaunchOptions& option
|
||||
|
||||
FollowedCall call;
|
||||
call.command = *NativeCommands::instance().find(python ? "script_run" : "replay_run");
|
||||
call.origin = {{"source", "command_line"}};
|
||||
call.person = true;
|
||||
// The file is read off the UI thread.
|
||||
call.ready = [&runtime, file, out = options.run_out, python, replay](json& args) {
|
||||
|
||||
@@ -24,20 +24,21 @@
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
namespace {
|
||||
|
||||
// Calls an observer method; what it throws stays here, out of the call's thread.
|
||||
template<class Fn> void notify(CallObserver* observer, Fn&& fn)
|
||||
// Calls an observer method on each observer; what one throws stays here, out of the call's thread.
|
||||
template<class Fn> void notify(const std::vector<CallObserver*>& observers, Fn&& fn)
|
||||
{
|
||||
if (observer == nullptr)
|
||||
return;
|
||||
try {
|
||||
fn(*observer);
|
||||
} catch (...) {
|
||||
// A recording's caption is not worth a call.
|
||||
for (CallObserver* observer : observers) {
|
||||
try {
|
||||
fn(*observer);
|
||||
} catch (...) {
|
||||
// A caption or an activity entry is not worth a call.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ class CallContext final : public ToolContext
|
||||
{
|
||||
public:
|
||||
CallContext(McpCore& core, const NativeCommand& def, std::string job, std::string parent, std::string plugin, Journal* journal,
|
||||
uint64_t journal_seq, CallObserver* observer, uint64_t call)
|
||||
uint64_t journal_seq, const std::vector<CallObserver*>& observers, uint64_t call)
|
||||
: m_core(core)
|
||||
, m_def(def)
|
||||
, m_job(std::move(job))
|
||||
@@ -72,7 +73,7 @@ public:
|
||||
, m_plugin(std::move(plugin))
|
||||
, m_journal(journal)
|
||||
, m_seq(journal_seq)
|
||||
, m_observer(observer)
|
||||
, m_observers(observers)
|
||||
, m_call(call)
|
||||
{}
|
||||
|
||||
@@ -140,7 +141,7 @@ public:
|
||||
|
||||
void set_journal_args(nlohmann::json args) override
|
||||
{
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_args(m_call, args); });
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_args(m_call, args); });
|
||||
if (m_journal != nullptr && m_seq != 0)
|
||||
m_journal->set_args(m_seq, without_guard_ids(m_core.catalog(), m_def.key, std::move(args)));
|
||||
}
|
||||
@@ -175,7 +176,7 @@ private:
|
||||
std::string m_plugin;
|
||||
Journal* m_journal;
|
||||
uint64_t m_seq;
|
||||
CallObserver* m_observer;
|
||||
const std::vector<CallObserver*>& m_observers;
|
||||
uint64_t m_call;
|
||||
bool m_saw_idle = false; // UI thread
|
||||
};
|
||||
@@ -209,8 +210,14 @@ std::chrono::milliseconds reply_budget_cap_from(const char* value)
|
||||
}
|
||||
|
||||
McpCore::McpCore(const CommandCatalog& catalog, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing, WorkerHooks worker,
|
||||
CallObserver* observer)
|
||||
: m_catalog(catalog), m_ui(ui), m_jobs(jobs), m_journal(journal), m_timing(timing), m_worker(std::move(worker)), m_observer(observer)
|
||||
std::vector<CallObserver*> observers)
|
||||
: m_catalog(catalog)
|
||||
, m_ui(ui)
|
||||
, m_jobs(jobs)
|
||||
, m_journal(journal)
|
||||
, m_timing(timing)
|
||||
, m_worker(std::move(worker))
|
||||
, m_observers(std::move(observers))
|
||||
{}
|
||||
|
||||
McpCore::~McpCore()
|
||||
@@ -244,14 +251,20 @@ 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, {}, {}, false); }
|
||||
ToolResult McpCore::call(const NativeCommand& command, const nlohmann::json& args, const nlohmann::json& origin)
|
||||
{
|
||||
return run(command, args, {}, {}, false, origin);
|
||||
}
|
||||
|
||||
ToolResult McpCore::call_person(const NativeCommand& command, const nlohmann::json& args) { return run(command, args, {}, {}, true); }
|
||||
ToolResult McpCore::call_person(const NativeCommand& command, const nlohmann::json& args, const nlohmann::json& origin)
|
||||
{
|
||||
return run(command, args, {}, {}, true, origin);
|
||||
}
|
||||
|
||||
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, false);
|
||||
return run(command, args, parent_job, plugin, false, nlohmann::json());
|
||||
}
|
||||
|
||||
ToolResult McpCore::call_child_named(const std::string& tool, const nlohmann::json& raw_args, const std::string& parent_job,
|
||||
@@ -272,7 +285,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, false);
|
||||
return run(command, args, {}, plugin_key, false, {{"source", "plugin"}, {"plugin", plugin_key}});
|
||||
}
|
||||
|
||||
std::string McpCore::submit(const NativeCommand& command, const nlohmann::json& args, std::function<void(const ToolResult&)> done)
|
||||
@@ -282,7 +295,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(command, args, {}, {}, true, 0, m_next_call++, done, refused);
|
||||
const std::string job = start_job(command, args, {}, {}, true, {{"source", "person"}}, 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);
|
||||
@@ -290,8 +303,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,
|
||||
bool person, uint64_t seq, uint64_t call, const std::function<void(const ToolResult&)>& done,
|
||||
ToolResult& refused)
|
||||
bool person, const nlohmann::json& origin, 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 (job_cancel) get through.
|
||||
@@ -321,19 +334,21 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a
|
||||
m_jobs.finish(job, refused);
|
||||
return {};
|
||||
}
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_queued(call, job, parent, origin); });
|
||||
// The job thread owns copies of what it needs; the core outlives it, as the owner destroys the
|
||||
// core only once drain() has seen every job thread leave.
|
||||
try {
|
||||
std::thread([this, def, args, job, parent, plugin, seq, call, done]() {
|
||||
CallContext ctx(*this, def, job, parent, plugin, m_journal, seq, m_observer, call);
|
||||
std::thread([this, def, args, job, parent, plugin, origin, seq, call, done]() {
|
||||
CallContext ctx(*this, def, job, parent, plugin, m_journal, seq, m_observers, call);
|
||||
ToolResult result;
|
||||
// The plugin may have unloaded since the job was registered; its handler then never starts.
|
||||
if (m_jobs.unloaded(job, {})) {
|
||||
result = ToolResult::error(kPluginUnloaded);
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_ended(call, result); });
|
||||
} else {
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_started(call, def, args, parent); });
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_started(call, def, args, parent, job, origin); });
|
||||
result = await_worker(job, def.key, invoke(def, args, ctx));
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_ended(call, result); });
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_ended(call, result); });
|
||||
}
|
||||
// Before finish(): a replay_export right after the app_wait that sees the result must know it.
|
||||
if (seq != 0)
|
||||
@@ -345,6 +360,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a
|
||||
}).detach();
|
||||
} catch (const std::system_error& e) {
|
||||
refused = ToolResult::error(std::string("Cannot start the call: ") + e.what());
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_ended(call, refused); });
|
||||
if (seq != 0)
|
||||
m_journal->job_ended(seq, refused);
|
||||
m_jobs.finish(job, refused);
|
||||
@@ -355,7 +371,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a
|
||||
}
|
||||
|
||||
ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin,
|
||||
bool person)
|
||||
bool person, const nlohmann::json& origin)
|
||||
{
|
||||
if (m_ui.is_shutdown() || !enter())
|
||||
return ToolResult::error("OrcaSlicer is shutting down");
|
||||
@@ -381,19 +397,19 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co
|
||||
|
||||
const uint64_t call = m_next_call++;
|
||||
if (def.inline_call) {
|
||||
CallContext ctx(*this, def, {}, parent, plugin, m_journal, seq, m_observer, call);
|
||||
CallContext ctx(*this, def, {}, parent, plugin, m_journal, seq, m_observers, call);
|
||||
// Any inline call can wait for the UI thread, so each holds a blocking slot.
|
||||
if (!acquire_slot())
|
||||
return finish(ToolResult::ok({{"status", "pending"}, {"note", "Too many calls are waiting right now; try again shortly."}}));
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_started(call, def, args, parent); });
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_started(call, def, args, parent, std::string(), origin); });
|
||||
ToolResult r = invoke(def, args, ctx);
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_ended(call, r); });
|
||||
notify(m_observers, [&](CallObserver& o) { o.call_ended(call, r); });
|
||||
release_slot();
|
||||
return finish(std::move(r));
|
||||
}
|
||||
|
||||
ToolResult refused;
|
||||
const std::string job = start_job(def, args, parent, plugin, person, seq, call, {}, refused);
|
||||
const std::string job = start_job(def, args, parent, plugin, person, origin, seq, call, {}, refused);
|
||||
if (job.empty())
|
||||
return finish(std::move(refused));
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
@@ -49,16 +50,29 @@ struct WorkerHooks
|
||||
std::function<void()> cancel; // asks the running job to stop, without waiting for it
|
||||
};
|
||||
|
||||
// Told about each call the core runs, client and child calls alike: what a recording captions. A call
|
||||
// refused before its handler runs (admission, blocking slots) is not reported. Methods are called on
|
||||
// the call's own thread, must be quick, and must not call back into the core; what they throw is
|
||||
// swallowed, so a caption never fails a call.
|
||||
// Told about each call the core runs, client and child calls alike: what a recording captions and the Agent
|
||||
// Activity pane lists. A call refused before its handler runs (admission, blocking slots) is not reported.
|
||||
// Methods are called on the call's own thread, must be quick, and must not call back into the core; what
|
||||
// they throw is swallowed, so a caption never fails a call.
|
||||
class CallObserver
|
||||
{
|
||||
public:
|
||||
virtual ~CallObserver() = default;
|
||||
// A call that runs as a job, as its job is registered and before its thread starts, on the thread that made the
|
||||
// call: the parent job, or the call that started it (`origin`'s `under`), is still running. Every call queued is
|
||||
// later ended, also when it never starts (its thread can't start, its plugin unloaded before its handler).
|
||||
virtual void call_queued(uint64_t /*call*/, const std::string& /*job*/, const std::string& /*parent*/,
|
||||
const nlohmann::json& /*origin*/)
|
||||
{}
|
||||
// Right before the handler runs: on the request thread for an inline call, the job's thread for a job.
|
||||
virtual void call_started(uint64_t call, const NativeCommand& command, const nlohmann::json& args, const std::string& parent) = 0;
|
||||
// `parent` is the job of the run that made a child call ("" for a top-level call), `job` the call's own
|
||||
// ("" for an inline call). `origin` says who made a top-level call, as an object whose `source` is
|
||||
// "agent" (with the client's name as `client`, empty when unknown, and its tools/call message as
|
||||
// `request`), "action_replay", "run_script", "command_line", "plugin" (with the plugin's key as `plugin`)
|
||||
// or "person"; a child call's is null, as its parent's job says where it comes from. A call a call starts to
|
||||
// outlive it (a recording's encode) names that call's job as `under`, and is listed with it.
|
||||
virtual void call_started(uint64_t call, const NativeCommand& command, const nlohmann::json& args, const std::string& parent,
|
||||
const std::string& job, const nlohmann::json& origin) = 0;
|
||||
// The handler replaced the arguments the journal records (refs became locators).
|
||||
virtual void call_args(uint64_t call, const nlohmann::json& args) = 0;
|
||||
// The call's final result: a job's once it finished, its UI job worker included.
|
||||
@@ -77,17 +91,18 @@ public:
|
||||
class McpCore : public ToolCaller
|
||||
{
|
||||
public:
|
||||
// `observer`, when given, must outlive the core.
|
||||
// The observers, told about every call in this order, must outlive the core.
|
||||
McpCore(const CommandCatalog& catalog, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing = {},
|
||||
WorkerHooks worker = {}, CallObserver* observer = nullptr);
|
||||
WorkerHooks worker = {}, std::vector<CallObserver*> observers = {});
|
||||
// Refuses new calls and waits for every call and job thread to leave, however long that takes:
|
||||
// they use the core. The owner drains first, so this returns at once.
|
||||
~McpCore() override;
|
||||
|
||||
// A call from a client. Mutate commands become top-level jobs.
|
||||
ToolResult call(const NativeCommand& command, const nlohmann::json& args) override;
|
||||
// A call from a client, or a run a front end follows, which `origin` names to the observers
|
||||
// (CallObserver::call_started). Mutate commands become top-level jobs.
|
||||
ToolResult call(const NativeCommand& command, const nlohmann::json& args, const nlohmann::json& origin = nlohmann::json()) override;
|
||||
// As call(), with the job marked a person's.
|
||||
ToolResult call_person(const NativeCommand& command, const nlohmann::json& args);
|
||||
ToolResult call_person(const NativeCommand& command, const nlohmann::json& args, const nlohmann::json& origin = nlohmann::json());
|
||||
// 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
|
||||
// `app_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,
|
||||
@@ -140,15 +155,16 @@ public:
|
||||
|
||||
private:
|
||||
std::uint64_t dialog_of(const std::string& job) const;
|
||||
// `person` marks the call's job a person's (JobRegistry::create()); an inline call has no job to mark.
|
||||
// `person` marks the call's job a person's (JobRegistry::create()); an inline call has no job to mark. `origin`
|
||||
// goes to the observers.
|
||||
ToolResult run(const NativeCommand& command, const nlohmann::json& args, const std::string& parent, const std::string& plugin,
|
||||
bool person);
|
||||
bool person, const nlohmann::json& origin);
|
||||
// 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,
|
||||
bool person, uint64_t seq, uint64_t call, const std::function<void(const ToolResult&)>& done,
|
||||
ToolResult& refused);
|
||||
bool person, const nlohmann::json& origin, 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
|
||||
@@ -162,7 +178,7 @@ private:
|
||||
Journal* m_journal;
|
||||
CoreTiming m_timing;
|
||||
WorkerHooks m_worker;
|
||||
CallObserver* m_observer;
|
||||
std::vector<CallObserver*> m_observers;
|
||||
AutomationRuntime* m_runtime = nullptr;
|
||||
std::atomic<uint64_t> m_next_call{1};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "McpEndpoint.hpp"
|
||||
|
||||
#include "ActivityLog.hpp"
|
||||
#include "AutomationRuntime.hpp"
|
||||
#include "McpHttpServer.hpp"
|
||||
#include "McpOptions.hpp"
|
||||
@@ -7,6 +8,7 @@
|
||||
#include "McpProtocol.hpp"
|
||||
#include "McpToken.hpp"
|
||||
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
|
||||
@@ -15,6 +17,7 @@
|
||||
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/nowide/cstdlib.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <wx/event.h>
|
||||
#include <wx/timer.h>
|
||||
@@ -137,6 +140,10 @@ bool McpEndpoint::listen(int port, std::string& err)
|
||||
// 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());
|
||||
// A call refused before it ran is shown too: it is the agent's.
|
||||
m_protocol->set_on_refused([&runtime = m_runtime](const std::string& tool, const nlohmann::json& origin, const ToolResult& error) {
|
||||
runtime.activity().refused(tool, origin, error);
|
||||
});
|
||||
m_gate = std::make_shared<RequestGate>();
|
||||
m_gate->protocol = m_protocol.get();
|
||||
}
|
||||
|
||||
@@ -111,6 +111,7 @@ std::shared_ptr<PersonRun> start_replay_run(AutomationRuntime& runtime, Replay r
|
||||
|
||||
FollowedCall call;
|
||||
call.command = std::move(def);
|
||||
call.origin = {{"source", "action_replay"}};
|
||||
call.person = true;
|
||||
call.ended = [&runtime, run, ctx_held](const std::optional<ToolResult>& r) {
|
||||
run->mark_ended();
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -192,32 +193,68 @@ json McpProtocol::tools_list() const
|
||||
return tools;
|
||||
}
|
||||
|
||||
json McpProtocol::call_tool(const json& params, bool& unknown_tool, std::string& unknown_name)
|
||||
void McpProtocol::client_seen(const json& params)
|
||||
{
|
||||
unknown_tool = false;
|
||||
const std::string name = params.value("name", "");
|
||||
std::shared_ptr<const NativeCommand> def = m_catalog.lookup(name);
|
||||
const auto info = params.find("clientInfo");
|
||||
if (info == params.end() || !info->is_object() || !info->contains("name") || !info->at("name").is_string())
|
||||
return;
|
||||
const std::string name = info->at("name").get<std::string>();
|
||||
if (name.empty())
|
||||
return;
|
||||
std::lock_guard<std::mutex> lock(m_clients_mutex);
|
||||
m_clients.insert(name);
|
||||
}
|
||||
|
||||
std::string McpProtocol::client_label() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_clients_mutex);
|
||||
return m_clients.size() == 1 ? *m_clients.begin() : std::string();
|
||||
}
|
||||
|
||||
void McpProtocol::refused(const std::string& tool, const json& origin, const ToolResult& error) const
|
||||
{
|
||||
if (!m_on_refused)
|
||||
return;
|
||||
try {
|
||||
m_on_refused(tool, origin, error);
|
||||
} catch (...) {
|
||||
// Whoever listens, the client still gets its reply.
|
||||
}
|
||||
}
|
||||
|
||||
json McpProtocol::call_tool(const json& message, const std::string& client, bool& unknown_tool, std::string& unknown_name)
|
||||
{
|
||||
unknown_tool = false;
|
||||
const json& params = message["params"];
|
||||
const std::string name = params.value("name", "");
|
||||
const json origin{{"source", "agent"}, {"client", client}, {"request", message}};
|
||||
std::shared_ptr<const NativeCommand> def = m_catalog.lookup(name);
|
||||
if (def == nullptr) {
|
||||
unknown_tool = true;
|
||||
unknown_name = name;
|
||||
refused(name, origin, ToolResult::error(m_catalog.unknown_command(name)));
|
||||
return json();
|
||||
}
|
||||
const auto refuse = [&](const std::string& tool, const ToolFailure& f) {
|
||||
const ToolResult r = ToolResult::error(f.what(), f.details);
|
||||
refused(tool, origin, r);
|
||||
return result_to_json(r);
|
||||
};
|
||||
json args = params.contains("arguments") && !params["arguments"].is_null() ? params["arguments"] : json::object();
|
||||
if (!args.is_object()) {
|
||||
const ToolFailure refused = argument_refusal(def->key, "arguments must be an object");
|
||||
return result_to_json(ToolResult::error(refused.what(), refused.details));
|
||||
}
|
||||
if (std::string err = argument_error(*def, args); !err.empty()) {
|
||||
const ToolFailure refused = argument_refusal(def->key, err);
|
||||
return result_to_json(ToolResult::error(refused.what(), refused.details));
|
||||
}
|
||||
if (const std::optional<ToolFailure> refused = resolve_call(m_catalog, def, args))
|
||||
return result_to_json(ToolResult::error(refused->what(), refused->details));
|
||||
if (!args.is_object())
|
||||
return refuse(def->key, argument_refusal(def->key, "arguments must be an object"));
|
||||
if (std::string err = argument_error(*def, args); !err.empty())
|
||||
return refuse(def->key, argument_refusal(def->key, err));
|
||||
// A tool_call it cannot resolve is the call of the tool it names, where it names one.
|
||||
const std::string named = args.contains("tool") && args["tool"].is_string() ? args["tool"].get<std::string>() : std::string();
|
||||
const std::string outer = def->key;
|
||||
if (const std::optional<ToolFailure> refusal = resolve_call(m_catalog, def, args))
|
||||
return refuse(outer == "tool_call" && !named.empty() ? named : outer, *refusal);
|
||||
const auto meta = params.find("_meta");
|
||||
const bool exact = meta != params.end() && meta->is_object() && meta->contains(kExactNumbers) &&
|
||||
meta->at(kExactNumbers) == true;
|
||||
try {
|
||||
return result_to_json(m_caller.call(*def, args), exact);
|
||||
return result_to_json(m_caller.call(*def, args, origin), exact);
|
||||
} catch (const ToolFailure& f) {
|
||||
return result_to_json(ToolResult::error(f.what(), f.details), exact);
|
||||
} catch (const std::exception& e) {
|
||||
@@ -250,7 +287,10 @@ PostReply McpProtocol::handle_post(const PostRequest& request)
|
||||
const std::string method = msg["method"].get<std::string>();
|
||||
if (msg.contains("params") && !msg["params"].is_object())
|
||||
return reply(200, error_body(id, kInvalidParams, "params must be an object"));
|
||||
const json params = msg.contains("params") ? msg["params"] : json::object();
|
||||
// The message as the handlers read it: params, checked here, an empty object when there are none.
|
||||
if (!msg.contains("params"))
|
||||
msg["params"] = json::object();
|
||||
const json& params = msg["params"];
|
||||
// The member a method reads as a string (the header check and the dispatch call value() on it, which throws for
|
||||
// any other type) is refused here as a parameter error, rather than escaping as an internal one.
|
||||
const char* const text_key = method == "resources/read" ? "uri" : method == "tools/call" || method == "prompts/get" ? "name" : nullptr;
|
||||
@@ -260,16 +300,19 @@ PostReply McpProtocol::handle_post(const PostRequest& request)
|
||||
try {
|
||||
if (params.contains("_meta") && params["_meta"].is_object() && params["_meta"].contains(kMetaVersion)) {
|
||||
const json& v = params["_meta"][kMetaVersion];
|
||||
return handle_modern(id, method, params, v.is_string() ? v.get<std::string>() : v.dump(), request);
|
||||
return handle_modern(msg, v.is_string() ? v.get<std::string>() : v.dump(), request);
|
||||
}
|
||||
return handle_legacy(id, method, params, request);
|
||||
return handle_legacy(msg, request);
|
||||
} catch (const std::exception& e) {
|
||||
return reply(500, error_body(id, kInternalError, e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
PostReply McpProtocol::handle_legacy(const json& id, const std::string& method, const json& params, const PostRequest& request)
|
||||
PostReply McpProtocol::handle_legacy(const json& message, const PostRequest& request)
|
||||
{
|
||||
const json& id = message["id"];
|
||||
const std::string method = message["method"].get<std::string>();
|
||||
const json& params = message["params"];
|
||||
const auto& versions = legacy_versions();
|
||||
if (method != "initialize" && !request.protocol_version.empty() &&
|
||||
std::find(versions.begin(), versions.end(), request.protocol_version) == versions.end())
|
||||
@@ -277,6 +320,7 @@ PostReply McpProtocol::handle_legacy(const json& id, const std::string& method,
|
||||
{{"supported", versions}}));
|
||||
|
||||
if (method == "initialize") {
|
||||
client_seen(params);
|
||||
const std::string requested = params.value("protocolVersion", "");
|
||||
const bool supported = std::find(versions.begin(), versions.end(), requested) != versions.end();
|
||||
json server_info{{"name", m_info.name}, {"title", m_info.title}, {"version", m_info.version}};
|
||||
@@ -292,7 +336,7 @@ PostReply McpProtocol::handle_legacy(const json& id, const std::string& method,
|
||||
if (method == "tools/call") {
|
||||
bool unknown = false;
|
||||
std::string name;
|
||||
json result = call_tool(params, unknown, name);
|
||||
json result = call_tool(message, client_label(), unknown, name);
|
||||
if (unknown) {
|
||||
json data{{"name", name}};
|
||||
if (auto close = m_catalog.similar(name); !close.empty())
|
||||
@@ -304,9 +348,11 @@ PostReply McpProtocol::handle_legacy(const json& id, const std::string& method,
|
||||
return reply(200, error_body(id, kMethodNotFound, "Method not found: " + method));
|
||||
}
|
||||
|
||||
PostReply McpProtocol::handle_modern(const json& id, const std::string& method, const json& params, const std::string& version,
|
||||
const PostRequest& request)
|
||||
PostReply McpProtocol::handle_modern(const json& message, const std::string& version, const PostRequest& request)
|
||||
{
|
||||
const json& id = message["id"];
|
||||
const std::string method = message["method"].get<std::string>();
|
||||
const json& params = message["params"];
|
||||
if (version != kModernVersion)
|
||||
return reply(400, error_body(id, kUnsupportedProto, "Unsupported protocol version",
|
||||
{{"supported", supported_versions()}, {"requested", version}}));
|
||||
@@ -354,7 +400,8 @@ PostReply McpProtocol::handle_modern(const json& id, const std::string& method,
|
||||
if (method == "tools/call") {
|
||||
bool unknown = false;
|
||||
std::string name;
|
||||
json result = call_tool(params, unknown, name);
|
||||
// This era has no handshake that names the client.
|
||||
json result = call_tool(message, std::string(), unknown, name);
|
||||
if (unknown) {
|
||||
json data{{"name", name}};
|
||||
if (auto close = m_catalog.similar(name); !close.empty())
|
||||
|
||||
@@ -5,7 +5,11 @@
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
@@ -47,9 +51,19 @@ struct PostReply
|
||||
std::string body;
|
||||
};
|
||||
|
||||
// A tools/call the protocol refused before the caller saw it (an unknown tool, arguments its schema refuses, a
|
||||
// tool_call it could not resolve): the tool the client named, the call's origin as the caller would have got it
|
||||
// (McpCore::call()), and the error the client was sent.
|
||||
using RefusedCall = std::function<void(const std::string& tool, const nlohmann::json& origin, const ToolResult& error)>;
|
||||
|
||||
// The MCP protocol layer: JSON-RPC 2.0 framing and the MCP methods of both eras, independent of
|
||||
// the HTTP transport and of wx. It never throws; every failure becomes a JSON-RPC error or an
|
||||
// isError tool result.
|
||||
//
|
||||
// Every tools/call reaches the caller with its origin: `{source: "agent", client, request}`, where `request` is the
|
||||
// JSON-RPC message as received and `client` the name the client gave in `initialize`, while only one name has been
|
||||
// given since the protocol was made; once a second name comes, or for a call of the 2026-07-28 era, which has no
|
||||
// handshake, `client` is empty, since the call could be either client's.
|
||||
class McpProtocol
|
||||
{
|
||||
public:
|
||||
@@ -57,22 +71,32 @@ public:
|
||||
McpProtocol(const CommandCatalog& catalog, ToolCaller& caller, ServerInfo info);
|
||||
|
||||
PostReply handle_post(const PostRequest& request);
|
||||
// Told about each tools/call refused before the caller, on the request's thread; what it throws is dropped.
|
||||
// Set before the first request.
|
||||
void set_on_refused(RefusedCall on_refused) { m_on_refused = std::move(on_refused); }
|
||||
|
||||
static nlohmann::json tool_to_json(const NativeCommand& command);
|
||||
// The MCP result of a tool's outcome, its numbers rounded to what they say (reply_number()) unless `exact`.
|
||||
static nlohmann::json result_to_json(const ToolResult& result, bool exact = false);
|
||||
|
||||
private:
|
||||
PostReply handle_legacy(const nlohmann::json& id, const std::string& method, const nlohmann::json& params,
|
||||
const PostRequest& request);
|
||||
PostReply handle_modern(const nlohmann::json& id, const std::string& method, const nlohmann::json& params,
|
||||
const std::string& version, const PostRequest& request);
|
||||
nlohmann::json call_tool(const nlohmann::json& params, bool& unknown_tool, std::string& unknown_name);
|
||||
// `message` is a request whose id, method and params handle_post() checked.
|
||||
PostReply handle_legacy(const nlohmann::json& message, const PostRequest& request);
|
||||
PostReply handle_modern(const nlohmann::json& message, const std::string& version, const PostRequest& request);
|
||||
// `message` is the whole tools/call request, `client` the name its origin carries.
|
||||
nlohmann::json call_tool(const nlohmann::json& message, const std::string& client, bool& unknown_tool, std::string& unknown_name);
|
||||
nlohmann::json tools_list() const;
|
||||
// Remembers the client name an initialize gave; the name a legacy call is labelled with.
|
||||
void client_seen(const nlohmann::json& params);
|
||||
std::string client_label() const;
|
||||
void refused(const std::string& tool, const nlohmann::json& origin, const ToolResult& error) const;
|
||||
|
||||
const CommandCatalog& m_catalog;
|
||||
ToolCaller& m_caller;
|
||||
ServerInfo m_info;
|
||||
RefusedCall m_on_refused;
|
||||
mutable std::mutex m_clients_mutex;
|
||||
std::set<std::string> m_clients;
|
||||
};
|
||||
|
||||
// Decodes the `=?base64?...?=` sentinel form of an Mcp-Name / Mcp-Param header value; plain values
|
||||
|
||||
@@ -836,6 +836,7 @@ bool McpRecorder::encode_when_closed(AutomationRuntime& runtime, json args, std:
|
||||
call.command = *encode;
|
||||
call.command.journal = false;
|
||||
call.args = std::move(args);
|
||||
call.origin = {{"source", "person"}};
|
||||
// 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()));
|
||||
@@ -893,7 +894,8 @@ void McpRecorder::shutdown(std::chrono::milliseconds timeout)
|
||||
rec->sink->abort("app_closing");
|
||||
}
|
||||
|
||||
void McpRecorder::call_started(uint64_t call, const NativeCommand& def, const json& args, const std::string& /*parent*/)
|
||||
void McpRecorder::call_started(uint64_t call, const NativeCommand& def, const json& args, const std::string& /*parent*/,
|
||||
const std::string& /*job*/, const json& /*origin*/)
|
||||
{
|
||||
// Calls that act on the app; the inspect ones, recording tools included, only look.
|
||||
if (def.guard == GuardClass::Inspect)
|
||||
|
||||
@@ -131,7 +131,8 @@ public:
|
||||
// still queued and leaves the rest to the sink's threads.
|
||||
void shutdown(std::chrono::milliseconds timeout);
|
||||
|
||||
void call_started(uint64_t call, const NativeCommand& command, const nlohmann::json& args, const std::string& parent) override;
|
||||
void call_started(uint64_t call, const NativeCommand& command, const nlohmann::json& args, const std::string& parent,
|
||||
const std::string& job, const nlohmann::json& origin) override;
|
||||
void call_args(uint64_t call, const nlohmann::json& args) override;
|
||||
void call_ended(uint64_t call, const ToolResult& result) override;
|
||||
|
||||
|
||||
@@ -48,7 +48,8 @@ bool is_job_envelope(const ToolResult& r)
|
||||
return status == "running" || status == "blocked_by_dialog";
|
||||
}
|
||||
|
||||
// Resolves one placeholder body ("vars.model", "env:HOME", ...) to a JSON value.
|
||||
} // namespace
|
||||
|
||||
std::optional<json> resolve_placeholder(const std::string& key, const Replay& replay, const ReplayContext& ctx)
|
||||
{
|
||||
if (key == "replay_dir")
|
||||
@@ -74,6 +75,8 @@ std::optional<json> resolve_placeholder(const std::string& key, const Replay& re
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// How a substitution went: in lenient mode an unresolvable placeholder is kept as written; otherwise
|
||||
// the first one fails the substitution and is recorded here, so replay_run can say why.
|
||||
struct Substitution
|
||||
@@ -81,8 +84,27 @@ struct Substitution
|
||||
bool lenient = false;
|
||||
std::string err;
|
||||
std::string failed; // the placeholder's body, e.g. "jobs.prefs"
|
||||
// What may still be put in, when bounded (substitute_lenient()'s budget); once it is spent, a placeholder is left
|
||||
// unresolved.
|
||||
std::size_t* budget = nullptr;
|
||||
};
|
||||
|
||||
// resolve_placeholder(), charged to `sub`'s budget: each value put in takes its size. An empty string and null are free:
|
||||
// neither holds a placeholder, so neither leads to more work, and the text that holds theirs is the caller's or a value
|
||||
// already charged, at least four bytes a placeholder.
|
||||
std::optional<json> resolve_charged(const std::string& key, const Replay& replay, const ReplayContext& ctx, Substitution& sub)
|
||||
{
|
||||
if (sub.budget != nullptr && *sub.budget == 0)
|
||||
return std::nullopt;
|
||||
std::optional<json> v = resolve_placeholder(key, replay, ctx);
|
||||
if (v && sub.budget != nullptr && !v->is_null()) {
|
||||
const std::size_t size = v->is_string() ? v->get_ref<const std::string&>().size() :
|
||||
v->dump(-1, ' ', false, json::error_handler_t::replace).size();
|
||||
*sub.budget -= std::min(*sub.budget, size);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// The 1-based index of the step that saves its job as `name`, or 0.
|
||||
std::size_t step_saving(const Replay& replay, const std::string& name)
|
||||
{
|
||||
@@ -135,7 +157,7 @@ json substitute_value(const json& value, const Replay& replay, const ReplayConte
|
||||
const std::string text = value.get<std::string>();
|
||||
std::smatch whole;
|
||||
if (std::regex_match(text, whole, placeholder)) {
|
||||
auto v = resolve_placeholder(whole[1].str(), replay, ctx);
|
||||
auto v = resolve_charged(whole[1].str(), replay, ctx, sub);
|
||||
if (!v) {
|
||||
if (!sub.lenient)
|
||||
fail_placeholder(sub, whole[1].str(), text, replay);
|
||||
@@ -150,7 +172,7 @@ json substitute_value(const json& value, const Replay& replay, const ReplayConte
|
||||
for (auto it = begin; it != std::sregex_iterator(); ++it) {
|
||||
out.append(text, last, std::size_t(it->position()) - last);
|
||||
last = std::size_t(it->position() + it->length());
|
||||
auto v = resolve_placeholder((*it)[1].str(), replay, ctx);
|
||||
auto v = resolve_charged((*it)[1].str(), replay, ctx, sub);
|
||||
if (!v) {
|
||||
if (!sub.lenient) {
|
||||
fail_placeholder(sub, (*it)[1].str(), it->str(), replay);
|
||||
@@ -160,7 +182,7 @@ json substitute_value(const json& value, const Replay& replay, const ReplayConte
|
||||
continue;
|
||||
}
|
||||
const json resolved = substitute_value(*v, replay, ctx, sub, depth + 1);
|
||||
out += resolved.is_string() ? resolved.get<std::string>() : resolved.dump();
|
||||
out += resolved.is_string() ? resolved.get<std::string>() : resolved.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
}
|
||||
out.append(text, last, std::string::npos);
|
||||
return json(out);
|
||||
@@ -358,9 +380,11 @@ json substitute_args(const std::string& tool, const json& args, const Replay& re
|
||||
steps.push_back(substitute_value(step, replay, ctx, sub, 0));
|
||||
continue;
|
||||
}
|
||||
json done = json::object();
|
||||
// A step's tool that isn't a string is the nested replay's to refuse, as it parses it.
|
||||
const std::string nested_tool = step.contains("tool") && step["tool"].is_string() ? step["tool"].get<std::string>() : std::string();
|
||||
json done = json::object();
|
||||
for (auto part = step.begin(); part != step.end(); ++part)
|
||||
done[part.key()] = part.key() == "args" ? substitute_args(step.value("tool", std::string()), part.value(), replay, ctx, sub) :
|
||||
done[part.key()] = part.key() == "args" ? substitute_args(nested_tool, part.value(), replay, ctx, sub) :
|
||||
substitute_value(part.value(), replay, ctx, sub, 0);
|
||||
steps.push_back(std::move(done));
|
||||
}
|
||||
@@ -390,6 +414,22 @@ json substitute_lenient(const json& value, const Replay& replay, const ReplayCon
|
||||
return substitute_value(value, replay, ctx, sub, 0);
|
||||
}
|
||||
|
||||
json substitute_lenient(const json& value, const Replay& replay, const ReplayContext& ctx, std::size_t& budget)
|
||||
{
|
||||
Substitution sub;
|
||||
sub.lenient = true;
|
||||
sub.budget = &budget;
|
||||
return substitute_value(value, replay, ctx, sub, 0);
|
||||
}
|
||||
|
||||
json substitute_args_lenient(const std::string& tool, const json& args, const Replay& replay, const ReplayContext& ctx, std::size_t& budget)
|
||||
{
|
||||
Substitution sub;
|
||||
sub.lenient = true;
|
||||
sub.budget = &budget;
|
||||
return substitute_args(tool, args, replay, ctx, sub);
|
||||
}
|
||||
|
||||
std::optional<ExpectFailure> check_expect_detail(const json& result, const json& expect)
|
||||
{
|
||||
for (auto it = expect.begin(); it != expect.end(); ++it) {
|
||||
|
||||
@@ -67,6 +67,20 @@ nlohmann::json substitute(const nlohmann::json& value, const Replay& replay, con
|
||||
// for describing steps before a run, when saved jobs and the like may not exist yet.
|
||||
nlohmann::json substitute_lenient(const nlohmann::json& value, const Replay& replay, const ReplayContext& ctx);
|
||||
|
||||
// As substitute_lenient(), with what is put in bounded: each value put in takes its size from `budget` (an empty string
|
||||
// or null nothing), and once it is spent the placeholders left stay as written. Variables that put each other in grow as the power of
|
||||
// the nesting, which reading what a replay will put in (the activity log's masking) must not follow without end.
|
||||
nlohmann::json substitute_lenient(const nlohmann::json& value, const Replay& replay, const ReplayContext& ctx, std::size_t& budget);
|
||||
|
||||
// A step's arguments as the bounded substitute_lenient() fills them in, except Python source, which a replay runs as
|
||||
// written: the code of a script_run call, of one a tool_call makes, and of those an inline replay's steps make.
|
||||
nlohmann::json substitute_args_lenient(const std::string& tool, const nlohmann::json& args, const Replay& replay,
|
||||
const ReplayContext& ctx, std::size_t& budget);
|
||||
|
||||
// What a replay puts in for one placeholder body ("vars.model", "env:HOME", "jobs.save", "replay_dir"); nullopt for
|
||||
// one it can't resolve.
|
||||
std::optional<nlohmann::json> resolve_placeholder(const std::string& key, const Replay& replay, const ReplayContext& ctx);
|
||||
|
||||
// Checks `expect` ({"/json/pointer": {"op": operand, ...}, ...}) against a step's result. nullopt
|
||||
// when every matcher passes, else a message naming the pointer and matcher that failed.
|
||||
// Matchers: eq ne gt ge lt le contains regex exists empty.
|
||||
|
||||
@@ -316,7 +316,7 @@ PostReply answer_offline(const std::string& line, const std::map<std::string, st
|
||||
// A tool needs the app, so the bridge never brings a tools/call here.
|
||||
struct NoApp final : ToolCaller
|
||||
{
|
||||
ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("OrcaSlicer is not running."); }
|
||||
ToolResult call(const NativeCommand&, const json&, const json&) override { return ToolResult::error("OrcaSlicer is not running."); }
|
||||
};
|
||||
static NoApp caller;
|
||||
// Made on the first request answered here, the only time `catalog` is called: this process never starts
|
||||
|
||||
@@ -213,6 +213,8 @@ std::string refusal_hint(const Ops::Refusal& refusal);
|
||||
|
||||
// Typed argument access with defaults; schema validation has already checked the types. arg_int() refuses
|
||||
// (ToolFailure, invalid_argument) a number that no int holds, rather than narrowing it into another value.
|
||||
// arg_string() gives the fallback for a missing or non-string member, and for `args` that isn't an object, so it also
|
||||
// reads JSON nothing checked.
|
||||
std::string arg_string(const nlohmann::json& args, const char* key, const std::string& fallback = {});
|
||||
int arg_int(const nlohmann::json& args, const char* key, int fallback);
|
||||
double arg_double(const nlohmann::json& args, const char* key, double fallback);
|
||||
@@ -332,8 +334,8 @@ nlohmann::json editor_tool_catalog(const CommandCatalog& catalog);
|
||||
|
||||
// Starts recording_encode 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 recording_stop starts, which a replay of the recording
|
||||
// asks for again. Any thread.
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args);
|
||||
// asks for again; the Agent Activity pane lists it with the stop, whose job is `stop_job`. Any thread.
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args, const std::string& stop_job);
|
||||
|
||||
// ---- settings (McpToolsConfig.cpp) -----------------------------------------------------------
|
||||
|
||||
|
||||
@@ -510,6 +510,18 @@ void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad)
|
||||
json::array({action("help_benchmark_3d_scene", L("Benchmark 3D Scene"), L("Help"), "", json::object(),
|
||||
benchmark)}),
|
||||
[](const json&) { return MenuItems::benchmark_3d_scene(); }));
|
||||
|
||||
// The Agent Activity pane's menu item, which has no argument form.
|
||||
const std::string activity = "Show or hide the Agent Activity pane, where a person watches what agents, Action Replay, Run Script, "
|
||||
"the command line's run and plugins do in the app, call by call. It is the person's: it lists your "
|
||||
"calls, and you never need it.";
|
||||
NativeCommand toggle_activity = menu_command("view_toggle_activity_panel", L("Agent Activity"), activity, object_schema({}),
|
||||
json::array({action("toggle_agent_activity_panel", L("Agent Activity"), L("View"), "",
|
||||
json::object(), activity)}),
|
||||
[](const json&) { return MenuItems::toggle_agent_activity_panel(); });
|
||||
// A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it.
|
||||
toggle_activity.listed = false;
|
||||
catalog.add(std::move(toggle_activity));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -351,6 +351,7 @@ std::shared_ptr<PersonRun> start_python_session(AutomationRuntime& runtime, std:
|
||||
|
||||
FollowedCall call;
|
||||
call.command = std::move(def);
|
||||
call.origin = {{"source", "run_script"}};
|
||||
call.person = true;
|
||||
call.ended = [&runtime, run, session, hosted](const std::optional<ToolResult>& r) {
|
||||
run->mark_ended();
|
||||
|
||||
@@ -96,7 +96,7 @@ std::vector<std::string> encode_preset_keys()
|
||||
|
||||
} // namespace
|
||||
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const json& args)
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const json& args, const std::string& stop_job)
|
||||
{
|
||||
const NativeCommand* encode = NativeCommands::instance().find("recording_encode");
|
||||
if (encode == nullptr || runtime.stopping())
|
||||
@@ -104,7 +104,7 @@ ToolResult start_encode(AutomationRuntime& runtime, const json& args)
|
||||
NativeCommand def = *encode;
|
||||
def.journal = false;
|
||||
def.budget_ms = 0; // the envelope at once; the result comes from app_wait
|
||||
return runtime.core().call(def, args);
|
||||
return runtime.core().call(def, args, {{"source", "agent"}, {"under", stop_job}});
|
||||
}
|
||||
|
||||
void register_record_tools(CommandCatalog& catalog)
|
||||
@@ -259,7 +259,7 @@ void register_record_tools(CommandCatalog& catalog)
|
||||
if (report.is_null())
|
||||
throw ToolFailure("No recording is running");
|
||||
if (!encode.is_null()) {
|
||||
const ToolResult r = start_encode(runtime, encode);
|
||||
const ToolResult r = start_encode(runtime, encode, ctx.job_id());
|
||||
report["encode"] = r.is_error ? json{{"error", r.message}} : r.data;
|
||||
}
|
||||
return ToolResult::ok(report);
|
||||
|
||||
@@ -2078,6 +2078,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
if (info.value("web", false) && native_dialog_button(top, rule.button) == wxID_NONE) {
|
||||
const int standard = standard_dialog_button(rule.button);
|
||||
start_web_answer(runtime.modals(), top, set.layer, rule.pattern, rule.button,
|
||||
info["message"].get<std::string>(),
|
||||
standard == wxID_CANCEL || standard == wxID_CLOSE ? standard : int(wxID_NONE));
|
||||
return {{"dialog", info["title"]}, {"button", rule.button}, {"web", "answering on its page"}};
|
||||
}
|
||||
@@ -2091,7 +2092,8 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
// As before any other press, the presses mouse_gesture downs left on pages end first.
|
||||
runtime.modals().before_press();
|
||||
if (press_dialog_button(top, id) != DialogPress::Failed) {
|
||||
runtime.modals().count_use(set.layer, rule.pattern, rule.button);
|
||||
runtime.modals().count_use(set.layer, rule.pattern, rule.button, info["title"].get<std::string>(),
|
||||
info["message"].get<std::string>());
|
||||
return {{"dialog", info["title"]}, {"button", rule.button}};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -979,16 +979,23 @@ bool ModalTracker::rule_in_force(int layer, const std::string& pattern, const st
|
||||
return false;
|
||||
}
|
||||
|
||||
void ModalTracker::count_use(int layer, const std::string& pattern, const std::string& button)
|
||||
void ModalTracker::count_use(int layer, const std::string& pattern, const std::string& button, const std::string& title,
|
||||
const std::string& message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
for (auto& [id, rules] : m_layers)
|
||||
if (layer == 0 || id == layer)
|
||||
for (AutoAnswerRule& r : rules)
|
||||
if (r.path.empty() && r.pattern == pattern && r.button == button) {
|
||||
++r.uses;
|
||||
return;
|
||||
}
|
||||
int used = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
for (auto& [id, rules] : m_layers)
|
||||
if (used == 0 && (layer == 0 || id == layer))
|
||||
for (AutoAnswerRule& r : rules)
|
||||
if (r.path.empty() && r.pattern == pattern && r.button == button) {
|
||||
++r.uses;
|
||||
used = id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (used != 0 && m_on_answered)
|
||||
m_on_answered(used, title, message, pattern, button);
|
||||
}
|
||||
|
||||
json ModalTracker::snapshot()
|
||||
@@ -1124,7 +1131,7 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
const bool picker = is_picker(dialog);
|
||||
// A web dialog's rule whose button is not one of its wx buttons is answered on its page, and a
|
||||
// wx dialog's rule once its button is pressed.
|
||||
std::optional<std::tuple<int, std::string, std::string>> web_rule, wx_rule;
|
||||
std::optional<std::tuple<int, std::string, std::string>> web_rule, wx_rule, used;
|
||||
const int answer = [&] {
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer) {
|
||||
@@ -1140,6 +1147,7 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
std::string why;
|
||||
const int id = answer_picker(dialog, rule, why);
|
||||
++rule.uses;
|
||||
used.emplace(layer->first, rule.pattern, rule.button);
|
||||
// A picker is named by its prompt, as its title is often empty.
|
||||
if (why.empty())
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered picker \"" << message << "\" with path \"" << rule.path
|
||||
@@ -1160,6 +1168,7 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
if (id != wxID_NONE && (id == wxID_CANCEL || !picker) && box_answers(dialog, id)) {
|
||||
if (native) {
|
||||
++rule.uses;
|
||||
used.emplace(layer->first, rule.pattern, rule.button);
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << title << "\" with " << rule.button
|
||||
<< " (rule \"" << rule.pattern << "\")";
|
||||
} else
|
||||
@@ -1170,6 +1179,10 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
}
|
||||
return int(wxID_NONE);
|
||||
}();
|
||||
if (used && m_on_answered) {
|
||||
const auto& [layer, pattern, button] = *used;
|
||||
m_on_answered(layer, title, message, pattern, button);
|
||||
}
|
||||
// A native dialog has no handlers to run: ShowModal() returns the id without showing it.
|
||||
if (answer != wxID_NONE && native)
|
||||
return answer;
|
||||
@@ -1185,7 +1198,7 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
// with it if it is destroyed first; a modal opened above it before then leaves it to
|
||||
// dialog_answer. The tracker lives as long as the app.
|
||||
if (wx_rule)
|
||||
dialog->CallAfter([this, dialog, answer, title, rule = *wx_rule] {
|
||||
dialog->CallAfter([this, dialog, answer, title, message, rule = *wx_rule] {
|
||||
const auto& [layer, pattern, button] = rule;
|
||||
// The rule may have been paused (a Run Script work ended) or dropped since the press was queued.
|
||||
if (top() != dialog || !rule_in_force(layer, pattern, button))
|
||||
@@ -1197,14 +1210,15 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
<< "; the dialog stays open";
|
||||
return;
|
||||
}
|
||||
count_use(layer, pattern, button);
|
||||
count_use(layer, pattern, button, title, message);
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << title << "\" with " << button << " (rule \"" << pattern
|
||||
<< "\")";
|
||||
});
|
||||
if (web_rule) {
|
||||
const auto& [layer, pattern, button] = *web_rule;
|
||||
const int standard = standard_dialog_button(button);
|
||||
start_web_answer(*this, dialog, layer, pattern, button, standard == wxID_CANCEL || standard == wxID_CLOSE ? standard : int(wxID_NONE));
|
||||
start_web_answer(*this, dialog, layer, pattern, button, message,
|
||||
standard == wxID_CANCEL || standard == wxID_CLOSE ? standard : int(wxID_NONE));
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
|
||||
@@ -76,7 +76,15 @@ public:
|
||||
// only as a picker opens, so a path rule sharing a pattern and button with another never takes its uses. Any
|
||||
// thread.
|
||||
bool rule_in_force(int layer, const std::string& pattern, const std::string& button) const;
|
||||
void count_use(int layer, const std::string& pattern, const std::string& button);
|
||||
// A rule of layer `layer` answered the dialog titled `title`: its uses grow, and the answer is reported
|
||||
// (set_on_answered()). UI thread.
|
||||
void count_use(int layer, const std::string& pattern, const std::string& button, const std::string& title,
|
||||
const std::string& message);
|
||||
// Told each time a rule answers a dialog: the rule's layer, the dialog's title and message (empty when unknown),
|
||||
// and the rule's pattern and button. UI thread; set before the first dialog.
|
||||
using RuleAnswered = std::function<void(int layer, const std::string& title, const std::string& message, const std::string& pattern,
|
||||
const std::string& button)>;
|
||||
void set_on_answered(RuleAnswered fn) { m_on_answered = std::move(fn); }
|
||||
|
||||
// [{title, message, class, native, buttons:[{id,label}]}] of the open modals, outermost first.
|
||||
// On the UI thread the dialogs are described as they are now, and that is published; other
|
||||
@@ -105,6 +113,7 @@ private:
|
||||
std::vector<std::uint64_t> m_serials; // m_stack's dialogs' serials
|
||||
std::uint64_t m_last_serial = 0;
|
||||
std::function<void()> m_before_press;
|
||||
RuleAnswered m_on_answered;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
nlohmann::json m_snapshot = nlohmann::json::array();
|
||||
|
||||
@@ -552,9 +552,6 @@ std::string join(const std::vector<std::string>& parts)
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace {
|
||||
|
||||
// Every scalar under `value`, as text.
|
||||
void scalars(const json& value, std::vector<std::string>& out)
|
||||
{
|
||||
if (value.is_string())
|
||||
@@ -566,6 +563,8 @@ void scalars(const json& value, std::vector<std::string>& out)
|
||||
scalars(v, out);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The values of sensitive keys anywhere in `args` (settings_set's values, a per-variant entry's value).
|
||||
void sensitive_values(const json& args, std::vector<std::string>& out)
|
||||
{
|
||||
@@ -582,7 +581,8 @@ void sensitive_values(const json& args, std::vector<std::string>& out)
|
||||
}
|
||||
}
|
||||
|
||||
// What caption_detail() leaves out of `tool`'s caption on purpose.
|
||||
} // namespace
|
||||
|
||||
std::vector<std::string> hidden_values(const std::string& tool, const json& args)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
@@ -602,27 +602,57 @@ std::vector<std::string> hidden_values(const std::string& tool, const json& args
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
json mask_hidden(json value, std::vector<std::string> hidden)
|
||||
{
|
||||
// Longest first, so a value inside another goes with it.
|
||||
std::sort(hidden.begin(), hidden.end(), [](const std::string& a, const std::string& b) { return a.size() > b.size(); });
|
||||
hidden.erase(std::remove(hidden.begin(), hidden.end(), std::string()), hidden.end());
|
||||
// What is taken out of longer text, each value as it is and as text that dumps JSON writes it ("a\"b" for a"b), from
|
||||
// three characters on: a shorter one would take out pieces of unrelated text.
|
||||
std::vector<std::string> forms;
|
||||
for (const std::string& value : hidden)
|
||||
if (value.size() >= 3) {
|
||||
const std::string quoted = json(value).dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
forms.push_back(quoted.substr(1, quoted.size() - 2));
|
||||
forms.push_back(value);
|
||||
}
|
||||
const std::function<void(json&)> walk = [&](json& v) {
|
||||
if (v.is_object()) {
|
||||
for (auto& [key, member] : v.items()) {
|
||||
if (is_sensitive_key(key) && !member.is_null())
|
||||
member = kMask;
|
||||
else
|
||||
walk(member);
|
||||
}
|
||||
} else if (v.is_array()) {
|
||||
for (json& item : v)
|
||||
walk(item);
|
||||
} else if (v.is_string()) {
|
||||
std::string& text = v.get_ref<std::string&>();
|
||||
if (std::find(hidden.begin(), hidden.end(), text) != hidden.end()) {
|
||||
v = kMask;
|
||||
return;
|
||||
}
|
||||
for (const std::string& form : forms)
|
||||
for (std::size_t at = text.find(form); at != std::string::npos; at = text.find(form, at + kMask.size()))
|
||||
text.replace(at, form.size(), kMask);
|
||||
} else if ((v.is_number() || v.is_boolean()) && !hidden.empty()) {
|
||||
if (std::find(hidden.begin(), hidden.end(), v.dump()) != hidden.end())
|
||||
v = kMask;
|
||||
}
|
||||
};
|
||||
walk(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string caption_error(const std::string& tool, const json& args, const std::string& error)
|
||||
{
|
||||
std::vector<std::string> hidden = hidden_values(tool, args);
|
||||
// Longest first, so a value inside another goes with it.
|
||||
std::sort(hidden.begin(), hidden.end(), [](const std::string& a, const std::string& b) { return a.size() > b.size(); });
|
||||
std::string out = error;
|
||||
for (const std::string& value : hidden) {
|
||||
if (value.empty())
|
||||
continue;
|
||||
if (value.size() < 3)
|
||||
const std::vector<std::string> hidden = hidden_values(tool, args);
|
||||
// A value too short to take out of other text safely leaves the error out.
|
||||
for (const std::string& value : hidden)
|
||||
if (!value.empty() && value.size() < 3)
|
||||
return {};
|
||||
// As it is, and as an error that dumps JSON writes it ("a\"b" for a"b).
|
||||
const std::string quoted = json(value).dump();
|
||||
const std::string escaped = quoted.substr(1, quoted.size() - 2);
|
||||
for (const std::string& form : {escaped, value})
|
||||
for (std::size_t at = out.find(form); at != std::string::npos; at = out.find(form, at + 9))
|
||||
out.replace(at, form.size(), "\xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2");
|
||||
}
|
||||
return out;
|
||||
return mask_hidden(json(error), hidden).get<std::string>();
|
||||
}
|
||||
|
||||
std::string shorten(const std::string& text, std::size_t limit)
|
||||
@@ -671,7 +701,7 @@ std::string caption_detail(const std::string& tool, const json& args)
|
||||
if (args.contains("values") && args["values"].is_object()) {
|
||||
std::vector<std::string> pairs;
|
||||
for (const auto& [key, value] : args["values"].items())
|
||||
pairs.push_back(key + " = " + (is_sensitive_key(key) ? std::string("\xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2") : scalar_text(value)));
|
||||
pairs.push_back(key + " = " + (is_sensitive_key(key) ? kMask : scalar_text(value)));
|
||||
return join(pairs);
|
||||
}
|
||||
const json what = describe_call(NativeCommands::instance(), tool, args);
|
||||
|
||||
@@ -225,6 +225,23 @@ std::string caption_detail(const std::string& tool, const nlohmann::json& args);
|
||||
// left out altogether. Give it the whole error, and shorten() it afterwards.
|
||||
std::string caption_error(const std::string& tool, const nlohmann::json& args, const std::string& error);
|
||||
|
||||
// What caption_detail() leaves out of `tool`'s caption on purpose, as text: the values of sensitive settings and
|
||||
// arguments (is_sensitive_key()), typed text, a value set into a field not found by its setting key, and a page's
|
||||
// JavaScript.
|
||||
std::vector<std::string> hidden_values(const std::string& tool, const nlohmann::json& args);
|
||||
|
||||
// `value` with what must not show replaced by "•••": every member of a sensitive key (is_sensitive_key()), every string
|
||||
// or number that is one of `hidden`, and `hidden`'s values inside longer strings, as they are and as JSON escapes them,
|
||||
// where a value has three characters or more (a shorter one would take out pieces of unrelated text).
|
||||
nlohmann::json mask_hidden(nlohmann::json value, std::vector<std::string> hidden);
|
||||
|
||||
// What mask_hidden() and caption_error() put in place of what they hide.
|
||||
inline const std::string kMask = "\xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2";
|
||||
|
||||
// Adds every string and number under `value` to `out`, as text: what a hidden value that is an object or an array
|
||||
// holds.
|
||||
void scalars(const nlohmann::json& value, std::vector<std::string>& out);
|
||||
|
||||
// The first line of `text`, cut to at most `limit` bytes at a character boundary and marked "..." when cut.
|
||||
std::string shorten(const std::string& text, std::size_t limit);
|
||||
|
||||
|
||||
@@ -637,8 +637,14 @@ namespace {
|
||||
class WebAnswer : public wxTimer
|
||||
{
|
||||
public:
|
||||
WebAnswer(ModalTracker& tracker, wxDialog* dialog, int layer, std::string pattern, std::string label, int fallback)
|
||||
: m_tracker(tracker), m_dialog(dialog), m_layer(layer), m_pattern(std::move(pattern)), m_label(std::move(label)), m_fallback(fallback)
|
||||
WebAnswer(ModalTracker& tracker, wxDialog* dialog, int layer, std::string pattern, std::string label, std::string message, int fallback)
|
||||
: m_tracker(tracker)
|
||||
, m_dialog(dialog)
|
||||
, m_layer(layer)
|
||||
, m_pattern(std::move(pattern))
|
||||
, m_label(std::move(label))
|
||||
, m_message(std::move(message))
|
||||
, m_fallback(fallback)
|
||||
{}
|
||||
|
||||
void Notify() override
|
||||
@@ -681,7 +687,7 @@ private:
|
||||
if (m_done || reply.state != PageReply::State::Answered || reply.value.contains("error"))
|
||||
return;
|
||||
if (reply.value.contains("pressed") && reply.value["pressed"].is_string()) {
|
||||
m_tracker.count_use(m_layer, m_pattern, m_label);
|
||||
m_tracker.count_use(m_layer, m_pattern, m_label, title(), m_message);
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered web dialog \"" << title() << "\" with its page's \"" << m_label << "\" (rule \""
|
||||
<< m_pattern << "\")";
|
||||
finish();
|
||||
@@ -716,7 +722,7 @@ private:
|
||||
<< " for \"" << m_label << "\", and its " << m_label << " button is "
|
||||
<< (press == DialogPress::Hidden ? "not shown" : "disabled") << "; gave up";
|
||||
else {
|
||||
m_tracker.count_use(m_layer, m_pattern, m_label);
|
||||
m_tracker.count_use(m_layer, m_pattern, m_label, dialog_title, m_message);
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << m_pattern << "\": the page of \"" << dialog_title << "\" " << why
|
||||
<< " for \"" << m_label << "\"; ended the dialog with " << m_label;
|
||||
}
|
||||
@@ -742,7 +748,7 @@ private:
|
||||
ModalTracker& m_tracker;
|
||||
wxWeakRef<wxDialog> m_dialog;
|
||||
int m_layer;
|
||||
std::string m_pattern, m_label;
|
||||
std::string m_pattern, m_label, m_message;
|
||||
int m_fallback;
|
||||
bool m_pending = false, m_done = false;
|
||||
int m_unshown = 0; // ticks in a row without a shown web view
|
||||
@@ -752,9 +758,10 @@ private:
|
||||
|
||||
} // namespace
|
||||
|
||||
void start_web_answer(ModalTracker& tracker, wxDialog* dialog, int layer, const std::string& pattern, const std::string& label, int fallback)
|
||||
void start_web_answer(ModalTracker& tracker, wxDialog* dialog, int layer, const std::string& pattern, const std::string& label,
|
||||
const std::string& message, int fallback)
|
||||
{
|
||||
auto* answer = new WebAnswer(tracker, dialog, layer, pattern, label, fallback);
|
||||
auto* answer = new WebAnswer(tracker, dialog, layer, pattern, label, message, fallback);
|
||||
answer->Start(250);
|
||||
}
|
||||
|
||||
|
||||
@@ -198,9 +198,9 @@ void release_web_presses(const std::shared_ptr<WebPresses>& presses, const std::
|
||||
// and the answer ends. The 10 s limit counts only time a complete document is shown and restarts
|
||||
// when the document changes, so a dialog's bootstrap page replaced by its content is waited out;
|
||||
// script errors, navigation and pending replies never end it. Past the limit, `fallback` (cancel or
|
||||
// close, else wxID_NONE) ends the dialog natively, otherwise the answer gives up. UI thread only;
|
||||
// `tracker` outlives every answer.
|
||||
// close, else wxID_NONE) ends the dialog natively, otherwise the answer gives up. `message` is the dialog's, which the
|
||||
// answer reports (ModalTracker::count_use()). UI thread only; `tracker` outlives every answer.
|
||||
void start_web_answer(ModalTracker& tracker, wxDialog* dialog, int layer, const std::string& pattern, const std::string& label,
|
||||
int fallback);
|
||||
const std::string& message, int fallback);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -101,6 +101,9 @@ AppActionRunResult refresh_plugins();
|
||||
// ---- Scripts ----
|
||||
AppActionRunResult toggle_run_script_panel();
|
||||
|
||||
// ---- Agent Activity ----
|
||||
AppActionRunResult toggle_agent_activity_panel();
|
||||
|
||||
// The schema of the argument of a command that opens or imports a file, in place of its file dialog: the absolute path
|
||||
// of `what`.
|
||||
nlohmann::json input_file(const char* what);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#include "I18N.hpp"
|
||||
#include "Shortcuts.hpp"
|
||||
#include "MainFrame.hpp"
|
||||
#include "AgentActivityPanel.hpp"
|
||||
#include "RunScriptPanel.hpp"
|
||||
#include "NetworkTestDialog.hpp"
|
||||
#include "Operations/ExportOps.hpp"
|
||||
@@ -1024,6 +1025,14 @@ AppActionRunResult MenuItems::toggle_run_script_panel()
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}
|
||||
|
||||
// ---- Agent Activity ----
|
||||
AppActionRunResult MenuItems::toggle_agent_activity_panel()
|
||||
{
|
||||
if (wxGetApp().mainframe != nullptr)
|
||||
wxGetApp().agent_activity_panel().toggle();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The headings of the places, in the order tools/list gives them.
|
||||
|
||||
@@ -7316,12 +7316,14 @@ struct Plater::priv
|
||||
// GUI elements
|
||||
AuiMgr m_aui_mgr;
|
||||
// Live dock panes. `on_close` runs when the user closes one from its close button; `shown` is
|
||||
// what the owner asked for; `hide_on_close` keeps the pane's window when it is closed.
|
||||
// what the owner asked for; `hide_on_close` keeps the pane's window when it is closed; `floats_on_every_tab`
|
||||
// keeps it up, floated, on the tabs other than Prepare and Preview.
|
||||
struct DockPane
|
||||
{
|
||||
std::function<void()> on_close;
|
||||
bool hide_on_close{false};
|
||||
bool shown{true};
|
||||
bool floats_on_every_tab{false};
|
||||
};
|
||||
std::map<wxWindow*, DockPane> m_dock_panes;
|
||||
wxString m_default_window_layout;
|
||||
@@ -7544,7 +7546,7 @@ struct Plater::priv
|
||||
void reset_window_layout();
|
||||
Sidebar::DockingState get_sidebar_docking_state();
|
||||
void add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock,
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close);
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close, bool floats_on_every_tab);
|
||||
void remove_dock_pane(wxWindow* window);
|
||||
void show_dock_pane(wxWindow* window, bool show);
|
||||
bool dock_pane_visible(const DockPane& dock_pane, const wxAuiPaneInfo& pane) const;
|
||||
@@ -8855,12 +8857,13 @@ void Plater::priv::reset_window_layout()
|
||||
|
||||
bool Plater::priv::dock_pane_visible(const DockPane& dock_pane, const wxAuiPaneInfo& pane) const
|
||||
{
|
||||
// A floating pane is a top-level window, so it does not hide with the Plater on other tabs.
|
||||
return dock_pane.shown && (!pane.IsFloating() || sidebar_layout.show);
|
||||
// A floating pane is a top-level window, so it does not hide with the Plater on other tabs: it is hidden there,
|
||||
// unless it stays up on every tab.
|
||||
return dock_pane.shown && (!pane.IsFloating() || sidebar_layout.show || dock_pane.floats_on_every_tab);
|
||||
}
|
||||
|
||||
void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock,
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close)
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close, bool floats_on_every_tab)
|
||||
{
|
||||
const wxString base_name = wxString::FromUTF8(name);
|
||||
wxString unique_name = base_name;
|
||||
@@ -8894,7 +8897,7 @@ void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, cons
|
||||
info.Right();
|
||||
}
|
||||
|
||||
const DockPane& dock_pane = m_dock_panes[window] = DockPane{std::move(on_close), hide_on_close};
|
||||
const DockPane& dock_pane = m_dock_panes[window] = DockPane{std::move(on_close), hide_on_close, true, floats_on_every_tab};
|
||||
info.Show(dock_pane_visible(dock_pane, info));
|
||||
m_aui_mgr.AddPane(window, info);
|
||||
|
||||
@@ -19974,9 +19977,14 @@ void Plater::reset_window_layout()
|
||||
}
|
||||
|
||||
void Plater::add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock,
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close)
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close, bool floats_on_every_tab)
|
||||
{
|
||||
p->add_dock_pane(window, name, caption, dock, size, std::move(on_close), hide_on_close);
|
||||
p->add_dock_pane(window, name, caption, dock, size, std::move(on_close), hide_on_close, floats_on_every_tab);
|
||||
}
|
||||
bool Plater::is_dock_pane_floating(wxWindow* window) const
|
||||
{
|
||||
const wxAuiPaneInfo& pane = p->m_aui_mgr.GetPane(window);
|
||||
return pane.IsOk() && pane.IsFloating();
|
||||
}
|
||||
void Plater::remove_dock_pane(wxWindow* window) { p->remove_dock_pane(window); }
|
||||
void Plater::remove_dock_panes()
|
||||
|
||||
@@ -611,9 +611,13 @@ public:
|
||||
// Dock panes sit alongside the sidebar; `window` must be a child of the Plater. `dock` is
|
||||
// "left", "right", "bottom" or "float", and `size` is in DIPs. A pane closed from its own close
|
||||
// button is destroyed after on_close runs, or, with `hide_on_close`, hidden as show_dock_pane(window,
|
||||
// false) hides it, keeping the window; remove_dock_pane() destroys it without calling on_close.
|
||||
// false) hides it, keeping the window; remove_dock_pane() destroys it without calling on_close. A pane
|
||||
// shows on Prepare and Preview, docked or floating; with `floats_on_every_tab`, floating it shows on every tab.
|
||||
void add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock,
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close = false);
|
||||
const wxSize& size, std::function<void()> on_close, bool hide_on_close = false,
|
||||
bool floats_on_every_tab = false);
|
||||
// Whether the dock pane `window` floats in a window of its own.
|
||||
bool is_dock_pane_floating(wxWindow* window) const;
|
||||
void remove_dock_pane(wxWindow* window);
|
||||
void show_dock_pane(wxWindow* window, bool show);
|
||||
// Removes every dock pane without calling on_close, for MainFrame::shutdown() (app exit and a
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "Plater.hpp"
|
||||
#include "Shortcuts.hpp"
|
||||
#include "format.hpp"
|
||||
#include "Mcp/ActivityLog.hpp"
|
||||
#include "Mcp/AutomationRuntime.hpp"
|
||||
#include "Mcp/McpArguments.hpp"
|
||||
#include "Mcp/McpPaths.hpp"
|
||||
@@ -40,7 +41,6 @@
|
||||
#include <wx/gdicmn.h>
|
||||
#include <wx/glcanvas.h>
|
||||
#include <wx/panel.h>
|
||||
#include <wx/sizer.h>
|
||||
#include <wx/string.h>
|
||||
#include <wx/timer.h>
|
||||
#include <wx/webview.h>
|
||||
@@ -270,41 +270,9 @@ RunScriptPane::RunScriptPane(wxWindow* parent, RunScriptPanel& owner)
|
||||
{
|
||||
const fs::path page = fs::path(resources_dir()) / "web" / "dialog" / "RunScript" / "index.html";
|
||||
m_page = wxFileName(from_path(page));
|
||||
// Created empty and loaded once the user scripts are in, so the first load has them, as a WebViewHostDialog's page does.
|
||||
m_web = WebView::CreateWebView(this, wxEmptyString);
|
||||
auto* sizer = new wxBoxSizer(wxVERTICAL);
|
||||
if (m_web != nullptr)
|
||||
sizer->Add(m_web, 1, wxEXPAND);
|
||||
SetSizer(sizer);
|
||||
if (m_web == nullptr)
|
||||
return;
|
||||
// WebView2's accelerator keys would reload the page (Ctrl+R, F5) and zoom it.
|
||||
m_web->EnableBrowserAcceleratorKeys(false);
|
||||
m_web->AddUserScript(wxString::FromUTF8(WebViewHostDialog::theme_user_script()));
|
||||
m_web->AddUserScript(wxString::FromUTF8(WebViewHostDialog::localized_strings_script(page_strings())));
|
||||
m_web->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, [this](wxWebViewEvent& event) {
|
||||
json payload;
|
||||
try {
|
||||
payload = json::parse(event.GetString().utf8_string());
|
||||
} catch (const std::exception&) {
|
||||
return;
|
||||
}
|
||||
// Out of the web view's message callback: window work on its stack (file dialogs, prompts) is a crash class on GTK
|
||||
// and macOS.
|
||||
wxGetApp().CallAfter([owner = &m_owner, alive = m_alive, payload = std::move(payload)] {
|
||||
if (alive->load())
|
||||
owner->handle(payload);
|
||||
});
|
||||
});
|
||||
m_web->Bind(wxEVT_WEBVIEW_NAVIGATING, &RunScriptPane::on_navigating, this);
|
||||
// A theme toggle re-themes the page in place.
|
||||
m_web->Bind(EVT_WEBVIEW_RECREATED, [this](wxCommandEvent&) {
|
||||
WebView::RunScript(m_web, wxString::FromUTF8(WebViewHostDialog::theme_apply_script()));
|
||||
});
|
||||
wxString url = file_url_from_path(page);
|
||||
if (const wxString lang = wxGetApp().current_language_code_safe(); !lang.empty())
|
||||
url += "?lang=" + lang;
|
||||
WebView::LoadUrl(m_web, url);
|
||||
m_web = WebViewHostDialog::create_pane_web_view(
|
||||
this, page, page_strings(), m_alive, [owner = &m_owner](const json& payload) { owner->handle(payload); },
|
||||
[this](wxWebViewEvent& event) { on_navigating(event); });
|
||||
}
|
||||
|
||||
RunScriptPane::~RunScriptPane()
|
||||
@@ -372,6 +340,8 @@ RunScriptPanel::~RunScriptPanel()
|
||||
m_session->end();
|
||||
m_session->stop();
|
||||
}
|
||||
if (m_running)
|
||||
work_ended("cancelled", {});
|
||||
if (m_api_thread.joinable())
|
||||
m_api_thread.join();
|
||||
}
|
||||
@@ -478,7 +448,9 @@ void RunScriptPanel::main_window_closing()
|
||||
m_backlog.clear();
|
||||
}
|
||||
m_waiting.reset();
|
||||
m_running = false;
|
||||
// The work's end, which its session reports to no page now, is the stop.
|
||||
if (m_running)
|
||||
work_ended("cancelled", {});
|
||||
m_ready_timer.Stop();
|
||||
m_pane = nullptr;
|
||||
m_editor_keys.clear();
|
||||
@@ -868,6 +840,12 @@ void RunScriptPanel::run(const json& payload)
|
||||
work.first_line = std::max(1, payload.value("first_line", 1));
|
||||
}
|
||||
json started{{"command", "run_started"}, {"kind", kind}, {"first_line", work.first_line}};
|
||||
m_work = {{"work", kind}, {"file", m_file.empty() ? std::string("<script_run>") : Mcp::path_to_utf8(m_file)}, {"code", work.code}};
|
||||
if (kind == "cell") {
|
||||
m_work["cell"] = payload.value("cell", 1);
|
||||
m_work["title"] = payload.value("title", "");
|
||||
m_work["lines"] = {work.first_line, std::max(work.first_line, payload.value("last_line", work.first_line))};
|
||||
}
|
||||
|
||||
// The script's tool calls act on the main window, and keys it sends without a target go where the focus is.
|
||||
if (MainFrame* frame = wxGetApp().mainframe) {
|
||||
@@ -905,8 +883,7 @@ bool RunScriptPanel::start_session()
|
||||
events.finished = [this, alive = m_alive, session](const json& result, const json&) {
|
||||
if (!alive->load() || session != m_session || !m_running)
|
||||
return;
|
||||
m_running = false;
|
||||
send({{"command", "run_finished"}, {"status", "refused"}, {"message", result.value("error", std::string())}});
|
||||
refused_run(result.value("error", std::string()));
|
||||
};
|
||||
m_session_run = Mcp::start_python_session(*s, session, m_file, std::move(events));
|
||||
if (!m_session_run) {
|
||||
@@ -933,8 +910,12 @@ void RunScriptPanel::end_session()
|
||||
|
||||
void RunScriptPanel::submit(PythonWork work, const json& started)
|
||||
{
|
||||
// Reported before the session can run it, so the calls it makes find it.
|
||||
m_work_result.clear();
|
||||
if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started())
|
||||
runtime->activity().work_started(m_work);
|
||||
if (!m_session->submit(std::move(work))) {
|
||||
m_running = false;
|
||||
work_ended("refused", _u8L("The script could not run."));
|
||||
refuse(_u8L("The script could not run."));
|
||||
return;
|
||||
}
|
||||
@@ -988,8 +969,10 @@ void RunScriptPanel::tick()
|
||||
flush();
|
||||
if (event.kind == PythonSessionEvent::Kind::Cell)
|
||||
send({{"command", "cell"}, {"index", event.cell}});
|
||||
else if (event.kind == PythonSessionEvent::Kind::Result)
|
||||
else if (event.kind == PythonSessionEvent::Kind::Result) {
|
||||
m_work_result = event.text;
|
||||
send({{"command", "result"}, {"text", event.text}});
|
||||
}
|
||||
else
|
||||
finish_run(event);
|
||||
m_backlog.pop_front();
|
||||
@@ -1011,16 +994,36 @@ void RunScriptPanel::tick()
|
||||
}
|
||||
} else if (m_running) {
|
||||
// Ended without reporting its work: its job was refused, or the runtime stopped.
|
||||
m_running = false;
|
||||
send({{"command", "run_finished"}, {"status", "refused"}, {"message", _u8L("Scripts can't run while OrcaSlicer is starting or closing.")}});
|
||||
refused_run(_u8L("Scripts can't run while OrcaSlicer is starting or closing."));
|
||||
}
|
||||
}
|
||||
send_session_state();
|
||||
}
|
||||
|
||||
void RunScriptPanel::work_ended(const std::string& status, const std::string& message)
|
||||
{
|
||||
m_running = false;
|
||||
// The result is the JSON text the session wrote (PythonSessionEvent::Result).
|
||||
json result;
|
||||
if (!m_work_result.empty()) {
|
||||
result = json::parse(m_work_result, nullptr, false);
|
||||
if (result.is_discarded())
|
||||
result = m_work_result;
|
||||
}
|
||||
m_work_result.clear();
|
||||
if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started())
|
||||
runtime->activity().work_ended(status, message, result);
|
||||
}
|
||||
|
||||
void RunScriptPanel::refused_run(const std::string& message)
|
||||
{
|
||||
work_ended("refused", message);
|
||||
send({{"command", "run_finished"}, {"status", "refused"}, {"message", message}});
|
||||
}
|
||||
|
||||
void RunScriptPanel::finish_run(const PythonSessionEvent& done)
|
||||
{
|
||||
m_running = false;
|
||||
work_ended(done.status, done.message);
|
||||
const std::string status = done.status;
|
||||
std::string status_text;
|
||||
if (status == "cancelled" || status == "timed_out")
|
||||
|
||||
@@ -103,6 +103,11 @@ private:
|
||||
void end_session();
|
||||
// Submits `work` and tells the page with `started`, unless that is null: the page was told when the work had to wait.
|
||||
void submit(PythonWork work, const nlohmann::json& started);
|
||||
// The run ended, and the work the panel reported to the Agent Activity pane with it, with the status a Finished
|
||||
// event gives.
|
||||
void work_ended(const std::string& status, const std::string& message);
|
||||
// The run was refused after it started: its work ends, and the page is told the run finished, refused.
|
||||
void refused_run(const std::string& message);
|
||||
void tick();
|
||||
void finish_run(const PythonSessionEvent& done);
|
||||
void send_runtime_state();
|
||||
@@ -129,6 +134,9 @@ private:
|
||||
bool m_detached = false;
|
||||
bool m_session_ending = false;
|
||||
std::optional<PythonWork> m_waiting; // a Run all waiting for the old session to end
|
||||
// The run's work as the Agent Activity pane lists it, and the JSON result it left.
|
||||
nlohmann::json m_work;
|
||||
std::string m_work_result;
|
||||
std::deque<PythonSessionEvent> m_backlog;
|
||||
bool m_running = false;
|
||||
std::chrono::steady_clock::time_point m_run_started;
|
||||
|
||||
@@ -25,6 +25,10 @@
|
||||
#include <wx/string.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <wx/webview.h>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
@@ -170,6 +174,47 @@ boost::filesystem::path WebViewHostDialog::dropped_file(const wxString& url)
|
||||
return into_path(wxFileSystem::URLToFileName(url.BeforeFirst('?').BeforeFirst('#')).GetFullPath());
|
||||
}
|
||||
|
||||
wxWebView* WebViewHostDialog::create_pane_web_view(wxWindow* pane, const boost::filesystem::path& page, const nlohmann::json& strings,
|
||||
std::shared_ptr<std::atomic<bool>> alive,
|
||||
std::function<void(const nlohmann::json&)> on_message,
|
||||
std::function<void(wxWebViewEvent&)> on_navigating)
|
||||
{
|
||||
// Created empty and loaded once the user scripts are in, so the first load has them, as a WebViewHostDialog's page does.
|
||||
wxWebView* web = WebView::CreateWebView(pane, wxEmptyString);
|
||||
auto* sizer = new wxBoxSizer(wxVERTICAL);
|
||||
if (web != nullptr)
|
||||
sizer->Add(web, 1, wxEXPAND);
|
||||
pane->SetSizer(sizer);
|
||||
if (web == nullptr)
|
||||
return nullptr;
|
||||
// WebView2's accelerator keys would reload the page (Ctrl+R, F5) and zoom it.
|
||||
web->EnableBrowserAcceleratorKeys(false);
|
||||
web->AddUserScript(wxString::FromUTF8(theme_user_script()));
|
||||
web->AddUserScript(wxString::FromUTF8(localized_strings_script(strings)));
|
||||
web->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, [alive, on_message = std::move(on_message)](wxWebViewEvent& event) {
|
||||
nlohmann::json payload;
|
||||
try {
|
||||
payload = nlohmann::json::parse(event.GetString().utf8_string());
|
||||
} catch (const std::exception&) {
|
||||
return;
|
||||
}
|
||||
// Out of the web view's message callback: window work on its stack (file dialogs, prompts) is a crash class on
|
||||
// GTK and macOS.
|
||||
wxGetApp().CallAfter([alive, on_message, payload = std::move(payload)] {
|
||||
if (alive->load())
|
||||
on_message(payload);
|
||||
});
|
||||
});
|
||||
web->Bind(wxEVT_WEBVIEW_NAVIGATING, std::move(on_navigating));
|
||||
// A theme toggle re-themes the page in place.
|
||||
web->Bind(EVT_WEBVIEW_RECREATED, [web](wxCommandEvent&) { WebView::RunScript(web, wxString::FromUTF8(theme_apply_script())); });
|
||||
wxString url = file_url_from_path(page);
|
||||
if (const wxString lang = wxGetApp().current_language_code_safe(); !lang.empty())
|
||||
url += "?lang=" + lang;
|
||||
WebView::LoadUrl(web, url);
|
||||
return web;
|
||||
}
|
||||
|
||||
nlohmann::json WebViewHostDialog::code_editor_strings()
|
||||
{
|
||||
// The annotation, error-marker and gutter-tooltip messages are left out: these editors never show them.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
@@ -84,6 +85,15 @@ public:
|
||||
static bool own_page_navigation(const wxString& url, const wxFileName& page);
|
||||
// The file a file: URL names: a web view navigates to a file dropped on it. Empty for any other URL.
|
||||
static boost::filesystem::path dropped_file(const wxString& url);
|
||||
// A web view filling the dock pane `pane`, on the bundled page `page`, as every dock pane's page wants it: with the
|
||||
// theme and `strings` in before it loads, the browser's reload and zoom keys off, a theme toggle applied in place
|
||||
// and the UI's language in the URL. A message from the page reaches `on_message` after the web view's callback,
|
||||
// while `alive`; every navigation reaches `on_navigating`, which vetoes what isn't the page's own. Null when no web
|
||||
// view can be made.
|
||||
static wxWebView* create_pane_web_view(wxWindow* pane, const boost::filesystem::path& page, const nlohmann::json& strings,
|
||||
std::shared_ptr<std::atomic<bool>> alive,
|
||||
std::function<void(const nlohmann::json&)> on_message,
|
||||
std::function<void(wxWebViewEvent&)> on_navigating);
|
||||
|
||||
protected:
|
||||
wxWebView* browser() const { return m_browser; }
|
||||
|
||||
@@ -54,11 +54,13 @@ private:
|
||||
class DirectCaller final : public ToolCaller
|
||||
{
|
||||
public:
|
||||
std::vector<std::string> called; // the tools it ran, in order
|
||||
std::vector<std::string> called; // the tools it ran, in order
|
||||
std::vector<nlohmann::json> origins; // and who the protocol said made each call
|
||||
|
||||
ToolResult call(const NativeCommand& def, const nlohmann::json& args) override
|
||||
ToolResult call(const NativeCommand& def, const nlohmann::json& args, const nlohmann::json& origin = nlohmann::json()) override
|
||||
{
|
||||
called.push_back(def.key);
|
||||
origins.push_back(origin);
|
||||
struct Context final : ToolContext
|
||||
{
|
||||
std::string id;
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
@@ -24,6 +25,7 @@
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <new>
|
||||
#include <optional>
|
||||
@@ -862,7 +864,7 @@ struct HeardCalls final : CallObserver
|
||||
{
|
||||
std::mutex mutex;
|
||||
std::vector<std::string> events;
|
||||
void call_started(uint64_t, const NativeCommand& def, const json&, const std::string& parent) override
|
||||
void call_started(uint64_t, const NativeCommand& def, const json&, const std::string& parent, const std::string&, const json&) override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
events.push_back("start " + def.key + (parent.empty() ? "" : " in a job"));
|
||||
@@ -906,7 +908,7 @@ TEST_CASE("the call observer hears inline, job and child calls, and not calls re
|
||||
});
|
||||
slice.budget_ms = 100;
|
||||
h.registry.add(slice);
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &heard);
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, std::vector<CallObserver*>{&heard});
|
||||
|
||||
CHECK_FALSE(h.call("look").is_error);
|
||||
CHECK(heard.take() == std::vector<std::string>{"start look", "end ok"});
|
||||
@@ -926,6 +928,114 @@ TEST_CASE("the call observer hears inline, job and child calls, and not calls re
|
||||
CHECK(heard.take() == std::vector<std::string>{"end ok"});
|
||||
}
|
||||
|
||||
// What the activity list hears of each call: its tool, its parent's job, its own job and its origin, in order.
|
||||
struct HeardOrigins final : CallObserver
|
||||
{
|
||||
struct Heard
|
||||
{
|
||||
std::string tool, parent, job;
|
||||
json origin;
|
||||
};
|
||||
std::mutex mutex;
|
||||
std::vector<Heard> heard;
|
||||
std::vector<std::string> queued; // "queued <job>" and "ended <call>" as they come, for the order
|
||||
std::map<uint64_t, std::string> jobs_of; // call -> its job, as queued
|
||||
void call_queued(uint64_t call, const std::string& job, const std::string&, const json&) override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
queued.push_back("queued " + job);
|
||||
jobs_of[call] = job;
|
||||
}
|
||||
void call_started(uint64_t, const NativeCommand& def, const json&, const std::string& parent, const std::string& job,
|
||||
const json& origin) override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
heard.push_back({def.key, parent, job, origin});
|
||||
queued.push_back("started " + job);
|
||||
}
|
||||
void call_args(uint64_t, const json&) override {}
|
||||
void call_ended(uint64_t call, const ToolResult&) override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
if (const auto it = jobs_of.find(call); it != jobs_of.end())
|
||||
queued.push_back("ended " + it->second);
|
||||
}
|
||||
std::vector<Heard> take()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
return std::exchange(heard, {});
|
||||
}
|
||||
};
|
||||
|
||||
TEST_CASE("every observer hears a call's job and origin, and a child call's parent job without an origin", "[Mcp]")
|
||||
{
|
||||
Harness h;
|
||||
HeardOrigins first, second;
|
||||
NativeCommand look = tool("look", GuardClass::Inspect, [](const json&, ToolContext&) { return ToolResult::ok(); });
|
||||
look.inline_call = true;
|
||||
h.registry.add(look);
|
||||
h.registry.add(tool("act", GuardClass::Mutate, [](const json&, ToolContext&) { return ToolResult::ok(); }));
|
||||
h.registry.add(tool("replay", GuardClass::Mutate, [](const json&, ToolContext& ctx) {
|
||||
ctx.call_child("look", json::object());
|
||||
return ctx.call_child("act", json::object());
|
||||
}));
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{},
|
||||
std::vector<CallObserver*>{&first, &second});
|
||||
|
||||
const json agent{{"source", "agent"}, {"client", "Claude Code"}, {"request", {{"method", "tools/call"}, {"id", 7}}}};
|
||||
CHECK_FALSE(h.core->call(*h.registry.find("look"), json::object(), agent).is_error);
|
||||
std::vector<HeardOrigins::Heard> heard = first.take();
|
||||
REQUIRE(heard.size() == 1);
|
||||
CHECK(heard[0].tool == "look");
|
||||
CHECK(heard[0].job.empty()); // inline: no job of its own
|
||||
CHECK(heard[0].parent.empty());
|
||||
CHECK(heard[0].origin == agent);
|
||||
|
||||
CHECK_FALSE(h.core->call(*h.registry.find("replay"), json::object(), {{"source", "action_replay"}}).is_error);
|
||||
heard = first.take();
|
||||
REQUIRE(heard.size() == 3);
|
||||
CHECK(heard[0].tool == "replay");
|
||||
CHECK_FALSE(heard[0].job.empty());
|
||||
CHECK(heard[0].origin == json{{"source", "action_replay"}});
|
||||
CHECK(heard[1].tool == "look");
|
||||
CHECK(heard[1].parent == heard[0].job);
|
||||
CHECK(heard[1].job.empty());
|
||||
CHECK(heard[1].origin.is_null());
|
||||
CHECK(heard[2].tool == "act");
|
||||
CHECK(heard[2].parent == heard[0].job);
|
||||
CHECK_FALSE(heard[2].job.empty());
|
||||
CHECK(heard[2].origin.is_null());
|
||||
|
||||
CHECK_FALSE(h.core->call_plugin(*h.registry.find("act"), json::object(), "measure").is_error);
|
||||
heard = first.take();
|
||||
REQUIRE(heard.size() == 1);
|
||||
CHECK_FALSE(heard[0].job.empty());
|
||||
CHECK(heard[0].origin == json{{"source", "plugin"}, {"plugin", "measure"}});
|
||||
|
||||
std::promise<ToolResult> ended;
|
||||
REQUIRE_FALSE(h.core->submit(*h.registry.find("act"), json::object(), [&ended](const ToolResult& r) { ended.set_value(r); }).empty());
|
||||
CHECK_FALSE(ended.get_future().get().is_error);
|
||||
heard = first.take();
|
||||
REQUIRE(heard.size() == 1);
|
||||
CHECK(heard[0].origin == json{{"source", "person"}});
|
||||
|
||||
CHECK(second.take().size() == 6); // the second observer heard every call too
|
||||
|
||||
// A job call is queued, on the calling thread, before its thread starts it; an inline call is not queued.
|
||||
const std::vector<std::string> order = [&] {
|
||||
std::lock_guard<std::mutex> lock(first.mutex);
|
||||
return first.queued;
|
||||
}();
|
||||
REQUIRE_FALSE(order.empty());
|
||||
for (std::size_t i = 0; i < order.size(); ++i)
|
||||
if (order[i].rfind("started ", 0) == 0 && order[i] != "started ") {
|
||||
const std::string job = order[i].substr(8);
|
||||
const auto at = std::find(order.begin(), order.end(), "queued " + job);
|
||||
CHECK(at != order.end());
|
||||
CHECK(at - order.begin() < std::ptrdiff_t(i));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("a child call whose arguments its schema refuses carries the tool_describe hint", "[Mcp]")
|
||||
{
|
||||
Harness h;
|
||||
@@ -951,7 +1061,10 @@ TEST_CASE("an observer that throws fails no call", "[Mcp]")
|
||||
{
|
||||
struct Throwing final : CallObserver
|
||||
{
|
||||
void call_started(uint64_t, const NativeCommand&, const json&, const std::string&) override { throw std::runtime_error("started"); }
|
||||
void call_started(uint64_t, const NativeCommand&, const json&, const std::string&, const std::string&, const json&) override
|
||||
{
|
||||
throw std::runtime_error("started");
|
||||
}
|
||||
void call_args(uint64_t, const json&) override { throw std::bad_alloc(); }
|
||||
void call_ended(uint64_t, const ToolResult&) override { throw std::runtime_error("ended"); }
|
||||
} throwing;
|
||||
@@ -963,7 +1076,7 @@ TEST_CASE("an observer that throws fails no call", "[Mcp]")
|
||||
ctx.set_journal_args({{"x", 1}});
|
||||
return ToolResult::ok({{"done", true}});
|
||||
}));
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, &throwing);
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{}, std::vector<CallObserver*>{&throwing});
|
||||
const ToolResult looked = h.call("look");
|
||||
CHECK_FALSE(looked.is_error);
|
||||
CHECK(looked.data["seen"] == true);
|
||||
@@ -1735,11 +1848,23 @@ TEST_CASE("a plugin's job never starts once the plugin unloads, as it registers
|
||||
h.registry.add(tool("make", GuardClass::Mutate, [&](const json&, ToolContext&) { ++ran; return ToolResult::ok(); }));
|
||||
h.timing.soft_budget = std::chrono::milliseconds(10000);
|
||||
h.start();
|
||||
HeardOrigins heard;
|
||||
h.core = std::make_unique<McpCore>(h.registry, h.invoker, h.jobs, &h.journal, h.timing, WorkerHooks{},
|
||||
std::vector<CallObserver*>{&heard});
|
||||
const ToolResult r = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure");
|
||||
CHECK(r.is_error);
|
||||
CHECK(r.message.find("unloaded") != std::string::npos);
|
||||
CHECK(ran == 0);
|
||||
CHECK(h.jobs.running_owned_by("measure").empty());
|
||||
// A call queued and never started is ended all the same; one refused before its job registered is never queued.
|
||||
std::lock_guard<std::mutex> lock(heard.mutex);
|
||||
if (unload_at == 3) {
|
||||
REQUIRE(heard.queued.size() == 2);
|
||||
CHECK(heard.queued[0].rfind("queued ", 0) == 0);
|
||||
CHECK(heard.queued[1].rfind("ended ", 0) == 0);
|
||||
} else
|
||||
CHECK(heard.queued.empty());
|
||||
CHECK(heard.heard.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("a plugin's running call is cancelled the moment the plugin unloads", "[Mcp]")
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -670,6 +671,89 @@ TEST_CASE("tool_call runs and is journaled as the tool it names", "[Mcp]")
|
||||
CHECK(unknown["content"][0]["text"].get<std::string>().find(R"({"code":"invalid_argument"})") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a call carries its client's name while one client has said its name, and none once two have", "[Mcp]")
|
||||
{
|
||||
Fixture f;
|
||||
const auto initialize = [&f](const char* name) {
|
||||
f.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"},
|
||||
{"params", {{"protocolVersion", "2025-06-18"}, {"clientInfo", {{"name", name}, {"version", "1"}}}}}});
|
||||
};
|
||||
const json call{{"jsonrpc", "2.0"}, {"id", 3}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"text", "hi"}}}}}};
|
||||
|
||||
// Before any handshake a call is the agent's, unnamed, and carries the message it came in.
|
||||
f.post(call);
|
||||
REQUIRE(f.caller.origins.size() == 1);
|
||||
CHECK(f.caller.origins.back() == json{{"source", "agent"}, {"client", ""}, {"request", call}});
|
||||
|
||||
initialize("Claude Code");
|
||||
initialize("Claude Code"); // the same client reconnecting is still one name
|
||||
f.post(call);
|
||||
CHECK(f.caller.origins.back()["client"] == "Claude Code");
|
||||
|
||||
initialize("Codex");
|
||||
f.post(call);
|
||||
CHECK(f.caller.origins.back()["client"] == "");
|
||||
|
||||
// A 2026-07-28 call has no handshake: whoever it is, it is unnamed.
|
||||
Fixture fresh;
|
||||
fresh.post({{"jsonrpc", "2.0"}, {"id", 1}, {"method", "initialize"},
|
||||
{"params", {{"protocolVersion", "2025-06-18"}, {"clientInfo", {{"name", "Claude Code"}}}}}});
|
||||
fresh.post({{"jsonrpc", "2.0"}, {"id", 2}, {"method", "tools/call"}, {"params", modern_params({{"name", "echo"}, {"arguments", {{"text", "hi"}}}})}},
|
||||
"2026-07-28", "tools/call", "echo");
|
||||
REQUIRE(fresh.caller.origins.size() == 1);
|
||||
CHECK(fresh.caller.origins.back()["client"] == "");
|
||||
}
|
||||
|
||||
TEST_CASE("a tool_call reaches the caller with its message as sent, and a call refused before it is reported", "[Mcp]")
|
||||
{
|
||||
Fixture f;
|
||||
NativeCommand api;
|
||||
api.key = "tool_call";
|
||||
api.input_schema = {{"type", "object"},
|
||||
{"properties", {{"tool", {{"type", "string"}}}, {"args", {{"type", "object"}}}}},
|
||||
{"required", {"tool"}}};
|
||||
api.run = [](const json&, ToolContext&) -> ToolResult { throw ToolFailure("not dispatched"); };
|
||||
f.registry.add(api);
|
||||
struct Refusal
|
||||
{
|
||||
std::string tool;
|
||||
json origin;
|
||||
ToolResult error;
|
||||
};
|
||||
std::vector<Refusal> refusals;
|
||||
f.protocol.set_on_refused([&refusals](const std::string& tool, const json& origin, const ToolResult& error) {
|
||||
refusals.push_back({tool, origin, error});
|
||||
});
|
||||
|
||||
const json wrapped{{"jsonrpc", "2.0"}, {"id", 4}, {"method", "tools/call"},
|
||||
{"params", {{"name", "tool_call"}, {"arguments", {{"tool", "echo"}, {"args", {{"text", "hi"}}}}}}}};
|
||||
f.post(wrapped);
|
||||
REQUIRE(f.caller.called == std::vector<std::string>{"echo"});
|
||||
CHECK(f.caller.origins.back()["request"] == wrapped);
|
||||
CHECK(refusals.empty());
|
||||
|
||||
const json bad{{"jsonrpc", "2.0"}, {"id", 5}, {"method", "tools/call"}, {"params", {{"name", "echo"}, {"arguments", {{"txt", "hi"}}}}}};
|
||||
f.post(bad);
|
||||
REQUIRE(refusals.size() == 1);
|
||||
CHECK(refusals[0].tool == "echo");
|
||||
CHECK(refusals[0].origin == json{{"source", "agent"}, {"client", ""}, {"request", bad}});
|
||||
CHECK(refusals[0].error.is_error);
|
||||
CHECK(refusals[0].error.message.rfind("Invalid arguments for echo: unknown argument txt", 0) == 0);
|
||||
|
||||
// A tool_call that names an unknown tool is the call of the tool it names; an unknown tool is refused too.
|
||||
f.post({{"jsonrpc", "2.0"}, {"id", 6}, {"method", "tools/call"}, {"params", {{"name", "tool_call"}, {"arguments", {{"tool", "ech"}}}}}});
|
||||
f.post({{"jsonrpc", "2.0"}, {"id", 7}, {"method", "tools/call"}, {"params", {{"name", "ecko"}}}});
|
||||
REQUIRE(refusals.size() == 3);
|
||||
CHECK(refusals[1].tool == "ech");
|
||||
CHECK(refusals[2].tool == "ecko");
|
||||
CHECK(refusals[2].error.message == f.registry.unknown_command("ecko"));
|
||||
CHECK(f.caller.called.size() == 1); // none of them reached the caller
|
||||
|
||||
// What the listener throws never reaches the client.
|
||||
f.protocol.set_on_refused([](const std::string&, const json&, const ToolResult&) { throw std::runtime_error("listener"); });
|
||||
CHECK(f.post(bad).status == 200);
|
||||
}
|
||||
|
||||
// Holds the one operation a plugin offers while it is loaded.
|
||||
class MeasureSource final : public CommandSource
|
||||
{
|
||||
|
||||
@@ -224,6 +224,34 @@ TEST_CASE("await false stores the job under save_as for later steps", "[Mcp]")
|
||||
CHECK(f.calls[2].second["job"] == "j5");
|
||||
}
|
||||
|
||||
TEST_CASE("a bounded substitution charges what it puts in, and nothing for an empty string or null", "[Mcp]")
|
||||
{
|
||||
Replay r;
|
||||
r.vars = {{"a", "xyz"}, {"e", ""}, {"n", nullptr}};
|
||||
std::size_t budget = 3;
|
||||
// Free: the empty variable, the replay's folder (empty here) and null, which is still put in.
|
||||
CHECK(substitute_lenient(json("${vars.e}${out_dir}${vars.n}"), r, ReplayContext{}, budget) == "null");
|
||||
CHECK(substitute_lenient(json("${vars.n}"), r, ReplayContext{}, budget).is_null());
|
||||
CHECK(budget == 3);
|
||||
// A value costs its length; past the budget, a placeholder stays as written.
|
||||
CHECK(substitute_lenient(json("${vars.a}${vars.a}"), r, ReplayContext{}, budget) == "xyz${vars.a}");
|
||||
CHECK(budget == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("an inline replay's step whose tool isn't a string is left to the nested run to refuse", "[Mcp]")
|
||||
{
|
||||
FakeHost f;
|
||||
f.tools["replay_run"] = [](const json&) { return ToolResult::error("step 1: \"tool\" must be a string"); };
|
||||
const Replay s = parse_ok(R"({"orca_replay_version": "0.2.0", "steps": [
|
||||
{"tool": "replay_run", "args": {"replay": {"steps": [{"tool": 17, "args": {}}]}}}]})");
|
||||
ReplayContext ctx;
|
||||
const json out = run_replay(s, ctx, f.host());
|
||||
CHECK(out["passed"] == false);
|
||||
CHECK(out["failed_step"] == 1);
|
||||
REQUIRE(f.calls.size() == 1);
|
||||
CHECK(f.calls[0].second["replay"]["steps"][0]["tool"] == 17);
|
||||
}
|
||||
|
||||
TEST_CASE("a run stops at the first failed step unless it is optional", "[Mcp]")
|
||||
{
|
||||
FakeHost f;
|
||||
|
||||
@@ -7215,6 +7215,36 @@
|
||||
"read_only": false,
|
||||
"title": "Refresh Plugins"
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
"args": {},
|
||||
"description": "Show or hide the Agent Activity pane, where a person watches what agents, Action Replay, Run Script, the command line's run and plugins do in the app, call by call. It is the person's: it lists your calls, and you never need it.",
|
||||
"group": "View",
|
||||
"icon": "",
|
||||
"key": "toggle_agent_activity_panel",
|
||||
"title": "Agent Activity"
|
||||
}
|
||||
],
|
||||
"completion": "immediate",
|
||||
"description": "Show or hide the Agent Activity pane, where a person watches what agents, Action Replay, Run Script, the command line's run and plugins do in the app, call by call. It is the person's: it lists your calls, and you never need it.",
|
||||
"destructive": false,
|
||||
"group": "View and windows",
|
||||
"guard": "mutate",
|
||||
"has_own_action": false,
|
||||
"idempotent": false,
|
||||
"input_schema": {
|
||||
"additionalProperties": false,
|
||||
"properties": {},
|
||||
"type": "object"
|
||||
},
|
||||
"key": "view_toggle_activity_panel",
|
||||
"listed": false,
|
||||
"open_world": false,
|
||||
"operations": [],
|
||||
"read_only": false,
|
||||
"title": "Agent Activity"
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
{
|
||||
|
||||
@@ -818,6 +818,11 @@
|
||||
"command": "script_toggle_panel",
|
||||
"args": {}
|
||||
},
|
||||
{
|
||||
"key": "toggle_agent_activity_panel",
|
||||
"command": "view_toggle_activity_panel",
|
||||
"args": {}
|
||||
},
|
||||
{
|
||||
"key": "toggle_developer_mode",
|
||||
"command": "settings_toggle_developer_mode",
|
||||
|
||||
@@ -62,6 +62,13 @@
|
||||
"icon": "media_play",
|
||||
"input": ""
|
||||
},
|
||||
{
|
||||
"key": "toggle_agent_activity_panel",
|
||||
"title": "Agent Activity",
|
||||
"group": "View",
|
||||
"icon": "",
|
||||
"input": ""
|
||||
},
|
||||
{
|
||||
"key": "open_action_replay",
|
||||
"title": "Action Replay",
|
||||
|
||||
@@ -30,6 +30,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_scene_raycaster.cpp
|
||||
test_scene_benchmark.cpp
|
||||
test_lazy.cpp
|
||||
test_mcp_activity_log.cpp
|
||||
test_mcp_config.cpp
|
||||
test_mcp_core.cpp
|
||||
test_operations.cpp
|
||||
|
||||
@@ -181,7 +181,7 @@ const std::vector<std::pair<std::string, std::set<std::string>>> kPlaces{
|
||||
{"printer_send", "printer_list_models", "printer_install", "printer_uninstall", "print_start", "printer_test_host",
|
||||
"printer_status", "print_pause", "print_resume", "print_stop"}},
|
||||
{"Plugins", {"plugin_list", "plugin_install_local", "plugin_enable", "plugin_reload", "plugin_uninstall", "plugin_refresh"}},
|
||||
{"View and windows", {"view_set", "window_list", "window_set", "window_open"}},
|
||||
{"View and windows", {"view_set", "view_toggle_activity_panel", "window_list", "window_set", "window_open"}},
|
||||
{"Recordings, replays and scripts",
|
||||
{"script_list_api", "script_describe_api", "window_screenshot", "recording_start", "recording_stop", "recording_encode", "replay_run", "replay_export",
|
||||
"script_run", "window_save_screenshot", "script_toggle_panel"}},
|
||||
@@ -202,12 +202,12 @@ std::vector<std::string> group_runs(const CommandCatalog& catalog, const std::ve
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("the process catalog gives the Speed Dial its 129 command actions", "[CommandCatalog]")
|
||||
TEST_CASE("the process catalog gives the Speed Dial its 130 command actions", "[CommandCatalog]")
|
||||
{
|
||||
const CommandCatalog& catalog = NativeCommands::instance();
|
||||
CHECK(catalog.sealed());
|
||||
const std::vector<NativeCommands::SpeedDialAction> speed_dial = NativeCommands::speed_dial_actions(catalog);
|
||||
CHECK(speed_dial.size() == 129);
|
||||
CHECK(speed_dial.size() == 130);
|
||||
for (const NativeCommands::SpeedDialAction& t : speed_dial) {
|
||||
REQUIRE(t.command != nullptr);
|
||||
INFO(t.command->key);
|
||||
@@ -223,12 +223,12 @@ TEST_CASE("the process catalog gives the Speed Dial its 129 command actions", "[
|
||||
|
||||
TEST_CASE("every Speed Dial action of today is still a command's action", "[CommandCatalog][SpeedDial]")
|
||||
{
|
||||
// The Speed Dial's 129 actions of commands, each with its id, title, section, icon and input: each is an action of
|
||||
// The Speed Dial's 130 actions of commands, each with its id, title, section, icon and input: each is an action of
|
||||
// the Speed Dial with that presentation, and the Speed Dial has no other.
|
||||
std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_actions.json", std::ios::binary);
|
||||
REQUIRE(in.is_open());
|
||||
const json fixture = json::parse(in);
|
||||
REQUIRE(fixture.size() == 129);
|
||||
REQUIRE(fixture.size() == 130);
|
||||
|
||||
const CommandCatalog& catalog = NativeCommands::instance();
|
||||
std::vector<std::string> expected;
|
||||
@@ -272,11 +272,11 @@ TEST_CASE("a menu item's id is an action's key, not a command", "[CommandCatalog
|
||||
|
||||
TEST_CASE("every action is its command's, with the design's arguments, and they fit its schema", "[CommandCatalog][SpeedDial]")
|
||||
{
|
||||
// Each of the 129 actions with the command the design folds its menu item into and the arguments it runs it with.
|
||||
// Each of the 130 actions with the command the design folds its menu item into and the arguments it runs it with.
|
||||
std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_action_calls.json", std::ios::binary);
|
||||
REQUIRE(in.is_open());
|
||||
const json fixture = json::parse(in);
|
||||
REQUIRE(fixture.size() == 129);
|
||||
REQUIRE(fixture.size() == 130);
|
||||
|
||||
const CommandCatalog& catalog = NativeCommands::instance();
|
||||
std::size_t folded = 0;
|
||||
@@ -314,7 +314,7 @@ TEST_CASE("every action is its command's, with the design's arguments, and they
|
||||
CHECK(Mcp::argument_error(*command, call).empty());
|
||||
}
|
||||
// Every action of today, under the command the design folds its menu item into.
|
||||
CHECK(folded == 129);
|
||||
CHECK(folded == 130);
|
||||
|
||||
// The actions that ask need none of what the silent form requires; one more argument is the silent form.
|
||||
const NativeCommand* save = catalog.find("project_save");
|
||||
@@ -430,7 +430,7 @@ TEST_CASE("a menu item's action runs its command with the item's arguments", "[S
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("outside the Design tab the catalog has its commands and 129 actions", "[CommandCatalog]")
|
||||
TEST_CASE("outside the Design tab the catalog has its commands and 130 actions", "[CommandCatalog]")
|
||||
{
|
||||
// The section the Speed Dial shows each action in, by its key.
|
||||
std::ifstream in(std::string(TEST_DATA_DIR) + "/speed_dial_actions.json", std::ios::binary);
|
||||
@@ -457,12 +457,12 @@ TEST_CASE("outside the Design tab the catalog has its commands and 129 actions",
|
||||
// The commands outside the Design tab: the typed tools, the commands made from menu items, the seven Parts 4a to 4c
|
||||
// add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the seven gizmo commands, the six printing
|
||||
// commands, the four of the filament list (filament_list, filament_edit_mixed, filament_set_colour and
|
||||
// filament_set_flushing), tool_describe, script_describe_api and settings_list_pages.
|
||||
CHECK(commands == 138);
|
||||
// The eight commands named as their menu items keep an action of their own; the other 121 actions are items.
|
||||
// filament_set_flushing), tool_describe, script_describe_api, settings_list_pages and view_toggle_activity_panel.
|
||||
CHECK(commands == 139);
|
||||
// The eight commands named as their menu items keep an action of their own; the other 122 actions are items.
|
||||
CHECK(own == std::set<std::string>{"plate_add", "plate_delete", "plate_duplicate", "plate_rename", "filament_add", "filament_delete",
|
||||
"undo", "redo"});
|
||||
CHECK(items == 121);
|
||||
CHECK(items == 122);
|
||||
}
|
||||
|
||||
TEST_CASE("the commands outside the Design tab are the design's, under its headings", "[CommandCatalog]")
|
||||
@@ -485,7 +485,7 @@ TEST_CASE("the commands outside the Design tab are the design's, under its headi
|
||||
commands += keys.size();
|
||||
}
|
||||
CHECK(by_heading.size() == kPlaces.size());
|
||||
CHECK(commands == 138);
|
||||
CHECK(commands == 139);
|
||||
|
||||
// tool_list's group says which there are.
|
||||
const NativeCommand* list = NativeCommands::find("tool_list");
|
||||
@@ -523,8 +523,9 @@ TEST_CASE("every command that runs from arguments is in the tool list, by place"
|
||||
else
|
||||
unlisted.insert(c.key);
|
||||
}
|
||||
// The three menu items with no argument form, which tool_list lists and tool_call runs.
|
||||
CHECK(unlisted == std::set<std::string>{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"});
|
||||
// The four menu items with no argument form, which tool_list lists and tool_call runs.
|
||||
CHECK(unlisted == std::set<std::string>{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode",
|
||||
"view_toggle_activity_panel"});
|
||||
// Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the
|
||||
// seven gizmo commands, the six printing commands, the filament list's four, tool_describe, script_describe_api and
|
||||
// settings_list_pages.
|
||||
@@ -747,10 +748,10 @@ TEST_CASE("the Speed Dial's actions are under the menu items' keys, not the tool
|
||||
"open_preferences", "open_wiki", "open_youtube", "plate_add", "plate_delete", "plate_duplicate", "plate_goto",
|
||||
"plate_rename", "plate_toggle_lock", "preset_bundle", "redo", "refresh_plugins", "reset_window_layout", "save_project",
|
||||
"save_project_as", "select_all", "send_gcode", "slice_all", "slice_and_preview", "start_recording", "stop_recording",
|
||||
"sync_ams", "sync_presets", "take_screenshot", "toggle_developer_mode", "toggle_run_script_panel", "undo", "view_bottom",
|
||||
"sync_ams", "sync_presets", "take_screenshot", "toggle_agent_activity_panel", "toggle_developer_mode", "toggle_run_script_panel", "undo", "view_bottom",
|
||||
"view_default", "view_fit_bed", "view_front", "view_iso", "view_left", "view_rear", "view_right",
|
||||
"view_toggle_perspective", "view_top"};
|
||||
REQUIRE(actions.size() == 129);
|
||||
REQUIRE(actions.size() == 130);
|
||||
|
||||
std::set<std::string> speed_dial;
|
||||
for (const NativeCommands::SpeedDialAction& t : NativeCommands::speed_dial_actions(NativeCommands::instance()))
|
||||
@@ -925,7 +926,7 @@ TEST_CASE("the catalog needs no runtime", "[CommandCatalog]")
|
||||
const CommandCatalog& catalog = NativeCommands::instance();
|
||||
struct NoApp final : ToolCaller
|
||||
{
|
||||
ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("no app"); }
|
||||
ToolResult call(const NativeCommand&, const json&, const json&) override { return ToolResult::error("no app"); }
|
||||
} caller;
|
||||
Mcp::McpProtocol protocol(catalog, caller, Mcp::ServerInfo{});
|
||||
const Mcp::PostReply reply = protocol.handle_post({json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}.dump(), {}, {}, {}});
|
||||
@@ -1402,7 +1403,7 @@ TEST_CASE("the reference leaves out nothing a client is told", "[CommandCatalog]
|
||||
// The entries marked listed are the tools a client's tools/list names.
|
||||
struct NoApp final : ToolCaller
|
||||
{
|
||||
ToolResult call(const NativeCommand&, const json&) override { return ToolResult::error("no app"); }
|
||||
ToolResult call(const NativeCommand&, const json&, const json&) override { return ToolResult::error("no app"); }
|
||||
} caller;
|
||||
Mcp::McpProtocol protocol(catalog, caller, Mcp::ServerInfo{});
|
||||
const Mcp::PostReply reply = protocol.handle_post({json{{"jsonrpc", "2.0"}, {"id", 1}, {"method", "tools/list"}}.dump(), {}, {}, {}});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -284,8 +284,14 @@ TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a nativ
|
||||
wxInitializer init;
|
||||
REQUIRE(init.IsOk());
|
||||
{
|
||||
ModalTracker tracker;
|
||||
tracker.push_rules({make_rule("unsaved", "Transfer"), make_rule("discard", "no")});
|
||||
ModalTracker tracker;
|
||||
const int layer = tracker.push_rules({make_rule("unsaved", "Transfer"), make_rule("discard", "no")});
|
||||
std::vector<std::string> answers; // what the tracker reports of each answer, for the Agent Activity pane
|
||||
tracker.set_on_answered([&answers](int layer, const std::string& title, const std::string&, const std::string& pattern,
|
||||
const std::string& button) {
|
||||
answers.push_back(std::to_string(layer) + " " + title + " / " + pattern + " / " + button);
|
||||
});
|
||||
const std::string in_layer = std::to_string(layer) + " ";
|
||||
|
||||
// The button's handler does the dialog's work, which ShowModal() returning its id would skip.
|
||||
wxDialog dialog(nullptr, wxID_ANY, "Unsaved changes");
|
||||
@@ -300,6 +306,7 @@ TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a nativ
|
||||
wxModalDialogHook::CallExit(&dialog);
|
||||
CHECK(tracker.top() == nullptr);
|
||||
CHECK(tracker.rules_json()[0]["uses"] == 1);
|
||||
CHECK(answers == std::vector<std::string>{in_layer + "Unsaved changes / unsaved / Transfer"});
|
||||
|
||||
// A modal opened above it before its loop ran leaves it to dialog_answer.
|
||||
wxDialog above(nullptr, wxID_ANY, "Other");
|
||||
@@ -314,6 +321,8 @@ TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a nativ
|
||||
wxMessageDialog native(nullptr, "Discard the changes?", "Changes", wxYES_NO);
|
||||
CHECK(wxModalDialogHook::CallEnter(&native) == wxID_NO);
|
||||
CHECK(tracker.top() == nullptr);
|
||||
CHECK(answers.size() == 2); // the press a modal above held back is no answer
|
||||
CHECK(answers.back() == in_layer + "Changes / discard / no");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -214,8 +214,8 @@ TEST_CASE("what action_run journals for an action of fixed arguments is a call i
|
||||
}
|
||||
return checked;
|
||||
};
|
||||
// The 129 Speed Dial entries outside the Design tab are commands' actions: eight own and 121 items.
|
||||
CHECK(check_actions(NativeCommands::instance()) == 129);
|
||||
// The 130 Speed Dial entries outside the Design tab are commands' actions: eight own and 122 items.
|
||||
CHECK(check_actions(NativeCommands::instance()) == 130);
|
||||
|
||||
const auto recorded_for = [](const CommandCatalog& catalog, const char* key, const json& given) {
|
||||
const auto [command, action] = find_command_action(catalog, key);
|
||||
@@ -229,7 +229,7 @@ TEST_CASE("what action_run journals for an action of fixed arguments is a call i
|
||||
CommandCatalog design;
|
||||
NativeCommands::register_all_commands(design, {true});
|
||||
design.seal();
|
||||
CHECK(check_actions(design) > 129);
|
||||
CHECK(check_actions(design) > 130);
|
||||
CHECK(recorded_for(design, "sk_array_polar", json::object()) == json{{"type", "circular"}});
|
||||
#endif
|
||||
}
|
||||
@@ -1407,13 +1407,13 @@ TEST_CASE("tool_list gives the menu items then the Design commands by heading, i
|
||||
if (!c.listed)
|
||||
expected.push_back(c.key);
|
||||
CHECK(names == expected);
|
||||
REQUIRE(names.size() == 91);
|
||||
CHECK(std::set<std::string>(names.begin(), names.begin() + 3) ==
|
||||
std::set<std::string>{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"});
|
||||
REQUIRE(names.size() == 92);
|
||||
CHECK(std::set<std::string>(names.begin(), names.begin() + 4) ==
|
||||
std::set<std::string>{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode", "view_toggle_activity_panel"});
|
||||
// Each Design command under its heading, heading by heading in the order tool_list's description indexes them.
|
||||
const std::string told = catalog.find("tool_list")->description;
|
||||
std::size_t indexed = 0;
|
||||
for (std::size_t i = 3; i < names.size(); ++i) {
|
||||
for (std::size_t i = 4; i < names.size(); ++i) {
|
||||
const json& item = all.at("items")[i];
|
||||
INFO(item.dump());
|
||||
CHECK(item.at("group") == Slic3r::GUI::kDesignGroup);
|
||||
|
||||
@@ -2116,6 +2116,7 @@ const std::map<std::string, const char*> kExceptions = {
|
||||
{"app_open_web_page", kMenuItemOpens},
|
||||
{"app_show_config_folder", kMenuItemOpens},
|
||||
{"script_toggle_panel", "it runs its menu item's function, which shows or hides the Run Script panel for a person"},
|
||||
{"view_toggle_activity_panel", "it runs its menu item's function, which shows or hides the Agent Activity pane for a person"},
|
||||
{"settings_set_mode", kMenuItemAppSetting},
|
||||
{"settings_toggle_developer_mode", kMenuItemAppSetting},
|
||||
{"undo", kHistory},
|
||||
|
||||
+1
-1
@@ -544,7 +544,7 @@ on a fresh data folder and printers the sweep does not seed: `test_install_print
|
||||
and `test_sidebar_floating.py` (`view_set`'s
|
||||
`sidebar_width` refused while the sidebar floats).
|
||||
|
||||
`test_speed_dial.py` checks that `action_list` lists each of the 129 Speed Dial actions of
|
||||
`test_speed_dial.py` checks that `action_list` lists each of the 130 Speed Dial actions of
|
||||
`tests/data/speed_dial_actions.json` with the command `tests/data/speed_dial_action_calls.json` gives it, and runs
|
||||
seven of them through `action_run`, one for each way an action runs (a calibration dialog, a handy model, a window,
|
||||
the rear view, Go to tab with its value, a screenshot and a refused Sync Presets), each from a state set up afresh,
|
||||
|
||||
@@ -6,7 +6,7 @@ in [TESTS.md](../TESTS.md).
|
||||
## `test_speed_dial`
|
||||
`test_speed_dial.py` · Python, 36 checks · in `sweep.json` as `{"path": "test_speed_dial.py"}`
|
||||
|
||||
**Tests:** The Speed Dial's actions as `action_list` and `action_run` give them: that `action_list` lists every one of the 129 actions of `tests/data/speed_dial_actions.json` with the command `tests/data/speed_dial_action_calls.json` gives it, that a section no action is in is refused and settings are listed only when asked for, and that a few actions, run through `action_run` on the Generic Klipper Printer 0.4, each from a state rebuilt by calls, do what a person's pick does: their dialog answered as the row says, their effect read back, the reply naming the action, and the journal keeping an `action_run` step for it with the arguments its command journals. Each action it runs stands for one way an action runs, and is one whose command no other test runs where there is one:
|
||||
**Tests:** The Speed Dial's actions as `action_list` and `action_run` give them: that `action_list` lists every one of the 130 actions of `tests/data/speed_dial_actions.json` with the command `tests/data/speed_dial_action_calls.json` gives it, that a section no action is in is refused and settings are listed only when asked for, and that a few actions, run through `action_run` on the Generic Klipper Printer 0.4, each from a state rebuilt by calls, do what a person's pick does: their dialog answered as the row says, their effect read back, the reply naming the action, and the journal keeping an `action_run` step for it with the arguments its command journals. Each action it runs stands for one way an action runs, and is one whose command no other test runs where there is one:
|
||||
- `calib_retraction`: a person's form that opens a dialog, answered OK, which then makes the project (the Retraction calibration dialog, which no other test opens).
|
||||
- `add_handy_orcasliced_combo`: a person's form that runs in place and loads several files.
|
||||
- `help_keyboard_shortcuts`: an action that opens one of the app's windows.
|
||||
@@ -16,14 +16,14 @@ in [TESTS.md](../TESTS.md).
|
||||
- `sync_presets`: a refused action, which journals nothing.
|
||||
- `go_to_layer`: an action whose command's schema refuses the value it is given, whose refusal names `tool_describe` for the command.
|
||||
|
||||
An action is its command run with fixed arguments as a person's pick, and `action_run` runs every action the same way, so the test runs a few, not all. What each of the 129 adds to its command is checked without running it: `tests/slic3rutils/test_command_catalog.cpp` ([CommandCatalog][SpeedDial]) checks the command each folds into, its fixed arguments, the value it collects and that it is a person's form of its command, against the same fixture. The commands themselves are checked through their tools in their areas' tests. The Speed Dial's own window, opened with Space and picked from by a click, is `test_speed_dial_open`'s and `test_menu_items_refusals`'.
|
||||
An action is its command run with fixed arguments as a person's pick, and `action_run` runs every action the same way, so the test runs a few, not all. What each of the 130 adds to its command is checked without running it: `tests/slic3rutils/test_command_catalog.cpp` ([CommandCatalog][SpeedDial]) checks the command each folds into, its fixed arguments, the value it collects and that it is a person's form of its command, against the same fixture. The commands themselves are checked through their tools in their areas' tests. The Speed Dial's own window, opened with Space and picked from by a click, is `test_speed_dial_open`'s and `test_menu_items_refusals`'.
|
||||
|
||||
**Starts from:** `start(client)`, which "starts from the Generic Klipper Printer" compares with `{printer: "MyKlipper 0.4 nozzle", process: "0.20mm Standard @MyKlipper", filaments: ["Generic PLA @System"]}`. The setup check `Start Recording's folder is the output folder` points the folder Take Screenshot saves in at the output folder, through the Start Recording dialog. Before each row, `empty()` makes a new project with its changes discarded, shows Prepare's 3D view, deletes filament slots down to one and sets the expert mode, and the row's state builds on that: `two_cubes` adds two 20 mm cubes side by side and selects the first. The list checks read no state: the actions and their commands are the app's own. No action it runs takes the focus from another program, so it runs among the other tests on a job's data folder.
|
||||
|
||||
**Leaves:** Start Recording's folder, the output folder, which the runner deletes when the test passes, so that a later capture with no path goes to the default capture folder, as on a new data folder (`folder_or_default()`, `RecordingDialog.cpp`); and an empty project with one filament slot, in the expert mode, which the next test's `start()` sets back to Simple. Its picks are `action_run` calls, which leave the Speed Dial's usage counts as they were. It saves no preset and installs nothing.
|
||||
|
||||
**Decides by:** Exits 1 when any check fails.
|
||||
- Setup: `starts from the Generic Klipper Printer`; `every action has a call in the fixture`; `every action is listed with its command` (`action_list`, read page by page, lists an item for each of the 129 ids, and its `command` equals the fixture's); `an unknown section is refused` (`action_list {section: "No such section"}`, code `invalid_argument`) and `the refusal lists the sections there are` (its `sections` holds "Slice & Export"); `include_settings lists the settings too` (`action_list {include_settings: true, limit: 200}` has a larger `total` than `action_list {limit: 1}`, and its page holds an id starting `orca_setting`: a setting's action has no section of its own in the order, so the settings come first); `Start Recording's folder is the output folder`.
|
||||
- Setup: `starts from the Generic Klipper Printer`; `every action has a call in the fixture`; `every action is listed with its command` (`action_list`, read page by page, lists an item for each of the 130 ids, and its `command` equals the fixture's); `an unknown section is refused` (`action_list {section: "No such section"}`, code `invalid_argument`) and `the refusal lists the sections there are` (its `sections` holds "Slice & Export"); `include_settings lists the settings too` (`action_list {include_settings: true, limit: 200}` has a larger `total` than `action_list {limit: 1}`, and its page holds an id starting `orca_setting`: a setting's action has no section of its own in the order, so the settings come first); `Start Recording's folder is the output folder`.
|
||||
- Common to every row that runs but `sync_presets` and `go_to_layer`: `... its reply names the action it ran` (`ran` == `orca_command:<key>:orca`), and `... the journal keeps its action_run with the arguments its command journals`, an `action_run` step of that id whose inner `args` are `{"tab": "preview"}` for `go_to_tab`, the value given for its input, and `{}`, no `args`, for the others: the calibration action opens its test's dialog (the person's form), and `calibration_generate_test` rewrites its journal entry (`ActionContext::set_journal_args`) only when it runs the test itself, with its parameters or `silent`.
|
||||
- `calib_retraction`, from `empty`: the dialog titled "Retraction" answered OK; the project's `name` is "Retraction" and it has at least 1 object.
|
||||
- `add_handy_orcasliced_combo`, from `empty`: the objects' names are exactly "Orca Head", "OrcaCube_v2.drc", "OrcaPlug_v2.drc", "Orca Belly" and "Orca Pedestal", in that order, and no dialog is open.
|
||||
|
||||
@@ -36,7 +36,7 @@ DATA = os.path.join(HERE, "..", "..", "tests", "data")
|
||||
PREFIX, SUFFIX = "orca_command:", ":orca"
|
||||
BED_CENTRE = 125.0 # the middle of the Generic Klipper Printer's 250 mm bed
|
||||
START = {"printer": checks.KLIPPER, "process": checks.KLIPPER_STD, "filaments": [checks.GENERIC_PLA]}
|
||||
ACTIONS = 129 # the actions of speed_dial_actions.json
|
||||
ACTIONS = 130 # the actions of speed_dial_actions.json
|
||||
RESTORE = {"match": "restore", "button": "no"} # the prompt to restore unsaved items after a start
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user