Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(desktop): retain managed UI exception details (#267)

Ruben Lütke95a73776168b
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 781a078c93..b7e6639fed 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -4984,6 +4984,9 @@ class DesktopApp:
def _hook_main_window_lifecycle(self) -> None:
"""Attach the closing/closed contract to the current main window."""
+ from jarvis.ui.winforms_errors import register_winforms_error_logging
+
+ register_winforms_error_logging(self._window)
self._window.events.closing += self._on_window_closing
self._window.events.closed += self._on_main_window_closed
# Real paths for dropped files/folders (see jarvis/ui/native_drop.py).
diff --git a/jarvis/ui/winforms_errors.py b/jarvis/ui/winforms_errors.py
new file mode 100644
index 0000000000..da319fc769
--- /dev/null
+++ b/jarvis/ui/winforms_errors.py
@@ -0,0 +1,92 @@
+"""Keep the details of a Windows Forms error after its dialog is dismissed.
+
+WinForms catches UI callback failures inside its managed message loop. Neither
+``sys.excepthook`` nor ``threading.excepthook`` sees them. Subscribe on the GUI
+thread (pywebview's synchronous ``before_show`` event), not the Python main
+thread. Keep the normal Continue/Quit dialog; logging is not crash recovery.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+from typing import Any
+
+log = logging.getLogger(__name__)
+_handlers: dict[int, tuple[Any, Any]] = {}
+
+
+def _report_exception(exception: Any) -> None:
+ from jarvis.core.redact import safe_preview
+
+ # ToString includes managed inner exceptions and stack traces. Python's
+ # traceback formatter cannot reconstruct those from a pythonnet proxy.
+ detail = safe_preview(str(exception.ToString()), max_chars=32_768)
+ log.critical("Unhandled Windows Forms UI exception:\n%s", detail)
+
+
+def _present_exception(forms: Any, exception: Any) -> None:
+ dialog = forms.ThreadExceptionDialog(exception)
+ try:
+ result = dialog.ShowDialog()
+ finally:
+ dialog.Dispose()
+ if result == forms.DialogResult.Abort:
+ # Run normal window-closing hooks, including Jarvis's bounded shutdown.
+ forms.Application.Exit()
+
+
+def _subscribe(forms: Any, thread_id: int) -> None:
+ """Install once per managed UI thread; release delegates on ThreadExit."""
+ if thread_id in _handlers:
+ return
+
+ def on_exception(_sender: Any, args: Any) -> None:
+ try:
+ _report_exception(args.Exception)
+ except Exception: # noqa: BLE001 — reporting must not hide the original dialog
+ log.exception("Could not record the Windows Forms exception")
+ _present_exception(forms, args.Exception)
+
+ def on_exit(_sender: Any, _args: Any) -> None:
+ # ThreadExit is process-wide; another GUI thread must keep its handler.
+ from System.Threading import Thread # type: ignore[import-not-found]
+
+ if int(Thread.CurrentThread.ManagedThreadId) != thread_id:
+ return
+ forms.Application.ThreadException -= on_exception
+ forms.Application.ThreadExit -= on_exit
+ _handlers.pop(thread_id, None)
+
+ forms.Application.ThreadException += on_exception
+ try:
+ forms.Application.ThreadExit += on_exit
+ except Exception:
+ forms.Application.ThreadException -= on_exception
+ raise
+ # Hold the Python callables for the full managed delegate lifetime.
+ _handlers[thread_id] = (on_exception, on_exit)
+ log.info("Windows Forms UI error logging installed")
+
+
+def _install_on_gui_thread() -> None:
+ try:
+ # The real window already loaded WinForms; importing here adds no CLR
+ # dependency to Linux, macOS, the API server, or Python module import.
+ import System.Windows.Forms as forms # type: ignore[import-not-found]
+ from System.Threading import Thread # type: ignore[import-not-found]
+
+ _subscribe(forms, int(Thread.CurrentThread.ManagedThreadId))
+ except Exception: # noqa: BLE001 — retain the framework's default error handling
+ log.exception("Windows Forms error logging could not be installed")
+
+
+def register_winforms_error_logging(window: Any) -> None:
+ """Arm logging before the first shown window, without loading .NET early."""
+ if sys.platform != "win32":
+ return
+ before_show = getattr(window.events, "before_show", None)
+ if before_show is None:
+ log.warning("Windows Forms error logging needs a synchronous before_show event")
+ return
+ before_show += _install_on_gui_thread
diff --git a/tests/unit/ui/test_winforms_errors.py b/tests/unit/ui/test_winforms_errors.py
new file mode 100644
index 0000000000..a6467b871a
--- /dev/null
+++ b/tests/unit/ui/test_winforms_errors.py
@@ -0,0 +1,145 @@
+"""Managed UI failures retain their details and their Continue/Quit behavior."""
+
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.ui import winforms_errors as errors
+
+
+class Event:
+ def __init__(self):
+ self.handlers = []
+
+ def __iadd__(self, handler):
+ self.handlers.append(handler)
+ return self
+
+ def __isub__(self, handler):
+ self.handlers.remove(handler)
+ return self
+
+ def fire(self, args):
+ for handler in self.handlers[:]:
+ handler(None, args)
+
+
+def forms(monkeypatch):
+ monkeypatch.setattr(errors, "_handlers", {})
+ current = SimpleNamespace(ManagedThreadId=42)
+ monkeypatch.setitem(sys.modules, "System.Threading", SimpleNamespace(
+ Thread=SimpleNamespace(CurrentThread=current),
+ ))
+ calls = []
+
+ class Dialog:
+ def __init__(self, exception):
+ calls.append(("dialog", exception))
+
+ def ShowDialog(self):
+ return api.result
+
+ def Dispose(self):
+ calls.append(("dispose", None))
+
+ api = SimpleNamespace(
+ Application=SimpleNamespace(
+ ThreadException=Event(), ThreadExit=Event(),
+ Exit=lambda: calls.append(("exit", None)),
+ ),
+ ThreadExceptionDialog=Dialog,
+ DialogResult=SimpleNamespace(Abort="abort"),
+ result="ignore", calls=calls, current=current,
+ )
+ return api
+
+
+def test_managed_details_logged_before_continue_dialog(forms, monkeypatch, caplog):
+ exception = SimpleNamespace(ToString=lambda: "OuterException\nInnerException\n at CloseWindow")
+ original = errors._present_exception
+
+ def present(api, exc):
+ assert "InnerException\n at CloseWindow" in caplog.text
+ original(api, exc)
+
+ monkeypatch.setattr(errors, "_present_exception", present)
+ errors._subscribe(forms, 42)
+ forms.Application.ThreadException.fire(SimpleNamespace(Exception=exception))
+ assert forms.calls == [("dialog", exception), ("dispose", None)]
+
+
+def test_quit_runs_application_exit_after_disposing_dialog(forms):
+ forms.result = "abort"
+ exception = SimpleNamespace(ToString=lambda: "Close failed")
+ errors._subscribe(forms, 42)
+ forms.Application.ThreadException.fire(SimpleNamespace(Exception=exception))
+ assert forms.calls == [("dialog", exception), ("dispose", None), ("exit", None)]
+
+
+def test_managed_error_details_redact_credentials(caplog):
+ credential_example = "example-credential-value"
+ exception = SimpleNamespace(
+ ToString=lambda: f"InvalidOperationException: password={credential_example}"
+ )
+ errors._report_exception(exception)
+ assert credential_example not in caplog.text
+ assert "<redacted:labelled_secret>" in caplog.text
+
+
+def test_partial_subscription_is_rolled_back(forms):
+ class UnavailableEvent:
+ def __iadd__(self, _handler):
+ raise RuntimeError("event unavailable")
+
+ forms.Application.ThreadExit = UnavailableEvent()
+ with pytest.raises(RuntimeError, match="event unavailable"):
+ errors._subscribe(forms, 42)
+ assert not forms.Application.ThreadException.handlers
+ assert not errors._handlers
+
+
+def test_logging_failure_still_presents_original_exception(forms, monkeypatch):
+ def broken(_exc):
+ raise OSError("log unavailable")
+
+ monkeypatch.setattr(errors, "_report_exception", broken)
+ exception = object()
+ errors._subscribe(forms, 42)
+ forms.Application.ThreadException.fire(SimpleNamespace(Exception=exception))
+ assert forms.calls[0] == ("dialog", exception)
+
+
+def test_duplicate_windows_do_not_duplicate_handler_and_thread_exit_releases_it(forms):
+ errors._subscribe(forms, 42)
+ errors._subscribe(forms, 42)
+ assert len(forms.Application.ThreadException.handlers) == 1
+ forms.current.ManagedThreadId = 99
+ forms.Application.ThreadExit.fire(None)
+ assert 42 in errors._handlers
+ forms.current.ManagedThreadId = 42
+ forms.Application.ThreadExit.fire(None)
+ assert not errors._handlers
+ assert not forms.Application.ThreadException.handlers
+ assert not forms.Application.ThreadExit.handlers
+
+
[email protected]("platform", ["linux", "darwin"])
+def test_non_windows_does_not_touch_native_dependencies(monkeypatch, platform):
+ monkeypatch.setattr(errors.sys, "platform", platform)
+ errors.register_winforms_error_logging(object())
+
+
+def test_install_waits_for_synchronous_gui_event(monkeypatch):
+ monkeypatch.setattr(errors.sys, "platform", "win32")
+ calls = []
+ monkeypatch.setattr(errors, "_install_on_gui_thread", lambda: calls.append("installed"))
+ event = Event()
+ window = SimpleNamespace(events=SimpleNamespace(before_show=event))
+ errors.register_winforms_error_logging(window)
+ assert calls == []
+ event.handlers[0]()
+ assert calls == ["installed"]