Python
Settings > Sandbox: one switch, a readiness checklist, collapsible sub-settings, and a guided "Set up sandbox" (OPE-207)
Devika Verma126e210cec98
diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex 7a2f3203..e568c14b 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -69,6 +69,18 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:}+def readiness() -> dict[str, Any]:+ """The checklist Settings ▸ Sandbox shows for OpenShell: the same rows as `openworker+ machine sandbox status`, with keys and whether the app may fix each one itself+ (OPE-207). Costs a few CLI calls; the page asks for it separately from `snapshot`."""+ from . import setup_cmd++ if sys.platform == "win32":+ return {"platform": sys.platform, "supported": False, "steps": [], "all_ok": False}+ rows = [s.as_dict() for s in setup_cmd.steps()]+ return {"platform": sys.platform, "supported": True, "steps": rows, "all_ok": all(r["ok"] for r in rows)}++def _for_display(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:"""A shipped entry's title and wording are left out when the user has not changedthem, so the app can show them in the user's language; a user's own text is kept."""diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.pyindex 9e621db0..859d2fef 100644--- a/coworker/sandbox/setup_cmd.py+++ b/coworker/sandbox/setup_cmd.py@@ -5,18 +5,25 @@ OpenShell sandboxes (design doc, ruling 23).`sudo` for you; when a step needs it, it prints the command. Someone who brings their ownOpenShell can ignore `setup` and use `status` to see what is missing.+The same steps serve Settings ▸ Sandbox (OPE-207): `steps()` is the readiness list the page+shows, and `setup_job.SetupJob` runs the fixes the app may apply on its own, with progress,+handing the rest over as commands to run. One list of checks and fixes, two front ends.+Hidden from `openworker --help` until it has been tried on a fresh machine."""from __future__ import annotations+import ctypesimport getpassimport osimport shutilimport subprocessimport sys+import threading+from dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Callable, Optional+from typing import Any, Callable, Optionalfrom .. import config as app_configfrom .providers import openshell@@ -29,6 +36,38 @@ _BIND_MOUNTS = "[openshell.drivers.docker]\nenable_bind_mounts = true\n"# outlives the create's timeout and hangs the first session (OPE-205). So it is a check of# its own, and `setup` offers the download with Docker's own progress and no time limit.IMAGE_ROW = "the sandbox base image is downloaded (about 5 GB, one time)"+# Unpacked, the image is larger than its download; this much free space avoids a failed+# pull halfway (OPE-207).+IMAGE_FREE_GB = 10++# Row titles, by key. Kept as constants: tests and `setup()` look rows up by title.+ROWS = {+ "docker": "Docker is installed and this user can use it",+ "openshell": f"OpenShell {PINNED_VERSION} is installed",+ "bind_mounts": "the gateway allows bind mounts (your folders reach a sandbox this way)",+ "linger": "the gateway keeps running after you log out (linger)",+ "gateway": "the gateway is running",+ "grpcio": "the `grpcio` package is installed",+ "landlock": "the kernel supports Landlock (OpenShell requires it)",+ "config": "this machine is set to use OpenShell",+ "disk": f"enough free disk space for the base image (about {IMAGE_FREE_GB} GB)",+ "image": IMAGE_ROW,+}+# Steps the app may fix on its own (no administrator, no installer). The rest are shown+# as a command for the user to run.+FIXABLE = {"bind_mounts", "config", "image", "linger"}+++@dataclass+class Step:+ key: str+ what: str+ ok: bool+ hint: str = "" # what to run, or why it failed+ fixable: bool = False # `SetupJob` can do this one itself++ def as_dict(self) -> dict[str, Any]:+ return {"key": self.key, "what": self.what, "ok": self.ok, "hint": self.hint, "fixable": self.fixable}def _run(argv: list[str], timeout: float = 600) -> subprocess.CompletedProcess:@@ -39,42 +78,175 @@ 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]] = []+def landlock_available() -> Optional[bool]:+ """Whether this kernel has Landlock: True/False on Linux, None elsewhere (a Mac's+ sandboxes run in Docker Desktop's own Linux VM, which cannot be asked from here).+ `landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION)` returns the ABI+ version; the syscall number 444 is the same on x86-64 and arm64."""+ if not sys.platform.startswith("linux"):+ return None+ try:+ libc = ctypes.CDLL(None, use_errno=True)+ return libc.syscall(444, None, 0, 1) >= 0+ except Exception:+ return None+++def image_store_free_gb() -> Optional[float]:+ """Free space where the driver keeps images, in GB, or None when it cannot be told."""+ try:+ tool = openshell.image_tool()+ if tool is None:+ return None+ root = _run([tool, "info", "--format", "{{.DockerRootDir}}" if tool == "docker" else "{{.Store.GraphRoot}}"], 30).stdout.strip()+ if not root or not os.path.isdir(root):+ # Docker Desktop's storage lives in its VM: the host's disk is the next best guess.+ root = str(Path.home())+ return shutil.disk_usage(root).free / 1e9+ except Exception: # no openshell, no docker, an odd `info`: "cannot tell", never a red row+ return None+++def steps() -> list[Step]:+ """Everything OpenShell sandboxes need on this machine, in the order `setup` handles it."""+ out: list[Step] = []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"))+ out.append(Step("docker", ROWS["docker"], 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'}"))+ out.append(Step("openshell", ROWS["openshell"], version == PINNED_VERSION, f"found {version or 'none'}" if version != PINNED_VERSION else ""))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)))+ out.append(Step("bind_mounts", ROWS["bind_mounts"], binds, "" if binds else str(gateway_toml), fixable=True))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()}"))+ out.append(Step("linger", ROWS["linger"], linger, "" if linger else f"sudo loginctl enable-linger {getpass.getuser()}", fixable=True))+ landlock = landlock_available()+ if landlock is not None:+ out.append(Step("landlock", ROWS["landlock"], landlock, "" if landlock else "update the kernel (on WSL: `wsl --update` from Windows)"))problem = openshell_problem(fresh=True) if exe else "OpenShell is not installed"# A missing image is not a gateway problem: it gets its own row below.image_missing = openshell.is_image_problem(problem)gateway_ok = problem is None or image_missing- out.append(("the gateway is running", gateway_ok, "" if gateway_ok else (problem or "")))+ out.append(Step("gateway", ROWS["gateway"], gateway_ok, "" if gateway_ok else (problem or "")))try:import grpc # noqa: F401grpc_ok = Trueexcept ImportError:grpc_ok = False- out.append(("the `grpcio` package is installed", grpc_ok, "" if grpc_ok else "pip install 'openworker[openshell]'"))+ out.append(Step("grpcio", ROWS["grpcio"], grpc_ok, "" if grpc_ok else "pip install 'openworker[openshell]'"))+ configured = app_config.load_config().sandbox_provider+ out.append(Step("config", ROWS["config"], configured == "openshell", "" if configured == "openshell" else f"sandbox_provider = {configured!r} in {app_config.global_config_path()}", fixable=True))if gateway_ok and exe:present = openshell.image_present()if present is not None: # only a local docker/podman driver can be asked; others get no row- out.append((IMAGE_ROW, present, "" if present else f"{openshell.image_tool() or 'docker'} pull {openshell.sandbox_image()}"))- 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()}"))+ if not present:+ free = image_store_free_gb()+ if free is not None:+ out.append(Step("disk", ROWS["disk"], free >= IMAGE_FREE_GB, "" if free >= IMAGE_FREE_GB else f"{free:.1f} GB free; free up space before the download"))+ out.append(Step("image", IMAGE_ROW, present, "" if present else f"{openshell.image_tool() or 'docker'} pull {openshell.sandbox_image()}", fixable=True))return out+def checks() -> list[tuple[str, bool, str]]:+ """(what, ok, detail) rows: the shape `status` prints and older callers read."""+ return [(s.what, s.ok, s.hint) for s in steps()]+++# -- the fixes, one function each: `setup` (with prompts) and `SetupJob` (with progress) --+++def bind_mounts_change() -> str:+ """What `apply_bind_mounts` will do, for showing before asking."""+ home = _openshell_home()+ return (+ f"Allow bind mounts, so a sandbox can be given your folders (and nothing else):\n write to {home / 'gateway.toml'}:\n "+ + _BIND_MOUNTS.replace("\n", "\n ").rstrip()+ + f"\n point the gateway at it in {home / 'gateway.env'}, then restart the gateway (running sandboxes restart too)"+ )+++def apply_bind_mounts() -> Optional[str]:+ """Write the gateway config, point the service at it, restart it. Returns an error+ text when the config already has a docker table (never edit that by hand-off)."""+ home = _openshell_home()+ gateway_toml, gateway_env = home / "gateway.toml", home / "gateway.env"+ 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:+ return f"{gateway_toml} already has a [openshell.drivers.docker] table; add `enable_bind_mounts = true` to it by hand."+ 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)+ return None+++def enable_linger() -> Optional[str]:+ """Try without an administrator; return the command to run when that is refused."""+ user = getpass.getuser()+ if _run(["loginctl", "enable-linger", user], 30).returncode != 0:+ return f"sudo loginctl enable-linger {user}"+ return None+++def apply_config() -> None:+ app_config.set_global_value("sandbox_provider", "openshell")+++@dataclass+class PullProgress:+ layers_total: int = 0+ layers_done: int = 0+ last_line: str = ""+ layers: dict[str, str] = field(default_factory=dict)++ def as_dict(self) -> dict[str, Any]:+ return {"layers_total": self.layers_total, "layers_done": self.layers_done, "last_line": self.last_line}+++def pull_image(on_progress: Optional[Callable[[PullProgress], None]] = None, cancel: Optional[threading.Event] = None) -> Optional[str]:+ """`docker pull` (or podman), streaming its per-layer lines into a PullProgress.+ No time limit: on a slow link this is the 20-minute step. Returns an error text on+ failure or cancellation, None when the image is there."""+ tool, image = openshell.image_tool() or "docker", openshell.sandbox_image()+ progress = PullProgress()+ try:+ proc = subprocess.Popen([tool, "pull", image], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)+ except OSError as exc:+ return f"could not run {tool}: {exc}"+ assert proc.stdout is not None+ for line in proc.stdout:+ if cancel is not None and cancel.is_set():+ proc.kill()+ proc.wait()+ return "download cancelled"+ line = line.strip()+ if not line:+ continue+ progress.last_line = line[:160]+ # Without a terminal Docker prints "<layer id>: <status>" once per change.+ if ": " in line:+ layer, status = line.split(": ", 1)+ if len(layer) == 12 and layer.isalnum():+ progress.layers[layer] = status+ progress.layers_total = len(progress.layers)+ progress.layers_done = sum(1 for s in progress.layers.values() if s.startswith(("Pull complete", "Already exists")))+ if on_progress is not None:+ on_progress(progress)+ code = proc.wait()+ if code != 0:+ return f"{tool} pull exited with {code}: {progress.last_line}"+ return None+++# -- the terminal front end -------------------------------------------------------------++def seatbelt_check() -> tuple[str, bool, str]:from .providers import seatbelt@@ -128,10 +300,10 @@ def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, pristop = _offer_image_download(rows, confirm, print_fn)return 2 if stop is None else stoprows = {what: ok for what, ok, _ in checks()}- if not rows["Docker is installed and this user can use it"]:+ if not rows[ROWS["docker"]]: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"]:+ if not rows[ROWS["openshell"]]: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?"):@@ -139,31 +311,22 @@ def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, priif 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 rows[ROWS["bind_mounts"]]:+ print_fn(bind_mounts_change())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.")+ problem = apply_bind_mounts()+ if problem:+ print_fn(problem)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"]:+ if not rows.get(ROWS["linger"], True):+ command = enable_linger()+ if command:+ print_fn(f"The gateway is a user service and stops when you log out. An administrator has to run:\n {command}")+ if not rows[ROWS["config"]]: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")+ apply_config()# Last, because it is the slow one: the image the gateway builds sandboxes from. The# gateway may only just have started (bind-mount change above), so ask again.if IMAGE_ROW not in rows:diff --git a/coworker/sandbox/setup_job.py b/coworker/sandbox/setup_job.pynew file mode 100644index 00000000..6bd9da9e--- /dev/null+++ b/coworker/sandbox/setup_job.py@@ -0,0 +1,163 @@+"""The guided setup behind Settings ▸ Sandbox ▸ "Set up sandbox" (OPE-207).++One job per machine, on a worker thread. It walks `setup_cmd.steps()` top to bottom: a+step the app may fix itself (bind mounts, the config line, linger when no administrator+is needed, the image download) is fixed with its status shown; a step that needs an+administrator or an installer is handed over as a command to run, and the job stops there+until the user says "check again". The image download reports progress and can be+cancelled. The job never runs anything as root and never lowers protection: a failure+leaves the machine "not ready, here is what to do", and sessions stay refused.+"""++from __future__ import annotations++import sys+import threading+import time+from typing import Any, Callable, Optional++from . import setup_cmd+++class SetupJob:+ # Step states, in the words the page shows.+ PENDING, FIXING, FIXED, OK, NEEDS_YOU, FAILED = "pending", "fixing", "fixed", "ok", "needs_you", "failed"++ def __init__(self, steps: Optional[Callable[[], list[setup_cmd.Step]]] = None) -> None:+ # Resolved at call time, not bound at import: tests swap `setup_cmd.steps` out.+ self._steps_fn = steps or (lambda: setup_cmd.steps())+ self._lock = threading.Lock()+ self._thread: Optional[threading.Thread] = None+ self._cancel = threading.Event()+ self.status = "idle" # idle | running | done | needs_you | failed | cancelled+ self.rows: list[dict[str, Any]] = []+ self.progress: Optional[dict[str, Any]] = None+ self.error = ""+ self.started_at = 0.0+ self.finished_at = 0.0++ # -- reading ----------------------------------------------------------------------+ def state(self) -> dict[str, Any]:+ with self._lock:+ return {+ "status": self.status,+ "rows": [dict(r) for r in self.rows],+ "progress": dict(self.progress) if self.progress else None,+ "error": self.error,+ "started_at": self.started_at,+ "finished_at": self.finished_at,+ "elapsed_s": int((self.finished_at or time.time()) - self.started_at) if self.started_at else 0,+ }++ def _set_row(self, key: str, **changes: Any) -> None:+ with self._lock:+ for row in self.rows:+ if row["key"] == key:+ row.update(changes)++ # -- control ----------------------------------------------------------------------+ def start(self) -> dict[str, Any]:+ """Start (or restart) the walk. Idempotent while running."""+ with self._lock:+ if self._thread is not None and self._thread.is_alive():+ return self.state()+ self._cancel.clear()+ self.status, self.error, self.progress = "running", "", None+ self.started_at, self.finished_at = time.time(), 0.0+ self.rows = []+ self._thread = threading.Thread(target=self._run, name="sandbox-setup", daemon=True)+ self._thread.start()+ return self.state()++ def cancel(self) -> dict[str, Any]:+ self._cancel.set()+ return self.state()++ # -- the walk ---------------------------------------------------------------------+ def _run(self) -> None:+ try:+ self._walk()+ except Exception as exc: # never leave the page without a verdict+ with self._lock:+ self.status, self.error = "failed", f"{type(exc).__name__}: {exc}"+ finally:+ with self._lock:+ self.finished_at = time.time()++ def _walk(self) -> None:+ steps = self._steps_fn()+ with self._lock:+ self.rows = [{**s.as_dict(), "state": self.OK if s.ok else self.PENDING} for s in steps]+ for step in steps:+ if self._cancel.is_set():+ with self._lock:+ self.status = "cancelled"+ return+ if step.ok:+ continue+ if not step.fixable:+ # Needs an administrator or an installer: hand the command over and stop+ # here, so later steps (which may depend on this one) are not attempted.+ self._set_row(step.key, state=self.NEEDS_YOU)+ with self._lock:+ self.status = "needs_you"+ return+ self._set_row(step.key, state=self.FIXING)+ problem = self._fix(step)+ if problem is None:+ self._set_row(step.key, state=self.FIXED, hint="")+ continue+ if step.key == "linger":+ # Refused without an administrator: not fatal, the command is shown; go on.+ self._set_row(step.key, state=self.NEEDS_YOU, hint=problem)+ continue+ self._set_row(step.key, state=self.FAILED, hint=problem)+ with self._lock:+ self.status = "cancelled" if self._cancel.is_set() else "failed"+ self.error = problem+ return+ # Everything fixable is fixed. Re-check, so the verdict is what `status` would say.+ final = self._steps_fn()+ with self._lock:+ done = {r["key"]: r for r in self.rows}+ for s in final:+ if s.key in done:+ done[s.key]["ok"] = s.ok+ if s.ok:+ done[s.key]["state"] = self.OK if done[s.key]["state"] != self.FIXED else self.FIXED+ elif done[s.key]["state"] not in (self.NEEDS_YOU, self.FAILED):+ done[s.key]["state"] = self.FAILED+ done[s.key]["hint"] = s.hint+ else:+ self.rows.append({**s.as_dict(), "state": self.OK if s.ok else self.NEEDS_YOU})+ self.status = "done" if all(s.ok for s in final) else "needs_you"++ def _fix(self, step: setup_cmd.Step) -> Optional[str]:+ if step.key == "bind_mounts":+ return setup_cmd.apply_bind_mounts()+ if step.key == "config":+ setup_cmd.apply_config()+ return None+ if step.key == "linger":+ return setup_cmd.enable_linger() if sys.platform.startswith("linux") else None+ if step.key == "image":++ def on_progress(p: setup_cmd.PullProgress) -> None:+ with self._lock:+ self.progress = {**p.as_dict(), "elapsed_s": int(time.time() - self.started_at)}++ return setup_cmd.pull_image(on_progress, self._cancel)+ return f"no automatic fix for {step.key}"+++_job: Optional[SetupJob] = None+_job_lock = threading.Lock()+++def job() -> SetupJob:+ """The machine's one setup job (the server is one machine)."""+ global _job+ with _job_lock:+ if _job is None:+ _job = SetupJob()+ return _jobdiff --git a/coworker/server/app.py b/coworker/server/app.pyindex be43336f..c48b1e06 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2405,6 +2405,33 @@ def create_app(manager: SessionManager) -> FastAPI:return sandbox_settings.update(body or {})+ @app.get("/v1/settings/sandbox/readiness")+ async def settings_sandbox_readiness() -> dict[str, Any]:+ # OPE-207: the checklist behind "Set up sandbox". A few CLI calls, so off the loop.+ from ..sandbox import settings as sandbox_settings++ return await asyncio.to_thread(sandbox_settings.readiness)++ @app.get("/v1/settings/sandbox/setup")+ def settings_sandbox_setup_state() -> dict[str, Any]:+ from ..sandbox import setup_job++ return setup_job.job().state()++ @app.post("/v1/settings/sandbox/setup")+ def settings_sandbox_setup_start() -> dict[str, Any]:+ # Runs on its own thread: fixes what the app may fix (never as root), hands the+ # rest over as commands, downloads the image with progress. GET polls the state.+ from ..sandbox import setup_job++ return setup_job.job().start()++ @app.post("/v1/settings/sandbox/setup/cancel")+ def settings_sandbox_setup_cancel() -> dict[str, Any]:+ from ..sandbox import setup_job++ return setup_job.job().cancel()+@app.post("/v1/settings/compaction")def settings_set_compaction(body: dict) -> dict[str, Any]:# Auto-compaction overrides (OPE-27): threshold % of the context window, thediff --git a/docs/openshell.md b/docs/openshell.mdindex c1132b90..311974fa 100644--- a/docs/openshell.md+++ b/docs/openshell.md@@ -80,6 +80,16 @@ Sandbox shows OpenShell as **needs download** and a session is refused with themessage, rather than hanging on the download. `setup` offers it with Docker's ownprogress; the command is also `docker pull` of the image named in the refusal.+Settings ▸ Sandbox does the same from the app: one switch, **Run agents in a sandbox**,+and under it the provider, a readiness checklist (the rows `status` prints, with what to+run for each missing one), and a **Set up sandbox** button that walks the list. The app+fixes what it may (the gateway's bind-mount setting, the config line, the image download+with progress) and hands the rest over as a command to copy, because it never runs+anything as an administrator; **Check again** continues once you have run it. The+network allow list and the shared credentials appear only while the switch is on: they+apply behind a wall and nowhere else. On Windows the switch is off and disabled; run+OpenWorker on a Linux machine (a WSL Ubuntu counts) added under Settings ▸ Machines.+The setting is per machine, in Settings ▸ Sandbox or in `config.toml`:```tomldiff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 7c49c347..bef3c8e1 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2128,6 +2128,51 @@ export async function setSandboxSettings(return res.json();}+// OPE-207: the readiness checklist behind Settings ▸ Sandbox (the rows `openworker machine+// sandbox status` prints, with a key and whether the app may fix each one itself), and+// the guided setup job that walks it on the machine where sessions run.+export interface SandboxReadinessStep {+ key: string;+ what: string;+ ok: boolean;+ hint: string;+ fixable: boolean;+}+export interface SandboxReadiness {+ platform: string;+ supported: boolean;+ steps: SandboxReadinessStep[];+ all_ok: boolean;+}+export type SandboxSetupRowState = "pending" | "fixing" | "fixed" | "ok" | "needs_you" | "failed";+export interface SandboxSetupState {+ status: "idle" | "running" | "done" | "needs_you" | "failed" | "cancelled";+ rows: (SandboxReadinessStep & { state: SandboxSetupRowState })[];+ progress: { layers_total: number; layers_done: number; last_line: string; elapsed_s: number } | null;+ error: string;+ elapsed_s: number;+}++export async function getSandboxReadiness(machineId?: string | null): Promise<SandboxReadiness> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/readiness`);+ return res.json();+}++export async function getSandboxSetup(machineId?: string | null): Promise<SandboxSetupState> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/setup`);+ return res.json();+}++export async function startSandboxSetup(machineId?: string | null): Promise<SandboxSetupState> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/setup`, { method: "POST" });+ return res.json();+}++export async function cancelSandboxSetup(machineId?: string | null): Promise<SandboxSetupState> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/setup/cancel`, { method: "POST" });+ return res.json();+}+export async function getSettings(machineId?: string | null): Promise<ModelSettings> {const res = await fetch(`${engineBase(machineId)}/v1/settings`);return res.json();diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsxindex ce2b1387..787123d8 100644--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx@@ -1,17 +1,17 @@-// Settings ▸ Sandbox (UX-051 A): the page shows what the machine reports and writes back-// the three kinds of change: provider, network profile, credential list.+// Settings ▸ Sandbox (UX-051 A, OPE-207): one switch, then the provider, the readiness+// checklist with its guided setup, and the sub-settings that only apply behind a wall.import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-const snapshot = {+const base = {platform: "darwin",provider: "",effective_provider: "direct",refused: "",providers: [- { name: "direct", usable: true, why: "" },- { name: "seatbelt", usable: true, why: "" },- { name: "openshell", usable: false, why: "OpenShell is not installed" },+ { name: "direct", usable: true, why: "", state: "ready" },+ { name: "seatbelt", usable: true, why: "", state: "ready" },+ { name: "openshell", usable: false, why: "OpenShell is not installed", state: "unavailable" },],network_profile: "strict",network_profiles: [@@ -24,8 +24,25 @@ const snapshot = {],config_path: "/Users/sam/.config/coworker/config.toml",};+let snapshot: any = base;+const readiness = {+ platform: "linux",+ supported: true,+ all_ok: false,+ steps: [+ { key: "docker", what: "Docker is installed and this user can use it", ok: true, hint: "", fixable: false },+ { key: "openshell", what: "OpenShell 0.0.116 is installed", ok: false, hint: "curl -LsSf https://example/install.sh | sh", fixable: false },+ { key: "image", what: "the sandbox base image is downloaded (about 5 GB, one time)", ok: false, hint: "docker pull img", fixable: true },+ ],+};+let setupState: any = { status: "idle", rows: [], progress: null, error: "", elapsed_s: 0 };-const setSandboxSettings = vi.fn(async (patch: any) => ({ ok: true, ...snapshot, ...patch }));+// Like the backend: each save returns the whole (updated) snapshot.+const setSandboxSettings = vi.fn(async (patch: any) => {+ snapshot = { ...snapshot, ...patch };+ return { ok: true, ...snapshot };+});+const startSandboxSetup = vi.fn(async () => setupState);vi.mock("../api", async (importOriginal) => {const actual = await importOriginal<typeof import("../api")>();@@ -33,6 +50,10 @@ vi.mock("../api", async (importOriginal) => {...actual,getSandboxSettings: vi.fn(async () => snapshot),setSandboxSettings: (patch: any) => setSandboxSettings(patch),+ getSandboxReadiness: vi.fn(async () => readiness),+ getSandboxSetup: vi.fn(async () => setupState),+ startSandboxSetup: () => startSandboxSetup(),+ cancelSandboxSetup: vi.fn(async () => setupState),getMachines: vi.fn(async () => ({ machines: [] })),getCloudMachines: vi.fn(async () => ({ machines: [] })),getCloudConnections: vi.fn(async () => []),@@ -45,27 +66,35 @@ vi.mock("../api", async (importOriginal) => {import { SettingsView } from "./SettingsView";describe("Settings ▸ Sandbox", () => {- beforeEach(() => setSandboxSettings.mockClear());+ beforeEach(() => {+ setSandboxSettings.mockClear();+ startSandboxSetup.mockClear();+ snapshot = base;+ setupState = { status: "idle", rows: [], progress: null, error: "", elapsed_s: 0 };+ });afterEach(cleanup);- it("shows the providers, the allow list and the credential rows from the machine", async () => {+ it("with no sandbox chosen: the switch is off and the sub-settings are not shown", async () => {render(<SettingsView initialTab="sandbox" />);await screen.findByTestId("sandbox-section");- expect((screen.getByTestId("sandbox-provider-direct") as HTMLInputElement).checked).toBe(true);- expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(true);- expect(screen.getByText("default")).toBeTruthy();- expect((screen.getByTestId("sandbox-network-strict") as HTMLInputElement).checked).toBe(true);- expect(screen.getByText("SSH keys")).toBeTruthy();- expect((screen.getByLabelText("GitHub CLI") as HTMLInputElement).checked).toBe(true);- expect(screen.getByText(/Also allows github.com:22/)).toBeTruthy();+ expect((screen.getByTestId("sandbox-switch") as HTMLInputElement).checked).toBe(false);+ expect(screen.getByText(/Off: commands run as you/)).toBeTruthy();+ expect(screen.queryByTestId("sandbox-network-section")).toBeNull();+ expect(screen.queryByTestId("sandbox-credentials-section")).toBeNull();+ expect(screen.queryByTestId("sandbox-readiness")).toBeNull();+ expect(screen.queryByText("ready")).toBeNull(); // no status word for "no sandbox"expect(screen.getByText(/config\.toml/)).toBeTruthy();});- it("writes a provider change, a profile change and a credential switch", async () => {+ it("switching on picks the provider that needs no setup on a Mac, and off clears the key", async () => {render(<SettingsView initialTab="sandbox" />);await screen.findByTestId("sandbox-section");- fireEvent.click(screen.getByTestId("sandbox-provider-seatbelt"));+ fireEvent.click(screen.getByTestId("sandbox-switch"));await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "seatbelt" }));+ // Now on: the provider line (a dropdown on a Mac) and the sub-settings appear.+ expect((screen.getByTestId("sandbox-provider-select") as HTMLSelectElement).value).toBe("seatbelt");+ expect(screen.getByTestId("sandbox-network-section")).toBeTruthy();+ expect(screen.getByTestId("sandbox-credentials-section")).toBeTruthy();fireEvent.click(screen.getByTestId("sandbox-network-standard"));await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ network_profile: "standard" }));fireEvent.click(screen.getByLabelText("SSH keys"));@@ -77,31 +106,90 @@ describe("Settings ▸ Sandbox", () => {],}),);+ fireEvent.click(screen.getByTestId("sandbox-switch"));+ await waitFor(() => expect(setSandboxSettings).toHaveBeenLastCalledWith({ provider: "" })); // cleared, not "direct"});- it("shows OpenShell as 'needs download' and keeps it selectable when only the base image is missing", async () => {- // OPE-205: everything is in place except the one-time 5 GB image; "ready" would send- // the user into a first session that hangs on the download.- const { getSandboxSettings } = await import("../api");- (getSandboxSettings as any).mockResolvedValueOnce({- ...snapshot,+ it("with OpenShell on Linux: the readiness checklist, its hints, and the setup button", async () => {+ snapshot = {+ ...base,+ platform: "linux",+ provider: "openshell",+ effective_provider: "",+ refused: "no session will start: OpenShell is not installed",providers: [{ name: "direct", usable: true, why: "", state: "ready" },- { name: "seatbelt", usable: true, why: "", state: "ready" },- { name: "openshell", usable: false, why: "The sandbox base image is not downloaded yet", state: "needs_download" },+ { name: "seatbelt", usable: false, why: "macOS only", state: "unavailable" },+ { name: "openshell", usable: false, why: "OpenShell is not installed", state: "unavailable" },],- });+ };render(<SettingsView initialTab="sandbox" />);- await screen.findByTestId("sandbox-section");- expect(screen.getByText("needs download")).toBeTruthy();- expect(screen.getByTestId("sandbox-provider-openshell-hint").textContent).toMatch(/sandbox setup/);- expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(false);- expect(screen.queryByText("not available")).toBeNull();+ await screen.findByTestId("sandbox-readiness");+ expect((screen.getByTestId("sandbox-switch") as HTMLInputElement).checked).toBe(true);+ expect(screen.getByTestId("sandbox-provider-openshell").textContent).toBe("OpenShell (NVIDIA)");+ expect(screen.queryByTestId("sandbox-provider-select")).toBeNull(); // one provider on Linux: no dropdown+ await screen.findByTestId("sandbox-readiness-row-openshell");+ expect(screen.getByText("2 requirements missing")).toBeTruthy();+ expect(screen.getByTestId("sandbox-readiness-row-docker").getAttribute("data-state")).toBe("ok");+ expect(screen.getByTestId("sandbox-readiness-row-openshell").getAttribute("data-state")).toBe("pending");+ expect(screen.getByText("curl -LsSf https://example/install.sh | sh")).toBeTruthy(); // the command to run+ expect(screen.getAllByText("Copy").length).toBe(2);+ expect((screen.getByTestId("sandbox-setup-start") as HTMLButtonElement).disabled).toBe(false);+ });++ it("running the setup: the job's rows, the download progress, and the handover verdict", async () => {+ snapshot = { ...base, platform: "linux", provider: "openshell", effective_provider: "openshell", providers: [{ name: "direct", usable: true, why: "", state: "ready" }, { name: "openshell", usable: true, why: "", state: "ready" }] };+ setupState = {+ status: "running",+ rows: [+ { ...readiness.steps[0], state: "ok" },+ { ...readiness.steps[1], ok: true, state: "ok" },+ { ...readiness.steps[2], state: "fixing" },+ ],+ progress: { layers_total: 8, layers_done: 3, last_line: "x: Downloading", elapsed_s: 75 },+ error: "",+ elapsed_s: 75,+ };+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-readiness");+ await screen.findByTestId("sandbox-download-progress");+ expect(screen.getByText("Downloading the base image: 3 of 8 layers, 1 min 15 s elapsed")).toBeTruthy();+ expect(screen.getByTestId("sandbox-setup-cancel")).toBeTruthy();+ expect(screen.getByTestId("sandbox-readiness-row-image").getAttribute("data-state")).toBe("fixing");+ cleanup();++ setupState = {+ status: "needs_you",+ rows: [+ { ...readiness.steps[0], state: "ok" },+ { ...readiness.steps[1], state: "needs_you" },+ { ...readiness.steps[2], state: "pending" },+ ],+ progress: null,+ error: "",+ elapsed_s: 3,+ };+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-setup-needs_you");+ expect(screen.getByText(/Run the command shown, then check again/)).toBeTruthy();+ expect(screen.getByTestId("sandbox-readiness-row-openshell").getAttribute("data-state")).toBe("needs_you");+ expect(screen.getByTestId("sandbox-setup-start").textContent).toBe("Check again");+ fireEvent.click(screen.getByTestId("sandbox-setup-start"));+ await waitFor(() => expect(startSandboxSetup).toHaveBeenCalled());});- it("adds an entry through the editor and removes one", async () => {+ it("on a Windows host the switch is disabled with the WSL hint", async () => {+ snapshot = { ...base, platform: "win32", providers: [{ name: "direct", usable: true, why: "", state: "ready" }, { name: "openshell", usable: false, why: "OpenShell is not installed", state: "unavailable" }] };render(<SettingsView initialTab="sandbox" />);await screen.findByTestId("sandbox-section");+ expect((screen.getByTestId("sandbox-switch") as HTMLInputElement).disabled).toBe(true);+ expect(screen.getByTestId("sandbox-windows-hint").textContent).toMatch(/WSL Ubuntu/);+ });++ it("adds a credential through the editor and removes one (when the sandbox is on)", async () => {+ snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-credentials-section");fireEvent.click(screen.getByTestId("sandbox-credential-add"));const editor = screen.getByTestId("sandbox-credential-editor");const inputs = editor.querySelectorAll("input, textarea");@@ -112,7 +200,7 @@ describe("Settings ▸ Sandbox", () => {await waitFor(() =>expect(setSandboxSettings).toHaveBeenLastCalledWith({credentials: [- ...snapshot.credentials,+ ...base.credentials,{ name: "npm-token", title: "npm token", path: "~/.npmrc", hosts: ["registry.npmjs.org:443"], does: undefined, enabled: true },],}),diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex db316e7f..c5964b58 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -20,6 +20,10 @@ import {type Machine,type MeInfo,getSandboxSettings,+ getSandboxReadiness,+ getSandboxSetup,+ startSandboxSetup,+ cancelSandboxSetup,getSettings,getTrustedWorkspaces,setSandboxSettings,@@ -37,6 +41,10 @@ import {type PdfSettings,type SandboxCredentialEntry,type SandboxSettings,+ type SandboxReadiness,+ type SandboxReadinessStep,+ type SandboxSetupState,+ type SandboxSetupRowState,type WorkspaceCommandTrust,} from "../api";import {@@ -720,15 +728,25 @@ function PersonasSection({// in, and the way out (moved here from the Machines page's inline bar). On// desktop and self-hosted browsers it is the optional OpenWorker Cloud// sign-in — the same one the sidebar's account menu offers, given a full page.-// Settings ▸ Sandbox (UX-051 A, design doc rulings 17, 29, 32): machine-level provider,-// network allow list, and the credential files an agent may be given. Reads and writes the-// machine's config.toml through /v1/settings/sandbox; nothing here is per project.+// Settings ▸ Sandbox (UX-051 A, OPE-207): one switch — run agents in a sandbox, or not —+// and, when it is on, the provider, a readiness checklist with a guided setup, and the+// sub-settings that only mean something behind a wall (network allow list, shared+// credentials). Reads and writes the machine's config.toml through /v1/settings/sandbox;+// nothing here is per project. The switch never lowers protection on its own: when the+// sandbox cannot be used, sessions are refused with the reason, and the checklist says+// what to do.+const SANDBOX_PROVIDERS = ["openshell", "seatbelt"] as const;+function SandboxSection({ machine }: { machine?: Machine | null }) {const { t } = useTranslation();const mid = machine?.id ?? null;const [cfg, setCfg] = useState<SandboxSettings | null>(null);const [error, setError] = useState<string>("");const [editing, setEditing] = useState<string | null>(null); // credential name being edited, "" = new+ const [readiness, setReadiness] = useState<SandboxReadiness | null>(null);+ const [setup, setSetup] = useState<SandboxSetupState | null>(null);+ const [copied, setCopied] = useState<string>("");+ const notifiedRef = useRef(false);useEffect(() => {getSandboxSettings(mid).then(setCfg).catch(() => setCfg(null));@@ -744,13 +762,88 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {setCfg(res as SandboxSettings);};+ // The switch reads the machine's choice; a headless machine's default rule (OpenShell+ // when installed) counts as on. `provider` is empty for "no choice made".+ const chosenName = cfg ? cfg.provider || cfg.effective_provider || "" : "";+ const enabled = (SANDBOX_PROVIDERS as readonly string[]).includes(chosenName);+ const providerName = enabled ? chosenName : "";+ const windowsHost = cfg?.platform === "win32";++ // The checklist is only about OpenShell (Seatbelt needs no setup). Loaded when the+ // switch is on, and again after a setup run.+ const loadReadiness = () => {+ if (!cfg || providerName !== "openshell") return;+ setReadiness(null);+ getSandboxReadiness(mid).then(setReadiness).catch(() => setReadiness({ platform: cfg.platform, supported: false, steps: [], all_ok: false }));+ };+ useEffect(loadReadiness, [mid, providerName, cfg?.platform]); // eslint-disable-line react-hooks/exhaustive-deps++ // A setup job may be running from before (the page was closed and reopened): adopt it.+ useEffect(() => {+ if (providerName !== "openshell") return;+ getSandboxSetup(mid).then((s) => setSetup(s.status === "idle" ? null : s)).catch(() => {});+ }, [mid, providerName]);++ // Poll the job while it runs; on the way out, reload the checklist and the settings+ // (the job may have written the config line) and say so once.+ useEffect(() => {+ if (!setup || setup.status !== "running") return;+ const timer = window.setInterval(() => {+ getSandboxSetup(mid)+ .then((s) => {+ setSetup(s);+ if (s.status !== "running") {+ loadReadiness();+ getSandboxSettings(mid).then(setCfg).catch(() => {});+ if (s.status === "done" && !notifiedRef.current) {+ notifiedRef.current = true;+ try {+ if ("Notification" in window && Notification.permission === "granted") {+ new Notification(t("settingsx.sandbox.notify_title"), { body: t("settingsx.sandbox.notify_body") });+ }+ } catch {+ /* notifications are a courtesy */+ }+ }+ }+ })+ .catch(() => {});+ }, 1000);+ return () => window.clearInterval(timer);+ }, [setup?.status, mid]); // eslint-disable-line react-hooks/exhaustive-deps++ const startSetup = async () => {+ notifiedRef.current = false;+ try {+ if ("Notification" in window && Notification.permission === "default") Notification.requestPermission().catch(() => {});+ } catch {+ /* ignore */+ }+ const s = await startSandboxSetup(mid).catch(() => null);+ if (s) setSetup(s);+ };+ const cancelSetup = async () => {+ const s = await cancelSandboxSetup(mid).catch(() => null);+ if (s) setSetup(s);+ };+ const copy = (text: string) => {+ navigator.clipboard?.writeText(text).then(() => {+ setCopied(text);+ window.setTimeout(() => setCopied(""), 1500);+ }).catch(() => {});+ };+if (!cfg) return null;const providerNames: Record<string, [string, string]> = {- direct: [t("settingsx.sandbox.provider_direct"), t("settingsx.sandbox.provider_direct_desc")],seatbelt: [t("settingsx.sandbox.provider_seatbelt"), t("settingsx.sandbox.provider_seatbelt_desc")],openshell: [t("settingsx.sandbox.provider_openshell"), t("settingsx.sandbox.provider_openshell_desc")],};- const chosen = cfg.provider || cfg.effective_provider || "direct";+ const available = cfg.providers.filter((p) => p.name !== "direct" && (p.name !== "seatbelt" || cfg.platform === "darwin"));+ // Switching on picks the provider that needs no setup where there is one (a Mac's+ // Seatbelt), otherwise OpenShell; the user can change it on the line below.+ const defaultProvider = cfg.platform === "darwin" && available.some((p) => p.name === "seatbelt") ? "seatbelt" : "openshell";+ const providerRow = cfg.providers.find((p) => p.name === providerName);+ const needsDownload = providerRow?.state === "needs_download";const shipped = (name: string, key: "title" | "does", fallback?: string) => {const k = `settingsx.sandbox.${key}_${name}`;const v = t(k);@@ -758,6 +851,12 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {};const updateCredentials = (rows: SandboxCredentialEntry[]) => save({ credentials: rows });+ // The checklist to show: the live job's rows while it runs or just ran, else readiness.+ const rows: (SandboxReadinessStep & { state?: SandboxSetupRowState })[] = setup && setup.status !== "idle" ? setup.rows : readiness?.steps ?? [];+ const missing = rows.filter((r) => !r.ok && r.state !== "fixed").length;+ const running = setup?.status === "running";+ const elapsed = (s: number) => (s >= 60 ? `${Math.floor(s / 60)} min ${s % 60} s` : `${s} s`);+return (<section data-testid="sandbox-section"><PanelHead@@ -766,111 +865,244 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {/>{error ? <div className="mb-3 text-meta text-danger">{error}</div> : null}- <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.run_in")}</div>- <div className={CARD + " mb-1 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.run_in")}>- {cfg.providers- .filter((p) => p.name !== "seatbelt" || cfg.platform === "darwin")- .map((p) => {- const [label, desc] = providerNames[p.name] ?? [p.name, ""];- const active = chosen === p.name;- // OpenShell is installed and running but its base image is not downloaded yet:- // the provider can be chosen (nothing else is missing), but the first session- // cannot start until the download is done, so say that here instead of "ready".- const needsDownload = p.state === "needs_download";- return (- <label key={p.name} className="flex items-start gap-3 px-4 py-3 cursor-pointer">- <input- type="radio"- name="sandbox-provider"- className="mt-1"- checked={active}- disabled={!p.usable && !active && !needsDownload}- onChange={() => save({ provider: p.name === "direct" && !cfg.provider ? "" : p.name })}- data-testid={`sandbox-provider-${p.name}`}- />- <span className="flex-1 min-w-0">- <span className="block text-ui text-ink">{label}</span>- <span className="block text-meta text-muted">{desc}</span>- {needsDownload ? (- <span className="block text-meta text-warnInk" data-testid={`sandbox-provider-${p.name}-hint`}>- {t("settingsx.sandbox.needs_download_hint")}- </span>- ) : null}- </span>- <span className={"text-meta shrink-0 " + (needsDownload ? "text-warnInk" : p.usable ? (active ? "text-success" : "text-muted") : "text-muted")} title={p.why || undefined}>- {p.name === "direct" && !cfg.provider- ? t("settingsx.sandbox.status_default")- : needsDownload- ? t("settingsx.sandbox.status_needs_download")- : p.usable- ? t("settingsx.sandbox.status_ready")- : t("settingsx.sandbox.status_unavailable")}- </span>- </label>- );- })}- </div>- {cfg.refused ? <div className="mb-4 text-meta text-danger">{t("settingsx.sandbox.refused", { why: cfg.refused })}</div> : <div className="mb-4" />}-- <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.network")}</div>- <div className={CARD + " divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.network")}>- {cfg.network_profiles.map((np) => (- <label key={np.name} className="flex items-start gap-3 px-4 py-3 cursor-pointer">- <input- type="radio"- name="sandbox-network"- className="mt-1"- checked={cfg.network_profile === np.name}- onChange={() => save({ network_profile: np.name })}- data-testid={`sandbox-network-${np.name}`}- />- <span className="flex-1 min-w-0">- <span className="block text-ui text-ink">{t(`settingsx.sandbox.profile_${np.name}`)}</span>- <span className="block text-meta text-muted">{t(`settingsx.sandbox.profile_${np.name}_desc`)}</span>+ <div className={CARD + " mb-4"}>+ <label className={"flex items-start gap-3 px-4 py-3 " + (windowsHost ? "opacity-60" : "cursor-pointer")}>+ <input+ type="checkbox"+ className="mt-1"+ checked={enabled}+ disabled={windowsHost}+ onChange={(e) => save({ provider: e.target.checked ? defaultProvider : "" })}+ data-testid="sandbox-switch"+ />+ <span className="flex-1 min-w-0">+ <span className="block text-ui text-ink">{t("settingsx.sandbox.switch")}</span>+ <span className="block text-meta text-muted">+ {enabled ? t("settingsx.sandbox.switch_on_desc") : t("settingsx.sandbox.switch_off_desc")}+ {!enabled && !windowsHost ? <span className="text-faint"> ({t("settingsx.sandbox.current")})</span> : null}</span>- </label>- ))}- </div>- <div className={FIELD_HELP + " mb-4"}>{t("settingsx.sandbox.network_help")}</div>+ {windowsHost ? (+ <span className="block text-meta text-warnInk" data-testid="sandbox-windows-hint">+ {t("settingsx.sandbox.windows_hint")}+ </span>+ ) : null}+ </span>+ </label>- <div className="flex items-center mb-2">- <div className={FIELD_LABEL}>{t("settingsx.sandbox.credentials")}</div>- <button className="ml-auto text-ui text-accent" onClick={() => setEditing("")} data-testid="sandbox-credential-add">- {t("settingsx.sandbox.add")}- </button>+ {enabled ? (+ <div className="border-t border-line px-4 py-3" data-testid="sandbox-provider-block">+ <div className="flex items-start gap-3">+ <span className="flex-1 min-w-0">+ <span className="block text-ui text-ink">+ {t("settingsx.sandbox.provider_label")}:{" "}+ {available.length > 1 ? (+ <select+ className="text-ui bg-transparent border border-line rounded-md px-1.5 py-0.5"+ value={providerName}+ onChange={(e) => save({ provider: e.target.value })}+ data-testid="sandbox-provider-select"+ >+ {available.map((p) => (+ <option key={p.name} value={p.name}>+ {providerNames[p.name]?.[0] ?? p.name}+ </option>+ ))}+ </select>+ ) : (+ <span data-testid={`sandbox-provider-${providerName}`}>{providerNames[providerName]?.[0] ?? providerName}</span>+ )}+ </span>+ <span className="block text-meta text-muted">{providerNames[providerName]?.[1] ?? ""}</span>+ {needsDownload ? (+ <span className="block text-meta text-warnInk" data-testid={`sandbox-provider-${providerName}-hint`}>+ {t("settingsx.sandbox.needs_download_hint")}+ </span>+ ) : null}+ </span>+ <span+ className={"text-meta shrink-0 " + (needsDownload ? "text-warnInk" : providerRow?.usable ? "text-success" : "text-muted")}+ title={providerRow?.why || undefined}+ data-testid="sandbox-provider-status"+ >+ {needsDownload+ ? t("settingsx.sandbox.status_needs_download")+ : providerRow?.usable+ ? t("settingsx.sandbox.status_ready")+ : t("settingsx.sandbox.status_unavailable")}+ </span>+ </div>+ {providerRow && !providerRow.usable && providerRow.why && !needsDownload ? (+ <div className={FIELD_HELP + " text-warnInk"}>{t("settingsx.sandbox.refused", { why: providerRow.why })}</div>+ ) : null}+ </div>+ ) : null}</div>- <div className={CARD + " divide-y divide-line"}>- {cfg.credentials.map((c) => (- <div key={c.name} className="flex items-start gap-3 px-4 py-3" data-testid={`sandbox-credential-${c.name}`}>- <input- type="checkbox"- className="mt-1"- checked={c.enabled}- onChange={(e) => updateCredentials(cfg.credentials.map((x) => (x.name === c.name ? { ...x, enabled: e.target.checked } : x)))}- aria-label={c.title || shipped(c.name, "title", c.name)}- />++ {enabled && providerName === "openshell" ? (+ <div className={CARD + " mb-4"} data-testid="sandbox-readiness">+ <div className="flex items-center gap-3 px-4 py-3 border-b border-line"><span className="flex-1 min-w-0">- <span className="block text-ui text-ink">- {c.title || shipped(c.name, "title", c.name)}{" "}- <code className="text-meta text-muted font-mono">{c.path}</code>- </span>- <span className="block text-meta text-muted">- {c.does ? c.does : shipped(c.name, "does")}{" "}- {c.hosts && c.hosts.length ? <span className="text-faint">{t("settingsx.sandbox.also_allows", { hosts: c.hosts.join(", ") })}</span> : null}+ <span className="block text-ui text-ink">{t("settingsx.sandbox.readiness")}</span>+ <span className={"block text-meta " + (rows.length && missing === 0 ? "text-success" : "text-muted")}>+ {!readiness && !setup+ ? t("settingsx.sandbox.readiness_loading")+ : missing === 0+ ? t("settingsx.sandbox.readiness_all_ok")+ : missing === 1+ ? t("settingsx.sandbox.readiness_missing_one")+ : t("settingsx.sandbox.readiness_missing", { count: missing })}</span></span>- <span className="text-meta text-muted shrink-0 whitespace-nowrap">- <button className="hover:text-ink" onClick={() => setEditing(c.name)}>{t("settingsx.sandbox.edit")}</button>- <span className="mx-1.5 text-faint">·</span>- <button className="hover:text-ink" onClick={() => updateCredentials(cfg.credentials.filter((x) => x.name !== c.name))}>- {t("settingsx.sandbox.remove")}+ {running ? (+ <button className={BTN_BORDERED} onClick={cancelSetup} data-testid="sandbox-setup-cancel">+ {t("settingsx.sandbox.setup_cancel")}</button>- </span>+ ) : (+ <button+ className={BTN_ACCENT}+ disabled={!rows.length || (missing === 0 && setup?.status !== "needs_you" && setup?.status !== "failed")}+ onClick={startSetup}+ data-testid="sandbox-setup-start"+ >+ {setup && setup.status !== "idle" ? t("settingsx.sandbox.setup_again") : t("settingsx.sandbox.setup_start")}+ </button>+ )}</div>- ))}- </div>- <div className={FIELD_HELP}>{t("settingsx.sandbox.credentials_help")}</div>- {cfg.platform === "darwin" ? <div className={FIELD_HELP}>{t("settingsx.sandbox.keychain_note")}</div> : null}+ <ul className="divide-y divide-line">+ {rows.map((r) => {+ const state: SandboxSetupRowState = r.state ?? (r.ok ? "ok" : "pending");+ const good = state === "ok" || state === "fixed";+ const showHint = !good && r.hint;+ return (+ <li key={r.key} className="px-4 py-2.5" data-testid={`sandbox-readiness-row-${r.key}`} data-state={state}>+ <div className="flex items-start gap-2">+ <span className={"shrink-0 w-4 " + (good ? "text-success" : state === "fixing" ? "text-muted" : "text-warnInk")} aria-hidden>+ {good ? "✓" : state === "fixing" ? "⟳" : "✗"}+ </span>+ <span className="flex-1 min-w-0 text-ui text-ink">{r.what}</span>+ <span className="text-meta text-muted shrink-0">{t(`settingsx.sandbox.step_${state}`)}</span>+ </div>+ {r.key === "image" && running && state === "fixing" && setup?.progress ? (+ <div className="mt-1.5 ml-6" data-testid="sandbox-download-progress">+ <div className="h-1.5 rounded bg-line overflow-hidden">+ <div+ className="h-full bg-accent transition-all"+ style={{ width: setup.progress.layers_total ? `${Math.round((100 * setup.progress.layers_done) / setup.progress.layers_total)}%` : "5%" }}+ />+ </div>+ <div className="text-meta text-muted mt-1">+ {setup.progress.layers_total+ ? t("settingsx.sandbox.download_progress", { done: setup.progress.layers_done, total: setup.progress.layers_total, elapsed: elapsed(setup.progress.elapsed_s) })+ : t("settingsx.sandbox.download_progress_unknown", { elapsed: elapsed(setup.progress.elapsed_s) })}+ </div>+ </div>+ ) : null}+ {showHint ? (+ <div className="mt-1 ml-6 flex items-start gap-2">+ <code className="text-meta font-mono text-muted break-all flex-1 min-w-0">{r.hint}</code>+ <button className="text-meta text-accent shrink-0" onClick={() => copy(r.hint)}>+ {copied === r.hint ? t("settingsx.sandbox.copied") : t("settingsx.sandbox.copy")}+ </button>+ </div>+ ) : null}+ </li>+ );+ })}+ </ul>+ {setup && setup.status !== "idle" && setup.status !== "running" ? (+ <div+ className={"px-4 py-3 border-t border-line text-ui " + (setup.status === "done" ? "text-success" : "text-warnInk")}+ data-testid={`sandbox-setup-${setup.status}`}+ >+ {setup.status === "done"+ ? t("settingsx.sandbox.setup_done", { provider: providerNames.openshell[0] })+ : setup.status === "needs_you"+ ? t("settingsx.sandbox.setup_needs_you")+ : setup.status === "cancelled"+ ? t("settingsx.sandbox.setup_cancelled")+ : t("settingsx.sandbox.setup_failed", { error: setup.error })}+ </div>+ ) : null}+ <div className={FIELD_HELP + " px-4 pb-3"}>{t("settingsx.sandbox.setup_never_root")}</div>+ </div>+ ) : null}++ {enabled ? (+ <>+ <details className={CARD + " mb-4"} data-testid="sandbox-network-section">+ <summary className="px-4 py-3 cursor-pointer text-ui text-ink">{t("settingsx.sandbox.network")}</summary>+ <div className="border-t border-line divide-y divide-line" role="radiogroup" aria-label={t("settingsx.sandbox.network")}>+ {cfg.network_profiles.map((np) => (+ <label key={np.name} className="flex items-start gap-3 px-4 py-3 cursor-pointer">+ <input+ type="radio"+ name="sandbox-network"+ className="mt-1"+ checked={cfg.network_profile === np.name}+ onChange={() => save({ network_profile: np.name })}+ data-testid={`sandbox-network-${np.name}`}+ />+ <span className="flex-1 min-w-0">+ <span className="block text-ui text-ink">{t(`settingsx.sandbox.profile_${np.name}`)}</span>+ <span className="block text-meta text-muted">{t(`settingsx.sandbox.profile_${np.name}_desc`)}</span>+ </span>+ </label>+ ))}+ </div>+ <div className={FIELD_HELP + " px-4 pb-3"}>{t("settingsx.sandbox.network_help")}</div>+ </details>++ <details className={CARD + " mb-4"} data-testid="sandbox-credentials-section">+ <summary className="px-4 py-3 cursor-pointer text-ui text-ink flex items-center">+ <span>{t("settingsx.sandbox.credentials")}</span>+ <button+ className="ml-auto text-ui text-accent"+ onClick={(e) => {+ e.preventDefault();+ setEditing("");+ }}+ data-testid="sandbox-credential-add"+ >+ {t("settingsx.sandbox.add")}+ </button>+ </summary>+ <div className="border-t border-line divide-y divide-line">+ {cfg.credentials.map((c) => (+ <div key={c.name} className="flex items-start gap-3 px-4 py-3" data-testid={`sandbox-credential-${c.name}`}>+ <input+ type="checkbox"+ className="mt-1"+ checked={c.enabled}+ onChange={(e) => updateCredentials(cfg.credentials.map((x) => (x.name === c.name ? { ...x, enabled: e.target.checked } : x)))}+ aria-label={c.title || shipped(c.name, "title", c.name)}+ />+ <span className="flex-1 min-w-0">+ <span className="block text-ui text-ink">+ {c.title || shipped(c.name, "title", c.name)}{" "}+ <code className="text-meta text-muted font-mono">{c.path}</code>+ </span>+ <span className="block text-meta text-muted">+ {c.does ? c.does : shipped(c.name, "does")}{" "}+ {c.hosts && c.hosts.length ? <span className="text-faint">{t("settingsx.sandbox.also_allows", { hosts: c.hosts.join(", ") })}</span> : null}+ </span>+ </span>+ <span className="text-meta text-muted shrink-0 whitespace-nowrap">+ <button className="hover:text-ink" onClick={() => setEditing(c.name)}>{t("settingsx.sandbox.edit")}</button>+ <span className="mx-1.5 text-faint">·</span>+ <button className="hover:text-ink" onClick={() => updateCredentials(cfg.credentials.filter((x) => x.name !== c.name))}>+ {t("settingsx.sandbox.remove")}+ </button>+ </span>+ </div>+ ))}+ </div>+ <div className={FIELD_HELP + " px-4"}>{t("settingsx.sandbox.credentials_help")}</div>+ {cfg.platform === "darwin" ? <div className={FIELD_HELP + " px-4"}>{t("settingsx.sandbox.keychain_note")}</div> : null}+ <div className="pb-3" />+ </details>+ </>+ ) : null}+<div className={FIELD_HELP + " mt-3"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>{editing !== null ? (diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 68029c3a..a1744e37 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2270,8 +2270,40 @@},"sandbox": {"title": "Sandbox",- "sub": "Where agents run their commands and file tools on this Mac. Applies to every session on this machine; a project cannot change it.",+ "sub": "Where agents run their commands and file tools on this machine. Applies to every session here; a project cannot change it.","sub_machine": "On ⌂ {{name}} — where its agents run their commands and file tools. Applies to every session on that machine; a project cannot change it.",+ "switch": "Run agents in a sandbox",+ "switch_off_desc": "Off: commands run as you, with no limits.",+ "switch_on_desc": "On: commands and file tools run behind a wall that holds only the session's folders and the network allow list.",+ "current": "current",+ "windows_hint": "Sandboxing needs a Linux machine. Add one under Settings ▸ Machines; a WSL Ubuntu on this PC works.",+ "provider_label": "Sandbox",+ "readiness": "Readiness",+ "readiness_all_ok": "All requirements met",+ "readiness_missing_one": "1 requirement missing",+ "readiness_missing": "{{count}} requirements missing",+ "readiness_loading": "Checking this machine…",+ "setup_start": "Set up sandbox",+ "setup_again": "Check again",+ "setup_cancel": "Cancel",+ "setup_running": "Setting up…",+ "setup_done": "Sandbox ready. New sessions will run in {{provider}}.",+ "setup_needs_you": "One or more steps need you. Run the command shown, then check again.",+ "setup_failed": "Setup stopped: {{error}}",+ "setup_cancelled": "Setup cancelled.",+ "setup_never_root": "Steps that need an administrator are shown as a command for you to run; the app never runs anything as root, and never turns the sandbox off on its own.",+ "step_pending": "waiting",+ "step_fixing": "working…",+ "step_fixed": "done",+ "step_ok": "ok",+ "step_needs_you": "needs you",+ "step_failed": "failed",+ "download_progress": "Downloading the base image: {{done}} of {{total}} layers, {{elapsed}} elapsed",+ "download_progress_unknown": "Downloading the base image… {{elapsed}} elapsed",+ "copy": "Copy",+ "copied": "Copied",+ "notify_title": "Sandbox ready",+ "notify_body": "You can start a new session now; its commands will run in the sandbox.","run_in": "Run agents in","provider_direct": "No sandbox","provider_direct_desc": "Commands run as you, with no limits. Fastest. The default until you choose otherwise.",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 68198d27..0959104d 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2230,9 +2230,41 @@},"sandbox": {"title": "沙箱",- "sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。",+ "sub": "同事在这台机器上运行命令和文件工具的位置。适用于这里的每个会话;项目无法更改。","sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话;项目无法更改。","run_in": "在哪里运行同事",+ "switch": "在沙箱中运行同事",+ "switch_off_desc": "关闭:命令以你的身份运行,没有限制。",+ "switch_on_desc": "开启:命令和文件工具在一道墙后运行,墙内只有会话的文件夹和网络允许列表。",+ "current": "当前",+ "windows_hint": "沙箱需要一台 Linux 机器。请在 设置 ▸ 机器 中添加一台;这台电脑上的 WSL Ubuntu 即可。",+ "provider_label": "沙箱",+ "readiness": "就绪情况",+ "readiness_all_ok": "所有要求已满足",+ "readiness_missing_one": "缺少 1 项要求",+ "readiness_missing": "缺少 {{count}} 项要求",+ "readiness_loading": "正在检查这台机器…",+ "setup_start": "设置沙箱",+ "setup_again": "重新检查",+ "setup_cancel": "取消",+ "setup_running": "正在设置…",+ "setup_done": "沙箱已就绪。新会话将在 {{provider}} 中运行。",+ "setup_needs_you": "有一步或多步需要你操作。请运行显示的命令,然后重新检查。",+ "setup_failed": "设置已停止:{{error}}",+ "setup_cancelled": "设置已取消。",+ "setup_never_root": "需要管理员权限的步骤会以命令的形式显示,由你来运行;应用绝不会以 root 身份运行任何东西,也绝不会自行关闭沙箱。",+ "step_pending": "等待中",+ "step_fixing": "处理中…",+ "step_fixed": "已完成",+ "step_ok": "正常",+ "step_needs_you": "需要你",+ "step_failed": "失败",+ "download_progress": "正在下载基础镜像:{{total}} 层中已完成 {{done}} 层,已用时 {{elapsed}}",+ "download_progress_unknown": "正在下载基础镜像… 已用时 {{elapsed}}",+ "copy": "复制",+ "copied": "已复制",+ "notify_title": "沙箱已就绪",+ "notify_body": "现在可以开始新会话了;其命令将在沙箱中运行。","provider_direct": "不使用沙箱","provider_direct_desc": "命令以你的身份运行,没有限制。最快。在你另作选择前为默认。","provider_seatbelt": "macOS 沙箱",diff --git a/tests/test_sandbox_setup_job.py b/tests/test_sandbox_setup_job.pynew file mode 100644index 00000000..f955f69b--- /dev/null+++ b/tests/test_sandbox_setup_job.py@@ -0,0 +1,174 @@+"""Settings ▸ Sandbox readiness and the guided setup job (OPE-207).++The same steps serve the terminal (`openworker machine sandbox status|setup`) and the+page: `setup_cmd.steps()` is the checklist, `SetupJob` walks it, fixing what the app may+fix on its own and handing the rest over as commands. Never as root, never lowering+protection.+"""++from __future__ import annotations++import threading+import time++import pytest+from fastapi.testclient import TestClient++from coworker.sandbox import setup_cmd, setup_job+from coworker.sandbox.setup_cmd import Step+++def _wait(job: setup_job.SetupJob, seconds: float = 5.0) -> dict:+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ state = job.state()+ if state["status"] != "running":+ return state+ time.sleep(0.02)+ raise AssertionError(f"job still running: {job.state()}")+++def _steps(*rows: tuple[str, bool]) -> list[Step]:+ return [Step(key, setup_cmd.ROWS[key], ok, "" if ok else f"fix {key}", fixable=key in setup_cmd.FIXABLE) for key, ok in rows]+++def test_steps_carry_keys_and_say_which_the_app_may_fix(monkeypatch):+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: None) # no docker, no openshell+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")+ monkeypatch.setattr(setup_cmd, "openshell_problem", lambda fresh=False: "OpenShell is not installed")+ rows = {s.key: s for s in setup_cmd.steps()}+ assert not rows["docker"].ok and not rows["docker"].fixable+ assert not rows["openshell"].ok and not rows["openshell"].fixable+ assert rows["bind_mounts"].fixable and rows["config"].fixable+ assert "linger" not in rows and "landlock" not in rows # Linux-only rows+ assert "image" not in rows # no gateway to ask+ assert [(w, ok) for w, ok, _ in setup_cmd.checks()] == [(s.what, s.ok) for s in setup_cmd.steps()]+++def test_the_job_fixes_what_it_may_and_stops_at_what_needs_an_administrator(monkeypatch):+ fixed: list[str] = []+ monkeypatch.setattr(setup_cmd, "apply_bind_mounts", lambda: fixed.append("bind_mounts") or None)+ monkeypatch.setattr(setup_cmd, "apply_config", lambda: fixed.append("config"))+ calls = {"n": 0}++ def steps():+ calls["n"] += 1+ after = calls["n"] > 1 # the second read (the final re-check) sees the fixes+ return _steps(("docker", True), ("openshell", True), ("bind_mounts", after), ("gateway", True), ("grpcio", True), ("config", after))++ job = setup_job.SetupJob(steps)+ job.start()+ state = _wait(job)+ assert state["status"] == "done" and fixed == ["bind_mounts", "config"]+ by_key = {r["key"]: r for r in state["rows"]}+ assert by_key["bind_mounts"]["state"] == "fixed" and by_key["config"]["state"] == "fixed"+ assert by_key["docker"]["state"] == "ok"++ # An administrator step in the way: the job hands it over and does not go past it.+ fixed.clear()+ job = setup_job.SetupJob(lambda: _steps(("docker", True), ("openshell", False), ("bind_mounts", False), ("config", False)))+ job.start()+ state = _wait(job)+ assert state["status"] == "needs_you" and fixed == [] # nothing after the handover ran+ by_key = {r["key"]: r for r in state["rows"]}+ assert by_key["openshell"]["state"] == "needs_you" and by_key["openshell"]["hint"] == "fix openshell"+ assert by_key["bind_mounts"]["state"] == "pending"+++def test_the_download_reports_progress_and_can_be_cancelled(monkeypatch):+ def slow_pull(on_progress, cancel):+ p = setup_cmd.PullProgress(layers_total=8)+ for i in range(8):+ if cancel.is_set():+ return "download cancelled"+ p.layers_done = i+ p.last_line = f"layer{i}: Downloading"+ on_progress(p)+ time.sleep(0.02)+ return None++ monkeypatch.setattr(setup_cmd, "pull_image", slow_pull)+ job = setup_job.SetupJob(lambda: _steps(("docker", True), ("openshell", True), ("gateway", True), ("image", False)))+ job.start()+ time.sleep(0.05)+ mid = job.state()+ assert mid["status"] == "running" and mid["progress"]["layers_total"] == 8 and mid["progress"]["layers_done"] >= 1+ job.cancel()+ state = _wait(job)+ assert state["status"] == "cancelled"+ assert {r["key"]: r["state"] for r in state["rows"]}["image"] == "failed"++ # Uncancelled, with the final re-check reporting the image present: done.+ monkeypatch.setattr(setup_cmd, "pull_image", lambda on_progress, cancel: None)+ reads = {"n": 0}++ def steps():+ reads["n"] += 1+ return _steps(("docker", True), ("openshell", True), ("gateway", True), ("image", reads["n"] > 1))++ job = setup_job.SetupJob(steps)+ job.start()+ assert _wait(job)["status"] == "done"+++def test_a_refused_linger_is_handed_over_and_the_walk_goes_on(monkeypatch):+ monkeypatch.setattr(setup_job.sys, "platform", "linux")+ monkeypatch.setattr(setup_cmd, "enable_linger", lambda: "sudo loginctl enable-linger sam")+ monkeypatch.setattr(setup_cmd, "apply_config", lambda: None)+ reads = {"n": 0}++ def steps():+ reads["n"] += 1+ return _steps(("docker", True), ("openshell", True), ("linger", False), ("config", reads["n"] > 1))++ job = setup_job.SetupJob(steps)+ job.start()+ state = _wait(job)+ by_key = {r["key"]: r for r in state["rows"]}+ assert by_key["linger"]["state"] == "needs_you" and "sudo loginctl" in by_key["linger"]["hint"]+ assert by_key["config"]["state"] == "fixed" # the walk went on past the handover+ assert state["status"] == "needs_you" # not done: one row still needs the user+++def test_pull_image_parses_docker_output_and_streams_progress(monkeypatch):+ lines = ["c6cd9b8593e5: Pulling fs layer\n", "a6c5096124c1: Pulling fs layer\n", "c6cd9b8593e5: Downloading\n", "c6cd9b8593e5: Pull complete\n", "a6c5096124c1: Pull complete\n", "Digest: sha256:abc\n", "Status: Downloaded newer image\n"]++ class Proc:+ stdout = iter(lines)++ def wait(self):+ return 0++ monkeypatch.setattr(setup_cmd.openshell, "image_tool", lambda: "docker")+ monkeypatch.setattr(setup_cmd.openshell, "sandbox_image", lambda: "img")+ argv: list[list[str]] = []+ monkeypatch.setattr(setup_cmd.subprocess, "Popen", lambda a, **kw: argv.append(a) or Proc())+ seen: list[tuple[int, int]] = []+ assert setup_cmd.pull_image(lambda p: seen.append((p.layers_done, p.layers_total)), threading.Event()) is None+ assert argv == [["docker", "pull", "img"]]+ assert seen[-1] == (2, 2) and (0, 2) in seen+++def test_the_readiness_endpoint_and_the_job_endpoints(tmp_path, monkeypatch):+ from coworker.sandbox import settings+ from coworker.server import create_app+ from tests.test_persona_connections import _mgr++ monkeypatch.setattr(setup_cmd, "steps", lambda: _steps(("docker", True), ("openshell", False)))+ monkeypatch.setattr(settings.sys, "platform", "linux")+ monkeypatch.setattr(setup_job, "_job", None)+ client = TestClient(create_app(_mgr(tmp_path, monkeypatch)))+ ready = client.get("/v1/settings/sandbox/readiness").json()+ assert ready["supported"] and not ready["all_ok"]+ assert [(s["key"], s["ok"], s["fixable"]) for s in ready["steps"]] == [("docker", True, False), ("openshell", False, False)]+ assert client.get("/v1/settings/sandbox/setup").json()["status"] == "idle"+ started = client.post("/v1/settings/sandbox/setup").json()+ assert started["status"] in ("running", "needs_you")+ deadline = time.monotonic() + 5+ while client.get("/v1/settings/sandbox/setup").json()["status"] == "running" and time.monotonic() < deadline:+ time.sleep(0.02)+ final = client.get("/v1/settings/sandbox/setup").json()+ assert final["status"] == "needs_you" and final["rows"][1]["state"] == "needs_you"+ assert client.post("/v1/settings/sandbox/setup/cancel").json()["status"] == "needs_you" # nothing running: unchanged+ monkeypatch.setattr(settings.sys, "platform", "win32")+ assert client.get("/v1/settings/sandbox/readiness").json() == {"platform": "win32", "supported": False, "steps": [], "all_ok": False}