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.

feat(cu): in-process run registry — every mission gets an id, status, and per-id cancel

Ruben Lütke4bf9ea8be0a4
diff --git a/jarvis/harness/cu_run_registry.py b/jarvis/harness/cu_run_registry.py
new file mode 100644
index 0000000000..d33bf6b6d7
--- /dev/null
+++ b/jarvis/harness/cu_run_registry.py
@@ -0,0 +1,171 @@
+"""In-process registry of Computer-Use runs (deep-dive 2026-07-15, H-09).
+
+The run-control REST surface (start / status / cancel) needs an inventory of
+missions: id, goal, lifecycle status, timestamps, result. The harness itself
+records every mission here — regardless of launch route (voice, LLM tool,
+scheduled task, REST) — so the API sees them all.
+
+Design constraints:
+
+* **Pure in-memory and bounded** — this is live run control, not history;
+ durable evidence already lives in the flight recorder and session store.
+* **Platform-neutral** — plain Python, no OS APIs, works identically on
+ Windows / macOS / Linux / headless.
+* **Never breaks a mission** — every mutation is defensive; a registry bug
+ must not take down the harness (mirror of the token-registry contract in
+ ``computer_use_context``).
+* **Single event loop** — mutations happen on the backend loop only (the
+ harness and the REST routes share it), so no locking is required.
+"""
+from __future__ import annotations
+
+import logging
+import time
+from collections import OrderedDict
+from dataclasses import dataclass, field
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: Bounded history: the oldest TERMINAL runs are evicted past this size.
+_MAX_RUNS = 100
+
+#: Truncation bound for the stored final output of a run.
+_RESULT_TEXT_MAX = 2000
+
+TERMINAL_STATUSES = frozenset({"finished", "error", "cancelled", "timeout"})
+ACTIVE_STATUSES = frozenset({"queued", "running"})
+
+
+@dataclass
+class CURun:
+ """One Computer-Use mission's control-plane view."""
+
+ mission_id: str
+ goal: str
+ source: str
+ status: str = "queued"
+ started_at: float = field(default_factory=time.time)
+ ended_at: float | None = None
+ exit_code: int | None = None
+ result_text: str = ""
+ #: CancelToken while the run is active; cleared when it ends.
+ token: Any = None
+
+ def snapshot(self) -> dict[str, Any]:
+ """JSON-safe public view (never exposes the token)."""
+ return {
+ "mission_id": self.mission_id,
+ "goal": self.goal,
+ "source": self.source,
+ "status": self.status,
+ "started_at": self.started_at,
+ "ended_at": self.ended_at,
+ "exit_code": self.exit_code,
+ "result_text": self.result_text,
+ }
+
+
+_RUNS: OrderedDict[str, CURun] = OrderedDict()
+
+
+def _evict_if_needed() -> None:
+ if len(_RUNS) <= _MAX_RUNS:
+ return
+ for mission_id, run in list(_RUNS.items()):
+ if len(_RUNS) <= _MAX_RUNS:
+ break
+ if run.status in TERMINAL_STATUSES:
+ _RUNS.pop(mission_id, None)
+
+
+def register_run(
+ mission_id: str, goal: str, token: Any, *, source: str = "app",
+) -> None:
+ """Record a mission the moment its cancel token exists (status queued)."""
+ try:
+ _RUNS[mission_id] = CURun(
+ mission_id=mission_id,
+ goal=str(goal or "")[:500],
+ source=str(source or "app"),
+ token=token,
+ )
+ _evict_if_needed()
+ except Exception: # noqa: BLE001 — the registry must never break a mission
+ log.debug("cu run register failed", exc_info=True)
+
+
+def mark_running(mission_id: str) -> None:
+ """The mission holds the desktop lock and is actually driving input."""
+ run = _RUNS.get(mission_id)
+ if run is not None and run.status == "queued":
+ run.status = "running"
+
+
+def finish_run(
+ mission_id: str,
+ status: str,
+ *,
+ exit_code: int | None = None,
+ result_text: str = "",
+) -> None:
+ """Terminal transition; clears the token so cancel becomes a no-op."""
+ run = _RUNS.get(mission_id)
+ if run is None:
+ return
+ run.status = status if status in TERMINAL_STATUSES else "finished"
+ run.ended_at = time.time()
+ run.exit_code = exit_code
+ run.result_text = str(result_text or "")[:_RESULT_TEXT_MAX]
+ run.token = None
+
+
+def cancel_run(mission_id: str, reason: str = "api_cancel") -> bool:
+ """Cancel ONE active run by id. False when unknown or already terminal.
+
+ The status flips to ``cancelled`` when the harness observes the token —
+ this only fires the token, mirroring the voice-hangup contract.
+ """
+ run = _RUNS.get(mission_id)
+ if run is None or run.status in TERMINAL_STATUSES or run.token is None:
+ return False
+ try:
+ run.token.cancel(reason)
+ except Exception: # noqa: BLE001 — a broken token must not 500 the API
+ log.debug("cu run cancel failed", exc_info=True)
+ return False
+ return True
+
+
+def cancel_all_runs(reason: str = "api_cancel") -> int:
+ """Cancel every active run; returns how many tokens were fired."""
+ cancelled = 0
+ for run in list(_RUNS.values()):
+ if run.status in ACTIVE_STATUSES and run.token is not None:
+ try:
+ run.token.cancel(reason)
+ cancelled += 1
+ except Exception: # noqa: BLE001 — keep cancelling the rest
+ log.debug("cu run cancel failed", exc_info=True)
+ return cancelled
+
+
+def get_run(mission_id: str) -> dict[str, Any] | None:
+ run = _RUNS.get(mission_id)
+ return run.snapshot() if run is not None else None
+
+
+def list_runs(limit: int = 20) -> list[dict[str, Any]]:
+ """Newest-first snapshots, active runs included."""
+ runs = list(_RUNS.values())
+ runs.sort(key=lambda r: r.started_at, reverse=True)
+ return [r.snapshot() for r in runs[: max(1, int(limit))]]
+
+
+def active_run_count() -> int:
+ return sum(1 for r in _RUNS.values() if r.status in ACTIVE_STATUSES)
+
+
+def clear_runs() -> None:
+ """Test/teardown helper — wipes the registry."""
+ _RUNS.clear()
diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.py
index 50e0a679fe..2fdba59720 100644
--- a/jarvis/plugins/harness/computer_use.py
+++ b/jarvis/plugins/harness/computer_use.py
@@ -20,6 +20,7 @@ from collections.abc import AsyncIterator
from jarvis.control import CancelScope
from jarvis.core.events import CUControlEnded, CUControlStarted
from jarvis.core.protocols import HarnessResult, HarnessTask
+from jarvis.harness import cu_run_registry
from jarvis.harness.computer_use_context import (
ComputerUseContext,
cu_recently_cancelled,
@@ -28,6 +29,11 @@ from jarvis.harness.computer_use_context import (
unregister_active_cu_token,
)
+# env keys the run-control REST surface uses to thread identity/provenance
+# through the (frozen) HarnessTask without a protocol change (H-09).
+CU_MISSION_ID_ENV_KEY = "JARVIS_CU_MISSION_ID"
+CU_SOURCE_ENV_KEY = "JARVIS_CU_SOURCE"
+
_log = logging.getLogger(__name__)
_TIMEOUT_EXIT_CODE = 124
@@ -181,8 +187,26 @@ 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)
- mission_id = uuid.uuid4().hex[:12]
+ # Run-control registry (H-09): the REST surface may pre-assign the
+ # mission id via task.env so it can hand it back to the caller;
+ # every other launch route gets a fresh one. Registered as
+ # "queued" here, "running" once the desktop lock is held, and
+ # terminal in the finally — so `jarvis api` status/cancel sees
+ # every mission regardless of how it was started.
+ task_env = task.env or {}
+ mission_id = (
+ str(task_env.get(CU_MISSION_ID_ENV_KEY, "") or "")
+ or uuid.uuid4().hex[:12]
+ )
+ cu_run_registry.register_run(
+ mission_id,
+ task.prompt,
+ token,
+ source=str(task_env.get(CU_SOURCE_ENV_KEY, "") or "app"),
+ )
end_reason = "finished"
+ final_exit_code: int | None = None
+ final_stdout = ""
control_started = False
lock_acquired = False
stream = None
@@ -198,6 +222,7 @@ class ComputerUseHarness:
while not lock_acquired:
if token.is_cancelled():
end_reason = "cancelled"
+ final_exit_code = _CANCEL_EXIT_CODE
yield HarnessResult(
stderr="[cu] cancelled while waiting for the desktop\n",
exit_code=_CANCEL_EXIT_CODE,
@@ -207,6 +232,7 @@ class ComputerUseHarness:
remaining_s = deadline - time.monotonic()
if remaining_s <= 0:
end_reason = "timeout"
+ final_exit_code = _TIMEOUT_EXIT_CODE
yield HarnessResult(
stderr=(
f"[cu] timeout after {timeout_s:.3g}s waiting "
@@ -232,6 +258,7 @@ class ComputerUseHarness:
ctx.bus, CUControlStarted(mission_id=mission_id)
)
control_started = True
+ cu_run_registry.mark_running(mission_id)
run_cu_loop = _resolve_run_cu_loop()
stream = run_cu_loop(task, ctx, cancel_token=token)
while True:
@@ -247,6 +274,8 @@ class ComputerUseHarness:
return
yield chunk
if chunk.is_final:
+ final_exit_code = chunk.exit_code
+ final_stdout = chunk.stdout or ""
if chunk.exit_code == _CANCEL_EXIT_CODE:
end_reason = "cancelled"
elif chunk.exit_code != 0:
@@ -254,6 +283,7 @@ class ComputerUseHarness:
return
except TimeoutError:
end_reason = "timeout"
+ final_exit_code = _TIMEOUT_EXIT_CODE
token.cancel("computer_use_harness_timeout")
duration_ms = (time.time_ns() - t_start) // 1_000_000
yield HarnessResult(
@@ -263,6 +293,12 @@ class ComputerUseHarness:
is_final=True,
)
finally:
+ cu_run_registry.finish_run(
+ mission_id,
+ end_reason,
+ exit_code=final_exit_code,
+ result_text=final_stdout,
+ )
if stream is not None:
await stream.aclose()
if lock_acquired:
diff --git a/tests/unit/harness/test_cu_run_registry.py b/tests/unit/harness/test_cu_run_registry.py
new file mode 100644
index 0000000000..1cfbd99526
--- /dev/null
+++ b/tests/unit/harness/test_cu_run_registry.py
@@ -0,0 +1,229 @@
+"""CU run registry + its harness integration (deep-dive 2026-07-15, H-09).
+
+The run-control REST surface needs an inventory of missions with a working
+per-id cancel. The harness records every mission regardless of launch route;
+these tests pin the lifecycle (queued -> running -> terminal), the cancel
+semantics, the boundedness, and the id pass-through from task.env.
+"""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+
+import pytest
+
+from jarvis.control import CancelToken, KillSwitch
+from jarvis.core.bus import EventBus
+from jarvis.core.protocols import HarnessResult, HarnessTask
+from jarvis.harness import cu_run_registry as reg
+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 (
+ CU_MISSION_ID_ENV_KEY,
+ CU_SOURCE_ENV_KEY,
+ ComputerUseHarness,
+)
+
+
[email protected](autouse=True)
+def _clean_state():
+ from jarvis.harness.computer_use_context import (
+ clear_cu_suppression,
+ register_active_cu_token,
+ )
+
+ reg.clear_runs()
+ cu_mod._DESKTOP_LOCK = asyncio.Lock()
+ clear_cu_suppression()
+ register_active_cu_token(None)
+ yield
+ reg.clear_runs()
+ cu_mod._DESKTOP_LOCK = asyncio.Lock()
+ clear_cu_suppression()
+ register_active_cu_token(None)
+
+
+# ----------------------------------------------------------------------
+# Pure registry semantics
+# ----------------------------------------------------------------------
+
+def test_lifecycle_and_snapshot_shape() -> None:
+ token = CancelToken()
+ reg.register_run("m1", "open the browser", token, source="api")
+ run = reg.get_run("m1")
+ assert run is not None
+ assert run["status"] == "queued"
+ assert run["goal"] == "open the browser"
+ assert run["source"] == "api"
+ assert "token" not in run # never expose the token
+
+ reg.mark_running("m1")
+ assert reg.get_run("m1")["status"] == "running"
+ assert reg.active_run_count() == 1
+
+ reg.finish_run("m1", "finished", exit_code=0, result_text="proof text")
+ run = reg.get_run("m1")
+ assert run["status"] == "finished"
+ assert run["exit_code"] == 0
+ assert run["result_text"] == "proof text"
+ assert run["ended_at"] is not None
+ assert reg.active_run_count() == 0
+
+
+def test_cancel_fires_the_token_only_while_active() -> None:
+ token = CancelToken()
+ reg.register_run("m1", "goal", token)
+ assert reg.cancel_run("m1") is True
+ assert token.is_cancelled()
+ assert token.reason == "api_cancel"
+
+ # Terminal runs and unknown ids refuse.
+ reg.finish_run("m1", "cancelled", exit_code=130)
+ assert reg.cancel_run("m1") is False
+ assert reg.cancel_run("nope") is False
+
+
+def test_cancel_all_hits_every_active_run() -> None:
+ tokens = [CancelToken() for _ in range(3)]
+ for i, tok in enumerate(tokens):
+ reg.register_run(f"m{i}", f"goal {i}", tok)
+ reg.finish_run("m0", "finished", exit_code=0) # terminal: not cancelled
+
+ assert reg.cancel_all_runs() == 2
+ assert not tokens[0].is_cancelled()
+ assert tokens[1].is_cancelled()
+ assert tokens[2].is_cancelled()
+
+
+def test_registry_stays_bounded() -> None:
+ for i in range(reg._MAX_RUNS + 30):
+ reg.register_run(f"m{i}", "g", CancelToken())
+ reg.finish_run(f"m{i}", "finished", exit_code=0)
+ assert len(reg.list_runs(limit=1000)) <= reg._MAX_RUNS
+
+
+def test_list_runs_newest_first() -> None:
+ reg.register_run("old", "g1", CancelToken())
+ reg._RUNS["old"].started_at -= 100
+ reg.register_run("new", "g2", CancelToken())
+ ids = [r["mission_id"] for r in reg.list_runs()]
+ assert ids == ["new", "old"]
+
+
+# ----------------------------------------------------------------------
+# Harness integration
+# ----------------------------------------------------------------------
+
+def _ctx(bus: EventBus) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=object(),
+ brain_manager=object(),
+ tool_executor=object(),
+ bus=bus,
+ kill_switch=KillSwitch(),
+ )
+
+
+def _stub_loop(*chunks: HarnessResult):
+ def factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:
+ async def run() -> AsyncIterator[HarnessResult]:
+ for chunk in chunks:
+ yield chunk
+ return run()
+
+ return factory
+
+
+async def test_harness_records_the_run_with_env_provided_id(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(stdout="the proof", exit_code=0, is_final=True)
+ ),
+ )
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+ task = HarnessTask(
+ prompt="open the browser",
+ timeout_s=5,
+ env={CU_MISSION_ID_ENV_KEY: "rest123", CU_SOURCE_ENV_KEY: "api"},
+ )
+ async for _ in harness.invoke(task):
+ pass
+
+ run = reg.get_run("rest123")
+ assert run is not None
+ assert run["status"] == "finished"
+ assert run["source"] == "api"
+ assert run["exit_code"] == 0
+ assert run["result_text"] == "the proof"
+
+
+async def test_harness_records_error_and_timeout_statuses(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(HarnessResult(stdout="", exit_code=7, is_final=True)),
+ )
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+ async for _ in harness.invoke(
+ HarnessTask(prompt="x", timeout_s=5, env={CU_MISSION_ID_ENV_KEY: "err1"})
+ ):
+ pass
+ assert reg.get_run("err1")["status"] == "error"
+
+ def hanging_factory(task, ctx, cancel_token=None):
+ async def run() -> AsyncIterator[HarnessResult]:
+ await asyncio.sleep(3600)
+ if False: # pragma: no cover
+ yield None
+ return run()
+
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: hanging_factory)
+ async for _ in harness.invoke(
+ HarnessTask(prompt="x", timeout_s=1, env={CU_MISSION_ID_ENV_KEY: "to1"})
+ ):
+ pass
+ run = reg.get_run("to1")
+ assert run["status"] == "timeout"
+ assert run["exit_code"] == 124
+
+
+async def test_registry_cancel_stops_a_live_mission(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The full H-09 cancel chain: registry cancel -> token -> loop stops."""
+ started = asyncio.Event()
+
+ def factory(task: HarnessTask, ctx, cancel_token=None):
+ async def run() -> AsyncIterator[HarnessResult]:
+ started.set()
+ await cancel_token.wait_until_cancelled()
+ yield HarnessResult(stdout="", exit_code=130, is_final=True)
+ return run()
+
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: factory)
+ harness = ComputerUseHarness(context=_ctx(EventBus()))
+
+ async def drain() -> list[HarnessResult]:
+ return [
+ c async for c in harness.invoke(
+ HarnessTask(
+ prompt="live", timeout_s=10,
+ env={CU_MISSION_ID_ENV_KEY: "live1"},
+ )
+ )
+ ]
+
+ run_task = asyncio.create_task(drain())
+ await asyncio.wait_for(started.wait(), timeout=2.0)
+ assert reg.get_run("live1")["status"] == "running"
+
+ assert reg.cancel_run("live1") is True
+ chunks = await asyncio.wait_for(run_task, timeout=2.0)
+ assert chunks and chunks[-1].exit_code == 130
+ assert reg.get_run("live1")["status"] == "cancelled"