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(cu): make Esc/hangup abort a RUNNING Computer-Use step immediately

Ruben Lütke7cf142f568a2
diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.py
index 874bfdcc77..d04ff88e82 100644
--- a/jarvis/plugins/harness/computer_use.py
+++ b/jarvis/plugins/harness/computer_use.py
@@ -39,6 +39,18 @@ _log = logging.getLogger(__name__)
_TIMEOUT_EXIT_CODE = 124
_CANCEL_EXIT_CODE = 130
+# Heartbeat for the per-step cancellation check (Esc / voice hangup / Emergency
+# Stop). The think-phase brain call is ONE long uninterruptible await (15-68 s
+# live), so without this the token is only read at the loop's next
+# is_cancelled() checkpoint and Esc "does nothing" until the current step ends
+# (live 2026-07-23: five Esc presses over 3 s, the mission ran ~9 s more). We
+# POLL the token flag on a short slice instead of awaiting a cancel EVENT on
+# purpose: on the py3.11 Windows proactor loop an event wakeup can be absorbed
+# when no timer is armed (BUG-081), which would make an event-based wait miss
+# the cancel entirely; a bounded slice always re-checks the flag on resume. At
+# 120 ms the abort is perceptually instant yet adds no measurable idle cost.
+_CANCEL_HEARTBEAT_S = 0.12
+
# 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
@@ -210,6 +222,7 @@ class ComputerUseHarness:
control_started = False
lock_acquired = False
stream = None
+ pending_anext: asyncio.Future | None = None
try:
# H-10: ONE mission drives the desktop at a time. Waiting in
# short slices keeps the queue responsive to the mission's own
@@ -265,13 +278,49 @@ class ComputerUseHarness:
remaining_s = deadline - time.monotonic()
if remaining_s <= 0:
raise TimeoutError
- try:
- chunk = await asyncio.wait_for(
- anext(stream),
- timeout=remaining_s,
+ # Drive the next step as a task so a cancel can ABORT the
+ # in-flight await (the think-phase brain call) the instant
+ # Esc is pressed, instead of waiting for the step to finish
+ # and only then hitting the loop's is_cancelled() checkpoint.
+ # Polled on a short heartbeat (see _CANCEL_HEARTBEAT_S) so a
+ # proactor-lost cancel wakeup can never strand a running
+ # mission after Esc.
+ if pending_anext is None:
+ pending_anext = asyncio.ensure_future(anext(stream))
+ slice_s = min(_CANCEL_HEARTBEAT_S, remaining_s)
+ await asyncio.wait({pending_anext}, timeout=slice_s)
+ if token.is_cancelled():
+ pending_anext.cancel()
+ # Await the settle: the cancel throws CancelledError
+ # (BaseException) into the step's await, and its own
+ # error/StopAsyncIteration may surface — swallow all so
+ # the honest exit-130 below is what the caller sees.
+ try:
+ await pending_anext
+ except asyncio.CancelledError:
+ pass
+ except Exception: # noqa: BLE001 — step is being aborted
+ _log.debug(
+ "[cu] in-flight step raised during Esc/cancel "
+ "abort", exc_info=True,
+ )
+ pending_anext = None
+ end_reason = "cancelled"
+ final_exit_code = _CANCEL_EXIT_CODE
+ yield HarnessResult(
+ stderr="[cu] cancelled\n",
+ exit_code=_CANCEL_EXIT_CODE,
+ is_final=True,
)
+ return
+ if not pending_anext.done():
+ continue # heartbeat expired mid-step — re-check cancel
+ try:
+ chunk = pending_anext.result()
except StopAsyncIteration:
return
+ finally:
+ pending_anext = None
yield chunk
if chunk.is_final:
final_exit_code = chunk.exit_code
@@ -299,6 +348,21 @@ class ComputerUseHarness:
exit_code=final_exit_code,
result_text=final_stdout,
)
+ # Tear down an in-flight step task before closing the generator
+ # (e.g. invoke() itself was cancelled mid-step): aclose() on a
+ # generator whose anext is still running raises "already
+ # running". Awaiting the cancelled task first settles it.
+ if pending_anext is not None and not pending_anext.done():
+ pending_anext.cancel()
+ try:
+ await pending_anext
+ except asyncio.CancelledError:
+ pass
+ except Exception: # noqa: BLE001 — step torn down on exit
+ _log.debug(
+ "[cu] in-flight step raised during teardown",
+ exc_info=True,
+ )
if stream is not None:
await stream.aclose()
if lock_acquired:
diff --git a/tests/unit/harness/test_cu_cancel_responsiveness.py b/tests/unit/harness/test_cu_cancel_responsiveness.py
new file mode 100644
index 0000000000..73bf9307ce
--- /dev/null
+++ b/tests/unit/harness/test_cu_cancel_responsiveness.py
@@ -0,0 +1,149 @@
+"""Esc / voice-hangup / Emergency-Stop must abort a RUNNING Computer-Use step
+immediately, not only at the loop's next checkpoint.
+
+Live 2026-07-23: the yellow screen indicator's "Esc to cancel" fired
+(``[cu-indicator] Escape pressed — cancelled``) but the mission kept going —
+the user pressed Esc five times over 3 s and the run continued ~9 s more. Root
+cause: the harness drove the loop with a single ``await anext(stream)`` per
+step, and the think-phase brain call is ONE long uninterruptible await (15-68 s
+live). The cancel token was only read at the loop's own ``is_cancelled()``
+checkpoints, which sit BETWEEN steps — so a cancel during the brain call did
+nothing until that call returned. The consumer now polls the token on a short
+heartbeat and cancels the in-flight step task the instant the flag is set.
+
+The heartbeat POLLS the flag rather than awaiting a cancel event on purpose:
+on the py3.11 Windows proactor loop an event wakeup can be absorbed when no
+timer is armed (BUG-081), which would strand a running mission after Esc.
+"""
+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,
+ cancel_active_cu,
+)
+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():
+ 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_escape_aborts_a_running_step_immediately(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A cancel during a long in-flight step ends the mission (exit 130) within
+ a couple of heartbeats — it must NOT wait for the step to finish."""
+ step_started = asyncio.Event()
+ release = asyncio.Event() # NEVER set: stands in for a 15-68 s brain call
+
+ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:
+ async def run() -> AsyncIterator[HarnessResult]:
+ yield HarnessResult(stdout="[cu] step 1: thinking\n", is_final=False)
+ step_started.set()
+ await release.wait() # the long, checkpoint-free await
+ yield HarnessResult(stdout="done", exit_code=0, is_final=True)
+ return run()
+
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+
+ async def drain() -> list[HarnessResult]:
+ return [c async for c in harness.invoke(HarnessTask(prompt="do it", timeout_s=30))]
+
+ task = asyncio.create_task(drain())
+ await asyncio.wait_for(step_started.wait(), timeout=2.0)
+ t0 = time.monotonic()
+ cancel_active_cu("user_escape", suppress_new=False) # exactly what Esc does
+ chunks = await asyncio.wait_for(task, timeout=2.0)
+ elapsed = time.monotonic() - t0
+
+ assert chunks and chunks[-1].exit_code == 130
+ assert not release.is_set(), "the test never released the step"
+ assert elapsed < 1.0, f"cancel took {elapsed:.2f}s — not immediate"
+
+
+async def test_cancel_before_first_yield_is_immediate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The very first think can run BEFORE any progress chunk. A cancel while
+ that first step blocks must still abort at once (not after it returns)."""
+ entered = asyncio.Event()
+ release = asyncio.Event() # never set
+
+ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:
+ async def run() -> AsyncIterator[HarnessResult]:
+ entered.set()
+ await release.wait() # blocks before ANY yield
+ yield HarnessResult(stdout="done", exit_code=0, is_final=True)
+ return run()
+
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+
+ async def drain() -> list[HarnessResult]:
+ return [c async for c in harness.invoke(HarnessTask(prompt="do it", timeout_s=30))]
+
+ task = asyncio.create_task(drain())
+ await asyncio.wait_for(entered.wait(), timeout=2.0)
+ t0 = time.monotonic()
+ cancel_active_cu("user_escape", suppress_new=False)
+ chunks = await asyncio.wait_for(task, timeout=2.0)
+
+ assert chunks and chunks[-1].exit_code == 130
+ assert time.monotonic() - t0 < 1.0
+
+
+async def test_uncancelled_mission_still_completes_normally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The heartbeat consumer must not disturb a normal run: every chunk still
+ arrives and the final exit code is preserved."""
+ def loop_factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:
+ async def run() -> AsyncIterator[HarnessResult]:
+ yield HarnessResult(stdout="[cu] step 1\n", is_final=False)
+ await asyncio.sleep(0.05)
+ yield HarnessResult(stdout="[cu] done\n", exit_code=0, is_final=True)
+ return run()
+
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: loop_factory)
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+
+ chunks = [
+ c async for c in harness.invoke(HarnessTask(prompt="do it", timeout_s=10))
+ ]
+
+ assert [c.is_final for c in chunks] == [False, True]
+ assert chunks[-1].exit_code == 0
+ assert chunks[-1].stdout == "[cu] done\n"