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): start terminals and workspaces directly on a connected computer

rubenluetke10-beep7c2deddb0e22
diff --git a/jarvis/agentic_ide/offload_on_quit.py b/jarvis/agentic_ide/offload_on_quit.py
index a85a4e1dfb..3cdc39827e 100644
--- a/jarvis/agentic_ide/offload_on_quit.py
+++ b/jarvis/agentic_ide/offload_on_quit.py
@@ -54,7 +54,7 @@ async def offload_before_quit(registry: Any) -> list[str]:
if not computer_id:
return []
moved: list[str] = []
- for workspace in list(registry.sessions()):
+ for workspace in list(registry.sessions):
running_here = [
term for term in workspace.terminals if term.pty_id and not term.computer_id
]
diff --git a/jarvis/agentic_ide/remote.py b/jarvis/agentic_ide/remote.py
index f34175f362..48abe25c79 100644
--- a/jarvis/agentic_ide/remote.py
+++ b/jarvis/agentic_ide/remote.py
@@ -9,6 +9,10 @@ Three things travel when a pane moves to a VPS ("offload") or comes back:
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).
+ Either way, a file that looks like a secret (``.env``, private keys) or
+ is over :data:`MAX_FILE_BYTES` stays here unless it is already committed
+ — the server may be rented or shared, and a key the user forgot to
+ ignore must not land there by accident.
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.
@@ -25,6 +29,7 @@ simply finds the work where it was.
from __future__ import annotations
import asyncio
+import fnmatch
import hashlib
import logging
import os
@@ -35,7 +40,8 @@ import tarfile
import tempfile
import time
import uuid
-from dataclasses import dataclass
+from collections.abc import Mapping
+from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from jarvis.computers.remote_terminal import SshPtyPool
@@ -46,7 +52,31 @@ log = logging.getLogger(__name__)
REMOTE_ROOT = "jarvis-workspaces"
SYNC_DIR = ".jarvis-sync"
MAX_TARBALL_BYTES = 300 * 1024 * 1024
+#: A new (uncommitted) file bigger than this stays on this machine.
+MAX_FILE_BYTES = 50 * 1024 * 1024
_SKIP_DIRS = {"node_modules", ".venv", "venv", "__pycache__", ".cache", ".mypy_cache", ".next"}
+#: File names that hold credentials. Matched on the base name, case-insensitive.
+SECRET_PATTERNS = (
+ ".env",
+ ".env.*",
+ "*.pem",
+ "*.key",
+ "*.p12",
+ "*.pfx",
+ "*.tfvars",
+ "*credentials*.json",
+ "id_rsa*",
+ "id_dsa*",
+ "id_ecdsa*",
+ "id_ed25519*",
+ ".netrc",
+ ".pypirc",
+ ".npmrc",
+ "login data",
+ "cookies",
+)
+#: Templates that document a secret's shape without holding one.
+SECRET_TEMPLATES = (".env.example", ".env.sample", ".env.template", ".env.dist")
_IDENTITY_ENV = {
"GIT_AUTHOR_NAME": "Jarvis",
"GIT_AUTHOR_EMAIL": "jarvis@localhost",
@@ -66,6 +96,25 @@ class Placement:
remote_folder: str
#: The snapshot commit the server was given (git folders only).
offload_snapshot: str | None
+ #: New files that were NOT sent (secrets, oversized), relative paths.
+ left_behind: tuple[str, ...] = field(default=())
+
+
+def is_secret_name(path: str) -> bool:
+ """True for a file whose name says it holds credentials."""
+ name = PurePosixPath(path.replace("\\", "/")).name.casefold()
+ if name in SECRET_TEMPLATES:
+ return False
+ return any(fnmatch.fnmatchcase(name, pattern) for pattern in SECRET_PATTERNS)
+
+
+def left_behind_note(paths: tuple[str, ...] | list[str]) -> str:
+ """One sentence naming the files that stayed on this machine."""
+ if not paths:
+ return ""
+ shown = ", ".join(sorted(paths)[:5])
+ more = f" and {len(paths) - 5} more" if len(paths) > 5 else ""
+ return f"Not copied (secrets or over 50 MB): {shown}{more}."
# ---------------------------------------------------------------------------
@@ -73,9 +122,10 @@ class Placement:
# ---------------------------------------------------------------------------
-def _git(
+def _git_bytes(
cwd: Path, *args: str, env: dict[str, str] | None = None, stdin: bytes | None = None
-) -> str:
+) -> bytes:
+ """Run git and return its stdout exactly as written (a patch, NUL lists)."""
merged = {**os.environ, **(env or {})}
result = subprocess.run( # noqa: S603 — fixed git argv, no shell
["git", *args], # noqa: S607
@@ -89,7 +139,13 @@ def _git(
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()
+ return result.stdout
+
+
+def _git(
+ cwd: Path, *args: str, env: dict[str, str] | None = None, stdin: bytes | None = None
+) -> str:
+ return _git_bytes(cwd, *args, env=env, stdin=stdin).decode("utf-8", "replace").strip()
def git_toplevel(folder: Path) -> Path | None:
@@ -114,34 +170,102 @@ def _branch(top: Path) -> str | None:
return name or None
-def snapshot_commit(top: Path, message: str) -> tuple[str, str]:
+def _stage_working_tree(top: Path, head: str | None, index: Path) -> tuple[str, list[str]]:
+ """Stage the working tree into the private ``index``; return (tree, left behind).
+
+ Seeded from a copy of the user's own index, so ``git add -A`` only has to
+ look at what changed (a fresh index re-hashes every file — seconds on a
+ large repo). New files that look like secrets or are too large are taken
+ back out again; a file already committed keeps its committed version.
+ """
+ env = {"GIT_INDEX_FILE": str(index)}
+ own_index = Path(_git(top, "rev-parse", "--git-path", "index"))
+ if not own_index.is_absolute():
+ own_index = top / own_index
+ if own_index.is_file():
+ index.write_bytes(own_index.read_bytes())
+ # A file the user marked "assume unchanged" would keep its old content
+ # in the copy: ``add -A`` does not look at it. Clear that mark in the
+ # private copy only. (Skip-worktree marks stay: a sparse checkout's
+ # absent files are not deletions.)
+ tagged = _git_bytes(top, "ls-files", "-v", "-z", env=env)
+ assumed = [
+ entry[2:] for entry in tagged.split(b"\0") if entry[:1].islower() and entry[1:2] == b" "
+ ]
+ if assumed:
+ _git_bytes(
+ top,
+ "update-index",
+ "--no-assume-unchanged",
+ "-z",
+ "--stdin",
+ env=env,
+ stdin=b"\0".join(assumed) + b"\0",
+ )
+ elif head:
+ _git(top, "read-tree", head, env=env)
+ _git(top, "add", "-A", env=env)
+ if head:
+ listed = _git_bytes(
+ # --no-renames: with diff.renames=copies a new .env copied from a
+ # committed template would show as a copy and slip past the filter.
+ top,
+ "diff",
+ "--cached",
+ "--no-renames",
+ "--name-only",
+ "-z",
+ "--diff-filter=A",
+ head,
+ env=env,
+ )
+ else:
+ listed = _git_bytes(top, "ls-files", "-z", env=env)
+ added = [path for path in listed.decode("utf-8", "surrogateescape").split("\0") if path]
+ held: list[str] = []
+ for path in added:
+ if is_secret_name(path):
+ held.append(path)
+ continue
+ try:
+ if (top / path).stat().st_size > MAX_FILE_BYTES:
+ held.append(path)
+ except OSError:
+ continue
+ if held:
+ _git_bytes(
+ top,
+ "update-index",
+ "--force-remove",
+ "-z",
+ "--stdin",
+ env=env,
+ stdin="\0".join(held).encode("utf-8", "surrogateescape") + b"\0",
+ )
+ return _git(top, "write-tree", env=env), held
+
+
+def snapshot_commit(top: Path, message: str) -> tuple[str, str, list[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.
+ Returns ``(commit, tree, left_behind)``. 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)
+ tree, held = _stage_working_tree(top, head, Path(tmp) / "index")
parents = ["-p", head] if head else []
commit = _git(top, "commit-tree", tree, *parents, "-m", message, env=_IDENTITY_ENV)
- return commit, tree
+ return commit, tree, held
def working_tree_id(top: Path) -> str:
- """The tree id the working tree would commit to right now."""
+ """The tree id the working tree would commit to right now (same filter)."""
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)
+ tree, _held = _stage_working_tree(top, head, Path(tmp) / "index")
+ return tree
def _relative_posix(folder: Path, top: Path) -> str:
@@ -149,6 +273,22 @@ def _relative_posix(folder: Path, top: Path) -> str:
return PurePosixPath(*Path(relative).parts).as_posix()
+def joined_folder(base_remote: str, base_local: Path, local: Path, top: Path) -> str:
+ """``local``'s folder inside a copy of repo ``top`` that was made for ``base_local``.
+
+ The copy holds the whole repo; ``base_remote`` is where ``base_local`` sits
+ in it. Walking up by ``base_local``'s depth gives the copy's root, and
+ ``local``'s own path below the repo top leads back down.
+ """
+ root = PurePosixPath(base_remote)
+ base_rel = _relative_posix(base_local, top)
+ if base_rel not in ("", "."):
+ for _part in PurePosixPath(base_rel).parts:
+ root = root.parent
+ relative = _relative_posix(local, top)
+ return str(root / relative) if relative not in ("", ".") else str(root)
+
+
def _slug(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:32] or "workspace"
@@ -188,6 +328,33 @@ echo ok
"""
+async def preflight(pool: SshPtyPool, commands: Mapping[str, str], where: str) -> None:
+ """Refuse early, in one sentence, when the server lacks a command panes need.
+
+ ``commands`` maps what the user reads ("Claude Code") to the command that
+ must be on the server's PATH ("claude"). One round trip for all of them,
+ before any folder is copied — a missing CLI used to show up only as a dead
+ pane after a long upload.
+ """
+ if not commands:
+ return
+ checks = " ".join(
+ f"command -v {shlex.quote(command)} >/dev/null 2>&1 || printf '%s\\n' "
+ f"{shlex.quote('missing:' + label)};"
+ for label, command in commands.items()
+ )
+ _code, out, _err = await pool.run(checks, timeout_s=30)
+ missing = [
+ line.strip()[len("missing:") :]
+ for line in out.splitlines()
+ if line.strip().startswith("missing:")
+ ]
+ if missing:
+ names = " and ".join(missing) if len(missing) < 3 else ", ".join(missing)
+ verb = "is" if len(missing) == 1 else "are"
+ raise MoveError(f"{names} {verb} not installed on {where}. Open Computers, then Prepare.")
+
+
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)' "
@@ -221,8 +388,8 @@ async def push_code(pool: SshPtyPool, local_folder: Path) -> Placement:
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)
+ held = await _push_tarball(pool, local_folder, remote)
+ return Placement(remote_folder=remote, offload_snapshot=None, left_behind=tuple(held))
remote_top = remote_folder_for(home, top)
relative = await asyncio.to_thread(_relative_posix, local_folder, top)
@@ -231,7 +398,7 @@ async def push_code(pool: SshPtyPool, local_folder: Path) -> Placement:
)
transfer = uuid.uuid4().hex[:12]
ref = f"refs/jarvis/offload/{transfer}"
- snap, _tree = await asyncio.to_thread(snapshot_commit, top, "jarvis: offload snapshot")
+ snap, _tree, held = 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)
@@ -266,28 +433,58 @@ async def push_code(pool: SshPtyPool, local_folder: Path) -> Placement:
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:
+ return Placement(remote_folder=remote_folder, offload_snapshot=snap, left_behind=tuple(held))
+
+
+def _tar_plan(folder: Path) -> tuple[int, list[str]]:
+ """Walk ``folder`` as the tarball will: (bytes to send, files held back)."""
+ total = 0
+ held: list[str] = []
+ for root, dirs, files in os.walk(folder):
+ dirs[:] = [d for d in dirs if d not in _SKIP_DIRS]
+ for name in files:
+ path = Path(root) / name
+ relative = path.relative_to(folder).as_posix()
+ try:
+ size = path.stat().st_size
+ except OSError:
+ continue
+ if is_secret_name(name) or size > MAX_FILE_BYTES:
+ held.append(relative)
+ continue
+ total += size
+ return total, held
+
+
+def _tar_filter(held: set[str]) -> object:
+ def keep(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
+ parts = PurePosixPath(info.name).parts
+ if any(part in _SKIP_DIRS for part in parts):
+ return None
+ relative = PurePosixPath(*parts).as_posix() if parts else ""
+ if info.isfile() and relative in held:
+ return None
+ return info
+
+ return keep
+
+
+async def _push_tarball(pool: SshPtyPool, folder: Path, remote: str) -> list[str]:
+ """Copy a folder without git; returns the files that stayed here."""
+ size, held = await asyncio.to_thread(_tar_plan, folder)
+ if size > MAX_TARBALL_BYTES:
+ # Measured before anything is packed: building a 5 GB archive only to
+ # refuse it cost minutes and the disk space for the archive.
+ raise MoveError("This folder is too large to copy without git (over 300 MB).")
with tempfile.TemporaryDirectory(prefix="jarvis-tar-") as tmp:
archive = Path(tmp) / "folder.tar.gz"
+ keep = _tar_filter(set(held))
- def build() -> int:
+ def build() -> None:
with tarfile.open(archive, "w:gz") as tar:
- tar.add(str(folder), arcname=".", filter=_tar_filter)
- return archive.stat().st_size
+ tar.add(str(folder), arcname=".", filter=keep) # type: ignore[arg-type]
- 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).")
+ await asyncio.to_thread(build)
home = await pool.home()
archive_name = f"{uuid.uuid4().hex[:12]}.tar.gz"
sync_dir = f"{home}/{SYNC_DIR}"
@@ -301,6 +498,7 @@ async def _push_tarball(pool: SshPtyPool, folder: Path, remote: str) -> None:
)
if code != 0:
raise MoveError(f"The folder could not be unpacked on the server: {err.strip()[:200]}")
+ return held
# ---------------------------------------------------------------------------
@@ -323,6 +521,19 @@ echo "$c"
"""
+def _free_branch(top: Path, prefix: str) -> str:
+ """``<prefix>/<time>``, with a counter when that name is taken already."""
+ base = f"{prefix}/{time.strftime('%Y%m%d-%H%M%S')}"
+ candidate, counter = base, 1
+ while True:
+ try:
+ _git(top, "rev-parse", "-q", "--verify", f"refs/heads/{candidate}")
+ except MoveError:
+ return candidate
+ counter += 1
+ candidate = f"{base}-{counter}"
+
+
@dataclass(frozen=True)
class Return:
branch: str | None
@@ -372,8 +583,7 @@ async def pull_code(
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}"
+ branch = await asyncio.to_thread(_free_branch, top, f"jarvis/{_slug(computer_name)}")
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)
@@ -386,12 +596,14 @@ async def pull_code(
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:
+ # Bytes as git wrote them: decoding and stripping cut the last context
+ # line of a hunk that ends on a blank line, and mangled non-UTF-8 text.
+ patch = await asyncio.to_thread(
+ _git_bytes, top, "diff", "--binary", offload_snapshot, remote_snap
+ )
+ if patch.strip():
try:
- await asyncio.to_thread(
- _git, top, "apply", "--whitespace=nowarn", stdin=(patch + "\n").encode("utf-8")
- )
+ await asyncio.to_thread(_git, top, "apply", "--whitespace=nowarn", stdin=patch)
except MoveError as exc:
return Return(branch=branch, applied=False, message=f"{exc} The work is on {branch}.")
return Return(
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 288e196ec6..04c4e4e0f8 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -1037,6 +1037,12 @@ class Terminal:
computer_id: str = ""
remote_folder: str = ""
offload_snapshot: str = ""
+ # Set while the pane's folder is on its way to (or back from) its
+ # computer: a viewer attaching then is told "not yet" instead of starting
+ # the agent in the wrong place. Never persisted.
+ placing: str = ""
+ # The last placement's one-line report for the UI ("Not copied: .env").
+ notice: str = ""
status: Status = "pending"
pty_id: str | None = None
# The geometry the PTY ACTUALLY holds, as last handed to `setwinsize`.
@@ -1916,6 +1922,43 @@ class SessionNotReady(SessionError):
"""
+class PlacementError(SessionError):
+ """A pane could not be set up on (or brought back from) a computer.
+
+ Its own type so the HTTP layer can answer 502 — the server, the network or
+ the copy failed — instead of blaming the request.
+ """
+
+
+class _Inherit:
+ """ "Run the new pane where its neighbours run" — the default placement."""
+
+ def __repr__(self) -> str:
+ return "INHERIT_PLACEMENT"
+
+
+#: ``add_terminal(computer_id=...)`` default: a split runs where its anchor
+#: runs, any other new pane where the whole workspace runs.
+INHERIT_PLACEMENT: Any = _Inherit()
+
+
+def _remote_commands(terms: Sequence[Terminal]) -> dict[str, str]:
+ """What must be on a computer's PATH before ``terms`` can start there."""
+ needed = {"tmux": "tmux"}
+ for term in terms:
+ spec = workspace_agents.get_agent(term.agent)
+ argv = remote_agent_argv(term.agent)
+ if spec is not None and spec.is_coding_agent and not spec.shell_launch and argv:
+ needed[term.display_name] = argv[0]
+ return needed
+
+
+def _copy_key(local: str) -> tuple[str, Path | None]:
+ """Blocking half of ``Registry._copy_root``: one git call and a realpath."""
+ top = remote.git_toplevel(Path(local))
+ return os.path.normcase(os.path.realpath(str(top) if top else local)), top
+
+
class Registry:
"""Process-wide holder of the open Agentic-IDE workspaces.
@@ -1955,6 +1998,11 @@ class Registry:
# burst for one account from starving unrelated ``asyncio.to_thread``
# work (BUG-043).
self._account_prepare_locks: dict[str, asyncio.Lock] = {}
+ # One gate per (computer, local folder): copies of one folder to one
+ # computer happen one at a time, so a second pane JOINS the first one's
+ # copy — sending it again reset the server's folder under the agent
+ # already working in it.
+ self._copy_locks: dict[tuple[str, str], asyncio.Lock] = {}
# Admits a few agent cold starts at a time (see COLD_START_LIMIT).
# Created on first use rather than here: a semaphore belongs to the loop
# it is first awaited on, and the registry is also built in tests that
@@ -2597,6 +2645,7 @@ class Registry:
*,
project_id: str | None = None,
name: str | None = None,
+ computer_id: str | None = None,
) -> Session:
"""Open ``folder`` as a NEW workspace with one terminal per request entry.
@@ -2607,6 +2656,12 @@ class Registry:
stays open with its agents running. The same folder may be opened more
than once deliberately: each workspace is a separate set of panes and
conversations, with a distinct tab name.
+
+ ``computer_id`` runs every pane on that connected computer from the
+ start: the server is checked (tmux, each CLI), the folder is copied
+ there once, and only then may a pane start — its CLI never has to be
+ installed on this machine. A failure closes the workspace again and
+ raises :class:`PlacementError`.
"""
async with self._lock:
if not requested:
@@ -2652,11 +2707,15 @@ class Registry:
if unknown:
raise SessionError(f"Unknown agent(s): {', '.join(sorted(unknown))}")
+ # A workspace that runs on a computer needs its CLIs THERE, not
+ # here — they are checked on the server before anything is copied.
+ launcher = remote_agent_argv if computer_id else agent_argv
missing = sorted(
- {str(r.get("agent")) for r in requested if agent_argv(str(r.get("agent"))) is None}
+ {str(r.get("agent")) for r in requested if launcher(str(r.get("agent"))) is None}
)
if missing:
raise SessionError(" ".join(_unavailable(m) for m in missing))
+ placing = self._placing_note(computer_id) if computer_id else ""
# Call-signs count from T1 WITHIN this workspace, and every
# workspace counts from T1 again. That is the whole promise of a
@@ -2701,6 +2760,8 @@ class Registry:
permission_mode=launch_picks.normalize_permission(
agent, entry.get("permission_mode")
),
+ computer_id=computer_id or "",
+ placing=placing,
)
)
@@ -2716,7 +2777,15 @@ class Registry:
len(terminals),
root,
)
- return session
+ if computer_id:
+ try:
+ await self._place_new(session, list(session.terminals), computer_id)
+ except BaseException:
+ # Also when the request itself was cancelled: a workspace whose
+ # panes can never start is closed rather than left behind.
+ await self.end(session.id)
+ raise
+ return session
# ------------------------------------------------------- workspace helpers
def _find_by_folder(self, root: Path) -> Session | None:
@@ -3097,7 +3166,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,
+ # A pane saved while its folder was still being copied has no
+ # folder on that computer to start in; it comes back here.
+ computer_id=entry.computer_id if entry.remote_folder else "",
remote_folder=entry.remote_folder,
offload_snapshot=entry.offload_snapshot,
was_running=entry.running,
@@ -3830,6 +3901,10 @@ class Registry:
raise SessionNotReady("No Agentic-IDE session is running.")
raise SessionError(f"Unknown terminal: {key}")
session, term = found
+ if term.placing:
+ # Its folder is still travelling to the computer it will run on; a
+ # viewer attaching now would start the agent in the wrong place.
+ raise SessionNotReady(term.placing)
if cols < MIN_VIEWER_COLS or rows < MIN_VIEWER_ROWS:
# A handshake tile too narrow for the agent to draw in, which is how
# a whole conversation ends up printed one character per line (the
@@ -5097,6 +5172,8 @@ class Registry:
model: str | None = None,
effort: str | None = None,
permission_mode: str | None = None,
+ computer_id: Any = INHERIT_PLACEMENT,
+ folder: str = "",
) -> Terminal:
"""Open one more terminal in the running workspace.
@@ -5131,6 +5208,14 @@ class Registry:
"another one of these settings", and a model quietly carried onto a
pane somebody opened to try something else is the confusing kind of
helpful.
+
+ ``computer_id`` says where the pane RUNS: a connected computer's id,
+ ``None`` for this machine, or (the default) where its neighbours run —
+ a split beside its anchor, any other pane with the workspace when all
+ of it runs on one computer. A pane for a computer is set up there
+ before it can start (:meth:`_place_new`) and removed again if that
+ fails. ``folder`` opens it in another folder than the workspace's (a
+ worktree fork).
"""
selected_id = workspace_id or self.active_id
async with self._lock:
@@ -5161,7 +5246,9 @@ class Registry:
chosen = _prevailing_agent(session)
if not is_runnable(chosen):
raise SessionError(f"Unknown agent: {chosen}")
- if agent_argv(chosen) is None:
+ target = self._new_pane_computer(session, base if anchor else None, computer_id)
+ launcher = remote_agent_argv if target else agent_argv
+ if launcher(chosen) is None:
raise SessionError(_unavailable(chosen))
# Unused within THIS workspace — the scope a positional call-sign
@@ -5223,6 +5310,9 @@ class Registry:
model=launch_picks.normalize_model(chosen, model),
effort=launch_picks.normalize_effort(chosen, effort),
permission_mode=launch_picks.normalize_permission(chosen, permission_mode),
+ folder=folder,
+ computer_id=target,
+ placing=self._placing_note(target) if target else "",
)
session.terminals.append(term)
# Where it goes is the tree's business, and the distinction is the
@@ -5267,7 +5357,16 @@ class Registry:
direction,
base.name if base else "the grid",
)
- return term
+ if term.computer_id:
+ try:
+ await self._place_new(session, [term], term.computer_id)
+ except BaseException:
+ # Nothing ever started (the pane was gated); take it away rather
+ # than leave a pane that can never start — also when the request
+ # itself was cancelled.
+ await self.close_terminals([term.name], workspace_id=session.id)
+ raise
+ return term
def fork_suggestion(self, wanted: str, workspace_id: str | None = None) -> dict[str, Any]:
"""What the fork dialog offers for pane ``wanted``, before anything is made.
@@ -5311,6 +5410,15 @@ class Registry:
target = computer_id or ""
if term.computer_id == target:
return {"moved": False, "message": "The pane already runs there."}
+ if term.placing:
+ raise SessionError(f"{term.name} is being moved already.")
+ if term.computer_id and target:
+ # Straight from one computer to another would copy this machine's
+ # stale folder and end the agent there with its work unreturned.
+ raise SessionError(
+ f"{term.name} runs on {self._computer_label(term.computer_id)}. "
+ "Bring it back to this computer first."
+ )
async with term.attach_lock:
was_live = bool(term.pty_id)
if target:
@@ -5325,29 +5433,80 @@ class Registry:
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."""
+ """Move every pane of a workspace, one folder transfer per folder.
+
+ To a computer: a pane already on ANOTHER computer stays there (the
+ messages say so) — moving it from there would lose its work. Back:
+ see :meth:`_bring_workspace_back`. Whatever moved before a failure is
+ remembered.
+ """
session = self.get(workspace_id)
if session is None:
raise SessionError("Unknown workspace.")
target = computer_id or ""
- placements: dict[str, remote.Placement] = {}
+ if not target:
+ return await self._bring_workspace_back(session)
+ placements: dict[str, tuple[remote.Placement, str]] = {}
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:
+ try:
+ for term in list(session.terminals):
+ if term.computer_id == target or term.placing:
+ continue
+ if term.computer_id:
+ messages.append(
+ f"{term.name} stays on {self._computer_label(term.computer_id)}; "
+ "bring it back first to move it."
+ )
+ continue
+ async with term.attach_lock:
+ was_live = bool(term.pty_id)
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()
+ if was_live:
+ await self._restart_in_place(session, term)
+ moved.append(term.key)
+ if message and message not in messages:
+ messages.append(message)
+ finally:
+ await self._persist()
+ return {"moved": moved, "messages": messages}
+
+ async def _bring_workspace_back(self, session: Session) -> dict[str, Any]:
+ """Bring every remote pane of ``session`` home, one folder transfer per folder.
+
+ Every agent stops BEFORE any folder is packed — a sibling still writing
+ while the first pane's copy came home lost its last edits — and the
+ panes are gated meanwhile so no viewer restarts one there. Each
+ (computer, folder) comes back once however many panes shared it: one
+ return per pane used to make a second branch, collide on its name and
+ leave the workspace half moved.
+ """
+ away = [t for t in session.terminals if t.computer_id and not t.placing]
+ moved: list[str] = []
+ messages: list[str] = []
+ live: set[str] = set()
+ returns: dict[tuple[str, str], remote.Return] = {}
+ for term in away:
+ term.placing = "Bringing the work back to this computer…"
+ try:
+ for term in away:
+ async with term.attach_lock:
+ if term.pty_id:
+ live.add(term.key)
+ await self._stop_for_move(term, self._pool(term))
+ for term in away:
+ async with term.attach_lock:
+ message = await self._bring_back_locked(session, term, returns)
+ term.placing = ""
+ if term.key in live:
+ await self._restart_in_place(session, term)
+ moved.append(term.key)
+ if message and message not in messages:
+ messages.append(message)
+ finally:
+ for term in away:
+ term.placing = ""
+ await self._persist()
return {"moved": moved, "messages": messages}
async def _stop_for_move(self, term: Terminal, pool: Any) -> None:
@@ -5374,82 +5533,240 @@ class Registry:
session: Session,
term: Terminal,
computer_id: str,
- placements: dict[str, remote.Placement],
+ placements: dict[str, tuple[remote.Placement, str]],
) -> str:
from jarvis.computers.remote_terminal import pool_for
+ from jarvis.computers.service import ComputerError
+
+ pool = pool_for(computer_id)
+ local = term.cwd(session.folder)
+ where = self._computer_label(computer_id)
+ key, top = await self._copy_root(local)
+ async with self._copy_lock(computer_id, key):
+ try:
+ await remote.preflight(pool, _remote_commands([term]), where)
+ placement, joined = await self._join_or_copy(
+ pool, computer_id, local, key, top, term, placements
+ )
+ 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 PlacementError(str(exc)) from exc
+ except ComputerError as exc:
+ raise PlacementError(exc.message) from exc
+ except Exception as exc: # noqa: BLE001 - SSH/SFTP failures become one sentence
+ logger.warning("Agentic IDE: moving {} failed: {}", term.name, exc)
+ raise PlacementError(f"The move failed: {exc}") from exc
+ 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 ""
+ moved = (
+ "Moved with its conversation." if carried else "Moved; the agent starts fresh there."
+ )
+ joined_note = f" It works in the copy already on {where}." if joined else ""
+ term.notice = (
+ f"{moved}{joined_note} {remote.left_behind_note(placement.left_behind)}".strip()
+ )
+ return term.notice
+
+ async def _place_new(self, session: Session, terms: list[Terminal], computer_id: str) -> None:
+ """Set up panes created for ``computer_id``: check the server, copy each repo once.
+
+ The panes exist already, gated by ``placing`` so no viewer can start
+ them anywhere yet. The server is asked first whether tmux and every
+ pane's CLI are there — a missing CLI used to show up only as a dead
+ pane after a long upload. A copy another pane already works in on
+ that computer is JOINED, not sent again.
+ """
+ from jarvis.computers.remote_terminal import pool_for
+ from jarvis.computers.service import ComputerError
pool = pool_for(computer_id)
- local_folder = Path(term.cwd(session.folder))
- folder_key = os.path.normcase(str(local_folder))
+ where = self._computer_label(computer_id)
+ placements: dict[str, tuple[remote.Placement, str]] = {}
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),
- )
+ await remote.preflight(pool, _remote_commands(terms), where)
+ for term in terms:
+ local = term.cwd(session.folder)
+ key, top = await self._copy_root(local)
+ async with self._copy_lock(computer_id, key):
+ placement, joined = await self._join_or_copy(
+ pool, computer_id, local, key, top, term, placements
+ )
+ term.remote_folder = placement.remote_folder
+ term.offload_snapshot = placement.offload_snapshot or ""
+ term.notice = (
+ f"Works in the copy already on {where}."
+ if joined
+ else f"Copied to {where}. {remote.left_behind_note(placement.left_behind)}"
+ ).strip()
+ term.placing = ""
except remote.MoveError as exc:
- raise SessionError(str(exc)) from exc
+ raise PlacementError(str(exc)) from exc
+ except ComputerError as exc:
+ raise PlacementError(exc.message) 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."
+ logger.warning("Agentic IDE: setting up panes on {} failed: {}", where, exc)
+ raise PlacementError(f"Copying the folder to {where} failed: {exc}") from exc
+ await self._persist()
- async def _bring_back_locked(self, session: Session, term: Terminal) -> str:
- from jarvis.computers.remote_terminal import pool_for, tmux_session_name
+ async def _copy_root(self, local: str) -> tuple[str, Path | None]:
+ """What one copy on a computer covers: the git repo ``local`` is in, else the folder.
+
+ Returns ``(key, repo top)``. Panes in different subfolders of one repo
+ share ONE copy there (the whole repo is sent), so they must share its
+ lock and join each other: keyed on their own folders, a subfolder pane
+ sent the repo again and reset it under the agent already working in it.
+ """
+ return await asyncio.to_thread(_copy_key, local)
+
+ async def _join_or_copy(
+ self,
+ pool: Any,
+ computer_id: str,
+ local: str,
+ key: str,
+ top: Path | None,
+ exclude: Terminal,
+ placements: dict[str, tuple[remote.Placement, str]],
+ ) -> tuple[remote.Placement, bool]:
+ """The copy ``local`` works in on ``computer_id``, and whether it joined one.
+
+ Caller holds the copy lock for ``key``. The same repo seen from another
+ subfolder maps to the matching subfolder of the copy.
+ """
+ known = placements.get(key) or await self._sibling_placement(computer_id, key, exclude)
+ if known is None:
+ placement = await remote.push_code(pool, Path(local))
+ placements[key] = (placement, local)
+ return placement, False
+ placements[key] = known
+ base, base_local = known
+ if top is None or os.path.normcase(base_local) == os.path.normcase(local):
+ return remote.Placement(base.remote_folder, base.offload_snapshot), True
+ folder = await asyncio.to_thread(
+ remote.joined_folder, base.remote_folder, Path(base_local), Path(local), top
+ )
+ return remote.Placement(folder, base.offload_snapshot), True
+
+ async def _sibling_placement(
+ self, computer_id: str, key: str, exclude: Terminal
+ ) -> tuple[remote.Placement, str] | None:
+ """The copy another pane already works in on ``computer_id``, and that pane's folder."""
+ for session in list(self._sessions.values()):
+ for other in list(session.terminals):
+ if (
+ other is exclude
+ or other.computer_id != computer_id
+ or not other.remote_folder
+ or other.placing
+ ):
+ continue
+ other_local = other.cwd(session.folder)
+ other_key, _top = await self._copy_root(other_local)
+ if other_key == key:
+ placement = remote.Placement(
+ other.remote_folder, other.offload_snapshot or None
+ )
+ return placement, other_local
+ return None
+
+ def _copy_lock(self, computer_id: str, key: str) -> asyncio.Lock:
+ return self._copy_locks.setdefault((computer_id, key), asyncio.Lock())
+
+ @staticmethod
+ def _new_pane_computer(session: Session, anchor: Terminal | None, wanted: Any) -> str:
+ """Where a new pane runs: named, else beside its anchor, else with the workspace."""
+ if wanted is not INHERIT_PLACEMENT:
+ return str(wanted or "")
+ if anchor is not None:
+ return anchor.computer_id
+ places = {t.computer_id for t in session.terminals}
+ return places.pop() if len(places) == 1 else ""
+
+ @staticmethod
+ def _computer_label(computer_id: str) -> str:
+ """The computer's name for messages."""
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"
+ return get_service().get(computer_id).name
+ except Exception: # noqa: BLE001 - a removed or unreadable record still needs a word
+ return "the other computer"
+
+ def _placing_note(self, computer_id: str) -> str:
+ return f"Copying the folder to {self._computer_label(computer_id)}…"
+
+ async def _bring_back_locked(
+ self,
+ session: Session,
+ term: Terminal,
+ returns: dict[tuple[str, str], remote.Return] | None = None,
+ ) -> str:
+ """Bring one pane home; ``returns`` shares one return per copy across calls.
+
+ The pane is gated meanwhile and the copy's lock is held, so no new pane
+ joins a copy that is being packed up.
+ """
+ from jarvis.computers.remote_terminal import pool_for, tmux_session_name
+
+ pool = pool_for(term.computer_id)
+ term.placing = term.placing or "Bringing the work back to this computer…"
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 = ""
+ 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))
+ name = self._computer_label(term.computer_id)
+ copy_key, _top = await self._copy_root(str(local_folder))
+ key = (term.computer_id, copy_key)
+ async with self._copy_lock(term.computer_id, copy_key):
+ try:
+ outcome = returns.get(key) if returns is not None else None
+ if outcome is None:
+ outcome = await remote.pull_code(
+ pool,
+ local_folder,
+ term.remote_folder,
+ term.offload_snapshot or None,
+ name,
+ )
+ if returns is not None:
+ returns[key] = outcome
+ 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 PlacementError(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 PlacementError(f"Bringing the pane back failed: {exc}") from exc
+ if not carried:
+ term.resume = None
+ term.computer_id = ""
+ term.remote_folder = ""
+ term.offload_snapshot = ""
+ finally:
+ term.placing = ""
return outcome.message
async def _restart_in_place(self, session: Session, term: Terminal) -> None:
@@ -5526,10 +5843,11 @@ class Registry:
model=source.model,
effort=source.effort,
permission_mode=source.permission_mode,
+ folder=folder,
)
# No await between the pane's creation and these, so no viewer can
- # attach (and spawn) before the pane knows it is a fork.
- term.folder = folder
+ # attach (and spawn) before the pane knows it is a fork. (A pane for
+ # a computer was gated by ``placing`` until add_terminal returned.)
term.branch = branch
term.fork_from = source.resume
await self._persist()
@@ -5886,6 +6204,10 @@ class Registry:
pool.close(term.pty_id)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
+ elif term.computer_id and term.remote_folder and hasattr(pool, "end_session"):
+ # Nobody is watching it, but its agent may still be working
+ # in tmux on the computer: closing the pane ends it there too.
+ pool.end_session(term.history_id)
term.pty_id = None
term.status = "exited"
term.viewer_output = None
@@ -6766,7 +7088,9 @@ __all__ = [
"MAX_GRID_ROWS",
"MAX_TERMINALS",
"MAX_WORKSPACES",
+ "INHERIT_PLACEMENT",
"PLAIN_TERMINAL",
+ "PlacementError",
"Registry",
"Session",
"SessionError",
diff --git a/jarvis/computers/remote_terminal.py b/jarvis/computers/remote_terminal.py
index 4ea3fd9c73..4d9b813024 100644
--- a/jarvis/computers/remote_terminal.py
+++ b/jarvis/computers/remote_terminal.py
@@ -247,6 +247,14 @@ class SshPtyPool:
)
task.add_done_callback(_log_task_failure)
+ def end_session(self, identity: str) -> None:
+ """End the tmux session of a pane nobody is viewing (by its ``history_id``)."""
+ name = tmux_session_name(identity)
+ task = asyncio.get_running_loop().create_task(
+ self._kill_session(name), name=f"ssh-pty-kill-{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)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index fefaed9152..5d090a9514 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -113,11 +113,13 @@ from jarvis.agentic_ide.folders import (
from jarvis.agentic_ide.names import default_names
from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
+ INHERIT_PLACEMENT,
MAX_PROMPT_CHARS,
MAX_TERMINAL_NAME,
MAX_TERMINALS,
MAX_WORKSPACES,
PendingPromptAttachmentBatch,
+ PlacementError,
Session,
SessionError,
SessionNotReady,
@@ -271,7 +273,8 @@ class StartSessionRequest(BaseModel):
default=None,
description=(
"Run every terminal on this connected computer (Computers) instead of "
- "this machine; the folder is copied there first."
+ "this machine; the server is checked and the folder is copied there "
+ "first. The CLIs need to be installed there, not here."
),
)
@@ -314,6 +317,14 @@ class AddTerminalRequest(BaseModel):
default=None,
description="Call-sign of the terminal to split; defaults to the last one.",
)
+ computer_id: str | None = Field(
+ default=None,
+ description=(
+ "Where the new terminal runs: a connected computer's id, or null for "
+ "this machine. Omitted, it runs where its anchor runs (or where the "
+ "whole workspace runs); a computer gets the folder copied first."
+ ),
+ )
direction: str = Field(
default="right",
description=(
@@ -2146,22 +2157,19 @@ async def start_session(request: Request, req: StartSessionRequest) -> dict:
history with folders the user never selected.
"""
try:
+ # With a computer, the panes are created gated and set up THERE before
+ # this returns; a viewer that attaches meanwhile is told "not yet".
session = await get_registry().start(
req.folder,
[t.model_dump() for t in req.terminals],
project_id=req.project_id,
name=req.name,
+ computer_id=req.computer_id or None,
)
+ except PlacementError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
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:
@@ -2179,7 +2187,13 @@ async def start_session(request: Request, req: StartSessionRequest) -> dict:
# of a workspace this one just replaced at the front, and a grid nobody
# corrects is a grid whose panes attach to the wrong workspace.
await _announce_workspace(request, session, "opened")
- return {"ok": True, "session": session.to_dict(), "state": get_registry().state()}
+ notices = [t.notice for t in session.terminals if t.notice]
+ return {
+ "ok": True,
+ "session": session.to_dict(),
+ "message": notices[0] if notices else "",
+ "state": get_registry().state(),
+ }
@router.delete(
@@ -2663,10 +2677,22 @@ async def add_terminal(req: AddTerminalRequest) -> dict:
model=req.model,
effort=req.effort,
permission_mode=req.permission_mode,
+ # Absent means "where its neighbours run"; an explicit null means
+ # this machine — the two must not collapse into one default.
+ computer_id=(
+ req.computer_id if "computer_id" in req.model_fields_set else INHERIT_PLACEMENT
+ ),
)
+ except PlacementError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
except SessionError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
- return {"ok": True, "terminal": term.to_dict(), "state": get_registry().state()}
+ return {
+ "ok": True,
+ "terminal": term.to_dict(),
+ "message": term.notice,
+ "state": get_registry().state(),
+ }
@router.get("/terminals/{name}/fork", summary="What a fork of a terminal would be called")
diff --git a/tests/unit/agentic_ide/test_remote_placement.py b/tests/unit/agentic_ide/test_remote_placement.py
index 9816b912c4..c939903323 100644
--- a/tests/unit/agentic_ide/test_remote_placement.py
+++ b/tests/unit/agentic_ide/test_remote_placement.py
@@ -10,6 +10,7 @@ recorded stand-in.
from __future__ import annotations
+import asyncio
from pathlib import Path
from typing import Any
@@ -168,3 +169,223 @@ async def test_bringing_back_kills_the_remote_agent_and_runs_here_again(
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"
+
+
+# -- creating panes directly on a computer -------------------------------------
+
+
+def _pushes(moves: list[Any]) -> list[Any]:
+ return [m for m in moves if m[0] == "push"]
+
+
+async def test_a_workspace_opened_on_a_computer_needs_no_local_cli_and_copies_once(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ local, far, moves = pools
+ monkeypatch.setattr(ide, "agent_argv", lambda name: None) # nothing installed here
+ registry = ide.Registry(pty_manager=local)
+
+ session = await registry.start(
+ str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}], computer_id="c_1"
+ )
+
+ assert all(t.computer_id == "c_1" and t.remote_folder for t in session.terminals)
+ assert _pushes(moves) == [("push", Path(str(tmp_path)))], "one copy for both panes"
+ term = session.terminals[0]
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+ assert local.spawns == [], "nothing starts on this machine"
+ assert far.spawns[-1]["argv"][0] == "claude"
+ assert far.spawns[-1]["cwd"] == "/home/u/jarvis-workspaces/app-abc123"
+
+
+async def test_a_viewer_that_attaches_during_the_copy_is_told_to_wait(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ local, far, _moves = pools
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def slow_push(_pool: object, folder: Path) -> remote.Placement:
+ started.set()
+ await release.wait()
+ return remote.Placement("/srv/app", "a" * 40)
+
+ monkeypatch.setattr(remote, "push_code", slow_push)
+ registry = ide.Registry(pty_manager=local)
+ opening = asyncio.create_task(
+ registry.start(str(tmp_path), [{"agent": "claude"}], computer_id="c_1")
+ )
+ await started.wait()
+ [session] = registry.sessions
+ term = session.terminals[0]
+
+ with pytest.raises(ide.SessionNotReady, match="Copying the folder"):
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+ assert local.spawns == [] and far.spawns == []
+
+ # A restart in the middle of the copy brings the pane back HERE: there is
+ # no folder on the computer yet for it to start in.
+ snapshot = registry.snapshot()
+ assert snapshot is not None
+ again = ide.Registry(pty_manager=FakePtyManager())
+ await again.restore(snapshot)
+ assert again.sessions[0].terminals[0].computer_id == ""
+
+ release.set()
+ await opening
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+ assert far.spawns[-1]["cwd"] == "/srv/app"
+
+
+async def test_new_panes_run_where_their_neighbours_run_unless_told(
+ 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"}], computer_id="c_1")
+
+ split = await registry.add_terminal(workspace_id=session.id, anchor=session.terminals[0].name)
+ appended = await registry.add_terminal(workspace_id=session.id)
+ here = await registry.add_terminal(workspace_id=session.id, computer_id=None)
+
+ assert split.computer_id == "c_1" and split.remote_folder
+ assert appended.computer_id == "c_1"
+ assert here.computer_id == "" and here.remote_folder == ""
+ assert len(_pushes(moves)) == 1, "new panes join the copy already there"
+ assert "copy already on" in split.notice
+
+ # A workspace running here can still get one pane on the computer.
+ plain = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ far_pane = await registry.add_terminal(workspace_id=plain.id, computer_id="c_1")
+ assert far_pane.computer_id == "c_1"
+ assert plain.terminals[0].computer_id == ""
+
+
+async def test_a_second_placement_of_a_folder_joins_the_running_copy(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ local, _far, moves = pools
+ registry = ide.Registry(pty_manager=local)
+ first = await registry.start(str(tmp_path), [{"agent": "claude"}], computer_id="c_1")
+ second = await registry.start(str(tmp_path), [{"agent": "claude"}])
+
+ await registry.place_workspace(second.id, computer_id="c_1")
+
+ assert len(_pushes(moves)) == 1, "sending it again reset the server copy under the agent"
+ assert second.terminals[0].remote_folder == first.terminals[0].remote_folder
+
+
+async def test_a_server_without_the_cli_refuses_before_anything_is_copied(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ local, far, moves = pools
+
+ async def run(command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
+ far.commands.append(command)
+ return 0, "missing:Claude Code\n", ""
+
+ monkeypatch.setattr(far, "run", run)
+ registry = ide.Registry(pty_manager=local)
+
+ with pytest.raises(ide.PlacementError, match="not installed"):
+ await registry.start(str(tmp_path), [{"agent": "claude"}], computer_id="c_1")
+ assert registry.sessions == [], "the half-made workspace is closed again"
+ assert _pushes(moves) == []
+
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ with pytest.raises(ide.PlacementError):
+ await registry.add_terminal(workspace_id=session.id, computer_id="c_1")
+ assert len(session.terminals) == 1, "the pane that could never start is gone"
+
+
+async def test_bringing_a_workspace_back_stops_every_agent_then_returns_each_folder_once(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ local, far, moves = pools
+ closing = far.close
+
+ def close(terminal_id: str) -> None:
+ moves.append(("stop", terminal_id))
+ closing(terminal_id)
+
+ monkeypatch.setattr(far, "close", close)
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(
+ str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}], computer_id="c_1"
+ )
+ for term in session.terminals:
+ await registry.attach(term.key, 100, 30, _sink, _gone, workspace_id=session.id)
+
+ result = await registry.place_workspace(session.id, computer_id=None)
+
+ pulls = [i for i, m in enumerate(moves) if m[0] == "pull"]
+ stops = [i for i, m in enumerate(moves) if m[0] == "stop"]
+ assert len(pulls) == 1, "one return for the shared folder, not one per pane"
+ assert len(stops) == 2 and max(stops) < pulls[0], "both agents stopped before packing"
+ assert all(t.computer_id == "" for t in session.terminals)
+ assert len(local.spawns) == 2, "both run here again"
+ assert result["messages"] == ["back"]
+
+
+async def test_a_workspace_moving_on_leaves_panes_on_another_computer_alone(
+ 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"}])
+ first, second = session.terminals
+ await registry.place_terminal(first.key, workspace_id=session.id, computer_id="c_1")
+
+ result = await registry.place_workspace(session.id, computer_id="c_2")
+
+ assert first.computer_id == "c_1"
+ assert second.computer_id == "c_2"
+ assert any("stays on" in m for m in result["messages"])
+ with pytest.raises(ide.SessionError, match="Bring it back"):
+ await registry.place_terminal(first.key, workspace_id=session.id, computer_id="c_2")
+
+
+async def test_keep_working_on_quit_moves_running_workspaces(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.agentic_ide import offload_on_quit
+
+ local, far, _moves = pools
+ monkeypatch.setattr(offload_on_quit, "target", lambda: "c_1")
+ 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)
+
+ moved = await offload_on_quit.offload_before_quit(registry)
+
+ assert moved == [session.id]
+ assert term.computer_id == "c_1" and far.spawns, "the agent runs on the server now"
+
+
+async def test_a_subfolder_of_the_same_repo_joins_the_running_copy(
+ pools: tuple[FakePtyManager, RemotePool, list[Any]], tmp_path: Path
+) -> None:
+ import subprocess
+
+ local, _far, moves = pools
+ subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) # noqa: S603, S607, ASYNC221
+ (tmp_path / "pkg").mkdir()
+ registry = ide.Registry(pty_manager=local)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}], computer_id="c_1")
+
+ inner = await registry.add_terminal(
+ workspace_id=session.id, computer_id="c_1", folder=str(tmp_path / "pkg")
+ )
+
+ assert len(_pushes(moves)) == 1, "one repo, one copy — a second send reset it"
+ assert inner.remote_folder == "/home/u/jarvis-workspaces/app-abc123/pkg"
diff --git a/tests/unit/agentic_ide/test_remote_sync.py b/tests/unit/agentic_ide/test_remote_sync.py
index d42ada2010..a631bd136b 100644
--- a/tests/unit/agentic_ide/test_remote_sync.py
+++ b/tests/unit/agentic_ide/test_remote_sync.py
@@ -13,6 +13,7 @@ import asyncio
import shutil
import subprocess
import sys
+import types
from pathlib import Path
import pytest
@@ -202,3 +203,151 @@ 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"
)
+
+
+async def test_secrets_and_huge_new_files_stay_on_this_machine(
+ project: Path, tmp_path: Path, copies: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(remote, "MAX_FILE_BYTES", 1000)
+ (project / "deploy.pem").write_text("committed on purpose\n", encoding="utf-8")
+ _git(project, "add", "deploy.pem")
+ _git(project, "commit", "-q", "-m", "tracked key")
+ (project / ".env").write_text("API_KEY=secret\n", encoding="utf-8")
+ (project / ".env.example").write_text("API_KEY=\n", encoding="utf-8")
+ (project / "keys").mkdir()
+ (project / "keys" / "id_ed25519").write_text("-----BEGIN OPENSSH\n", encoding="utf-8")
+ (project / "big.bin").write_bytes(b"0" * 2000)
+ (project / "notes.md").write_text("fine\n", encoding="utf-8")
+ server = tmp_path / "server-home"
+ server.mkdir()
+
+ placement = await remote.push_code(LocalPool(server), project)
+
+ there = Path(placement.remote_folder)
+ assert (there / "notes.md").is_file()
+ assert (there / ".env.example").is_file(), "a template holds no secret"
+ assert (there / "deploy.pem").is_file(), "what is committed already travels"
+ for held in (".env", "keys/id_ed25519", "big.bin"):
+ assert not (there / held).exists(), held
+ assert set(placement.left_behind) == {".env", "keys/id_ed25519", "big.bin"}
+ assert ".env" in remote.left_behind_note(placement.left_behind)
+
+
+async def test_bring_back_still_applies_when_secrets_stayed_here(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ (project / ".env").write_text("API_KEY=secret\n", encoding="utf-8")
+ 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("print('server')\n", encoding="utf-8")
+
+ outcome = await remote.pull_code(
+ pool, project, placement.remote_folder, placement.offload_snapshot, "vps"
+ )
+
+ assert outcome.applied, outcome.message
+ assert (project / ".env").read_text(encoding="utf-8") == "API_KEY=secret\n"
+
+
+async def test_bring_back_is_byte_exact_for_blank_line_hunks_and_other_encodings(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ (project / "text.txt").write_text("one\ntwo\n\n", encoding="utf-8")
+ _git(project, "add", "text.txt")
+ _git(project, "commit", "-q", "-m", "ends on a blank line")
+ server = tmp_path / "server-home"
+ server.mkdir()
+ pool = LocalPool(server)
+ placement = await remote.push_code(pool, project)
+ there = Path(placement.remote_folder)
+ (there / "text.txt").write_text("ONE\ntwo\n\n", encoding="utf-8")
+ (there / "latin.txt").write_bytes("caf\xe9\n".encode("latin-1"))
+
+ outcome = await remote.pull_code(
+ pool, project, placement.remote_folder, placement.offload_snapshot, "vps"
+ )
+
+ assert outcome.applied, outcome.message
+ assert (project / "text.txt").read_bytes().replace(b"\r\n", b"\n") == b"ONE\ntwo\n\n"
+ assert (project / "latin.txt").read_bytes().replace(b"\r\n", b"\n") == b"caf\xe9\n"
+
+
+def test_a_branch_name_taken_in_the_same_second_gets_a_counter(
+ project: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(remote, "time", types.SimpleNamespace(strftime=lambda _f: "20260930-1200"))
+ first = remote._free_branch(project, "jarvis/vps")
+ _git(project, "branch", first)
+
+ assert first == "jarvis/vps/20260930-1200"
+ assert remote._free_branch(project, "jarvis/vps") == "jarvis/vps/20260930-1200-2"
+
+
+async def test_preflight_names_every_missing_command(tmp_path: Path) -> None:
+ pool = LocalPool(tmp_path)
+
+ with pytest.raises(remote.MoveError, match="Nope CLI is not installed on vps"):
+ await remote.preflight(pool, {"git": "git", "Nope CLI": "no-such-cli-4711"}, "vps")
+ await remote.preflight(pool, {"git": "git"}, "vps")
+
+
+async def test_folder_without_git_leaves_secrets_here(tmp_path: Path, copies: None) -> None:
+ plain = tmp_path / "plain"
+ (plain / "sub").mkdir(parents=True)
+ (plain / "main.txt").write_text("hello\n", encoding="utf-8")
+ (plain / ".env").write_text("TOKEN=x\n", encoding="utf-8")
+ (plain / "sub" / "id_rsa").write_text("key\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").is_file()
+ assert not (there / ".env").exists()
+ assert not (there / "sub" / "id_rsa").exists()
+ assert set(placement.left_behind) == {".env", "sub/id_rsa"}
+
+
+async def test_a_committed_file_renamed_to_env_stays_here(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ (project / "sample.cfg").write_text("KEY=placeholder\n", encoding="utf-8")
+ _git(project, "add", "sample.cfg")
+ _git(project, "commit", "-q", "-m", "template")
+ (project / "sample.cfg").rename(project / ".env") # git would call this a rename
+ server = tmp_path / "server-home"
+ server.mkdir()
+
+ placement = await remote.push_code(LocalPool(server), project)
+
+ assert not (Path(placement.remote_folder) / ".env").exists()
+ assert ".env" in placement.left_behind
+
+
+async def test_an_assume_unchanged_edit_still_travels(
+ project: Path, tmp_path: Path, copies: None
+) -> None:
+ _git(project, "update-index", "--assume-unchanged", "app.py")
+ (project / "app.py").write_text("print('edited anyway')\n", encoding="utf-8")
+ server = tmp_path / "server-home"
+ server.mkdir()
+
+ placement = await remote.push_code(LocalPool(server), project)
+
+ there = Path(placement.remote_folder) / "app.py"
+ assert there.read_text(encoding="utf-8") == "print('edited anyway')\n"
+ assert "h app.py" in _git(project, "ls-files", "-v", "app.py"), "the user's own mark stays"
+
+
+def test_joined_folder_maps_a_subfolder_into_the_same_copy(tmp_path: Path) -> None:
+ top = tmp_path / "repo"
+ (top / "pkg" / "sub").mkdir(parents=True)
+
+ from_root = remote.joined_folder("/h/jw/repo-1", top, top / "pkg", top)
+ from_sub = remote.joined_folder("/h/jw/repo-1/pkg/sub", top / "pkg" / "sub", top, top)
+
+ assert from_root == "/h/jw/repo-1/pkg"
+ assert from_sub == "/h/jw/repo-1"