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(agentic-ide): turn host in installed builds and reattach at app start

rubenluetke10-beep6f2498721d1f
diff --git a/docs/agentic-ide-threads.md b/docs/agentic-ide-threads.md
index 44b732ea8a..16ae56bd71 100644
--- a/docs/agentic-ide-threads.md
+++ b/docs/agentic-ide-threads.md
@@ -89,11 +89,15 @@ every line the CLI prints and streams them to the app.
- **Another app process takes over** (a second start of the same instance):
the old process hands its turns over without ending them.
+Right after the app starts, it attaches to the host on its own, before any
+window opens a chat, so a waiting approval shows up without delay.
+
Only thread turns run there. A turn running as Jarvis, a goal turn and a
helper turn without tools need state inside the app and stay its children.
-A frozen build cannot start the host and keeps the old behaviour. So does
-any process that is not the desktop app or the web launcher, such as tests
-and scripts. Logs: `logs/turn_host.log` in the Jarvis data folder.
+An installed (frozen) build starts the host by running its own executable
+with `--turn-host`, since it has no `python -m`. Processes that are not the
+desktop app or the web launcher, such as tests and scripts, never start or
+attach to the host. Logs: `logs/turn_host.log` in the Jarvis data folder.
## Platforms
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 26368d3f93..dc2a11c165 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -55,6 +55,13 @@ if len(sys.argv) >= 2 and sys.argv[1] == "--background-service":
raise SystemExit(_launcher_main(sys.argv[1:]))
+# The thread turn host of a frozen build, same reason: no ``-m`` to start
+# ``jarvis.agent_chat.turn_host`` with (see turn_host.FROZEN_FLAG).
+if len(sys.argv) >= 2 and sys.argv[1] == "--turn-host":
+ from jarvis.agent_chat.turn_host import main as _turn_host_main
+
+ raise SystemExit(_turn_host_main(sys.argv[2:]))
+
# Windows Terminal defaults to cp1252 — which breaks Unicode (box-drawing,
# emojis, ✓/✗). Force utf-8 before printing anything.
if sys.platform == "win32":
diff --git a/jarvis/agent_chat/turn_host.py b/jarvis/agent_chat/turn_host.py
index 34ccbea2e5..ec552f6af0 100644
--- a/jarvis/agent_chat/turn_host.py
+++ b/jarvis/agent_chat/turn_host.py
@@ -1,7 +1,9 @@
"""The turn host — a small process that owns the coding CLIs of thread turns.
-Run as ``python -m jarvis.agent_chat.turn_host --state <file> --spool <dir>``.
-Started on demand by :mod:`jarvis.agent_chat.turn_host_client`, never by hand.
+Run as ``python -m jarvis.agent_chat.turn_host --state <file> --spool <dir>``
+(a frozen build: ``<app executable> --turn-host --state ...``, routed by
+``jarvis/__main__.py``). Started on demand by
+:mod:`jarvis.agent_chat.turn_host_client`, never by hand.
## Why a thread's CLI lives in its own process
@@ -69,6 +71,9 @@ from loguru import logger
#: another version alone (it may hold turns from before an update).
PROTOCOL_VERSION = 1
+#: How a frozen build re-enters its own executable as the turn host.
+FROZEN_FLAG = "--turn-host"
+
#: Environment variable carrying the auth token. Never on the command line.
TOKEN_ENV = "JARVIS_TURN_HOST_TOKEN" # noqa: S105 - a variable name, not a secret
diff --git a/jarvis/agent_chat/turn_host_client.py b/jarvis/agent_chat/turn_host_client.py
index d075c16240..a3619e28ba 100644
--- a/jarvis/agent_chat/turn_host_client.py
+++ b/jarvis/agent_chat/turn_host_client.py
@@ -29,13 +29,12 @@ import contextlib
import json
import logging
import secrets
-import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
-from .turn_host import MAX_FRAME_BYTES, PROTOCOL_VERSION, TOKEN_ENV
+from .turn_host import FROZEN_FLAG, MAX_FRAME_BYTES, PROTOCOL_VERSION, TOKEN_ENV
log = logging.getLogger(__name__)
@@ -92,11 +91,11 @@ def host_available() -> bool:
on ``agentic_ide.host_mode`` (the same switch that keeps the terminal
grid's agents in the PTY host). A test, a script or the CLI building an
agent-chat service never starts or attaches to the user's host. A frozen
- build has no ``python -m`` to start one with.
+ build starts it by re-entering its own executable (``FROZEN_FLAG``).
"""
from jarvis.agentic_ide import host_mode
- return host_mode.enabled() and not getattr(sys, "frozen", False)
+ return host_mode.enabled()
def _read_state(path: Path) -> dict[str, Any] | None:
@@ -561,6 +560,7 @@ async def _open(*, start: bool) -> TurnHostClient | None:
token_env=TOKEN_ENV,
log_path=_log_path(),
extra_args=("--spool", str(spool_dir())),
+ frozen_flag=FROZEN_FLAG,
)
if not started:
return None
diff --git a/jarvis/terminal/pty_host_client.py b/jarvis/terminal/pty_host_client.py
index 4ad50d2af5..acc61c537b 100644
--- a/jarvis/terminal/pty_host_client.py
+++ b/jarvis/terminal/pty_host_client.py
@@ -591,9 +591,16 @@ def _start_host(
token_env: str = TOKEN_ENV,
log_path: Path | None = None,
extra_args: tuple[str, ...] = (),
+ frozen_flag: str | None = None,
) -> bool:
- """Start a detached host process; the turn host reuses this with its own module."""
+ """Start a detached host process; the turn host reuses this with its own module.
+
+ A frozen build has no ``-m``: with ``frozen_flag`` it re-enters its own
+ executable with that flag instead, which ``jarvis/__main__.py`` routes to
+ the host's ``main``.
+ """
import jarvis
+ from jarvis.core.frozen import is_frozen
from jarvis.ui.relauncher import spawn_detached
# The host must import THIS jarvis, whichever interpreter path found it.
@@ -604,10 +611,10 @@ def _start_host(
part for part in (package_root, env.get("PYTHONPATH", "")) if part
)
env["PYTHONIOENCODING"] = "utf-8"
+ entry = [frozen_flag] if frozen_flag and is_frozen() else ["-m", module]
argv = [
sys.executable,
- "-m",
- module,
+ *entry,
"--state",
str(state_path),
"--log",
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 2d4a625796..0297842825 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3255,6 +3255,10 @@ class DesktopApp:
from jarvis.agentic_ide.session import schedule_boot_restore
schedule_boot_restore()
+ # Carry on the IDE thread turns the turn host kept running.
+ from jarvis.ui.web.agent_chat_routes import schedule_turn_reattach
+
+ schedule_turn_reattach(server.app.state)
except Exception as exc: # noqa: BLE001 — never kill the backend loop
from loguru import logger as _slog
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index da145b40db..ff9a84ee23 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -303,6 +303,41 @@ def _service_from_state(state: Any) -> AgentChatService | None:
return svc
+#: How long after the server is up the boot reattach waits, so it never sits
+#: on the path to a usable window (AP-26).
+_REATTACH_DELAY_S: Final = 2.0
+
+
+def schedule_turn_reattach(state: Any) -> asyncio.Task[None] | None:
+ """Carry on the thread turns the turn host kept running, right after boot.
+
+ Called by the two real app entry points beside the Agentic IDE's
+ ``schedule_boot_restore``. Without it a reattached turn waited for the
+ first window to open a chat: its output piled up in the host and an
+ approval its CLI asked for stayed unanswered meanwhile. Building the
+ service is what reattaches (``AgentChatService._seal_orphaned_turns``),
+ so this builds it only when the host or its spool holds something.
+ """
+ from jarvis.agent_chat import turn_host_client
+
+ if not turn_host_client.host_available():
+ return None
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ log.debug("agent chat: boot reattach not scheduled — no running loop")
+ return None
+
+ async def _run() -> None:
+ await asyncio.sleep(_REATTACH_DELAY_S)
+ if not await asyncio.to_thread(turn_host_client.may_hold_turns):
+ return
+ if _service_from_state(state) is None:
+ log.warning("agent chat: thread turns wait — the chat service could not be built")
+
+ return loop.create_task(_run(), name="agent-chat-boot-reattach")
+
+
def _service(request: Request) -> AgentChatService:
svc = _service_from_state(request.app.state)
if svc is None:
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 1f63f215d0..02ff9893e0 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -850,6 +850,10 @@ async def _run_headless(args) -> int:
from jarvis.agentic_ide.session import schedule_boot_restore
schedule_boot_restore()
+ # Carry on the IDE thread turns the turn host kept running.
+ from jarvis.ui.web.agent_chat_routes import schedule_turn_reattach
+
+ schedule_turn_reattach(server.app.state)
# The full app's init chain is done and the chat handler is subscribed — hand
# the real ASGI app to the already-listening bootstrap server, which now
diff --git a/tests/unit/agent_chat/test_turn_host.py b/tests/unit/agent_chat/test_turn_host.py
index b3bf61c8a5..fdbd870eed 100644
--- a/tests/unit/agent_chat/test_turn_host.py
+++ b/tests/unit/agent_chat/test_turn_host.py
@@ -327,3 +327,193 @@ def test_tests_and_scripts_never_reach_the_users_turn_host() -> None:
host_mode.reset()
assert not turn_host_client.host_available()
assert not turn_host_client.may_hold_turns()
+
+
+# Asks for a Bash approval on the control protocol, then reports the answer.
+_ASKING_CHILD = (
+ "import json, sys\n"
+ "ask = {'type': 'control_request', 'request_id': 'r1', 'request': {\n"
+ " 'subtype': 'can_use_tool', 'tool_name': 'Bash',\n"
+ " 'input': {'command': 'ls'}, 'tool_use_id': 'tu1'}}\n"
+ "print(json.dumps(ask), flush=True)\n"
+ "for raw in sys.stdin:\n"
+ " obj = json.loads(raw) if raw.strip().startswith('{') else {}\n"
+ " if obj.get('type') != 'control_response':\n"
+ " continue\n"
+ " said = obj['response']['response']['behavior']\n"
+ " text = {'type': 'text', 'text': 'approval: ' + said}\n"
+ " msg = {'type': 'assistant', 'message': {'id': 'm1', 'content': [text]}}\n"
+ " print(json.dumps(msg), flush=True)\n"
+ " end = {'type': 'result', 'subtype': 'success', 'is_error': False, 'usage': {}}\n"
+ " print(json.dumps(end), flush=True)\n"
+ " break\n"
+)
+
+
+async def test_an_approval_the_old_app_never_answered_opens_again_after_a_restart(
+ tmp_path: Path,
+) -> None:
+ host, task, port = await _start_host(tmp_path)
+ store = AgentChatStore(":memory:")
+ try:
+ session = store.create_session(
+ provider="claude-api", model="m", effort="medium", cwd=str(tmp_path), surface="agent"
+ )
+ meta = {
+ "session_id": session.session_id,
+ "turn_id": "t5",
+ "runner": "claude-cli",
+ "shape": "claude",
+ "keep_stdin": True,
+ "control": True,
+ "vendor_session": None,
+ "discover": False,
+ "codex_home": "",
+ "cwd": str(tmp_path),
+ "started_at": time.time(),
+ }
+ first = await _client(port)
+ cli = await first.spawn(
+ [sys.executable, "-c", _ASKING_CHILD],
+ cwd=str(tmp_path),
+ env=None,
+ stdin='{"type": "control_request", "request": {"subtype": "initialize"}}\n',
+ keep_stdin=True,
+ meta=meta,
+ )
+ # The old app saw the request and opened its card — then went away.
+ assert b"control_request" in await cli.stdout.readline()
+ first.detach()
+ await asyncio.sleep(0.2)
+
+ second = await _client(port)
+ again = await second.attach(cli.host_id)
+ assert again is not None
+ asked: list[tuple[str, str]] = []
+ events: list[dict[str, Any]] = []
+
+ async def emit(event: dict[str, Any]) -> None:
+ events.append(event)
+
+ async def approve(call_id: str, name: str, _args: Any, _summary: str) -> str:
+ asked.append((call_id, name))
+ return "allow"
+
+ handle = runner_api.TurnHandle(
+ session=session,
+ turn_id="t5",
+ emit=emit,
+ request_approval=approve,
+ cancel=asyncio.Event(),
+ )
+ await asyncio.wait_for(resume_hosted_cli_turn(handle, again), timeout=30)
+
+ assert asked == [("tu1", "Bash")]
+ texts = [e["payload"]["text"] for e in events if e["kind"] == "assistant_text"]
+ assert texts == ["approval: allow"]
+ assert events[-1]["kind"] == "turn_finished"
+ assert events[-1]["payload"]["status"] == "done"
+ second.detach()
+ finally:
+ store.close()
+ await _stop(host, task)
+
+
+def test_a_frozen_build_starts_the_turn_host_from_its_own_executable(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.core import frozen
+ from jarvis.terminal import pty_host_client
+ from jarvis.ui import relauncher
+
+ started: list[list[str]] = []
+ monkeypatch.setattr(frozen, "is_frozen", lambda: True)
+ monkeypatch.setattr(
+ pty_host_client,
+ "_start_host_windows",
+ lambda argv, *_rest: started.append(list(argv)) or True,
+ )
+ monkeypatch.setattr(
+ relauncher, "spawn_detached", lambda argv, **_kw: started.append(list(argv))
+ )
+ assert pty_host_client._start_host(
+ tmp_path / "state.json",
+ "tok",
+ module=turn_host_client.MODULE,
+ token_env=turn_host.TOKEN_ENV,
+ log_path=tmp_path / "host.log",
+ extra_args=("--spool", str(tmp_path / "spool")),
+ frozen_flag=turn_host.FROZEN_FLAG,
+ )
+ [argv] = started
+ assert argv[0] == sys.executable
+ assert argv[1:3] == ["--turn-host", "--state"]
+ assert "-m" not in argv
+
+
+def test_the_app_executable_routes_the_turn_host_flag_without_booting_the_app(
+ tmp_path: Path,
+) -> None:
+ import subprocess
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ env = {k: v for k, v in __import__("os").environ.items() if k != turn_host.TOKEN_ENV}
+ done = subprocess.run( # noqa: S603 - our own interpreter, fixed arguments
+ [
+ sys.executable,
+ "-m",
+ "jarvis",
+ "--turn-host",
+ "--state",
+ str(tmp_path / "s.json"),
+ "--spool",
+ str(tmp_path / "spool"),
+ ],
+ capture_output=True,
+ env=env,
+ timeout=60,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ # The host's own refusal (no token) — the app itself never started.
+ assert done.returncode == 2
+ assert b"no token" in done.stderr
+
+
+async def test_the_app_start_builds_the_chat_service_only_when_the_host_holds_turns(
+ monkeypatch: pytest.MonkeyPatch, app_host_mode: Any
+) -> None:
+ from types import SimpleNamespace
+
+ from jarvis.ui.web import agent_chat_routes
+
+ monkeypatch.setattr(agent_chat_routes, "_REATTACH_DELAY_S", 0.0)
+ built: list[str] = []
+ holds = {"value": False}
+ monkeypatch.setattr(turn_host_client, "may_hold_turns", lambda: holds["value"])
+
+ def factory() -> str:
+ built.append("svc")
+ return "svc"
+
+ state = SimpleNamespace(agent_chat=None, agent_chat_factory=factory)
+ task = agent_chat_routes.schedule_turn_reattach(state)
+ assert task is not None
+ await task
+ assert built == [] # nothing to carry on: the chat stays unbuilt (AP-26)
+
+ holds["value"] = True
+ task = agent_chat_routes.schedule_turn_reattach(state)
+ assert task is not None
+ await task
+ assert built == ["svc"] and state.agent_chat == "svc"
+
+
+def test_the_app_start_does_nothing_outside_a_real_app_process() -> None:
+ from types import SimpleNamespace
+
+ from jarvis.ui.web import agent_chat_routes
+
+ host_mode.reset()
+ assert agent_chat_routes.schedule_turn_reattach(SimpleNamespace()) is None