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(tasks): scheduled harness/Computer-Use actions actually run, are authorized, and are cancellable

Ruben Lütke3ff6fc95af82
diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.py
index a5e3aeb27a..f11f6ae52c 100644
--- a/jarvis/tasks/runner.py
+++ b/jarvis/tasks/runner.py
@@ -28,6 +28,8 @@ cancelled()`` before every step. If set, it aborts and sets the state to
"""
from __future__ import annotations
+import asyncio
+import contextlib
import logging
import time
from collections.abc import Iterable
@@ -270,6 +272,18 @@ class TaskRunner:
# test environments
from jarvis.core.protocols import HarnessTask
+ # Authorization gate (deep-dive 2026-07-15, H-03): allow_computer_use
+ # used to be write-only — nothing anywhere read it, so a task could
+ # drive the desktop regardless of the flag. Enforce it at the one
+ # place the flag originates: a dispatch targeting the Computer-Use
+ # harness without the grant fails before anything touches the screen.
+ if not action.allow_computer_use and _targets_computer_use(action.harness):
+ raise RuntimeError(
+ "this task dispatches to the Computer-Use harness but "
+ "allow_computer_use is false — re-create the task with "
+ "desktop control allowed to authorize it"
+ )
+
# Interpolate {field} placeholders from the triggering event so a CU goal
# like "open {result_uri} in the browser" resolves to the finished
# mission's artifact. No-op for time-based tasks (empty ctx).
@@ -287,24 +301,97 @@ class TaskRunner:
source_layer="tasks.runner")
)
- async for result in await _aiter_safe(self._harness.dispatch(action.harness, task)):
- self._check_cancel(cancel_token)
- payload: dict[str, Any] = {
- "stdout": getattr(result, "stdout", ""),
- "stderr": getattr(result, "stderr", ""),
- "exit_code": getattr(result, "exit_code", 0),
- "is_final": getattr(result, "is_final", False),
- }
- seq = await self._store.append_step(task_id, "log", payload)
- await self._bus.publish(
- TaskStepRecorded(task_id=task_id, seq=seq, kind="log",
- source_layer="tasks.runner")
- )
- if payload["is_final"] and int(payload["exit_code"]) != 0:
- raise RuntimeError(
- f"Harness '{action.harness}' exit_code={payload['exit_code']}: "
- f"{payload['stderr']!s}"
+ stream = await _aiter_safe(self._harness.dispatch(action.harness, task))
+ try:
+ while True:
+ result = await self._next_chunk(stream, cancel_token)
+ if result is _STREAM_END:
+ break
+ payload: dict[str, Any] = {
+ "stdout": getattr(result, "stdout", ""),
+ "stderr": getattr(result, "stderr", ""),
+ "exit_code": getattr(result, "exit_code", 0),
+ "is_final": getattr(result, "is_final", False),
+ }
+ seq = await self._store.append_step(task_id, "log", payload)
+ await self._bus.publish(
+ TaskStepRecorded(task_id=task_id, seq=seq, kind="log",
+ source_layer="tasks.runner")
)
+ if payload["is_final"] and int(payload["exit_code"]) != 0:
+ raise RuntimeError(
+ f"Harness '{action.harness}' exit_code={payload['exit_code']}: "
+ f"{payload['stderr']!s}"
+ )
+ except _Cancelled:
+ # H-03: abandoning the stream is not enough — a Computer-Use
+ # mission keeps driving the desktop. Stop the harness itself.
+ await self._cancel_harness(action.harness)
+ raise
+ finally:
+ aclose = getattr(stream, "aclose", None)
+ if callable(aclose):
+ with contextlib.suppress(Exception):
+ await aclose()
+
+ @staticmethod
+ async def _next_chunk(stream: Any, cancel_token: CancelToken | None) -> Any:
+ """Next stream item, racing the task's cancel token (H-03).
+
+ The old per-chunk cancel probe only ran BETWEEN items — a Computer-Use
+ mission can yield nothing for minutes, so a cancelled task kept
+ clicking until its own timeout. Returns :data:`_STREAM_END` when the
+ stream is exhausted; raises :class:`_Cancelled` the moment the token
+ fires, even mid-item.
+ """
+ if cancel_token is None:
+ try:
+ return await anext(stream)
+ except StopAsyncIteration:
+ return _STREAM_END
+ if cancel_token.is_cancelled():
+ raise _Cancelled(cancel_token.reason or "cancelled")
+ next_item = asyncio.ensure_future(anext(stream))
+ cancelled = asyncio.ensure_future(cancel_token.wait_until_cancelled())
+ try:
+ done, _pending = await asyncio.wait(
+ {next_item, cancelled}, return_when=asyncio.FIRST_COMPLETED,
+ )
+ finally:
+ for pending_task in (next_item, cancelled):
+ if not pending_task.done():
+ pending_task.cancel()
+ with contextlib.suppress(BaseException):
+ await cancelled
+ if next_item in done:
+ try:
+ return next_item.result()
+ except StopAsyncIteration:
+ return _STREAM_END
+ with contextlib.suppress(BaseException):
+ await next_item
+ raise _Cancelled(cancel_token.reason or "cancelled")
+
+ async def _cancel_harness(self, name: str) -> None:
+ """Best-effort: tell the running harness instance itself to stop.
+
+ Never raises and never masks the caller's :class:`_Cancelled` — a
+ harness without a ``cancel()`` (or a failing one) degrades to the old
+ abandon-the-stream behavior.
+ """
+ getter = getattr(self._harness, "get", None)
+ if not callable(getter):
+ return
+ try:
+ harness = getter(name)
+ except Exception: # noqa: BLE001 — unknown/unbuilt harness: nothing runs
+ return
+ cancel = getattr(harness, "cancel", None)
+ if callable(cancel):
+ try:
+ await cancel()
+ except Exception: # noqa: BLE001 — best-effort stop
+ log.debug("harness %r cancel failed", name, exc_info=True)
async def _run_speak(
self,
@@ -510,6 +597,23 @@ class _Cancelled(RuntimeError):
"""Internal sentinel for cancel paths."""
+#: Sentinel returned by ``_next_chunk`` when the harness stream is exhausted.
+_STREAM_END = object()
+
+
+def _targets_computer_use(harness_name: str) -> bool:
+ """True when a dispatch targets the Computer-Use harness.
+
+ The canonical harness name lives in the local action gate (single home
+ for the literal); the fallback keeps minimal test environments working.
+ """
+ try:
+ from jarvis.brain.local_action_gate import HARNESS_NAME # noqa: PLC0415
+ except Exception: # noqa: BLE001 — gate module unavailable (minimal env)
+ return harness_name == "screenshot"
+ return harness_name == HARNESS_NAME
+
+
class _SafeDict(dict):
"""``str.format_map`` backing dict that leaves unknown ``{key}`` untouched."""
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index adf865bdae..444b6b450e 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -105,6 +105,9 @@ class TaskScheduler:
self._fired_dedup: dict[tuple[str, str], None] = {}
# Pending runner tasks, so we can clean up on cancel.
self._runner_tasks: set[asyncio.Task[Any]] = set()
+ # Per-run cancel tokens (H-03): cancel_task() fires the token of a
+ # RUNNING task so its harness action stops; cleared in _safe_run.
+ self._running_tokens: dict[str, Any] = {}
# ------------------------------------------------------------------
# Runner wiring (DI — the runner can be set after construction)
@@ -138,15 +141,21 @@ class TaskScheduler:
async def cancel_task(self, task_id: str, reason: str = "user_cancel") -> bool:
"""Marks a task as ``cancelled`` if it isn't already terminal.
- Also removes it from the in-memory structures. Running runners are
- NOT interrupted directly — that's what the kill-switch path is for.
- The use case here is: "task was scheduled, user hits X."
+ Also removes it from the in-memory structures. A RUNNING task's
+ per-run cancel token is fired too (deep-dive 2026-07-15, H-03): the
+ runner races its harness stream against that token and stops the
+ harness itself, so cancelling a running Computer-Use task no longer
+ leaves desktop automation clicking until its own timeout. The global
+ kill switch remains the emergency path for everything at once.
"""
task = await self._store.get(task_id)
if task is None:
return False
if task["state"] in ("completed", "failed", "cancelled", "interrupted"):
return False
+ running_token = self._running_tokens.get(task_id)
+ if running_token is not None:
+ running_token.cancel(reason)
# Remove from heap (linear scan, small enough — a typical queue is < 100).
self._heap = [(due, tid) for (due, tid) in self._heap if tid != task_id]
heapq.heapify(self._heap)
@@ -408,13 +417,28 @@ class TaskScheduler:
async def _safe_run(
self, task_id: str, trigger_event: dict[str, Any] | None = None
) -> None:
+ # Per-run cancel token (deep-dive 2026-07-15, H-03): production runs
+ # used to pass NO token, so the runner's cancel probes were no-ops and
+ # a running harness action was unstoppable except via the global kill
+ # switch. cancel_task() fires this token for a single running task.
+ from jarvis.control.cancel import CancelToken # noqa: PLC0415
+
+ token = CancelToken()
+ self._running_tokens[task_id] = token
try:
- await self._runner.run(task_id, trigger_event=trigger_event) # type: ignore[union-attr]
+ await self._runner.run( # type: ignore[union-attr]
+ task_id, token, trigger_event=trigger_event,
+ )
except Exception as exc: # noqa: BLE001
log.exception("TaskRunner crashed task=%s: %s", task_id, exc)
+ finally:
+ self._running_tokens.pop(task_id, None)
async def shutdown(self) -> None:
- """Waits for runner tasks to finish (with a timeout). The caller must stop the loop first."""
+ """Waits for runner tasks to finish (with a timeout).
+
+ The caller must stop the loop first.
+ """
tasks = list(self._runner_tasks)
if not tasks:
return
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 0152725c02..0f099ab921 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -2618,9 +2618,18 @@ class WebServer:
# write/full auto-approve those ask-tier calls for their own turn.
auto_approver = TaskAutoApprover(self.bus)
+ # Harness dispatch (deep-dive 2026-07-15, H-02): the UI offers
+ # scheduled Computer-Use actions (taskSpec.ts thenKind "computer_use"
+ # -> harness_dispatch), but this runner shipped without a
+ # HarnessManager, so every such task failed at runtime with
+ # "HarnessManager not configured". The manager is cheap to construct
+ # (entry-point class scan; instances build lazily on first dispatch).
+ from jarvis.harness.manager import HarnessManager
+
runner = TaskRunner(
store=store,
bus=self.bus,
+ harness_manager=HarnessManager(bus=self.bus),
agent_brain=agent_brain,
auto_approver=auto_approver,
)
diff --git a/tests/unit/tasks/test_runner.py b/tests/unit/tasks/test_runner.py
index df7ba489bb..382f073e97 100644
--- a/tests/unit/tasks/test_runner.py
+++ b/tests/unit/tasks/test_runner.py
@@ -299,3 +299,122 @@ async def test_runner_emits_task_started(store: TaskStore, bus: EventBus) -> Non
async def _append(target: list[Any], evt: Any) -> None:
target.append(evt)
+
+
+# ----------------------------------------------------------------------
+# Computer-Use authorization + cancel propagation
+# (deep-dive 2026-07-15, H-02/H-03)
+# ----------------------------------------------------------------------
+
+class HangingHarness:
+ """Harness whose stream never yields until cancelled — models a running
+ Computer-Use mission that produces no chunks for minutes."""
+
+ def __init__(self) -> None:
+ self.cancelled = False
+ import asyncio
+ self._release = asyncio.Event()
+
+ async def cancel(self) -> None:
+ self.cancelled = True
+ self._release.set()
+
+
+class HangingHarnessManager:
+ """dispatch() blocks forever; exposes get() so the runner can cancel."""
+
+ def __init__(self) -> None:
+ self.harness = HangingHarness()
+ self.dispatched: list[tuple[str, Any]] = []
+
+ def get(self, name: str) -> Any:
+ return self.harness
+
+ async def dispatch(self, name: str, task: Any):
+ self.dispatched.append((name, task))
+ harness = self.harness
+
+ async def gen():
+ await harness._release.wait()
+ if False: # pragma: no cover — keep this an async generator
+ yield None
+ return gen()
+
+
+async def test_cu_dispatch_without_allow_flag_fails_closed(
+ store: TaskStore, bus: EventBus
+) -> None:
+ """A dispatch to the CU harness without allow_computer_use must fail
+ BEFORE anything reaches the harness (the flag used to be write-only)."""
+ hm = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ spec = TaskSpec(
+ title="unauthorized cu",
+ trigger=TriggerAfterDelay(delay_seconds=1.0),
+ action=HarnessDispatchAction(
+ harness="screenshot", prompt="click something",
+ allow_computer_use=False,
+ ),
+ )
+ tid = await store.insert(spec)
+ await runner.run(tid)
+
+ task = await store.get(tid)
+ assert task is not None
+ assert task["state"] == "failed"
+ assert "allow_computer_use" in (task["last_error"] or "")
+ assert hm.dispatched == [] # never reached the harness
+
+
+async def test_cu_dispatch_with_allow_flag_runs(
+ store: TaskStore, bus: EventBus
+) -> None:
+ hm = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ spec = TaskSpec(
+ title="authorized cu",
+ trigger=TriggerAfterDelay(delay_seconds=1.0),
+ action=HarnessDispatchAction(
+ harness="screenshot", prompt="open the browser",
+ allow_computer_use=True,
+ ),
+ )
+ tid = await store.insert(spec)
+ await runner.run(tid)
+
+ task = await store.get(tid)
+ assert task is not None
+ assert task["state"] == "completed"
+ assert len(hm.dispatched) == 1
+
+
+async def test_cancel_mid_stream_stops_the_harness(
+ store: TaskStore, bus: EventBus
+) -> None:
+ """Cancelling a running task must reach INTO the harness (H-03): the old
+ per-chunk probe never fired on a chunkless stream, and the harness was
+ never told to stop."""
+ import asyncio
+
+ hm = HangingHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ spec = TaskSpec(
+ title="cancel me",
+ trigger=TriggerAfterDelay(delay_seconds=1.0),
+ action=HarnessDispatchAction(
+ harness="screenshot", prompt="long mission",
+ allow_computer_use=True,
+ ),
+ )
+ tid = await store.insert(spec)
+
+ token = CancelToken()
+ run_task = asyncio.create_task(runner.run(tid, token))
+ await asyncio.sleep(0.05) # the stream is now pending with no chunks
+ token.cancel("user_cancel")
+ await asyncio.wait_for(run_task, timeout=2.0)
+
+ task = await store.get(tid)
+ assert task is not None
+ assert task["state"] == "cancelled"
+ assert hm.harness.cancelled # the stop reached the harness itself
diff --git a/tests/unit/tasks/test_scheduler.py b/tests/unit/tasks/test_scheduler.py
index 84cb852f85..87b7d11a3e 100644
--- a/tests/unit/tasks/test_scheduler.py
+++ b/tests/unit/tasks/test_scheduler.py
@@ -261,3 +261,47 @@ def test_filter_expr_rejects_dangerous_input() -> None:
assert _match_filter(evt, "role == 'user' and text == 'hi'") is True
assert _match_filter(evt, "role == 'user' or text == 'bye'") is True
assert _match_filter(evt, "not role == 'admin'") is True
+
+
+# ----------------------------------------------------------------------
+# Running-task cancellation (deep-dive 2026-07-15, H-03)
+# ----------------------------------------------------------------------
+
+async def test_cancel_task_fires_the_running_runs_token(
+ store: TaskStore, bus: EventBus
+) -> None:
+ """cancel_task() on a RUNNING task must fire that run's cancel token —
+ production used to pass no token at all, so a running harness action
+ (e.g. a Computer-Use mission) was unstoppable per-task."""
+
+ class BlockingRunner:
+ def __init__(self) -> None:
+ self.token: Any = None
+ self.started = asyncio.Event()
+
+ async def run(self, task_id: str, cancel_token: Any = None, **_kw: Any) -> None:
+ self.token = cancel_token
+ self.started.set()
+ # Behave like the real runner: wait until cancelled.
+ await cancel_token.wait_until_cancelled()
+
+ blocking = BlockingRunner()
+ scheduler = TaskScheduler(store=store, bus=bus, runner=blocking)
+
+ spec = TaskSpec(
+ title="long harness run",
+ trigger=TriggerAfterDelay(delay_seconds=0.01),
+ action=SpeakAction(text="x"),
+ )
+ tid = await scheduler.schedule(spec)
+ await scheduler._dispatch_runner(tid)
+ await asyncio.wait_for(blocking.started.wait(), timeout=2.0)
+
+ assert blocking.token is not None
+ assert not blocking.token.is_cancelled()
+
+ ok = await scheduler.cancel_task(tid, reason="user_cancel")
+ assert ok is True
+ assert blocking.token.is_cancelled()
+ assert blocking.token.reason == "user_cancel"
+ await scheduler.shutdown()
diff --git a/tests/unit/tasks/test_scheduler_whenthen.py b/tests/unit/tasks/test_scheduler_whenthen.py
index 9d96e554a3..882a1e009b 100644
--- a/tests/unit/tasks/test_scheduler_whenthen.py
+++ b/tests/unit/tasks/test_scheduler_whenthen.py
@@ -26,7 +26,11 @@ class CapturingRunner:
self.calls: list[tuple[str, dict[str, Any] | None]] = []
async def run(
- self, task_id: str, *, trigger_event: dict[str, Any] | None = None
+ self,
+ task_id: str,
+ cancel_token: Any = None,
+ *,
+ trigger_event: dict[str, Any] | None = None,
) -> None:
self.calls.append((task_id, trigger_event))