mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-12-06 03:38:01 -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
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user