Skip to content

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

fix(computers): make a connected Windows computer work for agents and the IDE

rubenluetke10-beep0e2e5a19dcce
diff --git a/jarvis/agent_chat/remote_cli.py b/jarvis/agent_chat/remote_cli.py
index 40abd27a68..812eebcde0 100644
--- a/jarvis/agent_chat/remote_cli.py
+++ b/jarvis/agent_chat/remote_cli.py
@@ -17,6 +17,11 @@ What does NOT travel:
* Jarvis' own MCP tools. That endpoint listens on this computer's localhost
and a remote CLI cannot reach it, so ``--mcp-config`` / the Codex
``mcp_servers`` overrides are dropped for remote turns.
+
+A Windows computer cannot take the turn on its command line (``cmd.exe``
+mangles non-ASCII text and line breaks, and stops at 8 191 characters), so
+there the system prompt is uploaded as a file and the CLI is started by a
+small Git Bash launcher uploaded next to it (``jarvis.computers.remote_os``).
"""
from __future__ import annotations
@@ -80,13 +85,15 @@ def remote_argv(
local_cwd: str,
remote_cwd: str,
system_prompt_files: dict[str, str] | None = None,
+ uploaded_prompt_files: dict[str, str] | None = None,
) -> list[str]:
"""Rewrite a locally planned argv for the remote machine.
The local launcher prefix becomes the bare ``binary`` (found on the
remote PATH); the local working folder becomes the remote one; Jarvis'
localhost MCP wiring is dropped; an ``--append-system-prompt-file`` (a
- local file) is inlined as ``--append-system-prompt``.
+ local file) points at its uploaded copy when ``uploaded_prompt_files``
+ has one, and is inlined as ``--append-system-prompt`` otherwise.
"""
parts = list(argv)
start = 0
@@ -96,6 +103,7 @@ def remote_argv(
out: list[str] = [binary]
skip = False
files = system_prompt_files or {}
+ uploaded = uploaded_prompt_files or {}
for index, part in enumerate(rest):
if skip:
skip = False
@@ -107,8 +115,11 @@ def remote_argv(
skip = True
continue
if part == "--append-system-prompt-file" and index + 1 < len(rest):
- text = files.get(rest[index + 1])
skip = True
+ if rest[index + 1] in uploaded:
+ out += [part, uploaded[rest[index + 1]]]
+ continue
+ text = files.get(rest[index + 1])
if text:
out += ["--append-system-prompt", text]
continue
@@ -188,6 +199,65 @@ class RemoteCliProcess:
await self._stack.aclose()
+def placement_note(computer: Any, remote_cwd: str) -> str:
+ """The system-prompt section that tells a remote CLI where it runs.
+
+ The briefing it rides on was written for this computer; without the note
+ the agent answers "which PC are you on?" wrongly and reaches for Jarvis
+ tools that do not exist over there.
+ """
+ facts = getattr(computer, "facts", None)
+ details = [
+ part
+ for part in (
+ getattr(facts, "hostname", None) and f"host name {facts.hostname}",
+ getattr(facts, "os_name", None),
+ )
+ if part
+ ]
+ where = f'"{computer.name}"' + (f" ({', '.join(details)})" if details else "")
+ return (
+ "\n\n## Where you run\n\n"
+ f"You run on the connected computer {where}, reached over SSH from the "
+ f"person's main computer — not on the main computer itself. Your working "
+ f"folder there is {remote_cwd}. Jarvis' own tools (the jarvis MCP tools) "
+ "are not available on that computer; work with the files and programs there.\n"
+ )
+
+
+async def _windows_launch(
+ opened: Any,
+ host: Any,
+ agent_id: str,
+ argv: Sequence[str],
+ binary: str,
+ local_cwd: str,
+ remote_cwd: str,
+ env: dict[str, str],
+ prompts: dict[str, str],
+) -> str:
+ """Upload the system prompt and a Git Bash launcher; the command that runs it."""
+ from jarvis.computers import remote_os
+
+ uploaded: dict[str, str] = {}
+ for index, (local_path, text) in enumerate(prompts.items()):
+ name = remote_os.launcher_name(f"{agent_id}-prompt-{index}", ".md")
+ relative = f"{remote_os.LAUNCH_DIR}/{name}"
+ await remote_os.upload_text(opened, host, relative, text)
+ uploaded[local_path] = f"{host.home}/{relative}"
+ command_argv = remote_argv(
+ argv,
+ binary=binary,
+ local_cwd=local_cwd,
+ remote_cwd=remote_cwd,
+ uploaded_prompt_files=uploaded,
+ )
+ launcher = f"{remote_os.LAUNCH_DIR}/{remote_os.launcher_name(agent_id)}"
+ script = remote_os.launcher_script(remote_cwd, command_argv, remote_env(env))
+ await remote_os.upload_text(opened, host, launcher, script)
+ return host.launcher_command(launcher)
+
+
async def spawn(
computer_id: str,
*,
@@ -200,6 +270,7 @@ async def spawn(
system_prompt_files: dict[str, str] | None = None,
) -> RemoteCliProcess:
"""Start the CLI on ``computer_id`` inside the agent's remote workspace."""
+ from jarvis.computers import remote_os
from jarvis.computers.service import ComputerError, get_service
from jarvis.computers.ssh import SshError, run_command
from jarvis.society.remote import remote_workspace_expr
@@ -207,34 +278,54 @@ async def spawn(
stack = contextlib.AsyncExitStack()
try:
opened = await stack.enter_async_context(get_service().session(computer_id))
+ computer = get_service().get(computer_id)
+ host = await remote_os.remote_host(computer_id, opened)
+ if host.windows and not host.bash:
+ raise RemoteCliUnavailable(
+ f"{computer.name} runs Windows without Git for Windows, which coding "
+ f"agents need there. {remote_os.GIT_FOR_WINDOWS_HINT}"
+ )
folder = remote_workspace_expr(agent_id)
- probe = await run_command(
- opened,
- f"mkdir -p {folder} && cd {folder} && pwd && "
- f"(command -v {shlex.quote(binary)} >/dev/null 2>&1 && echo found || echo missing)",
- timeout_s=20,
+ # Git Bash's ``pwd -W`` answers C:/Users/... — the path a Windows CLI reads.
+ check = (
+ f"mkdir -p {folder} && cd {folder} && {'pwd -W' if host.windows else 'pwd'} && "
+ f"(command -v {shlex.quote(binary)} >/dev/null 2>&1 && echo found || echo missing)"
)
+ if host.windows:
+ probe = await remote_os.run_bash(opened, host, check, timeout_s=30)
+ else:
+ probe = await run_command(opened, check, timeout_s=20)
lines = [line.strip() for line in probe.stdout.splitlines() if line.strip()]
if len(lines) < 2:
- raise RemoteCliUnavailable("The agent's computer did not answer the setup check.")
+ said = (probe.stderr or probe.stdout).strip().splitlines()
+ raise RemoteCliUnavailable(
+ "The agent's computer did not answer the setup check"
+ + (f": {said[-1][:200]}" if said else ".")
+ )
remote_cwd, presence = lines[-2], lines[-1]
- computer = get_service().get(computer_id)
if presence != "found":
raise RemoteCliUnavailable(
f"Install {binary} on {computer.name} (and log in there once), "
"or set the agent to run on this computer."
)
- command_argv = remote_argv(
- argv,
- binary=binary,
- local_cwd=local_cwd,
- remote_cwd=remote_cwd,
- system_prompt_files=system_prompt_files,
- )
- assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in remote_env(env).items())
- command = (
- f"cd {shlex.quote(remote_cwd)} && exec env {assignments} {shlex.join(command_argv)}"
- )
+ note = placement_note(computer, remote_cwd)
+ prompts = {path: text + note for path, text in (system_prompt_files or {}).items()}
+ if host.windows:
+ command = await _windows_launch(
+ opened, host, agent_id, argv, binary, local_cwd, remote_cwd, env, prompts
+ )
+ else:
+ command_argv = remote_argv(
+ argv,
+ binary=binary,
+ local_cwd=local_cwd,
+ remote_cwd=remote_cwd,
+ system_prompt_files=prompts,
+ )
+ assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in remote_env(env).items())
+ command = (
+ f"cd {shlex.quote(remote_cwd)} && exec env {assignments} {shlex.join(command_argv)}"
+ )
log.info("agent chat: %s turn for %s runs on %s", runner, agent_id, computer.name)
process = await opened.conn.create_process(command, encoding=None)
except (ComputerError, SshError) as exc:
diff --git a/jarvis/agentic_ide/remote.py b/jarvis/agentic_ide/remote.py
index 8fb3344090..4293edfb12 100644
--- a/jarvis/agentic_ide/remote.py
+++ b/jarvis/agentic_ide/remote.py
@@ -338,6 +338,18 @@ async def preflight(pool: SshPtyPool, commands: Mapping[str, str], where: str) -
"""
if not commands:
return
+ host = await pool.host()
+ if host.windows:
+ if not host.bash:
+ raise MoveError(
+ f"{where} runs Windows and needs Git for Windows first. "
+ "Open Computers, then Prepare."
+ )
+ # Panes there run without tmux (``remote_terminal``); the rest is checked
+ # the same way, in Git Bash.
+ commands = {label: cmd for label, cmd in commands.items() if cmd != "tmux"}
+ if not commands:
+ return
checks = " ".join(
f"command -v {shlex.quote(command)} >/dev/null 2>&1 || printf '%s\\n' "
f"{shlex.quote('missing:' + label)};"
@@ -367,6 +379,7 @@ async def _remote_known(pool: SshPtyPool, remote_folder: str) -> list[str]:
async def _upload(pool: SshPtyPool, local: Path, remote: str) -> None:
+ remote = await pool.sftp_path(remote)
session = await pool.connection()
async with session.conn.start_sftp_client() as sftp:
await sftp.makedirs(str(PurePosixPath(remote).parent), exist_ok=True)
@@ -374,6 +387,7 @@ async def _upload(pool: SshPtyPool, local: Path, remote: str) -> None:
async def _download(pool: SshPtyPool, remote: str, local: Path) -> None:
+ remote = await pool.sftp_path(remote)
session = await pool.connection()
async with session.conn.start_sftp_client() as sftp:
await sftp.get(remote, str(local))
diff --git a/jarvis/computers/probe.py b/jarvis/computers/probe.py
index 7e070372a4..0daefcd622 100644
--- a/jarvis/computers/probe.py
+++ b/jarvis/computers/probe.py
@@ -1,11 +1,12 @@
-"""The read-only health script and its parser.
-
-A check runs ONE command over SSH: a POSIX shell script that prints labelled
-sections (hostname, OS, cores, memory, disk, uptime, load). It only reads —
-nothing is installed or changed. Linux answers every section; macOS answers
-through its own tools; a machine whose login shell is not POSIX (a Windows
-OpenSSH server) answers little or nothing, and the check still counts as
-online with fewer facts.
+"""The read-only health scripts and their parser.
+
+A check runs ONE script over SSH that prints labelled sections (hostname, OS,
+cores, memory, disk, uptime, load). It only reads — nothing is installed or
+changed. Linux answers every section of :data:`PROBE_SCRIPT`; macOS answers
+through its own tools; a Windows OpenSSH server gets
+:data:`WINDOWS_PROBE_SCRIPT` (PowerShell, sent on stdin), which prints the
+same sections in the same shapes, so one parser reads all three. Windows has
+no load average; that section stays empty.
"""
from __future__ import annotations
@@ -29,6 +30,30 @@ echo "@@loadavg"; cat /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/n
echo "@@end"
""".strip()
+#: The same sections from a Windows computer, in the shapes the Linux tools
+#: print (``/etc/os-release`` lines, ``/proc/meminfo`` kB, ``df -Pk`` columns).
+WINDOWS_PROBE_SCRIPT = r"""
+$ErrorActionPreference = 'SilentlyContinue'
+$os = Get-CimInstance Win32_OperatingSystem
+'@@hostname'; $env:COMPUTERNAME
+'@@uname'; "Windows $($os.Version) $env:PROCESSOR_ARCHITECTURE"
+'@@os'; 'ID=windows'; "PRETTY_NAME=$($os.Caption -replace '^Microsoft ', '')"
+'@@nproc'; [Environment]::ProcessorCount
+'@@meminfo'
+"MemTotal: $($os.TotalVisibleMemorySize) kB"
+"MemAvailable: $($os.FreePhysicalMemory) kB"
+'@@df'
+$drive = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'"
+if ($drive -and $drive.Size) {
+ $total = [int64]($drive.Size / 1KB); $free = [int64]($drive.FreeSpace / 1KB)
+ "$env:SystemDrive $total $($total - $free) $free - $env:SystemDrive\"
+}
+'@@uptime'
+if ($os.LastBootUpTime) { [int64]((Get-Date) - $os.LastBootUpTime).TotalSeconds }
+'@@loadavg'
+'@@end'
+""".strip()
+
@dataclass(frozen=True)
class ProbeReading:
diff --git a/jarvis/computers/remote_os.py b/jarvis/computers/remote_os.py
new file mode 100644
index 0000000000..c48aa0175e
--- /dev/null
+++ b/jarvis/computers/remote_os.py
@@ -0,0 +1,228 @@
+"""Which shell a connected computer answers in, and how to speak it.
+
+A POSIX machine (Linux, macOS, BSD) runs every command in ``sh`` — the
+original path, unchanged. A Windows machine with the OpenSSH server runs
+commands in ``cmd.exe`` (or PowerShell, when its ``DefaultShell`` says so),
+and three facts decide how Jarvis talks to it:
+
+* ``cmd.exe`` carries neither line breaks nor non-ASCII text on its command
+ line intact (measured: each non-ASCII letter arrived as two U+FFFD
+ replacement characters), and it caps the line at
+ 8 191 characters. So nothing of substance travels there: a script goes on
+ **stdin** and is read whole before it runs, and a program that needs stdin
+ or a terminal itself (a coding CLI's turn, an IDE pane) is started by a
+ small launcher file uploaded over SFTP (:func:`launcher_script`).
+* Windows PowerShell 5.1 ships with every Windows 10/11 and Server box: it
+ reads the machine's facts, what is installed, and plants a login key
+ (:data:`POWERSHELL_STDIN`).
+* Git for Windows' ``bash`` runs the same POSIX scripts the Linux path uses —
+ code sync, conversation copies, the launchers. Claude Code on Windows needs
+ Git for Windows anyway, and so does every git workspace.
+
+Detection is one ``echo`` that each shell answers differently
+(:data:`DETECT_COMMAND`), cached per computer and server identity
+(:func:`remote_host`).
+"""
+
+from __future__ import annotations
+
+import re
+import shlex
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from typing import Final, Literal
+
+from jarvis.computers.ssh import CommandResult, Session, SshError, run_command
+
+RemoteOs = Literal["posix", "windows"]
+RemoteShell = Literal["sh", "cmd", "powershell"]
+
+#: ``cmd`` prints ``Windows_NT $env:OS``, PowerShell prints ``%OS%`` and
+#: ``Windows_NT`` on two lines, ``sh`` prints ``%OS% :OS``.
+DETECT_COMMAND: Final[str] = "echo %OS% $env:OS"
+
+#: Runs the PowerShell script sent on stdin, whole (a multi-line block works),
+#: with UTF-8 both ways. Holds no ``$``, so it reads the same to ``cmd`` and
+#: to a PowerShell default shell.
+POWERSHELL_STDIN: Final[str] = (
+ "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "
+ '"[Console]::InputEncoding=[Text.UTF8Encoding]::new(0); '
+ "[Console]::OutputEncoding=[Text.UTF8Encoding]::new(0); "
+ '& ([scriptblock]::Create([Console]::In.ReadToEnd()))"'
+)
+
+#: Folder (relative to the remote home) for the launcher files of CLI turns
+#: and IDE panes on a Windows computer.
+LAUNCH_DIR: Final[str] = "jarvis-agents/.launch"
+
+#: Git Bash converts arguments and variables that look like POSIX paths when
+#: it starts a Windows program ("/help" would become "C:/Program Files/Git/
+#: help"). A launcher hands its argv over untouched.
+_NO_PATH_CONVERSION: Final[str] = "export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'"
+
+_WINDOWS_FACTS: Final[str] = r"""
+$ErrorActionPreference = 'SilentlyContinue'
+"home " + ($HOME -replace '\\', '/')
+$candidates = @()
+$git = Get-Command git -CommandType Application | Select-Object -First 1
+if ($git) { $candidates += Join-Path (Split-Path (Split-Path $git.Source)) 'bin\bash.exe' }
+$candidates += Join-Path $env:ProgramFiles 'Git\bin\bash.exe'
+$x86 = ${env:ProgramFiles(x86)}
+if ($x86) { $candidates += Join-Path $x86 'Git\bin\bash.exe' }
+if ($env:LOCALAPPDATA) { $candidates += Join-Path $env:LOCALAPPDATA 'Programs\Git\bin\bash.exe' }
+foreach ($path in $candidates) {
+ if ($path -and (Test-Path -LiteralPath $path)) { "bash " + $path; break }
+}
+""".strip()
+
+_DRIVE_PATH = re.compile(r"^[A-Za-z]:/")
+_PLAIN_PATH = re.compile(r"^[A-Za-z]:/[A-Za-z0-9/._-]*$")
+
+
+@dataclass(frozen=True)
+class RemoteHost:
+ """How to reach programs on one computer."""
+
+ os: RemoteOs = "posix"
+ default_shell: RemoteShell = "sh"
+ #: Windows only: the home folder with forward slashes (``C:/Users/ada``).
+ home: str = ""
+ #: Windows only: Git for Windows' bash, ``None`` when it is not installed.
+ bash: str | None = None
+
+ @property
+ def windows(self) -> bool:
+ return self.os == "windows"
+
+ def program(self, path: str, args: str = "") -> str:
+ """The command line that starts ``path`` in this computer's default shell.
+
+ The path is quoted once and nothing else on the line is; ``cmd`` keeps
+ such a line as it is, and PowerShell needs its call operator in front.
+ """
+ call = "& " if self.default_shell == "powershell" else ""
+ return f'{call}"{path}" {args}'.rstrip()
+
+ def bash_script_command(self) -> str:
+ """Git Bash reading a script from stdin, as a login shell."""
+ if not self.bash:
+ raise SshError("protocol", "Git for Windows is not installed on this computer.")
+ return self.program(self.bash, "-l -s")
+
+ def launcher_command(self, relative_path: str) -> str:
+ """Git Bash running an uploaded launcher (a path relative to the home folder).
+
+ The path goes absolute when the home folder needs no quoting; a home
+ with spaces or umlauts stays relative, which the SSH server resolves
+ from that same home — ``cmd`` gets one quoted part per line, never two.
+ """
+ if not self.bash:
+ raise SshError("protocol", "Git for Windows is not installed on this computer.")
+ target = f"{self.home}/{relative_path}" if _PLAIN_PATH.match(self.home) else relative_path
+ return self.program(self.bash, f"--noprofile --norc {target}")
+
+ def sftp_path(self, path: str) -> str:
+ """``C:/x`` is a bad message to the Windows SFTP server; ``/C:/x`` is not."""
+ if self.windows and _DRIVE_PATH.match(path):
+ return "/" + path
+ return path
+
+
+def parse_detect(stdout: str) -> tuple[RemoteOs, RemoteShell]:
+ if "Windows_NT" not in stdout:
+ return "posix", "sh"
+ return "windows", ("powershell" if "%OS%" in stdout else "cmd")
+
+
+def parse_windows_facts(stdout: str) -> tuple[str, str | None]:
+ home, bash = "", None
+ for raw in stdout.splitlines():
+ line = raw.strip()
+ if line.startswith("home "):
+ home = line[5:].strip()
+ elif line.startswith("bash "):
+ bash = line[5:].strip() or None
+ return home, bash
+
+
+async def run_powershell(session: Session, script: str, *, timeout_s: float) -> CommandResult:
+ """One PowerShell script on a Windows computer, sent on stdin."""
+ return await run_command(session, POWERSHELL_STDIN, timeout_s=timeout_s, stdin=script)
+
+
+async def run_bash(
+ session: Session, host: RemoteHost, script: str, *, timeout_s: float
+) -> CommandResult:
+ """One POSIX script in Git Bash on a Windows computer, sent on stdin."""
+ return await run_command(session, host.bash_script_command(), timeout_s=timeout_s, stdin=script)
+
+
+async def detect(session: Session) -> RemoteHost:
+ """Ask the computer which shell it speaks (and, on Windows, where Git Bash is)."""
+ answer = await run_command(session, DETECT_COMMAND, timeout_s=20)
+ os_name, shell = parse_detect(answer.stdout)
+ if os_name == "posix":
+ return RemoteHost()
+ facts = await run_powershell(session, _WINDOWS_FACTS, timeout_s=45)
+ home, bash = parse_windows_facts(facts.stdout)
+ return RemoteHost(os="windows", default_shell=shell, home=home, bash=bash)
+
+
+#: computer id -> (pinned server identity, what it answered)
+_CACHE: dict[str, tuple[str, RemoteHost]] = {}
+
+
+async def remote_host(computer_id: str, session: Session) -> RemoteHost:
+ """:func:`detect`, remembered while the server keeps its identity.
+
+ A Windows answer without Git Bash is asked again next time: installing
+ Git for Windows must take effect without a restart of the app.
+ """
+ cached = _CACHE.get(computer_id)
+ if cached is not None and cached[0] == session.host_key:
+ host = cached[1]
+ if not host.windows or host.bash:
+ return host
+ host = await detect(session)
+ _CACHE[computer_id] = (session.host_key, host)
+ return host
+
+
+def forget(computer_id: str) -> None:
+ _CACHE.pop(computer_id, None)
+
+
+def launcher_script(cwd: str, argv: Sequence[str], env: Mapping[str, str] | None = None) -> str:
+ """The Git Bash file that starts ``argv`` in ``cwd`` with stdin and terminal intact."""
+ lines = [f"cd -- {shlex.quote(cwd)} || exit 97"]
+ for key, value in (env or {}).items():
+ lines.append(f"export {key}={shlex.quote(value)}")
+ lines.append(_NO_PATH_CONVERSION)
+ lines.append("exec " + shlex.join(argv))
+ return "\n".join(lines) + "\n"
+
+
+def launcher_name(identity: str, suffix: str = ".sh") -> str:
+ """A file name (under :data:`LAUNCH_DIR`) that is safe on every shell."""
+ return re.sub(r"[^A-Za-z0-9_.-]", "-", identity)[:64] + suffix
+
+
+async def upload_text(session: Session, host: RemoteHost, path: str, text: str) -> None:
+ """Write ``text`` (UTF-8) to ``path`` on the computer, creating its folder."""
+ import asyncssh
+
+ remote = host.sftp_path(path)
+ folder = remote.rsplit("/", 1)[0] if "/" in remote else ""
+ try:
+ async with session.conn.start_sftp_client() as sftp:
+ if folder:
+ await sftp.makedirs(folder, exist_ok=True)
+ async with sftp.open(remote, "wb") as handle:
+ await handle.write(text.encode("utf-8"))
+ except (asyncssh.Error, OSError) as exc:
+ raise SshError("protocol", f"A file could not be written there: {exc}") from exc
+
+
+GIT_FOR_WINDOWS_HINT: Final[str] = (
+ "Install Git for Windows there (winget install --id Git.Git -e), then try again."
+)
diff --git a/jarvis/computers/remote_terminal.py b/jarvis/computers/remote_terminal.py
index 4d9b813024..4dd8ad5edb 100644
--- a/jarvis/computers/remote_terminal.py
+++ b/jarvis/computers/remote_terminal.py
@@ -16,6 +16,13 @@ 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.
+
+A Windows computer has no tmux. There a pane runs its agent directly in the
+SSH terminal (ConPTY), started by a small Git Bash launcher uploaded first
+(``jarvis.computers.remote_os``), and non-interactive commands run in Git Bash
+from stdin. The agent then lives as long as its channel: closing the app or
+losing the network ends it, and the pane reports closed instead of waiting to
+re-attach. A plain terminal there is PowerShell.
"""
from __future__ import annotations
@@ -31,8 +38,9 @@ from dataclasses import dataclass, field
from typing import Any
from uuid import uuid4
+from jarvis.computers import remote_os
from jarvis.computers.service import ComputerError, get_service
-from jarvis.computers.ssh import Session, close
+from jarvis.computers.ssh import Session, SshError, close
log = logging.getLogger(__name__)
@@ -73,6 +81,13 @@ def tmux_command(
)
+def windows_pane_argv(argv: tuple[str, ...] | list[str]) -> tuple[str, ...]:
+ """A pane's argv for a Windows computer: the login shell becomes PowerShell."""
+ if tuple(argv) == ("bash", "-l"):
+ return ("powershell.exe", "-NoLogo")
+ return tuple(argv)
+
+
def login_shell(command: str) -> str:
"""Run through a login shell so user-installed CLIs (npm, nvm) are on PATH."""
quoted = shlex.quote(command)
@@ -121,6 +136,7 @@ class SshPtyPool:
self._connect_fn = connect or (lambda: get_service().connect(computer_id))
self._session: Session | None = None
self._home: str | None = None
+ self._host: remote_os.RemoteHost | None = None
self._lock = asyncio.Lock()
self._panes: dict[str, _Pane] = {}
self._tmux_checked = False
@@ -135,21 +151,70 @@ class SshPtyPool:
self._session = await self._connect_fn()
return self._session
+ async def host(self) -> remote_os.RemoteHost:
+ """Which shell the computer speaks (asked again while Git Bash is missing)."""
+ if self._host is None or (self._host.windows and not self._host.bash):
+ session = await self.connection()
+ try:
+ self._host = await remote_os.remote_host(self.computer_id, session)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ return self._host
+
+ async def windows(self) -> bool:
+ return (await self.host()).windows
+
async def home(self) -> str:
- """The remote user's home directory (absolute), cached per connection."""
+ """The remote user's home directory (absolute), cached per connection.
+
+ On Windows it is written ``C:/Users/name``: the form Git Bash, git,
+ the coding CLIs and (through :meth:`sftp_path`) SFTP all accept.
+ """
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"
+ host = await self.host()
+ if host.windows:
+ self._home = host.home or "C:/Users/Public"
+ else:
+ 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 sftp_path(self, path: str) -> str:
+ return (await self.host()).sftp_path(path)
+
async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
- """One non-interactive command on the shared connection."""
+ """One non-interactive command on the shared connection.
+
+ A POSIX computer runs it in a login shell; a Windows one in Git Bash,
+ from stdin.
+ """
+ host = await self.host()
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,
- )
+ if host.windows:
+ if not host.bash:
+ raise ComputerError(
+ "This Windows computer needs Git for Windows first. "
+ + remote_os.GIT_FOR_WINDOWS_HINT,
+ status=409,
+ )
+ result = await asyncio.wait_for(
+ session.conn.run(
+ host.bash_script_command(),
+ input=command,
+ check=False,
+ encoding="utf-8",
+ errors="replace",
+ ),
+ timeout=timeout_s,
+ )
+ else:
+ 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 "")
@@ -178,17 +243,22 @@ class SshPtyPool:
"""
identity = str((meta or {}).get("history_id") or shell_id)
name = tmux_session_name(identity)
+ host = await self.host()
+ if host.windows:
+ command = await self._windows_launcher(host, name, shell_argv, cwd)
+ else:
+ command = login_shell(tmux_command(name, tuple(shell_argv), cwd, cols, rows))
pane = _Pane(
terminal_id=uuid4().hex,
tmux_name=name,
- command=login_shell(tmux_command(name, tuple(shell_argv), cwd, cols, rows)),
+ command=command,
cols=cols,
rows=rows,
on_output=on_output,
on_closed=on_closed,
on_probe=on_probe,
)
- if not self._tmux_checked:
+ if not self._tmux_checked and not host.windows:
code, _out, _err = await self.run("command -v tmux >/dev/null", timeout_s=20)
if code != 0:
raise ComputerError(
@@ -283,6 +353,29 @@ class SshPtyPool:
# -- internals ---------------------------------------------------------------
+ async def _windows_launcher(
+ self,
+ host: remote_os.RemoteHost,
+ name: str,
+ shell_argv: tuple[str, ...] | list[str],
+ cwd: str,
+ ) -> str:
+ """Upload the pane's Git Bash launcher; the command that starts it."""
+ if not host.bash:
+ raise ComputerError(
+ "This Windows computer needs Git for Windows first. "
+ + remote_os.GIT_FOR_WINDOWS_HINT,
+ status=409,
+ )
+ relative = f"{remote_os.LAUNCH_DIR}/{remote_os.launcher_name(name)}"
+ script = remote_os.launcher_script(cwd, windows_pane_argv(shell_argv))
+ session = await self.connection()
+ try:
+ await remote_os.upload_text(session, host, relative, script)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ return host.launcher_command(relative)
+
async def _open(self, pane: _Pane) -> None:
session = await self.connection()
pane.session = session
@@ -305,6 +398,8 @@ class SshPtyPool:
pane.process.close()
async def _kill_session(self, name: str) -> None:
+ if self._host is not None and self._host.windows:
+ return # no tmux there: the closed channel already ended the agent
try:
await self.run(f"tmux kill-session -t {shlex.quote(name)}", timeout_s=15)
except Exception as exc: # noqa: BLE001 — logged: an agent may still be running there
@@ -312,6 +407,8 @@ class SshPtyPool:
async def _session_alive(self, name: str) -> bool | None:
"""True/False from the server; None when the server cannot be asked."""
+ if self._host is not None and self._host.windows:
+ return False # a Windows pane lives exactly as long as its channel
try:
code, _out, _err = await self.run(
f"tmux has-session -t {shlex.quote(name)}", timeout_s=15
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.py
index 319b1b1860..7227430b36 100644
--- a/jarvis/computers/service.py
+++ b/jarvis/computers/service.py
@@ -28,7 +28,7 @@ import time
from collections.abc import AsyncIterator
from typing import Any
-from jarvis.computers import cloud, identity, local_vm, providers
+from jarvis.computers import cloud, identity, local_vm, providers, remote_os
from jarvis.computers.models import (
AuthMethod,
Computer,
@@ -36,7 +36,7 @@ from jarvis.computers.models import (
LoginMode,
ProviderId,
)
-from jarvis.computers.probe import PROBE_SCRIPT, parse_probe
+from jarvis.computers.probe import PROBE_SCRIPT, WINDOWS_PROBE_SCRIPT, parse_probe
from jarvis.computers.ssh import (
MAX_COMMAND_TIMEOUT_S,
CommandResult,
@@ -44,6 +44,7 @@ from jarvis.computers.ssh import (
SshError,
SshTarget,
authorize_key_command,
+ authorize_key_script_windows,
close,
open_session,
run_command,
@@ -58,6 +59,18 @@ _USER_RE = re.compile(r"^[A-Za-z0-9._\-]{1,64}$")
_PROBE_TIMEOUT_S = 25.0
+async def _probe(opened: Session, host: remote_os.RemoteHost) -> CommandResult:
+ """The health script in the language the computer speaks."""
+ if host.windows:
+ return await remote_os.run_powershell(
+ # PowerShell alone took 6 s to start on a busy Windows VM.
+ opened,
+ WINDOWS_PROBE_SCRIPT,
+ timeout_s=_PROBE_TIMEOUT_S * 2,
+ )
+ return await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+
+
class ComputerError(Exception):
"""A request the service refuses; ``status`` maps to the HTTP code."""
@@ -316,7 +329,8 @@ class ComputerService:
try:
async with self.session(computer_id) as opened:
try:
- result = await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+ host = await remote_os.remote_host(computer_id, opened)
+ result = await _probe(opened, host)
except SshError as exc:
# A probe that times out or loses the channel is a health
# reading like a refused login, not a crash of the check.
@@ -386,17 +400,28 @@ class ComputerService:
opened = await open_session(target)
except SshError as exc:
raise _login_error(exc, target) from exc
+ windows = False
try:
- result = await run_command(
- opened, authorize_key_command(identity.public_key_line()), timeout_s=20
- )
+ host = await remote_os.detect(opened)
+ windows = host.windows
+ if windows:
+ result = await remote_os.run_powershell(
+ opened, authorize_key_script_windows(identity.public_key_line()), timeout_s=30
+ )
+ else:
+ result = await run_command(
+ opened, authorize_key_command(identity.public_key_line()), timeout_s=20
+ )
except SshError as exc:
raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
finally:
close(opened)
if result.exit_status not in (0, None):
raise ComputerError(
- "The login worked, but the key could not be saved on the server "
+ "The login worked, but Windows refused to save the key. Administrator "
+ "accounts need an elevated login to change the SSH key file."
+ if windows
+ else "The login worked, but the key could not be saved on the server "
"(is the home folder writable?).",
status=502,
kind="install_key",
@@ -564,7 +589,7 @@ class ComputerService:
return _test_result(False, exc.kind, message)
facts: dict[str, Any] | None = None
try:
- probe = await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+ probe = await _probe(opened, await remote_os.detect(opened))
facts = parse_probe(probe.stdout).facts.model_dump(mode="json")
except SshError as exc:
log.info("computers: test probe failed after login: %s", exc.message)
@@ -669,6 +694,7 @@ class ComputerService:
except local_vm.LocalVmError as exc:
raise ComputerError(exc.message, status=502) from exc
_forget_secrets(computer_id)
+ remote_os.forget(computer_id)
return self._store.remove(computer_id)
# -- cloud import ---------------------------------------------------------
diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.py
index acc0415dc4..f56e80ebf5 100644
--- a/jarvis/computers/ssh.py
+++ b/jarvis/computers/ssh.py
@@ -223,14 +223,20 @@ def _cut(text: str) -> tuple[str, bool]:
return text[:MAX_OUTPUT_CHARS], True
-async def run_command(session: Session, command: str, *, timeout_s: float) -> CommandResult:
- """Run one command on an open session and collect its output."""
+async def run_command(
+ session: Session, command: str, *, timeout_s: float, stdin: str | None = None
+) -> CommandResult:
+ """Run one command on an open session and collect its output.
+
+ ``stdin`` is written to the command and then closed — how a script
+ reaches a Windows computer, whose command line cannot carry one.
+ """
import asyncssh
started = time.perf_counter()
try:
result = await asyncio.wait_for(
- session.conn.run(command, check=False, encoding="utf-8", errors="replace"),
+ session.conn.run(command, input=stdin, check=False, encoding="utf-8", errors="replace"),
timeout=timeout_s,
)
except TimeoutError as exc:
@@ -267,6 +273,44 @@ def authorize_key_command(public_key: str) -> str:
)
+def authorize_key_script_windows(public_key: str) -> str:
+ """The PowerShell script (sent on stdin) that adds ``public_key`` on Windows.
+
+ The Windows OpenSSH server reads an administrator's keys ONLY from
+ ``%ProgramData%\\ssh\\administrators_authorized_keys``, and only while that
+ file is writable by Administrators and SYSTEM alone; every other account
+ uses its own ``.ssh\\authorized_keys``. The groups are named by their SIDs,
+ because "Administrators" is "Administratoren" on a German Windows. The
+ file is written as UTF-8 without a byte-order mark, which sshd requires.
+ """
+ key = public_key.strip().replace("'", "''")
+ return rf"""
+$ErrorActionPreference = 'Stop'
+$key = '{key}'
+$admin = [bool]((whoami /groups) -match 'S-1-5-32-544')
+if ($admin) {{
+ $file = Join-Path $env:ProgramData 'ssh\administrators_authorized_keys'
+}} else {{
+ $folder = Join-Path $HOME '.ssh'
+ New-Item -ItemType Directory -Force -Path $folder | Out-Null
+ $file = Join-Path $folder 'authorized_keys'
+}}
+$text = ''
+if (Test-Path -LiteralPath $file) {{ $text = [IO.File]::ReadAllText($file) }}
+$present = $text -split "`r?`n" | Where-Object {{ $_.Trim() -eq $key }}
+if (-not $present) {{
+ $gap = ''
+ if ($text.Length -gt 0 -and -not $text.EndsWith("`n")) {{ $gap = "`r`n" }}
+ [IO.File]::AppendAllText($file, $gap + $key + "`r`n")
+}}
+if ($admin) {{
+ icacls $file /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null
+ if ($LASTEXITCODE) {{ exit $LASTEXITCODE }}
+}}
+'ok'
+""".strip()
+
+
def close(session: Session) -> None:
"""Close without waiting; asyncssh finishes the teardown in the background."""
try:
diff --git a/jarvis/computers/toolbox.py b/jarvis/computers/toolbox.py
index f043b1e85a..4f703b9260 100644
--- a/jarvis/computers/toolbox.py
+++ b/jarvis/computers/toolbox.py
@@ -9,6 +9,11 @@ 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.
+
+A Windows computer is read and served in PowerShell (``remote_os``): it needs
+Git for Windows instead of tmux (panes there run without a server-side
+session), installs through ``winget`` and ``npm``, and keeps the CLI logins in
+the same ``~/.claude`` / ``~/.codex`` files.
"""
from __future__ import annotations
@@ -21,8 +26,10 @@ from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Literal
+from jarvis.computers import remote_os
from jarvis.computers.remote_terminal import login_shell
from jarvis.computers.service import ComputerError, get_service
+from jarvis.computers.ssh import SshError
log = logging.getLogger(__name__)
@@ -30,6 +37,8 @@ ToolId = Literal["tmux", "git", "node", "claude", "codex"]
AgentLogin = Literal["claude", "codex"]
TOOLS: tuple[ToolId, ...] = ("tmux", "git", "node", "claude", "codex")
+#: Windows has no tmux; Git for Windows brings the bash agents run in.
+WINDOWS_TOOLS: tuple[ToolId, ...] = ("git", "node", "claude", "codex")
_INSPECT = r"""
for t in tmux git node npm claude codex; do
@@ -51,6 +60,30 @@ command -v sudo >/dev/null 2>&1 && echo "sudo yes" || echo "sudo no"
echo "os $(uname -s)"
""".strip()
+#: The same report from a Windows computer ("uid 0" = an administrator).
+#: npm is left out: nothing shows it, and ``npm --version`` alone took 13 s
+#: on a busy Windows VM.
+_INSPECT_WINDOWS = r"""
+$ErrorActionPreference = 'SilentlyContinue'
+foreach ($t in 'git', 'node', 'claude', 'codex') {
+ $c = Get-Command $t -CommandType Application | Select-Object -First 1
+ if ($c) {
+ $v = & $c.Source --version 2>$null | Select-Object -First 1
+ "tool $t ok $v"
+ } else { "tool $t missing" }
+}
+if (Test-Path (Join-Path $HOME '.claude\.credentials.json')) { 'login claude ok' }
+else { 'login claude missing' }
+if (Test-Path (Join-Path $HOME '.codex\auth.json')) { 'login codex ok' }
+else { 'login codex missing' }
+if (Get-Command winget -CommandType Application) { 'pkg winget' }
+if ((whoami /groups) -match 'S-1-5-32-544') { 'uid 0' } else { 'uid 1000' }
+'sudo no'
+'os Windows'
+""".strip()
+
+_WINGET_IDS: dict[str, str] = {"git": "Git.Git", "node": "OpenJS.NodeJS.LTS"}
+
_PACKAGES: dict[str, dict[str, str]] = {
"apt-get": {
"tmux": "tmux",
@@ -129,9 +162,11 @@ def parse_inspection(output: str) -> Readiness:
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]
+ windows = os_name == "Windows"
+ ordered = [tools.get(t, ToolState(t, False)) for t in (WINDOWS_TOOLS if windows else TOOLS)]
have = {t.id for t in ordered if t.installed}
- ready = {"tmux", "git"} <= have and any(
+ base = {"git"} if windows else {"tmux", "git"}
+ ready = base <= have and any(
agent in have and logins.get(agent, False) for agent in ("claude", "codex")
)
return Readiness(
@@ -148,6 +183,14 @@ def parse_inspection(output: str) -> Readiness:
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:
+ try:
+ host = await remote_os.remote_host(computer_id, session)
+ if host.windows:
+ # PowerShell itself needs seconds to start on a busy machine.
+ answer = await remote_os.run_powershell(session, _INSPECT_WINDOWS, timeout_s=90)
+ return parse_inspection(answer.stdout)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
result = await asyncio.wait_for(
session.conn.run(
login_shell(_INSPECT), check=False, encoding="utf-8", errors="replace"
@@ -157,8 +200,44 @@ async def inspect(computer_id: str) -> Readiness:
return parse_inspection(str(result.stdout or ""))
+def install_script_windows(readiness: Readiness, wanted: list[str]) -> str:
+ """The PowerShell script that installs ``wanted`` on a Windows computer."""
+ missing = {t.id for t in readiness.tools if not t.installed}
+ system = [t for t in ("git", "node") if t in wanted and t in missing]
+ npm = [_NPM_PACKAGES[a] for a in _NPM_PACKAGES if a in wanted and a in missing]
+ if npm and "node" in missing and "node" not in system:
+ system.append("node")
+ lines = ["$ErrorActionPreference = 'Stop'"]
+ if system:
+ if readiness.package_manager != "winget":
+ raise ComputerError(
+ "winget was not found on this computer. Install Git for Windows and "
+ "Node.js by hand, then check again."
+ )
+ for tool in system:
+ lines.append(
+ f"winget install --id {_WINGET_IDS[tool]} -e --silent --disable-interactivity "
+ "--accept-source-agreements --accept-package-agreements"
+ )
+ # winget answers "already installed" with a non-zero code; only a
+ # tool that is still missing afterwards is a failure.
+ lines.append("$global:LASTEXITCODE = 0")
+ if npm:
+ # A Node.js installed a moment ago is not on this session's PATH yet.
+ lines.append(
+ "$env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + "
+ "[Environment]::GetEnvironmentVariable('Path', 'User')"
+ )
+ lines.append(f"npm install -g --silent {' '.join(npm)}")
+ lines.append("if ($LASTEXITCODE) { exit $LASTEXITCODE }")
+ lines.append("'[jarvis] done'")
+ return "\n".join(lines)
+
+
def install_script(readiness: Readiness, wanted: list[str]) -> str:
"""The shell script that installs ``wanted`` on this computer."""
+ if readiness.os == "Windows":
+ return install_script_windows(readiness, wanted)
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 "")
@@ -216,31 +295,40 @@ async def start_install(computer_id: str, items: list[str]) -> InstallJob:
if not wanted:
raise ComputerError("Choose at least one thing to install.")
readiness = await inspect(computer_id)
+ windows = readiness.os == "Windows"
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."
+ "Installing Git and Node.js needs an administrator login on this computer."
+ if windows
+ else "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}"
+ _run_install(new_job, script, windows=windows), name=f"computers-install-{computer_id}"
)
return new_job
-async def _run_install(current: InstallJob, script: str) -> None:
+async def _run_install(current: InstallJob, script: str, *, windows: bool = False) -> 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
+ remote_os.POWERSHELL_STDIN if windows else login_shell(script),
+ encoding="utf-8",
+ errors="replace",
+ stderr=asyncssh.STDOUT,
)
+ if windows:
+ process.stdin.write(script)
+ process.stdin.write_eof()
async for line in process.stdout:
current.log.append(line.rstrip())
await asyncio.wait_for(process.wait(), timeout=1500)
@@ -262,11 +350,31 @@ async def _run_install(current: InstallJob, script: str) -> None:
def local_login_file(agent: str) -> Path | None:
+ """The login file of this computer's ACTIVE account for ``agent``, if any.
+
+ An account the app manages keeps its login in its own config folder
+ (``CLAUDE_CONFIG_DIR`` / ``CODEX_HOME``); the plain ``~/.claude`` /
+ ``~/.codex`` one is the fallback.
+ """
rel = _LOGIN_FILES.get(agent)
if rel is None:
return None
- path = Path.home() / rel
- return path if path.is_file() else None
+ candidates: list[Path] = []
+ try:
+ from jarvis import agent_accounts
+
+ account = agent_accounts.active_account(agent) # type: ignore[arg-type]
+ overrides = agent_accounts.env_overrides(agent, account.id) # type: ignore[arg-type]
+ folder = overrides.get(_ACCOUNT_DIR_VARS[agent])
+ if folder:
+ candidates.append(Path(folder) / Path(rel).name)
+ except Exception as exc: # noqa: BLE001 — no account layer: the default login below
+ log.debug("computers: account folder for %s unknown: %s", agent, exc)
+ candidates.append(Path.home() / rel)
+ return next((path for path in candidates if path.is_file()), None)
+
+
+_ACCOUNT_DIR_VARS: dict[str, str] = {"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME"}
async def copy_login(computer_id: str, agent: AgentLogin) -> None:
@@ -278,10 +386,23 @@ async def copy_login(computer_id: str, agent: AgentLogin) -> None:
f"open a terminal there and run {agent}."
)
rel = _LOGIN_FILES[agent]
- remote_dir = shlex.quote(str(Path(rel).parent.as_posix()))
+ folder = 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)
+ try:
+ host = await remote_os.remote_host(computer_id, session)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ if not host.windows:
+ remote_dir = shlex.quote(folder)
+ await session.conn.run(
+ f"mkdir -p ~/{remote_dir} && chmod 700 ~/{remote_dir}", check=False
+ )
async with session.conn.start_sftp_client() as sftp:
+ if host.windows:
+ # Relative paths start in the home folder; Windows keeps its own
+ # ACLs, so there is no mode to set.
+ await sftp.makedirs(folder, exist_ok=True)
await sftp.put(str(source), rel)
- await sftp.chmod(rel, 0o600)
+ if not host.windows:
+ 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/society/agent_tools.py b/jarvis/society/agent_tools.py
index b7be22f302..2140db35ed 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -678,6 +678,10 @@ class ShellTool:
"folder": str(cwd),
"backend": getattr(backend, "name", "local"),
}
+ runs_on = getattr(backend, "where", None)
+ if runs_on:
+ # A remote command did not run in the local ``folder`` above; say where.
+ body["runs_on"] = runs_on
if result.timed_out:
return ToolResult(success=False, output=body, error="command timed out")
if result.failed_to_start:
diff --git a/jarvis/society/remote.py b/jarvis/society/remote.py
index 65f38207b3..1df757d42b 100644
--- a/jarvis/society/remote.py
+++ b/jarvis/society/remote.py
@@ -11,6 +11,11 @@ The agent's remote workspace is ``~/jarvis-agents/<agent_id>`` on that
machine, created on demand. Local containment (``resolve_contained``) still
decides WHICH subfolder a command may use; this module only maps that
subfolder onto the remote workspace.
+
+On a Windows computer the same command runs in Git for Windows' bash (the
+shell agents write for, and the one their coding CLI uses there too), sent on
+stdin because ``cmd.exe`` cannot carry it; without Git for Windows it runs in
+PowerShell in the same folder (``jarvis.computers.remote_os``).
"""
from __future__ import annotations
@@ -58,6 +63,24 @@ def wrap_in_workspace(agent_id: str, command: str, *, relative: str = "") -> str
return f"mkdir -p {folder} && cd {folder} && export CI=1 NO_COLOR=1 && {command}"
+def _ps_quote(text: str) -> str:
+ return "'" + text.replace("'", "''") + "'"
+
+
+def powershell_in_workspace(agent_id: str, command: str, *, relative: str = "") -> str:
+ """The PowerShell twin of :func:`wrap_in_workspace` for a Windows computer."""
+ parts = [REMOTE_ROOT, agent_id, *[p for p in relative.split("/") if p]]
+ folder = "\\".join(parts)
+ return (
+ f"$ws = Join-Path $HOME {_ps_quote(folder)}\n"
+ "New-Item -ItemType Directory -Force -Path $ws | Out-Null\n"
+ "Set-Location -LiteralPath $ws\n"
+ "$env:CI = '1'; $env:NO_COLOR = '1'; $global:LASTEXITCODE = 0\n"
+ f"{command}\n"
+ "if ($LASTEXITCODE) { exit $LASTEXITCODE } elseif (-not $?) { exit 1 }\n"
+ )
+
+
class SshShellBackend:
"""Runs an agent's shell commands inside its workspace on another computer."""
@@ -67,6 +90,8 @@ class SshShellBackend:
self._computer_id = computer_id
self._agent_id = agent_id
self._workspace = Path(workspace)
+ #: Where the last command ran, for the tool result ("Ubuntu, bash").
+ self.where: str | None = None
def _relative(self, cwd: Path) -> str:
try:
@@ -80,14 +105,28 @@ class SshShellBackend:
from jarvis.computers.service import ComputerError, get_service
timeout = max(1.0, min(float(timeout_s or DEFAULT_TIMEOUT_S), MAX_TIMEOUT_S))
- wrapped = wrap_in_workspace(self._agent_id, command, relative=self._relative(cwd))
+ relative = self._relative(cwd)
started = time.perf_counter()
try:
async with get_service().session(self._computer_id) as opened:
+ from jarvis.computers import remote_os
from jarvis.computers.ssh import SshError, run_command
try:
- result = await run_command(opened, wrapped, timeout_s=timeout)
+ host = await remote_os.remote_host(self._computer_id, opened)
+ name = get_service().get(self._computer_id).name
+ if not host.windows:
+ self.where = f"{name} (bash)"
+ wrapped = wrap_in_workspace(self._agent_id, command, relative=relative)
+ result = await run_command(opened, wrapped, timeout_s=timeout)
+ elif host.bash:
+ self.where = f"{name} (Windows, Git Bash)"
+ wrapped = wrap_in_workspace(self._agent_id, command, relative=relative)
+ result = await remote_os.run_bash(opened, host, wrapped, timeout_s=timeout)
+ else:
+ self.where = f"{name} (Windows, PowerShell)"
+ script = powershell_in_workspace(self._agent_id, command, relative=relative)
+ result = await remote_os.run_powershell(opened, script, timeout_s=timeout)
except SshError as exc:
if exc.kind == "timeout":
return ShellResult(
diff --git a/tests/fakes/fake_ssh_server.py b/tests/fakes/fake_ssh_server.py
index 28bfa98465..f590206d0f 100644
--- a/tests/fakes/fake_ssh_server.py
+++ b/tests/fakes/fake_ssh_server.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import re
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
+from pathlib import Path
from typing import Any
import asyncssh
@@ -97,11 +98,14 @@ class _Server(asyncssh.SSHServer):
class FakeSshServer:
"""Start with :meth:`start`, stop with :meth:`stop`; ``port`` is random."""
- def __init__(self, state: FakeSshState | None = None) -> None:
+ def __init__(self, state: FakeSshState | None = None, *, sftp_root: Path | None = None) -> None:
self.state = state or FakeSshState()
self.host_key = asyncssh.generate_private_key("ssh-ed25519")
self._acceptor: Any = None
self.port = 0
+ #: A folder that plays the remote home over SFTP (relative paths land
+ #: in it); ``None`` serves no SFTP at all.
+ self.sftp_root = sftp_root
async def _process(self, process: asyncssh.SSHServerProcess) -> None:
command = process.command or ""
@@ -126,12 +130,18 @@ class FakeSshServer:
process.exit(0)
async def start(self, port: int = 0) -> None:
+ root = self.sftp_root
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,
+ sftp_factory=(
+ (lambda chan: asyncssh.SFTPServer(chan, chroot=str(root)))
+ if root is not None
+ else None
+ ),
)
self.port = self._acceptor.sockets[0].getsockname()[1]
diff --git a/tests/unit/agentic_ide/test_remote_create_route.py b/tests/unit/agentic_ide/test_remote_create_route.py
index 817e9c303c..387c515265 100644
--- a/tests/unit/agentic_ide/test_remote_create_route.py
+++ b/tests/unit/agentic_ide/test_remote_create_route.py
@@ -18,7 +18,7 @@ from fastapi.testclient import TestClient
from jarvis.agentic_ide import remote
from jarvis.agentic_ide import session as session_mod
from jarvis.agentic_ide.session import Registry
-from jarvis.computers import remote_terminal
+from jarvis.computers import remote_os, remote_terminal
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -34,6 +34,9 @@ class RemotePool(FakePtyManager):
async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
return 0, self.missing, ""
+ async def host(self) -> remote_os.RemoteHost:
+ return remote_os.RemoteHost()
+
@pytest.fixture
def far(monkeypatch: pytest.MonkeyPatch) -> RemotePool:
diff --git a/tests/unit/agentic_ide/test_remote_placement.py b/tests/unit/agentic_ide/test_remote_placement.py
index c939903323..25ec424f3e 100644
--- a/tests/unit/agentic_ide/test_remote_placement.py
+++ b/tests/unit/agentic_ide/test_remote_placement.py
@@ -18,7 +18,7 @@ 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 jarvis.computers import remote_os, remote_terminal
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -40,6 +40,9 @@ class RemotePool(FakePtyManager):
self.commands.append(command)
return 0, "", ""
+ async def host(self) -> remote_os.RemoteHost:
+ return remote_os.RemoteHost()
+
@pytest.fixture
def pools(monkeypatch: pytest.MonkeyPatch) -> tuple[FakePtyManager, RemotePool, list[Any]]:
diff --git a/tests/unit/agentic_ide/test_remote_sync.py b/tests/unit/agentic_ide/test_remote_sync.py
index 2938dfaec9..1dfdb5b5e0 100644
--- a/tests/unit/agentic_ide/test_remote_sync.py
+++ b/tests/unit/agentic_ide/test_remote_sync.py
@@ -19,6 +19,7 @@ from pathlib import Path
import pytest
from jarvis.agentic_ide import remote
+from jarvis.computers import remote_os
def _posix_shell() -> str | None:
@@ -52,6 +53,9 @@ class LocalPool:
async def home(self) -> str:
return self._home.as_posix()
+ async def host(self) -> remote_os.RemoteHost:
+ return remote_os.RemoteHost()
+
async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
result = await asyncio.to_thread(
subprocess.run,
diff --git a/tests/unit/computers/test_windows_remote.py b/tests/unit/computers/test_windows_remote.py
new file mode 100644
index 0000000000..d5160432f2
--- /dev/null
+++ b/tests/unit/computers/test_windows_remote.py
@@ -0,0 +1,420 @@
+"""A connected Windows computer: every feature reaches it the way it can be reached.
+
+Windows OpenSSH runs commands in ``cmd.exe``, which carries neither line
+breaks nor non-ASCII text on its command line. These tests play such a server
+(real asyncssh, a scripted "cmd") and pin what goes over the wire: detection,
+PowerShell scripts on stdin, Git Bash launchers uploaded over SFTP, and the
+answers each feature builds from them.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+import shlex
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat import remote_cli
+from jarvis.computers import identity, remote_os, service, toolbox
+from jarvis.computers.probe import WINDOWS_PROBE_SCRIPT, parse_probe
+from jarvis.computers.remote_terminal import SshPtyPool, windows_pane_argv
+from jarvis.computers.service import ComputerService
+from jarvis.computers.ssh import authorize_key_script_windows
+from jarvis.computers.store import ComputerStore
+from jarvis.society import remote
+from tests.fakes.fake_ssh_server import TEST_PASSWORD, FakeSshServer
+
+GIT_BASH = r"C:\Program Files\Git\bin\bash.exe"
+HOME = "C:/Users/ada"
+
+WINDOWS_PROBE_OUTPUT = (
+ "@@hostname\r\nDESK-01\r\n@@uname\r\nWindows 10.0.26200 AMD64\r\n"
+ "@@os\r\nID=windows\r\nPRETTY_NAME=Windows 11 Pro\r\n@@nproc\r\n4\r\n"
+ "@@meminfo\r\nMemTotal: 8388608 kB\r\nMemAvailable: 4194304 kB\r\n"
+ "@@df\r\nC: 104857600 52428800 52428800 - C:\\\r\n@@uptime\r\n3600\r\n"
+ "@@loadavg\r\n@@end\r\n"
+)
+
+INSPECT_OUTPUT = (
+ "tool git ok git version 2.51.0.windows.1\r\ntool node ok v22.1.0\r\n"
+ "tool npm ok 10.0.0\r\ntool claude ok 2.1.284 (Claude Code)\r\ntool codex missing\r\n"
+ "login claude ok\r\nlogin codex missing\r\npkg winget\r\nuid 0\r\nsudo no\r\nos Windows\r\n"
+)
+
+
+class WindowsBox:
+ """Scripted answers of a Windows OpenSSH server whose default shell is cmd."""
+
+ def __init__(self, *, bash: bool = True, shell: str = "cmd") -> None:
+ self.bash = bash
+ self.shell = shell
+ self.scripts: list[tuple[str, str]] = []
+ self.launched: list[str] = []
+
+ async def __call__(self, command: str, process: Any) -> bool:
+ if command == remote_os.DETECT_COMMAND:
+ if self.shell == "powershell":
+ process.stdout.write("%OS%\r\nWindows_NT\r\n")
+ else:
+ process.stdout.write("Windows_NT $env:OS\r\n")
+ process.exit(0)
+ return True
+ if command.endswith(remote_os.POWERSHELL_STDIN):
+ script = await process.stdin.read()
+ self.scripts.append(("powershell", script))
+ process.stdout.write(self._powershell(script))
+ process.exit(0)
+ return True
+ if "-l -s" in command and GIT_BASH in command:
+ script = await process.stdin.read()
+ self.scripts.append(("bash", script))
+ if "pwd -W" in script:
+ process.stdout.write(f"{HOME}/jarvis-agents/scout\nfound\n")
+ else:
+ process.stdout.write("bash-ran\n")
+ process.exit(0)
+ return True
+ if "--noprofile --norc" in command:
+ self.launched.append(command)
+ if process.term_type:
+ process.stdout.write("pane-ready\r\n")
+ while True:
+ data = await process.stdin.read(1024)
+ if not data:
+ break
+ if "quit" in data:
+ process.exit(5)
+ return True
+ process.stdout.write("echo:" + data)
+ process.exit(0)
+ return True
+ line = await process.stdin.readline()
+ process.stdout.write(json.dumps({"type": "echo", "got": line.strip()}) + "\n")
+ process.exit(0)
+ return True
+ return False
+
+ def _powershell(self, script: str) -> str:
+ if "Test-Path -LiteralPath $path" in script:
+ return f"home {HOME}\r\n" + (f"bash {GIT_BASH}\r\n" if self.bash else "")
+ if script == WINDOWS_PROBE_SCRIPT:
+ return WINDOWS_PROBE_OUTPUT
+ if "tool $t" in script:
+ return INSPECT_OUTPUT
+ return "ps-ran\r\n"
+
+
+def computers(tmp_path: Path, secret_box, monkeypatch: pytest.MonkeyPatch) -> ComputerService: # noqa: ANN001
+ path = tmp_path / "computers.json"
+ monkeypatch.setattr("jarvis.computers.store.default_path", lambda: path)
+ svc = ComputerService(ComputerStore(path))
+ monkeypatch.setattr(service, "_SERVICE", svc)
+ return svc
+
+
+def box() -> WindowsBox:
+ return WindowsBox()
+
+
+async def ssh_server(tmp_path: Path, box: WindowsBox): # noqa: ANN201
+ home = tmp_path / "remote-home"
+ home.mkdir()
+ server = FakeSshServer(sftp_root=home)
+ server.state.handler = box
+ server.state.authorized.add(identity.public_key_line())
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+async def desk(computers: ComputerService, ssh_server: FakeSshServer): # noqa: ANN201
+ return await computers.add_server(name="Desk", host="127.0.0.1", port=ssh_server.port)
+
+
+# -- pure pieces ------------------------------------------------------------------
+
+
+def test_detection_tells_the_three_shells_apart() -> None:
+ assert remote_os.parse_detect("Windows_NT $env:OS\r\n") == ("windows", "cmd")
+ assert remote_os.parse_detect("%OS%\r\nWindows_NT\r\n") == ("windows", "powershell")
+ assert remote_os.parse_detect("%OS% :OS\n") == ("posix", "sh")
+ assert remote_os.parse_windows_facts(f"home {HOME}\r\nbash {GIT_BASH}\r\n") == (HOME, GIT_BASH)
+ assert remote_os.parse_windows_facts(f"home {HOME}\r\n") == (HOME, None)
+
+
+def test_command_lines_quote_the_program_once() -> None:
+ cmd = remote_os.RemoteHost(os="windows", default_shell="cmd", home=HOME, bash=GIT_BASH)
+ assert cmd.launcher_command("jarvis-agents/.launch/x.sh") == (
+ f'"{GIT_BASH}" --noprofile --norc {HOME}/jarvis-agents/.launch/x.sh'
+ )
+ powershell = remote_os.RemoteHost(
+ os="windows", default_shell="powershell", home=HOME, bash=GIT_BASH
+ )
+ assert powershell.bash_script_command() == f'& "{GIT_BASH}" -l -s'
+ # A home with a space stays out of the line: the relative path resolves there.
+ spaced = remote_os.RemoteHost(os="windows", home="C:/Users/Ada Lovelace", bash=GIT_BASH)
+ assert spaced.launcher_command("x.sh").endswith("--norc x.sh")
+ assert cmd.sftp_path("C:/Users/ada/f") == "/C:/Users/ada/f"
+ assert remote_os.RemoteHost().sftp_path("C:/x") == "C:/x"
+
+
+def test_launcher_keeps_every_argument_intact() -> None:
+ argv = ["claude", "--print", 'a "b" & c', "café Ω ✓", "multi\nline", "/help", "100%PATH%"]
+ script = remote_os.launcher_script(f"{HOME}/jarvis-agents/scout", argv, {"CI": "1"})
+ lines = script.splitlines()
+ assert lines[0] == f"cd -- {HOME}/jarvis-agents/scout || exit 97"
+ assert "export CI=1" in lines
+ assert "MSYS_NO_PATHCONV=1" in script
+ exec_line = script.split("exec ", 1)[1]
+ assert shlex.split(exec_line) == argv
+ assert remote_os.launcher_name("society:scout/x") == "society-scout-x.sh"
+
+
+def test_windows_probe_output_reads_like_linux() -> None:
+ reading = parse_probe(WINDOWS_PROBE_OUTPUT)
+ assert reading.facts.os_id == "windows"
+ assert reading.facts.os_name == "Windows 11 Pro"
+ assert reading.facts.hostname == "DESK-01"
+ assert reading.facts.kernel == "Windows 10.0.26200" and reading.facts.arch == "AMD64"
+ assert reading.facts.cpu_count == 4 and reading.facts.mem_total_mb == 8192
+ assert reading.mem_used_pct == 50.0 and reading.disk_used_pct == 50.0
+ assert reading.facts.disk_total_gb == 100.0 and reading.uptime_s == 3600
+ assert reading.load_1m is None
+
+
+def test_windows_readiness_needs_git_not_tmux() -> None:
+ readiness = toolbox.parse_inspection(INSPECT_OUTPUT)
+ assert [t.id for t in readiness.tools] == ["git", "node", "claude", "codex"]
+ assert readiness.ready and readiness.root and readiness.os == "Windows"
+ assert readiness.package_manager == "winget"
+ script = toolbox.install_script(readiness, ["codex"])
+ assert "npm install -g --silent @openai/codex" in script
+ assert "winget" not in script
+ no_node = toolbox.parse_inspection(
+ INSPECT_OUTPUT.replace("tool node ok v22.1.0", "tool node missing")
+ )
+ script = toolbox.install_script(no_node, ["codex"])
+ assert "winget install --id OpenJS.NodeJS.LTS" in script
+ no_winget = toolbox.parse_inspection(
+ INSPECT_OUTPUT.replace("pkg winget\r\n", "").replace(
+ "tool git ok git version 2.51.0.windows.1", "tool git missing"
+ )
+ )
+ with pytest.raises(service.ComputerError):
+ toolbox.install_script(no_winget, ["git"])
+
+
+def test_key_script_names_groups_by_sid_and_escapes_quotes() -> None:
+ script = authorize_key_script_windows("ssh-ed25519 AAAA ada's-pc")
+ assert "$key = 'ssh-ed25519 AAAA ada''s-pc'" in script
+ assert "administrators_authorized_keys" in script
+ assert "*S-1-5-32-544:F" in script and "*S-1-5-18:F" in script
+
+
+def test_powershell_workspace_quotes_the_folder() -> None:
+ script = remote.powershell_in_workspace("scout", "Get-ChildItem", relative="it's/sub")
+ assert "Join-Path $HOME 'jarvis-agents\\scout\\it''s\\sub'" in script
+ assert "\nGet-ChildItem\n" in script
+ assert windows_pane_argv(("bash", "-l")) == ("powershell.exe", "-NoLogo")
+ assert windows_pane_argv(("claude", "--resume", "x")) == ("claude", "--resume", "x")
+
+
+# -- over SSH -------------------------------------------------------------------------
+
+
+async def test_check_reads_windows_facts_through_powershell(desk, box: WindowsBox) -> None: # noqa: ANN001
+ assert desk.health.status == "online", desk.health.message
+ assert desk.facts is not None and desk.facts.os_id == "windows"
+ assert desk.facts.os_name == "Windows 11 Pro" and desk.facts.cpu_count == 4
+ assert ("powershell", WINDOWS_PROBE_SCRIPT) in box.scripts
+
+
+async def test_password_login_plants_the_key_on_windows(
+ computers: ComputerService, ssh_server: FakeSshServer, box: WindowsBox
+) -> None:
+ ssh_server.state.authorized.clear()
+ original = box._powershell
+
+ def planting(script: str) -> str:
+ if "administrators_authorized_keys" in script:
+ match = re.search(r"\$key = '([^']+)'", script)
+ assert match is not None
+ ssh_server.state.authorized.add(match.group(1))
+ return "ok\r\n"
+ return original(script)
+
+ box._powershell = planting # type: ignore[method-assign]
+ computer = await computers.add_server(
+ name="Desk",
+ host="127.0.0.1",
+ port=ssh_server.port,
+ auth="password",
+ password=TEST_PASSWORD,
+ )
+ assert computer.auth == "key"
+ assert computer.health.status == "online", computer.health.message
+ assert not any("authorized_keys" in c and "umask" in c for c in ssh_server.state.commands)
+
+
+async def test_cli_turn_starts_through_an_uploaded_launcher(
+ desk,
+ box: WindowsBox,
+ tmp_path: Path,
+ ssh_server: FakeSshServer, # noqa: ANN001
+) -> None:
+ proc = await remote_cli.spawn(
+ desk.id,
+ agent_id="scout",
+ runner="claude-cli",
+ binary="claude",
+ argv=[
+ r"C:\bin\claude.exe",
+ "--print",
+ "--append-system-prompt-file",
+ r"C:\local\identity.md",
+ "--mcp-config",
+ "{}",
+ ],
+ local_cwd=r"C:\ws",
+ env={"PATH": r"C:\secret-path", "NO_COLOR": "1"},
+ system_prompt_files={r"C:\local\identity.md": "You are Scout. café Ω ✓!"},
+ )
+ proc.stdin.write("naïve ✓\n".encode())
+ await proc.stdin.drain()
+ first = json.loads(await proc.stdout.readline())
+ proc.stdin.close()
+ assert await proc.wait() == 0
+ assert first == {"type": "echo", "got": "naïve ✓"}
+
+ home = tmp_path / "remote-home"
+ launcher = (home / "jarvis-agents/.launch/scout.sh").read_text(encoding="utf-8")
+ exec_line = launcher.split("exec ", 1)[1]
+ assert shlex.split(exec_line) == [
+ "claude",
+ "--print",
+ "--append-system-prompt-file",
+ f"{HOME}/jarvis-agents/.launch/scout-prompt-0.md",
+ ]
+ assert f"cd -- {HOME}/jarvis-agents/scout" in launcher
+ assert "secret-path" not in launcher
+ prompt = (home / "jarvis-agents/.launch/scout-prompt-0.md").read_text(encoding="utf-8")
+ assert prompt.startswith("You are Scout. café Ω ✓!")
+ assert '"Desk"' in prompt and "Windows 11 Pro" in prompt
+ launcher_path = f"{HOME}/jarvis-agents/.launch/scout.sh"
+ assert box.launched == [f'"{GIT_BASH}" --noprofile --norc {launcher_path}']
+
+
+async def test_cli_turn_without_git_bash_says_what_to_install(
+ computers: ComputerService, ssh_server: FakeSshServer, box: WindowsBox
+) -> None:
+ box.bash = False
+ desk = await computers.add_server(name="Desk", host="127.0.0.1", port=ssh_server.port)
+ with pytest.raises(remote_cli.RemoteCliUnavailable) as caught:
+ await remote_cli.spawn(
+ desk.id,
+ agent_id="scout",
+ runner="claude-cli",
+ binary="claude",
+ argv=["claude", "--print"],
+ local_cwd="/ws",
+ env={},
+ )
+ assert "Git for Windows" in str(caught.value)
+
+
+async def test_agent_shell_runs_in_git_bash_or_powershell(
+ desk,
+ box: WindowsBox,
+ tmp_path: Path, # noqa: ANN001
+) -> None:
+ agent = SimpleNamespace(agent_id="scout", computer_id=desk.id)
+ backend = remote.backend_for(agent, tmp_path)
+
+ result = await backend.run("ls -la", cwd=tmp_path, timeout_s=30)
+ assert result.ok and "bash-ran" in result.output
+ kind, script = box.scripts[-1]
+ assert kind == "bash" and script.endswith("&& ls -la")
+ assert backend.where == "Desk (Windows, Git Bash)"
+
+ box.bash = False
+ remote_os.forget(desk.id)
+ result = await backend.run("Get-ChildItem", cwd=tmp_path, timeout_s=30)
+ assert result.ok and "ps-ran" in result.output
+ kind, script = box.scripts[-1]
+ assert kind == "powershell" and "Set-Location -LiteralPath $ws" in script
+ assert backend.where == "Desk (Windows, PowerShell)"
+
+
+async def test_readiness_is_read_in_powershell(desk, box: WindowsBox) -> None: # noqa: ANN001
+ readiness = await toolbox.inspect(desk.id)
+ assert readiness.os == "Windows" and readiness.ready
+ assert "tmux" not in [t.id for t in readiness.tools]
+
+
+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, check: Any) -> None:
+ for _ in range(250):
+ if check():
+ return
+ await asyncio.sleep(0.02)
+ raise AssertionError(f"never happened; screen: {self.text!r}")
+
+
+async def test_ide_pane_runs_without_tmux_and_ends_with_its_channel(
+ computers: ComputerService,
+ desk,
+ box: WindowsBox,
+ tmp_path: Path, # noqa: ANN001
+) -> None:
+ pool = SshPtyPool(desk.id, connect=lambda: computers.connect(desk.id))
+ try:
+ assert await pool.home() == HOME
+ assert await pool.sftp_path(f"{HOME}/x") == f"/{HOME}/x"
+ code, out, _err = await pool.run("command -v git")
+ assert code == 0 and "bash-ran" in out
+
+ screen = _Screen()
+ spawned = await pool.spawn(
+ shell_argv=("bash", "-l"),
+ shell_id="agentic-ide:t1",
+ cwd=f"{HOME}/jarvis-workspaces/app",
+ cols=100,
+ rows=30,
+ on_output=screen.output,
+ on_closed=screen.exit,
+ meta={"history_id": "pane-1"},
+ )
+ await screen.wait_for(lambda: "pane-ready" in screen.text)
+ # The fake server edits lines (a real ConPTY would pass keys through).
+ assert pool.write(spawned.terminal_id, "hi\r")
+ await screen.wait_for(lambda: "echo:hi" in screen.text)
+ launcher = (tmp_path / "remote-home/jarvis-agents/.launch/jv-pane-1.sh").read_text()
+ assert "exec powershell.exe -NoLogo" in launcher
+ assert not any("tmux" in c for c in box.launched)
+
+ assert pool.write(spawned.terminal_id, "quit\r")
+ await screen.wait_for(lambda: screen.closed)
+ assert screen.closed == [5], "the agent's own exit, no re-attach attempt"
+ finally:
+ pool.close_all()