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(cu): serialize desktop missions with a global actuation lock
Ruben Lütke973cc6a642f4
diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.pyindex 08f9e46254..50e0a679fe 100644--- a/jarvis/plugins/harness/computer_use.py+++ b/jarvis/plugins/harness/computer_use.py@@ -33,6 +33,15 @@ _log = logging.getLogger(__name__)_TIMEOUT_EXIT_CODE = 124_CANCEL_EXIT_CODE = 130+# Global desktop actuation lock (deep-dive 2026-07-15, H-10). There is ONE+# physical mouse/keyboard/foreground focus: two missions with DIFFERENT goals+# used to run concurrently (the tool only dedupes IDENTICAL goals) and raced+# each other's pointer moves and foreground guards. Every launch route (voice,+# LLM tool, scheduled task) funnels through this harness, so serializing here+# covers them all. A queued mission waits honoring its own deadline and+# cancellation; the wait is logged so "nothing happens" is diagnosable.+_DESKTOP_LOCK = asyncio.Lock()+async def _publish_cu_control(bus, event) -> None:"""Publish a control-indicator event; a publish failure must never@@ -172,18 +181,59 @@ class ComputerUseHarness:# registry is a SET — concurrent CU missions each register so a# single hangup cancels them ALL (BUG-CU-CONCURRENT-CANCEL).register_active_cu_token(token)- # Control-indicator contract (jarvis.cu.indicator): Started fires- # once the token is registered — i.e. the moment this mission may- # actually drive mouse/keyboard — and Ended ALWAYS fires in the- # finally below, on every exit path.mission_id = uuid.uuid4().hex[:12]- await _publish_cu_control(- ctx.bus, CUControlStarted(mission_id=mission_id)- )end_reason = "finished"- run_cu_loop = _resolve_run_cu_loop()- stream = run_cu_loop(task, ctx, cancel_token=token)+ control_started = False+ lock_acquired = False+ stream = Nonetry:+ # H-10: ONE mission drives the desktop at a time. Waiting in+ # short slices keeps the queue responsive to the mission's own+ # deadline and to cancellation (hangup / Emergency Stop).+ if _DESKTOP_LOCK.locked():+ _log.info(+ "[cu] desktop busy — mission queued behind the "+ "active one",+ )+ while not lock_acquired:+ if token.is_cancelled():+ end_reason = "cancelled"+ yield HarnessResult(+ stderr="[cu] cancelled while waiting for the desktop\n",+ exit_code=_CANCEL_EXIT_CODE,+ is_final=True,+ )+ return+ remaining_s = deadline - time.monotonic()+ if remaining_s <= 0:+ end_reason = "timeout"+ yield HarnessResult(+ stderr=(+ f"[cu] timeout after {timeout_s:.3g}s waiting "+ "for the desktop (another mission was active)\n"+ ),+ exit_code=_TIMEOUT_EXIT_CODE,+ is_final=True,+ )+ return+ try:+ await asyncio.wait_for(+ _DESKTOP_LOCK.acquire(),+ timeout=min(0.25, remaining_s),+ )+ lock_acquired = True+ except TimeoutError:+ continue+ # Control-indicator contract (jarvis.cu.indicator): Started+ # fires the moment this mission may actually drive+ # mouse/keyboard (token registered AND desktop lock held);+ # Ended ALWAYS fires in the finally below, on every exit path.+ await _publish_cu_control(+ ctx.bus, CUControlStarted(mission_id=mission_id)+ )+ control_started = True+ run_cu_loop = _resolve_run_cu_loop()+ stream = run_cu_loop(task, ctx, cancel_token=token)while True:remaining_s = deadline - time.monotonic()if remaining_s <= 0:@@ -213,17 +263,21 @@ class ComputerUseHarness:is_final=True,)finally:- await stream.aclose()+ if stream is not None:+ await stream.aclose()+ if lock_acquired:+ _DESKTOP_LOCK.release()self._active_token = None# Remove only THIS mission's token — a concurrently-running# sibling stays registered and cancelable (BUG-CU-CONCURRENT-# CANCEL: clearing the whole registry here orphaned the sibling# so a later hangup found no token at all).unregister_active_cu_token(token)- await _publish_cu_control(- ctx.bus,- CUControlEnded(mission_id=mission_id, reason=end_reason),- )+ if control_started:+ await _publish_cu_control(+ ctx.bus,+ CUControlEnded(mission_id=mission_id, reason=end_reason),+ )async def cancel(self) -> None:"""Aborts the running invoke.diff --git a/tests/unit/harness/test_cu_desktop_lock.py b/tests/unit/harness/test_cu_desktop_lock.pynew file mode 100644index 0000000000..063d6f7c50--- /dev/null+++ b/tests/unit/harness/test_cu_desktop_lock.py@@ -0,0 +1,151 @@+"""Global desktop actuation lock at the ComputerUseHarness boundary+(deep-dive 2026-07-15, H-10).++There is ONE physical mouse/keyboard: two missions with DIFFERENT goals used+to run concurrently and race each other's pointer moves and foreground+guards (the tool layer only dedupes IDENTICAL goals). The harness now+serializes missions; a queued mission honors its own deadline and+cancellation while waiting.+"""+from __future__ import annotations++import asyncio+import time+from collections.abc import AsyncIterator++import pytest++from jarvis.control import KillSwitch+from jarvis.core.bus import EventBus+from jarvis.core.protocols import HarnessResult, HarnessTask+from jarvis.harness.computer_use_context import ComputerUseContext+from jarvis.plugins.harness import computer_use as cu_mod+from jarvis.plugins.harness.computer_use import ComputerUseHarness+++def _ctx(bus: EventBus) -> ComputerUseContext:+ return ComputerUseContext(+ vision_engine=object(),+ brain_manager=object(),+ tool_executor=object(),+ bus=bus,+ kill_switch=KillSwitch(),+ )++[email protected](autouse=True)+def _fresh_lock_and_registry():+ """Fresh module lock per test + clean CU token registry/suppression."""+ from jarvis.harness.computer_use_context import (+ clear_cu_suppression,+ register_active_cu_token,+ )++ cu_mod._DESKTOP_LOCK = asyncio.Lock()+ clear_cu_suppression()+ register_active_cu_token(None)+ yield+ cu_mod._DESKTOP_LOCK = asyncio.Lock()+ clear_cu_suppression()+ register_active_cu_token(None)+++async def test_two_missions_never_overlap(monkeypatch: pytest.MonkeyPatch) -> None:+ """The actuation windows of two concurrent missions must be disjoint."""+ windows: list[tuple[float, float]] = []++ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:+ async def run() -> AsyncIterator[HarnessResult]:+ start = time.monotonic()+ await asyncio.sleep(0.15) # simulated desktop activity+ windows.append((start, time.monotonic()))+ yield HarnessResult(stdout="ok", exit_code=0, is_final=True)+ return run()++ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)+ bus = EventBus()+ ctx = _ctx(bus)+ a = ComputerUseHarness(context=ctx)+ b = ComputerUseHarness(context=ctx)++ async def drain(h: ComputerUseHarness, goal: str) -> None:+ async for _ in h.invoke(HarnessTask(prompt=goal, timeout_s=10)):+ pass++ await asyncio.gather(drain(a, "goal a"), drain(b, "goal b"))++ assert len(windows) == 2+ (s1, e1), (s2, e2) = sorted(windows)+ assert e1 <= s2, "second mission actuated while the first was still active"+++async def test_queued_mission_cancel_aborts_without_running(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Cancelling a QUEUED mission must end it (exit 130) before its loop+ ever runs — the wait itself is cancellable."""+ ran: list[str] = []+ release = asyncio.Event()++ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:+ async def run() -> AsyncIterator[HarnessResult]:+ ran.append(task.prompt)+ await release.wait()+ yield HarnessResult(stdout="ok", exit_code=0, is_final=True)+ return run()++ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)+ bus = EventBus()+ ctx = _ctx(bus)+ first = ComputerUseHarness(context=ctx)+ queued = ComputerUseHarness(context=ctx)++ async def drain(h: ComputerUseHarness, goal: str) -> list[HarnessResult]:+ return [c async for c in h.invoke(HarnessTask(prompt=goal, timeout_s=10))]++ first_task = asyncio.create_task(drain(first, "holder"))+ await asyncio.sleep(0.05) # first mission holds the desktop lock+ queued_task = asyncio.create_task(drain(queued, "queued"))+ await asyncio.sleep(0.05) # queued mission is now waiting on the lock++ await queued.cancel()+ chunks = await asyncio.wait_for(queued_task, timeout=2.0)+ assert chunks and chunks[-1].exit_code == 130+ assert ran == ["holder"] # the queued loop never started++ release.set()+ await asyncio.wait_for(first_task, timeout=2.0)+++async def test_queued_mission_times_out_honestly(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A queued mission whose deadline expires while waiting reports the+ timeout (exit 124) instead of hanging forever."""+ release = asyncio.Event()++ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:+ async def run() -> AsyncIterator[HarnessResult]:+ await release.wait()+ yield HarnessResult(stdout="ok", exit_code=0, is_final=True)+ return run()++ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)+ bus = EventBus()+ ctx = _ctx(bus)+ first = ComputerUseHarness(context=ctx)+ queued = ComputerUseHarness(context=ctx)++ async def drain(h: ComputerUseHarness, goal: str, timeout_s: float) -> list[HarnessResult]:+ return [c async for c in h.invoke(HarnessTask(prompt=goal, timeout_s=timeout_s))]++ first_task = asyncio.create_task(drain(first, "holder", 10))+ await asyncio.sleep(0.05)+ chunks = await asyncio.wait_for(+ asyncio.create_task(drain(queued, "queued", 0.3)), timeout=3.0,+ )+ assert chunks and chunks[-1].exit_code == 124+ assert "waiting for the desktop" in (chunks[-1].stderr or "")++ release.set()+ await asyncio.wait_for(first_task, timeout=2.0)