Skip to content
Python

OpenShell: check for the base image up front instead of hanging the first session on its download (OPE-205)

Devika Verma80c72eb58007
diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.py
index b3b3f45a..4379faaa 100644
--- a/coworker/sandbox/providers/openshell.py
+++ b/coworker/sandbox/providers/openshell.py
@@ -53,6 +53,27 @@ class OpenShellUnavailable(RuntimeError):
message says what to do; callers show it as it is."""
+class OpenShellImageMissing(OpenShellUnavailable):
+ """OpenShell works, but the base image is not on this machine yet. The first `sandbox
+ create` would pull it (about 5 GB) and, on a slow link, outlive our timeout: the session
+ would hang for ten minutes and then fail with no word about why (OPE-205). So the image
+ is checked up front, and the message says how to get it."""
+
+
+IMAGE_MISSING_PREFIX = "The sandbox base image is not downloaded yet"
+
+
+def is_image_problem(problem: Optional[str]) -> bool:
+ """Whether a preflight message is the missing-image one (the only problem that
+ `setup` can fix by downloading, and that Settings shows as "needs download")."""
+ return bool(problem) and str(problem).startswith(IMAGE_MISSING_PREFIX)
+
+
+def sandbox_image() -> str:
+ """The image a sandbox is created from: the pinned one, unless the environment says."""
+ return os.environ.get("OPENWORKER_SANDBOX_IMAGE") or DEFAULT_IMAGE
+
+
def _cli(*args: str, timeout: float = _CLI_TIMEOUT, check: bool = True) -> subprocess.CompletedProcess:
exe = shutil.which("openshell")
if exe is None:
@@ -75,9 +96,45 @@ def preflight() -> dict[str, Any]:
status = _cli("status", timeout=30, check=False)
if status.returncode != 0 or "Connected" not in status.stdout:
raise OpenShellUnavailable("The OpenShell gateway is not running or cannot be reached (`openshell status`). On a headless machine, check `systemctl --user status openshell-gateway` and `loginctl enable-linger`.")
+ if image_present() is False:
+ raise OpenShellImageMissing(
+ f"{IMAGE_MISSING_PREFIX} (about 5 GB, one time). Run `openworker machine sandbox setup`, "
+ f"or `docker pull {sandbox_image()}`, then start the session again."
+ )
return {"version": version}
+def active_driver() -> str:
+ """The gateway's compute driver ("docker", "podman", "kubernetes", "vm"), or "" when it
+ cannot be told. Read from `openshell gateway info -o json`."""
+ done = _cli("gateway", "info", "-o", "json", timeout=30, check=False)
+ if done.returncode != 0:
+ return ""
+ try:
+ drivers = json.loads(done.stdout).get("compute_drivers") or []
+ return str(drivers[0].get("name") or "") if drivers else ""
+ except (ValueError, AttributeError, IndexError, TypeError):
+ return ""
+
+
+def image_present(image: Optional[str] = None) -> Optional[bool]:
+ """Whether the base image is on this machine: True or False when the gateway uses the
+ Docker driver and the `docker` command is here to ask, None when it cannot be told
+ (another driver, such as the MicroVM one on a Mac, or no `docker` on PATH). The check is
+ keyed on the driver, not the operating system: the same image serves Linux, WSL and
+ macOS, and only the driver knows where images live."""
+ if active_driver() != "docker":
+ return None
+ docker = shutil.which("docker")
+ if docker is None:
+ return None
+ done = subprocess.run(
+ [docker, "image", "inspect", image or sandbox_image()],
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30,
+ )
+ return done.returncode == 0
+
+
def _gateway() -> tuple[str, Path]:
"""(host:port, folder with the client certificate) of the active gateway."""
home = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "openshell"
@@ -107,7 +164,7 @@ class OpenShellProvider:
self.roots = [{"path": str(Path(r["path"]).expanduser().resolve()), "writable": bool(r.get("writable"))} for r in roots]
self.cwd = str(Path(cwd).expanduser().resolve()) if cwd else self.roots[0]["path"]
self.profile = profile
- self.image = image or os.environ.get("OPENWORKER_SANDBOX_IMAGE") or DEFAULT_IMAGE
+ self.image = image or sandbox_image()
# A label value may hold letters, digits, '-', '_' and '.', and at most 63 characters.
self.label = "".join(c if c.isalnum() or c in "-_." else "-" for c in label)[:63].strip("-_.")
self.sandbox_name = f"ow-{uuid.uuid4().hex[:12]}"
diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.py
index 46c30e65..7a2f3203 100644
--- a/coworker/sandbox/settings.py
+++ b/coworker/sandbox/settings.py
@@ -13,26 +13,32 @@ from . import credentials, network_profiles
from .workspace import DIRECT, OPENSHELL, SEATBELT
-def _availability(name: str) -> tuple[bool, str]:
- """(usable, why not) for a provider on this machine."""
+def _availability(name: str) -> tuple[bool, str, str]:
+ """(usable, why not, state) for a provider on this machine. `state` is what the page
+ shows next to the provider: "ready", "unavailable", or "needs_download" for OpenShell
+ when everything is in place except the base image (OPE-205: the page said "ready" while
+ the first session was bound to hang on that download)."""
if name == DIRECT:
- return True, ""
+ return True, "", "ready"
if name == SEATBELT:
if sys.platform != "darwin":
- return False, "macOS only"
+ return False, "macOS only", "unavailable"
from .providers import seatbelt
try:
seatbelt.preflight()
- return True, ""
+ return True, "", "ready"
except seatbelt.SeatbeltUnavailable as exc:
- return False, str(exc)
+ return False, str(exc), "unavailable"
if name == OPENSHELL:
+ from .providers.openshell import is_image_problem
from .selection import openshell_problem
problem = openshell_problem()
- return (problem is None), (problem or "")
- return False, "unknown"
+ if problem is None:
+ return True, "", "ready"
+ return False, problem, ("needs_download" if is_image_problem(problem) else "unavailable")
+ return False, "unknown", "unavailable"
def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:
@@ -46,8 +52,8 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:
effective, refused = "", str(exc)
providers = []
for name in (DIRECT, SEATBELT, OPENSHELL):
- usable, why = _availability(name)
- providers.append({"name": name, "usable": usable, "why": why})
+ usable, why, state = _availability(name)
+ providers.append({"name": name, "usable": usable, "why": why, "state": state})
return {
"platform": sys.platform,
"provider": cfg.sandbox_provider or "", # "" = the default rule
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
index a721198d..e11587cb 100644
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@ -19,11 +19,16 @@ from pathlib import Path
from typing import Callable, Optional
from .. import config as app_config
+from .providers import openshell
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"
+# The base image is pulled by the first `sandbox create` otherwise, which on a slow link
+# 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)"
def _run(argv: list[str], timeout: float = 600) -> subprocess.CompletedProcess:
@@ -50,7 +55,10 @@ def checks() -> list[tuple[str, bool, str]]:
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 ""))
+ # 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 "")))
try:
import grpc # noqa: F401
@@ -58,6 +66,10 @@ def checks() -> list[tuple[str, bool, str]]:
except ImportError:
grpc_ok = False
out.append(("the `grpcio` package is installed", grpc_ok, "" if grpc_ok else "pip install 'openworker[openshell]'"))
+ if gateway_ok and exe:
+ present = openshell.image_present()
+ if present is not None: # only the Docker driver can be asked; other drivers get no row
+ out.append((IMAGE_ROW, present, "" if present else f"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()}"))
return out
@@ -92,11 +104,29 @@ def status(print_fn: Callable[[str], None] = print) -> int:
return 0 if all(ok for _, ok, _ in rows) else 1
+def _offer_image_download(rows: dict[str, bool], confirm: Callable[[str], bool], print_fn: Callable[[str], None]) -> Optional[int]:
+ """When the base image is missing: show the command, ask, and run the pull with Docker's
+ own progress and no time limit. Returns an exit code to stop with, or None to go on."""
+ if rows.get(IMAGE_ROW, True):
+ return None
+ image = openshell.sandbox_image()
+ print_fn(f"The sandbox base image is not on this machine. It is about 5 GB and is downloaded once;\nuntil then the first session cannot start:\n docker pull {image}")
+ if not confirm("Download it now? (10 to 20 minutes on a slow connection)"):
+ return 1
+ if subprocess.run(["docker", "pull", image], stdin=subprocess.DEVNULL).returncode != 0:
+ print_fn("the download failed; nothing else was changed")
+ return 1
+ return None
+
+
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
+ # The one step that is the same on a Mac with Docker Desktop: the image download.
+ rows = {what: ok for what, ok, _ in checks()}
+ stop = _offer_image_download(rows, confirm, print_fn)
+ return 2 if stop is None else stop
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)")
@@ -134,5 +164,12 @@ def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, pri
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")
+ # 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:
+ rows = {what: ok for what, ok, _ in checks()}
+ stop = _offer_image_download(rows, confirm, print_fn)
+ if stop is not None:
+ return stop
print_fn("")
return status(print_fn)
diff --git a/docs/openshell.md b/docs/openshell.md
index 5f0241f4..19fe72eb 100644
--- a/docs/openshell.md
+++ b/docs/openshell.md
@@ -71,8 +71,14 @@ openworker machine sandbox setup
`status` lists what is missing. `setup` shows each change before it makes it and asks
first: it runs NVIDIA's installer for the pinned OpenShell release, allows bind mounts in
the gateway's configuration (that is how your folders reach a sandbox), keeps the gateway
-running after you log out, and sets the machine to use OpenShell. It never runs `sudo` for
-you; when a step needs an administrator, it prints the command.
+running after you log out, sets the machine to use OpenShell, and downloads the base
+image sandboxes are built from. It never runs `sudo` for you; when a step needs an
+administrator, it prints the command.
+
+The base image is about 5 GB and is downloaded once. Until it is on the machine, Settings ▸
+Sandbox shows OpenShell as **needs download** and a session is refused with the same
+message, rather than hanging on the download. `setup` offers it with Docker's own
+progress; the command is also `docker pull` of the image named in the refusal.
The setting is per machine, in Settings ▸ Sandbox or in `config.toml`:
@@ -154,7 +160,11 @@ enabled = true
- **"Sessions on this machine are refused"** — the machine is set to OpenShell and it
cannot be used right now. Run `openworker machine sandbox status` for the reason; the
- usual ones are the gateway not running, or bind mounts not allowed.
+ usual ones are the gateway not running, bind mounts not allowed, or the base image not
+ downloaded yet.
+- **"The sandbox base image is not downloaded yet"** — the one-time 5 GB download has
+ not happened. Run `openworker machine sandbox setup` and accept the download, or run the
+ `docker pull` command from the message; then start the session again.
- **A host is refused** — it is not on the profile; switch to `standard` if it is a search
API, or share the credential entry whose hosts include it.
- **`git push` says permission denied inside the sandbox** — no credential is shared.
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index 5209a656..d376352c 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -2102,7 +2102,9 @@ export interface SandboxSettings {
provider: string; // "" = the default rule
effective_provider: string;
refused: string;
- providers: { name: string; usable: boolean; why: string }[];
+ // `state` is what the page shows next to a provider. "needs_download": OpenShell is in
+ // place except for the base image (about 5 GB, pulled once); the radio stays enabled.
+ providers: { name: string; usable: boolean; why: string; state?: "ready" | "needs_download" | "unavailable" }[];
network_profile: string;
network_profiles: { name: string; hosts: string[] }[];
credentials: SandboxCredentialEntry[];
diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
index a6630ed9..ce2b1387 100644
--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
@@ -79,6 +79,26 @@ describe("Settings ▸ Sandbox", () => {
);
});
+ 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,
+ 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" },
+ ],
+ });
+ 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();
+ });
+
it("adds an entry through the editor and removes one", async () => {
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsx
index 01cf5790..db316e7f 100644
--- a/surfaces/gui/src/components/SettingsView.tsx
+++ b/surfaces/gui/src/components/SettingsView.tsx
@@ -773,6 +773,10 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
.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
@@ -780,20 +784,27 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
name="sandbox-provider"
className="mt-1"
checked={active}
- disabled={!p.usable && !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 " + (p.usable ? (active ? "text-success" : "text-muted") : "text-muted")} title={p.why || undefined}>
+ <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")
- : p.usable
- ? t("settingsx.sandbox.status_ready")
- : t("settingsx.sandbox.status_unavailable")}
+ : needsDownload
+ ? t("settingsx.sandbox.status_needs_download")
+ : p.usable
+ ? t("settingsx.sandbox.status_ready")
+ : t("settingsx.sandbox.status_unavailable")}
</span>
</label>
);
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index 5bda529e..e4285be1 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -2280,6 +2280,8 @@
"provider_openshell_desc": "One Linux container per agent, with the session's folders mounted. Needs OpenShell and Docker on this machine.",
"status_default": "default",
"status_ready": "ready",
+ "status_needs_download": "needs download",
+ "needs_download_hint": "The sandbox base image (about 5 GB, downloaded once) is not on this machine yet. Run `openworker machine sandbox setup` in a terminal; the first session cannot start until it is.",
"status_unavailable": "not available",
"refused": "Sessions on this machine are refused until this is fixed: {{why}}",
"network": "Network allow list",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 8eb9980b..7d35b7ec 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -2240,6 +2240,8 @@
"provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。",
"status_default": "默认",
"status_ready": "就绪",
+ "status_needs_download": "需要下载",
+ "needs_download_hint": "沙箱基础镜像(约 5 GB,仅下载一次)尚未下载到这台机器。请在终端运行 `openworker machine sandbox setup`;下载完成前第一个会话无法启动。",
"status_unavailable": "不可用",
"refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",
"network": "网络允许列表",
diff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.py
index ce28688d..ff2e5f38 100644
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@ -78,25 +78,65 @@ def test_missing_openshell_is_refused_with_a_message_a_person_can_act_on(monkeyp
assert "not installed" in str(err.value) and "sandbox setup" in str(err.value)
-def test_another_version_or_a_stopped_gateway_is_refused(monkeypatch):
- def fake(answers):
- def run(argv, **kwargs):
- assert kwargs.get("stdin") == subprocess.DEVNULL # an open stdin hangs the CLI
- out, code = answers[argv[1]]
- return subprocess.CompletedProcess(argv, code, out, "")
+def _fake_cli(answers):
+ """`subprocess.run` answering by the first argument after the program: `--version`,
+ `status`, `gateway` (info), and `image` (docker image inspect)."""
+
+ def run(argv, **kwargs):
+ assert kwargs.get("stdin") == subprocess.DEVNULL # an open stdin hangs the CLI
+ out, code = answers[argv[1]]
+ return subprocess.CompletedProcess(argv, code, out, "")
+
+ return run
+
+
+_OK_VERSION = (f"openshell {openshell.PINNED_VERSION}\n", 0)
+_CONNECTED = ("Status: Connected", 0)
+_DOCKER_GATEWAY = ('{"compute_drivers": [{"name": "docker"}], "status": "healthy"}', 0)
- return run
+def test_another_version_or_a_stopped_gateway_is_refused(monkeypatch):
monkeypatch.setattr(openshell.shutil, "which", lambda name: "/usr/bin/openshell")
- monkeypatch.setattr(openshell.subprocess, "run", fake({"--version": ("openshell 9.9.9\n", 0)}))
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli({"--version": ("openshell 9.9.9\n", 0)}))
with pytest.raises(openshell.OpenShellUnavailable, match="tested with"):
openshell.preflight()
- ok_version = (f"openshell {openshell.PINNED_VERSION}\n", 0)
- monkeypatch.setattr(openshell.subprocess, "run", fake({"--version": ok_version, "status": ("Status: Disconnected", 1)}))
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli({"--version": _OK_VERSION, "status": ("Status: Disconnected", 1)}))
with pytest.raises(openshell.OpenShellUnavailable, match="not running"):
openshell.preflight()
- monkeypatch.setattr(openshell.subprocess, "run", fake({"--version": ok_version, "status": ("Status: Connected", 0)}))
+ present = {"--version": _OK_VERSION, "status": _CONNECTED, "gateway": _DOCKER_GATEWAY, "image": ("[{...}]", 0)}
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli(present))
+ assert openshell.preflight() == {"version": openshell.PINNED_VERSION}
+
+
+def test_a_missing_base_image_is_refused_before_a_create_can_hang_on_it(monkeypatch):
+ # OPE-205: the first `sandbox create` pulls about 5 GB; on a slow link that outlives the
+ # create's timeout and the session hangs for ten minutes with no word about why. So the
+ # image is checked up front, with a message that names the download.
+ monkeypatch.setattr(openshell.shutil, "which", lambda name: f"/usr/bin/{name}")
+ missing = {"--version": _OK_VERSION, "status": _CONNECTED, "gateway": _DOCKER_GATEWAY, "image": ("Error: No such image", 1)}
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli(missing))
+ with pytest.raises(openshell.OpenShellImageMissing) as err:
+ openshell.preflight()
+ text = str(err.value)
+ assert openshell.is_image_problem(text) and "sandbox setup" in text and f"docker pull {openshell.DEFAULT_IMAGE}" in text
+ assert isinstance(err.value, openshell.OpenShellUnavailable) # callers that refuse sessions need no new branch
+ assert not openshell.is_image_problem("The OpenShell gateway is not running") and not openshell.is_image_problem(None)
+ # The check is keyed on the gateway's driver, not the OS: with another driver (a Mac's
+ # MicroVM, say) Docker cannot be asked, and the preflight passes as before.
+ vm_gateway = ('{"compute_drivers": [{"name": "vm"}]}', 0)
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli({"--version": _OK_VERSION, "status": _CONNECTED, "gateway": vm_gateway}))
+ assert openshell.image_present() is None
assert openshell.preflight() == {"version": openshell.PINNED_VERSION}
+ # No `docker` command on PATH: also "cannot tell", never a false refusal.
+ monkeypatch.setattr(openshell.shutil, "which", lambda name: "/usr/bin/openshell" if name == "openshell" else None)
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli({"--version": _OK_VERSION, "status": _CONNECTED, "gateway": _DOCKER_GATEWAY}))
+ assert openshell.image_present() is None
+ # The environment's image is the one asked for.
+ seen: list[str] = []
+ monkeypatch.setattr(openshell.shutil, "which", lambda name: f"/usr/bin/{name}")
+ monkeypatch.setattr(openshell.subprocess, "run", lambda argv, **kw: seen.append(argv[-1]) or _fake_cli({"gateway": _DOCKER_GATEWAY, "image": ("", 0)})(argv, **kw))
+ monkeypatch.setenv("OPENWORKER_SANDBOX_IMAGE", "registry.example.com/team/agent:2")
+ assert openshell.image_present() is True and seen[-1] == "registry.example.com/team/agent:2"
def test_registry_counts_caps_and_forgets(tmp_path, monkeypatch):
diff --git a/tests/test_sandbox_selection.py b/tests/test_sandbox_selection.py
index 7a310d1f..9c10fce9 100644
--- a/tests/test_sandbox_selection.py
+++ b/tests/test_sandbox_selection.py
@@ -138,3 +138,74 @@ def test_setup_asks_before_each_change_and_makes_none_when_refused(tmp_path, mon
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
+
+
+def _all_but_the_image(setup_cmd):
+ return [
+ ("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)", True, ""),
+ ("the gateway keeps running after you log out (linger)", True, ""),
+ ("the gateway is running", True, ""),
+ ("the `grpcio` package is installed", True, ""),
+ ("this machine is set to use OpenShell", True, ""),
+ (setup_cmd.IMAGE_ROW, False, "docker pull ghcr.io/example/base@sha256:abc"),
+ ]
+
+
+def test_setup_offers_the_base_image_download_and_runs_nothing_when_refused(tmp_path, monkeypatch):
+ # OPE-205: the download is the one slow step, so it is a row of its own, offered last,
+ # shown with its size and command, and run with no time limit only after a yes.
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")
+ monkeypatch.setattr(setup_cmd, "checks", lambda: _all_but_the_image(setup_cmd))
+ monkeypatch.setattr(setup_cmd.openshell, "sandbox_image", lambda: "ghcr.io/example/base@sha256:abc")
+ ran: list[list[str]] = []
+ monkeypatch.setattr(setup_cmd.subprocess, "run", lambda argv, **kw: ran.append(argv) or type("Done", (), {"returncode": 0})())
+ asked: list[str] = []
+ said: list[str] = []
+ assert setup_cmd.setup(ask=lambda q: asked.append(q) or False, print_fn=said.append) == 1
+ assert asked == ["Download it now? (10 to 20 minutes on a slow connection)"]
+ assert "5 GB" in "\n".join(said) and "docker pull ghcr.io/example/base@sha256:abc" in "\n".join(said)
+ assert ran == [] # refused: nothing ran
+ # Accepted: the pull runs as a plain command (Docker's own progress, no capture, no timeout).
+ monkeypatch.setattr(setup_cmd, "status", lambda print_fn=print: 0)
+ assert setup_cmd.setup(yes=True, print_fn=said.append) == 0
+ assert ran == [["docker", "pull", "ghcr.io/example/base@sha256:abc"]]
+
+
+def test_setup_on_a_mac_still_offers_the_download(tmp_path, monkeypatch):
+ # The rest of `setup` is Linux-only, but the image is the same on a Mac with Docker
+ # Desktop, and the first session hangs on it there just the same.
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")
+ monkeypatch.setattr(setup_cmd, "checks", lambda: _all_but_the_image(setup_cmd))
+ ran: list[list[str]] = []
+ monkeypatch.setattr(setup_cmd.subprocess, "run", lambda argv, **kw: ran.append(argv) or type("Done", (), {"returncode": 0})())
+ said: list[str] = []
+ assert setup_cmd.setup(yes=True, print_fn=said.append) == 2 # still "this configures a Linux machine"
+ assert ran and ran[0][:2] == ["docker", "pull"]
+ assert "configures a Linux machine" in "\n".join(said)
+
+
+def test_status_shows_a_missing_image_as_its_own_row_not_as_a_gateway_problem(tmp_path, monkeypatch):
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: f"/usr/bin/{name}")
+ monkeypatch.setattr(setup_cmd, "_run", lambda argv, timeout=600: type("Done", (), {"returncode": 0, "stdout": f"openshell {setup_cmd.PINNED_VERSION}\n"})())
+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin") # no linger row to fake
+ monkeypatch.setattr(setup_cmd, "openshell_problem", lambda fresh=False: f"{setup_cmd.openshell.IMAGE_MISSING_PREFIX} (about 5 GB, one time). Run `docker pull x`.")
+ monkeypatch.setattr(setup_cmd.openshell, "image_present", lambda image=None: False)
+ monkeypatch.setattr(setup_cmd.openshell, "sandbox_image", lambda: "x")
+ rows = {what: (ok, detail) for what, ok, detail in setup_cmd.checks()}
+ assert rows["the gateway is running"] == (True, "") # the gateway is fine; only the image is missing
+ assert rows[setup_cmd.IMAGE_ROW] == (False, "docker pull x")
+ # Another driver: Docker cannot be asked, so no row rather than a wrong one.
+ monkeypatch.setattr(setup_cmd, "openshell_problem", lambda fresh=False: None)
+ monkeypatch.setattr(setup_cmd.openshell, "image_present", lambda image=None: None)
+ assert setup_cmd.IMAGE_ROW not in {what for what, _, _ in setup_cmd.checks()}
diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.py
index 9ec4d77b..60b6e303 100644
--- a/tests/test_sandbox_settings.py
+++ b/tests/test_sandbox_settings.py
@@ -69,6 +69,25 @@ def test_removing_a_shipped_entry_and_going_back_to_the_default_rule(config_file
assert "sandbox_provider" not in text and "[[sandbox_credentials]]" not in text
+def test_a_missing_base_image_shows_as_needs_download_not_as_ready(config_file, monkeypatch):
+ # OPE-205: the page said "ready" while the first session was bound to hang on the
+ # one-time 5 GB download. Now that state has a name of its own, and the refusal a
+ # session would get carries the same message.
+ from coworker.sandbox import selection
+ from coworker.sandbox.providers.openshell import IMAGE_MISSING_PREFIX
+
+ message = f"{IMAGE_MISSING_PREFIX} (about 5 GB, one time). Run `openworker machine sandbox setup`."
+ monkeypatch.setattr(selection, "openshell_problem", lambda fresh=False: message)
+ snap = settings.snapshot()
+ row = next(p for p in snap["providers"] if p["name"] == "openshell")
+ assert row == {"name": "openshell", "usable": False, "why": message, "state": "needs_download"}
+ assert next(p for p in snap["providers"] if p["name"] == "direct")["state"] == "ready"
+ assert settings.update({"provider": "openshell"})["ok"] # the choice is allowed; the download is what is missing
+ assert "not downloaded yet" in settings.snapshot()["refused"]
+ monkeypatch.setattr(selection, "openshell_problem", lambda fresh=False: "The OpenShell gateway is not running.")
+ assert next(p for p in settings.snapshot()["providers"] if p["name"] == "openshell")["state"] == "unavailable"
+
+
def test_an_explicit_provider_that_cannot_be_used_shows_as_refused(config_file, monkeypatch):
from coworker.sandbox import selection
from coworker.sandbox.providers.openshell import OpenShellUnavailable