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): harden indicator lifecycle after code review

Ruben Lütke8cdbc384b31f
diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.py
index 8cbc4221f0..484623ebd2 100644
--- a/jarvis/cu/indicator/controller.py
+++ b/jarvis/cu/indicator/controller.py
@@ -30,7 +30,7 @@ import queue
import subprocess
import sys
import threading
-from contextlib import contextmanager
+from contextlib import contextmanager, suppress
from typing import Any
from jarvis.cu.indicator import capture_guard, protocol, self_input
@@ -152,8 +152,10 @@ class CUIndicatorController:
return
self._send(protocol.CMD_HIDE)
self._send(protocol.CMD_QUIT)
- proc, self._proc = self._proc, None
- await asyncio.to_thread(self._reap, proc)
+ with self._stdin_lock:
+ proc, self._proc = self._proc, None
+ if proc is not None:
+ await asyncio.to_thread(self._reap, proc)
@staticmethod
def _border_capability() -> tuple[bool, str]:
@@ -217,18 +219,28 @@ class CUIndicatorController:
assert proc.stdout is not None
for line in proc.stdout:
ack = protocol.decode_ack(line)
- if ack is not None:
+ # Only the capture guard ever WAITS on an ack, and only for
+ # blank/unblank — queueing the rest (show/hide/quit) would
+ # grow the queue unboundedly on Windows, where the guard is
+ # never registered (capture-affinity covers it).
+ if ack in (protocol.CMD_BLANK, protocol.CMD_UNBLANK):
self._acks.put(ack)
except Exception: # noqa: BLE001
log.debug("[cu-indicator] ack pipe closed", exc_info=True)
def _send(self, cmd: str, **fields: Any) -> bool:
- """Fire-and-forget command write; a dead pipe disables the sidecar."""
- proc = self._proc
- if proc is None or proc.stdin is None or proc.poll() is not None:
- return False
+ """Fire-and-forget command write; a dead pipe disables the sidecar.
+
+ ``_stdin_lock`` guards the whole check-then-write sequence: ``_proc``
+ is touched from the event loop, the capture-guard worker thread, and
+ the ``to_thread`` spawn/reap workers, so the handle swap must be an
+ explicit invariant rather than GIL luck.
+ """
try:
with self._stdin_lock:
+ proc = self._proc
+ if proc is None or proc.stdin is None or proc.poll() is not None:
+ return False
proc.stdin.write(protocol.encode_command(cmd, **fields))
proc.stdin.flush()
return True
@@ -237,7 +249,8 @@ class CUIndicatorController:
"[cu-indicator] sidecar pipe broke — border disabled for the "
"rest of this mission."
)
- self._proc = None
+ with self._stdin_lock:
+ self._proc = None
capture_guard.unregister_hook()
return False
@@ -250,6 +263,12 @@ class CUIndicatorController:
proc.wait(timeout=1.0)
except Exception: # noqa: BLE001
log.debug("[cu-indicator] sidecar reap failed", exc_info=True)
+ # Deterministic handle accounting on long-running installs — do not
+ # leave the pipe FDs to GC timing.
+ for pipe in (proc.stdin, proc.stdout):
+ if pipe is not None:
+ with suppress(Exception):
+ pipe.close()
# ----------------------------------------------------------- capture guard
@contextmanager
diff --git a/jarvis/harness/manager.py b/jarvis/harness/manager.py
index ca13126627..9632c8d6ed 100644
--- a/jarvis/harness/manager.py
+++ b/jarvis/harness/manager.py
@@ -96,11 +96,24 @@ class HarnessManager:
await self._bus.publish(HarnessDispatched(harness=name, task=task))
last: HarnessResult | None = None
- async for result in harness.invoke(task):
- last = result
- if self._bus is not None and not result.is_final:
- await self._bus.publish(HarnessProgress(harness=name, result=result))
- yield result
+ stream = harness.invoke(task)
+ try:
+ async for result in stream:
+ last = result
+ if self._bus is not None and not result.is_final:
+ await self._bus.publish(
+ HarnessProgress(harness=name, result=result)
+ )
+ yield result
+ finally:
+ # A consumer that abandons this dispatch mid-stream (break, outer
+ # cancellation, GC of the dispatch generator) must still unwind
+ # the harness's own finally deterministically — the CU harness
+ # releases the desktop lock, its cancel-token registration, and
+ # the screen indicator (CUControlEnded) there. Without this,
+ # cleanup would wait on the async-generator GC finalizer with no
+ # timing guarantee.
+ await stream.aclose()
if self._bus is not None and last is not None and last.is_final:
await self._bus.publish(HarnessCompleted(harness=name, result=last))
diff --git a/tests/unit/harness/test_cu_control_events.py b/tests/unit/harness/test_cu_control_events.py
index d0aba8db31..221443fff9 100644
--- a/tests/unit/harness/test_cu_control_events.py
+++ b/tests/unit/harness/test_cu_control_events.py
@@ -143,6 +143,65 @@ async def test_timeout_reports_timeout_and_still_ends(
assert [ev.reason for ev in rec.ended] == ["timeout"]
+async def test_abandoned_stream_still_publishes_ended(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A consumer that aborts the invoke stream mid-mission (break /
+ aclose / GC of the outer generator) must still get CUControlEnded —
+ otherwise the yellow border stays lit and Escape stays armed."""
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(stdout="progress", exit_code=0, is_final=False),
+ HarnessResult(stdout="done", exit_code=0, is_final=True),
+ ),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ stream = harness.invoke(HarnessTask(prompt="x", timeout_s=5))
+ first = await anext(stream)
+ assert first.is_final is False
+ await stream.aclose() # consumer walks away mid-mission
+
+ assert len(rec.started) == 1
+ assert len(rec.ended) == 1, (
+ "CUControlEnded must fire deterministically on an abandoned stream"
+ )
+ assert rec.started[0].mission_id == rec.ended[0].mission_id
+
+
+async def test_manager_dispatch_closes_harness_stream_on_break(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """HarnessManager.dispatch must aclose() the inner harness stream when
+ its own consumer breaks early, so the CU finally never waits on GC."""
+ from jarvis.harness.manager import HarnessManager
+
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(stdout="progress", exit_code=0, is_final=False),
+ HarnessResult(stdout="done", exit_code=0, is_final=True),
+ ),
+ )
+ manager = HarnessManager(bus=bus)
+ # Seed the instance directly — entry-point discovery would build the
+ # real harness against the global (unset) context.
+ manager._loaded = True
+ manager._classes["screenshot"] = ComputerUseHarness
+ manager._instances["screenshot"] = ComputerUseHarness(context=_ctx(bus))
+ stream = manager.dispatch("screenshot", HarnessTask(prompt="x", timeout_s=5))
+ async for _result in stream:
+ break # abandon after the first chunk
+ await stream.aclose()
+
+ assert len(rec.started) == 1
+ assert len(rec.ended) == 1
+
+
async def test_concurrent_missions_pair_up(
bus: EventBus, monkeypatch: pytest.MonkeyPatch
) -> None: