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(agentic-ide): reattach thread turns when a sync route builds the chat service

rubenluetke10-beep6d38e920462a
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 28919e168f..5f3bc633e3 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -76,6 +76,28 @@ _ORPHANED_TURN_ERROR: Final = (
Subscriber = asyncio.Queue[dict[str, Any]]
+def _app_loop() -> tuple[asyncio.AbstractEventLoop | None, bool]:
+ """The app's event loop, and whether this code runs on it.
+
+ The service is built on first use, and the first use is often a plain
+ ``def`` route that the web framework runs in a worker thread, where no
+ loop is running. Finding no loop there sealed every thread turn the turn
+ host still held as "Jarvis restarted" (2026-10-06): the worker thread asks
+ the loop it was dispatched from instead.
+ """
+ try:
+ return asyncio.get_running_loop(), True
+ except RuntimeError:
+ pass
+ try:
+ from anyio.from_thread import run_sync
+
+ return run_sync(asyncio.get_running_loop), False
+ except Exception: # noqa: BLE001 - not a framework worker: no loop to reach
+ log.debug("agent chat: built outside any event loop")
+ return None, False
+
+
def _orphan_event(turn_id: str, started_ms: int, last_ms: int) -> dict[str, Any]:
"""The ``turn_finished`` that closes a turn a restart cut off."""
return {
@@ -341,10 +363,7 @@ class AgentChatService:
except sqlite3.Error:
log.warning("agent chat: could not look for turns a restart left open", exc_info=True)
return
- try:
- loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()
- except RuntimeError:
- loop = None
+ loop, on_loop = _app_loop()
hosted_possible: bool | None = None
deferred: list[tuple[str, str, int, int]] = []
sealed = 0
@@ -370,9 +389,26 @@ class AgentChatService:
held = _Running(turn_id, asyncio.Event())
held.setup_task = None
self._running[session_id] = held
- self._reattach_task: asyncio.Task[None] | None = loop.create_task(
- self._reattach_hosted(deferred), name="agent-chat-reattach"
- )
+ if on_loop:
+ self._reattach_task = loop.create_task(
+ self._reattach_hosted(deferred), name="agent-chat-reattach"
+ )
+ else:
+ # Built in a worker thread (a sync route): hand the work to the
+ # app's loop, where every turn task of this service runs.
+ self._reattach_task = asyncio.run_coroutine_threadsafe(
+ self._reattach_hosted(deferred), loop
+ )
+
+ async def wait_reattached(self) -> None:
+ """Until the restart's thread turns are reattached or sealed (tests, tools)."""
+ task = getattr(self, "_reattach_task", None)
+ if task is None:
+ return
+ if isinstance(task, asyncio.Future):
+ await task
+ else:
+ await asyncio.wrap_future(task)
def _may_be_hosted(self, session_id: str) -> bool:
session = self.store.get_session(session_id)
@@ -401,7 +437,9 @@ class AgentChatService:
if delay:
await asyncio.sleep(delay)
client = await turn_host_client.get_client(start=False)
- if client is not None or not turn_host_client.may_hold_turns():
+ # Patience only for a host that is alive but busy; a spool alone
+ # is read at once.
+ if client is not None or not await asyncio.to_thread(turn_host_client.host_running):
break
by_turn: dict[str, Any] = {}
if client is not None:
diff --git a/jarvis/agent_chat/turn_host_client.py b/jarvis/agent_chat/turn_host_client.py
index baa8a6b9f0..0183241bc4 100644
--- a/jarvis/agent_chat/turn_host_client.py
+++ b/jarvis/agent_chat/turn_host_client.py
@@ -112,6 +112,11 @@ def _host_alive(state: dict[str, Any] | None) -> bool:
return host_is_alive(state, module=MODULE)
+def host_running() -> bool:
+ """Is a turn host process alive for this user and boot (it may be busy)?"""
+ return host_available() and _host_alive(_read_state(_state_path()))
+
+
def may_hold_turns() -> bool:
"""Is there anything to collect: a live host, or a turn it spooled to disk?
@@ -706,6 +711,7 @@ __all__ = [
"detach_all",
"get_client",
"host_available",
+ "host_running",
"live_turn_ids",
"may_hold_turns",
"read_spool",
diff --git a/tests/unit/agent_chat/test_turn_host.py b/tests/unit/agent_chat/test_turn_host.py
index f1e0ec4762..d2817c9423 100644
--- a/tests/unit/agent_chat/test_turn_host.py
+++ b/tests/unit/agent_chat/test_turn_host.py
@@ -273,8 +273,9 @@ def app_host_mode() -> Any:
host_mode.reset()
[email protected]("built_in", ["event-loop", "route-worker-thread"])
async def test_a_restarted_app_carries_on_the_thread_turn_the_host_kept(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, app_host_mode: Any
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, app_host_mode: Any, built_in: str
) -> None:
monkeypatch.setattr(turn_host_client, "spool_dir", lambda: tmp_path / "spool")
monkeypatch.setattr(turn_host_client, "_host_alive", lambda state: False)
@@ -297,10 +298,17 @@ async def test_a_restarted_app_carries_on_the_thread_turn_the_host_kept(
)
_spool_record(tmp_path, session_id=kept.session_id, turn_id=f"t-{kept.session_id}", acked=0)
- svc = AgentChatService(AgentChatStore(db))
+ if built_in == "event-loop":
+ svc = AgentChatService(AgentChatStore(db))
+ else:
+ # The thread list is a plain ``def`` route: the framework builds the
+ # service in a worker thread, where no event loop is running.
+ import anyio.to_thread
+
+ svc = await anyio.to_thread.run_sync(lambda: AgentChatService(AgentChatStore(db)))
# Held as running until the host was asked: no second CLI on the conversation.
assert svc.is_running(kept.session_id) and svc.is_running(lost.session_id)
- await svc._reattach_task
+ await svc.wait_reattached()
run = svc._running.get(kept.session_id)
if run is not None and run.task is not None:
await asyncio.wait_for(run.task, timeout=10)