Skip to content
Python

Sandbox provider selection, machine status line and the sandbox setup command

Devika Verma02f0b4d4c6a8
diff --git a/coworker/agent.py b/coworker/agent.py
index ee2e9350..b02cbf95 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -48,6 +48,7 @@ from .tools.toolreq import request_tool_tool
from .tools.subagent import explorer_tools
from .web import make_web_fetch_tool, make_web_search_tool
from .workspace_trust import WorkspaceTrustStore
+from .sandbox.selection import select as select_sandbox
from .sandbox.workspace import open_workspace
from .tools.todo import TodoList
@@ -339,7 +340,13 @@ def build_engine(
# The session's workspace decides where commands run: in this process (`direct`, the
# default, today's behaviour) or in a tool runner behind a sandbox provider.
sandbox_workspace = (
- open_workspace(cwd=ws, roots=root_list or None, session_id=session_id or "", agent=agent.name)
+ open_workspace(
+ cwd=ws,
+ provider=select_sandbox(config.sandbox_provider).provider,
+ roots=root_list or None,
+ session_id=session_id or "",
+ agent=agent.name,
+ )
if ws is not None
else None
)
diff --git a/coworker/config.py b/coworker/config.py
index 521425a3..ae740ff4 100644
--- a/coworker/config.py
+++ b/coworker/config.py
@@ -10,6 +10,7 @@ workspace path. Other permission grants remain global-only.
from __future__ import annotations
import os
+import re
try:
import tomllib # stdlib since 3.11
@@ -111,6 +112,12 @@ class Config:
# the signed-in desktop"). Empty override ⇒ the cloud machines surface is
# off entirely; dev/BYO deployments point elsewhere.
cloud_machines_base: str = "https://machines.openworker.com"
+ # Where agents' commands and file tools run: "direct" (in this process, unconfined),
+ # "openshell" (one OpenShell sandbox per agent; sessions are refused when OpenShell is
+ # not usable). Unset = the default rule in coworker/sandbox/selection.py. Machine-level
+ # only: a repository's own config must never be able to switch the sandbox off.
+ # Environment override: OPENWORKER_SANDBOX_PROVIDER.
+ sandbox_provider: Optional[str] = None
_FIELDS = {
@@ -120,6 +127,7 @@ _FIELDS = {
"max_output_tokens",
"reasoning_effort",
"tool_result_max_bytes",
+ "sandbox_provider",
"compaction_cap_tokens",
"compaction_summary_max_tokens",
"allowed_commands",
@@ -143,6 +151,7 @@ _FIELDS = {
# for a canonically trusted workspace; `auto_allow` and `allowed_domains` remain user-global
# only (a repo must not be able to widen the agent's command or network reach).
_GLOBAL_ONLY_FIELDS = {
+ "sandbox_provider",
"allowed_commands",
"auto_allow",
"allowed_domains",
@@ -156,6 +165,21 @@ def global_config_path() -> Path:
return state_dir() / "config.toml"
+def set_global_value(key: str, value: str, *, path: Optional[Path] = None) -> Path:
+ """Set one top-level string key in the machine's config.toml, keeping the rest of the
+ file as it is. The line goes at the top, because a top-level key must come before any
+ table header."""
+ if key not in _FIELDS:
+ raise ValueError(f"not a config key: {key}")
+ target = Path(path) if path is not None else global_config_path()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ lines = target.read_text(encoding="utf-8").splitlines() if target.is_file() else []
+ kept = [line for line in lines if not re.match(rf"\s*{re.escape(key)}\s*=", line)]
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
+ target.write_text("\n".join([f'{key} = "{escaped}"', *kept]) + "\n", encoding="utf-8")
+ return target
+
+
def _read(path: Path) -> dict[str, Any]:
try:
with open(path, "rb") as f:
diff --git a/coworker/remote/joiner.py b/coworker/remote/joiner.py
index bc8a7004..cb45f63a 100644
--- a/coworker/remote/joiner.py
+++ b/coworker/remote/joiner.py
@@ -548,7 +548,8 @@ def _lifespan(app):
TOP_COMMANDS = ("join", "up")
-MACHINE_COMMANDS = ("status", "keys", "logs", "service", "leave")
+# `sandbox` is served but not listed in `openworker --help` until it has been tried on a fresh machine.
+MACHINE_COMMANDS = ("status", "keys", "logs", "service", "leave", "sandbox")
class _Only:
@@ -557,10 +558,19 @@ class _Only:
def __init__(self, sub, only):
self._sub, self._only = sub, only
+ self._hidden: set[str] = set()
- def add_parser(self, name, **kw):
+ def add_parser(self, name, *, hidden=False, **kw):
+ """`hidden`: served, but shown in no help text (a command not yet tried widely)."""
if self._only is None or name in self._only:
- return self._sub.add_parser(name, **kw)
+ if hidden:
+ kw.pop("help", None) # no line of its own in the command list
+ parser = self._sub.add_parser(name, **kw)
+ if hidden:
+ self._hidden.add(name)
+ shown = [n for n in self._sub.choices if n not in self._hidden]
+ self._sub.metavar = "{" + ",".join(shown) + "}" # the usage line lists only these
+ return parser
return argparse.ArgumentParser(add_help=False)
@@ -633,6 +643,11 @@ def cli(
p_uninstall = service_sub.add_parser("uninstall", help="disable and remove the unit")
p_uninstall.add_argument("--unit", default=None, help="unit file name (default: this machine's)")
service_sub.add_parser("list", help="show every openworker unit on this box and its state dir")
+ p_sandbox = sub.add_parser("sandbox", hidden=True, description="Run this machine's agents in OpenShell sandboxes.")
+ sandbox_sub = p_sandbox.add_subparsers(dest="sandbox_command", required=True)
+ sandbox_sub.add_parser("status", help="what OpenShell sandboxes need here, and what is missing")
+ p_sandbox_setup = sandbox_sub.add_parser("setup", help="set this machine up (shows each change and asks first)")
+ p_sandbox_setup.add_argument("--yes", action="store_true", help="make the changes without asking")
args = parser.parse_args(argv)
state = state_dir()
@@ -654,6 +669,10 @@ def cli(
return _cmd_secrets(state, args)
if args.command == "service":
return _cmd_service(state, args)
+ if args.command == "sandbox":
+ from ..sandbox import setup_cmd
+
+ return setup_cmd.setup(yes=args.yes) if args.sandbox_command == "setup" else setup_cmd.status()
return 2
@@ -766,6 +785,12 @@ def _run(state: Path, controller: str, name: str, token=None, on_welcome=None) -
except EngineBusy as exc:
print(f"error: {exc}", file=sys.stderr)
return 3
+ # Sessions started by this process belong to a headless machine: with no setting they
+ # run in OpenShell sandboxes when OpenShell is usable here, and say so loudly when not.
+ from ..sandbox.selection import HEADLESS_ENV
+
+ os.environ[HEADLESS_ENV] = "1"
+ _announce_sandbox()
try:
asyncio.run(
run_joined(
@@ -785,6 +810,30 @@ def _run(state: Path, controller: str, name: str, token=None, on_welcome=None) -
return 1
+def sandbox_status() -> dict:
+ """How sessions on this machine will run: {"provider", "explicit", "warning"} or
+ {"provider": None, "refused": why}."""
+ from ..config import load_config
+ from ..sandbox.selection import select
+
+ try:
+ chosen = select(load_config().sandbox_provider, headless=True)
+ except Exception as exc:
+ return {"provider": None, "refused": str(exc)}
+ return {"provider": chosen.provider, "explicit": chosen.explicit, "warning": chosen.warning}
+
+
+def _announce_sandbox() -> None:
+ info = sandbox_status()
+ if info.get("refused"):
+ print(f"\n[openworker] SESSIONS WILL BE REFUSED: {info['refused']}\n", file=sys.stderr)
+ elif info.get("warning"):
+ bar = "!" * 78
+ print(f"\n{bar}\n[openworker] {info['warning']}\n{bar}\n", file=sys.stderr)
+ else:
+ print(f"[openworker] sandbox: {info['provider']}")
+
+
def _cmd_secrets(state: Path, args) -> int:
from ..secrets import SecretStore
@@ -1164,6 +1213,7 @@ def machine_status(state: Path) -> dict:
name=cfg.get("name", ""),
machine_id=cfg.get("machine_id", ""),
)
+ out["sandbox"] = sandbox_status()
return out
@@ -1189,6 +1239,13 @@ def _cmd_status(state: Path, as_json: bool = False) -> int:
print(f"controller: {cfg['controller']}")
print(f"name: {cfg.get('name', '')}")
print(f"machine id: {cfg.get('machine_id', '')}")
+ sandbox = sandbox_status()
+ if sandbox.get("refused"):
+ print(f"sandbox: SESSIONS REFUSED: {sandbox['refused']}")
+ else:
+ print(f"sandbox: {sandbox['provider']}" + (" (set explicitly)" if sandbox.get("explicit") else ""))
+ if sandbox.get("warning"):
+ print(f" {sandbox['warning']}")
return 0
diff --git a/coworker/sandbox/selection.py b/coworker/sandbox/selection.py
new file mode 100644
index 00000000..4ba07dfc
--- /dev/null
+++ b/coworker/sandbox/selection.py
@@ -0,0 +1,84 @@
+"""Which sandbox provider a session gets (design doc, rulings 17, 18, 22 and 29).
+
+- An explicit choice (the environment variable, or `sandbox_provider` in the machine's
+ config.toml) is obeyed. If it says `openshell` and OpenShell is not usable, sessions are
+ REFUSED: a silent fallback would hide the loss of protection.
+- With no choice made: a headless machine (`openworker up`) uses OpenShell when it is
+ installed and running, and otherwise runs `direct` with a loud warning. Anything else
+ (the desktop app, the terminal app, tests) runs `direct`, as it always has.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+import time
+from dataclasses import dataclass
+from typing import Optional
+
+from .workspace import DIRECT, OPENSHELL, PROVIDER_ENV, RUNNER_LOCAL
+
+HEADLESS_ENV = "OPENWORKER_HEADLESS" # set by `openworker up` / `join` for their process
+KNOWN = (DIRECT, OPENSHELL, RUNNER_LOCAL)
+_PROBE_SECONDS = 30.0
+
+_probe_lock = threading.Lock()
+_probe: tuple[float, Optional[str]] = (0.0, None) # (when, why OpenShell is unusable | None)
+
+
+@dataclass(frozen=True)
+class Selection:
+ provider: str
+ explicit: bool # someone chose it (environment or config), as opposed to the default rule
+ warning: str = "" # say this loudly (headless machine running unprotected)
+
+
+def is_headless() -> bool:
+ return os.environ.get(HEADLESS_ENV) == "1"
+
+
+def openshell_problem(*, fresh: bool = False) -> Optional[str]:
+ """None when OpenShell is usable on this machine, else why not. The answer is kept for a
+ short while, because it is asked for every session and costs two CLI calls."""
+ global _probe
+ with _probe_lock:
+ when, problem = _probe
+ if not fresh and when and time.monotonic() - when < _PROBE_SECONDS:
+ return problem
+ from .providers import openshell
+
+ try:
+ openshell.preflight()
+ problem = None
+ except (openshell.OpenShellUnavailable, RuntimeError, OSError) as exc:
+ problem = str(exc)
+ _probe = (time.monotonic(), problem)
+ return problem
+
+
+def select(configured: Optional[str] = None, *, headless: Optional[bool] = None) -> Selection:
+ """Raises `OpenShellUnavailable` when OpenShell was chosen explicitly and is not usable."""
+ chosen = (os.environ.get(PROVIDER_ENV) or configured or "").strip().lower()
+ if chosen:
+ if chosen not in KNOWN:
+ raise ValueError(f"unknown sandbox provider {chosen!r} (known: {', '.join(KNOWN)})")
+ if chosen == OPENSHELL:
+ problem = openshell_problem(fresh=True)
+ if problem:
+ from .providers.openshell import OpenShellUnavailable
+
+ raise OpenShellUnavailable(
+ f"This machine is set to run agents in OpenShell sandboxes, and OpenShell cannot be used right now, so no session will start. {problem}"
+ )
+ return Selection(chosen, explicit=True)
+ if headless if headless is not None else is_headless():
+ problem = openshell_problem()
+ if problem is None:
+ return Selection(OPENSHELL, explicit=False)
+ return Selection(DIRECT, explicit=False, warning=unprotected_warning(problem))
+ return Selection(DIRECT, explicit=False)
+
+
+def unprotected_warning(problem: str) -> str:
+ hint = "" if "sandbox setup" in problem else " Run `openworker machine sandbox setup` to protect this machine."
+ return f"WARNING: agents on this machine run WITHOUT a sandbox (direct mode). {problem}{hint}"
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
new file mode 100644
index 00000000..58d21a34
--- /dev/null
+++ b/coworker/sandbox/setup_cmd.py
@@ -0,0 +1,123 @@
+"""`openworker machine sandbox status|setup`: get a machine ready to run agents in
+OpenShell sandboxes (design doc, ruling 23).
+
+`setup` shows every change before it makes it and asks first (or `--yes`). It never runs
+`sudo` for you; when a step needs it, it prints the command. Someone who brings their own
+OpenShell can ignore `setup` and use `status` to see what is missing.
+
+Hidden from `openworker --help` until it has been tried on a fresh machine.
+"""
+
+from __future__ import annotations
+
+import getpass
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Callable, Optional
+
+from .. import config as app_config
+from .providers.openshell import PINNED_VERSION
+from .selection import openshell_problem, select
+
+_INSTALLER = "https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh"
+_BIND_MOUNTS = "[openshell.drivers.docker]\nenable_bind_mounts = true\n"
+
+
+def _run(argv: list[str], timeout: float = 600) -> subprocess.CompletedProcess:
+ return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)
+
+
+def _openshell_home() -> Path:
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "openshell"
+
+
+def checks() -> list[tuple[str, bool, str]]:
+ """(what, ok, detail) for everything OpenShell sandboxes need on this machine."""
+ out: list[tuple[str, bool, str]] = []
+ docker = shutil.which("docker")
+ docker_ok = bool(docker) and _run(["docker", "info", "--format", "{{.ServerVersion}}"], 30).returncode == 0
+ out.append(("Docker is installed and this user can use it", docker_ok, "" if docker_ok else "install Docker, and add this user to the `docker` group"))
+ exe = shutil.which("openshell")
+ version = _run([exe, "--version"], 15).stdout.strip().split()[-1] if exe else ""
+ out.append((f"OpenShell {PINNED_VERSION} is installed", version == PINNED_VERSION, f"found {version or 'none'}"))
+ gateway_toml = _openshell_home() / "gateway.toml"
+ binds = gateway_toml.is_file() and "enable_bind_mounts = true" in gateway_toml.read_text(encoding="utf-8")
+ out.append(("the gateway allows bind mounts (your folders reach a sandbox this way)", binds, str(gateway_toml)))
+ if sys.platform.startswith("linux"):
+ linger = _run(["loginctl", "show-user", getpass.getuser(), "-p", "Linger"], 15).stdout.strip() == "Linger=yes"
+ out.append(("the gateway keeps running after you log out (linger)", linger, "" if linger else f"sudo loginctl enable-linger {getpass.getuser()}"))
+ problem = openshell_problem(fresh=True) if exe else "OpenShell is not installed"
+ out.append(("the gateway is running", problem is None, problem or ""))
+ try:
+ import grpc # noqa: F401
+
+ grpc_ok = True
+ except ImportError:
+ grpc_ok = False
+ out.append(("the `grpcio` package is installed", grpc_ok, "" if grpc_ok else "pip install 'openworker[openshell]'"))
+ configured = app_config.load_config().sandbox_provider
+ out.append(("this machine is set to use OpenShell", configured == "openshell", f"sandbox_provider = {configured!r} in {app_config.global_config_path()}"))
+ return out
+
+
+def status(print_fn: Callable[[str], None] = print) -> int:
+ rows = checks()
+ for what, ok, detail in rows:
+ print_fn(f" [{'ok' if ok else '--'}] {what}" + (f" ({detail})" if detail and not ok else ""))
+ try:
+ chosen = select(app_config.load_config().sandbox_provider, headless=True)
+ print_fn(f"\nsessions on this machine run: {chosen.provider}" + (" (set explicitly)" if chosen.explicit else " (default rule)"))
+ if chosen.warning:
+ print_fn(chosen.warning)
+ except Exception as exc:
+ print_fn(f"\nsessions on this machine are REFUSED: {exc}")
+ return 0 if all(ok for _, ok, _ in rows) else 1
+
+
+def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, print_fn: Callable[[str], None] = print) -> int:
+ confirm = ask or (lambda question: yes or input(f"{question} [y/N] ").strip().lower() in ("y", "yes"))
+ if not sys.platform.startswith("linux"):
+ print_fn("`sandbox setup` configures a Linux machine. On a Mac, install OpenShell yourself and use `openworker machine sandbox status`.")
+ return 2
+ rows = {what: ok for what, ok, _ in checks()}
+ if not rows["Docker is installed and this user can use it"]:
+ print_fn("Docker is needed first, and installing it needs an administrator:\n https://docs.docker.com/engine/install/\n sudo usermod -aG docker $USER (then log in again)")
+ return 1
+ if not rows[f"OpenShell {PINNED_VERSION} is installed"]:
+ command = f"curl -LsSf {_INSTALLER} | OPENSHELL_VERSION=v{PINNED_VERSION} sh"
+ print_fn(f"OpenShell {PINNED_VERSION} is not installed. NVIDIA's installer downloads a package from their GitHub release,\nchecks its checksum and installs it (it will ask for sudo itself):\n {command}")
+ if not confirm("Run NVIDIA's installer now?"):
+ return 1
+ if subprocess.run(["sh", "-c", command]).returncode != 0:
+ print_fn("the installer failed; nothing else was changed")
+ return 1
+ home = _openshell_home()
+ gateway_toml, gateway_env = home / "gateway.toml", home / "gateway.env"
+ if not rows["the gateway allows bind mounts (your folders reach a sandbox this way)"]:
+ print_fn(f"Allow bind mounts, so a sandbox can be given your folders (and nothing else):\n write to {gateway_toml}:\n " + _BIND_MOUNTS.replace("\n", "\n ").rstrip() + f"\n point the gateway at it in {gateway_env}, then restart the gateway (running sandboxes restart too)")
+ if not confirm("Make this change?"):
+ return 1
+ home.mkdir(parents=True, exist_ok=True)
+ existing = gateway_toml.read_text(encoding="utf-8") if gateway_toml.is_file() else ""
+ if "[openshell.drivers.docker]" in existing:
+ print_fn(f"{gateway_toml} already has a [openshell.drivers.docker] table; add `enable_bind_mounts = true` to it by hand.")
+ return 1
+ gateway_toml.write_text((existing.rstrip() + "\n\n" if existing.strip() else "") + _BIND_MOUNTS, encoding="utf-8")
+ env_line = f"OPENSHELL_GATEWAY_CONFIG={gateway_toml}\n"
+ env_text = gateway_env.read_text(encoding="utf-8") if gateway_env.is_file() else ""
+ if "OPENSHELL_GATEWAY_CONFIG=" not in env_text:
+ gateway_env.write_text(env_text + env_line, encoding="utf-8")
+ _run(["systemctl", "--user", "restart", "openshell-gateway"], 120)
+ if not rows.get("the gateway keeps running after you log out (linger)", True):
+ user = getpass.getuser()
+ if _run(["loginctl", "enable-linger", user], 30).returncode != 0:
+ print_fn(f"The gateway is a user service and stops when you log out. An administrator has to run:\n sudo loginctl enable-linger {user}")
+ if not rows["this machine is set to use OpenShell"]:
+ print_fn(f"Set this machine to run agents in OpenShell sandboxes, and to REFUSE sessions when OpenShell is not running:\n sandbox_provider = \"openshell\" in {app_config.global_config_path()}")
+ if confirm("Make this change?"):
+ app_config.set_global_value("sandbox_provider", "openshell")
+ print_fn("")
+ return status(print_fn)
diff --git a/tests/test_sandbox_selection.py b/tests/test_sandbox_selection.py
new file mode 100644
index 00000000..7a310d1f
--- /dev/null
+++ b/tests/test_sandbox_selection.py
@@ -0,0 +1,140 @@
+"""Which sandbox provider a session gets, and the machine commands around it
+(design doc `sandbox-design.md`, rulings 17, 18, 22, 23 and 29)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from coworker import config
+from coworker.sandbox import selection
+from coworker.sandbox.providers.openshell import OpenShellUnavailable
+
+
[email protected](autouse=True)
+def clean(monkeypatch):
+ monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER", raising=False)
+ monkeypatch.delenv("OPENWORKER_HEADLESS", raising=False)
+
+
+def _openshell(monkeypatch, problem):
+ monkeypatch.setattr(selection, "openshell_problem", lambda fresh=False: problem)
+
+
+def test_the_desktop_and_the_terminal_app_stay_direct(monkeypatch):
+ _openshell(monkeypatch, None) # even with OpenShell installed and running
+ chosen = selection.select(None)
+ assert (chosen.provider, chosen.explicit, chosen.warning) == ("direct", False, "")
+
+
+def test_a_headless_machine_uses_openshell_when_it_is_there(monkeypatch):
+ _openshell(monkeypatch, None)
+ monkeypatch.setenv("OPENWORKER_HEADLESS", "1")
+ assert selection.select(None).provider == "openshell"
+
+
+def test_a_headless_machine_without_openshell_runs_direct_and_says_so_loudly(monkeypatch):
+ _openshell(monkeypatch, "The OpenShell gateway is not running.")
+ chosen = selection.select(None, headless=True)
+ assert chosen.provider == "direct" and not chosen.explicit
+ assert "WITHOUT a sandbox" in chosen.warning and "gateway is not running" in chosen.warning
+ assert chosen.warning.count("sandbox setup") == 1
+
+
+def test_an_explicit_openshell_setting_refuses_instead_of_falling_back(monkeypatch):
+ _openshell(monkeypatch, "The OpenShell gateway is not running.")
+ with pytest.raises(OpenShellUnavailable, match="no session will start"):
+ selection.select("openshell")
+ _openshell(monkeypatch, None)
+ assert selection.select("openshell") == selection.Selection("openshell", explicit=True)
+
+
+def test_the_environment_wins_over_the_config_and_unknown_names_are_refused(monkeypatch):
+ _openshell(monkeypatch, None)
+ monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "direct")
+ assert selection.select("openshell", headless=True) == selection.Selection("direct", explicit=True)
+ monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "firejail")
+ with pytest.raises(ValueError, match="unknown sandbox provider"):
+ selection.select(None)
+
+
+def test_a_repository_cannot_switch_the_sandbox_off(tmp_path):
+ machine = tmp_path / "config.toml"
+ config.set_global_value("sandbox_provider", "openshell", path=machine)
+ repo = tmp_path / "repo"
+ (repo / ".coworker").mkdir(parents=True)
+ (repo / ".coworker" / "config.toml").write_text('sandbox_provider = "direct"\nmodel = "from-the-repo"\n')
+ loaded = config.load_config(repo, global_path=machine)
+ assert loaded.sandbox_provider == "openshell" and loaded.model == "from-the-repo"
+
+
+def test_setting_a_config_value_keeps_the_rest_of_the_file(tmp_path):
+ path = tmp_path / "config.toml"
+ path.write_text('model = "x"\n\n[some.table]\nkey = 1\n')
+ config.set_global_value("sandbox_provider", "openshell", path=path)
+ config.set_global_value("sandbox_provider", "direct", path=path)
+ text = path.read_text()
+ assert text.count("sandbox_provider") == 1 and text.index("sandbox_provider") < text.index("[some.table]")
+ assert config.load_config(global_path=path).sandbox_provider == "direct" and 'model = "x"' in text
+ with pytest.raises(ValueError):
+ config.set_global_value("not_a_key", "x", path=path)
+
+
+def test_machine_status_reports_how_sessions_will_run(tmp_path, monkeypatch, capsys):
+ from coworker.remote import joiner
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ _openshell(monkeypatch, "OpenShell is not installed on this machine.")
+ info = joiner.machine_status(tmp_path)["sandbox"]
+ assert info["provider"] == "direct" and "WITHOUT a sandbox" in info["warning"]
+ joiner._cmd_status(tmp_path)
+ assert "sandbox: direct" in capsys.readouterr().out
+
+ config.set_global_value("sandbox_provider", "openshell")
+ refused = joiner.machine_status(tmp_path)["sandbox"]
+ assert refused["provider"] is None and "no session will start" in refused["refused"]
+ joiner._cmd_status(tmp_path, as_json=True)
+ assert json.loads(capsys.readouterr().out)["sandbox"]["provider"] is None
+
+
+def test_the_sandbox_command_is_served_but_not_advertised(tmp_path, monkeypatch, capsys):
+ from coworker import cli
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ _openshell(monkeypatch, "OpenShell is not installed on this machine.")
+ # The same answer on any machine, with or without OpenShell installed.
+ monkeypatch.setattr(setup_cmd, "checks", lambda: [(f"OpenShell {setup_cmd.PINNED_VERSION} is installed", False, "found none")])
+ assert "sandbox" not in cli.HELP # hidden until tried on a fresh machine
+ with pytest.raises(SystemExit) as done:
+ cli.main(["machine", "sandbox", "status"])
+ assert done.value.code == 1 # something is missing here
+ out = capsys.readouterr().out
+ assert "[--] OpenShell" in out and "sessions on this machine run: direct" in out
+
+
+def test_setup_asks_before_each_change_and_makes_none_when_refused(tmp_path, monkeypatch):
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")
+ monkeypatch.setattr(
+ setup_cmd,
+ "checks",
+ lambda: [
+ ("Docker is installed and this user can use it", True, ""),
+ (f"OpenShell {setup_cmd.PINNED_VERSION} is installed", True, ""),
+ ("the gateway allows bind mounts (your folders reach a sandbox this way)", False, ""),
+ ("the gateway is running", True, ""),
+ ("this machine is set to use OpenShell", False, ""),
+ ],
+ )
+ asked: list[str] = []
+ said: list[str] = []
+ code = setup_cmd.setup(ask=lambda q: asked.append(q) or False, print_fn=said.append)
+ assert code == 1 and asked == ["Make this change?"]
+ assert "enable_bind_mounts = true" in "\n".join(said) # the change was shown first
+ assert not (tmp_path / "xdg" / "openshell" / "gateway.toml").exists()
+ assert config.load_config().sandbox_provider is None