Keep Python Printer Agent Exceptions Out of the Host (#15819)

# Description
<!--
> Please provide a summary of the changes made in this PR. Include
details such as:
  > * What issue does this PR address or fix?
  > * What new features or enhancements does this PR introduce?
> * Are there any breaking changes or dependencies that need to be
considered?
-->

A Python printer agent plugin could take the host down, and one of its
operations could never report its result. This PR fixes both in
`PrinterAgentPluginCapabilityTrampoline.hpp`.

## Changes

### A faulty printer agent no longer throws into the GUI

`IPrinterAgent` reports failure through return values, and none of its
callers catch. A Python `raise`, a missing override or a wrongly typed
return from a printer agent plugin therefore escaped the trampoline as a
C++ exception.

Every trampoline operation now catches, logs `Printer agent plugin
'<key>': <operation> failed: <error>`, and answers with what
`NetworkAgent` returns when no printer agent is set. `BBLPrinterAgent`
returns the same values when the Bambu plug-in is unavailable:

- `-1` for every `int` status code
- `false` for `start_discovery` and `fetch_filament_info`
- `""` for `get_user_selected_machine`
- an empty `AgentInfo` for `get_agent_info` (registration already
rejects an empty agent ID)
- `FilamentSyncMode::none` for `get_filament_sync_mode`

`ORCA_PY_AGENT_OVERRIDE(ret, name, ...)` derives the fallback from the
return type through `printer_agent_failure<ret>()`, so the call sites
carry no fallback values of their own.

An exception is the safety net for plugin bugs, not an error channel. A
plugin reports an expected failure by returning a code, as the Bambu
plug-in does. A raise is logged as a failure and collapses to the
generic `-1`, so the GUI shows the generic message instead of the
specific one (`-18` cancelled, `-4020` FTP upload failed, …).

### `bind_detect` results now reach the host

`detect` is an out-parameter (`detectResult&`). pybind11 casts a
reference argument to an override with a copy, so a plugin that filled
in `detect` wrote to a throwaway object and the host always saw an empty
`detectResult`. It is now passed so that Python edits the caller's
struct. Plugins see the same `DetectResult` argument as before.

## TODO

- Expose the `BAMBU_NETWORK_*` return codes to Python (the
`orca.printer_agent` binding and the generated stub from
`scripts/generate_orca_python_stubs.py`). Plugins can already return
them, but only as hard-coded numbers.

# Screenshots/Recordings/Graphs

<!--
> Please attach relevant screenshots to showcase the UI changes.
> Please attach images that can help explain the changes.
-->

## Tests

<!--
> Please describe the tests that you have conducted to verify the
changes made in this PR.
-->

- New `tests/slic3rutils/test_plugin_printer_agent.cpp`: an agent whose
operations raise, one that omits them, and one that returns the wrong
type all answer like a missing agent, and the interpreter stays usable.
A working agent's answers reach the host unchanged, including
`request_bind_ticket`'s out-param and the fields a plugin writes into
`bind_detect`'s `detect`.
- The `bind_detect` check failed before the fix (`"" == "192.168.0.2"`)
and passes after.
- `slic3rutils` passes under `ctest` (144/144); full Release build clean
on Linux.
- End to end on Linux with a test plugin whose chosen operations raise
(`start_discovery`, `get_filament_sync_mode`, `disconnect_printer`):
selecting the plugin's agent in the printer preset and switching back
logged each raise as a `Printer agent plugin '…': <operation> failed`
line, and the app kept running and closed cleanly (exit 0). Without the
guard, the first raise (`start_discovery`, on selecting the agent) ended
the app with `Uncaught exception` and SIGABRT (exit 134); that run used
a build whose printer-agent files are identical to `main`.

<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)
This commit is contained in:
Ian Chua
2026-09-22 16:57:55 +08:00
committed by GitHub
3 changed files with 244 additions and 98 deletions
+1
View File
@@ -13,6 +13,7 @@ add_executable(${_TEST_NAME}_tests
test_plugin_capabilities_in_use.cpp
test_plugin_install.cpp
test_plugin_lifecycle.cpp
test_plugin_printer_agent.cpp
test_slicing_pipeline_bindings.cpp
test_slicing_pipeline_config.cpp
test_plugin_sort.cpp
@@ -0,0 +1,161 @@
#include <catch2/catch_all.hpp>
#include <slic3r/plugin/PluginManager.hpp>
#include <slic3r/plugin/PythonInterpreter.hpp>
#include <slic3r/plugin/PythonPluginBridge.hpp>
#include <slic3r/plugin/PythonPluginInterface.hpp>
#include <slic3r/Utils/IPrinterAgent.hpp>
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
#include <memory>
#include <string>
namespace py = pybind11;
using namespace Slic3r;
namespace {
// Same idiom as ScopedPluginManager in test_plugin_lifecycle.cpp: the trampolines refuse to call
// into Python unless PythonInterpreter::instance() reports initialized.
struct ScopedPluginManager
{
bool initialized = PluginManager::instance().initialize();
~ScopedPluginManager()
{
PluginManager::instance().shutdown();
PythonInterpreter::instance().shutdown();
}
};
// The host reaches a printer agent plugin through IPrinterAgent, so the tests do too. The Python
// instance carries the overrides, so it has to outlive every call, as PluginInstanceHandle ensures
// in production.
struct Agent
{
py::object instance;
std::shared_ptr<IPrinterAgent> agent;
IPrinterAgent* operator->() const { return agent.get(); }
IPrinterAgent& operator*() const { return *agent; }
};
Agent make_agent(const std::string& body)
{
(void) PythonPluginBridge::instance(); // force the embedded module registration into the binary
py::dict globals;
globals["orca"] = py::module_::import("orca");
py::exec("class Agent(orca.printer_agent.PrinterAgentBase):\n"
" def get_name(self): return 'agent'\n" + body, globals);
py::object instance = globals["Agent"]();
auto capability = instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
capability->set_audit_plugin_key("agent_plugin");
return {instance, std::dynamic_pointer_cast<IPrinterAgent>(capability)};
}
// One operation per return type and dispatch shape; the rest share their macro.
const std::string OPERATIONS[] = {"get_agent_info", "disconnect_printer", "start_discovery", "get_user_selected_machine",
"get_filament_sync_mode", "install_device_cert", "start_local_print", "request_bind_ticket"};
// What NetworkAgent answers when no printer agent is set.
void check_answers_like_no_agent(IPrinterAgent& agent)
{
std::string ticket = "untouched";
CHECK(agent.get_agent_info().id.empty());
CHECK(agent.disconnect_printer() == -1);
CHECK_FALSE(agent.start_discovery(true, false));
CHECK(agent.get_user_selected_machine().empty());
CHECK(agent.get_filament_sync_mode() == FilamentSyncMode::none);
CHECK_NOTHROW(agent.install_device_cert("dev", true));
CHECK(agent.start_local_print(PrintParams{}, nullptr, nullptr) == -1);
CHECK(agent.request_bind_ticket(&ticket) == -1);
CHECK(ticket == "untouched");
}
std::string define_all(const std::string& signature_tail, const std::string& statement)
{
std::string body;
for (const std::string& operation : OPERATIONS)
body += " def " + operation + "(self" + signature_tail + "): " + statement + "\n";
return body;
}
} // namespace
TEST_CASE("A printer agent operation that raises answers like a missing agent", "[PluginPrinterAgent][Python]")
{
ScopedPluginManager plugin_system; // declared first: destroyed last
if (!plugin_system.initialized)
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
auto agent = make_agent(define_all(", *args", "raise RuntimeError('boom')"));
REQUIRE(agent.agent);
check_answers_like_no_agent(*agent);
// The interpreter stays usable.
CHECK(py::eval("1 + 1").cast<int>() == 2);
}
TEST_CASE("A printer agent that omits its operations answers like a missing agent", "[PluginPrinterAgent][Python]")
{
ScopedPluginManager plugin_system;
if (!plugin_system.initialized)
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
py::gil_scoped_acquire gil;
auto agent = make_agent("");
REQUIRE(agent.agent);
check_answers_like_no_agent(*agent);
}
TEST_CASE("A printer agent operation returning the wrong type answers like a missing agent", "[PluginPrinterAgent][Python]")
{
ScopedPluginManager plugin_system;
if (!plugin_system.initialized)
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
py::gil_scoped_acquire gil;
auto agent = make_agent(define_all(", *args", "return object()"));
REQUIRE(agent.agent);
check_answers_like_no_agent(*agent);
}
TEST_CASE("A working printer agent's answers reach the host unchanged", "[PluginPrinterAgent][Python]")
{
ScopedPluginManager plugin_system;
if (!plugin_system.initialized)
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
py::gil_scoped_acquire gil;
auto agent = make_agent(" def get_agent_info(self): return orca.printer_agent.AgentInfo('id', 'name', '1', 'description')\n"
" def disconnect_printer(self): return 7\n"
" def start_discovery(self, start, sending): return start and not sending\n"
" def get_user_selected_machine(self): return 'machine'\n"
" def get_filament_sync_mode(self): return orca.printer_agent.FilamentSyncMode.Pull\n"
" def request_bind_ticket(self): return (3, 'ticket')\n"
" def bind_detect(self, dev_ip, sec_link, detect):\n"
" detect.dev_id = dev_ip\n"
" return 0\n");
REQUIRE(agent.agent);
std::string ticket;
detectResult detect;
CHECK(agent->get_agent_info().id == "id");
CHECK(agent->disconnect_printer() == 7);
CHECK(agent->start_discovery(true, false));
CHECK(agent->get_user_selected_machine() == "machine");
CHECK(agent->get_filament_sync_mode() == FilamentSyncMode::pull);
CHECK(agent->request_bind_ticket(&ticket) == 3);
CHECK(ticket == "ticket");
CHECK(agent->bind_detect("192.168.0.2", "secure", detect) == 0);
CHECK(detect.dev_id == "192.168.0.2");
}