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
feat(ide): keep coding agents running in a PTY host across app restarts
rubenluetke10-beep7100db0cc254
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 42f2482e2b..a1461cd2d9 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1,5 +1,32 @@# OS Feature Parity — macOS / Linux Gap Register+## Persistent Agentic IDE terminals (2026-09-28, T3)++Coding-agent panes now live in a separate PTY host process+(`jarvis/terminal/pty_host.py`) instead of the app process, so closing, quitting+or restarting the app detaches from the agents rather than killing them. The+next start attaches to the host, reopens the last open workspaces in their+saved layout, and re-joins every pane whose agent is still running (with its+screen replayed). A reboot ends the host with everything in it; those panes+then continue through the existing `--resume` path. Closing a pane or a+workspace still ends its agent.++One capability probe, `pty_host_client.host_available()` (a PTY backend exists+and the build is not frozen), decides it on every OS. The host is spawned+detached through `jarvis.ui.relauncher.spawn_detached`: on Windows with+`DETACHED_PROCESS | CREATE_NO_WINDOW | CREATE_BREAKAWAY_FROM_JOB` (retried+without breakaway when a parent job forbids it), on macOS and Linux with+`start_new_session`. It owns the ConPTY / POSIX PTYs and their kill-on-close+containers (Job Object / process group), listens on 127.0.0.1 with a random+token handed over in the environment, and exits after 60 s with no terminal+and no client. Where the probe fails, or the host cannot start, the registry+keeps the in-process pool: terminals work as before and die with the app. A+headless `python:3.11-slim` without `ptyprocess` reports the same missing-PTY+error it always did. Verified live on Windows (host survives its client's+process exit, adopt replays the screen); macOS and Linux run the same code+path through `ptyprocess` and are covered by the process-level test in+`tests/integration/terminal/test_pty_host_process.py`, not yet by a live run.+## iGentic project workspaces (T3)Project ownership, workspace snapshots, eight-session ordering and addresseddiff --git a/jarvis/agentic_ide/interrupted.py b/jarvis/agentic_ide/interrupted.pyindex 782e3c39c8..f46e81008f 100644--- a/jarvis/agentic_ide/interrupted.py+++ b/jarvis/agentic_ide/interrupted.py@@ -49,11 +49,18 @@ honest three-state answer about whether it was accepted. This module adds nosecond write path into a PTY; it decides WHICH panes to send to and reports whathappened. A caller can pass its own wording.-Deliberately not automatic. Sending "continue" to every resumed pane the moment-a workspace comes back would restart twelve agents on twelve unattended tasks-because somebody reopened a folder to look at one file, and an agent that was-interrupted for a reason ("stop, that is the wrong approach") would resume-exactly what it was told to stop doing. The offer is a button.+Never triggered by opening a workspace. Sending "continue" to every resumed pane+the moment a workspace comes back would restart twelve agents on twelve+unattended tasks because somebody reopened a folder to look at one file, and an+agent that was interrupted for a reason ("stop, that is the wrong approach")+would resume exactly what it was told to stop doing. Inside a running app the+offer is a button.++The one automatic caller is the app's startup after a REBOOT+(``Registry._continue_interrupted_after_reboot``): the agents' own process+died with the machine, the checkpoint saw them working, and the user asked for+exactly that recovery (RUB-102). An app that was merely closed never gets+there — its agents kept running in the PTY host and are re-joined, not nudged."""from __future__ import annotationsdiff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex f510bca199..6812285f26 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -189,6 +189,9 @@ class SnapshotWorkspace:# and the merge in `save` has to know which record is the newer one.saved_at: float = 0.0project_id: str = ""+ # The pane that had the focus, by name, so a reopened workspace lands on+ # it instead of on its first pane. Empty on older snapshots.+ focused: str = ""def to_dict(self) -> dict[str, Any]:return {@@ -198,6 +201,7 @@ class SnapshotWorkspace:"name": self.name,"saved_at": self.saved_at,"layout": self.layout,+ "focused": self.focused,"terminals": [t.to_dict() for t in self.terminals],}@@ -233,6 +237,7 @@ class SnapshotWorkspace:terminals=terminals,layout=raw_layout if isinstance(raw_layout, dict) else None,saved_at=saved_at,+ focused=str(data.get("focused") or "").strip(),)@@ -556,6 +561,7 @@ def _restamp(workspace: SnapshotWorkspace, when: float) -> SnapshotWorkspace:terminals=workspace.terminals,layout=workspace.layout,saved_at=when,+ focused=workspace.focused,)@@ -585,6 +591,32 @@ def load() -> Snapshot | None:return Snapshot.from_dict(data)+def _all_closed_path() -> Path:+ """Sibling of the store: when the last open workspace was closed by hand."""+ return _store_path().with_name(_store_path().stem + ".all_closed")+++def note_all_closed(when: float | None = None) -> None:+ """Record that the user closed every workspace (not that the app quit).++ Kept beside the snapshot rather than in it, so the snapshot keeps offering+ those workspaces for a deliberate reopen (``Registry._close_locked`` says+ why it must) while the app's startup restore can tell "closed for the day"+ from "the app was shut with work open".+ """+ path = _all_closed_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(repr(time.time() if when is None else when), encoding="utf-8")+++def all_closed_at() -> float | None:+ """When every workspace was last closed by hand, or None."""+ try:+ return float(_all_closed_path().read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return None++def clear() -> bool:"""Withdraw the offer. True when something was actually removed."""path = _store_path()diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 5b3fca3d38..3cce25cb8b 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -73,7 +73,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Sequencefrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, castfrom uuid import uuid4from loguru import logger@@ -1442,6 +1442,10 @@ class Session:# next dropped file or instruction belongs.surface_on_screen: bool = Falsesurface_prompt_target: str = ""+ # The pane last selected on screen, kept when the section goes off screen+ # (unlike ``surface_prompt_target``) and saved with the workspace, so a+ # reopened app puts the focus back where it was (RUB-102).+ focused: str = ""# When this workspace was last brought to the front. Orders the "most# recently used" answer the resume snapshot and the UI both want, which is# NOT the order the workspaces were opened in.@@ -1519,6 +1523,7 @@ class Session:"project": self.profile.to_dict(),"created_at": self.created_at,"focus_mode": self.focus_mode,+ "focused": self.focused,# The split tree the grid draws from. The per-terminal column/slot# fields riding along below are coarse hints for consumers that# only talk ABOUT the layout; a client that renders it needs this.@@ -1693,6 +1698,18 @@ def _announce_geometry(term: Terminal, cols: int, rows: int, *, except_viewer: A_tell_geometry(watched, cols, rows)+async def _connect_pty_host(*, start: bool) -> Any:+ """Attach to (or start) the PTY host; ``None`` keeps terminals in-process.++ A module function rather than an inline import so tests can replace it, and+ so the terminal stack stays off the import path until a pane needs it+ (AP-26).+ """+ from jarvis.terminal.pty_host_client import connect++ return await connect(start=start)++def _viewers(term: Terminal) -> list[Any]:"""Every output callback this pane should write to, newest last.@@ -1812,6 +1829,16 @@ class Registry:# references to tasks; without this set a hold could be collected# mid-wait and its slot never given back.self._cold_start_holds: set[asyncio.Task[None]] = set()+ # Whether panes may live in the PTY host (``jarvis.terminal.pty_host``)+ # 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+ # 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+ self._host_lock = asyncio.Lock()+ self._boot_restored = False# ---------------------------------------------------------------- state@property@@ -1969,6 +1996,247 @@ class Registry:self._pty = PtyManager()return self._pty+ # ---------------------------------------------------------- PTY host+ async def _live_manager(self) -> PtyManager:+ """The pool a NEW agent should start in — the PTY host when possible.++ Panes live in the host so that closing, quitting or restarting the app+ detaches from them instead of killing them (see+ ``jarvis.terminal.pty_host``). Everything degrades to the in-process+ pool: host disabled (tests, CLI), host unavailable on this install, or+ an in-process pool that already holds running agents — those would be+ orphaned by a switch, so the switch waits for the next app start.+ """+ if not self._host_enabled:+ return self._manager()+ async with self._host_lock:+ current = self._pty+ if current is not None and (+ # An in-process pool stays for the rest of this process once it+ # exists: it may hold running agents, and a host that failed to+ # start once is not worth a stall on every pane that connects.+ not getattr(current, "persistent", False) or getattr(current, "connected", False)+ ):+ return current+ # No pool yet, or the host went away (its agents went with it —+ # ``RemotePtyManager._lost`` already told their panes).+ remote = await _connect_pty_host(start=True)+ if remote is None:+ return self._fallback_manager()+ self._pty = cast("PtyManager", remote)+ return self._pty++ 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()++ async def boot_restore(self) -> None:+ """Bring back what was open when the app last ran — once per process.++ Called by the web server shortly after boot, off the critical path+ (AP-26). Three steps:++ 1. Attach to the PTY host if one is still running from before. Its+ terminals are agents that never stopped: the app was closed, the+ machine was not.+ 2. Reopen the workspaces that were open at the last save, in their+ layout. Each pane whose agent is still running in the host is+ re-joined to it (``_adopt_hosted``); the rest come back pending and+ continue their conversation through ``--resume`` when they connect,+ which is what a reboot leaves behind.+ 3. End hosted terminals no reopened pane claimed. Nothing can reach+ them any more, and left alone they would keep the host alive forever.++ Deliberately closing every workspace before quitting is respected:+ ``resume_store.all_closed_at`` records it, and a snapshot older than+ that is not reopened unasked.+ """+ if self._boot_restored:+ return+ self._boot_restored = True+ self._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)+ try:+ snapshot = await asyncio.to_thread(resume_store.load)+ closed_at = await asyncio.to_thread(resume_store.all_closed_at)+ except Exception as exc: # noqa: BLE001 - a broken file must not break boot+ logger.warning("Agentic IDE: restore point unreadable at startup: {}", exc)+ snapshot, closed_at = None, None+ newest = max((w.saved_at for w in snapshot.workspaces), default=0.0) if snapshot else 0.0+ if snapshot is not None and snapshot.workspaces and not self._sessions:+ if closed_at is not None and closed_at >= newest:+ logger.info(+ "Agentic IDE: every workspace was closed before the app quit — "+ "nothing reopened at startup"+ )+ else:+ try:+ await self.restore(snapshot)+ except SessionError as exc:+ logger.info("Agentic IDE: nothing reopened at startup: {}", exc)+ manager = self._pty+ hosted = manager.hosted() if manager is not None and hasattr(manager, "hosted") else []+ for info in hosted:+ logger.info(+ "Agentic IDE: ending hosted terminal {} — no reopened pane claims it ({})",+ info.terminal_id,+ info.meta.get("name", "unnamed"),+ )+ manager.kill_hosted(info.terminal_id) # type: ignore[union-attr]+ await self._continue_interrupted_after_reboot()++ async def _continue_interrupted_after_reboot(self) -> None:+ """Carry on with the work a reboot interrupted, in every workspace.++ Only panes whose agent did NOT survive (nothing in the PTY host claimed+ them — the machine restarted, or the host died) and whose last+ checkpoint saw them actively working. ``interrupted.continue_panes``+ applies the rest of the gate: a pane showing a question or waiting for+ an approval is never typed into, and a pane that finished or was+ stopped carries no ``continuation_pending`` in the first place.++ Their agents are started here without a viewer, so continuing does not+ depend on somebody opening each workspace; the ``continue`` is held+ until each CLI's input line is writable (``defer_continue``).+ """+ from . import interrupted++ try:+ report = await interrupted.continue_panes(self)+ except Exception as exc: # noqa: BLE001 - startup must not fail on this+ logger.warning("Agentic IDE: interrupted work not continued at startup: {}", exc)+ return+ starts = [+ (session, term)+ for session in self._sessions.values()+ for term in session.terminals+ if term.status == "pending" and term.continue_when_ready+ ]+ for session, term in starts:+ task = asyncio.create_task(+ self._start_unviewed(session, term), name=f"ide-continue-{term.key}"+ )+ self._cold_start_holds.add(task)+ task.add_done_callback(self._cold_start_holds.discard)+ if starts or report.continued:+ logger.info(+ "Agentic IDE: continuing {} interrupted pane(s) after a restart ({} started "+ "without a viewer)",+ len(starts) + len(report.continued),+ len(starts),+ )++ async def _start_unviewed(self, session: Session, term: Terminal) -> None:+ """Start a pane's agent with nobody watching (the registry records output)."""++ async def discard(_value: Any) -> None:+ return None++ identity = "pane:" + term.history_id+ try:+ await self.attach(+ identity,+ term.pty_cols or term.transcript.cols,+ term.pty_rows or term.transcript.rows,+ discard,+ discard,+ workspace_id=session.id,+ claim_owner=False,+ )+ except SessionError as exc:+ logger.warning("Agentic IDE: {} could not be started to continue: {}", term.name, exc)+ finally:+ self.detach(identity, workspace_id=session.id, viewer=discard)++ async def _adopt_hosted(self, session: Session) -> None:+ """Re-join each pane of ``session`` to its agent, if it is still running.++ A pane is recognised by its ``history_id`` — the stable identity that+ survives renames and the call-sign deduplication — which the spawn+ stored in the hosted terminal's ``meta``. A pane that finds its agent+ becomes ``live`` on the spot, with the host's copy of its screen in the+ 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+ 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+ 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+ # 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+ logger.info(+ "Agentic IDE: {} re-joined its running agent after an app restart", term.name+ )++ def _adopted_callbacks(self, term: Terminal) -> tuple[Any, Any]:+ """Output/exit callbacks for an agent this process did not start.++ The same fan-out as the ones ``_attach_locked`` builds at spawn, minus+ the failed-resume recovery: an adopted agent was not just resumed, it+ has been running all along.+ """++ async def _output(_tid: str, text: str) -> None:+ term.transcript.feed(text)+ term.replay.feed(text)+ term.last_output_at = time.time()+ for viewer in _viewers(term):+ await viewer(text)++ async def _closed(_tid: str, code: int) -> None:+ term.pty_id = None+ term.status = "exited"+ term.exit_code = code+ for viewer in _exit_viewers(term):+ await viewer(code)++ return _output, _closed+# -------------------------------------------------------------- sessionasync def start(self,@@ -2503,6 +2771,8 @@ class Registry:# Which record this came back from, so a second restore of the same file# recognises it rather than opening a duplicate.session.restored_from = _restore_key(space)+ focused = session.find(space.focused) if space.focused else None+ session.focused = focused.name if focused is not None else ""# The remembered split tree, when the snapshot carries one and it# parses. `_open_locked` already built the coarse columns-of-stacks# equivalent from the legacy (column, slot) pairs, so a snapshot from@@ -2526,6 +2796,9 @@ class Registry:# close and its renumbering (or a remembered tree can disagree with the# panes that really came back), and `_renumber` settles both.self._renumber(session)+ # Panes whose agents never stopped (the app was closed, the PTY host+ # kept them) are re-joined now rather than resumed on connect.+ await self._adopt_hosted(session)return session@staticmethod@@ -2647,6 +2920,43 @@ class Registry:await self._close_locked(workspace_id)return count+ def runtime_status(self) -> dict[str, Any]:+ """Where the agents run right now, for the UI and ``jarvis api``.++ ``host`` — in the PTY host, surviving the app; ``in_process`` — in this+ process, ending with it; ``idle`` — no agent has been started yet.+ """+ manager = self._pty+ hosted = bool(getattr(manager, "persistent", False)) and bool(+ getattr(manager, "connected", False)+ )+ mode = "host" if hosted else ("in_process" if manager is not None else "idle")+ return {+ "mode": mode,+ "host_pid": int(getattr(manager, "host_pid", 0) or 0) if hosted else 0,+ "persistent_enabled": self._host_enabled,+ "workspaces": len(self._sessions),+ "live_agents": sum(+ 1+ for session in self._sessions.values()+ for term in session.terminals+ if term.status == "live" and term.pty_id+ ),+ }++ async def stop_runtime(self) -> int:+ """The explicit "stop everything": end every agent in every workspace.++ Closing the app only detaches from the agents (``jarvis.terminal.pty_host``);+ this is the separate, deliberate action that ends them. It closes each+ workspace the ordinary way — so the restore point stays on offer and+ the next start does not reopen anything unasked — and the PTY host,+ left with no terminal, exits on its own shortly after.+ """+ count = await self.close_all()+ logger.info("Agentic IDE: runtime stopped by request — {} workspace(s) closed", count)+ return count+# ------------------------------------------------------------- snapshotdef snapshot(self) -> resume_store.Snapshot | None:"""EVERY open workspace, in the form the resume store keeps it.@@ -2678,6 +2988,7 @@ class Registry:name=session.name,terminals=[t.to_snapshot() for t in session.terminals],layout=layout_tree.to_dict(session.layout) if session.layout else None,+ focused=session.focused,)for session in self._sessions.values()],@@ -2803,6 +3114,14 @@ class Registry:# third of it back tomorrow". The cost of the other direction is a# workspace that lingers in the offer until something else happens, and# reopening one workspace too many is trivially undone.+ if not self._sessions:+ # The restore point stays on offer, but the app must not reopen it+ # by itself at the next start: the user shut everything down on+ # purpose (see ``boot_restore``).+ try:+ await asyncio.to_thread(resume_store.note_all_closed)+ except Exception as exc: # noqa: BLE001 - closing must always succeed+ logger.warning("Agentic IDE: could not record that everything closed: {}", exc)logger.info("Agentic IDE session ended: {}", session.id)def set_focus_mode(self, enabled: bool) -> bool:@@ -2852,8 +3171,16 @@ class Registry:session.surface_prompt_target = (prompt.name if prompt is not None and accepts_prompts(prompt.agent) else "")+ if prompt is not None and prompt.name != session.focused:+ session.focused = prompt.name+ self._focus_dirty = Truereturn True+ def take_focus_dirty(self) -> bool:+ """Did a focus change arrive since the last call? (Then it wants saving.)"""+ dirty, self._focus_dirty = self._focus_dirty, False+ return dirty+# ------------------------------------------------------------------ ptydef _locate(self, key: str, workspace_id: str | None) -> tuple[Session, Terminal] | None:"""One pane and the workspace holding it, by call-sign.@@ -3141,10 +3468,14 @@ class Registry:# transcript's default is exactly the right answer.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 appearance in THEME_COLOURS:term.queries.appearance = appearance+ if term.pty_id and hasattr(manager, "set_appearance"):+ # A hosted agent's emulator queries are answered in the host,+ # from its own copy of the appearance (``pty_host_client.spawn``).+ manager.set_appearance(term.pty_id, appearance)- manager = self._manager()if term.pty_id and manager.has(term.pty_id):# The agent never stopped. A foreground viewer takes over the owner# slot; a background viewer only joins the output fanout. A viewer@@ -3468,6 +3799,21 @@ class Registry:# and landed in the CLI's prompt as junk the user never# typed. Off the loop it is immediate.on_probe=term.queries.feed,+ # Only the PTY host takes (and needs) this: it is how a+ # still-running agent is matched back to its pane after+ # an app restart (``_adopt_hosted``).+ **(+ {+ "meta": {+ "history_id": term.history_id,+ "name": term.name,+ "workspace_id": session.id,+ "agent": term.agent,+ }+ }+ if getattr(manager, "persistent", False)+ else {}+ ),)if term.stopping or self._locate(identity, session.id) != (session, term):manager.close(pty_session.terminal_id)@@ -5593,6 +5939,29 @@ def get_registry() -> Registry:return _REGISTRY+def schedule_boot_restore() -> asyncio.Task[None] | None:+ """Run :meth:`Registry.boot_restore` in the background, once.++ Called by the two real app entry points (the desktop shell and the web+ launcher) right after the server is up — never by ``WebServer.start``,+ which tests boot against the real user data directory and must not attach+ to the user's PTY host or reopen their workspaces.+ """+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ logger.debug("Agentic IDE: startup restore not scheduled — no running loop")+ return None++ async def _run() -> None:+ try:+ await get_registry().boot_restore()+ except Exception as exc: # noqa: BLE001 - startup must not fail on this+ logger.opt(exception=exc).warning("Agentic IDE: startup restore failed")++ return loop.create_task(_run(), name="agentic-ide-boot-restore")++def reset_registry() -> None:"""Drop the registry — tests only."""global _REGISTRYdiff --git a/jarvis/terminal/pty_host.py b/jarvis/terminal/pty_host.pynew file mode 100644index 0000000000..6c51113987--- /dev/null+++ b/jarvis/terminal/pty_host.py@@ -0,0 +1,510 @@+"""The PTY host — a small process that owns the Agentic IDE's terminals.++Run as ``python -m jarvis.terminal.pty_host --state <file>``. Started on demand+by :mod:`jarvis.terminal.pty_host_client`, never by hand.++## Why the terminals live in their own process++A coding agent in a pane used to be a child of the desktop app. Everything+that ended the app ended the agents with it: closing the last window, "Quit"+in the tray, an update, a restart to pick up a fix. Each of those threw away+work in progress — the pane came back through ``--resume`` at best, as a+fresh CLI that re-reads its conversation and has forgotten what it was in the+middle of.++The shape that avoids this is the one tmux has: a long-lived server owns the+terminals, and the UI is only a client that attaches to them. Closing the+client detaches; opening it again re-attaches to the SAME processes, with the+screen they drew meanwhile. Only a reboot (or closing the pane deliberately)+ends an agent.++This module is that server, and deliberately nothing more:++* it spawns PTYs through the ordinary :class:`~jarvis.terminal.pty_manager.PtyManager`+ (so the output pump, the kill-on-close process tree and the exit-code+ normalisation are the exact code the app already runs),+* it keeps each terminal's raw output tail in a+ :class:`~jarvis.agentic_ide.transcript.ReplayBuffer`, so a client that+ attaches later can rebuild the screen,+* it answers the terminal's emulator queries itself+ (:class:`~jarvis.agentic_ide.terminal_input.TerminalQueryResponder`) —+ those replies are worthless once late, and a round trip through the app+ would make them late (see ``pty_manager``'s module docstring).++Everything that is policy — which agent runs where, resume handles, layout —+stays in the app. The host does not know what a workspace is; it knows+terminal ids and an opaque ``meta`` dict the client attached at spawn.++## Lifetime++The kill-on-close containers (a Job Object on Windows, the process group on+POSIX) belong to THIS process, so the agents live exactly as long as the host+does. The host itself therefore has to outlive the app — it is spawned+detached (``jarvis.ui.relauncher.spawn_detached``) — and it has to go away+on its own when nobody needs it, or every app start would leave one behind:+with no terminal alive and no client connected for :data:`IDLE_EXIT_S`, it+exits.++## Wire protocol++Newline-delimited JSON over one loopback TCP connection, authenticated by a+random token the client generated and handed over in the environment. One+client at a time — a new, authenticated client replaces the old one, which is+exactly what an app restart looks like from here.++Requests carry ``rid`` and are answered with ``{"rid", "ok", ...}``. Events+the host sends unprompted carry ``ev``: ``o`` (output) and ``exit``. Output is+only streamed for terminals this client spawned or adopted; everything else+keeps filling its replay buffer until somebody adopts it.+"""++from __future__ import annotations++import argparse+import asyncio+import hmac+import json+import os+import sys+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from loguru import logger++#: Bumped only for an incompatible change. A client refuses a host speaking+#: another version rather than guessing — and must then leave it alone, since+#: that host may be holding agents from before an update.+PROTOCOL_VERSION = 1++#: Environment variable carrying the auth token from the client that started+#: this host. Never on the command line: a process list is readable by every+#: process of the user.+TOKEN_ENV = "JARVIS_PTY_HOST_TOKEN" # noqa: S105 - a variable name, not a secret++#: With no terminal alive and no client attached for this long, the host exits.+#: Short enough that a closed app does not leave a process behind for long,+#: long enough to survive the gap between an app quitting and starting again.+IDLE_EXIT_S = 60.0++#: How often the idle check runs.+_IDLE_POLL_S = 5.0++#: Largest single frame a client may send. A pasted prompt is the biggest+#: thing that legitimately crosses; this is far above it and far below+#: anything that could hurt.+MAX_FRAME_BYTES = 16 * 1024 * 1024+++@dataclass(slots=True)+class HostedTerminal:+ """One terminal the host owns."""++ terminal_id: str+ pid: int+ meta: dict[str, Any]+ cols: int+ rows: int+ started_at: float+ replay: Any # jarvis.agentic_ide.transcript.ReplayBuffer (imported lazily)+ queries: Any # jarvis.agentic_ide.terminal_input.TerminalQueryResponder+ #: True once the connected client asked for this terminal's live output.+ streaming: bool = False+ exit_code: int | None = None+++@dataclass+class _Client:+ reader: asyncio.StreamReader+ writer: asyncio.StreamWriter+ send_lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ closed: bool = False++ async def send(self, frame: dict[str, Any]) -> None:+ if self.closed:+ return+ data = (json.dumps(frame, ensure_ascii=False) + "\n").encode("utf-8")+ async with self.send_lock:+ if self.closed:+ return+ try:+ self.writer.write(data)+ await self.writer.drain()+ except (ConnectionError, OSError, RuntimeError) as exc:+ # The client went away mid-send. Its terminals keep running and+ # keep filling their replay buffers; the next client adopts them.+ logger.info("PTY host: client connection lost while sending: {}", exc)+ self.closed = True++ def close(self) -> None:+ self.closed = True+ try:+ self.writer.close()+ except Exception as exc: # noqa: BLE001 - already closed is the goal+ logger.debug("PTY host: closing a client socket failed: {}", exc)+++class PtyHost:+ """The server: a :class:`PtyManager` plus replay buffers plus one client."""++ def __init__(self, token: str, *, idle_exit_s: float = IDLE_EXIT_S) -> None:+ from jarvis.terminal.pty_manager import PtyManager++ self._token = token+ self._manager = PtyManager()+ self._terminals: dict[str, HostedTerminal] = {}+ #: Exit codes of terminals that ended while nobody was attached, so an+ #: adopting client learns how they ended instead of "unknown id".+ self._ended: dict[str, int] = {}+ self._client: _Client | None = None+ self._idle_exit_s = idle_exit_s+ self._idle_since: float | None = time.monotonic()+ self._stop = asyncio.Event()++ # ------------------------------------------------------------ lifecycle+ async def serve(self, state_path: Path) -> None:+ """Listen on a loopback port, publish it, and run until idle."""+ server = await asyncio.start_server(+ self._on_connect, host="127.0.0.1", port=0, limit=MAX_FRAME_BYTES+ )+ port = int(server.sockets[0].getsockname()[1])+ _write_state(+ state_path,+ {+ "pid": os.getpid(),+ "port": port,+ "token": self._token,+ "proto": PROTOCOL_VERSION,+ "started_at": time.time(),+ },+ )+ logger.info("PTY host listening on 127.0.0.1:{} (pid {})", port, os.getpid())+ idle = asyncio.create_task(self._idle_watch(), name="pty-host-idle")+ try:+ async with server:+ await self._stop.wait()+ finally:+ idle.cancel()+ _remove_state(state_path, os.getpid())+ # Reached only when idle — no terminal left to protect. Closing+ # anyway keeps a forced stop from leaking a tree.+ self._manager.close_all()+ logger.info("PTY host stopped")++ async def _idle_watch(self) -> None:+ while not self._stop.is_set():+ await asyncio.sleep(_IDLE_POLL_S)+ busy = bool(self._terminals) or (self._client is not None and not self._client.closed)+ now = time.monotonic()+ if busy:+ self._idle_since = None+ continue+ if self._idle_since is None:+ self._idle_since = now+ elif now - self._idle_since >= self._idle_exit_s:+ logger.info("PTY host idle for {:.0f} s — exiting", now - self._idle_since)+ self._stop.set()++ # ----------------------------------------------------------- connection+ async def _on_connect(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ client = _Client(reader, writer)+ try:+ hello = await asyncio.wait_for(_read_frame(reader), timeout=10.0)+ except (TimeoutError, ValueError, ConnectionError, OSError) as exc:+ logger.info("PTY host: connection dropped before hello: {}", exc)+ client.close()+ return+ if (+ not isinstance(hello, dict)+ or hello.get("op") != "hello"+ or not hmac.compare_digest(str(hello.get("token", "")), self._token)+ ):+ logger.warning("PTY host: refused a connection with a bad hello")+ client.close()+ return+ if hello.get("proto") != PROTOCOL_VERSION:+ await client.send(+ {+ "rid": hello.get("rid"),+ "ok": False,+ "error": "protocol",+ "proto": PROTOCOL_VERSION,+ }+ )+ client.close()+ return++ previous = self._client+ if previous is not None and not previous.closed:+ logger.info("PTY host: a new client replaces the attached one")+ previous.close()+ # A new client starts with nothing streaming: it adopts what it wants.+ for term in self._terminals.values():+ term.streaming = False+ self._client = client+ await client.send(+ {+ "rid": hello.get("rid"),+ "ok": True,+ "pid": os.getpid(),+ "proto": PROTOCOL_VERSION,+ "terminals": self._listing(),+ }+ )+ try:+ while not client.closed:+ try:+ frame = await _read_frame(reader)+ except (ValueError, ConnectionError, OSError) as exc:+ logger.info("PTY host: client disconnected: {}", exc)+ break+ if frame is None:+ break+ await self._handle(client, frame)+ finally:+ client.close()+ if self._client is client:+ self._client = None+ for term in self._terminals.values():+ term.streaming = False+ logger.info(+ "PTY host: client detached — {} terminal(s) keep running",+ len(self._terminals),+ )++ async def _handle(self, client: _Client, frame: dict[str, Any]) -> None:+ op = frame.get("op")+ rid = frame.get("rid")+ try:+ if op == "spawn":+ reply = await self._spawn(frame)+ elif op == "adopt":+ reply = self._adopt(str(frame.get("id", "")))+ elif op == "write":+ self._manager.write(str(frame.get("id", "")), str(frame.get("d", "")))+ return+ elif op == "resize":+ self._resize(frame)+ return+ elif op == "appearance":+ term = self._terminals.get(str(frame.get("id", "")))+ if term is not None:+ term.queries.appearance = str(frame.get("appearance", ""))+ return+ elif op == "close":+ self._close(str(frame.get("id", "")))+ return+ elif op == "list":+ reply = {"terminals": self._listing()}+ elif op == "ping":+ reply = {}+ else:+ reply = {"ok": False, "error": f"unknown op {op!r}"}+ except Exception as exc: # noqa: BLE001 - one bad request must not end the host+ logger.warning("PTY host: {} failed: {}", op, exc)+ reply = {"ok": False, "error": str(exc)}+ if rid is not None:+ reply.setdefault("ok", True)+ reply["rid"] = rid+ await client.send(reply)++ # ------------------------------------------------------------ requests+ async def _spawn(self, frame: dict[str, Any]) -> dict[str, Any]:+ from jarvis.agentic_ide.terminal_input import TerminalQueryResponder+ from jarvis.agentic_ide.transcript import ReplayBuffer++ argv = tuple(str(part) for part in frame.get("argv") or ())+ if not argv:+ return {"ok": False, "error": "empty argv"}+ cols = int(frame.get("cols") or 120)+ rows = int(frame.get("rows") or 30)+ env = frame.get("env")+ queries = TerminalQueryResponder()+ appearance = frame.get("appearance")+ if isinstance(appearance, str) and appearance:+ queries.appearance = appearance+ replay = ReplayBuffer()+ # The id is not known until spawn returns, and output can arrive before+ # that — so the callbacks look the terminal up by the id they are given.+ pending: list[tuple[str, str]] = []++ async def _output(tid: str, text: str) -> None:+ term = self._terminals.get(tid)+ if term is None:+ pending.append((tid, text))+ return+ await self._deliver(term, text)++ async def _closed(tid: str, code: int) -> None:+ await self._on_exit(tid, code)++ session = await self._manager.spawn(+ shell_argv=argv,+ shell_id=str(frame.get("shell_id") or "pty-host"),+ cwd=frame.get("cwd") or None,+ cols=cols,+ rows=rows,+ on_output=_output,+ on_closed=_closed,+ env=dict(env) if isinstance(env, dict) else None,+ on_probe=queries.feed,+ )+ term = HostedTerminal(+ terminal_id=session.terminal_id,+ pid=session.pid,+ meta=dict(frame.get("meta") or {}),+ cols=cols,+ rows=rows,+ started_at=time.time(),+ replay=replay,+ queries=queries,+ # The spawning client is the viewer from the first byte.+ streaming=True,+ )+ self._terminals[term.terminal_id] = term+ for _tid, text in pending:+ await self._deliver(term, text)+ pending.clear()+ return {"id": term.terminal_id, "pid": term.pid}++ def _adopt(self, terminal_id: str) -> dict[str, Any]:+ term = self._terminals.get(terminal_id)+ if term is None:+ code = self._ended.pop(terminal_id, None)+ return {"alive": False, "code": code}+ # Replay and "stream from now on" in ONE step on the loop: no output can+ # land between the two, so the client sees every byte exactly once.+ term.streaming = True+ return {+ "alive": True,+ "replay": term.replay.text(),+ "truncated": bool(term.replay.truncated),+ "cols": term.cols,+ "rows": term.rows,+ }++ def _resize(self, frame: dict[str, Any]) -> None:+ terminal_id = str(frame.get("id", ""))+ cols = int(frame.get("cols") or 0)+ rows = int(frame.get("rows") or 0)+ if cols <= 0 or rows <= 0:+ return+ if self._manager.resize(terminal_id, cols, rows):+ term = self._terminals.get(terminal_id)+ if term is not None:+ term.cols, term.rows = cols, rows++ def _close(self, terminal_id: str) -> None:+ # The pump reports the exit afterwards through ``_on_exit``.+ self._manager.close(terminal_id)++ def _listing(self) -> list[dict[str, Any]]:+ return [+ {+ "id": term.terminal_id,+ "pid": term.pid,+ "meta": term.meta,+ "cols": term.cols,+ "rows": term.rows,+ "started_at": term.started_at,+ }+ for term in self._terminals.values()+ ]++ # --------------------------------------------------------------- events+ async def _deliver(self, term: HostedTerminal, text: str) -> None:+ term.replay.feed(text)+ client = self._client+ if client is not None and term.streaming:+ await client.send({"ev": "o", "id": term.terminal_id, "d": text})++ async def _on_exit(self, terminal_id: str, code: int) -> None:+ term = self._terminals.pop(terminal_id, None)+ streaming = term is not None and term.streaming+ client = self._client+ if client is not None and not client.closed and streaming:+ await client.send({"ev": "exit", "id": terminal_id, "code": code})+ else:+ # Nobody saw it end; keep the answer for whoever adopts it next.+ self._ended[terminal_id] = code+ while len(self._ended) > 256:+ self._ended.pop(next(iter(self._ended)))+ logger.info("PTY host: terminal {} ended (exit {})", terminal_id, code)+++# ---------------------------------------------------------------- framing+async def _read_frame(reader: asyncio.StreamReader) -> dict[str, Any] | None:+ """One JSON line, or None at a clean end of stream."""+ line = await reader.readline()+ if not line:+ return None+ frame = json.loads(line.decode("utf-8"))+ if not isinstance(frame, dict):+ raise ValueError("frame is not an object")+ return frame+++def _write_state(path: Path, data: dict[str, Any]) -> None:+ """Publish where the host listens — atomically, readable only by the user."""+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(path.name + f".{os.getpid()}.tmp")+ tmp.write_text(json.dumps(data), encoding="utf-8")+ try:+ os.chmod(tmp, 0o600)+ except OSError as exc:+ # Windows keeps per-user ACLs on the data dir; chmod is a POSIX nicety.+ logger.debug("PTY host: could not restrict the state file: {}", exc)+ os.replace(tmp, path)+++def _remove_state(path: Path, pid: int) -> None:+ """Remove the state file — only if it still describes THIS host."""+ try:+ current = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return+ if isinstance(current, dict) and current.get("pid") == pid:+ try:+ path.unlink()+ except OSError as exc:+ logger.debug("PTY host: state file not removed: {}", exc)+++def _configure_logging(log_path: Path | None) -> None:+ logger.remove()+ if log_path is None:+ return+ log_path.parent.mkdir(parents=True, exist_ok=True)+ logger.add(+ str(log_path),+ level="INFO",+ rotation="2 MB",+ retention=2,+ encoding="utf-8",+ enqueue=False,+ )+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="jarvis.terminal.pty_host")+ parser.add_argument("--state", required=True, help="Where to publish the port and token.")+ parser.add_argument("--log", default=None, help="Log file (none when omitted).")+ parser.add_argument("--idle-exit", type=float, default=IDLE_EXIT_S)+ args = parser.parse_args(argv)++ token = os.environ.pop(TOKEN_ENV, "")+ if not token:+ print("PTY host: no token in the environment — refusing to start.", file=sys.stderr)+ return 2+ _configure_logging(Path(args.log) if args.log else None)+ host = PtyHost(token, idle_exit_s=args.idle_exit)+ try:+ asyncio.run(host.serve(Path(args.state)))+ except KeyboardInterrupt:+ return 0+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/terminal/pty_host_client.py b/jarvis/terminal/pty_host_client.pynew file mode 100644index 0000000000..4355273350--- /dev/null+++ b/jarvis/terminal/pty_host_client.py@@ -0,0 +1,609 @@+"""The app's side of the PTY host — a drop-in for :class:`PtyManager`.++:mod:`jarvis.terminal.pty_host` explains why the Agentic IDE's terminals live+in a process of their own. This module is how the app talks to it:+:class:`RemotePtyManager` answers the same calls ``PtyManager`` does (``spawn``,+``write``, ``resize``, ``close``, ``has``), so the registry that drives the+panes does not care which of the two it holds — plus the two things only a+remote pool can do: list the terminals that were already running when the app+started (:meth:`RemotePtyManager.hosted`) and take one of them over+(:meth:`RemotePtyManager.adopt`).++**Quitting the app detaches, it does not kill.** ``close_all`` on this class+only lets go of the connection; the terminals keep running in the host and the+next app start adopts them. Ending an agent is ``close(id)`` — what closing a+pane or a workspace does.++Output is coalesced exactly the way ``PtyManager`` coalesces it (one pump per+terminal, everything that arrived while a send was in flight leaves as one+chunk), for the same reason: a busy pane must cost frame COUNT, never queue+depth. The difference is only where the bytes come from — a socket instead of+a reader thread.++:func:`connect` finds the running host or starts one. It never raises: a host+that cannot be reached or started returns ``None``, and the caller keeps the+in-process ``PtyManager`` — terminals that die with the app are worse than+terminals that survive it, and far better than no terminals.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import os+import secrets+import sys+import threading+import time+from collections import deque+from collections.abc import Awaitable, Callable, Mapping+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from loguru import logger++from .pty_host import MAX_FRAME_BYTES, PROTOCOL_VERSION, TOKEN_ENV+from .pty_manager import MAX_PENDING_CHARS, UNKNOWN_EXIT_CODE++OutputCallback = Callable[[str, str], Awaitable[None]]+ClosedCallback = Callable[[str, int], Awaitable[None]]++#: How long a request may wait for the host's answer. A spawn is the slowest+#: one (the host starts a process and a console), and it is still well under.+REQUEST_TIMEOUT_S = 30.0++#: How long a freshly started host gets to publish its port.+START_TIMEOUT_S = 15.0+++@dataclass(slots=True)+class HostedInfo:+ """A terminal the host was already running when this client connected."""++ terminal_id: str+ pid: int+ meta: dict[str, Any]+ cols: int+ rows: int+ started_at: float+++@dataclass(slots=True)+class AdoptResult:+ """What adopting a hosted terminal handed back."""++ alive: bool+ replay: str = ""+ truncated: bool = False+ cols: int = 0+ rows: int = 0+ exit_code: int | None = None+++@dataclass(slots=True)+class RemoteSession:+ """The client-side half of one hosted terminal: a pump, like ``PtySession``."""++ terminal_id: str+ pid: int+ on_output: OutputCallback+ on_closed: ClosedCallback+ _pending: deque[str] = field(default_factory=deque, init=False)+ _pending_chars: int = field(default=0, init=False)+ _wake: asyncio.Event = field(default_factory=asyncio.Event, init=False)+ _finished: bool = field(default=False, init=False)+ _exit_code: int | None = field(default=None, init=False)+ _pump: asyncio.Task[None] | None = field(default=None, init=False)++ def offer(self, text: str) -> None:+ if not text or self._finished:+ return+ self._pending.append(text)+ self._pending_chars += len(text)+ # Oldest first, for the reason PtyManager gives: a TUI's newest bytes+ # ARE its screen.+ while self._pending_chars > MAX_PENDING_CHARS and len(self._pending) > 1:+ self._pending_chars -= len(self._pending.popleft())+ self._wake.set()++ def finish(self, code: int) -> None:+ if self._finished:+ return+ self._finished = True+ self._exit_code = code+ self._wake.set()++ def take(self) -> str:+ if not self._pending:+ return ""+ text = "".join(self._pending)+ self._pending.clear()+ self._pending_chars = 0+ return text++ async def run(self) -> None:+ while True:+ await self._wake.wait()+ self._wake.clear()+ while True:+ text = self.take()+ if not text:+ break+ try:+ await self.on_output(self.terminal_id, text)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - the terminal outlives its viewer+ logger.debug(+ "PTY host output callback failed: terminal={} error={}",+ self.terminal_id,+ exc,+ )+ if self._finished:+ break+ code = UNKNOWN_EXIT_CODE if self._exit_code is None else self._exit_code+ try:+ await self.on_closed(self.terminal_id, code)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - the viewer may be gone+ logger.debug(+ "PTY host close callback failed: terminal={} error={}", self.terminal_id, exc+ )+++class HostConnectionError(RuntimeError):+ """The host could not be reached, or dropped the connection."""+++class RemotePtyManager:+ """A ``PtyManager`` whose terminals live in the PTY host process."""++ #: Lets the registry tell the two pools apart without an isinstance check+ #: against a class it would otherwise have to import eagerly.+ persistent = True++ def __init__(+ self,+ reader: asyncio.StreamReader,+ writer: asyncio.StreamWriter,+ hosted: list[HostedInfo],+ host_pid: int,+ ) -> None:+ self._reader = reader+ self._writer = writer+ self._loop = asyncio.get_running_loop()+ self._loop_thread = threading.get_ident()+ self._sessions: dict[str, RemoteSession] = {}+ self._futures: dict[int, asyncio.Future[dict[str, Any]]] = {}+ self._next_rid = 1+ self._hosted = {info.terminal_id: info for info in hosted}+ self._closed = False+ self.host_pid = host_pid+ self._reader_task = self._loop.create_task(self._read_loop(), name="pty-host-client")++ # ---------------------------------------------------------- properties+ @property+ def connected(self) -> bool:+ return not self._closed++ def hosted(self) -> list[HostedInfo]:+ """Terminals that were running before this client attached, not yet adopted."""+ return list(self._hosted.values())++ # ----------------------------------------------------- PtyManager API+ async def spawn(+ self,+ shell_argv: tuple[str, ...],+ shell_id: str,+ cwd: str | None,+ cols: int,+ rows: int,+ on_output: OutputCallback,+ on_closed: ClosedCallback,+ env: Mapping[str, str] | None = None,+ on_probe: Callable[[str], str] | None = None,+ meta: Mapping[str, Any] | None = None,+ ) -> RemoteSession:+ """Start a terminal in the host. Same contract as ``PtyManager.spawn``.++ ``on_probe`` cannot cross a process boundary — the host answers the+ emulator queries itself, from the appearance handed over here (read+ off the responder ``on_probe`` is bound to, which is what the registry+ passes) and kept current by :meth:`set_appearance`.++ ``meta`` travels with the terminal and comes back from+ :meth:`hosted` after an app restart; it is how the registry recognises+ which pane a still-running terminal belongs to.+ """+ responder = getattr(on_probe, "__self__", None)+ appearance = getattr(responder, "appearance", None)+ reply = await self._request(+ {+ "op": "spawn",+ "argv": list(shell_argv),+ "shell_id": shell_id,+ "cwd": cwd,+ "cols": cols,+ "rows": rows,+ "env": dict(env) if env is not None else None,+ "appearance": appearance if isinstance(appearance, str) else None,+ "meta": dict(meta or {}),+ }+ )+ if not reply.get("ok"):+ raise RuntimeError(str(reply.get("error") or "The terminal host refused the spawn."))+ session = self._register(str(reply["id"]), int(reply.get("pid") or 0), on_output, on_closed)+ logger.info(+ "PTY spawned in host: shell={} terminal={} pid={} size={}x{}",+ shell_id,+ session.terminal_id,+ session.pid,+ cols,+ rows,+ )+ return session++ async def adopt(+ self, terminal_id: str, on_output: OutputCallback, on_closed: ClosedCallback+ ) -> AdoptResult:+ """Take over a terminal that was running before this client attached.++ The host hands back the tail of its output (the screen, for a+ viewer to rebuild) and streams everything after it — the two in one+ step on the host, so no byte is lost or doubled in between.+ """+ info = self._hosted.pop(terminal_id, None)+ reply = await self._request({"op": "adopt", "id": terminal_id})+ if not reply.get("ok") or not reply.get("alive"):+ code = reply.get("code")+ return AdoptResult(alive=False, exit_code=int(code) if code is not None else None)+ pid = info.pid if info is not None else 0+ self._register(terminal_id, pid, on_output, on_closed)+ return AdoptResult(+ alive=True,+ replay=str(reply.get("replay") or ""),+ truncated=bool(reply.get("truncated")),+ cols=int(reply.get("cols") or 0),+ rows=int(reply.get("rows") or 0),+ )++ def write(self, terminal_id: str, data: str) -> bool:+ if terminal_id not in self._sessions or self._closed:+ return False+ return self._send({"op": "write", "id": terminal_id, "d": data})++ def resize(self, terminal_id: str, cols: int, rows: int) -> bool:+ if terminal_id not in self._sessions or self._closed:+ return False+ return self._send({"op": "resize", "id": terminal_id, "cols": cols, "rows": rows})++ def set_appearance(self, terminal_id: str, appearance: str) -> None:+ """Keep the host's emulator-query answers on the viewer's light/dark ground."""+ if terminal_id in self._sessions:+ self._send({"op": "appearance", "id": terminal_id, "appearance": appearance})++ def swap_sessions(self, id_a: str, id_b: str) -> bool:+ """Not offered by the host; refused, leaving both routes untouched."""+ return id_a == id_b++ def close(self, terminal_id: str) -> bool:+ """End a terminal for good. Its exit still arrives through ``on_closed``."""+ known = terminal_id in self._sessions or terminal_id in self._hosted+ self._hosted.pop(terminal_id, None)+ if not known or self._closed:+ return False+ return self._send({"op": "close", "id": terminal_id})++ def kill_hosted(self, terminal_id: str) -> bool:+ """End a still-unadopted hosted terminal nobody is going to claim."""+ return self.close(terminal_id)++ def close_all(self) -> None:+ """Detach from the host. The terminals keep running (module docstring)."""+ self.detach()++ def has(self, terminal_id: str) -> bool:+ return terminal_id in self._sessions and not self._closed++ def detach(self) -> None:+ if self._closed:+ return+ self._closed = True+ with contextlib.suppress(Exception):+ self._writer.close()+ self._reader_task.cancel()+ logger.info(+ "PTY host: detached — {} terminal(s) keep running in the host", len(self._sessions)+ )++ # ------------------------------------------------------------ internals+ def _register(+ self, terminal_id: str, pid: int, on_output: OutputCallback, on_closed: ClosedCallback+ ) -> RemoteSession:+ session = RemoteSession(+ terminal_id=terminal_id, pid=pid, on_output=on_output, on_closed=on_closed+ )+ self._sessions[terminal_id] = session+ session._pump = self._loop.create_task(+ self._pump(session), name=f"pty-host-pump-{terminal_id[:8]}"+ )+ return session++ async def _pump(self, session: RemoteSession) -> None:+ try:+ await session.run()+ finally:+ if self._sessions.get(session.terminal_id) is session:+ del self._sessions[session.terminal_id]++ def _send(self, frame: dict[str, Any]) -> bool:+ """Queue one frame. Safe from any thread; never blocks."""+ if self._closed:+ return False+ data = (json.dumps(frame, ensure_ascii=False) + "\n").encode("utf-8")+ try:+ if threading.get_ident() == self._loop_thread:+ self._writer.write(data)+ else:+ self._loop.call_soon_threadsafe(self._writer.write, data)+ except (ConnectionError, OSError, RuntimeError) as exc:+ logger.warning("PTY host: send failed: {}", exc)+ self._lost(exc)+ return False+ return True++ async def _request(self, frame: dict[str, Any]) -> dict[str, Any]:+ if self._closed:+ raise HostConnectionError("The terminal host is not connected.")+ rid = self._next_rid+ self._next_rid += 1+ future: asyncio.Future[dict[str, Any]] = self._loop.create_future()+ self._futures[rid] = future+ frame = {**frame, "rid": rid}+ if not self._send(frame):+ self._futures.pop(rid, None)+ raise HostConnectionError("The terminal host is not connected.")+ try:+ await self._writer.drain()+ return await asyncio.wait_for(future, timeout=REQUEST_TIMEOUT_S)+ except TimeoutError as exc:+ raise HostConnectionError("The terminal host did not answer in time.") from exc+ finally:+ self._futures.pop(rid, None)++ async def _read_loop(self) -> None:+ error: BaseException | None = None+ try:+ while True:+ line = await self._reader.readline()+ if not line:+ break+ try:+ frame = json.loads(line.decode("utf-8"))+ except ValueError as exc:+ logger.warning("PTY host: unreadable frame dropped: {}", exc)+ continue+ if not isinstance(frame, dict):+ continue+ self._dispatch(frame)+ except asyncio.CancelledError:+ raise+ except (ConnectionError, OSError, ValueError) as exc:+ # ANY read error ends the loop (AP-20): a socket that failed once is+ # not going to produce a valid frame on the next read either.+ error = exc+ self._lost(error)++ def _dispatch(self, frame: dict[str, Any]) -> None:+ rid = frame.get("rid")+ if rid is not None:+ future = self._futures.get(int(rid))+ if future is not None and not future.done():+ future.set_result(frame)+ return+ event = frame.get("ev")+ session = self._sessions.get(str(frame.get("id", "")))+ if session is None:+ return+ if event == "o":+ session.offer(str(frame.get("d", "")))+ elif event == "exit":+ code = frame.get("code")+ session.finish(int(code) if code is not None else UNKNOWN_EXIT_CODE)++ def _lost(self, error: BaseException | None) -> None:+ """The host is gone: every terminal it held is gone with it."""+ was_open = not self._closed+ self._closed = True+ for future in self._futures.values():+ if not future.done():+ future.set_exception(HostConnectionError("The terminal host went away."))+ self._futures.clear()+ if was_open:+ logger.warning(+ "PTY host connection lost ({}) — {} terminal(s) reported as ended",+ error or "end of stream",+ len(self._sessions),+ )+ for session in list(self._sessions.values()):+ session.finish(UNKNOWN_EXIT_CODE)+ self._hosted.clear()+++# --------------------------------------------------------------- discovery+def _state_path() -> Path:+ from jarvis.core.instance import current_instance+ from jarvis.core.paths import user_data_dir++ suffix = current_instance().state_file_suffix+ return user_data_dir() / "agentic_ide" / f"pty_host{suffix}.json"+++def _log_path() -> Path:+ from jarvis.core.instance import current_instance+ from jarvis.core.paths import user_data_dir++ suffix = current_instance().state_file_suffix+ return user_data_dir() / "logs" / f"pty_host{suffix}.log"+++def _read_state(path: Path) -> dict[str, Any] | None:+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ return data if isinstance(data, dict) else None+++async def _handshake(+ port: int, token: str, wait_s: float+) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, dict[str, Any]] | None:+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_connection("127.0.0.1", port, limit=MAX_FRAME_BYTES), timeout=wait_s+ )+ except (OSError, TimeoutError) as exc:+ logger.debug("PTY host: no answer on port {}: {}", port, exc)+ return None+ try:+ hello = {"op": "hello", "token": token, "proto": PROTOCOL_VERSION, "rid": 0}+ writer.write((json.dumps(hello) + "\n").encode("utf-8"))+ await writer.drain()+ line = await asyncio.wait_for(reader.readline(), timeout=wait_s)+ reply = json.loads(line.decode("utf-8")) if line else None+ except (OSError, TimeoutError, ValueError) as exc:+ logger.info("PTY host: handshake on port {} failed: {}", port, exc)+ writer.close()+ return None+ if not isinstance(reply, dict) or not reply.get("ok"):+ logger.warning("PTY host: handshake refused on port {}: {}", port, reply)+ writer.close()+ return None+ return reader, writer, reply+++def _manager_from(+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter, reply: dict[str, Any]+) -> RemotePtyManager:+ hosted = [+ HostedInfo(+ terminal_id=str(item.get("id", "")),+ pid=int(item.get("pid") or 0),+ meta=dict(item.get("meta") or {}),+ cols=int(item.get("cols") or 0),+ rows=int(item.get("rows") or 0),+ started_at=float(item.get("started_at") or 0.0),+ )+ for item in reply.get("terminals") or ()+ if isinstance(item, dict) and item.get("id")+ ]+ return RemotePtyManager(reader, writer, hosted, int(reply.get("pid") or 0))+++def host_available() -> bool:+ """Can this install run a PTY host at all?++ A frozen build has no ``python -m`` to start one with, and a host without a+ PTY backend would only answer every spawn with the same error the in-process+ pool gives.+ """+ if getattr(sys, "frozen", False):+ return False+ from jarvis.platform.capabilities import detect_capabilities++ return bool(detect_capabilities().has_pty)+++def _start_host(state_path: Path, token: str) -> bool:+ import jarvis+ from jarvis.ui.relauncher import spawn_detached++ # The host must import THIS jarvis, whichever interpreter path found it.+ package_root = str(Path(jarvis.__file__).resolve().parent.parent)+ env = dict(os.environ)+ env[TOKEN_ENV] = token+ env["PYTHONPATH"] = os.pathsep.join(+ part for part in (package_root, env.get("PYTHONPATH", "")) if part+ )+ env["PYTHONIOENCODING"] = "utf-8"+ argv = [+ sys.executable,+ "-m",+ "jarvis.terminal.pty_host",+ "--state",+ str(state_path),+ "--log",+ str(_log_path()),+ ]+ try:+ spawn_detached(argv, cwd=package_root, env=env)+ except OSError as exc:+ logger.warning("PTY host could not be started: {}", exc)+ return False+ return True+++async def connect(*, start: bool = True) -> RemotePtyManager | None:+ """Attach to the running PTY host, starting one if none answers.++ Never raises; ``None`` means "keep terminals in this process" (module+ docstring).+ """+ if not host_available():+ return None+ state_path = _state_path()+ state = await asyncio.to_thread(_read_state, state_path)+ if state is not None and state.get("port") and state.get("token"):+ if state.get("proto") != PROTOCOL_VERSION:+ # A host from another build may be holding agents; never replace it+ # blindly. It exits on its own once they are gone.+ logger.warning(+ "PTY host speaks protocol {} (this build: {}) — terminals stay in-process",+ state.get("proto"),+ PROTOCOL_VERSION,+ )+ return None+ found = await _handshake(int(state["port"]), str(state["token"]), wait_s=3.0)+ if found is not None:+ manager = _manager_from(*found)+ logger.info(+ "PTY host attached (pid {}) — {} terminal(s) still running",+ manager.host_pid,+ len(manager.hosted()),+ )+ return manager+ if not start:+ return None++ token = secrets.token_urlsafe(32)+ if not await asyncio.to_thread(_start_host, state_path, token):+ return None+ deadline = time.monotonic() + START_TIMEOUT_S+ while time.monotonic() < deadline:+ await asyncio.sleep(0.1)+ state = await asyncio.to_thread(_read_state, state_path)+ if not state or state.get("token") != token or not state.get("port"):+ continue+ found = await _handshake(int(state["port"]), token, wait_s=3.0)+ if found is not None:+ manager = _manager_from(*found)+ logger.info("PTY host started (pid {})", manager.host_pid)+ return manager+ logger.warning(+ "PTY host did not come up within {:.0f} s — terminals stay in-process", START_TIMEOUT_S+ )+ return None+++__all__ = [+ "AdoptResult",+ "HostConnectionError",+ "HostedInfo",+ "RemotePtyManager",+ "RemoteSession",+ "connect",+ "host_available",+]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex f01565969b..40be485de3 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2880,6 +2880,11 @@ class DesktopApp:try:await server.start(start_serving=False)_db_mark("server_start")+ # Reattach to coding agents that kept running while the app+ # was closed, and reopen the workspaces in their layout.+ from jarvis.agentic_ide.session import schedule_boot_restore++ schedule_boot_restore()except Exception as exc: # noqa: BLE001 — never kill the backend loopfrom loguru import logger as _slogdiff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 718e8d5640..f961e93c53 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -1359,6 +1359,28 @@ def get_state() -> dict:return get_registry().state()[email protected]("/runtime", summary="Where the Agentic-IDE agents run")+def get_runtime() -> dict:+ """``host`` when the agents live in the PTY host and survive closing the app.++ ``in_process`` when they run inside the app and end with it (the host is+ unavailable on this install), ``idle`` before any agent was started.+ """+ return get_registry().runtime_status()++[email protected]("/runtime/stop", summary="Stop every Agentic-IDE agent and its runtime")+async def stop_runtime() -> dict:+ """End every agent in every open workspace.++ Closing the app never does this — it only detaches. The workspaces stay on+ offer for a deliberate reopen, and none of them is reopened automatically+ at the next start.+ """+ closed = await get_registry().stop_runtime()+ return {"ok": True, "closed_workspaces": closed}++@router.get("/panes", summary="Every coding session running in any open workspace")def get_panes() -> dict:"""One row per pane, across ALL open workspaces — not just the front one.@@ -2499,7 +2521,7 @@ async def set_mode(request: Request, req: ModeRequest) -> dict:@router.put("/surface-context", summary="Report the visible Agentic-IDE terminal")-def set_surface_context(req: SurfaceContextRequest) -> dict:+async def set_surface_context(req: SurfaceContextRequest) -> dict:"""Keep deictic voice/chat references aligned with the visible pane.The state is ephemeral and active-workspace scoped. Grid view clears it,@@ -2511,13 +2533,17 @@ def set_surface_context(req: SurfaceContextRequest) -> dict:view that promises the least — see `workspace_view.VIEW_DEFAULT`."""view = req.view if req.view is not None else view_from_legacy_chat_flag(req.chat_view)- accepted = get_registry().set_surface_context(+ registry = get_registry()+ accepted = registry.set_surface_context(workspace_id=req.workspace_id,view=view,on_screen=req.on_screen,terminal=req.terminal,prompt_target=req.prompt_target,)+ if accepted and registry.take_focus_dirty():+ # The selected pane is part of what a reopened app restores (RUB-102).+ await registry.persist_resume_activity()return {"ok": True, "accepted": accepted}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 7c7b917998..4bc8cd00f9 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -361,6 +361,11 @@ export interface SessionState {project: ProjectProfile;created_at: number;focus_mode: boolean;+ /**+ * The pane last selected in this workspace, saved with it so a reopened app+ * lands on the same pane. Absent from older backends.+ */+ focused?: string;/*** WHERE every pane sits and how much room it has — the split tree the grid* draws from (see `components/agentic/treeLayout`). Null only while thediff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsxindex 699d1e5de7..2d79cb51ee 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx@@ -9,6 +9,7 @@ const api = vi.hoisted(() => ({fetchIdeState: vi.fn(), fetchIdeProjects: vi.fn(), fetchIdeAgents: vi.fn(),startIdeSession: vi.fn(), activateWorkspace: vi.fn(), restoreIdeWorkspace: vi.fn(),addTerminal: vi.fn(), closeTerminal: vi.fn(), closeWorkspace: vi.fn(), renameWorkspace: vi.fn(), reorderIdeTerminals: vi.fn(), pushToast: vi.fn(),+ syncAgenticIdeSurface: vi.fn(() => Promise.resolve()),}));const openProject = vi.hoisted(() => vi.fn());vi.mock("@/lib/agenticIdeApi", () => api);diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 17c3acb25f..9391cf9106 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -17,7 +17,7 @@ import { useIdeProjectsStore } from "@/store/ideProjects";import { openProject } from "@/lib/chatLibraryApi";import {activateWorkspace, addTerminal, closeTerminal, closeWorkspace, fetchIdeAgents, fetchIdeProjects, fetchIdeState, renameWorkspace,- reorderIdeTerminals, restoreIdeWorkspace, startIdeSession,+ reorderIdeTerminals, restoreIdeWorkspace, startIdeSession, syncAgenticIdeSurface,type AgentStatus, type IdeProject, type IdeState, type TerminalState,} from "@/lib/agenticIdeApi";@@ -180,9 +180,22 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {useEffect(() => {setWorkspace(session ? { id: session.id, name: session.name ?? session.project.name, path: session.folder } : null);setWorkspaces((state?.workspaces ?? []).map((workspace) => ({ id: workspace.id, name: workspace.name, folder: workspace.folder, active: workspace.active })));- if (session && !session.terminals.some((terminal) => terminal.name === selected)) setSelected(session.terminals[0]?.name ?? "");+ if (session && !session.terminals.some((terminal) => terminal.name === selected)) {+ // The pane the workspace was left on, when it still exists; else the first.+ const focused = session.terminals.find((terminal) => terminal.name === session.focused);+ setSelected(focused?.name ?? session.terminals[0]?.name ?? "");+ }}, [session, state?.workspaces, selected, setWorkspace, setWorkspaces]);+ // Report the selected pane: it is the voice/prompt target, and the backend+ // saves it with the workspace so a reopened app restores the focus.+ const sessionId = session?.id ?? "";+ useEffect(() => {+ if (!sessionId || !selected) return;+ void syncAgenticIdeSurface({ workspaceId: sessionId, view: "grid", onScreen, terminal: null, promptTarget: selected })+ .catch((error) => console.warn("Agentic IDE focus report failed:", error));+ }, [sessionId, selected, onScreen]);+const run = useCallback(async (work: () => Promise<void>) => {++refreshEpoch.current; // invalidate reads started before this mutationsetBusy(true);diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.pyindex 6998676782..c79fe42ee4 100644--- a/jarvis/ui/web/launcher.py+++ b/jarvis/ui/web/launcher.py@@ -807,6 +807,11 @@ async def _run_headless(args) -> int:await server.start(start_serving=False)_lx_mark("server_start_total")+ # Reattach to coding agents that kept running while the app was closed,+ # and reopen the Agentic IDE workspaces in their layout.+ from jarvis.agentic_ide.session import schedule_boot_restore++ schedule_boot_restore()# 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 nowdiff --git a/tests/integration/terminal/test_pty_host_process.py b/tests/integration/terminal/test_pty_host_process.pynew file mode 100644index 0000000000..421dd6f785--- /dev/null+++ b/tests/integration/terminal/test_pty_host_process.py@@ -0,0 +1,161 @@+"""The PTY host, end to end: a real host process, a real child in a real PTY.++The whole promise of the host in one test — an agent keeps running while no+client is attached, and the next client re-joins it with the screen it drew+meanwhile — driven through the public client API only.++The user's own host is never touched: ``LOCALAPPDATA`` and the home directory+point into ``tmp_path``, so the state file this test finds (and the host it+starts) are its own. The host is killed at the end whatever happened.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import os+import signal+import sys+from collections.abc import Callable, Iterator+from pathlib import Path++import pytest++from jarvis.platform.capabilities import detect_capabilities++pytestmark = pytest.mark.skipif(+ not detect_capabilities().has_pty, reason="no PTY backend on this machine"+)++WAIT_S = 30.0++#: The "agent": prints a marker, then echoes every line it is given.+CHILD_SOURCE = (+ "import sys\n"+ "print('hello-marker', flush=True)\n"+ "while True:\n"+ " line = sys.stdin.readline()\n"+ " if not line:\n"+ " break\n"+ " print('echo:' + line.strip(), flush=True)\n"+)+++async def _until(check: Callable[[], bool], limit_s: float = WAIT_S) -> None:+ loop = asyncio.get_running_loop()+ deadline = loop.time() + limit_s+ while not check():+ if loop.time() > deadline:+ raise AssertionError("condition not reached in time")+ await asyncio.sleep(0.05)+++def _kill(pid: int) -> None:+ if pid <= 0 or pid == os.getpid():+ return+ with contextlib.suppress(OSError):+ # TerminateProcess on Windows; on POSIX the host's process group+ # containment takes its children with it.+ os.kill(pid, signal.SIGTERM)+++def isolated_data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ """Point every per-user path at ``tmp_path``, and kill whatever host it held."""+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "localappdata"))+ monkeypatch.setenv("HOME", str(tmp_path / "home"))+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "home"))+ from jarvis.terminal import pty_host_client++ state_path = pty_host_client._state_path() # noqa: SLF001 - locating the test's own host+ assert tmp_path in state_path.parents, "the test must never reach the real user's host"+ yield state_path+ # Belt and braces: whatever host the state file names is the test's own.+ with contextlib.suppress(OSError, ValueError, AttributeError):+ _kill(int(json.loads(state_path.read_text(encoding="utf-8")).get("pid") or 0))+++class Viewer:+ def __init__(self) -> None:+ self.chunks: list[str] = []+ self.exits: list[int] = []++ async def output(self, _tid: str, text: str) -> None:+ self.chunks.append(text)++ async def closed(self, _tid: str, code: int) -> None:+ self.exits.append(code)++ @property+ def text(self) -> str:+ return "".join(self.chunks)+++async def test_a_terminal_survives_a_detach_and_is_adopted_with_its_screen(+ isolated_data_dir: Path, tmp_path: Path+) -> None:+ from jarvis.terminal.pty_host_client import connect++ host_pids: list[int] = []+ first = await connect(start=True)+ if first is None:+ pytest.skip("the PTY host cannot run on this install")+ host_pids.append(first.host_pid)+ second = None+ try:+ assert first.connected+ assert first.hosted() == []+ assert await asyncio.to_thread(isolated_data_dir.is_file)++ one = Viewer()+ session = await first.spawn(+ (sys.executable, "-u", "-c", CHILD_SOURCE),+ "test",+ str(tmp_path),+ 100,+ 30,+ one.output,+ one.closed,+ meta={"history_id": "hist-xyz", "name": "T1"},+ )+ terminal_id = session.terminal_id+ await _until(lambda: "hello-marker" in one.text)+ assert first.write(terminal_id, "first\r")+ await _until(lambda: "echo:first" in one.text)++ # Quitting the app: detach, do not kill.+ first.close_all()+ assert not first.connected+ await asyncio.sleep(0.2)+ assert one.exits == [], "detaching must not report the agent as ended"++ second = await connect(start=False)+ assert second is not None, "the host must still be running"+ assert second.host_pid == first.host_pid+ hosted = second.hosted()+ assert [info.terminal_id for info in hosted] == [terminal_id]+ assert hosted[0].meta == {"history_id": "hist-xyz", "name": "T1"}+ assert (hosted[0].cols, hosted[0].rows) == (100, 30)++ two = Viewer()+ result = await second.adopt(terminal_id, two.output, two.closed)+ assert result.alive+ assert "hello-marker" in result.replay+ assert "echo:first" in result.replay+ assert second.hosted() == []+ assert second.has(terminal_id)++ assert second.write(terminal_id, "second\r")+ await _until(lambda: "echo:second" in two.text)++ assert second.close(terminal_id)+ await _until(lambda: len(two.exits) == 1)+ await _until(lambda: not second.has(terminal_id))+ assert one.exits == []+ finally:+ if second is not None:+ second.close_all()+ first.close_all()+ for pid in host_pids:+ _kill(pid)diff --git a/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py b/tests/unit/agentic_ide/test_ide_runtime_lifecycle.pynew file mode 100644index 0000000000..c9b780e25d--- /dev/null+++ b/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py@@ -0,0 +1,192 @@+"""RUB-102 lifecycle pieces around the PTY host: focus, reboot recovery, stop.++* the focused pane is saved with its workspace and put back on reopen,+* after a reboot (nothing left in the host) panes that were working are+ started without a viewer and continued; panes whose agent survived are not,+* the explicit stop ends every agent and keeps the next start from reopening.+"""++from __future__ import annotations++import asyncio+import time+from pathlib import Path++import pytest++from jarvis.agentic_ide import 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 _no_real_agents(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))+++def _snapshot(folder: Path, *, working: bool, focused: str = "") -> None:+ now = time.time()+ workspace = resume_store.SnapshotWorkspace(+ session_id="ide_lifecycle01",+ folder=str(folder),+ terminals=[+ resume_store.SnapshotTerminal(+ key=f"t{index + 1}",+ name=f"T{index + 1}",+ agent="claude",+ history_id=f"hist-{index + 1}",+ column=index,+ continuation_needed=working,+ )+ for index in range(2)+ ],+ saved_at=now,+ focused=focused,+ )+ resume_store.save(+ resume_store.Snapshot(+ saved_at=now, workspaces=[workspace], active_session_id=workspace.session_id+ )+ )+++def _checkpoint_says_working(terminals: list[ide.Terminal]) -> None:+ # The real check asks the CLI's own history; here the checkpoint is enough.+ for term in terminals:+ term.continuation_pending = term.resume_continuation_needed+++# ------------------------------------------------------------------ focus+async def test_focused_pane_is_saved_and_restored(tmp_path: Path) -> None:+ registry = ide.Registry(pty_manager=FakeHostedPool())+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])+ second = session.terminals[1].name++ assert registry.set_surface_context(+ workspace_id=session.id, view="grid", on_screen=True, terminal=None, prompt_target=second+ )+ assert registry.take_focus_dirty() is True+ # The same report again is not a change and asks for no save.+ registry.set_surface_context(+ workspace_id=session.id, view="grid", on_screen=True, terminal=None, prompt_target=second+ )+ assert registry.take_focus_dirty() is False+ assert session.to_dict()["focused"] == second++ snapshot = registry.snapshot()+ assert snapshot is not None+ parsed = resume_store.Snapshot.from_dict(snapshot.to_dict())+ assert parsed is not None and parsed.workspaces[0].focused == second++ reopened = ide.Registry(pty_manager=FakeHostedPool())+ await reopened.restore(parsed)+ assert reopened.sessions[0].focused == second+++async def test_a_focus_on_a_pane_that_is_gone_is_dropped(tmp_path: Path) -> None:+ _snapshot(tmp_path, working=False, focused="Nobody")+ snapshot = resume_store.load()+ assert snapshot is not None+ registry = ide.Registry(pty_manager=FakeHostedPool())+ await registry.restore(snapshot)+ assert registry.sessions[0].focused == ""+++# ----------------------------------------------------------- after reboot+async def test_reboot_starts_and_continues_panes_that_were_working(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _snapshot(tmp_path, working=True)+ monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)+ pool = FakeHostedPool() # a fresh host: nothing survived the reboot+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))++ registry = ide.Registry()+ nudged: list[tuple[str, str]] = []++ async def record_prompt(name: str, text: str, **_kwargs: object) -> None:+ nudged.append((name, text))++ monkeypatch.setattr(registry, "send_prompt", record_prompt)+ await registry.boot_restore()+ for _ in range(100):+ if len(nudged) == 2:+ break+ await asyncio.sleep(0.02)++ # Both agents were started although no viewer ever connected ...+ assert sorted(meta["history_id"] for meta in pool.metas) == ["hist-1", "hist-2"]+ # ... and each was told to carry on exactly once, once it was live.+ assert sorted(nudged) == [("T1", "continue"), ("T2", "continue")]+ assert all(term.status == "live" for term in registry.sessions[0].terminals)+++async def test_agents_that_survived_are_rejoined_not_continued(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _snapshot(tmp_path, working=True)+ monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)+ pool = FakeHostedPool()+ pool.add_hosted("h-1", history_id="hist-1")+ pool.add_hosted("h-2", history_id="hist-2")+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))++ registry = ide.Registry()+ await registry.boot_restore()+ await asyncio.sleep(0.05)++ session = registry.sessions[0]+ assert pool.adopted == ["h-1", "h-2"]+ assert pool.metas == [] # nothing new was spawned+ assert not any(term.continuation_pending for term in session.terminals)+ assert not any(term.continue_when_ready for term in session.terminals)+++async def test_panes_that_were_idle_are_not_continued_after_reboot(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _snapshot(tmp_path, working=False)+ monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)+ pool = FakeHostedPool()+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))++ registry = ide.Registry()+ await registry.boot_restore()+ await asyncio.sleep(0.05)++ assert pool.metas == []+ assert all(term.status == "pending" for term in registry.sessions[0].terminals)+++# ------------------------------------------------------------------- stop+async def test_stop_runtime_ends_everything_and_blocks_the_auto_reopen(tmp_path: Path) -> None:+ pool = FakeHostedPool()+ registry = ide.Registry(pty_manager=pool)+ first = tmp_path / "a"+ second = tmp_path / "b"+ first.mkdir()+ second.mkdir()+ await registry.start(str(first), [{"agent": "claude"}])+ await registry.start(str(second), [{"agent": "claude"}])+ status = registry.runtime_status()+ assert status["mode"] == "host" and status["workspaces"] == 2++ assert await registry.stop_runtime() == 2+ assert registry.sessions == []+ closed_at = resume_store.all_closed_at()+ snapshot = resume_store.load()+ assert closed_at is not None and snapshot is not None+ newest = max(w.saved_at for w in snapshot.workspaces)+ assert closed_at >= newest+ assert registry.runtime_status()["workspaces"] == 0+++def test_runtime_status_before_anything_started() -> None:+ status = ide.Registry().runtime_status()+ assert status == {+ "mode": "idle",+ "host_pid": 0,+ "persistent_enabled": False,+ "workspaces": 0,+ "live_agents": 0,+ }diff --git a/tests/unit/agentic_ide/test_pty_host_adoption.py b/tests/unit/agentic_ide/test_pty_host_adoption.pynew file mode 100644index 0000000000..d9e5988b32--- /dev/null+++ b/tests/unit/agentic_ide/test_pty_host_adoption.py@@ -0,0 +1,344 @@+"""The registry's side of the PTY host: adopting agents that outlived the app.++Driven against a fake persistent pool (``FakeHostedPool``) that behaves like+``RemotePtyManager`` from the registry's point of view — ``persistent``,+``connected``, ``hosted()``, ``adopt()``, ``kill_hosted()`` — on top of the+ordinary fake PTY pool, so no host process and no pseudo-terminal is needed.+The resume store is redirected to a temporary file by this package's conftest.+"""++from __future__ import annotations++import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import pytest++from jarvis.agentic_ide import resume_store+from jarvis.agentic_ide import session as ide+from jarvis.terminal.pty_host_client import AdoptResult, HostedInfo+from tests.fakes.fake_pty_manager import FakePtyManager, FakePtySession+++@dataclass+class FakeHostedPool(FakePtyManager):+ """A fake PTY pool that also holds terminals from before the app started."""++ persistent: bool = True+ connected: bool = True+ hosted_terminals: dict[str, HostedInfo] = field(default_factory=dict)+ replays: dict[str, str] = field(default_factory=dict)+ adopted: list[str] = field(default_factory=list)+ killed: list[str] = field(default_factory=list)+ metas: list[dict[str, Any]] = field(default_factory=list)+ appearances: list[tuple[str, str]] = field(default_factory=list)++ def add_hosted(+ self, terminal_id: str, *, history_id: str, replay: str = "", started_at: float = 1.0+ ) -> None:+ self.hosted_terminals[terminal_id] = HostedInfo(+ terminal_id=terminal_id,+ pid=500,+ meta={"history_id": history_id, "name": terminal_id},+ cols=100,+ rows=40,+ started_at=started_at,+ )+ self.replays[terminal_id] = replay++ def hosted(self) -> list[HostedInfo]:+ return list(self.hosted_terminals.values())++ async def adopt(self, terminal_id: str, on_output: Any, on_closed: Any) -> AdoptResult:+ self.hosted_terminals.pop(terminal_id, None)+ self.adopted.append(terminal_id)+ self._live.add(terminal_id)+ self._callbacks[terminal_id] = (on_output, on_closed)+ return AdoptResult(alive=True, replay=self.replays.get(terminal_id, ""), cols=100, rows=40)++ def kill_hosted(self, terminal_id: str) -> bool:+ self.hosted_terminals.pop(terminal_id, None)+ self.killed.append(terminal_id)+ return True++ def set_appearance(self, terminal_id: str, appearance: str) -> None:+ self.appearances.append((terminal_id, appearance))++ async def spawn( # type: ignore[override]+ self,+ shell_argv: tuple[str, ...],+ shell_id: str,+ cwd: str | None,+ cols: int,+ rows: int,+ on_output: Any,+ on_closed: Any,+ env: Any = None,+ on_probe: Any = None,+ meta: dict[str, Any] | None = None,+ ) -> FakePtySession:+ self.metas.append(dict(meta or {}))+ return await FakePtyManager.spawn(+ self, shell_argv, shell_id, cwd, cols, rows, on_output, on_closed, env, on_probe+ )+++class ConnectRecorder:+ """Replaces ``session._connect_pty_host``: hands out a pool, remembers calls."""++ def __init__(self, pool: Any) -> None:+ self.pool = pool+ self.calls: list[bool] = []++ async def __call__(self, *, start: bool) -> Any:+ self.calls.append(start)+ return self.pool++[email protected](autouse=True)+def _no_real_agents(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++def _save_snapshot(folder: Path, histories: list[str], saved_at: float) -> None:+ workspace = resume_store.SnapshotWorkspace(+ session_id="ide_restoreme01",+ folder=str(folder),+ terminals=[+ resume_store.SnapshotTerminal(+ key=f"t{index + 1}",+ name=f"T{index + 1}",+ agent="claude",+ history_id=history,+ column=index,+ )+ for index, history in enumerate(histories)+ ],+ saved_at=saved_at,+ )+ resume_store.save(+ resume_store.Snapshot(+ saved_at=saved_at, workspaces=[workspace], active_session_id=workspace.session_id+ )+ )+++# ------------------------------------------------------------- _adopt_hosted+async def test_adopt_hosted_rejoins_matching_panes_with_their_screen(tmp_path: Path) -> None:+ pool = FakeHostedPool()+ registry = ide.Registry(pty_manager=pool)+ session = await registry.start(+ str(tmp_path), [{"agent": "claude", "name": "T1"}, {"agent": "claude", "name": "T2"}]+ )+ t1, t2 = session.find("T1"), session.find("T2")+ # Two hosted terminals claim T1's history: the newer one wins.+ pool.add_hosted("old", history_id=t1.history_id, replay="stale", started_at=1.0)+ pool.add_hosted("new", history_id=t1.history_id, replay="hello from before", started_at=2.0)+ pool.add_hosted("unrelated", history_id="someone-else", replay="x")++ await registry._adopt_hosted(session) # noqa: SLF001 - the unit under test++ assert pool.adopted == ["new"]+ assert t1.status == "live"+ assert t1.pty_id == "new"+ assert (t1.pty_cols, t1.pty_rows) == (100, 40)+ assert "hello from before" in t1.replay.text()+ assert t1.resumed is False+ assert t1.exit_code is None+ assert t1.started_at == 2.0+ # The pane without a hosted agent is untouched: it resumes on connect.+ assert t2.status == "pending"+ assert t2.pty_id is None+ # Nothing is killed here; that is boot_restore's job.+ assert pool.killed == []+ assert {info.terminal_id for info in pool.hosted()} == {"old", "unrelated"}++ # Live output keeps flowing into the pane, and an exit ends it.+ await pool.emit("new", "more output")+ assert "more output" in t1.replay.text()+ assert t1.last_output_at is not None+ await pool.die("new", 3)+ assert t1.status == "exited"+ assert t1.exit_code == 3+ assert t1.pty_id is None+++async def test_an_adopted_pane_is_rejoined_on_attach_not_respawned(tmp_path: Path) -> None:+ pool = FakeHostedPool()+ registry = ide.Registry(pty_manager=pool)+ session = await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ pool.add_hosted("h1", history_id=session.find("T1").history_id, replay="screen")+ await registry._adopt_hosted(session) # noqa: SLF001++ seen: list[str] = []++ async def _viewer(text: str) -> None:+ seen.append(text)++ await registry.attach("T1", 100, 40, _viewer, _noop_exit)+ assert pool.spawns == []+ await pool.emit("h1", "live bytes")+ assert "live bytes" in "".join(seen)+++# --------------------------------------------------------------- boot_restore+async def test_boot_restore_reopens_the_snapshot_and_ends_unclaimed_terminals(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ now = time.time()+ _save_snapshot(tmp_path, ["hist-1", "hist-2"], saved_at=now)+ # An older all-closed marker does not stop the reopen.+ resume_store.note_all_closed(now - 100)+ pool = FakeHostedPool()+ pool.add_hosted("h-1", history_id="hist-1", replay="agent one was here")+ pool.add_hosted("orphan", history_id="closed-long-ago")+ connect = ConnectRecorder(pool)+ monkeypatch.setattr(ide, "_connect_pty_host", connect)++ registry = ide.Registry()+ await registry.boot_restore()++ # Attach only — a boot must never START a host nobody needs.+ assert connect.calls == [False]+ assert len(registry.sessions) == 1+ session = registry.sessions[0]+ t1, t2 = session.find("T1"), session.find("T2")+ assert t1.status == "live" and t1.pty_id == "h-1"+ assert "agent one was here" in t1.replay.text()+ assert t2.status == "pending"+ assert pool.adopted == ["h-1"]+ assert pool.killed == ["orphan"]+ assert pool.hosted() == []++ # Once per process.+ await registry.boot_restore()+ assert connect.calls == [False]+ assert len(registry.sessions) == 1+++async def test_boot_restore_respects_closing_everything_by_hand(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ now = time.time()+ _save_snapshot(tmp_path, ["hist-1"], saved_at=now - 50)+ resume_store.note_all_closed(now)+ pool = FakeHostedPool()+ pool.add_hosted("h-1", history_id="hist-1")+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))++ registry = ide.Registry()+ await registry.boot_restore()++ assert registry.sessions == []+ assert pool.adopted == []+ # Nothing reopened claims it, so it is ended rather than kept alive forever.+ assert pool.killed == ["h-1"]+++async def test_boot_restore_without_a_host_still_reopens(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _save_snapshot(tmp_path, ["hist-1"], saved_at=time.time())+ connect = ConnectRecorder(None)+ monkeypatch.setattr(ide, "_connect_pty_host", connect)++ registry = ide.Registry(pty_manager=FakePtyManager())+ await registry.boot_restore()++ # A pool that already exists is kept; no attach is even attempted.+ assert connect.calls == []+ assert len(registry.sessions) == 1+ assert registry.sessions[0].find("T1").status == "pending"+++async def test_closing_the_last_workspace_writes_the_all_closed_marker(tmp_path: Path) -> None:+ registry = ide.Registry(pty_manager=FakePtyManager())+ assert resume_store.all_closed_at() is None+ other = tmp_path / "other"+ other.mkdir()+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.start(str(other), [{"agent": "claude", "name": "T1"}])+ await registry.end(registry.sessions[0].id)+ assert resume_store.all_closed_at() is None, "one workspace is still open"+ before = time.time()+ await registry.end(registry.sessions[0].id)+ stamp = resume_store.all_closed_at()+ assert stamp is not None and stamp >= before - 1+++# ------------------------------------------------------------- _live_manager+async def test_the_host_is_never_used_without_boot_restore(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ connect = ConnectRecorder(FakeHostedPool())+ monkeypatch.setattr(ide, "_connect_pty_host", connect)+ fake = FakePtyManager()+ registry = ide.Registry(pty_manager=fake)+ assert registry._host_enabled is False # noqa: SLF001++ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit)++ assert connect.calls == []+ assert len(fake.spawns) == 1+ assert await registry._live_manager() is fake # noqa: SLF001+++async def test_after_boot_restore_new_panes_start_in_the_host_with_meta(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ pool = FakeHostedPool()+ connect = ConnectRecorder(pool)+ monkeypatch.setattr(ide, "_connect_pty_host", connect)+ registry = ide.Registry()+ await registry.boot_restore()+ assert connect.calls == [False]++ session = await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit, appearance="dark")+ term = session.find("T1")++ assert len(pool.spawns) == 1+ assert pool.metas == [+ {+ "history_id": term.history_id,+ "name": "T1",+ "workspace_id": session.id,+ "agent": "claude",+ }+ ]+ assert term.pty_id == "fake-pty-1"+++async def test_a_lost_host_is_reconnected_with_start_for_the_next_pane(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ first = FakeHostedPool()+ connect = ConnectRecorder(first)+ monkeypatch.setattr(ide, "_connect_pty_host", connect)+ registry = ide.Registry()+ await registry.boot_restore()++ first.connected = False+ second = FakeHostedPool()+ connect.pool = second+ assert await registry._live_manager() is second # noqa: SLF001+ assert connect.calls == [False, True]++ # A host that cannot come back degrades to an in-process pool, for good.+ second.connected = False+ connect.pool = None+ fallback = await registry._live_manager() # noqa: SLF001+ assert not getattr(fallback, "persistent", False)+ assert await registry._live_manager() is fallback # noqa: SLF001+ assert connect.calls == [False, True, True]diff --git a/tests/unit/terminal/test_pty_host_client.py b/tests/unit/terminal/test_pty_host_client.pynew file mode 100644index 0000000000..7700375aed--- /dev/null+++ b/tests/unit/terminal/test_pty_host_client.py@@ -0,0 +1,453 @@+"""The app's side of the PTY host: ``RemoteSession`` and ``RemotePtyManager``.++No host process and no pseudo-terminal: a tiny asyncio server runs in the test+and plays the host's half of the wire protocol, so every frame the client sends+and every event it reacts to is visible here.+"""++from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator, Callable+from typing import Any++import pytest++from jarvis.terminal.pty_host_client import (+ HostConnectionError,+ HostedInfo,+ RemotePtyManager,+ RemoteSession,+)+from jarvis.terminal.pty_manager import MAX_PENDING_CHARS, UNKNOWN_EXIT_CODE++WAIT_S = 5.0+++async def _until(check: Callable[[], bool], limit_s: float = WAIT_S) -> None:+ """Poll ``check`` until it holds, failing loudly after ``limit_s``."""+ loop = asyncio.get_running_loop()+ deadline = loop.time() + limit_s+ while not check():+ if loop.time() > deadline:+ raise AssertionError("condition not reached in time")+ await asyncio.sleep(0.01)+++class Recorder:+ """Output/exit callbacks that remember what they were handed, in order."""++ def __init__(self) -> None:+ self.events: list[tuple[str, Any]] = []++ async def output(self, _tid: str, text: str) -> None:+ self.events.append(("o", text))++ async def closed(self, _tid: str, code: int) -> None:+ self.events.append(("exit", code))++ @property+ def text(self) -> str:+ return "".join(value for kind, value in self.events if kind == "o")++ @property+ def exits(self) -> list[int]:+ return [value for kind, value in self.events if kind == "exit"]+++# ------------------------------------------------------------ RemoteSession+async def test_output_that_arrives_during_a_send_leaves_as_one_chunk() -> None:+ gate = asyncio.Event()+ received: list[str] = []++ async def _output(_tid: str, text: str) -> None:+ received.append(text)+ if len(received) == 1:+ await gate.wait()++ async def _closed(_tid: str, _code: int) -> None:+ return None++ session = RemoteSession("t1", 1, _output, _closed)+ pump = asyncio.create_task(session.run())+ session.offer("a")+ await _until(lambda: received == ["a"])+ # The first send is still in flight: these three must coalesce.+ session.offer("b")+ session.offer("c")+ session.offer("d")+ gate.set()+ await _until(lambda: len(received) == 2)+ assert received == ["a", "bcd"]+ session.finish(0)+ await asyncio.wait_for(pump, WAIT_S)+++async def test_the_exit_is_reported_only_after_the_last_output_is_flushed() -> None:+ rec = Recorder()+ session = RemoteSession("t1", 1, rec.output, rec.closed)+ session.offer("last words")+ session.finish(3)+ # Offered after the exit: dropped, never delivered after on_closed.+ session.offer("ghost")+ await asyncio.wait_for(session.run(), WAIT_S)+ assert rec.events == [("o", "last words"), ("exit", 3)]+++async def test_a_backlog_over_the_cap_drops_the_oldest_chunks() -> None:+ rec = Recorder()+ session = RemoteSession("t1", 1, rec.output, rec.closed)+ old = "x" * (MAX_PENDING_CHARS // 2 + 1)+ new = "y" * (MAX_PENDING_CHARS // 2 + 1)+ session.offer(old)+ session.offer(new)+ session.offer("tail")+ session.finish(0)+ await asyncio.wait_for(session.run(), WAIT_S)+ assert rec.text == new + "tail"+ assert rec.exits == [0]+++async def test_a_failing_output_callback_does_not_stop_the_exit() -> None:+ closed: list[int] = []++ async def _boom(_tid: str, _text: str) -> None:+ raise RuntimeError("viewer gone")++ async def _closed(_tid: str, code: int) -> None:+ closed.append(code)++ session = RemoteSession("t1", 1, _boom, _closed)+ session.offer("x")+ session.finish(7)+ await asyncio.wait_for(session.run(), WAIT_S)+ assert closed == [7]+++# ---------------------------------------------------- in-test host server+class FakeHost:+ """Plays the host's side of the wire protocol for one client."""++ def __init__(self) -> None:+ self.frames: list[dict[str, Any]] = []+ self.writer: asyncio.StreamWriter | None = None+ self.eof = asyncio.Event()+ self.server: asyncio.base_events.Server | None = None+ self.answer_requests = True+ self._next = 0++ async def start(self) -> int:+ self.server = await asyncio.start_server(self._on_connect, "127.0.0.1", 0)+ return int(self.server.sockets[0].getsockname()[1])++ async def _on_connect(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ self.writer = writer+ try:+ while True:+ line = await reader.readline()+ if not line:+ break+ frame = json.loads(line.decode("utf-8"))+ self.frames.append(frame)+ await self._answer(frame)+ except (ConnectionError, OSError):+ pass+ finally:+ self.eof.set()++ async def _answer(self, frame: dict[str, Any]) -> None:+ rid = frame.get("rid")+ if rid is None or not self.answer_requests:+ return+ op = frame.get("op")+ if op == "spawn":+ self._next += 1+ reply = {"ok": True, "id": f"host-{self._next}", "pid": 900 + self._next}+ elif op == "adopt":+ if frame["id"] == "dead":+ reply = {"ok": True, "alive": False, "code": 5}+ else:+ reply = {+ "ok": True,+ "alive": True,+ "replay": "screen so far",+ "truncated": True,+ "cols": 100,+ "rows": 40,+ }+ else:+ reply = {"ok": True}+ reply["rid"] = rid+ await self.send(reply)++ async def send(self, frame: dict[str, Any]) -> None:+ assert self.writer is not None+ self.writer.write((json.dumps(frame) + "\n").encode("utf-8"))+ await self.writer.drain()++ def ops(self, op: str) -> list[dict[str, Any]]:+ return [f for f in self.frames if f.get("op") == op]++ async def drop(self) -> None:+ assert self.writer is not None+ self.writer.close()++ async def stop(self) -> None:+ if self.writer is not None:+ self.writer.close()+ if self.server is not None:+ self.server.close()+ await self.server.wait_closed()+++class Responder:+ """Stands in for ``TerminalQueryResponder``: the client reads its appearance."""++ appearance = "light"++ def feed(self, text: str) -> str:+ return ""+++async def host() -> AsyncIterator[FakeHost]:+ fake = FakeHost()+ await fake.start()+ yield fake+ await fake.stop()+++async def _client(host: FakeHost, hosted: list[HostedInfo] | None = None) -> RemotePtyManager:+ assert host.server is not None+ port = int(host.server.sockets[0].getsockname()[1])+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ manager = RemotePtyManager(reader, writer, hosted or [], host_pid=4321)+ await _until(lambda: host.writer is not None)+ return manager+++async def _cleanup(manager: RemotePtyManager) -> None:+ manager.detach()+ for session in list(manager._sessions.values()): # noqa: SLF001 - test teardown+ if session._pump is not None: # noqa: SLF001+ session._pump.cancel() # noqa: SLF001+ await asyncio.sleep(0)+++def _hosted(terminal_id: str, **meta: Any) -> HostedInfo:+ return HostedInfo(+ terminal_id=terminal_id, pid=77, meta=dict(meta), cols=80, rows=24, started_at=1.0+ )+++# --------------------------------------------------------- RemotePtyManager+async def test_spawn_sends_argv_meta_and_the_viewers_appearance(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ session = await manager.spawn(+ ("agent", "--flag"),+ "agentic-ide:t1",+ "/work",+ 120,+ 30,+ rec.output,+ rec.closed,+ env={"A": "1"},+ on_probe=Responder().feed,+ meta={"history_id": "h1", "name": "T1"},+ )+ assert session.terminal_id == "host-1"+ assert session.pid == 901+ spawn = host.ops("spawn")[0]+ assert spawn["argv"] == ["agent", "--flag"]+ assert spawn["cwd"] == "/work"+ assert (spawn["cols"], spawn["rows"]) == (120, 30)+ assert spawn["env"] == {"A": "1"}+ assert spawn["appearance"] == "light"+ assert spawn["meta"] == {"history_id": "h1", "name": "T1"}+ assert manager.persistent is True+ assert manager.connected is True+ assert manager.has("host-1")+ finally:+ await _cleanup(manager)+++async def test_output_and_exit_events_reach_the_right_terminal(host: FakeHost) -> None:+ manager = await _client(host)+ one, two = Recorder(), Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, one.output, one.closed)+ await manager.spawn(("b",), "s", None, 80, 24, two.output, two.closed)+ await host.send({"ev": "o", "id": "host-1", "d": "hello "})+ await host.send({"ev": "o", "id": "host-2", "d": "other"})+ await host.send({"ev": "o", "id": "host-1", "d": "world"})+ # An event for a terminal this client does not hold is ignored.+ await host.send({"ev": "o", "id": "stranger", "d": "nope"})+ await host.send({"ev": "exit", "id": "host-1", "code": 0})+ await _until(lambda: one.exits == [0])+ assert one.text == "hello world"+ await _until(lambda: two.text == "other")+ assert two.exits == []+ # The ended terminal is forgotten; the other is still routed.+ await _until(lambda: not manager.has("host-1"))+ assert manager.has("host-2")+ finally:+ await _cleanup(manager)+++async def test_write_resize_appearance_and_close_become_frames(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, rec.output, rec.closed)+ assert manager.write("host-1", "ls\r") is True+ assert manager.resize("host-1", 132, 50) is True+ manager.set_appearance("host-1", "dark")+ # Unknown ids never reach the wire.+ assert manager.write("nope", "x") is False+ assert manager.resize("nope", 1, 1) is False+ assert manager.close("nope") is False+ assert manager.close("host-1") is True+ await _until(lambda: bool(host.ops("close")))+ assert host.ops("write") == [{"op": "write", "id": "host-1", "d": "ls\r"}]+ assert host.ops("resize") == [{"op": "resize", "id": "host-1", "cols": 132, "rows": 50}]+ assert host.ops("appearance") == [+ {"op": "appearance", "id": "host-1", "appearance": "dark"}+ ]+ assert host.ops("close") == [{"op": "close", "id": "host-1"}]+ # Closing is not an exit: the exit still comes from the host.+ assert rec.exits == []+ await host.send({"ev": "exit", "id": "host-1", "code": 1})+ await _until(lambda: rec.exits == [1])+ finally:+ await _cleanup(manager)+++async def test_adopt_returns_the_replay_and_streams_from_then_on(host: FakeHost) -> None:+ manager = await _client(host, [_hosted("h-live", history_id="x"), _hosted("dead")])+ rec = Recorder()+ try:+ assert {info.terminal_id for info in manager.hosted()} == {"h-live", "dead"}+ result = await manager.adopt("h-live", rec.output, rec.closed)+ assert result.alive is True+ assert result.replay == "screen so far"+ assert result.truncated is True+ assert (result.cols, result.rows) == (100, 40)+ assert manager.has("h-live")+ assert manager._sessions["h-live"].pid == 77 # noqa: SLF001+ assert [info.terminal_id for info in manager.hosted()] == ["dead"]+ await host.send({"ev": "o", "id": "h-live", "d": "live"})+ await _until(lambda: rec.text == "live")++ gone = await manager.adopt("dead", rec.output, rec.closed)+ assert gone.alive is False+ assert gone.exit_code == 5+ assert not manager.has("dead")+ assert manager.hosted() == []+ finally:+ await _cleanup(manager)+++async def test_kill_hosted_closes_an_unclaimed_terminal(host: FakeHost) -> None:+ manager = await _client(host, [_hosted("orphan")])+ try:+ assert manager.kill_hosted("orphan") is True+ assert manager.hosted() == []+ await _until(lambda: bool(host.ops("close")))+ assert host.ops("close") == [{"op": "close", "id": "orphan"}]+ finally:+ await _cleanup(manager)+++async def test_losing_the_host_ends_every_terminal_with_unknown_code(host: FakeHost) -> None:+ manager = await _client(host, [_hosted("never-adopted")])+ one, two = Recorder(), Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, one.output, one.closed)+ await manager.spawn(("b",), "s", None, 80, 24, two.output, two.closed)+ await host.send({"ev": "o", "id": "host-1", "d": "before"})+ await _until(lambda: one.text == "before")+ # A request in flight when the host goes away fails instead of hanging.+ host.answer_requests = False+ pending = asyncio.create_task(manager.adopt("never-adopted", one.output, one.closed))+ await _until(lambda: bool(host.ops("adopt")))+ await host.drop()+ await _until(lambda: one.exits == [UNKNOWN_EXIT_CODE])+ await _until(lambda: two.exits == [UNKNOWN_EXIT_CODE])+ with pytest.raises(HostConnectionError):+ await asyncio.wait_for(pending, WAIT_S)+ assert manager.connected is False+ assert manager.hosted() == []+ assert not manager.has("host-1")+ assert manager.write("host-2", "x") is False+ with pytest.raises(HostConnectionError):+ await manager.spawn(("c",), "s", None, 80, 24, one.output, one.closed)+ finally:+ await _cleanup(manager)+++async def test_lost_finishes_sessions_directly(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, rec.output, rec.closed)+ manager._lost(ConnectionResetError("boom")) # noqa: SLF001 - the unit under test+ await _until(lambda: rec.exits == [UNKNOWN_EXIT_CODE])+ # A second loss report must not finish anybody twice.+ manager._lost(None) # noqa: SLF001+ await asyncio.sleep(0.05)+ assert rec.exits == [UNKNOWN_EXIT_CODE]+ finally:+ await _cleanup(manager)+++async def test_close_all_only_detaches(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, rec.output, rec.closed)+ manager.close_all()+ # The host sees the connection end — and no close for the terminal.+ await asyncio.wait_for(host.eof.wait(), WAIT_S)+ assert host.ops("close") == []+ assert manager.connected is False+ assert manager.write("host-1", "x") is False+ assert manager.close("host-1") is False+ # Detaching is not an exit: nobody is told their agent ended.+ await asyncio.sleep(0.05)+ assert rec.exits == []+ manager.close_all() # idempotent+ finally:+ await _cleanup(manager)+++async def test_swap_sessions_is_refused(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ await manager.spawn(("a",), "s", None, 80, 24, rec.output, rec.closed)+ await manager.spawn(("b",), "s", None, 80, 24, rec.output, rec.closed)+ assert manager.swap_sessions("host-1", "host-2") is False+ assert manager.swap_sessions("host-1", "host-1") is True+ assert not [f for f in host.frames if f.get("op") not in {"spawn"}]+ finally:+ await _cleanup(manager)+++async def test_a_refused_spawn_raises(host: FakeHost) -> None:+ manager = await _client(host)+ rec = Recorder()+ try:+ # The fake answers every spawn; this time the test answers, refusing it.+ host.answer_requests = False+ task = asyncio.create_task(manager.spawn(("a",), "s", None, 80, 24, rec.output, rec.closed))+ await _until(lambda: bool(host.ops("spawn")))+ rid = host.ops("spawn")[0]["rid"]+ await host.send({"rid": rid, "ok": False, "error": "empty argv"})+ with pytest.raises(RuntimeError, match="empty argv"):+ await asyncio.wait_for(task, WAIT_S)+ assert manager.connected is True+ finally:+ await _cleanup(manager)