Skip to content

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

feat(ide): run Agentic IDE panes on a connected computer

rubenluetke10-beepb92ee08416ea
diff --git a/jarvis/agentic_ide/remote.py b/jarvis/agentic_ide/remote.py
new file mode 100644
index 0000000000..f34175f362
--- /dev/null
+++ b/jarvis/agentic_ide/remote.py
@@ -0,0 +1,506 @@
+"""Moving IDE work between this computer and a connected one.
+
+Three things travel when a pane moves to a VPS ("offload") or comes back:
+
+1. **The code.** A git folder travels as a *snapshot commit* — the working
+ tree exactly as it is, uncommitted edits and new files included — built
+ with a throw-away index so the user's own index, branch and stash are never
+ touched, and shipped as a git bundle over SFTP. On the server it lands
+ checked out on the same branch with the edits back as uncommitted changes.
+ Only objects the server does not have yet are sent after the first time.
+ A folder without git travels as a tarball (heavy build folders skipped).
+2. **The conversation.** Claude Code and Codex keep a transcript per
+ conversation id; that file is copied into the matching place on the other
+ side, so the agent continues with ``--resume`` instead of starting blind.
+ Other agents start fresh there (said so in the log).
+3. **Nothing else.** No credentials move here; logging a CLI in on the server
+ is its own explicit step (``jarvis.computers.toolbox``).
+
+Coming back reverses 1 and 2. The server's work returns as a local branch
+``jarvis/<computer>/<time>``; when this folder has not changed since the
+offload, the same changes are also applied to the working tree, so the user
+simply finds the work where it was.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import logging
+import os
+import re
+import shlex
+import subprocess
+import tarfile
+import tempfile
+import time
+import uuid
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+
+from jarvis.computers.remote_terminal import SshPtyPool
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+REMOTE_ROOT = "jarvis-workspaces"
+SYNC_DIR = ".jarvis-sync"
+MAX_TARBALL_BYTES = 300 * 1024 * 1024
+_SKIP_DIRS = {"node_modules", ".venv", "venv", "__pycache__", ".cache", ".mypy_cache", ".next"}
+_IDENTITY_ENV = {
+ "GIT_AUTHOR_NAME": "Jarvis",
+ "GIT_AUTHOR_EMAIL": "jarvis@localhost",
+ "GIT_COMMITTER_NAME": "Jarvis",
+ "GIT_COMMITTER_EMAIL": "jarvis@localhost",
+}
+
+
+class MoveError(RuntimeError):
+ """A move failed; the message is written for the user."""
+
+
+@dataclass(frozen=True)
+class Placement:
+ """Where a pane's code lives on the server, and what it left behind here."""
+
+ remote_folder: str
+ #: The snapshot commit the server was given (git folders only).
+ offload_snapshot: str | None
+
+
+# ---------------------------------------------------------------------------
+# local git, never touching the user's index
+# ---------------------------------------------------------------------------
+
+
+def _git(
+ cwd: Path, *args: str, env: dict[str, str] | None = None, stdin: bytes | None = None
+) -> str:
+ merged = {**os.environ, **(env or {})}
+ result = subprocess.run( # noqa: S603 — fixed git argv, no shell
+ ["git", *args], # noqa: S607
+ cwd=str(cwd),
+ env=merged,
+ input=stdin,
+ capture_output=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ check=False,
+ )
+ if result.returncode != 0:
+ detail = result.stderr.decode("utf-8", "replace").strip().splitlines()
+ raise MoveError(f"git {args[0]} failed: {detail[-1] if detail else result.returncode}")
+ return result.stdout.decode("utf-8", "replace").strip()
+
+
+def git_toplevel(folder: Path) -> Path | None:
+ try:
+ return Path(_git(folder, "rev-parse", "--show-toplevel"))
+ except (MoveError, OSError):
+ return None
+
+
+def _head(top: Path) -> str | None:
+ try:
+ return _git(top, "rev-parse", "-q", "--verify", "HEAD^{commit}")
+ except MoveError:
+ return None
+
+
+def _branch(top: Path) -> str | None:
+ try:
+ name = _git(top, "symbolic-ref", "-q", "--short", "HEAD")
+ except MoveError:
+ return None
+ return name or None
+
+
+def snapshot_commit(top: Path, message: str) -> tuple[str, str]:
+ """Commit the working tree as it is (tracked + untracked, .gitignore honoured).
+
+ Returns ``(commit, tree)``. Uses a private index file, so the user's index,
+ branch and stash are untouched; the commit is reachable only through the
+ ref the caller gives it.
+ """
+ head = _head(top)
+ with tempfile.TemporaryDirectory(prefix="jarvis-snap-") as tmp:
+ env = {"GIT_INDEX_FILE": str(Path(tmp) / "index"), **_IDENTITY_ENV}
+ if head:
+ _git(top, "read-tree", head, env=env)
+ _git(top, "add", "-A", env=env)
+ tree = _git(top, "write-tree", env=env)
+ parents = ["-p", head] if head else []
+ commit = _git(top, "commit-tree", tree, *parents, "-m", message, env=_IDENTITY_ENV)
+ return commit, tree
+
+
+def working_tree_id(top: Path) -> str:
+ """The tree id the working tree would commit to right now."""
+ head = _head(top)
+ with tempfile.TemporaryDirectory(prefix="jarvis-tree-") as tmp:
+ env = {"GIT_INDEX_FILE": str(Path(tmp) / "index")}
+ if head:
+ _git(top, "read-tree", head, env=env)
+ _git(top, "add", "-A", env=env)
+ return _git(top, "write-tree", env=env)
+
+
+def _relative_posix(folder: Path, top: Path) -> str:
+ relative = os.path.relpath(os.path.realpath(folder), os.path.realpath(top))
+ return PurePosixPath(*Path(relative).parts).as_posix()
+
+
+def _slug(text: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:32] or "workspace"
+
+
+def remote_folder_for(home: str, local_folder: Path) -> str:
+ """Stable per local folder: ``~/jarvis-workspaces/<name>-<hash>``."""
+ digest = hashlib.sha1(str(local_folder.resolve()).encode("utf-8")).hexdigest()[:6] # noqa: S324
+ return str(PurePosixPath(home) / REMOTE_ROOT / f"{_slug(local_folder.name)}-{digest}")
+
+
+# ---------------------------------------------------------------------------
+# code: up
+# ---------------------------------------------------------------------------
+
+
+_APPLY = r"""
+set -e
+DEST={dest}; BUNDLE={bundle}; REF={ref}; BASE={base}; BRANCH={branch}; SNAP={snap}
+mkdir -p "$DEST" && cd "$DEST"
+[ -d .git ] || git init -q
+if git rev-parse -q --verify HEAD >/dev/null && [ -n "$(git status --porcelain)" ]; then
+ export GIT_INDEX_FILE="$(mktemp)"; git read-tree HEAD; git add -A; t=$(git write-tree)
+ c=$(git -c user.name=Jarvis -c user.email=jarvis@localhost commit-tree "$t" -p HEAD \
+ -m "jarvis: server state before sync")
+ git update-ref "refs/jarvis/backup/$(date +%s)" "$c"
+ rm -f "$GIT_INDEX_FILE"; unset GIT_INDEX_FILE
+fi
+git fetch -q "$BUNDLE" "$REF:$REF"
+if [ -n "$BASE" ]; then
+ if [ -n "$BRANCH" ]; then git checkout -q -f -B "$BRANCH" "$BASE"
+ else git checkout -q -f --detach "$BASE"; fi
+fi
+git read-tree -u --reset "$SNAP"
+if [ -n "$BASE" ]; then git reset -q; fi
+rm -f "$BUNDLE"
+echo ok
+"""
+
+
+async def _remote_known(pool: SshPtyPool, remote_folder: str) -> list[str]:
+ code, out, _err = await pool.run(
+ f"cd {shlex.quote(remote_folder)} 2>/dev/null && git for-each-ref --format='%(objectname)' "
+ "refs/heads refs/jarvis 2>/dev/null",
+ timeout_s=30,
+ )
+ return [
+ line.strip() for line in out.splitlines() if re.fullmatch(r"[0-9a-f]{40}", line.strip())
+ ]
+
+
+async def _upload(pool: SshPtyPool, local: Path, remote: str) -> None:
+ session = await pool.connection()
+ async with session.conn.start_sftp_client() as sftp:
+ await sftp.makedirs(str(PurePosixPath(remote).parent), exist_ok=True)
+ await sftp.put(str(local), remote)
+
+
+async def _download(pool: SshPtyPool, remote: str, local: Path) -> None:
+ session = await pool.connection()
+ async with session.conn.start_sftp_client() as sftp:
+ await sftp.get(remote, str(local))
+
+
+async def push_code(pool: SshPtyPool, local_folder: Path) -> Placement:
+ """Put ``local_folder`` (as it is right now) onto the server."""
+ home = await pool.home()
+ code, _out, _err = await pool.run("command -v git >/dev/null")
+ if code != 0:
+ raise MoveError("This computer needs git first. Open Computers, then Prepare.")
+ top = await asyncio.to_thread(git_toplevel, local_folder)
+ if top is None:
+ remote = remote_folder_for(home, local_folder)
+ await _push_tarball(pool, local_folder, remote)
+ return Placement(remote_folder=remote, offload_snapshot=None)
+
+ remote_top = remote_folder_for(home, top)
+ relative = await asyncio.to_thread(_relative_posix, local_folder, top)
+ remote_folder = (
+ str(PurePosixPath(remote_top) / relative) if relative not in ("", ".") else remote_top
+ )
+ transfer = uuid.uuid4().hex[:12]
+ ref = f"refs/jarvis/offload/{transfer}"
+ snap, _tree = await asyncio.to_thread(snapshot_commit, top, "jarvis: offload snapshot")
+ head = await asyncio.to_thread(_head, top)
+ branch = await asyncio.to_thread(_branch, top)
+ known = await _remote_known(pool, remote_top)
+ with tempfile.TemporaryDirectory(prefix="jarvis-bundle-") as tmp:
+ bundle = Path(tmp) / "offload.bundle"
+ await asyncio.to_thread(_git, top, "update-ref", ref, snap)
+ present = []
+ for sha in known:
+ try:
+ await asyncio.to_thread(_git, top, "cat-file", "-e", f"{sha}^{{commit}}")
+ present.append(f"^{sha}")
+ except MoveError:
+ continue
+ try:
+ await asyncio.to_thread(_git, top, "bundle", "create", str(bundle), ref, *present)
+ except MoveError:
+ # Nothing new to send is reported as an error by git; send it whole.
+ await asyncio.to_thread(_git, top, "bundle", "create", str(bundle), ref)
+ remote_bundle = f"{home}/{SYNC_DIR}/{transfer}.bundle"
+ await _upload(pool, bundle, remote_bundle)
+ script = _APPLY.format(
+ dest=shlex.quote(remote_top),
+ bundle=shlex.quote(remote_bundle),
+ ref=shlex.quote(ref),
+ base=shlex.quote(head or ""),
+ branch=shlex.quote(branch or ""),
+ snap=shlex.quote(snap),
+ )
+ code, out, err = await pool.run(script, timeout_s=600)
+ if code != 0 or "ok" not in out:
+ detail = (err or out).strip().splitlines()
+ raise MoveError(
+ "The code could not be set up on the server" + (f": {detail[-1]}" if detail else ".")
+ )
+ return Placement(remote_folder=remote_folder, offload_snapshot=snap)
+
+
+def _tar_filter(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
+ parts = PurePosixPath(info.name).parts
+ if any(part in _SKIP_DIRS for part in parts):
+ return None
+ return info
+
+
+async def _push_tarball(pool: SshPtyPool, folder: Path, remote: str) -> None:
+ with tempfile.TemporaryDirectory(prefix="jarvis-tar-") as tmp:
+ archive = Path(tmp) / "folder.tar.gz"
+
+ def build() -> int:
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(str(folder), arcname=".", filter=_tar_filter)
+ return archive.stat().st_size
+
+ size = await asyncio.to_thread(build)
+ if size > MAX_TARBALL_BYTES:
+ raise MoveError("This folder is too large to copy without git (over 300 MB).")
+ home = await pool.home()
+ archive_name = f"{uuid.uuid4().hex[:12]}.tar.gz"
+ sync_dir = f"{home}/{SYNC_DIR}"
+ await _upload(pool, archive, f"{sync_dir}/{archive_name}")
+ # Relative archive name: some tars read "C:/..." as a remote host.
+ code, _out, err = await pool.run(
+ f"mkdir -p {shlex.quote(remote)} && cd {shlex.quote(sync_dir)} && "
+ f"tar -xzf {shlex.quote(archive_name)} -C {shlex.quote(remote)} && "
+ f"rm -f {shlex.quote(archive_name)}",
+ timeout_s=600,
+ )
+ if code != 0:
+ raise MoveError(f"The folder could not be unpacked on the server: {err.strip()[:200]}")
+
+
+# ---------------------------------------------------------------------------
+# code: down
+# ---------------------------------------------------------------------------
+
+
+_PACK = r"""
+set -e
+cd {dest}
+export GIT_INDEX_FILE="$(mktemp)"; git read-tree HEAD; git add -A; t=$(git write-tree)
+c=$(git -c user.name=Jarvis -c user.email=jarvis@localhost commit-tree "$t" -p HEAD \
+ -m "jarvis: work from the server")
+rm -f "$GIT_INDEX_FILE"; unset GIT_INDEX_FILE
+git update-ref {ref} "$c"
+mkdir -p {sync}
+git bundle create {bundle} {ref} {exclude} >/dev/null 2>&1 \
+ || git bundle create {bundle} {ref} >/dev/null
+echo "$c"
+"""
+
+
+@dataclass(frozen=True)
+class Return:
+ branch: str | None
+ applied: bool
+ message: str
+
+
+async def pull_code(
+ pool: SshPtyPool,
+ local_folder: Path,
+ remote_folder: str,
+ offload_snapshot: str | None,
+ computer_name: str,
+) -> Return:
+ """Bring the server's version of the folder back."""
+ top = await asyncio.to_thread(git_toplevel, local_folder)
+ if top is None or offload_snapshot is None:
+ return Return(
+ branch=None,
+ applied=False,
+ message="This folder has no git history, so the server's copy stays on the server.",
+ )
+ home = await pool.home()
+ code, remote_top, _ = await pool.run(
+ f"cd {shlex.quote(remote_folder)} && git rev-parse --show-toplevel", timeout_s=30
+ )
+ remote_top = remote_top.strip()
+ if code != 0 or not remote_top:
+ raise MoveError("The server's copy of this folder is gone.")
+ transfer = uuid.uuid4().hex[:12]
+ ref = f"refs/jarvis/return/{transfer}"
+ remote_bundle = f"{home}/{SYNC_DIR}/{transfer}.bundle"
+ script = _PACK.format(
+ dest=shlex.quote(remote_top),
+ ref=shlex.quote(ref),
+ sync=shlex.quote(f"{home}/{SYNC_DIR}"),
+ bundle=shlex.quote(remote_bundle),
+ exclude=shlex.quote(f"^{offload_snapshot}"),
+ )
+ code, out, err = await pool.run(script, timeout_s=600)
+ lines = [line for line in out.split() if re.fullmatch(r"[0-9a-f]{40}", line)]
+ if code != 0 or not lines:
+ raise MoveError(f"The server's work could not be packed: {(err or out).strip()[-200:]}")
+ remote_snap = lines[-1]
+ with tempfile.TemporaryDirectory(prefix="jarvis-return-") as tmp:
+ bundle = Path(tmp) / "return.bundle"
+ await _download(pool, remote_bundle, bundle)
+ await pool.run(f"rm -f {shlex.quote(remote_bundle)}", timeout_s=30)
+ await asyncio.to_thread(_git, top, "fetch", "-q", str(bundle), f"{ref}:{ref}")
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ branch = f"jarvis/{_slug(computer_name)}/{stamp}"
+ await asyncio.to_thread(_git, top, "branch", branch, remote_snap)
+ offload_tree = await asyncio.to_thread(_git, top, "rev-parse", f"{offload_snapshot}^{{tree}}")
+ current_tree = await asyncio.to_thread(working_tree_id, top)
+ if current_tree != offload_tree:
+ return Return(
+ branch=branch,
+ applied=False,
+ message=(
+ f"This folder changed while the work was away, so nothing was overwritten. "
+ f"The server's work is on the branch {branch}."
+ ),
+ )
+ patch = await asyncio.to_thread(_git, top, "diff", "--binary", offload_snapshot, remote_snap)
+ if patch:
+ try:
+ await asyncio.to_thread(
+ _git, top, "apply", "--whitespace=nowarn", stdin=(patch + "\n").encode("utf-8")
+ )
+ except MoveError as exc:
+ return Return(branch=branch, applied=False, message=f"{exc} The work is on {branch}.")
+ return Return(
+ branch=branch,
+ applied=True,
+ message="The server's changes are back in this folder (also kept on " + branch + ").",
+ )
+
+
+# ---------------------------------------------------------------------------
+# conversations
+# ---------------------------------------------------------------------------
+
+
+def claude_project_dir(cwd: str) -> str:
+ """Claude Code's folder name for a working directory."""
+ return re.sub(r"[^A-Za-z0-9]", "-", cwd)
+
+
+def _claude_home(override: Path | None) -> Path:
+ if override is not None:
+ return override
+ raw = os.environ.get("CLAUDE_CONFIG_DIR")
+ return Path(raw).expanduser() if raw else Path.home() / ".claude"
+
+
+def _codex_home(override: Path | None) -> Path:
+ if override is not None:
+ return override
+ raw = os.environ.get("CODEX_HOME")
+ return Path(raw).expanduser() if raw else Path.home() / ".codex"
+
+
+def find_local_transcript(
+ agent: str, conversation_id: str, home: Path | None
+) -> tuple[Path, str] | None:
+ """The local transcript file and its path relative to the CLI home."""
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", conversation_id or ""):
+ return None
+ if agent == "claude":
+ root = _claude_home(home)
+ match = next((root / "projects").glob(f"*/{conversation_id}.jsonl"), None)
+ return (match, "") if match else None
+ if agent == "codex":
+ root = _codex_home(home)
+ match = next((root / "sessions").glob(f"*/*/*/rollout-*{conversation_id}*.jsonl"), None)
+ if match:
+ return match, match.relative_to(root).as_posix()
+ return None
+
+
+async def push_conversation(
+ pool: SshPtyPool, agent: str, conversation_id: str | None, remote_cwd: str, home: Path | None
+) -> bool:
+ """Copy a conversation to the server so ``--resume`` finds it there."""
+ if not conversation_id:
+ return False
+ found = await asyncio.to_thread(find_local_transcript, agent, conversation_id, home)
+ if found is None:
+ log.info("agentic-ide: no local %s transcript for %s to move", agent, conversation_id)
+ return False
+ path, relative = found
+ remote_home = await pool.home()
+ if agent == "claude":
+ project = claude_project_dir(remote_cwd)
+ target = f"{remote_home}/.claude/projects/{project}/{conversation_id}.jsonl"
+ else:
+ target = f"{remote_home}/.codex/{relative}"
+ await _upload(pool, path, target)
+ return True
+
+
+async def pull_conversation(
+ pool: SshPtyPool,
+ agent: str,
+ conversation_id: str | None,
+ local_cwd: Path,
+ home: Path | None,
+) -> bool:
+ """Copy the server's transcript back so the local ``--resume`` continues it."""
+ if not conversation_id or not re.fullmatch(r"[A-Za-z0-9._-]+", conversation_id):
+ return False
+ remote_home = await pool.home()
+ if agent == "claude":
+ code, out, _ = await pool.run(
+ f"ls {shlex.quote(remote_home)}/.claude/projects/*/{conversation_id}.jsonl "
+ "2>/dev/null | head -n 1"
+ )
+ remote = out.strip()
+ if code != 0 or not remote:
+ return False
+ target = (
+ _claude_home(home)
+ / "projects"
+ / claude_project_dir(str(local_cwd))
+ / f"{conversation_id}.jsonl"
+ )
+ elif agent == "codex":
+ code, out, _ = await pool.run(
+ f"cd {shlex.quote(remote_home)}/.codex 2>/dev/null && "
+ f"ls sessions/*/*/*/rollout-*{conversation_id}*.jsonl 2>/dev/null | head -n 1"
+ )
+ relative = out.strip()
+ if code != 0 or not relative:
+ return False
+ remote = f"{remote_home}/.codex/{relative}"
+ target = _codex_home(home) / relative
+ else:
+ return False
+ target.parent.mkdir(parents=True, exist_ok=True)
+ await _download(pool, remote, target)
+ return True
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index 959c82a280..014ab8c468 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -106,6 +106,13 @@ class SnapshotTerminal:
# process started; kept here so a fork that never got to start before a
# restart still starts as the copy it was opened as.
fork_from: ResumeHandle | None = None
+ # A pane placed on a connected computer (Computers): that computer's id,
+ # the folder its agent runs in there, and the snapshot commit the code
+ # left this machine as (what "bring back" compares against). Empty on
+ # older snapshots and on every pane running on this machine.
+ computer_id: str = ""
+ remote_folder: str = ""
+ offload_snapshot: str = ""
# Was this pane's agent running when the snapshot was written? A reboot
# brings back exactly those (``Registry._resume_after_reboot``); an agent
# that ended by itself — ``/exit``, a finished one-shot — stays ended.
@@ -133,6 +140,9 @@ class SnapshotTerminal:
"folder": self.folder,
"branch": self.branch,
"fork_from": self.fork_from.to_dict() if self.fork_from else None,
+ "computer_id": self.computer_id,
+ "remote_folder": self.remote_folder,
+ "offload_snapshot": self.offload_snapshot,
"running": self.running,
}
@@ -167,6 +177,9 @@ class SnapshotTerminal:
folder=str(data.get("folder") or "").strip(),
branch=str(data.get("branch") or "").strip(),
fork_from=ResumeHandle.from_dict(data.get("fork_from")),
+ computer_id=str(data.get("computer_id") or "").strip(),
+ remote_folder=str(data.get("remote_folder") or "").strip(),
+ offload_snapshot=str(data.get("offload_snapshot") or "").strip(),
running=data.get("running") is not False,
)
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 2f62bb5627..0fb2786e68 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -65,6 +65,7 @@ import asyncio
import hashlib
import os
import re
+import shlex
import shutil
import sys
import threading
@@ -81,7 +82,16 @@ from loguru import logger
from jarvis.workspace import agents as workspace_agents
from jarvis.workspace import launch_picks
-from . import fork, layout_tree, library, opening, prompt_history, recap_engine, resume_store
+from . import (
+ fork,
+ layout_tree,
+ library,
+ opening,
+ prompt_history,
+ recap_engine,
+ remote,
+ resume_store,
+)
from .activity import NO_READING, Reading, has_work_behind_it, observed
from .agent_sessions import (
ResumeHandle,
@@ -799,6 +809,28 @@ def account_home(agent: str, account_id: str | None) -> Path | None:
return agent_accounts.config_dir_for(agent, account_id) # type: ignore[arg-type]
+def remote_agent_argv(agent: str) -> tuple[str, ...] | None:
+ """argv for ``agent`` on a connected computer (a POSIX server).
+
+ Resolved THERE, by the server's own PATH (the pane starts in a login
+ shell), so only the command name travels, never this machine's absolute
+ path or a Windows shim. A plain terminal is the server's login shell.
+ """
+ spec = workspace_agents.get_agent(agent)
+ if spec is None:
+ return None
+ if not spec.is_coding_agent:
+ return ("bash", "-l")
+ if spec.shell_launch:
+ return ("sh", "-c", spec.launch_command or "")
+ binary = spec.executable or spec.launch_command or spec.name
+ name = binary.replace("\\", "/").rsplit("/", 1)[-1]
+ for suffix in (".cmd", ".bat", ".exe", ".ps1"):
+ if name.lower().endswith(suffix):
+ name = name[: -len(suffix)]
+ return (name, *spec.launch_args)
+
+
def agent_argv(agent: str) -> tuple[str, ...] | None:
"""argv that runs ``agent`` as the PTY's own process, or None if missing.
@@ -994,6 +1026,14 @@ class Terminal:
# own handle in `resume`), so a restart afterwards resumes the copy rather
# than forking the original a second time.
fork_from: ResumeHandle | None = None
+ # Where this pane's agent RUNS when that is a connected computer rather
+ # than this machine (``jarvis.computers``): the computer's id, the folder
+ # there, and the snapshot commit the code left here as. The agent then
+ # lives in a tmux session on that computer and keeps working while this
+ # app is closed; this pane is only its viewer. Empty = this machine.
+ computer_id: str = ""
+ remote_folder: str = ""
+ offload_snapshot: str = ""
status: Status = "pending"
pty_id: str | None = None
# The geometry the PTY ACTUALLY holds, as last handed to `setwinsize`.
@@ -1371,6 +1411,9 @@ class Terminal:
# Set only for a pane running in a git worktree of its own.
"folder": self.folder,
"branch": self.branch,
+ # Set only for a pane running on a connected computer.
+ "computer_id": self.computer_id,
+ "remote_folder": self.remote_folder,
# Can this pane be forked with its conversation? False for a CLI
# without a fork of its own — the fork then starts a fresh chat.
"can_fork": can_fork(self.agent),
@@ -1467,6 +1510,9 @@ class Terminal:
folder=self.folder,
branch=self.branch,
fork_from=self.fork_from,
+ computer_id=self.computer_id,
+ remote_folder=self.remote_folder,
+ offload_snapshot=self.offload_snapshot,
running=self._counts_as_running(),
)
@@ -2093,6 +2139,14 @@ class Registry:
logger.info("Agentic IDE: new {} terminals will use {!r}", agent, account.label)
return account
+ def _pool(self, term: Terminal) -> Any:
+ """The pool that owns ``term``'s process: its computer's, else this machine's."""
+ if term.computer_id:
+ from jarvis.computers.remote_terminal import pool_for
+
+ return pool_for(term.computer_id)
+ return self._manager()
+
def _manager(self) -> PtyManager:
if self._pty is None:
# Lazy: keeps the terminal stack off the import/boot path (AP-26).
@@ -2387,7 +2441,7 @@ class Registry:
by_history = self._hosted_for(manager)
for term in session.terminals:
info = by_history.pop(term.history_id, None)
- if info is not None:
+ if info is not None and not term.computer_id:
await self._adopt_one(manager, term, info)
async def _adopt_one(self, manager: Any, term: Terminal, info: Any) -> bool:
@@ -2977,6 +3031,9 @@ class Registry:
folder=entry.folder if entry.folder and Path(entry.folder).is_dir() else "",
branch=entry.branch if entry.folder and Path(entry.folder).is_dir() else "",
fork_from=entry.fork_from,
+ computer_id=entry.computer_id,
+ remote_folder=entry.remote_folder,
+ offload_snapshot=entry.offload_snapshot,
was_running=entry.running,
)
@@ -3308,11 +3365,12 @@ class Registry:
term.viewer_exit = None
term.watchers.clear()
term.prompt_viewers.clear()
- if manager is not None:
- for term in session.terminals:
+ for term in session.terminals:
+ owner = self._pool(term) if term.computer_id else manager
+ if owner is not None:
if term.pty_id:
try:
- manager.close(term.pty_id)
+ owner.close(term.pty_id)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
# Its pane notifications go with it. Each one is a "jump to this pane"
@@ -3713,8 +3771,10 @@ 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 not (term.pty_id and manager.has(term.pty_id)):
+ # A pane on a connected computer is driven by that computer's SSH pool;
+ # everything below (re-join, replay, resume) is the same path.
+ manager = self._pool(term) if term.computer_id else await self._live_manager()
+ if not term.computer_id and not (term.pty_id and manager.has(term.pty_id)):
# Herdr's rule: attach to the running session first, start one only
# when there is none. The host may still hold this pane's agent
# from before the app restarted — whichever path restored the pane.
@@ -3793,7 +3853,7 @@ class Registry:
logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
return term
- argv = agent_argv(term.agent)
+ argv = remote_agent_argv(term.agent) if term.computer_id else agent_argv(term.agent)
if argv is None:
term.status = "error"
term.error = f"{term.display_name} is not on PATH."
@@ -3822,8 +3882,12 @@ class Registry:
# takes the same call to a thread for the same reason.
home = account_home(term.agent, term.account)
continuing = resume_argv(term.agent, term.resume)
- if continuing is not None and not await asyncio.to_thread(
- has_conversation, term.agent, term.resume, home
+ # A remote pane's history lives on that computer; its handle was
+ # carried there with it (``remote.push_conversation``), so trust it.
+ if (
+ continuing is not None
+ and not term.computer_id
+ and not await asyncio.to_thread(has_conversation, term.agent, term.resume, home)
):
logger.info(
"Agentic IDE: {} has no conversation to continue — starting fresh",
@@ -3841,7 +3905,9 @@ class Registry:
if continuing is None and term.fork_from is not None:
source = term.fork_from
term.fork_from = None
- if await asyncio.to_thread(has_conversation, term.agent, source, home):
+ if not term.computer_id and await asyncio.to_thread(
+ has_conversation, term.agent, source, home
+ ):
forking = fork_argv(term.agent, source)
if forking is None:
logger.info(
@@ -4015,7 +4081,11 @@ class Registry:
# claimed to be starting forever, with the actual reason living only in
# a socket frame the pane painted over a moment later.
try:
- if redirected_home is None:
+ if term.computer_id:
+ # The CLI's account, config and env are the SERVER's own;
+ # nothing of this machine's setup applies there.
+ env: dict[str, str] | None = {}
+ elif redirected_home is None:
env = await asyncio.to_thread(self._prepare_spawn, term, term.cwd(session.folder))
else:
account_key = os.path.normcase(str(redirected_home))
@@ -4063,7 +4133,11 @@ class Registry:
pty_session = await manager.spawn(
shell_argv=argv,
shell_id=f"agentic-ide:{term.key}",
- cwd=term.cwd(session.folder),
+ cwd=(
+ term.remote_folder or term.cwd(session.folder)
+ if term.computer_id
+ else term.cwd(session.folder)
+ ),
cols=cols,
rows=rows,
on_output=_output,
@@ -4090,7 +4164,7 @@ class Registry:
"agent": term.agent,
}
}
- if getattr(manager, "persistent", False)
+ if getattr(manager, "persistent", False) or term.computer_id
else {}
),
)
@@ -4159,9 +4233,10 @@ class Registry:
)
finally:
agent_start_gate.release()
- if term.resume is None and can_resume(term.agent):
+ if term.resume is None and can_resume(term.agent) and not term.computer_id:
# A CLI that cannot be told its session id (Codex): find out which
- # one it just created, shortly from now.
+ # one it just created, shortly from now. (Not on a remote pane:
+ # its history is on that computer, not in this machine's folders.)
self._schedule_lookup(session, term, term.cwd(session.folder), term.started_at)
if term.continue_when_ready:
# Somebody pressed "Continue" while this pane was still waiting for
@@ -4399,7 +4474,7 @@ class Registry:
owner, term = found
if not term.pty_id:
return False
- manager = self._manager()
+ manager = self._pool(term)
if is_pointer_noise_only(data):
# A wheel tick, a click, a focus flip: the terminal talking, not a
# person typing. It echoes nothing, so it must not arm the typing
@@ -4595,7 +4670,7 @@ class Registry:
pty_id = term.pty_id
if not pty_id:
return False
- manager = self._manager()
+ manager = self._pool(term)
try:
# The whole point of the nudge is a full repaint — which must read
# as the redraw it is, not as the agent suddenly working. Stamped
@@ -4788,7 +4863,7 @@ class Registry:
# transcript keeps wrapping at the old width.
if (term.transcript.cols, term.transcript.rows) == (cols, rows):
return True
- if not self._manager().resize(term.pty_id, cols, rows):
+ if not self._pool(term).resize(term.pty_id, cols, rows):
return False
term.pty_cols, term.pty_rows = cols, rows
# The TUI answers the new size with a full redraw — shadow it so a
@@ -5097,6 +5172,194 @@ class Registry:
"has_conversation": term.resume is not None,
}
+ # ------------------------------------------------------------ placement
+ async def place_terminal(
+ self, key: str, *, workspace_id: str | None, computer_id: str | None
+ ) -> dict[str, Any]:
+ """Run pane ``key`` on ``computer_id`` from now on (``None`` = this machine).
+
+ To a computer ("offload"): the pane's folder travels as it is, uncommitted
+ edits included, its conversation is copied so the agent continues with
+ ``--resume``, the local process ends and the agent starts again THERE,
+ inside tmux, where it keeps running while this app is closed.
+
+ Back ("bring back"): the agent on the server ends, the server's work and
+ the conversation come home (``remote.pull_code`` never overwrites local
+ changes made meanwhile), and the pane runs here again.
+
+ A pane that is not running just changes place; it starts there on its
+ next attach.
+ """
+ found = self._locate(key, workspace_id)
+ if found is None:
+ raise SessionError(f"Unknown terminal: {key}")
+ session, term = found
+ target = computer_id or ""
+ if term.computer_id == target:
+ return {"moved": False, "message": "The pane already runs there."}
+ async with term.attach_lock:
+ was_live = bool(term.pty_id)
+ if target:
+ message = await self._offload_locked(session, term, target, {})
+ else:
+ message = await self._bring_back_locked(session, term)
+ if was_live:
+ await self._restart_in_place(session, term)
+ await self._persist()
+ return {"moved": True, "message": message, "terminal": term.to_dict()}
+
+ async def place_workspace(
+ self, workspace_id: str, *, computer_id: str | None
+ ) -> dict[str, Any]:
+ """Move every pane of a workspace, one folder transfer per folder."""
+ session = self.get(workspace_id)
+ if session is None:
+ raise SessionError("Unknown workspace.")
+ target = computer_id or ""
+ placements: dict[str, remote.Placement] = {}
+ moved: list[str] = []
+ messages: list[str] = []
+ for term in list(session.terminals):
+ if term.computer_id == target:
+ continue
+ async with term.attach_lock:
+ was_live = bool(term.pty_id)
+ if target:
+ message = await self._offload_locked(session, term, target, placements)
+ else:
+ message = await self._bring_back_locked(session, term)
+ if was_live:
+ await self._restart_in_place(session, term)
+ moved.append(term.key)
+ if message and message not in messages:
+ messages.append(message)
+ await self._persist()
+ return {"moved": moved, "messages": messages}
+
+ async def _stop_for_move(self, term: Terminal, pool: Any) -> None:
+ """End the pane's current process and wait until its exit is recorded."""
+ if not term.pty_id or pool is None:
+ return
+ term.stopping = True
+ try:
+ pool.close(term.pty_id)
+ except Exception as exc: # noqa: BLE001 - the move proceeds; the process is gone or going
+ logger.info("Agentic IDE: stopping {} for a move: {}", term.name, exc)
+ # A local PTY reports its exit through `_closed`, which clears
+ # `pty_id` and must land BEFORE the new process is recorded. A remote
+ # pool's close is final at once and reports nothing.
+ if not getattr(pool, "computer_id", None):
+ for _ in range(50):
+ if term.pty_id is None:
+ break
+ await asyncio.sleep(0.1)
+ term.pty_id = None
+
+ async def _offload_locked(
+ self,
+ session: Session,
+ term: Terminal,
+ computer_id: str,
+ placements: dict[str, remote.Placement],
+ ) -> str:
+ from jarvis.computers.remote_terminal import pool_for
+
+ pool = pool_for(computer_id)
+ local_folder = Path(term.cwd(session.folder))
+ folder_key = os.path.normcase(str(local_folder))
+ try:
+ placement = placements.get(folder_key)
+ if placement is None:
+ placement = await remote.push_code(pool, local_folder)
+ placements[folder_key] = placement
+ carried = await remote.push_conversation(
+ pool,
+ term.agent,
+ term.resume.id if term.resume else None,
+ placement.remote_folder,
+ account_home(term.agent, term.account),
+ )
+ except remote.MoveError as exc:
+ raise SessionError(str(exc)) from exc
+ except Exception as exc: # noqa: BLE001 - SSH/SFTP failures become one sentence
+ logger.warning("Agentic IDE: moving {} failed: {}", term.name, exc)
+ raise SessionError(f"The move failed: {exc}") from exc
+ if term.computer_id:
+ await self._stop_for_move(term, pool_for(term.computer_id))
+ else:
+ await self._stop_for_move(term, self._pty)
+ if not carried:
+ # Nothing to continue from on the server: start clean there rather
+ # than asking the CLI for a conversation it does not have.
+ term.resume = None
+ term.computer_id = computer_id
+ term.remote_folder = placement.remote_folder
+ term.offload_snapshot = placement.offload_snapshot or ""
+ return (
+ "Moved with its conversation." if carried else "Moved; the agent starts fresh there."
+ )
+
+ async def _bring_back_locked(self, session: Session, term: Terminal) -> str:
+ from jarvis.computers.remote_terminal import pool_for, tmux_session_name
+ from jarvis.computers.service import get_service
+
+ pool = pool_for(term.computer_id)
+ if term.pty_id:
+ await self._stop_for_move(term, pool)
+ else:
+ await pool.run(
+ f"tmux kill-session -t {shlex.quote(tmux_session_name(term.history_id))}"
+ " 2>/dev/null; true",
+ timeout_s=20,
+ )
+ local_folder = Path(term.cwd(session.folder))
+ try:
+ name = get_service().get(term.computer_id).name
+ except Exception: # noqa: BLE001 - a removed computer still has a branch name
+ name = "server"
+ try:
+ outcome = await remote.pull_code(
+ pool, local_folder, term.remote_folder, term.offload_snapshot or None, name
+ )
+ carried = await remote.pull_conversation(
+ pool,
+ term.agent,
+ term.resume.id if term.resume else None,
+ local_folder,
+ account_home(term.agent, term.account),
+ )
+ except remote.MoveError as exc:
+ raise SessionError(str(exc)) from exc
+ except Exception as exc: # noqa: BLE001 - SSH/SFTP failures become one sentence
+ logger.warning("Agentic IDE: bringing {} back failed: {}", term.name, exc)
+ raise SessionError(f"Bringing the pane back failed: {exc}") from exc
+ if not carried:
+ term.resume = None
+ term.computer_id = ""
+ term.remote_folder = ""
+ term.offload_snapshot = ""
+ return outcome.message
+
+ async def _restart_in_place(self, session: Session, term: Terminal) -> None:
+ """Start the pane's agent in its new place for whoever is watching it."""
+
+ async def _discard(_data: Any) -> None:
+ return None
+
+ term.status = "pending"
+ term.stopping = False
+ try:
+ await self._attach_locked(
+ term.key,
+ term.pty_cols or term.transcript.cols,
+ term.pty_rows or term.transcript.rows,
+ term.viewer_output or _discard,
+ term.viewer_exit or _discard,
+ workspace_id=session.id,
+ )
+ except SessionError as exc:
+ logger.warning("Agentic IDE: {} did not start after its move: {}", term.name, exc)
+
async def fork_terminal(
self,
wanted: str,
@@ -5505,9 +5768,10 @@ class Registry:
for term in resolved:
term.stopping = True # a deliberate kill, not a crashed resume
- if term.pty_id and self._pty is not None:
+ pool = self._pool(term) if term.computer_id else self._pty
+ if term.pty_id and pool is not None:
try:
- self._pty.close(term.pty_id)
+ pool.close(term.pty_id)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
term.pty_id = None
@@ -5752,7 +6016,7 @@ class Registry:
not in (("asking", "waiting") if allow_question else ("waiting",))
):
raise SessionError("The input request changed while waiting; nothing was sent.")
- manager = self._manager()
+ manager = self._pool(term)
multiline = "\n" in payload
submitted = await self._write_and_confirm(term, payload, manager, multiline)
@@ -5932,7 +6196,7 @@ class Registry:
if term.name not in ready:
declined[pick] = f"{term.name} is still starting — its input line never appeared."
continue
- submitted = await self._write_and_confirm(term, line, self._manager(), False)
+ submitted = await self._write_and_confirm(term, line, self._pool(term), False)
if submitted is False:
declined[pick] = f"{term.name} kept `{line}` in its input box instead of taking it."
continue
diff --git a/jarvis/computers/remote_terminal.py b/jarvis/computers/remote_terminal.py
new file mode 100644
index 0000000000..a340a65c04
--- /dev/null
+++ b/jarvis/computers/remote_terminal.py
@@ -0,0 +1,385 @@
+"""Terminals that live on a connected computer, driven over SSH.
+
+The Agentic IDE's panes normally run in a PTY on this machine. A pane placed
+on a computer (a VPS, a local VM) runs its agent there instead, inside a
+**tmux session on the server** — the server owns the process, the app is only
+a viewer. That is the one property that matters: closing the app, losing the
+network or shutting this PC down detaches the viewer and nothing else; the
+agent keeps working, and the next attach re-joins the same session
+(``tmux new-session -A``), screen included.
+
+:class:`SshPtyPool` speaks the same small interface the IDE's registry uses
+for its local pool — ``spawn`` / ``write`` / ``resize`` / ``close`` / ``has``
+— so a remote pane goes through the exact same attach path as a local one.
+One SSH connection per computer carries every pane's channel.
+
+A dropped connection is not an exit: the pool reconnects with jittered backoff
+(AP-33) and re-attaches to the still-running tmux session. Only a session that
+is really gone on the server reports the pane closed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+import random
+import re
+import shlex
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+from jarvis.computers.service import ComputerError, get_service
+from jarvis.computers.ssh import Session, close
+
+log = logging.getLogger(__name__)
+
+OutputCallback = Callable[[str, str], Awaitable[None]]
+ClosedCallback = Callable[[str, int], Awaitable[None]]
+ProbeCallback = Callable[[str], str]
+
+#: Reconnect delays after a dropped connection; jittered, then given up.
+RECONNECT_DELAYS_S = (1.0, 2.0, 4.0, 8.0, 15.0, 30.0)
+_NAME_RE = re.compile(r"[^A-Za-z0-9_-]")
+
+
+def tmux_session_name(identity: str) -> str:
+ """A tmux-safe, stable session name for one pane."""
+ return "jv-" + _NAME_RE.sub("-", identity)[:48]
+
+
+def tmux_command(
+ name: str, argv: tuple[str, ...] | list[str], cwd: str, cols: int, rows: int
+) -> str:
+ """Create-or-attach the pane's tmux session, quiet and full-screen.
+
+ ``-A`` attaches when the session already exists, so the same command both
+ starts a new agent and re-joins a running one; the agent's argv is only
+ used for a new session. The status line and mouse capture are off — the
+ pane is the agent's screen, not tmux's.
+ """
+ agent = shlex.join(argv)
+ session = shlex.quote(name)
+ return (
+ f"tmux -u new-session -A -s {session} -x {cols} -y {rows} -c {shlex.quote(cwd)} "
+ f"{shlex.quote(agent)} "
+ f"\\; set-option -t {session} status off "
+ f"\\; set-option -t {session} mouse off "
+ f"\\; set-option -t {session} escape-time 0"
+ )
+
+
+def login_shell(command: str) -> str:
+ """Run through a login shell so user-installed CLIs (npm, nvm) are on PATH."""
+ quoted = shlex.quote(command)
+ return (
+ "if command -v bash >/dev/null 2>&1; "
+ f"then exec bash -lc {quoted}; else exec sh -lc {quoted}; fi"
+ )
+
+
+@dataclass
+class _Pane:
+ terminal_id: str
+ tmux_name: str
+ command: str
+ cols: int
+ rows: int
+ on_output: OutputCallback
+ on_closed: ClosedCallback
+ on_probe: ProbeCallback | None
+ process: Any = None
+ pump: asyncio.Task[None] | None = None
+ closing: bool = False
+ exit_status: int | None = field(default=None)
+
+
+@dataclass(frozen=True)
+class RemoteSpawn:
+ """What ``spawn`` hands back — the registry reads ``terminal_id`` only."""
+
+ terminal_id: str
+
+
+class SshPtyPool:
+ """Every remote pane of ONE computer, over one shared SSH connection."""
+
+ #: Not the local PTY host: the registry's host-only paths skip this pool.
+ persistent = False
+
+ def __init__(
+ self, computer_id: str, *, connect: Callable[[], Awaitable[Session]] | None = None
+ ) -> None:
+ self.computer_id = computer_id
+ self._connect_fn = connect or (lambda: get_service().connect(computer_id))
+ self._session: Session | None = None
+ self._home: str | None = None
+ self._lock = asyncio.Lock()
+ self._panes: dict[str, _Pane] = {}
+ self._tmux_checked = False
+
+ # -- connection ----------------------------------------------------------
+
+ async def connection(self) -> Session:
+ async with self._lock:
+ session = self._session
+ if session is not None and not session.conn.is_closed():
+ return session
+ self._session = await self._connect_fn()
+ return self._session
+
+ async def home(self) -> str:
+ """The remote user's home directory (absolute), cached per connection."""
+ if self._home is None:
+ session = await self.connection()
+ result = await session.conn.run('printf %s "$HOME"', check=False)
+ self._home = str(result.stdout or "").strip() or "/root"
+ return self._home
+
+ async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
+ """One non-interactive command on the shared connection."""
+ session = await self.connection()
+ result = await asyncio.wait_for(
+ session.conn.run(login_shell(command), check=False, encoding="utf-8", errors="replace"),
+ timeout=timeout_s,
+ )
+ code = result.exit_status if result.exit_status is not None else -1
+ return code, str(result.stdout or ""), str(result.stderr or "")
+
+ # -- the pool interface ----------------------------------------------------
+
+ async def spawn(
+ self,
+ shell_argv: tuple[str, ...] | list[str],
+ shell_id: str,
+ cwd: str,
+ cols: int,
+ rows: int,
+ on_output: OutputCallback,
+ on_closed: ClosedCallback,
+ env: dict[str, str] | None = None,
+ on_probe: ProbeCallback | None = None,
+ meta: dict[str, Any] | None = None,
+ ) -> RemoteSpawn:
+ """Start (or re-join) the pane's tmux session and stream it."""
+ identity = str((meta or {}).get("history_id") or shell_id)
+ name = tmux_session_name(identity)
+ pane = _Pane(
+ terminal_id=shell_id,
+ tmux_name=name,
+ command=login_shell(tmux_command(name, tuple(shell_argv), cwd, cols, rows)),
+ cols=cols,
+ rows=rows,
+ on_output=on_output,
+ on_closed=on_closed,
+ on_probe=on_probe,
+ )
+ if not self._tmux_checked:
+ code, _out, _err = await self.run("command -v tmux >/dev/null", timeout_s=20)
+ if code != 0:
+ raise ComputerError(
+ "tmux is not installed on this computer. Open Computers, then Prepare.",
+ status=409,
+ )
+ self._tmux_checked = True
+ previous = self._panes.pop(shell_id, None)
+ if previous is not None:
+ self._drop(previous)
+ await self._open(pane)
+ self._panes[shell_id] = pane
+ pane.pump = asyncio.create_task(self._pump(pane), name=f"ssh-pty-{name}")
+ return RemoteSpawn(terminal_id=shell_id)
+
+ def has(self, terminal_id: str) -> bool:
+ pane = self._panes.get(terminal_id)
+ return pane is not None and not pane.closing
+
+ def write(self, terminal_id: str, data: str) -> bool:
+ pane = self._panes.get(terminal_id)
+ if pane is None or pane.process is None or pane.closing:
+ return False
+ try:
+ pane.process.stdin.write(data)
+ except Exception as exc: # noqa: BLE001 — a dead channel is reported, not raised
+ log.debug("computers: remote write to %s failed: %s", pane.tmux_name, exc)
+ return False
+ return True
+
+ def resize(self, terminal_id: str, cols: int, rows: int) -> bool:
+ pane = self._panes.get(terminal_id)
+ if pane is None or pane.process is None:
+ return False
+ pane.cols, pane.rows = cols, rows
+ try:
+ pane.process.change_terminal_size(cols, rows)
+ except Exception as exc: # noqa: BLE001 — resize of a closing channel is moot
+ log.debug("computers: remote resize of %s failed: %s", pane.tmux_name, exc)
+ return False
+ return True
+
+ def close(self, terminal_id: str) -> None:
+ """End the pane for good: kill its tmux session on the server."""
+ pane = self._panes.pop(terminal_id, None)
+ if pane is None:
+ return
+ pane.closing = True
+ self._drop(pane)
+ task = asyncio.get_running_loop().create_task(
+ self._kill_session(pane.tmux_name), name=f"ssh-pty-kill-{pane.tmux_name}"
+ )
+ task.add_done_callback(_log_task_failure)
+
+ def detach(self, terminal_id: str) -> None:
+ """Stop viewing the pane; the agent keeps running on the server."""
+ pane = self._panes.pop(terminal_id, None)
+ if pane is not None:
+ pane.closing = True
+ self._drop(pane)
+
+ def close_all(self) -> None:
+ """Detach every pane (never kills: the server owns the agents)."""
+ for terminal_id in list(self._panes):
+ self.detach(terminal_id)
+ if self._session is not None:
+ close(self._session)
+ self._session = None
+
+ def swap_sessions(self, first: str, second: str) -> None:
+ a, b = self._panes.get(first), self._panes.get(second)
+ if a is not None:
+ a.terminal_id = second
+ if b is not None:
+ b.terminal_id = first
+ self._panes[first], self._panes[second] = b, a # type: ignore[assignment]
+ for key in (first, second):
+ if self._panes.get(key) is None:
+ self._panes.pop(key, None)
+
+ # -- internals ---------------------------------------------------------------
+
+ async def _open(self, pane: _Pane) -> None:
+ session = await self.connection()
+ pane.process = await session.conn.create_process(
+ pane.command,
+ term_type="xterm-256color",
+ term_size=(pane.cols, pane.rows),
+ encoding="utf-8",
+ errors="replace",
+ )
+
+ def _drop(self, pane: _Pane) -> None:
+ if pane.pump is not None and pane.pump is not asyncio.current_task():
+ pane.pump.cancel()
+ if pane.process is not None:
+ with contextlib.suppress(Exception):
+ pane.process.close()
+
+ async def _kill_session(self, name: str) -> None:
+ with contextlib.suppress(Exception):
+ await self.run(f"tmux kill-session -t {shlex.quote(name)}", timeout_s=15)
+
+ async def _session_alive(self, name: str) -> bool | None:
+ """True/False from the server; None when the server cannot be asked."""
+ try:
+ code, _out, _err = await self.run(
+ f"tmux has-session -t {shlex.quote(name)}", timeout_s=15
+ )
+ except (ComputerError, OSError, TimeoutError) as exc:
+ log.debug("computers: cannot ask for tmux session %s: %s", name, exc)
+ return None
+ except Exception as exc: # noqa: BLE001 — asyncssh errors: treat as unreachable
+ log.debug("computers: cannot ask for tmux session %s: %s", name, exc)
+ return None
+ return code == 0
+
+ async def _pump(self, pane: _Pane) -> None:
+ """Stream output; on EOF decide between "exited" and "reconnect"."""
+ while True:
+ lost = False
+ try:
+ while True:
+ chunk = await pane.process.stdout.read(8192)
+ if not chunk:
+ break
+ if pane.on_probe is not None:
+ reply = ""
+ with contextlib.suppress(Exception):
+ reply = pane.on_probe(chunk)
+ if reply:
+ self.write(pane.terminal_id, reply)
+ await pane.on_output(pane.terminal_id, chunk)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — a broken channel ends in the checks below
+ log.info("computers: remote pane %s stream ended: %s", pane.tmux_name, exc)
+ lost = True
+ if pane.closing:
+ return
+ if lost:
+ # The connection itself is gone; asking the server anything on
+ # it would hang until a timeout. Start the next call afresh.
+ await self._forget_connection()
+ with contextlib.suppress(Exception):
+ pane.exit_status = pane.process.exit_status
+ alive = await self._session_alive(pane.tmux_name)
+ if alive is False:
+ await self._finish(pane, pane.exit_status or 0)
+ return
+ # The agent is still there (or the server is unreachable right now):
+ # this was the network, not the agent. Re-attach.
+ if not await self._reattach(pane):
+ await self._finish(pane, 255)
+ return
+
+ async def _reattach(self, pane: _Pane) -> bool:
+ for delay in RECONNECT_DELAYS_S:
+ if pane.closing:
+ return False
+ await asyncio.sleep(delay * random.uniform(0.7, 1.3)) # noqa: S311 — jitter, not crypto
+ await self._forget_connection()
+ try:
+ await self._open(pane)
+ except Exception as exc: # noqa: BLE001 — retried with backoff
+ log.info("computers: re-attaching %s failed: %s", pane.tmux_name, exc)
+ continue
+ log.info("computers: re-attached remote pane %s", pane.tmux_name)
+ return True
+ return False
+
+ async def _forget_connection(self) -> None:
+ async with self._lock:
+ if self._session is not None:
+ close(self._session)
+ self._session = None
+
+ async def _finish(self, pane: _Pane, code: int) -> None:
+ if self._panes.get(pane.terminal_id) is pane:
+ self._panes.pop(pane.terminal_id, None)
+ pane.closing = True
+ try:
+ await pane.on_closed(pane.terminal_id, code)
+ except Exception:
+ log.warning("computers: closing callback for %s failed", pane.tmux_name, exc_info=True)
+
+
+def _log_task_failure(task: asyncio.Task[None]) -> None:
+ if not task.cancelled() and task.exception() is not None:
+ log.info("computers: background tmux call failed: %s", task.exception())
+
+
+_POOLS: dict[str, SshPtyPool] = {}
+
+
+def pool_for(computer_id: str) -> SshPtyPool:
+ """The one pool per computer (panes of all workspaces share it)."""
+ pool = _POOLS.get(computer_id)
+ if pool is None:
+ pool = _POOLS[computer_id] = SshPtyPool(computer_id)
+ return pool
+
+
+def forget_pool(computer_id: str) -> None:
+ pool = _POOLS.pop(computer_id, None)
+ if pool is not None:
+ pool.close_all()
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.py
index c2aca6f87d..ba29d54cc4 100644
--- a/jarvis/computers/service.py
+++ b/jarvis/computers/service.py
@@ -169,6 +169,21 @@ class ComputerService:
self._store.update(computer_id, change)
+ async def connect(self, computer_id: str) -> Session:
+ """A long-lived authenticated connection; the caller closes it.
+
+ For callers that keep a connection open across many channels (the IDE's
+ remote terminals). Pins the host key on first contact like
+ :meth:`session`.
+ """
+ computer = self.get(computer_id)
+ try:
+ opened = await open_session(self._target(computer))
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ self._pin(computer_id, opened)
+ return opened
+
@contextlib.asynccontextmanager
async def session(self, computer_id: str) -> AsyncIterator[Session]:
"""An authenticated connection; pins the host key on first contact."""
diff --git a/jarvis/computers/toolbox.py b/jarvis/computers/toolbox.py
new file mode 100644
index 0000000000..d74bd2d045
--- /dev/null
+++ b/jarvis/computers/toolbox.py
@@ -0,0 +1,287 @@
+"""What a computer needs before coding agents can run on it — and getting it there.
+
+A remote IDE pane needs ``tmux`` (the server owns the agent), ``git`` (the
+workspace travels as a git bundle) and the agent CLI itself, logged in. This
+module reads what is there in one command, installs what is missing ONLY when
+the user asks (herdr's rule: nothing is installed on a server unasked), and can
+copy this computer's CLI login to the server on an explicit click — never on
+its own.
+
+Installation is a background job with a log the UI polls, because a fresh VPS
+takes minutes to fetch Node and two npm packages.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shlex
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Literal
+
+from jarvis.computers.remote_terminal import login_shell
+from jarvis.computers.service import ComputerError, get_service
+
+log = logging.getLogger(__name__)
+
+ToolId = Literal["tmux", "git", "node", "claude", "codex"]
+AgentLogin = Literal["claude", "codex"]
+
+TOOLS: tuple[ToolId, ...] = ("tmux", "git", "node", "claude", "codex")
+
+_INSPECT = r"""
+for t in tmux git node npm claude codex; do
+ p=$(command -v "$t" 2>/dev/null)
+ if [ -n "$p" ]; then
+ v=$("$t" --version 2>/dev/null | head -n 1 | tr -d '\r')
+ echo "tool $t ok $v"
+ else
+ echo "tool $t missing"
+ fi
+done
+[ -f "$HOME/.claude/.credentials.json" ] && echo "login claude ok" || echo "login claude missing"
+[ -f "$HOME/.codex/auth.json" ] && echo "login codex ok" || echo "login codex missing"
+for m in apt-get dnf yum apk pacman brew; do
+ command -v "$m" >/dev/null 2>&1 && { echo "pkg $m"; break; }
+done
+echo "uid $(id -u)"
+command -v sudo >/dev/null 2>&1 && echo "sudo yes" || echo "sudo no"
+echo "os $(uname -s)"
+""".strip()
+
+_PACKAGES: dict[str, dict[str, str]] = {
+ "apt-get": {
+ "tmux": "tmux",
+ "git": "git",
+ "node": "nodejs npm",
+ "update": "apt-get update -qq",
+ "install": "DEBIAN_FRONTEND=noninteractive apt-get install -y -qq",
+ },
+ "dnf": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "dnf install -y -q"},
+ "yum": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "yum install -y -q"},
+ "apk": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "apk add --no-cache"},
+ "pacman": {
+ "tmux": "tmux",
+ "git": "git",
+ "node": "nodejs npm",
+ "install": "pacman -S --noconfirm",
+ },
+ "brew": {"tmux": "tmux", "git": "git", "node": "node", "install": "brew install"},
+}
+
+_NPM_PACKAGES: dict[str, str] = {
+ "claude": "@anthropic-ai/claude-code",
+ "codex": "@openai/codex",
+}
+
+_LOGIN_FILES: dict[str, str] = {
+ "claude": ".claude/.credentials.json",
+ "codex": ".codex/auth.json",
+}
+
+
+@dataclass
+class ToolState:
+ id: str
+ installed: bool
+ version: str | None = None
+
+
+@dataclass
+class Readiness:
+ tools: list[ToolState]
+ logins: dict[str, bool]
+ package_manager: str | None
+ root: bool
+ sudo: bool
+ os: str | None
+ #: Ready for at least one coding agent: tmux + git + a logged-in CLI.
+ ready: bool
+ checked_at: float = field(default_factory=time.time)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def parse_inspection(output: str) -> Readiness:
+ tools: dict[str, ToolState] = {}
+ logins: dict[str, bool] = {}
+ pkg: str | None = None
+ root = sudo = False
+ os_name: str | None = None
+ for raw in output.splitlines():
+ parts = raw.strip().split(" ", 3)
+ if not parts or not parts[0]:
+ continue
+ kind = parts[0]
+ if kind == "tool" and len(parts) >= 3:
+ version = parts[3].strip() if len(parts) > 3 else None
+ tools[parts[1]] = ToolState(parts[1], parts[2] == "ok", version or None)
+ elif kind == "login" and len(parts) >= 3:
+ logins[parts[1]] = parts[2] == "ok"
+ elif kind == "pkg" and len(parts) >= 2:
+ pkg = parts[1]
+ elif kind == "uid" and len(parts) >= 2:
+ root = parts[1] == "0"
+ elif kind == "sudo" and len(parts) >= 2:
+ sudo = parts[1] == "yes"
+ elif kind == "os" and len(parts) >= 2:
+ os_name = parts[1]
+ ordered = [tools.get(t, ToolState(t, False)) for t in TOOLS]
+ have = {t.id for t in ordered if t.installed}
+ ready = {"tmux", "git"} <= have and any(
+ agent in have and logins.get(agent, False) for agent in ("claude", "codex")
+ )
+ return Readiness(
+ tools=ordered,
+ logins={a: logins.get(a, False) for a in ("claude", "codex")},
+ package_manager=pkg,
+ root=root,
+ sudo=sudo,
+ os=os_name,
+ ready=ready,
+ )
+
+
+async def inspect(computer_id: str) -> Readiness:
+ """Read what the computer has, in one round trip."""
+ async with get_service().session(computer_id) as session:
+ result = await asyncio.wait_for(
+ session.conn.run(
+ login_shell(_INSPECT), check=False, encoding="utf-8", errors="replace"
+ ),
+ timeout=45,
+ )
+ return parse_inspection(str(result.stdout or ""))
+
+
+def install_script(readiness: Readiness, wanted: list[str]) -> str:
+ """The shell script that installs ``wanted`` on this computer."""
+ missing = {t.id for t in readiness.tools if not t.installed}
+ lines = ["set -e"]
+ prefix = "" if readiness.root else ("sudo -n " if readiness.sudo else "")
+ pkg = readiness.package_manager
+ system = [t for t in ("tmux", "git", "node") if t in wanted and t in missing]
+ needs_node = any(a in wanted and a in missing for a in _NPM_PACKAGES) and "node" in missing
+ if needs_node and "node" not in system:
+ system.append("node")
+ if system:
+ if pkg is None or pkg not in _PACKAGES:
+ raise ComputerError(
+ "No supported package manager was found. Install tmux, git and Node.js by hand."
+ )
+ spec = _PACKAGES[pkg]
+ if "update" in spec:
+ lines.append(f"{prefix}{spec['update']}")
+ names = " ".join(spec[t] for t in system)
+ lines.append(f"{prefix}{spec['install']} {names}")
+ npm = [_NPM_PACKAGES[a] for a in _NPM_PACKAGES if a in wanted and a in missing]
+ if npm:
+ lines.append(f"{prefix}npm install -g --silent {' '.join(npm)}")
+ lines.append("echo '[jarvis] done'")
+ return "\n".join(lines)
+
+
+@dataclass
+class InstallJob:
+ computer_id: str
+ items: list[str]
+ state: Literal["running", "done", "failed"] = "running"
+ log: list[str] = field(default_factory=list)
+ started_at: float = field(default_factory=time.time)
+ finished_at: float | None = None
+ message: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ data = asdict(self)
+ data["log"] = self.log[-200:]
+ return data
+
+
+_JOBS: dict[str, InstallJob] = {}
+_TASKS: dict[str, asyncio.Task[None]] = {}
+
+
+def job(computer_id: str) -> InstallJob | None:
+ return _JOBS.get(computer_id)
+
+
+async def start_install(computer_id: str, items: list[str]) -> InstallJob:
+ current = _JOBS.get(computer_id)
+ if current is not None and current.state == "running":
+ return current
+ wanted: list[str] = [i for i in items if i in TOOLS]
+ if not wanted:
+ raise ComputerError("Choose at least one thing to install.")
+ readiness = await inspect(computer_id)
+ if (
+ not readiness.root
+ and not readiness.sudo
+ and any(t in wanted for t in ("tmux", "git", "node"))
+ ):
+ raise ComputerError(
+ "Installing system packages needs root or sudo without a password on this login."
+ )
+ script = install_script(readiness, wanted)
+ new_job = InstallJob(computer_id=computer_id, items=wanted)
+ _JOBS[computer_id] = new_job
+ _TASKS[computer_id] = asyncio.create_task(
+ _run_install(new_job, script), name=f"computers-install-{computer_id}"
+ )
+ return new_job
+
+
+async def _run_install(current: InstallJob, script: str) -> None:
+ try:
+ async with get_service().session(current.computer_id) as session:
+ import asyncssh
+
+ process = await session.conn.create_process(
+ login_shell(script), encoding="utf-8", errors="replace", stderr=asyncssh.STDOUT
+ )
+ async for line in process.stdout:
+ current.log.append(line.rstrip())
+ await asyncio.wait_for(process.wait(), timeout=1500)
+ code = process.exit_status
+ if code == 0:
+ current.state = "done"
+ else:
+ current.state = "failed"
+ current.message = f"The installation stopped (exit {code}). See the log."
+ except ComputerError as exc:
+ current.state = "failed"
+ current.message = exc.message
+ except Exception as exc: # noqa: BLE001 — reported in the job, logged here
+ log.warning("computers: install on %s failed", current.computer_id, exc_info=True)
+ current.state = "failed"
+ current.message = f"The installation failed: {type(exc).__name__}"
+ finally:
+ current.finished_at = time.time()
+
+
+def local_login_file(agent: str) -> Path | None:
+ rel = _LOGIN_FILES.get(agent)
+ if rel is None:
+ return None
+ path = Path.home() / rel
+ return path if path.is_file() else None
+
+
+async def copy_login(computer_id: str, agent: AgentLogin) -> None:
+ """Copy this computer's CLI login file to the server (explicit user action)."""
+ source = local_login_file(agent)
+ if source is None:
+ raise ComputerError(
+ f"No {agent} login was found on this computer. Log in on the server instead: "
+ f"open a terminal there and run {agent}."
+ )
+ rel = _LOGIN_FILES[agent]
+ remote_dir = shlex.quote(str(Path(rel).parent.as_posix()))
+ async with get_service().session(computer_id) as session:
+ await session.conn.run(f"mkdir -p ~/{remote_dir} && chmod 700 ~/{remote_dir}", check=False)
+ async with session.conn.start_sftp_client() as sftp:
+ await sftp.put(str(source), rel)
+ await sftp.chmod(rel, 0o600)
+ log.info("computers: copied the %s login to %s at the user's request", agent, computer_id)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index fbdfeb1416..6fdcca0584 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -267,6 +267,21 @@ class StartSessionRequest(BaseModel):
default_factory=list,
description="One entry per terminal, in grid order.",
)
+ computer_id: str | None = Field(
+ default=None,
+ description=(
+ "Run every terminal on this connected computer (Computers) instead of "
+ "this machine; the folder is copied there first."
+ ),
+ )
+
+
+class PlaceRequest(BaseModel):
+ workspace_id: str | None = Field(default=None, description="Workspace the pane is in.")
+ computer_id: str | None = Field(
+ default=None,
+ description="Connected computer to run on; null brings the work back to this machine.",
+ )
class ForkTerminalRequest(BaseModel):
@@ -2240,6 +2255,14 @@ async def start_session(request: Request, req: StartSessionRequest) -> dict:
)
except SessionError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
+ if req.computer_id:
+ # Placed BEFORE anyone is told the workspace exists: a pane that
+ # attached first would start its agent on this machine instead.
+ try:
+ await get_registry().place_workspace(session.id, computer_id=req.computer_id)
+ except SessionError as exc:
+ await get_registry().end(session.id)
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
split: dict[str, int] = {}
for terminal in session.terminals:
@@ -2824,6 +2847,48 @@ async def fork_suggestion(name: str, workspace_id: str | None = None) -> dict:
return {"ok": True, **suggestion}
+ "/terminals/{name}/place",
+ summary="Run a terminal on a connected computer, or bring it back",
+)
+async def place_terminal(request: Request, name: str, req: PlaceRequest) -> dict:
+ """Move one pane's agent to a computer (a VPS, a local VM) or back here.
+
+ The folder travels with its uncommitted edits, the conversation is carried
+ so the agent continues, and on the computer the agent runs inside tmux,
+ so it keeps working while this app is closed. ``computer_id: null`` brings
+ it back; the server's work returns (never overwriting local changes).
+ """
+ registry = get_registry()
+ try:
+ result = await registry.place_terminal(
+ name, workspace_id=req.workspace_id, computer_id=req.computer_id
+ )
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ session = registry.get(req.workspace_id) if req.workspace_id else None
+ if session is not None:
+ await _announce_workspace(request, session, "updated")
+ return {"ok": True, **result, "state": registry.state()}
+
+
+ "/workspaces/{workspace_id}/place",
+ summary="Run a whole workspace on a connected computer, or bring it back",
+)
+async def place_workspace(request: Request, workspace_id: str, req: PlaceRequest) -> dict:
+ """Every pane of the workspace, moved in one go (one folder transfer)."""
+ registry = get_registry()
+ try:
+ result = await registry.place_workspace(workspace_id, computer_id=req.computer_id)
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ session = registry.get(workspace_id)
+ if session is not None:
+ await _announce_workspace(request, session, "updated")
+ return {"ok": True, **result, "state": registry.state()}
+
+
@router.post("/terminals/{name}/fork", summary="Fork a terminal's chat into a new terminal")
async def fork_terminal(name: str, req: ForkTerminalRequest) -> dict:
"""Open a new pane that continues a copy of this pane's conversation.
diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.py
index 0b98b159bc..45df16de6e 100644
--- a/jarvis/ui/web/computers_routes.py
+++ b/jarvis/ui/web/computers_routes.py
@@ -19,6 +19,10 @@
POST /api/computers/{id}/install-key plant Jarvis's key with a password
POST /api/computers/{id}/trust-host-key accept a changed server identity
POST /api/computers/{id}/power start / stop a local VM
+ GET /api/computers/{id}/readiness tmux / git / agent CLIs / logins
+ POST /api/computers/{id}/install install what is missing (job)
+ GET /api/computers/{id}/install that job's state and log
+ POST /api/computers/{id}/copy-login copy this computer's CLI login there
Static paths are registered before ``/{computer_id}`` so the dynamic route
cannot swallow them. Store reads are plain ``def`` (threadpool); anything that
@@ -35,7 +39,7 @@ from typing import Any, Literal
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
-from jarvis.computers import cloud, identity, local_vm
+from jarvis.computers import cloud, identity, local_vm, toolbox
from jarvis.computers.models import Computer
from jarvis.computers.service import ComputerError, get_service
@@ -98,6 +102,14 @@ class ImportBody(BaseModel):
password: str | None = Field(default=None, max_length=1024)
+class InstallBody(BaseModel):
+ items: list[Literal["tmux", "git", "node", "claude", "codex"]] = Field(min_length=1)
+
+
+class CopyLoginBody(BaseModel):
+ agent: Literal["claude", "codex"]
+
+
class LocalVmBody(BaseModel):
name: str = Field(min_length=2, max_length=40)
cpus: int = Field(default=2, ge=1, le=64)
@@ -276,6 +288,10 @@ async def remove_computer(computer_id: str, destroy_vm: bool = False) -> dict[st
removed = await get_service().remove(computer_id, destroy_vm=destroy_vm)
except ComputerError as exc:
raise _fail(exc) from exc
+ # Its IDE panes' connection goes with it (the agents on it are not killed).
+ from jarvis.computers.remote_terminal import forget_pool
+
+ forget_pool(computer_id)
return {"removed": removed}
@@ -324,3 +340,39 @@ async def power_computer(computer_id: str, body: PowerBody) -> dict[str, Any]:
return _row(await get_service().power(computer_id, body.action))
except ComputerError as exc:
raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}/readiness")
+async def computer_readiness(computer_id: str) -> dict[str, Any]:
+ """What coding agents need on this computer, and what is there."""
+ try:
+ readiness = await toolbox.inspect(computer_id)
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ job = toolbox.job(computer_id)
+ return {**readiness.to_dict(), "install": job.to_dict() if job else None}
+
+
[email protected]("/{computer_id}/install", status_code=202)
+async def install_tools(computer_id: str, body: InstallBody) -> dict[str, Any]:
+ try:
+ job = await toolbox.start_install(computer_id, list(body.items))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return job.to_dict()
+
+
[email protected]("/{computer_id}/install")
+def install_state(computer_id: str) -> dict[str, Any]:
+ job = toolbox.job(computer_id)
+ return {"install": job.to_dict() if job else None}
+
+
[email protected]("/{computer_id}/copy-login")
+async def copy_login(computer_id: str, body: CopyLoginBody) -> dict[str, Any]:
+ """Copy this computer's CLI login to the server — only ever on this request."""
+ try:
+ await toolbox.copy_login(computer_id, body.agent)
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return {"copied": body.agent}
diff --git a/tests/fakes/fake_tmux_server.py b/tests/fakes/fake_tmux_server.py
new file mode 100644
index 0000000000..25ae44115a
--- /dev/null
+++ b/tests/fakes/fake_tmux_server.py
@@ -0,0 +1,109 @@
+"""An in-process SSH server that behaves like a VPS running tmux.
+
+Built on :class:`tests.fakes.fake_ssh_server.FakeSshServer` (real asyncssh,
+127.0.0.1, random port). Only the handful of commands the IDE's remote panes
+send are understood:
+
+* ``tmux ... new-session -A -s NAME ...`` — creates (or re-joins) session NAME
+ and becomes its screen: prints ``ready NAME`` and echoes every keystroke back
+ as ``echo:<data>`` until the session is killed.
+* ``tmux has-session -t NAME`` — exit 0 while NAME lives, 1 after.
+* ``tmux kill-session -t NAME`` — ends NAME (and the screen attached to it).
+* ``printf %s "$HOME"`` — ``/home/test``.
+
+``drop_connections()`` cuts every client connection WITHOUT ending the tmux
+sessions, which is what a flaky network or a sleeping laptop does.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+import asyncssh
+
+from tests.fakes.fake_ssh_server import FakeSshServer, FakeSshState, _Server
+
+_NEW = re.compile(r"new-session -A -s ([A-Za-z0-9_-]+)")
+_HAS = re.compile(r"has-session -t ([A-Za-z0-9_-]+)")
+_KILL = re.compile(r"kill-session -t ([A-Za-z0-9_-]+)")
+
+
+@dataclass
+class TmuxState:
+ alive: set[str] = field(default_factory=set)
+ created: list[str] = field(default_factory=list)
+ attaches: list[str] = field(default_factory=list)
+ screens: dict[str, list[Any]] = field(default_factory=dict)
+ sizes: dict[str, tuple[int, int]] = field(default_factory=dict)
+
+
+class FakeTmuxServer(FakeSshServer):
+ def __init__(self, state: FakeSshState | None = None) -> None:
+ super().__init__(state)
+ self.tmux = TmuxState()
+ self._connections: list[Any] = []
+
+ async def start(self, port: int = 0) -> None:
+ self._acceptor = await asyncssh.listen(
+ "127.0.0.1",
+ port,
+ server_host_keys=[self.host_key],
+ server_factory=lambda: _Server(self.state),
+ process_factory=self._process,
+ line_editor=False,
+ )
+ self.port = self._acceptor.sockets[0].getsockname()[1]
+
+ async def _process(self, process: asyncssh.SSHServerProcess) -> None:
+ command = process.command or ""
+ self.state.commands.append(command)
+ self._connections.append(process.channel.get_connection())
+ if (match := _NEW.search(command)) is not None:
+ await self._screen(process, match.group(1).strip("'\""))
+ return
+ if (match := _HAS.search(command)) is not None:
+ process.exit(0 if match.group(1).strip("'\"") in self.tmux.alive else 1)
+ return
+ if (match := _KILL.search(command)) is not None:
+ name = match.group(1).strip("'\"")
+ self.tmux.alive.discard(name)
+ for screen in self.tmux.screens.pop(name, []):
+ screen.exit(0)
+ process.exit(0)
+ return
+ if 'printf %s "$HOME"' in command:
+ process.stdout.write("/home/test")
+ process.exit(0)
+ return
+ await super()._process(process)
+
+ async def _screen(self, process: asyncssh.SSHServerProcess, name: str) -> None:
+ if name in self.tmux.alive:
+ self.tmux.attaches.append(name)
+ else:
+ self.tmux.alive.add(name)
+ self.tmux.created.append(name)
+ self.tmux.screens.setdefault(name, []).append(process)
+ size = process.term_size
+ if size:
+ self.tmux.sizes[name] = (size[0], size[1])
+ process.stdout.write("ready " + name + "\r\n")
+ while name in self.tmux.alive:
+ try:
+ data = await process.stdin.read(1024)
+ except asyncssh.TerminalSizeChanged as change:
+ self.tmux.sizes[name] = (change.width, change.height)
+ continue
+ except (asyncssh.Error, OSError):
+ return
+ if not data:
+ return
+ process.stdout.write("echo:" + data)
+
+ def drop_connections(self) -> None:
+ """Cut every client connection; tmux sessions survive."""
+ for conn in self._connections:
+ conn.abort()
+ self._connections.clear()
diff --git a/tests/unit/agentic_ide/test_remote_placement.py b/tests/unit/agentic_ide/test_remote_placement.py
new file mode 100644
index 0000000000..9816b912c4
--- /dev/null
+++ b/tests/unit/agentic_ide/test_remote_placement.py
@@ -0,0 +1,170 @@
+"""Placing IDE panes on a connected computer, and bringing them back.
+
+The registry must: stop the local agent, start it again THROUGH the
+computer's pool with a server-side argv and folder, continue the same
+conversation, remember the placement across a restart, and route every
+keystroke/resize/close for that pane to the computer instead of this machine.
+The code transfer itself is covered in ``test_remote_sync``; here it is a
+recorded stand-in.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.agentic_ide import remote, resume_store
+from jarvis.agentic_ide import session as ide
+from jarvis.computers import remote_terminal
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+class RemotePool(FakePtyManager):
+ """A computer's pool: a FakePtyManager that also answers ``run``."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.commands: list[str] = []
+
+ computer_id = "c_1"
+
+ async def spawn(self, *args: Any, meta: dict[str, Any] | None = None, **kwargs: Any) -> Any:
+ spawned = await super().spawn(*args, **kwargs)
+ self.spawns[-1]["meta"] = meta or {}
+ return spawned
+
+ async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
+ self.commands.append(command)
+ return 0, "", ""
+
+
+def pools(monkeypatch: pytest.MonkeyPatch) -> tuple[FakePtyManager, RemotePool, list[Any]]:
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"C:/tools/{name}.exe",))
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ local = FakePtyManager()
+ far = RemotePool()
+ moves: list[Any] = []
+ monkeypatch.setattr(remote_terminal, "pool_for", lambda computer_id: far)
+
+ async def push_code(_pool: object, folder: Path) -> remote.Placement:
+ moves.append(("push", folder))
+ return remote.Placement("/home/u/jarvis-workspaces/app-abc123", "f" * 40)
+
+ async def push_conversation(
+ _pool: object, agent: str, cid: str | None, cwd: str, home: object
+ ) -> bool:
+ moves.append(("chat-up", agent, cid, cwd))
+ return cid is not None
+
+ async def pull_code(_pool: object, folder: Path, rf: str, snap: str | None, name: str) -> Any:
+ moves.append(("pull", rf, snap))
+ return remote.Return(branch="jarvis/vps/1", applied=True, message="back")
+
+ async def pull_conversation(
+ _pool: object, agent: str, cid: str | None, cwd: Path, home: object
+ ) -> bool:
+ moves.append(("chat-down", cid))
+ return True
+
+ monkeypatch.setattr(remote, "push_code", push_code)
+ monkeypatch.setattr(remote, "push_conversation", push_conversation)
+ monkeypatch.setattr(remote, "pull_code", pull_code)
+ monkeypatch.setattr(remote, "pull_conversation", pull_conversation)
+ return local, far, moves
+
+
+async def _sink(_text: str) -> None:
+ return None
+
+
+async def _gone(_code: int) -> None:
+ return None
+
+
+async def test_a_live_pane_moves_to_the_computer_and_continues_its_chat(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ local, far, moves = pools
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+ conversation = term.resume.id if term.resume else None
+ local_id = term.pty_id
+
+ result = await registry.place_terminal(term.key, workspace_id=session.id, computer_id="c_1")
+
+ assert result["moved"] is True
+ assert local_id in local.closed, "the local agent was stopped"
+ assert term.computer_id == "c_1"
+ spawn = far.spawns[-1]
+ assert spawn["argv"][0] == "claude", "the server's own binary, not C:/tools"
+ assert "--resume" in spawn["argv"] and conversation in spawn["argv"]
+ assert spawn["cwd"] == "/home/u/jarvis-workspaces/app-abc123"
+ assert spawn.get("meta", {}).get("history_id") == term.history_id
+ assert ("chat-up", "claude", conversation, "/home/u/jarvis-workspaces/app-abc123") in moves
+
+ # Input and resize for this pane now go to the computer.
+ registry.write(term.key, "x", session.id)
+ assert far.writes and far.writes[-1][1] == "x"
+
+
+async def test_placement_survives_a_restart(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ local, _far, _moves = pools
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.place_terminal(term.key, workspace_id=session.id, computer_id="c_1")
+
+ saved = term.to_snapshot()
+ again = resume_store.SnapshotTerminal.from_dict(saved.to_dict())
+
+ assert again is not None
+ assert again.computer_id == "c_1"
+ assert again.remote_folder == "/home/u/jarvis-workspaces/app-abc123"
+ assert again.offload_snapshot == "f" * 40
+
+
+async def test_a_workspace_moves_with_one_folder_transfer(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ local, far, moves = pools
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])
+
+ result = await registry.place_workspace(session.id, computer_id="c_1")
+
+ assert len(result["moved"]) == 2
+ assert [m for m in moves if m[0] == "push"] == [("push", Path(str(tmp_path)))]
+ assert all(t.computer_id == "c_1" for t in session.terminals)
+ assert far.spawns == [], "panes that were not running only change place"
+
+
+async def test_bringing_back_kills_the_remote_agent_and_runs_here_again(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ local, far, moves = pools
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+ await registry.place_terminal(term.key, workspace_id=session.id, computer_id="c_1")
+ remote_id = term.pty_id
+
+ result = await registry.place_terminal(term.key, workspace_id=session.id, computer_id=None)
+
+ assert result["message"] == "back"
+ assert remote_id in far.closed
+ assert term.computer_id == "" and term.remote_folder == ""
+ assert local.spawns[-1]["argv"][0] == "C:/tools/claude.exe"
+ assert ("pull", "/home/u/jarvis-workspaces/app-abc123", "f" * 40) in moves
+
+
+def test_remote_argv_uses_the_command_name_only() -> None:
+ argv = ide.remote_agent_argv("claude")
+ assert argv is not None and argv[0] == "claude"
diff --git a/tests/unit/agentic_ide/test_remote_sync.py b/tests/unit/agentic_ide/test_remote_sync.py
new file mode 100644
index 0000000000..d42ada2010
--- /dev/null
+++ b/tests/unit/agentic_ide/test_remote_sync.py
@@ -0,0 +1,204 @@
+"""Moving a folder to a "server" and back, with real git and a real shell.
+
+The server here is this machine: a pool double runs the remote commands in a
+local POSIX shell inside a temp "home", and file transfer is a copy. That keeps
+the part that can actually go wrong — the snapshot commit, the bundle, the
+checkout on the other side, the way back — fully real, on every OS that has
+git and a POSIX shell (Git Bash on Windows).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import remote
+
+
+def _posix_shell() -> str | None:
+ if sys.platform == "win32":
+ git = shutil.which("git")
+ if git is None:
+ return None
+ roots = Path(git).resolve().parents
+ for candidate in (
+ *(root / "bin" / "bash.exe" for root in list(roots)[:3]),
+ *(root / "usr" / "bin" / "bash.exe" for root in list(roots)[:3]),
+ ):
+ if candidate.is_file():
+ return str(candidate)
+ return None
+ return shutil.which("bash") or shutil.which("sh")
+
+
+SHELL = _posix_shell()
+pytestmark = pytest.mark.skipif(
+ SHELL is None or shutil.which("git") is None, reason="needs git and a POSIX shell"
+)
+
+
+class LocalPool:
+ """Stands in for ``SshPtyPool``: the 'server' is a folder on this machine."""
+
+ def __init__(self, home: Path) -> None:
+ self._home = home
+
+ async def home(self) -> str:
+ return self._home.as_posix()
+
+ async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
+ result = await asyncio.to_thread(
+ subprocess.run,
+ [str(SHELL), "-c", command],
+ capture_output=True,
+ timeout=timeout_s,
+ check=False,
+ cwd=str(self._home),
+ )
+ return (
+ result.returncode,
+ result.stdout.decode("utf-8", "replace"),
+ result.stderr.decode("utf-8", "replace"),
+ )
+
+
+def copies(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def upload(_pool: object, local: Path, remote_path: str) -> None:
+ target = Path(remote_path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(local, target)
+
+ async def download(_pool: object, remote_path: str, local: Path) -> None:
+ shutil.copyfile(Path(remote_path), local)
+
+ monkeypatch.setattr(remote, "_upload", upload)
+ monkeypatch.setattr(remote, "_download", download)
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run( # noqa: S603
+ ["git", *args], # noqa: S607
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ check=True,
+ env={**__import__("os").environ, **remote._IDENTITY_ENV},
+ ).stdout.strip()
+
+
+def project(tmp_path: Path) -> Path:
+ repo = tmp_path / "My App"
+ repo.mkdir()
+ _git(repo, "init", "-q", "-b", "main")
+ (repo / "app.py").write_text("print('v1')\n", encoding="utf-8")
+ (repo / ".gitignore").write_text("secret.env\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "first")
+ return repo
+
+
+async def test_offload_carries_uncommitted_and_new_files_but_not_ignored_ones(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ (project / "app.py").write_text("print('v2 draft')\n", encoding="utf-8")
+ (project / "notes.md").write_text("new file\n", encoding="utf-8")
+ (project / "secret.env").write_text("TOKEN=x\n", encoding="utf-8")
+ index_before = (project / ".git" / "index").read_bytes()
+ server = tmp_path / "server-home"
+ server.mkdir()
+
+ placement = await remote.push_code(LocalPool(server), project)
+
+ there = Path(placement.remote_folder)
+ assert (there / "app.py").read_text(encoding="utf-8") == "print('v2 draft')\n"
+ assert (there / "notes.md").is_file()
+ assert not (there / "secret.env").exists(), ".gitignore is honoured"
+ assert _git(there, "rev-parse", "--abbrev-ref", "HEAD") == "main"
+ assert "app.py" in _git(there, "status", "--porcelain"), "edits arrive uncommitted"
+ assert (project / ".git" / "index").read_bytes() == index_before, "local index untouched"
+ assert placement.offload_snapshot
+
+
+async def test_bring_back_applies_the_servers_work_when_nothing_changed_here(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ server = tmp_path / "server-home"
+ server.mkdir()
+ pool = LocalPool(server)
+ placement = await remote.push_code(pool, project)
+ there = Path(placement.remote_folder)
+ (there / "app.py").write_text("print('done on the vps')\n", encoding="utf-8")
+ (there / "vps.txt").write_text("made there\n", encoding="utf-8")
+
+ outcome = await remote.pull_code(
+ pool, project, placement.remote_folder, placement.offload_snapshot, "My VPS"
+ )
+
+ assert outcome.applied, outcome.message
+ assert (project / "app.py").read_text(encoding="utf-8") == "print('done on the vps')\n"
+ assert (project / "vps.txt").is_file()
+ assert outcome.branch and outcome.branch.startswith("jarvis/my-vps/")
+ assert _git(project, "rev-parse", "--verify", outcome.branch)
+
+
+async def test_bring_back_never_overwrites_local_changes(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ server = tmp_path / "server-home"
+ server.mkdir()
+ pool = LocalPool(server)
+ placement = await remote.push_code(pool, project)
+ (Path(placement.remote_folder) / "app.py").write_text("server\n", encoding="utf-8")
+ (project / "app.py").write_text("local meanwhile\n", encoding="utf-8")
+
+ outcome = await remote.pull_code(
+ pool, project, placement.remote_folder, placement.offload_snapshot, "vps"
+ )
+
+ assert not outcome.applied
+ assert (project / "app.py").read_text(encoding="utf-8") == "local meanwhile\n"
+ assert outcome.branch and outcome.branch in outcome.message
+
+
+async def test_second_offload_backs_up_the_servers_unsaved_state(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ server = tmp_path / "server-home"
+ server.mkdir()
+ pool = LocalPool(server)
+ placement = await remote.push_code(pool, project)
+ (Path(placement.remote_folder) / "app.py").write_text("unsaved on server\n", encoding="utf-8")
+
+ await remote.push_code(pool, project)
+
+ backups = _git(Path(placement.remote_folder), "for-each-ref", "refs/jarvis/backup")
+ assert backups, "the server's own edits were kept before being replaced"
+
+
+async def test_folder_without_git_travels_as_a_tarball(tmp_path: Path, copies: None) -> None:
+ plain = tmp_path / "plain"
+ (plain / "node_modules" / "x").mkdir(parents=True)
+ (plain / "node_modules" / "x" / "big.js").write_text("x", encoding="utf-8")
+ (plain / "main.txt").write_text("hello\n", encoding="utf-8")
+ server = tmp_path / "server-home"
+ server.mkdir()
+
+ placement = await remote.push_code(LocalPool(server), plain)
+
+ there = Path(placement.remote_folder)
+ assert (there / "main.txt").read_text(encoding="utf-8") == "hello\n"
+ assert not (there / "node_modules").exists()
+ assert placement.offload_snapshot is None
+
+
+def test_claude_project_dir_matches_the_cli_convention() -> None:
+ assert remote.claude_project_dir("/root/jarvis-workspaces/app-1a2b3c") == (
+ "-root-jarvis-workspaces-app-1a2b3c"
+ )
diff --git a/tests/unit/computers/test_remote_terminal.py b/tests/unit/computers/test_remote_terminal.py
new file mode 100644
index 0000000000..aad83f3680
--- /dev/null
+++ b/tests/unit/computers/test_remote_terminal.py
@@ -0,0 +1,168 @@
+"""Remote IDE panes over real SSH against a server that behaves like tmux.
+
+The properties that make "run it on the VPS" worth having: output and input
+flow both ways, the agent's session is created once and re-joined afterwards,
+a dropped connection re-attaches instead of ending the pane, and only a
+session that really ended reports the pane closed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.computers import identity, remote_terminal
+from jarvis.computers.remote_terminal import SshPtyPool, tmux_session_name
+from jarvis.computers.service import ComputerService
+from tests.fakes.fake_tmux_server import FakeTmuxServer
+
+
+async def tmux_server(): # noqa: ANN201
+ server = FakeTmuxServer()
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+async def pool(computer_service: ComputerService, tmux_server: FakeTmuxServer): # noqa: ANN201
+ tmux_server.state.authorized.add(identity.public_key_line())
+ computer = await computer_service.add_server(
+ name="vps", host="127.0.0.1", port=tmux_server.port
+ )
+ assert computer.health.status == "online"
+ remote = SshPtyPool(computer.id, connect=lambda: computer_service.connect(computer.id))
+ try:
+ yield remote
+ finally:
+ remote.close_all()
+
+
+class Screen:
+ def __init__(self) -> None:
+ self.text = ""
+ self.closed: list[int] = []
+
+ async def output(self, _tid: str, chunk: str) -> None:
+ self.text += chunk
+
+ async def exit(self, _tid: str, code: int) -> None:
+ self.closed.append(code)
+
+ async def wait_for(self, needle: str) -> None:
+ for _ in range(250):
+ if needle in self.text:
+ return
+ await asyncio.sleep(0.02)
+ raise AssertionError(f"{needle!r} never arrived; screen: {self.text!r}")
+
+
+async def _spawn(pool: SshPtyPool, screen: Screen, identity_id: str = "abc123") -> str:
+ spawned = await pool.spawn(
+ shell_argv=("claude", "--resume", "id-1"),
+ shell_id="agentic-ide:t1",
+ cwd="/home/test/jarvis-workspaces/app",
+ cols=100,
+ rows=30,
+ on_output=screen.output,
+ on_closed=screen.exit,
+ meta={"history_id": identity_id},
+ )
+ return spawned.terminal_id
+
+
+async def test_spawn_streams_both_ways_inside_a_named_tmux_session(
+ pool: SshPtyPool, tmux_server: FakeTmuxServer
+) -> None:
+ screen = Screen()
+ terminal = await _spawn(pool, screen)
+ name = tmux_session_name("abc123")
+
+ await screen.wait_for(f"ready {name}")
+ assert pool.write(terminal, "hello")
+ await screen.wait_for("echo:hello")
+ assert tmux_server.tmux.created == [name]
+ assert tmux_server.tmux.sizes[name] == (100, 30)
+ command = next(c for c in tmux_server.state.commands if "new-session" in c)
+ assert "claude --resume id-1" in command
+ assert "jarvis-workspaces/app" in command
+
+
+async def test_resize_reaches_the_server(pool: SshPtyPool, tmux_server: FakeTmuxServer) -> None:
+ screen = Screen()
+ terminal = await _spawn(pool, screen)
+ await screen.wait_for("ready")
+
+ assert pool.resize(terminal, 140, 40)
+ name = tmux_session_name("abc123")
+ for _ in range(100):
+ if tmux_server.tmux.sizes.get(name) == (140, 40):
+ break
+ await asyncio.sleep(0.02)
+ assert tmux_server.tmux.sizes[name] == (140, 40)
+
+
+async def test_a_dropped_connection_re_attaches_instead_of_closing(
+ pool: SshPtyPool, tmux_server: FakeTmuxServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(remote_terminal, "RECONNECT_DELAYS_S", (0.05, 0.05, 0.05))
+ screen = Screen()
+ terminal = await _spawn(pool, screen)
+ await screen.wait_for("ready")
+
+ tmux_server.drop_connections()
+ name = tmux_session_name("abc123")
+ for _ in range(200):
+ if tmux_server.tmux.attaches:
+ break
+ await asyncio.sleep(0.02)
+
+ assert tmux_server.tmux.attaches == [name], "the same session was re-joined"
+ assert screen.closed == [], "a network drop is not the agent exiting"
+ await asyncio.sleep(0.1)
+ assert pool.write(terminal, "again")
+ await screen.wait_for("echo:again")
+
+
+async def test_close_kills_the_session_and_a_server_side_end_reports_closed(
+ pool: SshPtyPool, tmux_server: FakeTmuxServer
+) -> None:
+ screen = Screen()
+ terminal = await _spawn(pool, screen)
+ await screen.wait_for("ready")
+ name = tmux_session_name("abc123")
+
+ pool.close(terminal)
+ for _ in range(200):
+ if name not in tmux_server.tmux.alive:
+ break
+ await asyncio.sleep(0.02)
+ assert name not in tmux_server.tmux.alive
+ assert not pool.has(terminal)
+
+ # A second pane whose agent ends on the server by itself.
+ other = Screen()
+ await _spawn(pool, other, identity_id="zzz")
+ await other.wait_for("ready")
+ tmux_server.tmux.alive.discard(tmux_session_name("zzz"))
+ for screen_proc in tmux_server.tmux.screens.pop(tmux_session_name("zzz"), []):
+ screen_proc.exit(0)
+ for _ in range(200):
+ if other.closed:
+ break
+ await asyncio.sleep(0.02)
+ assert other.closed == [0]
+
+
+def test_tmux_command_is_create_or_attach_and_quiet() -> None:
+ command = remote_terminal.tmux_command(
+ "jv-x", ("claude", "--resume", "a b"), "/srv/my app", 80, 24
+ )
+ assert "new-session -A -s jv-x" in command
+ assert "status off" in command
+ assert "'/srv/my app'" in command
+ assert remote_terminal.tmux_session_name("a/b c") == "jv-a-b-c"