Skip to content
Python

Settings > Sandbox: the app installs OpenShell itself where it can; one command where it cannot (OPE-207)

Devika Verma9a7cc2bceaae
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
index 859d2fef..6ca244c1 100644
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@ -1,13 +1,21 @@
"""`openworker machine sandbox status|setup`: get a machine ready to run agents in
OpenShell sandboxes (design doc, ruling 23).
-`setup` shows every change before it makes it and asks first (or `--yes`). It never runs
-`sudo` for you; when a step needs it, it prints the command. Someone who brings their own
-OpenShell can ignore `setup` and use `status` to see what is missing.
+`setup` shows every change before it makes it and asks first (or `--yes`). Someone who
+brings their own OpenShell 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.
+shows, and `setup_job.SetupJob` runs the fixes, with progress. One list of checks and fixes,
+two front ends.
+
+Two steps need an administrator on Linux: installing the OpenShell package, and `linger`
+(the gateway is a user service and stops at logout otherwise). The app runs them itself
+when it can do so without holding a password: through `sudo` when this user may use it
+without one, or through the system's own password prompt (`pkexec`) on a Linux desktop.
+Where neither exists (WSL has no prompt), the two are folded into ONE command for the
+user to run, and the job stops there until "check again". A Mac needs no administrator:
+Homebrew installs OpenShell as the user, and there is no linger. The app never asks for,
+sees or stores a password.
Hidden from `openworker --help` until it has been tried on a fresh machine.
"""
@@ -31,6 +39,9 @@ from .providers.openshell import PINNED_VERSION
from .selection import openshell_problem, select
_INSTALLER = "https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh"
+# Where the page's "Guide" links point: how OpenShell fits, what a machine needs, setup.
+GUIDE_URL = "https://github.com/andrewyng/openworker/blob/main/docs/openshell.md"
+DOCKER_INSTALL_URL = "https://docs.docker.com/engine/install/"
_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
@@ -53,8 +64,8 @@ ROWS = {
"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.
+# Steps the app may fix on its own without an administrator. `openshell` joins them at
+# run time when `admin_prefix()` finds a way to run as one; see `steps()`.
FIXABLE = {"bind_mounts", "config", "image", "linger"}
@@ -63,11 +74,13 @@ class Step:
key: str
what: str
ok: bool
- hint: str = "" # what to run, or why it failed
+ hint: str = "" # a note: what was found, or why it failed. Never a command.
fixable: bool = False # `SetupJob` can do this one itself
+ command: str = "" # what to run in a terminal on this machine when the app cannot
+ docs: str = "" # a page that explains this requirement
def as_dict(self) -> dict[str, Any]:
- return {"key": self.key, "what": self.what, "ok": self.ok, "hint": self.hint, "fixable": self.fixable}
+ return {"key": self.key, "what": self.what, "ok": self.ok, "hint": self.hint, "fixable": self.fixable, "command": self.command, "docs": self.docs}
def _run(argv: list[str], timeout: float = 600) -> subprocess.CompletedProcess:
@@ -78,6 +91,45 @@ def _openshell_home() -> Path:
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "openshell"
+def installer_command() -> str:
+ """NVIDIA's installer, pinned to the tested release. It downloads the package from
+ their GitHub release, checks its checksum and installs it. On Linux it needs `sudo`
+ (it asks itself when it has a terminal); on a Mac it uses Homebrew as the user."""
+ return f"curl -LsSf {_INSTALLER} | OPENSHELL_VERSION=v{PINNED_VERSION} sh"
+
+
+def is_wsl() -> bool:
+ try:
+ return "microsoft" in Path("/proc/version").read_text(encoding="utf-8").lower()
+ except OSError:
+ return False
+
+
+def admin_prefix() -> Optional[list[str]]:
+ """How this process can run a command as an administrator WITHOUT holding a password,
+ or None. `sudo -n` when this user may use sudo without a password (a dev VM, a cloud
+ box); else `pkexec` on a Linux desktop, where polkit shows the system's own password
+ prompt and the app never sees what is typed. WSL has no such prompt, so None there:
+ the caller hands the command over. `SUDO_USER` tells NVIDIA's installer which user's
+ gateway service to set up; sudo sets it by itself, pkexec does not."""
+ if not sys.platform.startswith("linux"):
+ return None
+ if shutil.which("sudo") and _run(["sudo", "-n", "true"], 15).returncode == 0:
+ return ["sudo", "-n"]
+ if shutil.which("pkexec") and not is_wsl() and (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
+ return ["pkexec", "env", f"SUDO_USER={getpass.getuser()}", f"PATH={os.environ.get('PATH', '/usr/bin:/bin')}"]
+ return None
+
+
+def install_handover_command() -> str:
+ """The ONE command a user runs in a terminal when the app cannot run the administrator
+ steps itself: linger first (the installer needs the user's systemd manager, which does
+ not run without it on WSL), then the installer. On a Mac, the installer alone."""
+ if sys.platform.startswith("linux"):
+ return f"sudo loginctl enable-linger {getpass.getuser()} && {installer_command()}"
+ return installer_command()
+
+
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).
@@ -112,19 +164,35 @@ def steps() -> list[Step]:
out: list[Step] = []
docker = shutil.which("docker")
docker_ok = bool(docker) and _run(["docker", "info", "--format", "{{.ServerVersion}}"], 30).returncode == 0
- out.append(Step("docker", ROWS["docker"], 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, then add this user to the `docker` group and log in again", docs="" if docker_ok else DOCKER_INSTALL_URL))
exe = shutil.which("openshell")
version = _run([exe, "--version"], 15).stdout.strip().split()[-1] if exe else ""
- out.append(Step("openshell", ROWS["openshell"], version == PINNED_VERSION, f"found {version or 'none'}" if version != PINNED_VERSION else ""))
+ openshell_ok = version == PINNED_VERSION
+ # The app installs it when it can run as an administrator without a password (or
+ # needs none, on a Mac); otherwise the row carries the one command to run.
+ can_install = sys.platform == "darwin" or (sys.platform.startswith("linux") and admin_prefix() is not None)
+ out.append(
+ Step(
+ "openshell",
+ ROWS["openshell"],
+ openshell_ok,
+ "" if openshell_ok or not version else f"found {version}, not the tested release",
+ fixable=not openshell_ok and can_install,
+ command="" if openshell_ok or can_install else install_handover_command(),
+ docs="" if openshell_ok else GUIDE_URL,
+ )
+ )
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(Step("bind_mounts", ROWS["bind_mounts"], binds, "" if binds else str(gateway_toml), fixable=True))
+ out.append(Step("bind_mounts", ROWS["bind_mounts"], binds, fixable=True))
if sys.platform.startswith("linux"):
linger = _run(["loginctl", "show-user", getpass.getuser(), "-p", "Linger"], 15).stdout.strip() == "Linger=yes"
- out.append(Step("linger", ROWS["linger"], linger, "" if linger else f"sudo loginctl enable-linger {getpass.getuser()}", fixable=True))
+ # Fixable: `enable_linger` tries as the user, then as an administrator; when both
+ # are refused the job hands this command over and goes on.
+ out.append(Step("linger", ROWS["linger"], linger, fixable=True, command="" if linger else f"sudo loginctl enable-linger {getpass.getuser()}"))
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)"))
+ out.append(Step("landlock", ROWS["landlock"], landlock, "" if landlock else "update the kernel (on WSL: run `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)
@@ -136,7 +204,7 @@ def steps() -> list[Step]:
grpc_ok = True
except ImportError:
grpc_ok = False
- out.append(Step("grpcio", ROWS["grpcio"], grpc_ok, "" if grpc_ok else "pip install 'openworker[openshell]'"))
+ out.append(Step("grpcio", ROWS["grpcio"], grpc_ok, command="" 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:
@@ -146,13 +214,13 @@ def steps() -> list[Step]:
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))
+ out.append(Step("image", IMAGE_ROW, present, fixable=True, command="" if present else f"{openshell.image_tool() or 'docker'} pull {openshell.sandbox_image()}"))
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()]
+ return [(s.what, s.ok, s.command or s.hint) for s in steps()]
# -- the fixes, one function each: `setup` (with prompts) and `SetupJob` (with progress) --
@@ -187,10 +255,57 @@ def apply_bind_mounts() -> Optional[str]:
def enable_linger() -> Optional[str]:
- """Try without an administrator; return the command to run when that is refused."""
+ """Try as the user, then as an administrator without a password (`admin_prefix`);
+ return the command to run when both are refused."""
user = getpass.getuser()
- if _run(["loginctl", "enable-linger", user], 30).returncode != 0:
- return f"sudo loginctl enable-linger {user}"
+ if _run(["loginctl", "enable-linger", user], 30).returncode == 0:
+ return None
+ prefix = admin_prefix()
+ if prefix is not None and _run(prefix + ["loginctl", "enable-linger", user], 120).returncode == 0:
+ return None
+ return f"sudo loginctl enable-linger {user}"
+
+
+def _stream(argv: list[str], on_line: Optional[Callable[[str], None]], cancel: Optional[threading.Event]) -> tuple[Optional[int], str]:
+ """Run `argv` with stdin closed, feeding each output line to `on_line`. Returns the
+ exit code (None when cancelled) and the last line seen."""
+ last = ""
+ try:
+ proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ except OSError as exc:
+ return 127, f"could not run {argv[0]}: {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 None, last
+ line = line.strip()
+ if line:
+ last = line[:160]
+ if on_line is not None:
+ on_line(last)
+ return proc.wait(), last
+
+
+def install_openshell(on_line: Optional[Callable[[str], None]] = None, cancel: Optional[threading.Event] = None) -> Optional[str]:
+ """Install the pinned OpenShell from the app (Settings ▸ Set up sandbox). On a Mac the
+ installer runs as the user. On Linux it runs as an administrator through
+ `admin_prefix()`, with linger enabled FIRST in the same run (the installer needs the
+ user's systemd manager, which does not run without linger on WSL and on a headless
+ box). Returns an error text, or None when it succeeded."""
+ if sys.platform == "darwin":
+ argv = ["sh", "-c", installer_command()]
+ else:
+ prefix = admin_prefix()
+ if prefix is None:
+ return "this machine has no way to run an administrator step without a password; run: " + install_handover_command()
+ argv = prefix + ["sh", "-c", f"loginctl enable-linger {getpass.getuser()} && {installer_command()}"]
+ code, last = _stream(argv, on_line, cancel)
+ if code is None:
+ return "installation cancelled"
+ if code != 0:
+ return f"the installer exited with {code}: {last}"
return None
@@ -303,9 +418,18 @@ def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, pri
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.get(ROWS["linger"], True):
+ # Before the installer: it starts the gateway through the user's systemd manager,
+ # which on WSL and on a headless box only runs once linger is on.
+ print_fn(f"The gateway is a user service and stops when you log out. Keeping it running needs an administrator:\n sudo loginctl enable-linger {getpass.getuser()}")
+ if not confirm("Run it now (sudo will ask for your password)?"):
+ return 1
+ if subprocess.run(["sudo", "loginctl", "enable-linger", getpass.getuser()]).returncode != 0:
+ print_fn("enable-linger failed; nothing else was changed")
+ return 1
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}")
+ command = installer_command()
+ 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}\nGuide: {GUIDE_URL}")
if not confirm("Run NVIDIA's installer now?"):
return 1
if subprocess.run(["sh", "-c", command]).returncode != 0:
@@ -319,10 +443,6 @@ def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, pri
if problem:
print_fn(problem)
return 1
- 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?"):
diff --git a/coworker/sandbox/setup_job.py b/coworker/sandbox/setup_job.py
index 6bd9da9e..f8738b2b 100644
--- a/coworker/sandbox/setup_job.py
+++ b/coworker/sandbox/setup_job.py
@@ -1,12 +1,13 @@
"""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.
+One job per machine, on a worker thread. It walks `setup_cmd.steps()` top to bottom and
+fixes each step it may: the OpenShell install (through `sudo` without a password or the
+system's password prompt, see `setup_cmd.admin_prefix`; as the user on a Mac), bind
+mounts, linger, the config line, the image download. The two slow ones (install,
+download) stream progress and can be cancelled. A step the app cannot do on this machine
+is handed over as ONE command to run in a terminal, and the job stops there until the
+user says "check again". The job never holds a password and never lowers protection: a
+failure leaves the machine "not ready, here is what to do", and sessions stay refused.
"""
from __future__ import annotations
@@ -96,8 +97,8 @@ class SetupJob:
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.
+ # The app cannot do this one here: hand its command over and stop, 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"
@@ -105,11 +106,12 @@ class SetupJob:
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="")
+ self._set_row(step.key, state=self.FIXED, hint="", command="")
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)
+ # Refused as the user and as an administrator: not fatal, the command is
+ # shown; go on with the rest.
+ self._set_row(step.key, state=self.NEEDS_YOU, command=problem)
continue
self._set_row(step.key, state=self.FAILED, hint=problem)
with self._lock:
@@ -127,12 +129,18 @@ class SetupJob:
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
+ done[s.key]["hint"], done[s.key]["command"] = s.hint, s.command
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 _progress(self, line: str, **more: Any) -> None:
+ with self._lock:
+ self.progress = {"layers_total": 0, "layers_done": 0, "last_line": line, "elapsed_s": int(time.time() - self.started_at), **more}
+
def _fix(self, step: setup_cmd.Step) -> Optional[str]:
+ if step.key == "openshell":
+ return setup_cmd.install_openshell(self._progress, self._cancel)
if step.key == "bind_mounts":
return setup_cmd.apply_bind_mounts()
if step.key == "config":
@@ -143,8 +151,7 @@ class SetupJob:
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)}
+ self._progress(p.last_line, layers_total=p.layers_total, layers_done=p.layers_done)
return setup_cmd.pull_image(on_progress, self._cancel)
return f"no automatic fix for {step.key}"
diff --git a/docs/openshell.md b/docs/openshell.md
index 311974fa..d4471897 100644
--- a/docs/openshell.md
+++ b/docs/openshell.md
@@ -69,26 +69,33 @@ 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, 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.
+first: it keeps the gateway running after you log out (`linger`, which needs `sudo` and
+comes first, because NVIDIA's installer starts the gateway through your user's systemd
+manager, and on WSL or a headless box that manager only runs once linger is on), 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), sets the machine to use
+OpenShell, and downloads the base image sandboxes are built from.
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.
+message, rather than hanging on the download. `setup` and the page's **Set up sandbox**
+download it with Docker's own progress; 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.
+and under it the provider, a readiness checklist (the rows `status` prints, each with a
+Guide link and, where the app cannot do it, the one command to run), and a **Set up
+sandbox** button that walks the list and does each step itself. The two steps that need
+an administrator on Linux (the OpenShell install and linger) go through `sudo` when your
+user may use it without a password, or through the system's own password prompt on a
+Linux desktop; the app never sees or stores the password. On a Mac, Homebrew installs
+OpenShell as you, so nothing needs an administrator. Where there is no prompt to use
+(WSL), both steps are folded into ONE command shown with Copy, and **Check again**
+continues once you have run it. The install and the image download show their progress
+and can be cancelled. 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`:
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index bef3c8e1..8a4aa016 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -2135,8 +2135,10 @@ export interface SandboxReadinessStep {
key: string;
what: string;
ok: boolean;
- hint: string;
- fixable: boolean;
+ hint: string; // a note (what was found, why it failed); never a command
+ fixable: boolean; // the setup job does this one itself on that machine
+ command: string; // what to run in a terminal there when the app cannot
+ docs: string; // a page explaining the requirement, or ""
}
export interface SandboxReadiness {
platform: string;
diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
index 787123d8..f9a5985b 100644
--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
@@ -30,9 +30,11 @@ const readiness = {
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 },
+ { key: "docker", what: "Docker is installed and this user can use it", ok: true, hint: "", fixable: false, command: "", docs: "" },
+ // Handed over (no way to run as an administrator here): a command, and a guide.
+ { key: "openshell", what: "OpenShell 0.0.116 is installed", ok: false, hint: "", fixable: false, command: "curl -LsSf https://example/install.sh | sh", docs: "https://example/guide" },
+ { key: "gateway", what: "the gateway is running", ok: false, hint: "OpenShell is not installed", fixable: false, command: "", docs: "" },
+ { key: "image", what: "the sandbox base image is downloaded (about 5 GB, one time)", ok: false, hint: "", fixable: true, command: "docker pull img", docs: "" },
],
};
let setupState: any = { status: "idle", rows: [], progress: null, error: "", elapsed_s: 0 };
@@ -78,12 +80,12 @@ describe("Settings ▸ Sandbox", () => {
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
expect((screen.getByTestId("sandbox-switch") as HTMLInputElement).checked).toBe(false);
- expect(screen.getByText(/Off: commands run as you/)).toBeTruthy();
+ expect(screen.getByText(/Off: commands run directly on this machine/)).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();
+ expect(screen.queryByText(/config\.toml/)).toBeNull(); // off = nothing stored: no "stored in" line
});
it("switching on picks the provider that needs no setup on a Mac, and off clears the key", async () => {
@@ -129,11 +131,17 @@ describe("Settings ▸ Sandbox", () => {
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.getByText("3 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);
+ // Only the handed-over row shows its command with Copy; the image row is the app's to
+ // do, and a note (the gateway row) gets neither.
+ expect(screen.getAllByText("Run this in a terminal on this machine:").length).toBe(1);
+ expect(screen.getAllByText("Copy").length).toBe(1);
+ expect(screen.getByText("OpenShell is not installed")).toBeTruthy(); // the gateway row's note, plain
+ expect(screen.queryByTestId("sandbox-readiness-command-gateway")).toBeNull();
+ expect((screen.getByTestId("sandbox-readiness-docs-openshell") as HTMLAnchorElement).href).toBe("https://example/guide");
expect((screen.getByTestId("sandbox-setup-start") as HTMLButtonElement).disabled).toBe(false);
});
@@ -144,7 +152,8 @@ describe("Settings ▸ Sandbox", () => {
rows: [
{ ...readiness.steps[0], state: "ok" },
{ ...readiness.steps[1], ok: true, state: "ok" },
- { ...readiness.steps[2], state: "fixing" },
+ { ...readiness.steps[2], ok: true, state: "ok" },
+ { ...readiness.steps[3], state: "fixing" },
],
progress: { layers_total: 8, layers_done: 3, last_line: "x: Downloading", elapsed_s: 75 },
error: "",
@@ -158,12 +167,32 @@ describe("Settings ▸ Sandbox", () => {
expect(screen.getByTestId("sandbox-readiness-row-image").getAttribute("data-state")).toBe("fixing");
cleanup();
+ // The app installing OpenShell itself: the installer's output is the progress.
+ setupState = {
+ status: "running",
+ rows: [
+ { ...readiness.steps[0], state: "ok" },
+ { ...readiness.steps[1], command: "", fixable: true, state: "fixing" },
+ { ...readiness.steps[2], state: "pending" },
+ { ...readiness.steps[3], state: "pending" },
+ ],
+ progress: { layers_total: 0, layers_done: 0, last_line: "downloading v0.0.116 release checksums...", elapsed_s: 12 },
+ error: "",
+ elapsed_s: 12,
+ };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-install-progress");
+ expect(screen.getByTestId("sandbox-install-progress").textContent).toBe("Installing OpenShell… 12 s elapsed · downloading v0.0.116 release checksums...");
+ expect(screen.queryByText("Copy")).toBeNull(); // nothing to hand over while it works
+ cleanup();
+
setupState = {
status: "needs_you",
rows: [
{ ...readiness.steps[0], state: "ok" },
{ ...readiness.steps[1], state: "needs_you" },
{ ...readiness.steps[2], state: "pending" },
+ { ...readiness.steps[3], state: "pending" },
],
progress: null,
error: "",
@@ -171,7 +200,7 @@ describe("Settings ▸ Sandbox", () => {
};
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-setup-needs_you");
- expect(screen.getByText(/Run the command shown, then check again/)).toBeTruthy();
+ expect(screen.getByText(/run the command shown in a terminal on this machine, then click 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"));
diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsx
index c5964b58..6b30b54e 100644
--- a/surfaces/gui/src/components/SettingsView.tsx
+++ b/surfaces/gui/src/components/SettingsView.tsx
@@ -972,7 +972,12 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
{rows.map((r) => {
const state: SandboxSetupRowState = r.state ?? (r.ok ? "ok" : "pending");
const good = state === "ok" || state === "fixed";
+ // A command is something to run in a terminal on that machine (with Copy); a
+ // hint is a note about what was found. A row the app fixes itself shows its
+ // command only once the app could not (handed over, or failed).
+ const showCommand = !good && r.command && (!r.fixable || state === "needs_you" || state === "failed");
const showHint = !good && r.hint;
+ const showDocs = !good && r.docs;
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">
@@ -982,6 +987,12 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
<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 === "openshell" && running && state === "fixing" && setup?.progress ? (
+ <div className="mt-1 ml-6 text-meta text-muted font-mono break-all" data-testid="sandbox-install-progress">
+ {t("settingsx.sandbox.install_progress", { elapsed: elapsed(setup.progress.elapsed_s) })}
+ {setup.progress.last_line ? ` · ${setup.progress.last_line}` : ""}
+ </div>
+ ) : null}
{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">
@@ -997,14 +1008,23 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
</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>
+ {showHint ? <div className="mt-1 ml-6 text-meta text-muted">{r.hint}</div> : null}
+ {showCommand ? (
+ <div className="mt-1 ml-6" data-testid={`sandbox-readiness-command-${r.key}`}>
+ <div className="text-meta text-muted">{t("settingsx.sandbox.run_in_terminal")}</div>
+ <div className="flex items-start gap-2">
+ <code className="text-meta font-mono text-ink break-all flex-1 min-w-0">{r.command}</code>
+ <button className="text-meta text-accent shrink-0" onClick={() => copy(r.command)}>
+ {copied === r.command ? t("settingsx.sandbox.copied") : t("settingsx.sandbox.copy")}
+ </button>
+ </div>
</div>
) : null}
+ {showDocs ? (
+ <a className="mt-1 ml-6 inline-block text-meta text-accent" href={r.docs} target="_blank" rel="noreferrer" data-testid={`sandbox-readiness-docs-${r.key}`}>
+ {t("settingsx.sandbox.guide")}
+ </a>
+ ) : null}
</li>
);
})}
@@ -1103,7 +1123,7 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {
</>
) : null}
- <div className={FIELD_HELP + " mt-3"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>
+ {enabled ? <div className={FIELD_HELP + " mt-3"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div> : null}
{editing !== null ? (
<CredentialEditor
@@ -1139,15 +1159,17 @@ function CredentialEditor({
const valid = Boolean(slug) && (path.startsWith("~/") || path.startsWith("/"));
return (
<div className={CARD + " p-4 mt-3"} data-testid="sandbox-credential-editor">
+ <div className="text-ui text-ink mb-1">{entry ? t("settingsx.sandbox.editor_title_edit") : t("settingsx.sandbox.editor_title_add")}</div>
+ <div className={FIELD_HELP + " mb-3"}>{t("settingsx.sandbox.editor_help")}</div>
<div className="grid grid-cols-[150px_1fr] gap-x-3 gap-y-2 items-center">
<label className="text-ui text-muted">{t("settingsx.sandbox.field_title")}</label>
- <input className={INPUT} value={title} onChange={(e) => { setTitle(e.target.value); if (!entry) setName(""); }} />
+ <input className={INPUT} value={title} placeholder={t("settingsx.sandbox.field_title_example")} onChange={(e) => { setTitle(e.target.value); if (!entry) setName(""); }} />
<label className="text-ui text-muted">{t("settingsx.sandbox.field_path")}</label>
- <input className={INPUT + " font-mono"} value={path} onChange={(e) => setPath(e.target.value)} />
+ <input className={INPUT + " font-mono"} value={path} placeholder={t("settingsx.sandbox.field_path_example")} onChange={(e) => setPath(e.target.value)} />
<label className="text-ui text-muted self-start pt-2">{t("settingsx.sandbox.field_hosts")}</label>
- <textarea className={INPUT + " font-mono"} rows={3} value={hosts} onChange={(e) => setHosts(e.target.value)} />
+ <textarea className={INPUT + " font-mono"} rows={3} value={hosts} placeholder={t("settingsx.sandbox.field_hosts_example")} onChange={(e) => setHosts(e.target.value)} />
<label className="text-ui text-muted">{t("settingsx.sandbox.field_does")}</label>
- <input className={INPUT} value={does} onChange={(e) => setDoes(e.target.value)} />
+ <input className={INPUT} value={does} placeholder={t("settingsx.sandbox.field_does_example")} onChange={(e) => setDoes(e.target.value)} />
</div>
<div className="flex justify-end gap-2 mt-3">
<button className={BTN_BORDERED} onClick={onCancel}>{t("settingsx.sandbox.cancel")}</button>
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index a1744e37..771bdc88 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -2273,7 +2273,7 @@
"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_off_desc": "Off: commands run directly on this machine, with the same access as your user account.",
"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.",
@@ -2288,10 +2288,13 @@
"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_needs_you": "One step needs you: run the command shown in a terminal on this machine, then click 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.",
+ "setup_never_root": "The app does each step itself where it can. A step that needs an administrator goes through the system's own password prompt; where there is none (WSL), it is shown as one command for you to run. The app never sees or stores your password, and never turns the sandbox off on its own.",
+ "run_in_terminal": "Run this in a terminal on this machine:",
+ "guide": "Guide",
+ "install_progress": "Installing OpenShell… {{elapsed}} elapsed",
"step_pending": "waiting",
"step_fixing": "working…",
"step_fixed": "done",
@@ -2306,7 +2309,7 @@
"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.",
+ "provider_direct_desc": "Commands run directly on this machine, with the same access as your user account. Fastest. The default until you choose otherwise.",
"provider_seatbelt": "macOS sandbox",
"provider_seatbelt_desc": "Commands can read and write only the session's folders and reach only the network hosts on the allow list. Your other files and logins are hidden.",
"provider_openshell": "OpenShell (NVIDIA)",
@@ -2314,7 +2317,7 @@
"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.",
+ "needs_download_hint": "The sandbox base image (about 5 GB, downloaded once) is not on this machine yet. Click Set up sandbox below to download it; 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",
@@ -2324,7 +2327,14 @@
"profile_standard_desc": "Strict plus the search APIs.",
"network_help": "Shared credentials below add the hosts their tools need.",
"credentials": "Credentials an agent may be given",
- "add": "Add a file or folder…",
+ "add": "Add another credential…",
+ "editor_title_add": "Add a credential",
+ "editor_title_edit": "Edit this credential",
+ "editor_help": "A file or folder under your home folder that a tool needs to log in, for example ~/.npmrc for npm or ~/.config/gcloud for Google Cloud. It is copied into each sandbox for the session, and the hosts you list are allowed through the network allow list.",
+ "field_title_example": "npm",
+ "field_path_example": "~/.npmrc",
+ "field_hosts_example": "registry.npmjs.org:443",
+ "field_does_example": "Publish packages to npm as you",
"copied_from": "Copied from",
"also_allows": "Also allows {{hosts}}.",
"edit": "Edit",
@@ -2345,7 +2355,7 @@
"title_gh": "GitHub CLI",
"title_aws": "AWS",
"title_kube": "Kubernetes",
- "saved_in": "Saved in {{path}}"
+ "saved_in": "This setting is stored in {{path}}"
}
},
"misc": {
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 0959104d..d6465a73 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -2234,7 +2234,7 @@
"sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话;项目无法更改。",
"run_in": "在哪里运行同事",
"switch": "在沙箱中运行同事",
- "switch_off_desc": "关闭:命令以你的身份运行,没有限制。",
+ "switch_off_desc": "关闭:命令直接在这台机器上运行,权限与你的用户账户相同。",
"switch_on_desc": "开启:命令和文件工具在一道墙后运行,墙内只有会话的文件夹和网络允许列表。",
"current": "当前",
"windows_hint": "沙箱需要一台 Linux 机器。请在 设置 ▸ 机器 中添加一台;这台电脑上的 WSL Ubuntu 即可。",
@@ -2249,10 +2249,13 @@
"setup_cancel": "取消",
"setup_running": "正在设置…",
"setup_done": "沙箱已就绪。新会话将在 {{provider}} 中运行。",
- "setup_needs_you": "有一步或多步需要你操作。请运行显示的命令,然后重新检查。",
+ "setup_needs_you": "有一步需要你操作:在这台机器的终端里运行显示的命令,然后点击“重新检查”。",
"setup_failed": "设置已停止:{{error}}",
"setup_cancelled": "设置已取消。",
- "setup_never_root": "需要管理员权限的步骤会以命令的形式显示,由你来运行;应用绝不会以 root 身份运行任何东西,也绝不会自行关闭沙箱。",
+ "setup_never_root": "应用会尽量自行完成每一步。需要管理员权限的步骤通过系统自带的密码提示完成;没有该提示的环境(WSL)会显示一条命令由你运行。应用绝不会看到或保存你的密码,也绝不会自行关闭沙箱。",
+ "run_in_terminal": "在这台机器的终端里运行:",
+ "guide": "指南",
+ "install_progress": "正在安装 OpenShell… 已用 {{elapsed}}",
"step_pending": "等待中",
"step_fixing": "处理中…",
"step_fixed": "已完成",
@@ -2266,7 +2269,7 @@
"notify_title": "沙箱已就绪",
"notify_body": "现在可以开始新会话了;其命令将在沙箱中运行。",
"provider_direct": "不使用沙箱",
- "provider_direct_desc": "命令以你的身份运行,没有限制。最快。在你另作选择前为默认。",
+ "provider_direct_desc": "命令直接在这台机器上运行,权限与你的用户账户相同。最快。在你另作选择前为默认。",
"provider_seatbelt": "macOS 沙箱",
"provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。",
"provider_openshell": "OpenShell(NVIDIA)",
@@ -2274,7 +2277,7 @@
"status_default": "默认",
"status_ready": "就绪",
"status_needs_download": "需要下载",
- "needs_download_hint": "沙箱基础镜像(约 5 GB,仅下载一次)尚未下载到这台机器。请在终端运行 `openworker machine sandbox setup`;下载完成前第一个会话无法启动。",
+ "needs_download_hint": "沙箱基础镜像(约 5 GB,仅下载一次)尚未下载到这台机器。点击下方的“设置沙箱”进行下载;下载完成前第一个会话无法启动。",
"status_unavailable": "不可用",
"refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",
"network": "网络允许列表",
@@ -2284,7 +2287,14 @@
"profile_standard_desc": "严格模式加上搜索 API。",
"network_help": "下方共享的凭据会加入其工具所需的主机。",
"credentials": "可提供给同事的凭据",
- "add": "添加文件或文件夹…",
+ "add": "添加其他凭据…",
+ "editor_title_add": "添加凭据",
+ "editor_title_edit": "编辑此凭据",
+ "editor_help": "主目录下某个工具登录所需的文件或文件夹,例如 npm 的 ~/.npmrc 或 Google Cloud 的 ~/.config/gcloud。它会被复制到本次会话的每个沙箱中,你列出的主机会加入网络白名单。",
+ "field_title_example": "npm",
+ "field_path_example": "~/.npmrc",
+ "field_hosts_example": "registry.npmjs.org:443",
+ "field_does_example": "以你的身份向 npm 发布包",
"copied_from": "复制自",
"also_allows": "同时允许 {{hosts}}。",
"edit": "编辑",
@@ -2305,7 +2315,7 @@
"title_gh": "GitHub CLI",
"title_aws": "AWS",
"title_kube": "Kubernetes",
- "saved_in": "保存在 {{path}}"
+ "saved_in": "此设置存储在 {{path}}"
}
},
"misc": {
diff --git a/tests/test_sandbox_setup_job.py b/tests/test_sandbox_setup_job.py
index f955f69b..e853d012 100644
--- a/tests/test_sandbox_setup_job.py
+++ b/tests/test_sandbox_setup_job.py
@@ -1,9 +1,10 @@
"""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.
+page: `setup_cmd.steps()` is the checklist, `SetupJob` walks it and fixes each step it
+can on this machine (the OpenShell install included, through sudo-without-password or
+the system's password prompt), handing over ONE command for what it cannot. Never holding
+a password, never lowering protection.
"""
from __future__ import annotations
@@ -29,7 +30,8 @@ def _wait(job: setup_job.SetupJob, seconds: float = 5.0) -> dict:
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]
+ # A failing row the app may fix carries nothing; one it may not carries the command.
+ return [Step(key, setup_cmd.ROWS[key], ok, fixable=key in setup_cmd.FIXABLE, command="" if ok or key in setup_cmd.FIXABLE else f"fix {key}") for key, ok in rows]
def test_steps_carry_keys_and_say_which_the_app_may_fix(monkeypatch):
@@ -37,14 +39,110 @@ def test_steps_carry_keys_and_say_which_the_app_may_fix(monkeypatch):
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 not rows["docker"].ok and not rows["docker"].fixable and rows["docker"].docs == setup_cmd.DOCKER_INSTALL_URL
+ # A Mac needs no administrator (Homebrew installs as the user): the app installs it.
+ assert not rows["openshell"].ok and rows["openshell"].fixable and rows["openshell"].command == ""
+ assert rows["openshell"].docs == setup_cmd.GUIDE_URL and rows["openshell"].hint == ""
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_on_linux_the_install_is_the_apps_when_it_can_run_as_an_administrator(monkeypatch):
+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: None)
+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")
+ monkeypatch.setattr(setup_cmd.getpass, "getuser", lambda: "sam")
+ monkeypatch.setattr(setup_cmd, "openshell_problem", lambda fresh=False: "OpenShell is not installed")
+ monkeypatch.setattr(setup_cmd, "landlock_available", lambda: True)
+ monkeypatch.setattr(setup_cmd, "_run", lambda argv, timeout=600: type("Done", (), {"returncode": 1, "stdout": ""})()) # no loginctl here
+ # No way to run as an administrator without a password (WSL): ONE command handed over,
+ # linger first, because the installer needs the user's systemd manager.
+ monkeypatch.setattr(setup_cmd, "admin_prefix", lambda: None)
+ rows = {s.key: s for s in setup_cmd.steps()}
+ assert not rows["openshell"].fixable
+ assert rows["openshell"].command == f"sudo loginctl enable-linger sam && {setup_cmd.installer_command()}"
+ assert rows["openshell"].command.startswith("sudo loginctl enable-linger sam && curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | OPENSHELL_VERSION=v")
+ assert rows["linger"].fixable and rows["linger"].command == "sudo loginctl enable-linger sam"
+ assert rows["grpcio"].ok or rows["grpcio"].command.startswith("pip install")
+ # With one (sudo without a password, or the desktop's prompt): the app installs it.
+ monkeypatch.setattr(setup_cmd, "admin_prefix", lambda: ["sudo", "-n"])
+ rows = {s.key: s for s in setup_cmd.steps()}
+ assert rows["openshell"].fixable and rows["openshell"].command == ""
+ # Another version than the pinned one is said, as a note, not a command.
+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: "/usr/bin/openshell" if name == "openshell" else None)
+ monkeypatch.setattr(setup_cmd, "_run", lambda argv, timeout=600: type("Done", (), {"returncode": 0, "stdout": "openshell 0.0.1\n"})())
+ rows = {s.key: s for s in setup_cmd.steps()}
+ assert rows["openshell"].hint == "found 0.0.1, not the tested release" and rows["openshell"].fixable
+
+
+def test_admin_prefix_prefers_passwordless_sudo_then_the_desktop_prompt_never_wsl(monkeypatch):
+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")
+ monkeypatch.setattr(setup_cmd.getpass, "getuser", lambda: "sam")
+ 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": ""})())
+ assert setup_cmd.admin_prefix() == ["sudo", "-n"]
+ # sudo wants a password: the desktop's prompt (pkexec) when there is a display and
+ # this is not WSL, which has no polkit agent to show one.
+ monkeypatch.setattr(setup_cmd, "_run", lambda argv, timeout=600: type("Done", (), {"returncode": 1, "stdout": ""})())
+ monkeypatch.setenv("DISPLAY", ":0")
+ monkeypatch.setattr(setup_cmd, "is_wsl", lambda: False)
+ prefix = setup_cmd.admin_prefix()
+ assert prefix is not None and prefix[:3] == ["pkexec", "env", "SUDO_USER=sam"] # the installer sets up sam's gateway, not root's
+ monkeypatch.setattr(setup_cmd, "is_wsl", lambda: True)
+ assert setup_cmd.admin_prefix() is None
+ monkeypatch.setattr(setup_cmd, "is_wsl", lambda: False)
+ monkeypatch.delenv("DISPLAY")
+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
+ assert setup_cmd.admin_prefix() is None # headless: nothing can show a prompt
+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")
+ assert setup_cmd.admin_prefix() is None # a Mac needs none
+
+
+def test_install_openshell_runs_the_installer_as_the_user_on_a_mac_and_as_an_administrator_on_linux(monkeypatch):
+ ran: list[list[str]] = []
+ monkeypatch.setattr(setup_cmd, "_stream", lambda argv, on_line, cancel: ran.append(argv) or (0, "done"))
+ monkeypatch.setattr(setup_cmd.getpass, "getuser", lambda: "sam")
+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")
+ assert setup_cmd.install_openshell() is None
+ assert ran == [["sh", "-c", setup_cmd.installer_command()]]
+ ran.clear()
+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")
+ monkeypatch.setattr(setup_cmd, "admin_prefix", lambda: ["sudo", "-n"])
+ assert setup_cmd.install_openshell() is None
+ assert ran == [["sudo", "-n", "sh", "-c", f"loginctl enable-linger sam && {setup_cmd.installer_command()}"]]
+ monkeypatch.setattr(setup_cmd, "_stream", lambda argv, on_line, cancel: (1, "checksum mismatch"))
+ assert setup_cmd.install_openshell() == "the installer exited with 1: checksum mismatch"
+ monkeypatch.setattr(setup_cmd, "_stream", lambda argv, on_line, cancel: (None, ""))
+ assert setup_cmd.install_openshell() == "installation cancelled"
+ monkeypatch.setattr(setup_cmd, "admin_prefix", lambda: None)
+ assert "sudo loginctl enable-linger sam && curl" in (setup_cmd.install_openshell() or "")
+
+
+def test_the_job_installs_openshell_with_its_output_as_progress(monkeypatch):
+ def fake_install(on_line, cancel):
+ for line in ("downloading v0.0.116 release checksums...", "installing openshell...", "gateway registered"):
+ on_line(line)
+ time.sleep(0.02)
+ return None
+
+ monkeypatch.setattr(setup_cmd, "install_openshell", fake_install)
+ reads = {"n": 0}
+
+ def steps():
+ reads["n"] += 1
+ return [Step("docker", setup_cmd.ROWS["docker"], True), Step("openshell", setup_cmd.ROWS["openshell"], reads["n"] > 1, fixable=True, docs=setup_cmd.GUIDE_URL)]
+
+ job = setup_job.SetupJob(steps)
+ job.start()
+ time.sleep(0.03)
+ mid = job.state()
+ assert mid["status"] == "running" and mid["progress"]["last_line"].startswith(("downloading", "installing"))
+ assert {r["key"]: r["state"] for r in mid["rows"]}["openshell"] == "fixing"
+ state = _wait(job)
+ assert state["status"] == "done" and {r["key"]: r["state"] for r in state["rows"]}["openshell"] == "fixed"
+
+
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)
@@ -71,7 +169,7 @@ def test_the_job_fixes_what_it_may_and_stops_at_what_needs_an_administrator(monk
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["openshell"]["state"] == "needs_you" and by_key["openshell"]["command"] == "fix openshell"
assert by_key["bind_mounts"]["state"] == "pending"
@@ -125,7 +223,7 @@ def test_a_refused_linger_is_handed_over_and_the_walk_goes_on(monkeypatch):
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["linger"]["state"] == "needs_you" and "sudo loginctl" in by_key["linger"]["command"]
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
@@ -160,7 +258,7 @@ def test_the_readiness_endpoint_and_the_job_endpoints(tmp_path, monkeypatch):
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 [(s["key"], s["ok"], s["fixable"], s["command"]) for s in ready["steps"]] == [("docker", True, False, ""), ("openshell", False, False, "fix openshell")]
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")