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(control): wire the global Emergency Stop end-to-end into Computer Use

Ruben Lütkeb135d43602d0
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 414ea41759..3b2fc3f12b 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -421,6 +421,14 @@ async def _run_tray_app(debug: bool = False) -> int:
return
if cmd.action == "pause":
tray.set_state(JarvisState.PAUSED)
+ elif cmd.action == "kill":
+ # Standalone tray mode runs no backend/bus, so there is no
+ # mission to stop — say so instead of swallowing the click
+ # (deep-dive 2026-07-15, C-02).
+ print(
+ "Emergency stop: no backend is running in tray-only mode; "
+ "nothing to stop."
+ )
elif cmd.action == "resume":
tray.set_state(JarvisState.IDLE)
elif cmd.action == "reload_config":
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 3550256fa2..632056b0f7 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -561,7 +561,6 @@ def _load_local_action_tools(
from jarvis.plugins.tool.hotkey import HotkeyTool
from jarvis.plugins.tool.open_app import OpenAppTool
from jarvis.plugins.tool.reset_orb_position import ResetOrbPositionTool
- from jarvis.plugins.tool.respawn_mascot import RespawnMascotTool
from jarvis.plugins.tool.type_text import TypeTextTool
return {
@@ -578,11 +577,6 @@ def _load_local_action_tools(
# "wo bist du" / "reset orb"). Publishes OrbResetRequested
# on the bus; the orb-side bridge handles the Tk-thread dispatch.
"reset_orb_position": ResetOrbPositionTool(bus=bus),
- # Voice-driven mascot recovery ("Maskottchen wieder auftauchen" /
- # "Spawner" / "respawn mascot"). Calls OverlaySupervisor.force_respawn
- # so the user can get the mascot back after a cap-fire, crash, or
- # hidden-window state.
- "respawn_mascot": RespawnMascotTool(),
}
@@ -1164,12 +1158,24 @@ def _phase2_full_brain(
native_cu.model)
except Exception as _exc: # noqa: BLE001 — never block CU bootstrap
log.debug("native CU engine not built: %s", _exc)
+ # Emergency Stop (deep-dive 2026-07-15, C-02): the CU harness
+ # already registers its CancelScope token with ctx.kill_switch —
+ # but nothing ever provided one, so the advertised global stop
+ # (tray "Emergency stop", hotkey, voice kill phrase) never reached
+ # a running mission. Bind the process-wide switch to THIS bus
+ # (idempotent) so every KillRequested cancels active CU tokens.
+ from jarvis.control import get_kill_switch # noqa: PLC0415
+
+ cu_kill_switch = get_kill_switch()
+ if bus is not None:
+ cu_kill_switch.bind(bus)
set_computer_use_context(ComputerUseContext(
vision_engine=vision_engine_for_cu,
brain_manager=manager,
tool_executor=executor,
tools=cu_tools,
bus=bus,
+ kill_switch=cu_kill_switch,
step_budget=cu_cfg.step_budget,
per_step_timeout_s=cu_cfg.per_step_timeout_s,
think_timeout_cap_s=getattr(cu_cfg, "think_timeout_cap_s", 10.0),
diff --git a/jarvis/control/__init__.py b/jarvis/control/__init__.py
index 4d71a55ec6..dce2184d9d 100644
--- a/jarvis/control/__init__.py
+++ b/jarvis/control/__init__.py
@@ -7,7 +7,7 @@ Protocol definitions: `jarvis.core.protocols.CancelToken` / `CostMeter`.
"""
from __future__ import annotations
-from .cancel import CancelScope, CancelToken, KillSwitch
+from .cancel import CancelScope, CancelToken, KillSwitch, get_kill_switch
from .cost import BudgetConfig, CooldownState, CostMeter, ModelPrice
from .wiring import (
DEFAULT_KILL_HOTKEY,
@@ -27,6 +27,7 @@ __all__ = [
"CostMeter",
"KillSwitch",
"ModelPrice",
+ "get_kill_switch",
"run_kill_hotkey_trigger",
"voice_matches_kill_intent",
"wire_kill_switch_on_bus",
diff --git a/jarvis/control/cancel.py b/jarvis/control/cancel.py
index cc817982fb..be8a1a182d 100644
--- a/jarvis/control/cancel.py
+++ b/jarvis/control/cancel.py
@@ -210,6 +210,32 @@ class KillSwitch:
await to_bus.publish(event)
+# ----------------------------------------------------------------------
+# Process-wide singleton (deep-dive 2026-07-15, C-02)
+# ----------------------------------------------------------------------
+#
+# Every component of the Emergency Stop existed (this KillSwitch, the wiring
+# helpers, the tray menu item, the CancelScope in the CU harness) but nothing
+# at boot ever INSTANTIATED a KillSwitch — so ComputerUseContext.kill_switch
+# stayed None and the advertised global stop was a no-op. The singleton gives
+# the brain factory, the tray bridge, and REST routes one shared instance
+# without threading it through every constructor.
+
+_PROCESS_KILL_SWITCH: KillSwitch | None = None
+
+
+def get_kill_switch() -> KillSwitch:
+ """The process-wide :class:`KillSwitch`, created on first use.
+
+ Callers that own a bus should also call ``.bind(bus)`` (idempotent per
+ bus) so ``KillRequested`` events actually reach it.
+ """
+ global _PROCESS_KILL_SWITCH
+ if _PROCESS_KILL_SWITCH is None:
+ _PROCESS_KILL_SWITCH = KillSwitch()
+ return _PROCESS_KILL_SWITCH
+
+
def event_bus_of(_event: KillRequested, bound: list[EventBus]) -> EventBus | None:
"""Heuristic: we do not know which bus the event came from because the bus
reference is not embedded in the event. We publish acks on the last bound
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 99495d0e19..1981b83663 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1773,37 +1773,6 @@ class DesktopApp:
# the deferred brain proxy — NONE of that chain. The user-perceived
# "ready to talk to Jarvis" gate is the wake listener, not the full
# backend, so it must not wait ~15-20 s for subsystems it never uses.
- async def _start_overlay_bg() -> None:
- try:
- # Phase 9.8: start the overlay subprocess when [overlay].enabled=true.
- # Optional package: when it is not installed, desktop boot still serves.
- from jarvis.overlay.integration import start_overlay
-
- await start_overlay(bus=server.bus)
- except ModuleNotFoundError as exc:
- from loguru import logger as _overlay_logger
- if exc.name == "overlay":
- # Genuinely headless: the optional overlay package
- # itself isn't installed (cloud/VPS base install).
- _overlay_logger.debug(
- "Overlay bootstrap skipped: optional overlay package not installed."
- )
- else:
- # AP-23 W2-C: some OTHER dependency in the overlay
- # import chain is missing (e.g. `python-ulid`) — a
- # real, fixable gap, not "no overlay package". Name
- # it explicitly instead of collapsing into the same
- # silent "headless" bucket.
- _overlay_logger.opt(exception=exc).warning(
- "Overlay bootstrap skipped: overlay dependency {!r} missing.",
- exc.name,
- )
- except Exception as exc: # noqa: BLE001
- from loguru import logger as _overlay_logger
- _overlay_logger.opt(exception=exc).warning(
- "Overlay bootstrap failed."
- )
-
def _log_speech_and_orb_done(task: asyncio.Task) -> None:
if task.cancelled():
return
@@ -1836,7 +1805,6 @@ class DesktopApp:
name="speech-and-orb",
)
speech_task.add_done_callback(_log_speech_and_orb_done)
- loop.create_task(_start_overlay_bg(), name="overlay-bootstrap")
# === 2) Everything else, BEHIND the live wake listener ==========
# The heavy backend keeps its original internal order (server.start()
@@ -3498,6 +3466,13 @@ class DesktopApp:
action = cmd.action
if action == "open_ui":
self._safe_window_show()
+ elif action == "kill":
+ # Emergency stop (deep-dive 2026-07-15, C-02): this arm was
+ # missing entirely — the advertised tray "Emergency stop"
+ # was silently swallowed here. Publish KillRequested on the
+ # backend bus (the same bus the CU context's KillSwitch is
+ # bound to) from this non-async pystray bridge thread.
+ self._publish_kill_requested_threadsafe()
elif action == "quit":
self._user_requested_quit = True
try:
@@ -3511,6 +3486,33 @@ class DesktopApp:
target=_bridge_loop, name="jarvis-tray-bridge", daemon=True
).start()
+ def _publish_kill_requested_threadsafe(self) -> None:
+ """Publish ``KillRequested(source="tray")`` from a non-async thread.
+
+ Best-effort and never raises: during early boot the backend loop or
+ the server bus may not exist yet — then there is nothing running that
+ could be stopped, and we log honestly instead of crashing the tray.
+ """
+ from loguru import logger
+
+ loop = self._backend_loop
+ bus = getattr(self._server, "bus", None) if self._server is not None else None
+ if loop is None or loop.is_closed() or bus is None:
+ logger.warning(
+ "Emergency stop pressed, but the backend bus is not up yet — "
+ "nothing is running that could be stopped."
+ )
+ return
+ try:
+ from jarvis.core.events import KillRequested # noqa: PLC0415
+
+ asyncio.run_coroutine_threadsafe(
+ bus.publish(KillRequested(source="tray")), loop
+ )
+ logger.info("Emergency stop: KillRequested(source=tray) published.")
+ except Exception: # noqa: BLE001 — the tray must survive a failed kill
+ logger.opt(exception=True).warning("Emergency stop publish failed.")
+
async def _on_show_window_requested(self, _event: object) -> None:
"""Bus subscriber for ``ShowWindowRequested`` (overlay right-click).
@@ -3812,12 +3814,6 @@ class DesktopApp:
asyncio.run_coroutine_threadsafe(_pty_cleanup(), loop).result(timeout=2.0)
except Exception: # noqa: BLE001
pass
- # Phase 9.8: stop the overlay subprocess BEFORE server.stop().
- try:
- from jarvis.overlay.integration import stop_overlay
- asyncio.run_coroutine_threadsafe(stop_overlay(), loop).result(timeout=2.0)
- except Exception: # noqa: BLE001
- pass
# Stop the serve-first bootstrap (it owns the listening socket).
if self._bootstrap is not None:
try:
diff --git a/tests/unit/control/test_kill_switch_singleton.py b/tests/unit/control/test_kill_switch_singleton.py
new file mode 100644
index 0000000000..f479be3838
--- /dev/null
+++ b/tests/unit/control/test_kill_switch_singleton.py
@@ -0,0 +1,82 @@
+"""Process-wide KillSwitch singleton + the Emergency-Stop chain (C-02).
+
+Deep-dive 2026-07-15 found the advertised global Emergency Stop was never
+wired: no KillSwitch instance existed at boot, ComputerUseContext.kill_switch
+stayed None, and the tray "kill" command was swallowed. These tests pin the
+repaired chain: singleton identity, factory-style bind, and the full
+KillRequested -> registered-CU-token cancellation path (ADR-0004).
+"""
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.control import CancelScope, KillSwitch, get_kill_switch
+from jarvis.control import cancel as cancel_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.events import KillRequested
+
+
[email protected](autouse=True)
+def _reset_singleton():
+ """Isolate the process-global singleton per test."""
+ cancel_mod._PROCESS_KILL_SWITCH = None
+ yield
+ cancel_mod._PROCESS_KILL_SWITCH = None
+
+
+def test_get_kill_switch_returns_one_shared_instance():
+ first = get_kill_switch()
+ second = get_kill_switch()
+ assert isinstance(first, KillSwitch)
+ assert first is second
+
+
+async def test_bind_is_idempotent_per_bus():
+ bus = EventBus()
+ ks = get_kill_switch()
+ ks.bind(bus)
+ ks.bind(bus) # second bind must not double-subscribe
+ assert ks._bound_buses.count(bus) == 1
+
+
+async def test_kill_requested_cancels_a_registered_cu_token():
+ """The full Emergency-Stop chain: a KillRequested event on a bound bus
+ cancels the token a CU mission registered via CancelScope."""
+ bus = EventBus()
+ ks = get_kill_switch()
+ ks.bind(bus)
+
+ async with CancelScope(ks, holder="cu_loop") as token:
+ assert not token.is_cancelled()
+ await bus.publish(KillRequested(source="tray"))
+ # The bus dispatches subscribers asynchronously; give it a beat.
+ for _ in range(50):
+ if token.is_cancelled():
+ break
+ await asyncio.sleep(0.01)
+ assert token.is_cancelled()
+ assert (token.reason or "").startswith("kill_switch")
+
+
+async def test_factory_injects_the_singleton_into_the_cu_context():
+ """The brain factory must hand the SAME process-wide switch to the CU
+ context — the harness's CancelScope(ctx.kill_switch) only works then.
+
+ Exercised structurally (no full factory boot): the context accepts the
+ singleton and the harness-visible field is non-None.
+ """
+ from jarvis.harness.computer_use_context import ComputerUseContext
+
+ ks = get_kill_switch()
+ ctx = ComputerUseContext(
+ vision_engine=object(),
+ brain_manager=object(),
+ tool_executor=object(),
+ kill_switch=ks,
+ )
+ assert ctx.kill_switch is ks