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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ide): re-join agents the PTY host kept running when the app reopens
rubenluetke10-beepf91f2867e675
diff --git a/jarvis/agentic_ide/host_mode.py b/jarvis/agentic_ide/host_mode.pynew file mode 100644index 0000000000..d5f9d33668--- /dev/null+++ b/jarvis/agentic_ide/host_mode.py@@ -0,0 +1,35 @@+"""Whether this process keeps its coding agents in the PTY host.++A switch, deliberately in a module that imports nothing: the desktop shell+turns it on BEFORE its API answers the UI, and importing the registry itself+there would put ~0.4 s of imports in front of the app becoming usable (AP-26).+:class:`jarvis.agentic_ide.session.Registry` reads it when it is created.++Why it has to be on that early: the grid restores and attaches panes the+moment the API answers. A registry that met its first pane with the host still+off started that pane's agent in-process — while the agent the PTY host had+kept running since the app closed went on, unseen (RUB-102, 2026-09-28).+"""++from __future__ import annotations++_enabled = False+++def enable() -> None:+ """Keep this process's coding agents in the PTY host from now on."""+ global _enabled+ _enabled = True+++def enabled() -> bool:+ return _enabled+++def reset() -> None:+ """Tests only."""+ global _enabled+ _enabled = False+++__all__ = ["enable", "enabled", "reset"]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 9f7f34afba..2f62bb5627 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1930,7 +1930,15 @@ class Registry:# instead of this process. Off until the app turns it on through# ``boot_restore``: a registry built by a test, a script or the CLI# keeps its terminals in-process and never starts a background process.- self._host_enabled = False+ # On when the app's entry point switched it on before the UI could+ # reach the API (``host_mode``); ``enable_host`` / ``boot_restore``+ # turn it on later otherwise. Off for tests, scripts and the CLI.+ from . import host_mode++ self._host_enabled = host_mode.enabled()+ # What ``_manager`` hands a synchronous caller while the host is enabled+ # but not attached yet: an empty pool, never pinned (see ``_manager``).+ self._idle_pool: PtyManager | None = None# Set by ``set_surface_context`` when the focused pane changed, so the# route can save it without saving on every repeated report.self._focus_dirty = False@@ -2090,9 +2098,32 @@ class Registry:# Lazy: keeps the terminal stack off the import/boot path (AP-26).from jarvis.terminal.pty_manager import PtyManager+ if self._host_enabled:+ # Never PINNED here while the PTY host is in use. A synchronous+ # caller (a write, a resize, a status read) can arrive before+ # the async path has attached to the host; pinning an+ # in-process pool at that moment made every pane of a reopened+ # app start its agent again inside the app while the originals+ # kept running, unseen, in the host (RUB-102, 2026-09-28). An+ # empty pool answers those callers truthfully: nothing of+ # theirs runs in this process.+ if self._idle_pool is None:+ self._idle_pool = PtyManager()+ return self._idle_poolself._pty = PtyManager()return self._pty+ def enable_host(self) -> None:+ """Put new and re-joined panes in the PTY host from now on.++ Synchronous and called by the app's entry points BEFORE the UI can+ reach the registry, so no pane ever starts in-process ahead of it.+ """+ from . import host_mode++ host_mode.enable()+ self._host_enabled = True+# ---------------------------------------------------------- PTY hostasync def _live_manager(self) -> PtyManager:"""The pool a NEW agent should start in — the PTY host when possible.@@ -2123,11 +2154,57 @@ class Registry:self._pty = cast("PtyManager", remote)return self._pty+ async def _attached_host(self) -> Any:+ """The PTY host's pool when one is running, WITHOUT starting one.++ Every re-join goes through here, whichever path gets there first — the+ boot pass, a workspace the UI restores, a pane that connects. None when+ the host is disabled, not running, or this process already keeps its+ agents in-process.+ """+ current = self._pty+ if current is not None and getattr(current, "persistent", False):+ if getattr(current, "connected", False):+ return current+ if not self._host_enabled:+ return None+ async with self._host_lock:+ current = self._pty+ if current is not None and not getattr(current, "persistent", False):+ return None+ if current is not None and getattr(current, "connected", False):+ return current+ remote = await _connect_pty_host(start=False)+ if remote is not None:+ self._pty = cast("PtyManager", remote)+ return remote++ @staticmethod+ def _hosted_for(manager: Any) -> dict[str, Any]:+ """The host's not-yet-adopted terminals by pane identity, newest wins."""+ found: dict[str, Any] = {}+ if manager is None or not hasattr(manager, "hosted"):+ return found+ for info in manager.hosted():+ history = str(info.meta.get("history_id") or "")+ if not history:+ continue+ older = found.get(history)+ if older is None or info.started_at > older.started_at:+ found[history] = info+ return found+def _fallback_manager(self) -> PtyManager:- """An in-process pool, replacing a host connection that is gone."""- if self._pty is not None and getattr(self._pty, "persistent", False):- self._pty = None- return self._manager()+ """An in-process pool, replacing a host that is gone or cannot start.++ Pinned on purpose (``_manager`` would not pin one in host mode): a host+ that failed to start is not worth a retry on every pane that connects.+ """+ if self._pty is None or getattr(self._pty, "persistent", False):+ from jarvis.terminal.pty_manager import PtyManager++ self._pty = PtyManager()+ return self._ptyasync def boot_restore(self) -> None:"""Bring back what was open when the app last ran — once per process.@@ -2154,11 +2231,7 @@ class Registry:returnself._boot_restored = Trueself._host_enabled = True- async with self._host_lock:- if self._pty is None:- remote = await _connect_pty_host(start=False)- if remote is not None:- self._pty = cast("PtyManager", remote)+ await self._attached_host()try:snapshot = await asyncio.to_thread(resume_store.load)closed_at = await asyncio.to_thread(resume_store.all_closed_at)@@ -2177,15 +2250,24 @@ class Registry:await self.restore(snapshot)except SessionError as exc:logger.info("Agentic IDE: nothing reopened at startup: {}", exc)- manager = self._pty+ # Ended only when NO workspace could ever claim them — neither an open+ # one nor any the restore point remembers. A remembered workspace that+ # was not reopened now can still be reopened by hand, and its agents+ # must be there to re-join rather than killed on a guess.+ manager: Any = self._pty+ known = set(self._sessions) | {+ w.session_id for w in (snapshot.workspaces if snapshot is not None else [])+ }hosted = manager.hosted() if manager is not None and hasattr(manager, "hosted") else []for info in hosted:+ if str(info.meta.get("workspace_id") or "") in known:+ continuelogger.info(- "Agentic IDE: ending hosted terminal {} — no reopened pane claims it ({})",+ "Agentic IDE: ending hosted terminal {} — no workspace claims it ({})",info.terminal_id,info.meta.get("name", "unnamed"),)- manager.kill_hosted(info.terminal_id) # type: ignore[union-attr]+ manager.kill_hosted(info.terminal_id)await self._resume_after_reboot()async def _resume_after_reboot(self) -> None:@@ -2297,57 +2379,52 @@ class Registry:replay buffer, so the viewer that connects next takes the ordinary"re-join a running agent" path in ``_attach_locked``."""- # Only the host's pool can adopt; typed loosely because the registry- # otherwise sees every pool as the in-process ``PtyManager``.- manager: Any = self._pty+ # Attached here rather than trusted to be attached already: the UI can+ # restore a workspace before the boot pass has reached the host.+ manager: Any = await self._attached_host()if manager is None or not hasattr(manager, "adopt"):return- by_history: dict[str, Any] = {}- for info in manager.hosted():- history = str(info.meta.get("history_id") or "")- if not history:- continue- older = by_history.get(history)- if older is None or info.started_at > older.started_at:- by_history[history] = info+ by_history = self._hosted_for(manager)for term in session.terminals:info = by_history.pop(term.history_id, None)- if info is None:- continue- on_output, on_closed = self._adopted_callbacks(term)- try:- result = await manager.adopt(info.terminal_id, on_output, on_closed)- except Exception as exc: # noqa: BLE001 - the pane falls back to a resume- logger.warning("Agentic IDE: {} could not be re-joined: {}", term.name, exc)- continue- if not result.alive:- continue- cols = result.cols or term.transcript.cols- rows = result.rows or term.transcript.rows- term.transcript.resize(cols, rows)- term.transcript.feed(result.replay)- term.replay.clear()- term.replay.feed(result.replay)- if result.truncated:- term.replay.truncated = True- term.pty_id = info.terminal_id- term.pty_cols, term.pty_rows = cols, rows- term.status = "live"- term.error = ""- term.exit_code = None- term.resumed = False- term.worked_while_detached = term.resume_continuation_needed- # Never interrupted, so never offered a "continue" — the flag- # ``_mark_restored_continuations`` may have raised assumed a restart.- term.continuation_pending = False- term.resume_continuation_needed = False- term.started_at = info.started_at or time.time()- term.last_output_at = time.time() if result.replay else None- if await self._adopted_with_work(term):- term.adopted_generation = term.process_generation- logger.info(- "Agentic IDE: {} re-joined its running agent after an app restart", term.name- )+ if info is not None:+ await self._adopt_one(manager, term, info)++ async def _adopt_one(self, manager: Any, term: Terminal, info: Any) -> bool:+ """Re-join ``term`` to the hosted terminal ``info``. True when it is live."""+ on_output, on_closed = self._adopted_callbacks(term)+ try:+ result = await manager.adopt(info.terminal_id, on_output, on_closed)+ except Exception as exc: # noqa: BLE001 - the pane falls back to a resume+ logger.warning("Agentic IDE: {} could not be re-joined: {}", term.name, exc)+ return False+ if not result.alive:+ return False+ cols = result.cols or term.transcript.cols+ rows = result.rows or term.transcript.rows+ term.transcript.resize(cols, rows)+ term.transcript.feed(result.replay)+ term.replay.clear()+ term.replay.feed(result.replay)+ if result.truncated:+ term.replay.truncated = True+ term.pty_id = info.terminal_id+ term.pty_cols, term.pty_rows = cols, rows+ term.status = "live"+ term.error = ""+ term.exit_code = None+ term.resumed = False+ term.worked_while_detached = term.resume_continuation_needed+ # Never interrupted, so never offered a "continue" — the flag+ # ``_mark_restored_continuations`` may have raised assumed a restart.+ term.continuation_pending = False+ term.resume_continuation_needed = False+ term.started_at = info.started_at or time.time()+ term.last_output_at = time.time() if result.replay else None+ if await self._adopted_with_work(term):+ term.adopted_generation = term.process_generation+ logger.info("Agentic IDE: {} re-joined its running agent after an app restart", term.name)+ return True@staticmethodasync def _adopted_with_work(term: Terminal) -> bool:@@ -3637,6 +3714,13 @@ class Registry:cols = max(term.pty_cols or term.transcript.cols, MIN_VIEWER_COLS)rows = max(term.pty_rows or term.transcript.rows, MIN_VIEWER_ROWS)manager = await self._live_manager()+ if not (term.pty_id and manager.has(term.pty_id)):+ # Herdr's rule: attach to the running session first, start one only+ # when there is none. The host may still hold this pane's agent+ # from before the app restarted — whichever path restored the pane.+ hosted = self._hosted_for(manager).get(term.history_id)+ if hosted is not None:+ await self._adopt_one(manager, term, hosted)if appearance in THEME_COLOURS:term.queries.appearance = appearanceif term.pty_id and hasattr(manager, "set_appearance"):@@ -6291,6 +6375,8 @@ def schedule_boot_restore() -> asyncio.Task[None] | None:which tests boot against the real user data directory and must not attachto the user's PTY host or reopen their workspaces."""+ # Before anything can reach the registry — see ``Registry.enable_host``.+ get_registry().enable_host()try:loop = asyncio.get_running_loop()except RuntimeError:diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 40be485de3..2d3c9a1da5 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2863,6 +2863,14 @@ class DesktopApp:# mission/wiki/session/channel init. TTI forensic 2026-07-02:# the window served at 1.2 s but set_app happened at +16 s,# which is the "Getting ready" wall the user actually sees.+ # BEFORE the UI can reach the API: the grid restores and+ # attaches panes the moment it can, and each of them must+ # re-join the agent the PTY host kept running instead of+ # starting it again in this process (RUB-102). A bare flag —+ # the registry and the reattach pass come after server.start.+ from jarvis.agentic_ide import host_mode++ host_mode.enable()bootstrap.set_app(server.app)_db_mark("app_interactive")if _bp:diff --git a/tests/unit/agentic_ide/test_host_reattach.py b/tests/unit/agentic_ide/test_host_reattach.pynew file mode 100644index 0000000000..75610be682--- /dev/null+++ b/tests/unit/agentic_ide/test_host_reattach.py@@ -0,0 +1,138 @@+"""RUB-102 regression: a reopened app re-joins what the PTY host kept running.++Live failure 2026-09-28: the UI restored and attached panes before the boot+pass ran, a synchronous ``_manager()`` call pinned an in-process pool, and+every agent was started again inside the app while the originals kept running+unseen in the host. Whatever order things arrive in, a pane must re-join its+hosted agent and never start a second one.+"""++from __future__ import annotations++import time+from pathlib import Path+from typing import Any++import pytest++from jarvis.agentic_ide import host_mode, resume_store+from jarvis.agentic_ide import session as ide+from tests.unit.agentic_ide.test_pty_host_adoption import ConnectRecorder, FakeHostedPool++[email protected](autouse=True)+def _isolated(monkeypatch: pytest.MonkeyPatch) -> Any:+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ host_mode.reset()+ yield+ host_mode.reset()+++async def _noop(_value: object) -> None:+ return None+++def _snapshot(folder: Path, *, ws_id: str = "ide_reattach01") -> resume_store.Snapshot:+ now = time.time()+ workspace = resume_store.SnapshotWorkspace(+ session_id=ws_id,+ folder=str(folder),+ terminals=[+ resume_store.SnapshotTerminal(+ key=f"t{i}", name=f"T{i}", agent="claude", history_id=f"hist-{i}", column=i+ )+ for i in (1, 2)+ ],+ saved_at=now,+ )+ snap = resume_store.Snapshot(saved_at=now, workspaces=[workspace], active_session_id=ws_id)+ resume_store.save(snap)+ return snap+++def _host_with_both(ws_id: str = "ide_reattach01") -> FakeHostedPool:+ pool = FakeHostedPool()+ for i in (1, 2):+ pool.add_hosted(f"h-{i}", history_id=f"hist-{i}", replay=f"agent {i} kept working")+ pool.hosted_terminals[f"h-{i}"].meta["workspace_id"] = ws_id+ return pool+++def test_the_switch_is_read_when_the_registry_is_created() -> None:+ assert ide.Registry()._host_enabled is False+ host_mode.enable()+ assert ide.Registry()._host_enabled is True+++def test_a_sync_caller_never_pins_an_in_process_pool_in_host_mode() -> None:+ host_mode.enable()+ registry = ide.Registry()+ pool = registry._manager()+ assert registry._pty is None # not pinned: the host can still be attached+ assert pool.has("anything") is False+++async def test_ui_restoring_before_the_boot_pass_rejoins_the_hosted_agents(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ snap = _snapshot(tmp_path)+ pool = _host_with_both()+ connect = ConnectRecorder(pool)+ monkeypatch.setattr(ide, "_connect_pty_host", connect)+ host_mode.enable()+ registry = ide.Registry()+ registry._manager() # an early synchronous touch, as in the live failure++ # The UI restores the workspace; the boot pass has not run.+ await registry.restore_workspace(snap.workspaces[0].session_id)++ session = registry.sessions[0]+ assert [t.pty_id for t in session.terminals] == ["h-1", "h-2"]+ assert all(t.status == "live" for t in session.terminals)+ assert connect.calls == [False] # attached to the running host, started none+ assert pool.spawns == []++ # A viewer connecting now re-joins; nothing is started again.+ term = await registry.attach("T1", 100, 30, _noop, _noop, workspace_id=session.id)+ assert term.reattached is True+ assert pool.spawns == []+++async def test_a_pane_restored_before_the_host_answered_rejoins_on_attach(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ snap = _snapshot(tmp_path)+ pool = _host_with_both()+ answers: list[Any] = [None] # the first look finds no host yet++ async def connect(*, start: bool) -> Any:+ return answers.pop(0) if answers else pool++ monkeypatch.setattr(ide, "_connect_pty_host", connect)+ host_mode.enable()+ registry = ide.Registry()+ await registry.restore(snap)+ session = registry.sessions[0]+ assert all(t.status == "pending" for t in session.terminals)++ term = await registry.attach("T2", 100, 30, _noop, _noop, workspace_id=session.id)++ assert term.pty_id == "h-2" and term.reattached is True+ assert pool.spawns == [] # re-joined, not started a second time+ assert pool.adopted == ["h-2"]+++async def test_boot_keeps_hosted_agents_of_remembered_workspaces(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _snapshot(tmp_path)+ resume_store.note_all_closed(time.time() + 10) # nothing is reopened at boot+ pool = _host_with_both()+ pool.add_hosted("stray", history_id="nobody") # belongs to no known workspace+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))++ registry = ide.Registry()+ await registry.boot_restore()++ assert pool.killed == ["stray"]+ assert {info.terminal_id for info in pool.hosted()} == {"h-1", "h-2"}