Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): stop a workspace of panes eating the whole machine

Ruben Lütke4498649f0eda
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 3f4259aaf8..e8d0f65e2f 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -67,6 +67,8 @@ import re
import shutil
import sys
import time
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -164,6 +166,37 @@ RESUME_FAILED_WINDOW_S = 45.0
# nothing; two attempts cover a slow machine without turning into polling.
DISCOVERY_DELAYS_S = (4.0, 12.0)
+# ---------------------------------------------------------------------------
+# How many agent CLIs may be COLD-STARTING at the same moment.
+#
+# Opening a workspace mounts every pane at once, each pane connects at once, and
+# each connection starts a coding CLI — so the grid used to launch all of them
+# in the same instant. A coding CLI's start is not cheap: it loads its plugins
+# and hooks, and then starts one process per MCP server the user has configured,
+# most of them through ``npx``, which resolves a package before it runs one.
+# Measured on this install: eleven user-scope servers, roughly two and a half
+# processes each. Eight panes therefore meant well over two hundred process
+# starts inside a second or two — every core pinned, the machine unresponsive,
+# and the app itself too starved to draw the panes it was starting.
+#
+# The work is the same either way; only its SHAPE changes. Panes past the limit
+# wait for a slot, so the same workspace opens as a rolling start that leaves
+# the machine usable, and the pane the user is looking at is up immediately
+# rather than last-of-eight in a freeze.
+#
+# A quarter of the cores, at least two: enough parallelism that a small
+# workspace (which is most of them) is never held back at all, and a floor that
+# keeps a dual-core VPS from serializing completely.
+COLD_START_LIMIT = max(2, (os.cpu_count() or 4) // 4)
+
+# How long a started pane keeps its slot. The expensive part happens AFTER the
+# process exists — the CLI is loading while ``spawn`` has long returned — so
+# releasing the slot on spawn would let the whole grid pile into the same second
+# regardless of the limit. Roughly the length of a CLI's own boot burst; long
+# enough to stagger, short enough that nobody watches a spinner for it.
+COLD_START_SETTLE_S = 1.2
+
+
# How long the nudged window size is held before it is put back (see
# ``_nudge_repaint``). A PTY carries one size, not a queue of them: set twice
# within the same event-loop tick, the agent may only ever observe the second
@@ -748,6 +781,12 @@ class Registry:
# rewrite the same config file eight times — and that file grows to tens
# of kilobytes on a heavy user (see jarvis.workspace.trust).
self._pre_trusted: set[tuple[str, str]] = set()
+ # Admits a few agent cold starts at a time (see COLD_START_LIMIT).
+ # Created on first use rather than here: a semaphore belongs to the loop
+ # it is first awaited on, and the registry is also built in tests that
+ # run each case on a loop of its own.
+ self._cold_start: asyncio.Semaphore | None = None
+
# ---------------------------------------------------------------- state
@property
@@ -1418,6 +1457,42 @@ class Registry:
term = session.find(key)
return None if term is None else (session, term)
+ @asynccontextmanager
+ async def _cold_start_slot(self) -> AsyncIterator[None]:
+ """Hold one of the few slots for starting an agent CLI.
+
+ Waiting here is what turns "open a workspace" from a burst that pins
+ every core into a rolling start (see :data:`COLD_START_LIMIT`). It
+ gates STARTS only: a pane re-joining an agent that never stopped — the
+ common case on every workspace switch — returns long before this, and
+ an agent already running is never made to wait behind one that is
+ booting.
+
+ The slot is released a moment AFTER the block, not at its end. What
+ costs is the CLI loading itself and its servers, and by then ``spawn``
+ has returned; releasing immediately would let the whole grid through in
+ the same instant and the limit would gate nothing. A spawn that FAILED
+ releases at once — nothing is loading, and a broken pane must not hold
+ up the ones behind it.
+ """
+ gate = self._cold_start
+ if gate is None:
+ # No await between the check and the assignment, so two panes
+ # arriving together cannot end up with a semaphore each.
+ gate = self._cold_start = asyncio.Semaphore(COLD_START_LIMIT)
+ await gate.acquire()
+ started = False
+ try:
+ yield
+ started = True
+ finally:
+ if started:
+ asyncio.get_running_loop().call_later(
+ COLD_START_SETTLE_S, gate.release
+ )
+ else:
+ gate.release()
+
async def attach(
self,
key: str,
@@ -1620,24 +1695,30 @@ class Registry:
if viewer is not None:
await viewer(code)
- # Off the event loop: getting the pane's account ready is filesystem
- # work (a few stat calls once it is in place — see `_prepare_spawn`).
- env = await asyncio.to_thread(self._prepare_spawn, term, session.folder)
- try:
- pty_session = await manager.spawn(
- shell_argv=argv,
- shell_id=f"agentic-ide:{term.key}",
- cwd=session.folder,
- cols=cols,
- rows=rows,
- on_output=_output,
- on_closed=_closed,
- env=_spawn_env(term),
- )
- except Exception as exc: # noqa: BLE001 - surfaced to the pane
- term.status = "error"
- term.error = str(exc)
- raise SessionError(str(exc)) from exc
+ # One of a few starts at a time (see COLD_START_LIMIT). The wait covers
+ # the account preparation too: that is filesystem work on the same
+ # directory every pane of an account shares, so letting eight of them
+ # queue on its lock while eight CLIs boot is the same pile-up one step
+ # earlier.
+ async with self._cold_start_slot():
+ # Off the event loop: getting the pane's account ready is filesystem
+ # work (a few stat calls once it is in place — see `_prepare_spawn`).
+ env = await asyncio.to_thread(self._prepare_spawn, term, session.folder)
+ try:
+ pty_session = await manager.spawn(
+ shell_argv=argv,
+ shell_id=f"agentic-ide:{term.key}",
+ cwd=session.folder,
+ cols=cols,
+ rows=rows,
+ on_output=_output,
+ on_closed=_closed,
+ env=_spawn_env(term),
+ )
+ except Exception as exc: # noqa: BLE001 - surfaced to the pane
+ term.status = "error"
+ term.error = str(exc)
+ raise SessionError(str(exc)) from exc
term.pty_id = pty_session.terminal_id
term.status = "live"
diff --git a/jarvis/core/process_tree.py b/jarvis/core/process_tree.py
new file mode 100644
index 0000000000..19ac294a4c
--- /dev/null
+++ b/jarvis/core/process_tree.py
@@ -0,0 +1,308 @@
+"""Kill a spawned process together with everything it started.
+
+Terminating a child terminates exactly that child. Everything it spawned in
+turn keeps running, reparented and unreachable — and for a coding CLI that is
+not a detail, it is the bulk of the tree: every MCP server the CLI starts is a
+separate ``npx`` process pair that does NOT exit when the pipe to its client
+breaks. It waits on a stdin that will never speak again, forever.
+
+Measured on this machine after a day of Agentic-IDE use, with the app already
+closed: 102 ``node``, 59 ``cmd`` and 89 ``conhost`` processes still resident,
+all of them descendants of panes that had been shut long before. Each workspace
+that is opened adds another set, so the machine's idle floor climbs with every
+session until a reboot — which is what "it was immediately back at 100 %" is
+made of.
+
+So a spawn is CONTAINED instead: the child is put in a kill-on-close container
+before it can fork, and closing the container reaps the whole descendant tree
+at once.
+
+* **Windows** — a Job Object with ``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE``.
+ Descendants inherit membership automatically, and the kernel does the reaping
+ when the last handle closes — including when this process dies without ever
+ running its own cleanup.
+* **POSIX** — the child's process GROUP, signalled ``SIGTERM`` and then
+ ``SIGKILL`` after a short grace. A PTY child is a session leader
+ (``ptyprocess`` calls ``setsid``), so its group is exactly its tree.
+* **Anywhere else** — a no-op that says so once, because containment is a
+ safeguard and its absence must not stop a terminal from opening.
+
+Deliberately SYNCHRONOUS, unlike the mission-scoped container in
+``jarvis/missions/isolation/job_object.py``: this one is closed from a PTY
+teardown that runs on the event loop, where an ``await`` grace period would
+stall every other pane. The POSIX escalation therefore runs on a short-lived
+timer thread rather than a sleep.
+
+``allow_breakaway`` is left ON. A process created with
+``CREATE_BREAKAWAY_FROM_JOB`` inside a job that forbids breakaway does not
+detach — it FAILS TO START, and a toolchain that does this (some installers,
+some launchers) would turn containment into "the agent will not open". Nothing
+in a normal CLI's tree asks to break away, so permitting it costs nothing real
+and removes a whole class of spawn failures.
+"""
+from __future__ import annotations
+
+import ctypes
+import os
+import signal
+import sys
+import threading
+from ctypes import wintypes
+from typing import Protocol
+
+from loguru import logger
+
+#: How long a POSIX tree gets to exit on ``SIGTERM`` before it is killed.
+#: Long enough for a CLI to flush its state, short enough that a user closing a
+#: workspace never waits on it (the escalation runs on its own thread anyway).
+GRACE_S = 0.5
+
+# Win32 constants — stable kernel API, declared here so the base install needs
+# no pywin32 (that package lives in the desktop extra; containment must work
+# without it).
+_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
+_JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800
+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
+_PROCESS_TERMINATE = 0x0001
+_PROCESS_SET_QUOTA = 0x0100
+
+# Resolved once, by name: process groups and SIGKILL exist on POSIX only, and
+# looking them up as attributes is what lets this module be imported, type-
+# checked and unit-tested on a Windows host without a platform branch around
+# every call.
+_getpgid = getattr(os, "getpgid", None)
+_killpg = getattr(os, "killpg", None)
+_SIGKILL = getattr(signal, "SIGKILL", signal.SIGTERM)
+
+
+class ProcessTree(Protocol):
+ """One spawned process and everything it goes on to start."""
+
+ def assign(self, pid: int) -> None:
+ """Put a freshly spawned process under this container's control."""
+
+ def close(self) -> None:
+ """Reap the tree. Safe to call more than once."""
+
+
+class _NoContainment:
+ """What an unsupported host gets: honest nothing.
+
+ Reported once per container rather than per call — a workspace opens a
+ dozen panes and a warning per pane would be a wall of the same line.
+ """
+
+ __slots__ = ("_name",)
+
+ def __init__(self, name: str) -> None:
+ self._name = name
+ logger.debug(
+ "No process-tree containment on this host — {} may leave descendants "
+ "behind when it exits",
+ name,
+ )
+
+ def assign(self, pid: int) -> None:
+ return None
+
+ def close(self) -> None:
+ return None
+
+
+class _WindowsJob:
+ """A Win32 Job Object that kills its members when the handle closes."""
+
+ __slots__ = ("_kernel32", "_handle", "_closed", "_name")
+
+ def __init__(self, name: str) -> None:
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
+ kernel32.SetInformationJobObject.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ kernel32.SetInformationJobObject.restype = wintypes.BOOL
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ # Unnamed: a NAMED job is shared machine-wide, so two Jarvis instances
+ # would land their panes in one container and the first one to quit
+ # would kill the other's agents.
+ handle = kernel32.CreateJobObjectW(None, None)
+ if not handle:
+ raise ctypes.WinError(ctypes.get_last_error())
+ self._kernel32 = kernel32
+ self._handle = handle
+ self._closed = False
+ self._name = name
+ try:
+ info = _JobObjectExtendedLimitInformation()
+ info.BasicLimitInformation.LimitFlags = (
+ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | _JOB_OBJECT_LIMIT_BREAKAWAY_OK
+ )
+ if not kernel32.SetInformationJobObject(
+ handle,
+ _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
+ ctypes.byref(info),
+ ctypes.sizeof(info),
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ except BaseException:
+ kernel32.CloseHandle(handle)
+ self._closed = True
+ raise
+
+ def assign(self, pid: int) -> None:
+ if self._closed or not pid:
+ return
+ process = self._kernel32.OpenProcess(
+ _PROCESS_TERMINATE | _PROCESS_SET_QUOTA, False, pid
+ )
+ if not process:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ if not self._kernel32.AssignProcessToJobObject(self._handle, process):
+ raise ctypes.WinError(ctypes.get_last_error())
+ finally:
+ self._kernel32.CloseHandle(process)
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ # Flagged before the call, so a failing CloseHandle cannot turn into a
+ # retry loop that leaks a handle per attempt.
+ self._closed = True
+ if not self._kernel32.CloseHandle(self._handle):
+ logger.debug(
+ "Closing the job object for {} failed — its tree may survive: {}",
+ self._name,
+ ctypes.WinError(ctypes.get_last_error()),
+ )
+
+
+class _JobObjectBasicLimitInformation(ctypes.Structure):
+ _fields_ = (
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ )
+
+
+class _IoCounters(ctypes.Structure):
+ _fields_ = (
+ ("ReadOperationCount", ctypes.c_ulonglong),
+ ("WriteOperationCount", ctypes.c_ulonglong),
+ ("OtherOperationCount", ctypes.c_ulonglong),
+ ("ReadTransferCount", ctypes.c_ulonglong),
+ ("WriteTransferCount", ctypes.c_ulonglong),
+ ("OtherTransferCount", ctypes.c_ulonglong),
+ )
+
+
+class _JobObjectExtendedLimitInformation(ctypes.Structure):
+ _fields_ = (
+ ("BasicLimitInformation", _JobObjectBasicLimitInformation),
+ ("IoInfo", _IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ )
+
+
+class _PosixProcessGroup:
+ """Reap a PTY child's process group: ``SIGTERM``, grace, ``SIGKILL``.
+
+ The grace runs on a timer thread rather than an ``await``, because this is
+ closed from a teardown on the event loop and half a second of blocking
+ there is half a second in which no other pane draws.
+ """
+
+ __slots__ = ("_pgids", "_closed", "_name")
+
+ def __init__(self, name: str) -> None:
+ self._pgids: set[int] = set()
+ self._closed = False
+ self._name = name
+
+ def assign(self, pid: int) -> None:
+ if self._closed or not pid:
+ return
+ try:
+ pgid = _getpgid(pid) if _getpgid is not None else pid
+ except (ProcessLookupError, OSError):
+ # Gone already, or no group to read — a PTY child is its own group
+ # leader (``setsid``), so its pid IS the group in every case that
+ # still matters.
+ pgid = pid
+ self._pgids.add(pgid)
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ groups = tuple(self._pgids)
+ self._pgids.clear()
+ if not groups:
+ return
+ self._signal(groups, signal.SIGTERM)
+ timer = threading.Timer(GRACE_S, self._signal, args=(groups, _SIGKILL))
+ timer.daemon = True
+ timer.start()
+
+ def _signal(self, groups: tuple[int, ...], sig: int) -> None:
+ if _killpg is None:
+ return
+ for pgid in groups:
+ try:
+ _killpg(pgid, sig)
+ except (ProcessLookupError, PermissionError, OSError):
+ # Already gone, or not ours to signal. Reaping is best-effort by
+ # nature: the tree exiting on its own is the good outcome.
+ logger.debug(
+ "Signalling process group {} of {} did nothing — already gone",
+ pgid,
+ self._name,
+ )
+
+
+def make_process_tree(name: str) -> ProcessTree:
+ """A kill-on-close container for one spawned process tree.
+
+ Never raises. A host where containment cannot be set up gets the honest
+ no-op: a terminal that opens and leaves debris behind is worth far more
+ than one that refuses to open.
+
+ ``name`` appears in the log lines only; it is never a Windows object name
+ (see :class:`_WindowsJob`).
+ """
+ if sys.platform == "win32":
+ try:
+ return _WindowsJob(name)
+ except Exception as exc: # noqa: BLE001 - containment is a safeguard
+ logger.warning(
+ "Could not create a job object for {} — its descendants will "
+ "not be reaped: {}",
+ name,
+ exc,
+ )
+ return _NoContainment(name)
+ if _killpg is not None:
+ return _PosixProcessGroup(name)
+ return _NoContainment(name)
+
+
+__all__ = ["GRACE_S", "ProcessTree", "make_process_tree"]
diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.py
index a0fcb81b80..36c6d3b9bb 100644
--- a/jarvis/terminal/pty_manager.py
+++ b/jarvis/terminal/pty_manager.py
@@ -16,7 +16,21 @@ Design decisions:
daemon-thread read-loop is structurally unchanged — only the handle type
swapped from a raw ``winpty.PtyProcess`` to a ``PtyHandle``.
- Lifecycle: close() signals the reader thread via a flag and terminates the
- process. No join, so a hung PTY never blocks the web server.
+ process TREE. No join, so a hung PTY never blocks the web server.
+
+## Why a session owns a container and not just a process
+
+Terminating a PTY child terminates that child. A coding CLI, though, is the
+smallest part of what it started: every MCP server it connects to is a separate
+process pair that does NOT exit when its client goes away — it waits on a
+stdin nothing will ever write to again. So each closed pane used to leave its
+whole server fleet resident, and every workspace opened added another one.
+Measured with the app already shut down: 102 ``node``, 59 ``cmd`` and 89
+``conhost`` processes, all belonging to panes closed hours earlier.
+
+Every session therefore spawns INTO a kill-on-close container
+(``jarvis.core.process_tree``) — a Win32 Job Object, or the child's process
+group on POSIX — and closing the session reaps the descendants with it.
## Why output is coalesced instead of forwarded chunk by chunk
@@ -64,6 +78,8 @@ from uuid import uuid4
from loguru import logger
+from jarvis.core.process_tree import ProcessTree, make_process_tree
+
from .backend import PtyHandle, make_pty_backend
OutputCallback = Callable[[str, str], Awaitable[None]]
@@ -95,6 +111,10 @@ class PtySession:
pid: int
proc: PtyHandle # normalized PTY handle behind the backend seam (AD-6)
stop_flag: threading.Event
+ #: Kill-on-close container holding this child AND everything it spawns —
+ #: the MCP servers a coding CLI starts outlive it otherwise (module
+ #: docstring). Assigned right after construction, like ``reader_thread``.
+ tree: ProcessTree | None = field(default=None, init=False)
#: Assigned right after construction — the thread is handed the session it
#: feeds, so the two cannot be built in one expression.
reader_thread: threading.Thread | None = field(default=None, init=False)
@@ -250,6 +270,20 @@ class PtyManager:
proc=proc,
stop_flag=stop_flag,
)
+ # Before the child has produced a byte, so the servers it starts on the
+ # way up are already inside the container. Containment is a safeguard
+ # and never a reason to fail a spawn: a host that cannot provide one
+ # gets a no-op and a terminal that works (module docstring).
+ session.tree = make_process_tree(f"pty:{shell_id}")
+ try:
+ session.tree.assign(pid)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "PTY could not be contained — its descendants will survive it",
+ terminal_id=terminal_id,
+ pid=pid,
+ error=str(exc),
+ )
session.reader_thread = threading.Thread(
target=self._reader_loop,
name=f"pty-reader-{terminal_id[:8]}",
@@ -388,6 +422,20 @@ class PtyManager:
session.proc.terminate(force=True)
except Exception: # noqa: BLE001, S110 - terminate is best-effort cleanup
pass
+ # AFTER the child itself, so a CLI that shuts its servers down cleanly
+ # gets the chance to; the container is what catches the ones that do
+ # not, which for an MCP server over a dead pipe is all of them.
+ tree = session.tree
+ if tree is not None:
+ session.tree = None
+ try:
+ tree.close()
+ except Exception as exc: # noqa: BLE001 - reaping is best-effort
+ logger.debug(
+ "PTY tree teardown failed",
+ terminal_id=session.terminal_id,
+ error=str(exc),
+ )
# No join — the reader thread is a daemon and may still be running
# through one last read(). That's fine; Python exit cleans it up.
# The pump is deliberately NOT cancelled here: the reader thread is
@@ -455,6 +503,21 @@ class PtyManager:
terminal_id=session.terminal_id,
error=str(exc),
)
+ # A child that ended BY ITSELF never goes through ``_terminate``, and
+ # the servers it started are exactly as orphaned as after a kill — a
+ # coding CLI that is quit with /exit leaves its whole MCP fleet behind.
+ # Same container, same reap, one pass either way (it is idempotent).
+ tree = session.tree
+ if tree is not None:
+ session.tree = None
+ try:
+ tree.close()
+ except Exception as exc: # noqa: BLE001 - reaping is best-effort
+ logger.debug(
+ "PTY tree teardown after exit failed",
+ terminal_id=session.terminal_id,
+ error=str(exc),
+ )
def _reader_loop(
self,
diff --git a/tests/unit/agentic_ide/test_cold_start_gate.py b/tests/unit/agentic_ide/test_cold_start_gate.py
new file mode 100644
index 0000000000..a81f5e54c3
--- /dev/null
+++ b/tests/unit/agentic_ide/test_cold_start_gate.py
@@ -0,0 +1,162 @@
+"""Opening a workspace starts its agents in waves, not all at once.
+
+The defect these pin down: every pane of a workspace mounts together, connects
+together and therefore used to launch its coding CLI in the same instant. A
+CLI's start is the expensive part of a pane — it loads its plugins and hooks
+and then starts one process per configured MCP server, most of them through
+``npx``, which resolves a package before it runs one. On a real install that is
+eleven servers at roughly two and a half processes each, so eight panes meant
+over two hundred process starts inside a second: every core pinned, the machine
+unresponsive, and the app too starved to draw the panes it was starting.
+
+The same work still happens — only its shape changes. What must hold:
+
+* no more than :data:`COLD_START_LIMIT` agents are STARTING at any moment,
+* a pane re-joining an agent that never stopped is never made to wait behind
+ one that is booting (switching workspaces has to stay instant),
+* a spawn that FAILS gives its slot back immediately rather than making the
+ panes behind it wait out a settle window for nothing.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as ide
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+class CountingPtyManager(FakePtyManager):
+ """A pty pool that reports how many spawns overlap in time.
+
+ ``spawn`` holds for as long as the test tells it to, which is what makes
+ "how many were in flight at once" observable at all — a spawn that returns
+ instantly can never overlap with anything.
+ """
+
+ def __init__(self) -> None:
+ # The base is a dataclass; its generated ``__init__`` builds the
+ # recording fields, and the counters below are this subclass's own.
+ super().__init__()
+ self.in_flight = 0
+ self.peak = 0
+ self.hold_s = 0.0
+
+ async def spawn(self, *args, **kwargs): # noqa: ANN002, ANN003, ANN201
+ self.in_flight += 1
+ self.peak = max(self.peak, self.in_flight)
+ try:
+ if self.hold_s:
+ await asyncio.sleep(self.hold_s)
+ return await super().spawn(*args, **kwargs)
+ finally:
+ self.in_flight -= 1
+
+
+def pool(monkeypatch: pytest.MonkeyPatch) -> CountingPtyManager:
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return CountingPtyManager()
+
+
+async def _attach_all(registry: ide.Registry, session) -> None: # noqa: ANN001
+ async def sink(_text: str) -> None:
+ return None
+
+ async def gone(_code: int) -> None:
+ return None
+
+ await asyncio.gather(
+ *(
+ registry.attach(term.key, 80, 24, sink, gone, workspace_id=session.id)
+ for term in session.terminals
+ )
+ )
+
+
+async def test_a_full_workspace_starts_in_waves(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The whole grid connecting at once must not become one starting storm."""
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 3)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ pool.hold_s = 0.05
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(
+ str(tmp_path), [{"agent": "claude"} for _ in range(12)]
+ )
+
+ await _attach_all(registry, session)
+
+ assert len(pool.spawns) == 12, "every pane still gets its agent"
+ assert pool.peak <= 3, f"{pool.peak} agents were starting at once"
+
+
+async def test_rejoining_a_running_agent_never_waits_for_a_starting_one(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Switching workspaces re-joins agents; that path must not be gated.
+
+ With the gate full of slow starts, a pane whose agent is already alive has
+ to come back immediately — it is not starting anything.
+ """
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 1)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(
+ str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}]
+ )
+ first, second = session.terminals
+
+ async def sink(_text: str) -> None:
+ return None
+
+ async def gone(_code: int) -> None:
+ return None
+
+ # Both agents are up and running.
+ await registry.attach(first.key, 80, 24, sink, gone, workspace_id=session.id)
+ await registry.attach(second.key, 80, 24, sink, gone, workspace_id=session.id)
+ spawned = len(pool.spawns)
+
+ # Now make every START slow, and re-join one of the running agents.
+ pool.hold_s = 5.0
+ await asyncio.wait_for(
+ registry.attach(first.key, 80, 24, sink, gone, workspace_id=session.id),
+ timeout=2.0,
+ )
+ assert len(pool.spawns) == spawned, "a re-join must not start anything"
+
+
+async def test_a_failed_start_hands_its_slot_back_at_once(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A broken pane must not hold up the ones queued behind it.
+
+ The settle window exists to keep a HEALTHY agent's boot from overlapping
+ with the next one. Nothing is booting after a failure, so waiting it out
+ would delay every remaining pane for a pane that does not exist.
+ """
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 1)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 30.0)
+ pool.spawn_error = "no pseudo-terminal on this host"
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(
+ str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}]
+ )
+
+ async def sink(_text: str) -> None:
+ return None
+
+ async def gone(_code: int) -> None:
+ return None
+
+ for term in session.terminals:
+ with pytest.raises(ide.SessionError):
+ await asyncio.wait_for(
+ registry.attach(term.key, 80, 24, sink, gone, workspace_id=session.id),
+ timeout=2.0,
+ )
diff --git a/tests/unit/terminal/test_pty_containment.py b/tests/unit/terminal/test_pty_containment.py
new file mode 100644
index 0000000000..fbc4c73695
--- /dev/null
+++ b/tests/unit/terminal/test_pty_containment.py
@@ -0,0 +1,177 @@
+"""A closed pane takes the processes its agent started with it.
+
+The defect these pin down: terminating a PTY child terminates that child and
+nothing else. A coding CLI's MCP servers are separate processes that keep
+running when their client disappears — they wait on a stdin nobody will ever
+write to again — so every closed pane used to leave its whole server fleet
+resident, and the machine's idle load climbed with each workspace opened.
+Measured on a real install with the app already shut down: 102 ``node``, 59
+``cmd`` and 89 ``conhost`` processes, all of them descendants of long-closed
+panes.
+
+So a session owns a kill-on-close container and everything it spawns lands in
+it (``jarvis.core.process_tree``). What matters is the CONTRACT, pinned here
+against a fake container so the tests run on every OS:
+
+* a spawned child is put in a container before it can fork,
+* closing the pane reaps it,
+* an agent that exits BY ITSELF is reaped too — quitting a CLI orphans exactly
+ the same servers as killing it,
+* reaping happens once, not twice,
+* and a host that cannot contain anything still gets a working terminal.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+import jarvis.terminal.pty_manager as pty_mod
+from jarvis.terminal.pty_manager import PtyManager
+from tests.fakes.fake_pty_backend import FakePtyBackend
+
+
+class FakeTree:
+ """A ``ProcessTree`` that records what it was asked to hold and reap."""
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.assigned: list[int] = []
+ self.closes = 0
+
+ def assign(self, pid: int) -> None:
+ self.assigned.append(pid)
+
+ def close(self) -> None:
+ self.closes += 1
+
+
+class RefusingTree(FakeTree):
+ """A container on a host where assignment does not work."""
+
+ def assign(self, pid: int) -> None:
+ raise OSError("no containment on this host")
+
+
+def trees(monkeypatch: pytest.MonkeyPatch) -> list[FakeTree]:
+ made: list[FakeTree] = []
+
+ def _make(name: str) -> FakeTree:
+ tree = FakeTree(name)
+ made.append(tree)
+ return tree
+
+ monkeypatch.setattr(pty_mod, "make_process_tree", _make)
+ return made
+
+
+async def _spawn(manager: PtyManager, backend: FakePtyBackend):
+ async def on_output(_tid: str, _text: str) -> None:
+ return None
+
+ async def on_closed(_tid: str, _code: int) -> None:
+ return None
+
+ return await manager.spawn(
+ shell_argv=("sh",),
+ shell_id="pane-a",
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=on_output,
+ on_closed=on_closed,
+ )
+
+
+async def test_a_spawned_child_is_contained(
+ monkeypatch: pytest.MonkeyPatch, trees: list[FakeTree]
+) -> None:
+ """The child is in a container, holding its real pid, before it runs."""
+ backend = FakePtyBackend(pid=1234)
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: backend)
+ manager = PtyManager()
+
+ session = await _spawn(manager, backend)
+
+ assert len(trees) == 1
+ assert trees[0].assigned == [1234]
+ assert session.tree is trees[0]
+ manager.close(session.terminal_id)
+
+
+async def test_closing_a_pane_reaps_its_tree(
+ monkeypatch: pytest.MonkeyPatch, trees: list[FakeTree]
+) -> None:
+ """This is the leak: the descendants have to go when the pane does."""
+ backend = FakePtyBackend(pid=1234)
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: backend)
+ manager = PtyManager()
+ session = await _spawn(manager, backend)
+
+ assert trees[0].closes == 0
+ manager.close(session.terminal_id)
+
+ assert trees[0].closes == 1
+ # Reaped once, not once per teardown path — the pump reaps too, and both
+ # running would signal a process group whose id may since have been reused.
+ await asyncio.sleep(0.05)
+ assert trees[0].closes == 1
+
+
+async def test_an_agent_that_quits_by_itself_is_reaped_too(
+ monkeypatch: pytest.MonkeyPatch, trees: list[FakeTree]
+) -> None:
+ """Quitting a CLI orphans the same servers as killing it does.
+
+ Nothing calls ``close`` in this case — the child simply ended — so the reap
+ has to come from the path that notices the exit.
+ """
+ backend = FakePtyBackend(pid=1234, exitstatus=0)
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: backend)
+ manager = PtyManager()
+
+ exited = asyncio.Event()
+
+ async def on_output(_tid: str, _text: str) -> None:
+ return None
+
+ async def on_closed(_tid: str, _code: int) -> None:
+ exited.set()
+
+ session = await manager.spawn(
+ shell_argv=("sh",),
+ shell_id="pane-a",
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=on_output,
+ on_closed=on_closed,
+ )
+ # The child ends on its own — no ``manager.close``, nothing terminated from
+ # this side. The handle simply stops being alive, which is all the reader
+ # loop ever learns about an agent that quit.
+ handle = backend.last_handle
+ assert handle is not None
+ handle.terminate(force=False)
+
+ await asyncio.wait_for(exited.wait(), timeout=5.0)
+ await asyncio.sleep(0.05)
+ assert trees[0].closes == 1
+ assert session.tree is None
+
+
+async def test_a_host_without_containment_still_opens_a_terminal(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Containment is a safeguard. Its absence must not cost the user a pane."""
+ backend = FakePtyBackend(pid=1234)
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: backend)
+ monkeypatch.setattr(pty_mod, "make_process_tree", RefusingTree)
+ manager = PtyManager()
+
+ session = await _spawn(manager, backend)
+
+ assert manager.has(session.terminal_id)
+ manager.close(session.terminal_id)