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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(desktop): account for every silent failure in the desktop app
Ruben Lütkeb44fdf8a8fec
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 180273bfb9..3a3b8d325c 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -32,12 +32,16 @@ if sys.platform == "win32":sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]sys.stderr.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]except (AttributeError, OSError):+ # Nothing to log to yet — this IS the call that makes the streams+ # usable, and no logger exists this early in the process.passtry:from jarvis.ui.icon_utils import ensure_windows_app_identityensure_windows_app_identity()- except Exception:+ except Exception: # noqa: S110+ # Taskbar-icon grouping is cosmetic and Windows-only; failing here must+ # not stop the app from starting on any other OS.passfrom filelock import FileLock, Timeout@@ -102,6 +106,8 @@ def _supported_call_kwargs(try:signature = inspect.signature(function)except (TypeError, ValueError):+ # Builtins and C callables have no introspectable signature; passing+ # every kwarg through is the documented fallback of this helper.return dict(kwargs)parameters = tuple(signature.parameters.values())if any(@@ -189,6 +195,8 @@ def _install_desktop_log_sink(log_path: Path) -> None:try:level: str | int = logger.level(record.levelname).nameexcept ValueError:+ # A custom stdlib level loguru does not know by name; the+ # numeric level carries the same information.level = record.levelnoframe, depth = _logging.currentframe(), 2while frame and frame.f_code.co_filename == _logging.__file__:@@ -234,6 +242,8 @@ def _pid_alive(pid: int) -> bool:try:return psutil.pid_exists(int(pid))except Exception: # noqa: BLE001+ # Fail SAFE, not quiet: claiming "alive" keeps the caller from evicting+ # a lock holder it could not verify, which is the conservative answer.return True@@ -254,7 +264,9 @@ def _write_meta(port: int, pid: int) -> None:from loguru import loggerlogger.warning("Could not write Jarvis meta sidecar: {}", exc)- except Exception:+ except Exception: # noqa: S110+ # The logger itself failed (very early boot); the outer handler+ # above already carries the real report.pass@@ -296,12 +308,16 @@ def _read_meta() -> dict[str, Any] | None:try:raw = META_FILE_PATH.read_text(encoding="utf-8")except FileNotFoundError:+ # No sidecar means no running instance — the normal first-start case.return Noneexcept OSError:+ # Unreadable is treated as absent: the caller's next step (probe the+ # known ports) covers both, and a log here would fire on every start.return Nonetry:data = json.loads(raw)except json.JSONDecodeError:+ # A sidecar caught mid-write; the port probe below handles it.return Noneif not isinstance(data, dict):return None@@ -321,11 +337,15 @@ def _focus_existing_instance() -> bool:try:import httpxexcept Exception: # noqa: BLE001+ # httpx is absent on a minimal install; the caller falls back to the+ # window-title path, which needs no HTTP at all.return Falseurl = f"http://127.0.0.1:{int(meta['port'])}/api/window/focus"try:r = httpx.post(url, timeout=1.0)except Exception: # noqa: BLE001+ # Nothing listening = no running instance, which is the ANSWER this+ # function returns, not a failure worth reporting.return Falsereturn 200 <= r.status_code < 300@@ -340,7 +360,9 @@ def focus_existing_instance_robust() -> bool:cfg_port = int(load_config().ui.admin_api_port)if cfg_port not in ports:ports.append(cfg_port)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Config unreadable: the hardcoded default port below still gets tried,+ # which is the whole point of this being the "robust" variant.passif 47821 not in ports:ports.append(47821)@@ -358,13 +380,16 @@ def focus_existing_instance_robust() -> bool:f"http://127.0.0.1:{port}/api/window/focus",timeout=1.0,)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S112+ # This port is not the running instance; try the next candidate.continueif 200 <= r.status_code < 300:try:payload = r.json()focused = bool(payload.get("ok", True))except Exception: # noqa: BLE001+ # A 2xx without a JSON body still means the instance+ # accepted the focus request, so treat it as success.focused = Trueif focused:_bring_window_to_front_by_title(WINDOW_TITLE)@@ -509,6 +534,9 @@ def _bring_window_to_front_by_title(title: str) -> bool:user32.MoveWindow(hwnd, 80, 60, width, height, True)return _force_foreground_hwnd(hwnd, user32, ctypes.windll.kernel32)except Exception: # noqa: BLE001+ # Win32-only path; on any non-Windows host, or when the window has+ # already gone, False is the honest answer and the caller has its own+ # fallback. Returning False here is the report.return False@@ -696,6 +724,8 @@ def _terminate_pid(pid: int) -> bool:try:import psutil # type: ignore[import-not-found]except Exception: # noqa: BLE001+ # Without psutil we cannot prove the zombie died, and the docstring's+ # contract is to keep the lock blocked rather than claim an eviction.return Falsetry:proc = psutil.Process(int(pid))@@ -754,6 +784,8 @@ def acquire_single_instance_lock(lock.acquire(timeout=timeout)return lockexcept Timeout:+ # Expected whenever another instance holds the lock; the zombie check+ # below decides whether that holder is real, and reports from there.pass# Held — is the holder still alive?@@ -762,6 +794,8 @@ def acquire_single_instance_lock(raw = mp.read_text(encoding="utf-8")meta = json.loads(raw)except (FileNotFoundError, OSError, json.JSONDecodeError):+ # No usable sidecar: pid/port stay None below, which routes to the+ # conservative path (assume a healthy holder, do not evict).meta = Nonepid = int(meta["pid"]) if meta and "pid" in meta else None@@ -1293,6 +1327,8 @@ class DesktopApp:try:await asyncio.wait_for(brain_ready.wait(), timeout=timeout_s)except TimeoutError:+ # Expected while the brain is still warming; the caller+ # handles a None brain and the timeout is the signal.passreturn brain_holder["brain"]@@ -1403,10 +1439,14 @@ class DesktopApp:try:iterator = stream(text, **call_kwargs)except TypeError:+ # Capability probe, not an error: older brain plugins do not+ # accept these kwargs, so drop them one at a time and retry.call_kwargs.pop("allow_voice_confirm", None)try:iterator = stream(text, **call_kwargs)except TypeError:+ # Second and last kwarg to drop; a TypeError after this+ # is a real signature mismatch and propagates.call_kwargs.pop("on_progress", None)iterator = stream(text, **call_kwargs)async for chunk in iterator:@@ -2017,7 +2057,9 @@ class DesktopApp:self._stop_loop_watchdog()try:loop.close()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Closing an already-closed or still-busy loop on the way out;+ # the process exits either way.pass# Never waited on: a worker still inside a blocking native call# would hold the quit open, and this process is on its way out@@ -2253,8 +2295,12 @@ class DesktopApp:enabled = bool(enabled)try:self.cfg.ui.bar_persistent = enabled- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # The live flip below still happens, so the bar visibly changes and+ # this call still reports ok — but the value never reached the+ # config, so it is gone at the next start. That reads as "the+ # setting does not stick", which is unfindable without this line.+ logger.warning("bar_persistent not stored in config: {}", exc)bar = getattr(self, "_orb", None)bridge = getattr(self, "_bridge", None)if bar is None or bridge is None:@@ -2289,8 +2335,10 @@ class DesktopApp:scale = renderer.clamp_user_size(scale)try:self.cfg.ui.bar_size_scale = scale- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Same trap as set_bar_persistent: the bar resizes on screen but the+ # scale is lost at the next start, and the call still reports ok.+ logger.warning("bar_size_scale not stored in config: {}", exc)bar = getattr(self, "_orb", None)fn = getattr(bar, "set_size_scale", None)if not callable(fn):@@ -2316,8 +2364,10 @@ class DesktopApp:enabled = bool(enabled)try:self.cfg.ui.bar_follow_cursor_monitor = enabled- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Same trap as set_bar_persistent: follow-cursor applies live but is+ # lost at the next start, while the call still reports ok.+ logger.warning("bar_follow_cursor_monitor not stored in config: {}", exc)bar = getattr(self, "_orb", None)fn = getattr(bar, "set_follow_cursor", None)if not callable(fn):@@ -2735,7 +2785,7 @@ class DesktopApp:_name = getattr(_inst, "name", None)if _name and hasattr(_inst, "execute"):skill_tool_registry[_name] = _inst- except Exception:+ except Exception: # noqa: S112continue # Tool needs args — not relevant for skills.skill_runner = SkillRunner(@@ -3116,7 +3166,7 @@ class DesktopApp:from jarvis.core import runtime_refsruntime_refs.set_speech_pipeline(pipeline)- except Exception: # noqa: BLE001 — best-effort, never block voice boot+ except Exception: # noqa: BLE001, S110 - best-effort, never block voice bootpassself._pipeline_task = loop.create_task(pipeline.run(), name="speech-pipeline"@@ -3258,6 +3308,9 @@ class DesktopApp:self._wake_model_loaded.wait(), timeout=120.0)except TimeoutError:+ # The gate is an optimisation, not a precondition:+ # after two minutes the upgrade proceeds anyway+ # rather than abandoning the hot-swap entirely.passturbo = await asyncio.to_thread(@@ -3395,6 +3448,8 @@ class DesktopApp:"reason": "foreground_lock",}except Exception as exc: # noqa: BLE001+ # Not swallowed: the reason travels back to the caller in the+ # response body and surfaces in the focus API result.return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}# ---- WebView hooks -------------------------------------------------------@@ -3419,7 +3474,7 @@ class DesktopApp:)try:window.evaluate_js(js)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110# Not fatal: the local control key can still unlock AuthGate.pass@@ -3430,7 +3485,9 @@ class DesktopApp:)set_window_icon_by_title(WINDOW_TITLE, project_icon_path())- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Window-icon polish is cosmetic and Win32-only; the app works+ # identically with the default icon.pass# Repair shell registration only after the first webview paint. This is@@ -3486,7 +3543,9 @@ class DesktopApp:r = httpx.get(url, timeout=0.5)if r.status_code == 200:return True- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Expected on every poll until the backend binds its port;+ # logging here would emit a line every 250 ms during boot.passtime.sleep(0.25)return False@@ -3628,7 +3687,7 @@ class DesktopApp:pin_linux_wm_class()ensure_linux_desktop_entry()apply_macos_dock_icon()- except Exception: # noqa: BLE001 — icon/identity pins are never load-bearing+ except Exception: # noqa: BLE001, S110 - icon/identity pins are never load-bearingpass# Native file drag-out: dragging a saved-download toast drops the REAL@@ -3643,7 +3702,7 @@ class DesktopApp:from jarvis.ui.native_drag import install_native_draginstall_native_drag(allowed_base_dirs=[_Path.home() / "Downloads"])- except Exception: # noqa: BLE001 — the drag bridge is never load-bearing+ except Exception: # noqa: BLE001, S110 - the drag bridge is never load-bearingpass# webview.start blocks the main thread. func/args gets called after@@ -3664,6 +3723,8 @@ class DesktopApp:debug=debug,)except webview.WebViewException as exc:+ # Not swallowed: the exception is handed to the degrade path, which+ # reports it and opens the UI in the default browser instead.return self._degrade_to_browser_ui(exc)# webview.start returns once the window is destroyed. A real quit (the# X, tray "Quit", or a restart) has set ``_user_requested_quit``; in that@@ -3844,6 +3905,8 @@ class DesktopApp:try:cmd = cmd_queue.get(timeout=0.5)except queue.Empty:+ # The idle case of a polling loop, not a failure: no command+ # arrived within the tick, so check the shutdown flag again.continueaction = cmd.actionif action == "open_ui":@@ -3860,7 +3923,9 @@ class DesktopApp:try:if self._window is not None:self._window.destroy()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Teardown best-effort: the window may already be gone,+ # and the process is exiting on the next line anyway.passreturn@@ -3917,8 +3982,13 @@ class DesktopApp:self._reload_window_if_stale()# Bring the persistent bar back too (it was cleared on minimise).self._restore_overlay_for_visible_window()- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # The whole show-the-window path is in this try, so a failure here+ # is exactly the "clicked the tray icon and nothing happened"+ # report — with no other trace anywhere.+ from loguru import logger++ logger.opt(exception=exc).warning("Showing the desktop window failed")def _reload_window_if_stale(self) -> None:"""Re-fetch the SPA root if the embedded WebView is stuck on an@@ -3934,16 +4004,25 @@ class DesktopApp:"""if self._window is None:return+ from loguru import logger+try:title = self._window.evaluate_js("document.title")- except Exception: # noqa: BLE001+ except Exception as exc: # noqa: BLE001+ # A probe that ALWAYS fails looks identical to "the SPA never+ # booted", so every show() reloads the window — the reload loop+ # that reads as a flickering window at startup. Distinguishing a+ # broken probe from a genuinely stale frame needs this line.+ logger.debug("Staleness probe failed, assuming a stale frame: {}", exc)title = Noneif title and isinstance(title, str) and "Jarvis" in title:returntry:self._window.load_url(self._url())- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Nothing left to try: the window keeps showing the stale body, so+ # the user sees an error page that never refreshes.+ logger.warning("Could not reload the stale window: {}", exc)# ---- Window close (X) = minimise to tray + clear overlay ---------------@@ -4081,7 +4160,9 @@ class DesktopApp:stop()else:self._orb.hide()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Teardown best-effort: the process is exiting and the OS+ # reclaims the window regardless.pass# Restore other apps' audio (in case a session was muting music at quit).@@ -4089,8 +4170,12 @@ class DesktopApp:if ducker is not None:try:ducker.restore_sync()- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Worth a line: a failure here leaves the user's music ducked+ # AFTER Jarvis is gone, and nothing else will restore it.+ from loguru import logger as _logger++ _logger.warning("Could not restore other apps' audio on quit: {}", exc)# Virtual-mouse overlay down too (own Tk thread). Its shutdown blocks# up to ~5s on the Tk thread join + does a ShowWindow(SW_HIDE) Win32@@ -4122,7 +4207,9 @@ class DesktopApp:try:from jarvis.overlay.system_cursor import set_jarvis_system_cursorset_jarvis_system_cursor(None)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # The shutdown() above already logged if the cursor is stuck;+ # this is the second, redundant restore attempt.passself._jarvis_cursor = None@@ -4134,8 +4221,13 @@ class DesktopApp:if self._pipeline_task is not None and not self._pipeline_task.done():try:loop.call_soon_threadsafe(self._pipeline_task.cancel)- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # If this cancel never lands, HotkeyTrigger stays in the loop+ # and server.stop() never gets a turn — the hung-shutdown+ # shape that once kept a dead process on the port.+ from loguru import logger as _logger++ _logger.warning("Pipeline-task cancel did not dispatch: {}", exc)# Wake-model background tasks + gate: cancel the turbo hot-swap task# and RELEASE the wake-model-loaded gate so any task still parked in# ``await self._wake_model_loaded.wait()`` (the heavy-backend gate)@@ -4147,14 +4239,23 @@ class DesktopApp:if _wut is not None and not _wut.done():try:loop.call_soon_threadsafe(_wut.cancel)- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # This is the exact path behind the 2026-06-27 forensic+ # above: a task left pending can stall loop.stop, the+ # self-restart hangs, and the old process keeps the port.+ from loguru import logger as _logger++ _logger.warning("Wake-upgrade task cancel did not dispatch: {}", exc)_wml = getattr(self, "_wake_model_loaded", None)if _wml is not None:try:loop.call_soon_threadsafe(_wml.set)- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Same failure shape: anything parked on this gate stays+ # parked through shutdown instead of unblocking.+ from loguru import logger as _logger++ _logger.warning("Wake-model gate release did not dispatch: {}", exc)# Cleanly shut down the workflow scheduler + store — prevents# a cron tick from still triggering a run mid-shutdown.wf_scheduler = getattr(self, "_workflow_scheduler", None)@@ -4167,19 +4268,25 @@ class DesktopApp:try:if sched is not None:await sched.stop()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # One scheduler refusing to stop must not skip the+ # other, nor the store closes below.passfor st in (wf_store, cd_store):try:if st is not None:await st.close()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Same: the process is exiting, so an unclosed+ # store handle is released by the OS anyway.passtry:asyncio.run_coroutine_threadsafe(_workflow_cleanup(), loop,).result(timeout=2.0)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Bounded by the 2 s timeout on purpose: a wedged cleanup+ # must not hold the whole quit open.pass# Cleanly close PTY sessions — otherwise zombies remainasync def _pty_cleanup() -> None:@@ -4194,7 +4301,9 @@ class DesktopApp:_logger.warning("PTY-Cleanup failed: {}", exc)try:asyncio.run_coroutine_threadsafe(_pty_cleanup(), loop).result(timeout=2.0)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # _pty_cleanup already logs its own failure; this only bounds+ # how long the quit waits for it.pass# Stop the serve-first bootstrap (it owns the listening socket).if self._bootstrap is not None:@@ -4202,20 +4311,25 @@ class DesktopApp:asyncio.run_coroutine_threadsafe(self._bootstrap.stop(), loop).result(timeout=3.0)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Timed out or already down; the loop stop below is the+ # backstop that frees the socket either way.passtry:fut = asyncio.run_coroutine_threadsafe(server.stop(), loop)try:fut.result(timeout=3.0)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110# Server shutdown may hang; the event loop still stops forcibly.pass- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # Could not even schedule the stop (loop already closing); the+ # forced loop.stop below covers it.passtry:loop.call_soon_threadsafe(loop.stop)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S110+ # The loop is already stopped or closed — the desired end state.passif self._backend_thread is not None:@@ -4226,14 +4340,23 @@ class DesktopApp:if self._tray is not None:try:self._tray.stop()- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # Worth a line: the visible symptom is a ghost tray icon that+ # outlives the process, which reads as "Jarvis did not quit".+ from loguru import logger as _logger++ _logger.warning("Tray icon did not stop cleanly: {}", exc)self._tray = Nonetry:META_FILE_PATH.unlink(missing_ok=True)- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # A sidecar left behind makes the NEXT start believe an instance is+ # already running, so it refuses to launch or tries to focus a dead+ # window. Silence here costs the user the next start.+ from loguru import logger as _logger++ _logger.warning("Could not remove the instance sidecar: {}", exc)return 0@@ -4263,8 +4386,11 @@ def main() -> int:finally:try:lock.release()- except Exception: # noqa: BLE001- pass+ except Exception as exc: # noqa: BLE001+ # A lock left held blocks the next start outright. The zombie+ # eviction path recovers it, but only after a confusing delay, so+ # the reason belongs in the log of the run that caused it.+ sys.stderr.write(f"Could not release the single-instance lock: {exc}\n")if __name__ == "__main__":diff --git a/scripts/ci/check_silent_exception_handlers.py b/scripts/ci/check_silent_exception_handlers.pyindex 4a11b77eab..963d7ca4b0 100644--- a/scripts/ci/check_silent_exception_handlers.py+++ b/scripts/ci/check_silent_exception_handlers.py@@ -74,6 +74,9 @@ _REPORTING = ("record","publish","trace",+ # Writing to stderr IS telling someone — it is how the earliest boot paths+ # report, before any logger exists.+ "stderr",)diff --git a/scripts/ci/silent-handlers-baseline.json b/scripts/ci/silent-handlers-baseline.jsonindex 47048e2fa1..739630d5e5 100644--- a/scripts/ci/silent-handlers-baseline.json+++ b/scripts/ci/silent-handlers-baseline.json@@ -1,6 +1,6 @@{"_comment": "Per-file count of exception handlers that neither log nor re-raise. Generated by scripts/ci/check_silent_exception_handlers.py --update. These numbers may go DOWN freely; an increase is a gate failure.",- "total": 1591,+ "total": 1535,"files": {"jarvis/__main__.py": 9,"jarvis/admin/executor.py": 9,@@ -119,7 +119,6 @@"jarvis/cu/conventions.py": 3,"jarvis/cu/engine.py": 11,"jarvis/cu/geometry.py": 1,- "jarvis/cu/indicator/__main__.py": 1,"jarvis/cu/indicator/capture_guard.py": 1,"jarvis/cu/indicator/controller.py": 4,"jarvis/cu/indicator/protocol.py": 2,@@ -206,7 +205,6 @@"jarvis/missions/workers/api_agent_tools.py": 10,"jarvis/missions/workers/claude_direct_worker.py": 2,"jarvis/missions/workers/codex_direct_worker.py": 5,- "jarvis/missions/workers/codex_worker.py": 1,"jarvis/missions/workers/gemini_worker.py": 1,"jarvis/missions/workers/provider_chain.py": 1,"jarvis/missions/workers/stream_consumer.py": 1,@@ -250,7 +248,7 @@"jarvis/plugins/tool/hotkey.py": 5,"jarvis/plugins/tool/manage_mcp_server.py": 2,"jarvis/plugins/tool/move_mouse.py": 4,- "jarvis/plugins/tool/multi_spawn.py": 2,+ "jarvis/plugins/tool/multi_spawn.py": 1,"jarvis/plugins/tool/open_app.py": 2,"jarvis/plugins/tool/read_visible_ui_state.py": 1,"jarvis/plugins/tool/remember.py": 1,@@ -323,10 +321,9 @@"jarvis/telephony/session.py": 1,"jarvis/telephony/twiml.py": 2,"jarvis/terminal/pty_manager.py": 2,- "jarvis/tools/latency_report.py": 2,+ "jarvis/tools/latency_report.py": 1,"jarvis/trigger/backends/noop.py": 1,"jarvis/trigger/hotkey.py": 1,- "jarvis/ui/desktop_app.py": 52,"jarvis/ui/icon_utils.py": 2,"jarvis/ui/jarvisbar/interaction.py": 3,"jarvis/ui/jarvisbar/overlay.py": 5,